Step 32: Encapsulate Behavior, not Just State ~ Einar Landre

Birat Rai
2 min readNov 7, 2017

--

This is the 32nd Step towards gaining the Programming Enlightenment series. If you didn’t learn the 31st Step, read it.

What is Encapsulation?

Encapsulation is an OOP information-hiding mechanism used to hide the values or state of a structured data object.

Also, encapsulation is gathering all operations on the object’s state into the object’s interface, and only those operations.

What is State and Behavior of an object?

Objects in real-world or OOP share two characteristics: They have state and behavior.

Example; For Dog Object have

  • State -> (name, color, breed, hungry) usually defined as variables or field.
  • Behavior -> (barking, fetching, wagging taile) usually defined as accessor methods.

Why encapsulate behavior, not just state?

Let’s say we have three classes: Customer, Order and Item.

customer.validateCredit(item.price()) //Here price of item is delegated to item object, whereas validateCredit is deligated to customer object. If condition fails, an exception can be thrown and purchase aborted.

So, if we don’t encapsulate behavior, we might decide to wrap all the business rules into an object, as OrderManager or OrderService, where Order, Customer and Item are fields or variables.

We tie those fields with logic in a one large mess, following procedural approach and losing the OOP approach, hence breaking encapsulation.

TL;DR Realize the power of encapsulation and allow OOP paradigm to dig deep within the codebase.

Go to the series.

Go to 31st Step

Go to the 32nd Step.

References:

--

--

Birat Rai
Birat Rai

No responses yet