Using Private Methods
No one likes repetitive code. Repetitive code can cause errors and some may say that is causes your code to look messy. That is where private methods can come into play and can be very beneficial.
Creating private methods is a great way to refractor repetitive code. I am going to give a few examples of how private methods could have been used in my Sinatra project. Private methods could have been place in my entries_controller:
private
end
Get_entry & redirect_if_not_user methods can then be added in the private methods.
private
def get_entry
end
def redirect_if_not_user
end
end
The @entry = Entry.find_by(id: params[:id] & if @entry.user != current_user codes were used several times with the entries controller application. The two repeated codes can simply be encapsulated into the get_entry & redirect_if_not_user methods mentioned above:
private
def get_entry
@entry = Entry.find_by(id:params[:id])
end
def redirect_if_not_user
if @entry.user != current_user
end
end
Now all I would have to do is call those methods (get_entry or redirect_if_not_user) in place of that code.
In addition to having cleaner coder, if changes were needed to be made; I would only have to make that change in one place instead of several places.