Disclaimer: the following tips apply to programs more complex than this |
If you are working in a team, these suggestions will also help your colleagues to understand your code and make changes autonomously.
1. Use Defines
This is a quite common suggestion but, believe me or not, I've seen several programs using numeric constants. Basically, every time you declare a fixed size array or set a limit, you should create a define. In this way it'll be faster to change it when requirements evolve. Unfortunately, not every programming language supports defines or constants; in such cases, the fastest way is to use variables with all uppercase names.2. Use Getters and Setters
For object oriented languages, it's not a good idea to directly expose members. Even for simple things it's preferable to use functions to change a member or to retrieve a value in order to hide the implementation of your classes. So, in the future, you may change an integer to an iterator without impacting the existing code. The exception is Python, where properties should be used, but only because they do the same thing: implementation hiding.3. Write Small Functions that Do a Single Thing
There's nothing worst than having a function one-thousand lines long. It's hard to understand and almost impossible to change it's behavior without rewriting it. With small functions it's easier to change some details or add something in the right place without being frightened of hidden side effects.Corollary: unless a heavy optimization is needed, don't write code that is hard to understand for an average programmer. If you cannot avoid tricky code, remember to comment very well what it is supposed to do.
4. Prefer Text Files Where Possible
Unless you are working on systems with limited speed or storage, consider using text files to save (and load) configurations, logs and everything else. Binary structures are faster to read and write but every time you'll change the format, you need to update several part of your code. Moreover, the debug is easier and, in case of troubles, an handmade change can save you time and money.5. Use Names Not Related to the Solution
It is easy to call a classArrayValues
, and it seems reasonable, too. But it's wrong. Again there is a problem with implementation hiding but not only. If one day the array has to be changed in a hash table, what would you do? Keep the name even if it's wrong or change it everywhere in your project? The key point here is that the solution you have found to solve a problem may vary in the future, so it's better that names of variables, functions, classes, etc. reflect a something that will never change: the problem to solve.
Post a Comment