Introduction

My wife Farhana wants to resume her career as a software developer (she started her career as a software developer, but couldn't proceed much because of our first child's birth), and these days, I am trying to help her learn Object Oriented Designs as I've got some experience in software design and development.

Since my early days in software development, I have always observed that no matter how hard a technical issue seems, it always becomes easier if explained from a real life perspective and discussed in a conversational manner. As we had some fruitful conversations on Object Oriented Designs, I thought I could share it because someone might find it an interesting way of learning OOD.

Topic: Introducing OOD

Farhana: You mean, Encapsulation, Inheritance, and Polymorphism, right? Yes, I know the principles.

Shubho: OK, I hope you already know how to use classes and objects. Let us learn Object Oriented Designs today.

Farhana: Hold on a second. Isn't Object Oriented Principles enough to do Object Oriented programming? I mean, I can define classes and encapsulate properties and methods. I can also define a class hierarchy based upon their relationship. So, what's left?

Shubho: Good question. Object Oriented Principles and Object Oriented Design are actually two different things. Let me give you a real life example to help you understand.

When you were child you learned alphabets first, right?

Farhana: Yes.

Shubho: OK. You also learned words and how to assemble the alphabets to make those meaningful words. Along with that, you learned some basic grammar to assemble the words into sentences. For example, you had to maintain tenses, and you had to use prepositions, conjunctions, and others properly to create grammatically correct sentences. Say, a sentence like the following:

You see, you are assembling the words in some order, and you are also choosing the correct words to end up with a sentence that has some meaning.

Farhana: OK, so, what does this mean?

Shubho: This is analogous to Object Oriented Principles. OOP says about the basic principles and the core ideas to do Object Oriented programming. Here, OOP can be compared to the basic English grammar, where the basic grammar teaches you how to construct a meaningful and correct sentence using words, and OOP teaches you to construct classes, encapsulate properties and methods inside them, and also develop a hierarchy between them and use them in your code.

Farhana: Hm..I got the point. So, where does OOD fit here?

Shubho: You'll get your answer soon. Now, suppose you need to write articles and essays on some topics. You may also wish to write books on different subjects that you have expertise on. Knowing how to construct sentences is not enough to write good essays/articles or books, right? You need to write a lot, and need to learn to explain things in a good way so that readers can easily understand what you are trying to say.

Farhana: Seems interesting... carry on.

Shubho: Now, if you want to write a book on a particular subject (say, Learning Object Oriented Design), you got to know how to divide the subject into smaller topics. You also need to write chapters on those topics, and you need to write prefaces, introductions, explanations, examples, and many other paragraphs in the chapters. You need to design the overall book and learn some best practices of writing techniques so that the reader can easily understand what you are trying to explain. This is about the bigger picture.

In software development, OOD addresses the bigger picture. You need to design your software in a way that your classes and code are modularized, re-usable, and flexible, and there are some good guidelines to do that so that you don't have to re-invent the wheel. There are some design principles that you can apply to design your classes and objects. Makes sense?

Shubho: Exactly! The universal truth of software is "your software is bound to change". Why?

Because, your software solves real life business problems and real life business processes evolve and change - always.

Your software does what it is supposed to do today and does it good enough. But, is your software smart enough to support "changes"? If not, you don't have a smartly designed software.

Farhana: OK, so, please explain "smartly designed software" sir!

Shubho: "A smartly designed software can adjust changes easily; it can be extended, and it is re-usable."

And, applying a good "Object Oriented Design" is the key to achieve such a smart design. Now, when can you claim that you have applied good OOD in your code?

Farhana: That's my question too.

Shubho: You are doing Object Oriented Design if your code is:

Of course, object oriented.

Re-usable.

Can be changed with minimal effort.

Can be extended without changing existing code.

Farhana: And..?

Shubho: We are not alone. Many people have already given lots of thoughts and put a lot of effort on this issue, and they've tried to achieve good Object Oriented Design and identify some basic principles for doing Object Oriented Design (some basic inspirations which you can use to lay out your object oriented design). They also have identified some common design patterns that are applicable to common scenarios (based on the basic principles).

Farhana: Can you name some?

Shubho: Sure. There are many design principles out there, but at the basic level, there are five principles which are abbreviated as the SOLID principles (thanks to Uncle Bob, the great OOD mentor).

In the following discussion, we will try to understand each of these in detail.

Topic: Single Responsibility Principle

Shubho: Let me show you the poster first. We should thank the person who made the posters, these are really interesting.

Single Responsibility Principle poster

It says, "just because you can implement all the features in a single device, you shouldn't". Why? Because it adds a lot of manageability problems for you in the long run.

Let me tell you the principle in Object Oriented terms.

"There should never be more than one reason for a class to change."

Or, differently said: "A class should have one and only one responsibility".

Farhana: Can you please explain?

Shubho: Sure, this principle says that if you have a class that has more than one reason to change (or has more than one overall responsibility), you need to split the class into multiple classes based upon their responsibility.

Farhana: Hmm... does that mean that I can't have multiple methods in a single class?

Shubho: Not at all. Rather, you surely can have multiple methods in a single class. The issue is, they have to meet a single purpose. Now, why is splitting important?

It's important because:

Each responsibility is an axis of change.

Code becomes coupled if classes have more than one responsibility.

Farhana: Could you please give me an example?

Shubho: Sure, take a look at the following class hierarchy. Actually, this example is taken from Uncle Bob, so thanks to him again.

Class hierarchy showing violation of SRP principle

Here, the Rectangle class does the following:

It calculates the value of the rectangular area.

It renders the rectangle in the UI.

And, two applications are using this Rectangle class:

A computational geometry application uses this class to calculate the area

A graphical application uses this class to draw a rectangle in the UI

This is violating the SRP (Single Responsibility Principle)!

Farhana: How?

Shubho: You see, the Rectangle class is actually performing two different things. It is calculating the area in one method, and it is returning a GUI representation of the rectangle in another method. This leads to some interesting problems:

We must include the GUI in the computational geometry application. While deploying the geometry application, we must include the GUI library.

A change to the Rectangle class for the graphical application may lead to a change, build, and test for the computational geometry application, and vice-versa.

Farhana: It's getting interesting. So I guess we should break up the class based on its responsibilities, right?

Shubho: Exactly. Can you predict what we should do?

Farhana: Sure, let me try. Following is what we might need to do:

Separate the responsibilities into two different classes, such as:

Rectangle: This class should define the area() method.

RectangleUI: This class should inherit the Rectangle class and define the Draw() method.

Shubho: Perfect. In this case, the Rectangle class will be used by the computational geometry application, and the RectangleUI class will be used by the graphical application. We could even separate the classes into two separate DLLs, and that will allow us not to touch the other in case a change is needed to be implemented in one.

Farhana: Thanks, I think I understand SRP. One thing, SRP seems to be an idea of breaking things into molecular parts so that it becomes reusable and can be managed centrally. So, shouldn't we apply SRP in the method level as well? I mean, we might have written methods that have many lines of code for doing multiple things. These methods might be violating SRP, right?

Shubho: You got it right. You should break down your methods so that each method does a particular work. That will allow you to re-use methods, and in case a change is required, you are able to do the change by modifying minimal amount of code.

Topic: Open-Closed Principle

Shubho: Here goes the poster for the Open-Closed Principle:

Figure: Open Closed Principle poster

If I need to explain it in design oriented terms, it would be as follows:

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

At the most basic level, that means, you should be able to extend a class's behavior without modifying it. It's just like I should be able to put on a dress without doing any change to my body, ha ha.

Farhana: Interesting. You can change your look by putting any dress you want, and you don't have to change your body for that. So you are open for extension, right?

Shubho: Yes. In OOD, open for extensions means that the behavior of the module/class can be extended and we can make the module behave in new and different ways as the requirements change, or to meet the needs of new applications.

Farhana: And your body is closed for modification. I like this example. So, the source code for a core class or module should not be modified when it needs an extension. Can you explain with some examples?

Shubho: Sure, take a look at the following example. This doesn't support the "Open-Closed" principle:

Class hierarchy showing violation of Open Closed principle

You see, the Client and Server classes are both concrete. So, if for any reason, the server implementation is changed, the client also needs a change.

Farhana: Makes sense. If a browser is implemented as tightly coupled to a specific server (such as IIS), then if the server is replaced for some reason with another one (say, Apache) the browser also needs to be changed or replaced. That would be really horrible!

Shubho: Correct. So following would be the correct design:

Class hierarchy showing Open Closed Principle

In this example, there is an Abstract Server class added, and the client holds a reference to the abstract class, and the Concrete Server class implements the Abstract Server class. So, if for any reason the Server implementation is changed, the Client is not likely to require any change.

The Abstract Server class here is closed for modification, and the concrete class implementations here are open for extension.

Farhana: As I understand, abstraction is the key, right?

Shubho: Yes, basically, you abstract the things that are the core concepts of your system, and if you do the abstraction well, most likely, it would require no change when the functionality is to be extended (such as the server is an abstract concept). And, you define the abstract things in the implementations (say, IISServer implements the Server) and code against abstractions (Server) as much as possible. This would allow you to extend the abstract thing and define a new implementation (say, ApacheServer) without doing any change in the client code.

Topic: Liskov's Substitution Principle

Shubho: The name "Liskov's Substitution Principle" sounds very heavy, but the idea is pretty basic. Take a look at this interesting poster:

Liskov Substitution Principle poster

The principle says:

"Subtypes must be substitutable for their base types."

Or, if said differently:

"Functions that use references to base classes must be able to use objects of derived classes without knowing it."

Farhana: Sorry, sounds confusing to me. I thought this is the basic rule of OOP. This is polymorphism, right? Why was an Object Oriented Principle required on this issue?

Shubho: Good question. Here is your answer:

In basic Object Oriented Principles, "Inheritance" is usually described as an "is a" relationship. If a "Developer" is a "SoftwareProfessional", then the "Developer" class should inherit the "SoftwareProfessional" class. Such "Is a" relationships are very important in class designs, but it's easy to get carried away and end up in a wrong design with a bad inheritance.

The "Liskov's Substitution Principle" is just a way of ensuring that inheritance is used correctly.

Farhana: I see. Interesting.

Shubho: Yes darling, indeed. Let's take a look at an example:

Class hierarchy showing an example of Liskov Substitution Principle

Here, the KingFisher class extends the Bird base class and hence inherits the Fly() method, which is pretty good.

Now take a look at the following example:

Corrected class hierarchy of Liskov Substitution Principle

Ostrich is a Bird (definitely it is!) and hence it inherits the Bird class. Now, can it fly? No! Here, the design violates the LSP.

So, even if in real world this seems natural, in the class design, Ostrich should not inherit the Bird class, and there should be a separate class for birds that can't really fly and Ostrich should inherit that.

Farhana: OK, understood. So, let me try to point out why the LSP is so important:

If LSP is not maintained, class hierarchies would be a mess, and if a subclass instance was passed as parameter to methods, strange behavior might occur.

If LSP is not maintained, unit tests for the base classes would never succeed for the subclass.

Am I right?

Shubho: You are absolutely right. You can design objects and apply LSP as a verification tool to test the hierarchy whether inheritance is properly done.

Topic: The Interface Segregation Principle

Shubho: Today, we will learn the "Interface Segregation Principle". Here is the poster:

Interface Segregation Principle poster

Farhana: What does it mean?

Shubho: It means the following:

"Clients should not be forced to depend upon interfaces that they do not use."

Farhana: Explain please.

Shubho: Sure, here is your explanation:

Suppose you want to purchase a television and you have two to choose from. One has many switches and buttons, and most of those seem confusing and doesn't seem necessary to you. Another has a few switches and buttons, which seems familiar and logical to you. Given that both televisions offer roughly the same functionality, which one would you choose?

Farhana: Obviously the second one with the fewer switches and buttons.

Shubho: Yes, but why?

Farhana: Because I don't need the switches and buttons that seem confusing and unnecessary to me.

Shubho: Correct. Similarly, suppose you have some classes and you expose the functionality of the classes using interfaces so that the outside world can know the available functionality of the classes and the client code can be done against interfaces. Now, if the interfaces are too big and have too many exposed methods, it would seem confusing to the outside world. Also, interfaces with too many methods are less re-usable, and such "fat interfaces" with additional useless methods lead to increased coupling between classes.

This also leads to another problem. If a class wants to implement the interface, it has to implement all of the methods, some of which may not be needed by that class at all. So, doing this also introduces unnecessary complexity, and reduces maintainability or robustness in the system.

The Interface Segregation principle ensures that Interfaces are developed so that each of them have their own responsibility and thus they are specific, easily understandable, and re-usable.

Farhana: I see. You mean interfaces should contain only the necessary methods and not anything else?

Shubho: Exactly. Let's see an example.

The following interface is a "Fat interface" which violates the Interface Segregation principle:

Example of an interface violating the Interface Segregation principle

Note that the IBird interface has many bird behaviours defined along with the Fly() behaviour. Now, if a Bird class (say, Ostrich) implements this interface, it has to implement the Fly() behaviour unnecessarily (Ostrich doesn't fly).

Farhana: That's correct. So, this interface must be split?

Shubho: Yes. The "Fat Interface" should be broken down into two different interfaces, IBird and IFlyingBird, where the IFlyingBird inherits IBird.

Correct version of the interface in the Interface Segregation principle example

If there is a bird that can't fly (say, Ostrich), it would implement the IBird interface. And if there is a bird that can fly (say, KingFisher), it would implement the IFlyingBird interface.

Farhana: So, if I go back to the example with the television with many switches and buttons, the manufacturer of that television must have a blueprint of that television where the switches and buttons are included in the plan. Whenever they want to create a new model of the television, if they need to re-use this blueprint, they would need to create as many switches and buttons as included in the plan. That wouldn't allow them to re-use the plan, right?

Shubho: Right.

Farhana: And, if they really want to re-use their plans, they should divide their television's blueprint into smaller pieces so that they can re-use the plan whenever any new kind of television is to be created.

Shubho: You got the idea.

Topic: The Dependency Inversion Principle

Shubho: This is the last principle among the SOLID principles. Here is the poster:

Dependency Inversion principle poster

It says..

"High level modules should not depend upon low level modules. Rather, both should depend upon abstractions."

Shubho: Let's consider a real world example to understand it. Your car is composed of lots of objects like the engine, the wheels, the air conditioner, and other things, right?

Farhana: Yes, of course.

Shubho: OK, none of these things are rigidly built within a single unit; rather, each of these are "pluggable" so that when the engine or the wheel has problem, you can repair it (without repairing the other things) and you can even replace it.

While replacement, you just have to ensure that the engine/wheel conforms to the car's design (say, the car would accept any 1500 CC engine and will run on any 18 inch wheel).

Also, the car might allow you to put a 2000 CC engine in place of the 1500 CC, given the fact that the manufacturer (say, Toyota) is the same.

Now, what if the different parts of your car were not built in such a "pluggable nature"?

Farhana: That would be horrible! Because, in that case, if your car's engine is out of order, you will have to fix the whole car or purchase a new one!

Shubho: Yes. Now, how can the "pluggable nature" be achieved?

Farhana: "Abstraction" is the key, right?

Shubho: Yes. In real world, Car is the higher level module/entity, and it depends on the lower level modules/entities like the Engines or Wheels.

Rather than directly depending on the Engines or Wheels, the car depends on the abstraction of some specification of Engine or Wheels so that if any the Engine or Wheel conforms to the abstraction, these could be assembled with the car and the car would run.

Let's take a look at the following class diagram:

Dependency Inversion principle class hierarchy

Shubho: In the above Car class, notice that there are two properties, and both of these are of abstract type (Interface) rather than concrete type.

The Engine and Wheels are pluggable because the car would accept any object implementing the declared interfaces, and that will not require any change in the Car class.

Farhana: So, if Dependency Inversion is not implemented in the code, we run the risk of:

Damaging the higher level code that uses the lower level classes.

Requiring too much time and effort to change the higher level code when a change occurs in the lower level classes.

Producing less-reusable code.

Shubho: You got it perfect darling!

Summary

Shubho: There are many other Object Oriented principles other than the SOLID principles. Some are:

"Composition over Inheritance": This says about favoring composition over inheritance.

"Principle of least knowledge": This says that "the less your class knows, the better".

"The Common Closure principle" : This says that "related classes should be packaged together".

"The Stable Abstractions principle": This says that "the more stable a class is, the more it must consist of abstract classes."

Farhana: Shouldn't I learn those principles too?

Shubho: Yes, of course. You have the whole world wide web to learn from. Just Google on those principles and try to understand. And of course, don't hesitate me to ask me if you need help.

Farhana: I've heard there are many Design Patterns built upon those design principles.

Shubho: You are right. Design Patterns are nothing but some commonly suggested design suggestions in commonly recurring situations. These are mainly inspired by the Object Oriented Design principles. You can think of Design Patterns as "Frameworks" and OOD principles as "Specifications".

I have one question from the example that you have given in 'Single Responsibility principle'. For giving single responsibility to a class, so we have divided Rectangle into two classes viz. Rectangle having Area() method and RectangleUI (which inherits Rectangle) having Draw() method. So that GUI and Geometry application can access corresponding class as per need. But if GUI is goign to access RectangleUI class then it can access Area() method as well because RectangleUI inheriting base class rectangle also.

Hi Shubho, your article is like a story book... it is well written & interesting to read..but, one this i am struggling to understand - I think I am the only person who did not understand this statement "We must include the GUI in the computational geometry application"...