User Tools

Site Tools


programming:object_oriented_rules_of_thumb

This is an old revision of the document!


Designing an implementing successful object oriented code is tough because of the variety of situations with which a programmer will find themselves. Often when a coder is trying to code a solution to a problem the question is asked, “what pattern should I use, or what object scheme should I use?” The answer invariably is “it depends”. There are so many variables in any problem, there is generally not a single fit answer. This page is an attempt to capture more of the interesting ways of looking at problems.

Red Flags

Red Flags are conditions which should indicate to you that something isn't heading in an object oriented direction…

* Too many method parameters: If you spot a method with too many arguments, it's likely you've built it for a very specific use. That's OK, but if you are writing a general purpose object, you want it to be easy and the more information you require of the caller, the less easy it is to use. Consider aggregatnig some of the information into another object, or split your method call (of course that's another problem).

* Getters and Setters for everything in the object: It used to be that conventional wisdom said you need to put Getters and Setters on every item in your object. That may be partially true if you are creating a JavaBean (but even then it's limited). If every (or even most) of the instance variables have getters and setters, why bother making the instance variables “private”, perhaps “public” would be a better option. It makes them quicker to access with less fuss. We're not talking about cases where some code needs to be involved to translate the data (e.g. setTemperatureFarenheight vs. setTemperatureCelsius) or do other processing. Also consider what's happening here. You've provided access to everything in the object, which is like going back to C style structs with full visibility. You've lost the ability to do information hiding, such as how something is implemented. Generally callers should be dealing with abstractions, and not specific implementations.

* Constructors for every combinations: Sometimes it is convenient to add another constructor with takes different forms of similar objects to do conversion. This can lead to an N2 number of constructors between various forms and makes your class implementation longer than it needs to be. Consider using normalized data representaions and interfaces. (e.g. use Iterable or Collection style abstractions) ====== References ====== * Design Patterns: Elements of Reusable Object-Oriented Software**, Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides. Addison-Wesley Professional Computing Series, Addison-Wesley, Reading Mass. 1994.

programming/object_oriented_rules_of_thumb.1311284489.txt.gz · Last modified: 2012/10/10 16:47 (external edit)