Encapsulation & Cohesion

Steven Klavins
2 min readApr 12, 2020

Before getting into things take a look at the two following images, I know which one I like best…

Well why am I showing you these two contrasting images? Well they provide a pretty good analogy of what a poorly designed program looks like and what a well-designed one does. When coding we don't want methods and classes tightly coupled, we want them pluggable, easy to read and interchangeable just like the server cabinet shown on the right. This is were cohesion comes in, we want our methods and classes to work in unity in an ordered and transparent manner.

Imagine the left image was an actual program, then imagine how rigid it would be trying to work within it, pure chaos right? When we hear people criticizing poorly designed code we will often hear the phrase “tight coupling” this is when methods and classes have a high dependency on each other (i.e if you change one method it breaks another). This method of hardwiring things can cause a program to fall apart in seconds causing a chain reaction, resulting in your code crashing down like a building with a poor structure. This is why concepts like dependency injection and interfaces are so great, interfaces can act as plugs for interchangeability and dependency injection offloads our dependencies outside of our classes.

So how do we avoid these issues you may ask, it's unavoidable having code that relies on something else right? You would certainly be correct in assuming so, this is where we have something wonderful come in and its called encapsulation!

Encapsulation is a way in which we can hide away those methods and variables not needed outside of a class. We do this with such words as “Private” (Only available in the class a method is contained in).“Protected” (Typically something that can be called by a subclass but not by unrelated classes). “Public” (Something that can be accessed everywhere). It is important to note not all programming languages have the capability to do this however most popular languages do (because it's awesome).

Thanks for reading! I plan to do some more blogs on concepts such as polymorphism, inheritance, and abstraction soon so keep an eye out if you're interested.

--

--

Steven Klavins

Hi, I’m Steven, most call me Steve! I’m a programmer, musician, and artist. This blog contains various tutorials and posts related to software development.