Perfecting OO classes/methods

The following constraints help in writing better OO code
1) Use only one indention per method, if there is a need to indent again create another method and call that method from the first one.
2) Don’t use else. Use the if condition to test the condition and exit the method if the condition is false. So every method tests for just one thing
3) Wrap all primitives and Strings to prevent primitive obsession. If you need to use a primitive, create a class to define its role.
4) Use only one dot per line. This prevents you from reaching deeply into objects to get to methods and fields and prevents breaking encapsulation.
5) Don’t abbreviate names. Hence you spend less time thinking about method names. Thus have methods for Order like ship() rather than Order.shipOrder() ;
6) Keep entities small. No more than 50 lines per class and no more than 10 classes per package. This helps to keep classes concise and focused.
7) Don’t use classes more than 2 instance variables. Difficult but then a lot of instance variables might warrant extracting a class.
8) Use first-class collections. In other words, any class that contains a collection should contain no other member variables. The idea is an extension of primitive obsession. If you need a class that’s a subsumes the collection, then write it that way.
9) Don’t use setters, getters, or properties. This is a radical approach to enforcing encapsulation. It also requires implementation of dependency injection approaches and adherence to the maxim “tell, don’t ask.”

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: