11/11/2024

Cyber Pro

Securing Your Digital Future

The Importance of Decoupled Objects in OOP

The Importance of Decoupled Objects in OOP

In OOP (object oriented programming) it’s important 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 place! The purpose of this post is to explore the real benefit of OOP and how to structure your models appropriately.

What is a decoupled object?

Contrary to the novice OOP programmer’s belief, an object is much more than a collection of data members and related methods. It’s important to remember that an object embodies data and methods that pertain only to itself. The term “decoupling” is used to identify the separation of software blocks that shouldn’t depend on each other.

Why is it important to decouple objects?

Let’s say that we have a Car Class with the methods driveForward(), stop(), turn(), honkHorn(), and changeLanes(). This object has a poor design 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() method is completely meaningless to your object instantiation. Furthermore, if the turn() method were to reference the changeLanes() method, the entire object would start 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 method 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 create what I call “purified objects”, we need to completely decouple them in such a way 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 move the changeLanes() method to another object that interacts with Car, like CityDriving. This new 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 question when creating new objects, not only will you end up creating much cleaner code, you’ll also spend less time re-factoring. Good luck!

denitomiadv.com © All rights reserved. | Newsphere by AF themes.