Monday, September 05, 2005

Good OO Thoughts

From Steve Dekorte's blog:
The amount to which the program is object oriented has an inverse relation to:

1. the number of arguments passed in message calls
2. The number of instance variables in the objects

I tend to use "7 +/- 2" rule. If I have 5 or less instance variables in my object, then everything is cool. I'm even OK with 7, but 9 is on the cusp of too many. The reason why is because too many instance variables is not only a code smell, but your object is getting away from having one responsbility and needs to be broken up.

Arguments are little bit more restrictive. I try to keep them below 5. Otherwise, you're writing big methods and well, your methods should do one thing and nothing more.

Of course, the rule above is excellent, as is the "DRY, Shy, and Tell The Other Guy" rule from the Pragmatic Programmers. They are just some things that I strive for when programming.

2 comments:

Anonymous said...

Ooh, that's a nice one. I never thought about the number of instance variables in a class, but I guess it does make sense. Thanks for the tip Blaine!

Anonymous said...

I system I work has many classes way over 7 instance variables -- even unto 7 times 7 instance variables.

Are there any refactoring patterns documented by to help tackle the situation?