More features |
|
About this chapter |
Proper use of functions, methods and classes is one of the distinguishing marks of an experienced programmer. Here are some important pieces of advice.
A function or a method should do one thing and do it well.
If you can't sumarize in one sentence what the function does, it's probably too complicated.
If you have to scroll to see the entire function, it is too long.
Studies suggest that a person can only keep track of at most 7 or so things at one time. If your function has more than 5 or 6 variables, it is probably too long.
As you write more complex programs, the use of comments becomes more important.
Comments don't have to be long. They just have to explain the purpose of the code clearly.
Every function should have a comment that states what the function does. The exception is a function that is so simple that it's use is obvious. For example:
The methods initialize, add and remove didn't need comments.
In AddresBook, the methods each and each_address have only a one simple comment. The comment says that they are iterators. Once the developer knows that they are iterators, their use becomes apparent from their names.
The method by_name has a comment saying that it is a sorting function. Once you know that, it's use is also apparent.
Comments can also be used to group together related functions. For instance, in AddressBook I used comments to group together "fundamental functions", "iterators" and "sorting functions".
Always try to divide your code into manageable pieces.
More features |
|
About this chapter |