A Systematic Approach to Write Better Code With OOP Concepts

DZone 's Guide to

A Systematic Approach to Write Better Code With OOP Concepts

This real-world approach to applying OOP will walk you through important concepts like encapsulation, inheritance, and access modifiers in a new light.

· Java Zone ·
Free Resource

Haaaah another article on object-oriented programming. You might be thinking that I will be discussing the same OOP definitions with boring examples. The same definitions and examples that you have studied before, maybe in your class or when preparing for a job interview. But today I will not rephrase those disjointed definitions but give you a simple layout that will make it easy for you to understand OOP concepts.

OOP is easy to understand. We often learn it with the classic metaphors like Cat, Duck, Animal, etc., but sometimes, it is hard to swallow these metaphors, and most OOP material is filled with them. There is nothing wrong with these metaphors and examples when introducing OOP concepts to a beginner programmer, but the learning materials never progress in the quality of OOP examples. They start with metaphors and end at metaphors.

Well, I also struggled with OOP concepts during my undergrad studies. I understand OOP concepts, but when faced with writing actual code, I stalled and could not think of where to start. At one time, I thought that I should stop learning OOP, but the world around me kept telling me the importance of OOP.

If you combine all embedded developers and low-level API developers, then that will only make 10% of all the developers in the universe. The remaining 90% of developers are programming in OOP-based programming languages.

object oriented programming

Besides, object-oriented programming skills will be with you for life. On the contrary, if you are tied to a specific framework for two, then in three or five years, you will be in the rabbit hole. What happens if that framework is replaced by another optimized framework — you will have to start from scratch.

But if you know object-oriented concepts and have applied them firmly in your work, then you have that experience for life. You can always get leverage out of that object-oriented programming experience.

Also, I don't want to be the kind of developer who writes only glue code and becomes just an API consumer. I want to learn skills that I can use to produce frameworks that are used by others.

So how did I grasp OOP concepts? A different mindset. Over the past 10 years of programming experience, I have developed a mindset towards OOP, and I will present that mindset in the following template or layout. This is a systematic approach that I will use if I introduce OOP concepts to a new student.

  1. Context: Previously, people were tired of procedural programming because the information was available to all.
  2. So, they developed a method to hide information called encapsulation.
  3. But they needed a way to communicate besides hiding, so they invented communication methods: association and inheritance.
  4. Meanwhile, communication came with a dependency problem. The solution is: abstraction and polymorphism.
  5. Design patterns were discovered to decrease dependency issues. For design patterns, I have another article here.

Context of OOP: Information Is Everywhere

Well, after reading the Steve Jobs biography, I understood the evolution of computers, operating systems, and graphical user interface. All of this helped me understand modern technologies. Therefore, it is necessary to understand a little bit of background.

Where does OOP fit in the larger context of software development? Is it a process? Is it an architecture? Something else? Well, I am feeling stupid right now by asking these questions, but there are people who ask these types of questions and they are still confused. Object-oriented programming is a development methodology. 

Developers, especially young developers, know about OOP only as a development methodology. If they read a little bit of history, then they will know that there is another development methodology that people have abandoned (or tried to abandon) — procedural development. 

Procedural programming languages like COBOL, Fortran, and Pascal were the default choices for our programming ancestors, and before that, assembly language programming was a must for every computer scientist.

In procedural programming, we divide a large set of instructions into procedures — like functions in C#. Before procedural programming, there was another paradigm, monolithic programming. In monolithic programming, everything is written in one large method, and all the variables are defined at the topmost location. But as program sizes grew, managing monolithic and procedural code became difficult so OOP was invented.

Encapsulation: Hiding the information

Let me share a personal story. One night, there was a call from my boss. I had to update the demo for our product and show a couple of parameters on the screen. Demos in trade shows are important for marketing. Usually, it is a high-pressure situation. Every engineer was counting on me.

The update was small. I had to add two text fields to the display. I created a class, and since both fields were related, I put them in a single class and used the object of that class. I did this to make the code clean. In such stressful situations, you cannot afford to make mistakes and, fortunately, the update worked flawlessly.

One of the engineers praised me in such a way that I still remember him after so many years. He told me that “Wow, you created a new variable!” (He was not a software engineer, so we can forgive him.)

First of all, I don’t want my readers to be like that, i.e treating an object like a variable. Secondly, you can see how I used encapsulation to save the day. You merge one or more pieces of data and/or one or more methods into a single entity — encapsulation.

Encapsulation is also defined as the mechanism for data hiding/data protection/data security. Data hiding is achieved via access modifiers. If a data member is defined using the 'private'  access modifier, it will be accessible within the boundary of the class. Meanwhile, if an access modifier is public, it will be accessible by everybody else. But this definition needs clarification. Let's see if it is true for the following example:

Example 1:

class StoreItem
    private int itemPrice;
    public int GetPrice()
        return itemPrice;

    public void SetPrice(int price)
        itemPrice = price;

Here, I define a private data member and give its access to everybody else via a public method. Is the item price hidden? Let's see another example:

Example 2:

class StoreItem
    public int itemPrice;

Everybody can access the item price, since it is public now. So what is the difference in the above two code examples? This is not data hiding, and if someone told you that the first example is data hiding, then you should run away.

In my opinion, data hiding is controlled access to internal data via public methods. You are hiding data if the outside user does not know how many variables are in your class but still get the desired result from your class via public methods.

Example 3:

class Process {
    private int ingredient1;
    private int ingredient2;
    private int ingredientFromOutside1;
    private int ingredientFromOutside2;

    public int GetFinalProduct() {

        int result = GetLocalProduct() + GetProductFromOutside();
        return result;

    private int GetLocalProduct() {
        return ingredient1 + ingredient2;
    private int GetProductFromOutside() {
        return ingrdientFromOuside1 + ingredientFromOutside2;


In example 3, there are several variables, and I hid them from the outside world and gave only the controlled access to them. Outside the class, no one knows how many data members or methods are there. They just know about one public method named GetFinalPoduct and nothing else. In this way, we hide data from outside world using encapsulation.


In example 1, I have just exposed the instance variable — the property type. There are several methods to access property types:

  1. Write your own public methods for accessing member variables (first example).

  2. Make your member variables public (second example — never use that).

  3. Use accessors.

Writing your own methods is a good approach, but it is not extensible. The most suitable method is using accessors. Getter and setter methods in Java and the property type in C# are called accessors. With accessors, you can give unified access to the user of your class.

C# is the programming language for the following example:

public class Automobile
    int _weight = 200;
    public int Weight

        return _weight;

         _weight = val;

There are a lot of things that you can do here in the accessor code. You can do any validation before setting any value, you can update or calculate any other value, or you can store/retrieve a value from storage devices directly from here.

Sharing Responsibilities/Information via Communication

The primary purpose of OOP is to write a lot of software code easily. You divide a large problem into smaller problems and then write classes and create objects for those smaller problems.

But many people write one huge class and fill it with dozens of responsibilities. I believe that this is because people from the procedural programming background are unable to distribute responsibilities in different classes. You can solve this problem by distributing responsibilities among classes using association and inheritance.


Consider there are two classes that do two different things. With association, one class uses the power of the other class to accomplish a common goal. That is it. The purpose of association is sharing responsibilities.


public class Member{

public Class Community{
    Member aMember;

By having a reference to another object, your object has the ability to call the referenced object's methods. You can say that both of these citizens have joined hands to accomplish a goal.

In this article, I will not tell you the intricate details of association, aggregation, and composition in the UML's latest version or their differences. For me, association means sharing responsibilities between two classes. But if you are interested in minute details, here is a good article on that.

If a class A object is communicating with a class B object to accomplish a goal, then class A is dependent upon class B. Dependency is considered a bad thing in the programming world (nobody likes dependency in the real world, either!). How do you reduce this dependency and still make the objects work together as a team? This is the question for which many design patterns and principles were invented. I will discuss some tools to reduce dependency later in the article, but first, let's discuss another tool that we can use to share responsibilities.


Inheritance is about distributing responsibilities between two classes: parent and child. The benefit is that the child class inherits all the qualities of the parent. As the child is using the parent's capabilities, it is said that inheritance supports reusability.

Let’s see some examples of inheritance:


As you can see, I have modeled the Vehicle class and its children so that the common features for both vehicles, namely ‘car’ and ‘boat,’ are combined in one parent class named ‘vehicle’.

Now if I want another specialized car, like a sports car, I can extend the ‘car’ class and implement the logic specific to a sports car.

Nice hierarchy! It sounds logical, but the problem is that real life problems are hardly like that. Real world problems are complex, and any code that you write will evolve over time. Evolving requirements will cause evolving inheritance hierarchies.

I have seen systems where developers' lives are consumed in managing large hierarchies of inheritance. Due to this, inheritance is not good for maintainability. But don't underestimate the power of inheritance. There are some scenarios where using inheritance is a natural fit, such as WinForms.

Similiar to composition, there is the dependency between child and parent classes, and dependency is a bad thing in programming. Now I will discuss how can you minimize the side effects of communication known as dependency.

Reduce Dependency


My boss once asked me to update one of my software creations. This update enabled the software to receive data from network devices as well as from serial devices.

In order to implement this update, I needed to take care of a lot of things. For example, I had to include conditional statements to determine the kind of operation (serial or network) and update I/O methods, since there are different methods for receiving data from a network device and a serial device. Hence this code is dependent upon tiny details.

But by using abstraction, I designed my code in a way that I can defer tiny details of implementation. I have abstracted out the tiny details, and now my code depends upon abstraction. Therefore, my code will be updated easily with any new device code.

Hence his ability to communicate with any new code without hassle and dependency is achieved through abstraction. There are two tools of abstraction that I will discuss in this article.

Interface: First Tool of Abstraction

The concept of deferring the responsibilities to the implementing classes is called abstraction, and a tool for accomplishing this feature is ‘interface’ in Java or C#.

This is how I define the interface for the example described above:

Interface IStream
    byte[] getData();

Every class that implements an interface must define methods of the interface:

NetworkStream :IStream
    public byte[] getData()
      byte[] data = NetworkCard.GetData();// read data from network
      return data;

Here the 'interface' acts as an abstraction layer. It does not define or implement the behavior, but it gives the hint or overall picture of how a behavior should look like (i.e signatures of methods). It defers the responsibility for defining the behavior to the implementing class.

In above example, every class that wants to act like a Stream should implement the methods in the IStream interface. In this way, any piece of code that wants to work with a network stream will talk to the interface of the implementing class. Here is the example code:

void CoreClassMethod()
    IStream aDataStream =new NetworkStream(); // using the interface 
    Byte[] data = aDataStream.getData();

Therefore, if in future my boss asks me to extend the capability of CoreClassMethod to handle PCI data, I will just write a new class that implements the IStream interface and creates the instance of that class in CoreClassMethod:

    Public byte[] getData(){
    // read data here using low leve I/O libraries and return it.



void CoreClassMethod()

    IStream aDataStream =new PCIStream(); // using the interface
    Byte[] data = aDataStream.getData();


The good thing is that the code that was written months ago can work with the newly written code with minimal effort.

Abstract Class: The Second Tool of Abstraction

An abstract class is something in between a full-fledged class and an Interface. You can define some behaviors and defer some behaviors to be defined by its children.

For example:

abstract class GeometricalObject {
    void showOnScreen() {
        // implementation steps
    abstract void draw();

// Child 1: 
class rectangle: GeometricalObject {
    void Draw() {

        //specifics of drawing a rectangle


//  Child 2:
class circle: GeometricalObject {

    void Draw() {
        //specifics of drawing a circle


Code that is shared among all children is written in the method showOnScreen(). The principle that makes all the above interfacing and abstraction possible is polymorphism.


In simpler words, polymorphism is the ability of the parent reference to hold the reference to any of its children. A parent can be an interface, an abstract class, or a full-fledged class. So when you call from parent references, the desired method gets called on the appropriate children. See the following code for an example of Streaming data.

Interface IStream {
    byte[] getData();

NetworkStream: IStream {
    public byte[] getData() {
        byte[] data = NetworkCard.GetData(); // read data from network
        return data;

SerialStream: IStream {
    public byte[] getData() {

        byte[] data = SerialPort.GetData(); // read data
        return data;


// Now if I have the reference of the parent class, IStream, 
// I can call the method of any child class
IStream anObject = new NetworkStream();
data = anObject.getData();

//Change this in the run-time
anObject = new SeriaStream();
data = anObject.getData();

So these are the basic tools for lowering the damage done by communication between objects. These tools help us reduce the dependency between objects.

Final Words

Hence, in this OOP article, I did not give you an index of definitions. Rather, I tried to give you a layout of OOP concepts that you can use to understand the most important concepts of OOP. This article answers most of the 'Why' question and a little bit of the 'How' question. Why do you need encapsulation? Why abstraction? How do you communicate while reducing the side effects of communication? I hope this layout will give you a different perspective of OOP concepts.

composition, dependencies, encapsulation, inheritance, java, oop concept, tutorial

Published at DZone with permission of Muhammad Umair . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}