As a novice Ruby programmer, I am constantly butting my head up against the process known as defining methods. Defining a method means encapsulating a bit of code that you find yourself needing repeatedly throughout a program. By encapsulating the code in a method, which has a name, you can call on that method throughout the program by simply invoking its name. Methods help us adhere to the Ruby philosophy of DRY (Don't Repeat Yourself).
Looking at my first few programs, it is obvious that I am in violation of the DRY principal EVERYWHERE! There are few, if any methods defined and code duplicated from top to bottom.
Going back 2 weeks, I would have spent more time understanding methods and I would have explained the process to myself like this:
Why methods? Because they isolate problems in your code allowing a reviewer (and yourself!) to find a problem without combing through hundreds of lines of code. You can have hundreds of lines of code written in methods, which you may still need to comb through, but you can isolate problems to a specific encapsulation and know where to search. Additionally, keeping your code broken down by methods insures that you will not break another section of your code accidentally while trying to fix something unrelated.
When methods? You can define a method for ANY process in which you pass in a variable. Sometimes you don't need to define a method. But often times you do. If you have a process in which you pass in a variable more than once, write a method.
How methods? I still don't know if I can articulate the 'how' of methods. I have written a few, and they work, but I still feel like I have a couple of different 'thought balloons' floating over my head. I can sometimes merge them together to get a meaningful bit of information but, as soon as I apply it, the balloon is released and becomes a disparate bit of knowledge. I'm still working to permanently merge the knowledge into a firm foundation for writing Ruby methods.
No comments:
Post a Comment