Why do we need to learn Object Oriented Programming?

Algorithms + Data Structures = Programs’

Mohan had thoroughly read a book by Niklaus Wirth, which covered fundamental concepts of programming. He boasted, "I know everything about how to write a program; why do I need to learn OOPS?"

A wise developer replied, "Because what Niklaus said is theoretically correct: a program is a combination of two things: information (data) and a set of instructions for manipulating that information (algorithms). But it turns out that we are not just writing programs, we are writing software."

Mohan asked, "Well, what is the difference?"

The developer explained that a program is written to perform a specific task, such as sorting a linked list, finding a shortest path in a graph, or displaying a 'hello world' message on the console. Software, on the other hand, is a collection of programs that work together to perform one or more tasks.

Modern software is often extremely complex, consisting of millions of lines of code and operating on terabytes of data. It is usually too complex for a single person to understand in its entirety. Therefore, we need a way to organize these instructions in a way that makes them:

  • Easier to understand and explain
  • Easier to reuse and extend
  • Easier to maintain

Object-Oriented Programming (OOP) has been a popular paradigm for achieving these goals in the last few decades. When Mohan asked, "What is OOP and how can it help me?", the wise developer replied, "OOP is a programming paradigm that is based on the concept of 'objects', which can contain both data and behavior. It is designed to make it easier to understand, reuse, and maintain large software systems."

Before discussing Object-Oriented Programming (OOP), it is important to understand what an object is. An object is a logical construct that consists of user-defined data and a set of operations for manipulating that data. It can be thought of as a combination of data and behavior (Data + Operations = Object). OOP is a way of organizing and structuring a program around these objects.

The central idea behind OOP is that thinking in an object-oriented way can help you understand the problem you are trying to solve and create more maintainable and understandable software. It allows you to break a problem down into smaller, more manageable pieces and think about each piece individually, rather than trying to understand the entire problem at once. This can make it easier to design and build software that is easier for other people to understand and use.

Building System: The 'OOP 'Way

As an example, consider the task of building an inventory management system for a bookstore. The requirements for this system might include:

  • Storing metadata for each book, such as the name, author, and price.
  • Allowing books to be added to or removed from the inventory.
  • Providing the ability to search for books by metadata.

OOPS example to build an inventory management system for a bookstore

To build your system using an object-oriented approach, you will need to:

  • Identify objects in your system: The nouns in your requirements often correspond to objects in your system.
  • Identify the relationships and responsibilities of these objects: Identifying verbs in your requirements can give you a sense of the roles and responsibilities of each object.
  • Identify attributes (data) and operations (methods) for each object: Look at the remaining nouns, adjectives, and verbs again. Adjectives can define attributes, while verbs can define the operations to be performed on the object.

To further refine your design using an object-oriented approach, write down your analysis and go through the steps again. Ask questions like:

  • Does the author need to be a class or a string?
  • How should I store books so that they can be searched easily?
  • Does the order of search results matter? What if the user wants to sort books by price?

Asking these types of questions can also help you:

  • How to understand which objects are necessary and which ones are not?
  • How to avoid bugs in your system?
  • How to deliver software that meets the needs of the user?

Here is a simple example of how your classes might look like:

class Book {
    string name;
    string authorName;
    float price;
    string getName() { return this.name; }
    void setName(string name) { this.name = name; }
    string getAuthorName() { return this.authorName; }
    void setAuthorName(string authorName) { this.author = author; }
    float getPrice() { return this.price; }
    void setPrice(float price) { this.price = price; }
}

class Inventory {
    Book [] bookList;
    Book [] searchItem(string name) {}
    void addItem(Book book) {}
    Book removeItem(Book book) {}
}

As another example, consider the task of building a chess game. To get started, think about the physical objects you need in order to play a game of chess in real life. These might include:

  • A board with 8x8 squares, where the game is played.
  • Chess pieces of different types, such as pawns, bishops, knights, kings, queens, and rooks, for each player.
  • Two players to play the game.

From the requirements above, we can identify the following objects: player, board, square, pawn, bishop, knight, king, queen, rook, game, etc. These objects can be used to structure the chess game and make it easier to understand, reuse, and maintain.

Wait!

It is common when designing a real-world system to model objects according to physical objects that we can see in the real world. In the case of the chess game, we could create a separate class for each noun identified in the requirements. But a wise programmer always thinks twice before writing any code.

As Robert C. Martin wrote in "Clean Code: A Handbook of Agile Software Craftsmanship," "the ratio of time spent reading versus writing is well over 10 to 1." This means that we spend a lot of time reading code, so it is important to make it easy to read in order to make it easier to write.

When designing your system, consider whether each piece requires a separate class, or if they are instances of the same class with different types. For example, do you need a separate player class, or can players be considered external initiators interacting with the system? Remember, there is no single correct answer, but a simple design with fewer entities is often a good starting point.

One such answer could be :

enum Color { BLACK, WHITE };
class ChessPiece {
    enum Type { PAWN, BISHOP, KNIGHT, KING, QUEEN, ROOK };
    Type type;
    Color color; 
    Square currentPos;
    // moves the piece to target square.
    void move(Square targetSquare);
}

class Square {
    Color color;
    ChessPiece piece;
    String position;
}

class Board {
    Square squares[8][8];
    //initialize game board and setup pieces
    constructor();
}

class Game {
    ChessPiece activePieces[];
    ChessPiece capturedPieces[];
    void startGame();
    void stopGame();
    void pauseGame();
}

"So, just like in the world of algorithms, where we try to divide a problem into smaller parts in order to find an optimal solution for the computer, we are dividing our program into smaller parts in order to find an optimal code for developers." - Mohan

"Yes, that's correct. There are many other programming paradigms that were created with this goal in mind. But that's a topic for another time. For now, you should focus on improving your object-oriented programming skills." - The wise developer replied.

Conclusion

Objects are an integral part of every software system that you interact with in your daily life. Deciding which objects you need and which you don't require careful analysis of your requirements and a lot of experience. Remember that object-oriented programming (OOP) provides a mental model for how to structure your software. Once you understand this concept, you can use it in any programming language.

Try applying these ideas to software that you use in your daily life to gain a deeper understanding of how OOP works in practice. Enjoy learning, enjoy OOPS!

Share feedback with us

More blogs to explore

Our weekly newsletter

Subscribe to get weekly content on data structure and algorithms, machine learning, system design and oops.

© 2022 Code Algorithms Pvt. Ltd.

All rights reserved.