Object Oriented Design Principle: The Open-Closed Principle (OCP)

open closed principle

When there’s a single change in the program that results to unexpected changes to the other dependent modules that program have obviously undesirable traits that we have come to associate with “bad design”. The program can easily break, hard to maintain and worse it can be unreusable. The OCP principle guides to us to avoid this.

The OCP principle states that,

Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

To paraphrase, it says that you should design modules that never change. Whenever there’s a change in requirement, you should extend the existing module by adding new code, not by modifying existing code that have already been tested.

Conformance to this principle comes in two aspect.

  1. Modules should be “Open for Extension”

This means that the module can be extended. Let say you have already perfect, tested and working code, you don’t want anybody messing your code. You can let them extend through abstraction. For example, you have a class designed for inheritance, of course it’s designed to be extended. You can override the methods or add methods to the the class declared in the superclass to add or extend functionality to your more specific classes . In that case, you’re extending the module without messing the code that you know is working.

Inheritance is the easiest way to achieve OCP principle. But there are other better ways to achieve this like composition, delegation and many more.

2. Modules should be “Closed for modification”

This means that code that are already working should not be modified unless you have to. You can add functionality to the existing system by extending them. You make sure that you design modules that can easily change in the way that you’re not modifying perfect code that can cause to break other program’s functionality.

By avoiding changes to the existing code, you can also avoid new bugs and errors that will come up.

Conclusion

Like with other design principles, if you followed those principles correctly, you’re making your code easy to extend and maintain.

For code example to this principle, you may refer to this page.

If I miss something on this blog post, just leave a comment below. And I’ll add it to this blog post.

Don’t forget to subscribe to this blog to get notified for the new posts!

Object Oriented Design Principle: Programming for Interface NOT Implementation

Programming for interface not implementation

Programming for interface not implementation principle will lead to code flexibility. Most important purpose of interface is polymorphism.  By polymorphism, java can handle objects dynamically at runtime.

Okay, let’s take a very simple example for you to realize how this principle will make your code flexible!

Suppose we have already a Tiger and Lion class.

And we have this Zoo class


import java.util.ArrayList;

public class Zoo {
    private ArrayList animalList;
    
    public Zoo() {
        animalList = new ArrayList();
    }
    
    public void addAnimal( Lion lion ) {
        animalList.add( lion );
    }
    
    public void addAnimal( Tiger tiger ) {
        animalList.add( tiger );
    }
}

The animal list will hold all animals in the zoo. And we have to overload addAnimal() method for adding each animal. But wait, what if we add zebra to be added in the zoo?

Solution #1 – it’s pretty easy add another addAnimal method takes Zebra object.


import java.util.ArrayList;

public class Zoo {
    private ArrayList animalList;
    
    public Zoo() {
        animalList = new ArrayList();
    }
    
    public void addAnimal( Lion lion ) {
        animalList.add( lion );
    }
    
    public void addAnimal( Tiger tiger ) {
        animalList.add( tiger );
    }

    public void addAnimal( Zebra zebra ) {
        animalList.add( zebra );
    }
}

Cool! But the zoo has expanded! The zoo can accommodate hundreds of animals.

Here’s your code now!


import java.util.ArrayList;

public class Zoo {
    private ArrayList animalList;
    
    public Zoo() {
        animalList = new ArrayList();
    }
    
    public void addAnimal( Lion lion ) {
        animalList.add( lion );
    }
    
    public void addAnimal( Tiger tiger ) {
        animalList.add( tiger );
    }

    public void addAnimal( Zebra zebra ) {
        animalList.add( zebra );
    }

    public void addAnimal( Monkey monkey ) {
        animalList.add( monkey );
    }

    public void addAnimal( Crocodile crocodile ) {
        animalList.add( crocodile );
    }

    public void addAnimal( Eagle eagle ) {
        animalList.add( eagle );
    }
    //100 MORE ANIMALS!
}

What the heck! 1000 lines of code full of duplications!

this-is-why-i-bomb-people

The code above clearly violates not only programming for interface not implementation principle but also  DRY Principle and Open-Closed Principle.

Every time we add an animal we need also to change the code for the Zoo class. But how can we solve this?

Interface to the rescue!

Create an interface Animal and let all animal concrete classes to implement it.


public class Tiger implements Animal {

} 

//for the rest of the animals also

And here’s our new Zoo class.



import java.util.ArrayList;

public class Zoo {
    private ArrayList animalList;
    
    public Zoo() {
        animalList = new ArrayList();
    }
    
    public void addAnimal( Animal animal ) {
        animalList.add( animal );
    }
}


In that case, Zoo class doesn’t have to know what type of animal to be added in the list. In the other words, you can create another animal-specific class without changing our code! Isn’t awesome?

You just made your code flexible!

I apologize for the simplicity of the example 🙂

For more design principle, just click here.

If you liked or disliked with this blog post, feel free leave a comment below. I really love to hear critics.

Don’t forget to share it and follow my blog for more updates.

Object Oriented Design Principle: The Single Responsibility Principle (SRP)

SRP principle

Look at the guy above. He’s an employee of a company. While doing his work, he diverts his attention to other things — doing side projects, answering personal phone calls, browsing social media sites, etc. After no work being done, his boss fired him. In short, NOT focusing on one responsibility at a time kills you!

It’s the same in object oriented programming. Classes that have many responsibilities is difficult to change, debug, and maintain. Having single responsibility implies simplicity. The simpler your code is, the easier to maintain. On the other hand, having multiple responsibilities to classes indicates complexity. Complexity makes the system hard or cannot be maintain. Therefore, complexity kills your project!

There’s a principle to the rescue,

It’s the Single Responsibility Principle (SRP).

The SRP principle states that,

Every object in your system should have a single responsibility, and all the object’s services should be focused carrying out single responsibility.

Now, let’s take an example that violates this principle.

Vehicle.java


public class Vehicle {
    public void start() {
    }
    public void stop() {
    }
    public void changeTires( Tire[] tires ) {
    }
    public void drive() {
    }
    public void checkOil() {
    }
}

If you understood well the definition of SRP, you can spot the methods that made the Vehicle class violates SRP. 

Take a minute to think before reading the answers below!

If you can’t spot them, here’s the technique:

The                                                            itself.

  1. In the first underline, place your class name in there.
  2. For the second underline, place each method name.

Then analyze the sentence, if it makes sense, it doesn’t violate SRP.

Let’s analyze the first two methods.

  • The Vehicle starts itself.
  • The Vehicle stops itself.

It makes sense, the Vehicle is responsible for starting and stopping the engine.

  • The Vehicle changeTires itself.
  • The Vehicle checks oil itself.

No! You need a mechanic to change the vehicle tires and to check the vehicle’s oil. How can a vehicle change its tires and checks oil itself? Oh! It’s possible, only when the vehicle is very high-tech and robotic! But this vehicle I’m making is just an ordinary vehicle!

  • The Vehicle drives itself.

Again, it doesn’t make sense. You’ll need a driver to drive a vehicle!

Let’s solve this!

Much simplier Vehicle class.

public class Vehicle {
    public void start() {
    }
    public void stop() {
    }
}

Changing the tires and checking oil is really the responsibility of a mechanic.

public class Mechanic {
    public void changeTires( Vehicle vehicle, Tire[] tires ) {
    }
    public void checkOil() {
    }
}

And then the driver,

public class Driver {
    public void drive( Vehicle vehicle ) {
    }
}

The code above might violate other design principles like “Programming for Interface Not Implementation”. But for this SRP principle, I just show you how to separate responsibilities.

Imagine you have many classes in your project, and each class overlaps responsibilities, it’s so difficult to maintain whenever the requirements of the project would change. Again, the simpler your code is, the easier to maintain.

SRP doesn’t apply only to classes but also other modules in your code like methods. So you make sure your methods has only single responsibility.

By the way this principle is also similar to cohesion. If you followed SRP correctly, then your code is considered highly cohesive.

For more design principles, click here.

I’m not an expert on this topic. If you disagree with me just let me know, I would love to hear it from you.

If you have learned something on this blog post, don’t forget to follow my blog to receive email notifications for new my posts. Also, share it to your friends to any social media you like.

Happy Learning!

Change Your Life With FREE Blogging Course by John Sonmez

This blog would not be possible if I didn’t discover Simple Programmer.

The founder of Simple Programmer is John Sonmez:

john sonmez
John Sonmez

He is a software developer, author, blogger and many more. You can know more about him here.

In Simple Programmer, he talks about how to market yourself as a software developer, specialization, productivity, etc. He talks more about soft skills and passionate in making the complex simple.

He has a 3-week blogging course to help boost the careers of programmers. I immediately signed up to his course. I got two emails from him every week. He will teach you how to setup your blog, choosing a theme for you blog, tells you the secret for a successful blog, get some traffic to your blog and of course how blog will boost your career. The best thing is, it’s FREE.

As a student, this blog is really a stepping stone for me. I learned that to master something you need to teach it. And one way to teach it is by starting a blog. The really challenge for me here is to be consistent writing quality blog posts.

Whether you’re a programmer or not, I encourage you to join John’s free blogging course. If you ignore it, you’ll regret it for the rest of your life! I’m not kidding! Read this — 12 Reasons You Should Start Blog Today

Sign up now! And come along with me changing our lives. 

Object Oriented Design Principle: Don’t Repeat Yourself (DRY)

dry

DRY principle, as the name it implies, you should not make duplicate code.   I think it’s the most fundamental principle among others. However, many of us violate this principle. 

Less code, less bugs

If you found duplicate a code, move that code to a reusable unit like methods. By that way, you’re making less codes and when the time comes that you need changes or fix a bug, you can easily refractor it because it’s already in a single sensible place. 

Imagine 10000 lines of code full of duplication, that’s really a maintenance nightmare.

ComputerRegret_main_0415

If you need to change a code, you’ll also to change other duplicates. This principle is pretty simple but it’s the most important practices in software development.

I’m not gonna provide you a example for DRY. Instead, try to read your code on your projects and spot for duplicate code and refractor it. You’ll gonna benefit it in the long run.

But, DRY isn’t not all about code

But DRY principle is more than just about duplicate code. According to the book, The Pragmatic Programmer, DRY defines,

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

DRY can be also applied to writing requirements, making use cases or anything involved in the system. Making sure that you implemented the requirement once and making sure use cases don’t overlap.

After all, DRY is not just removing or avoiding duplication, it’s also about making good decisions about how to break system’s functionality.

For more design principles, click here.

If you liked this post, please share this post or subscribed to my blog.

Object Oriented Design Principles

OOP Design Principles

In this blog post, I’ll share to you different object oriented design principles that every programmer or software developer has to master. There are already so many articles about this on the internet but I’ll try to explain it in my own way to expand my understanding about this topic.

Design Principles is an essential way of designing or writing code to make that code more maintainable, flexible or extensible.

These design principles are proven and tested by the great programmers and authors who has many years of experience in software development. It is good when you know these design principles to avoid problems when maintaining your code.

I created a list below.

For each design principle, I will create a blog posts explaining the design principle and provide a code that violates that principle and code that conforms with that principle. And here, I will update the link for each principle. I cannot publish all design principle for one day, but I intend to published it all this month.

If you want to keep updated with my posts, don’t forget to subscribe.

A Book Every Programmer/Developer SHOULD Read

clean-code

In software development, a common mistake especially for beginners(like me), they often write messy and unmaintainable code. And that is because they don’t know the best and proper practices in software development. I am a strong believer of the quote saying,

“Learning from your own mistakes is wise but learning from others mistakes is wiser”.

One way of learning from others mistake is by reading books from the great programmers and authors who had gone many years of experience dealing mistakes.

The book Clean Code: A Handbook of Agile Software Craftmanship change the way of writing and organizing my code. It changed the way how I named my variables, the way I wrote methods and the way how I structured my code.

So if you haven’t read the book, read the book now and change the way you code. It won’t make you better at any programming language but it will definitely make you a better programmer and clean coder.