In OOP (object oriented programming) it’s notable to remember why you are building an application with objects instead of mere functions (procedural programming) . Sometimes programmers will treat objects more like functions which completely defeats the purpose of objects in the first site! The purpose of this post is to glance the actual attend of OOP and how to structure your models appropriately.
What is a decoupled object?
Contrary to the novice OOP programmer’s plan, an object is worthy more than a collection of data members and related methods. It’s principal to remember that an object embodies data and methods that pertain only to itself. The term “decoupling” is mature to identify the separation of software blocks that shouldn’t depend on each other.
Why is it indispensable to decouple objects?
Let’s say that we have a Car Class with the methods driveForward(), halt(), turn(), honkHorn(), and changeLanes() . This object has a dreadful construct because one of the methods, changeLanes(), might depend on a Street class. What if you were trying to reuse this class for a car that only drives off-road? In this case, the changeLanes() blueprint is completely meaningless to your object instantiation. Furthermore, if the turn() procedure were to reference the changeLanes() design, the entire object would originate to seem too specific to instantiate and work with an off-road car. In addition, if a change is made to the Street class, it’s very likely that the Car class will also have to be modified. Since Car has a plot that depends on another object, this object is said to be “coupled” (which is what we are trying to avoid) .
How to decouple objects
To earn what I call “purified objects”, we need to completely decouple them in such a method that all of their fields and methods are specific to what the object can do in any circumstance. To decouple the Car class, you would want to go the changeLanes() arrangement to another object that interacts with Car, like CityDriving. This fresh object acts as a mediator because it uses the Car class for special circumstances without tainting its pure definition.
When designing your object models, ask yourself “are these objects purified? Are they decoupled? ” If you religiously ask yourself this put a question to when creating original objects, not only will you demolish up creating powerful cleaner code, you’ll also exercise less time re-factoring. first-rate luck!