Most languages provide support to create Object-Oriented (OO) systems. Why correct OO design is essential:
- Code re-use
- Multithreading
- Easy to maintain code
- Easy to understand code
Below are a few steps to check if you are applying proper object orientation
At Object level #
The most important feature of a good design is SRP (Single Responsibility Principle). When designing your Object you can verify if it attends SRP by asking, “How many responsibilities this object has?”.
Naming objects ending “er”-“or” (Controller, Processor, Manager) should be avoided because their name implies that they have more than one reason to exist.
Make your objects Immutable is the main idea behind having thread-safe Objects. Objects are not thread-safe when they share/expose internal state directly with other Objects.
Encapsulation is the technique behind avoiding exposing your object state. Do not create an unnecessary getter/setter methods. Create your objects at once in a static immutable way.
Use strategy design or template pattern - polymorphism at its basic form. Polymorphism will make your code cleaner and avoid if/else chains. “Law of Demeter”/“Don’t talk to your neighbor’s neighbor” principle enforces that your Object is not getting tightly coupled with other objects. Example:
public class Object1
boolean checkCondition() {
this.object2.getObject3().getObject4().call();
}
In the code above Object1 has Object2 that also returns another object. This is bad because if Object3 is modified to stop getting Object4 you will have to modify Object2.getObject3() and Object1.checkCondition(). A better implementation is to modify Object1 to use Object4 directly eliminating the need to use Object3:
public class Object1
boolean checkCondition() {
this.object4.call();
At Application level #
IoC/DI through Spring/Java EE/Guice. It will provide a higher decoupling/easy to maintain code because it eliminates the glue code that you usually find in objects. Why? Because It avoids “new” object instantiations.
If your application has a presentation layer, ensure that it does not have business logic, only logic related to the presentation itself should be allowed.