The Importance of Method Naming
So, this is my first time writing about code. Bear with me here.
When I started my pre-work for the software engineering program at Flatiron School, I didn’t even know what variables or methods were. I now understand how significant the name of a method or a variable can be in a number of different circumstances.
Before we get into some examples, let’s just talk about why it may be important to name your variables and methods appropriately:
As a programmer you will most likely work with a team. Not everyone will always speak your native language, and anyone on your team will need to be able to read your code and manipulate it quickly.
If you come back to a model or a controller a few months after you’ve written the code, and the method names do not make sense, it will be much harder to debug.
Clean code makes everything easier in the long run. Refactoring is huge, and when you refactor, those methods need to be named accordingly or you’ve defeated the purpose of refactoring.
- Methods that return Booleans:
Above we have a method that is looking for a file in our reminder_files folder that pertains to this user’s username. Because we have the question mark at the end of the method name “file_exists?”, I can gather immediately that the return value will be truthy/falsy. If the file is found it will return true, if not false.
Above we call that method, using the return value to aid in the operation of a larger, more complex method to create an ics file and make sure it ends up in the right directory…if it exists :).
2. Methods should really be named to indicate what they return:
Here we have a series of helper methods to grab a random sample of a quote, a piece of art, and some music. In rails you can pass either the object, or it’s ID to create an instance of another object. The thing is…they weren’t returning an actual quote object, but it’s ID. So let’s go ahead and update that to follow this principle:
Now that we’ve updated the helper method names in the create method, in order for us not to receive a NoMethodError, let’s update the “random” helper method names too:
All set! Now we’re following the appropriate principles so that if someone else reads our code or we need to debug, the return values of these helper methods is pretty clear from the naming of the methods themselves.
TL;DR: do your future self (and fellow devs) a favor and name your methods responsibly. It will make debugging (and your dev life) much easier.