Search Sreeni's Insights

Filter by content type
technical October 4, 2011 11 min read

How all these concepts connect? - Part 8

This final article connects the three series, showing how real-world problems, computational thinking and object-oriented principles form one practical mental model for designing software with a grocery shop example.

Share:

How all these concepts connect? - Part 8

When we learn a big subject one article at a time, we usually end up with a box of separate pieces, a definition of abstraction here, a rule about inheritance there, a code example of polymorphism somewhere else. Each piece makes sense on its own, but when we sit down to design a real system, we don’t know which piece to use first or how they fit. Knowledge without connections is hard to use, and it is forgotten quickly. Over three series, we travelled from how a computer solves a real-world problem, to how a programmer thinks, to how an object-oriented designer thinks. In the previous article, we discussed how objects relate to each other. In this final article, we are going to connect all the pieces, the journey from real-world problem solving to computational problem solving to object-oriented thinking, the threads which run through all of them and how each object-oriented principle builds on the previous one, so that you have one clear mental model.

Object-Oriented Thinking series:

  1. How to model the real world with objects? - Part 1
  2. How do we organize what we know? - Part 2
  3. What is abstraction? - Part 3
  4. What is encapsulation? - Part 4
  5. What is inheritance? - Part 5
  6. What are subtype and subclass polymorphism? - Part 6
  7. How objects relate to each other? - Part 7
  8. How all these concepts connect? (this article)

TL; DR Summary

  • Real-world problem solving, computational thinking and object-oriented thinking are not three subjects, they are three stages of the same way of thinking.
  • Every stage uses the same few mental tools, breaking down, finding what is common, keeping what matters and planning the steps.
  • Object-oriented thinking adds one question to computational thinking, “who is responsible for this?”, instead of only “what are the steps?”.
  • The principles are layered, classification gives kinds, abstraction keeps the essence of a kind, encapsulation protects it, inheritance specializes it, polymorphism treats the special kinds the same way and relationships connect them into a system.
  • Each principle depends on the ones below it. A weak layer at the bottom makes every layer above it weak.
  • All of them exist for one purpose, managing complexity, so that the system can grow and still be understood and changed.

Common Challenges

Knowing the pieces, not the picture

Many developers can define all four principles in an interview, but in the design they still create one big class with everything inside. The reason is, they learned the principles as separate rules, not as connected steps. When a rule is not connected to a reason, we don’t know when to apply it, and we either use it everywhere or nowhere.

Learning the tools before the thinking

Most of the courses start with the keywords, class, interface, extends, private. The tools are learned first and the thinking is expected to come later, which rarely happens. As a result of this, “abstraction” becomes “abstract class”, “encapsulation” becomes “getters and setters” and “inheritance” becomes “reuse”. This series intentionally went the other way, the real world and philosophy first, then the software.

The journey in three stages

The following diagram depicts the full journey across the three series. Each stage builds on the previous one, and the dashed lines show how the ideas of computational thinking continue as the ideas of object-oriented thinking.

From the real world to objects
From the real world to objects

Let us discuss each stage.

Stage 1 - Real-world problem solving

Everything starts with a real problem, a shopkeeper who writes every bill by hand in a notebook, makes mistakes in the totals and takes too long when the queue is growing. Humans have always solved such problems with their own mind, by planning, by noticing what is repeating and by focusing on what matters.

In the Understanding Computers and Programming series, we saw that a computer can help only when the solution is written as a program, a precise set of instructions, in a programming language which is finally converted to machine code and executed by the CPU. The computer is very fast and never gets tired, but it has no common sense. It means, the burden of thinking clearly is fully on us.

Stage 2 - Computational problem solving

In the Thinking Like a Programmer series, we learned how to convert a messy real-world problem into something a computer can execute. The four pillars of computational thinking, decomposition, pattern recognition, abstraction and algorithm design, gave us a method. Then we saw how the information is represented as data, how the data is organized in data structures and finally, that there are different paradigms, different ways of thinking about the same solution.

Notice that none of these pillars are about computers. We use them to plan a wedding or prepare for an exam. Computational thinking is the same real-world thinking, made precise enough for a machine.

Stage 3 - Object-oriented thinking

Object-oriented paradigm is one of those paradigms, and in this series, we looked at it in depth. It doesn’t throw away computational thinking, it changes the main question. Procedural thinking asks “what are the steps?”. Object-oriented thinking asks “what are the things, what kind is each one and what is each one responsible for?”. The steps are still there, but they live inside the objects which are responsible for them.

The threads which run through all three stages

The same few ideas appear in every stage, only in a different form. Find below these threads,

IdeaReal-world problem solvingComputational thinkingObject-oriented thinking
Breaking downDivide the wedding work among the familyDecomposition into smaller problems and stepsDecomposition into objects, each with a responsibility (Part 1)
Seeing what is common”This is like the problem I solved last year”Pattern recognitionClassification, generalization and classes (Part 2)
Keeping what mattersA map shows only the roadsAbstraction pillarAbstraction principle, the outside view of an object (Part 3)
Doing the workA recipe, step by stepAlgorithmBehaviour, the algorithm lives inside the object (Part 1)
Knowing thingsThe shopkeeper’s notebookData and data typesState of an object, protected by encapsulation (Part 4)
Organizing thingsRacks and sections in a shopData structuresComposition and relationships between objects (Part 7)
Choosing an approachMany ways to reach the same placeProgramming paradigmsPolymorphism, many forms for one behaviour (Part 6)

If you remember only one thing from this article, remember this table. Every principle in object-oriented thinking is an older idea, coming from the real world, through computational thinking, into objects.

How the principles build on each other?

The principles are not a list, they are a stack. The following diagram depicts the stack, with the foundation at the bottom and the question each layer answers on the right.

How the principles build on each other
How the principles build on each other

Let us walk through the stack from the bottom.

  1. Classification (Part 2) - Before we can think about anything, we group the things into kinds. Rice, sugar and oil become “item”. Without kinds, every thing is unique and nothing can be reused, so all the other principles start here.
  2. Abstraction (Part 3) - Once we have a kind, we decide what is essential about it for our purpose, the essence of Picasso’s bull. For billing, an item is a name, a price and a barcode. Abstraction works on kinds, that is why it needs classification below it.
  3. Encapsulation (Part 4) - Once we know what is essential and visible, we protect everything else behind a boundary, and the object becomes responsible for its own state. Encapsulation needs abstraction, otherwise we don’t know what to show and what to hide, and an abstraction needs encapsulation, otherwise it can be bypassed.
  4. Inheritance (Part 5) - Once a kind is well abstracted and well protected, we can create special kinds of it, the weighed item from the item. The child inherits the abstraction (what it looks like from outside) and the promises protected by encapsulation (the invariants). If the parent is poorly abstracted or poorly encapsulated, every child inherits the same problems, the fragile base class.
  5. Polymorphism (Part 6) - Once we have many special kinds which keep the same promises, the caller can treat all of them as the general kind, like the conductor with the orchestra. Polymorphism needs abstraction (what to ask), encapsulation (how stays inside each form) and inheritance or subtyping (every form keeps the promise). If one form breaks the promise, like the square, polymorphism fails.
  6. Relationships (Part 7) - Finally, objects of different kinds are connected into a working system, association, aggregation, composition, dependency and inheritance. The “is a kind of” hierarchy becomes inheritance and the “is a part of” hierarchy becomes composition, the two hierarchies we separated in Part 2.

It means, a problem at a lower layer always shows up at a higher layer. Most of the “polymorphism doesn’t work” or “inheritance broke everything” issues are actually a wrong classification or a weak abstraction at the bottom of the stack.

Everything is about managing complexity

Based on the above, you may be wondering, why do we need so many principles? The answer is that a real system is too complex for one mind, and each principle removes a different kind of complexity. Find below the summary,

  • Classification - Reduces the number of things to remember, we learn the kind once instead of every thing.
  • Abstraction - Reduces what we need to see, we look only at the essential part.
  • Encapsulation - Reduces what can break, only the responsible object can change its state.
  • Inheritance - Reduces repetition, we say a thing once at the general level.
  • Polymorphism - Reduces the ripple effect of change, a new form doesn’t change the caller.
  • Relationships - Reduce the coupling, each object knows only the objects it really needs.

When a system is small, we can survive without these principles. When the system is growing, with more features, more teams and more years of changes, these principles decide whether the system can still be understood and changed, or whether every small change becomes a risk.

One problem, end to end

Let us take our grocery shop once again and see the whole journey on one page.

  1. Real-world problem - The shopkeeper writes bills by hand, the totals have mistakes and the queue is long.
  2. Program - We decide that a computer will calculate the bill, so we need a program, written in a programming language and executed by the CPU.
  3. Computational thinking - We decompose billing into reading items, calculating the total, applying the discount and printing. We notice that every item follows the same pattern, price multiplied by quantity. We keep only the name, price and quantity. We write the algorithm for the total.
  4. Objects (Part 1) - We ask “who is responsible?”. The item knows its price and its amount, the bill knows its lines and its total, the customer places bills.
  5. Classification (Part 2) - Rice, sugar and oil are all items. Cash, card and wallet are all payments. Some items are sold by weight, which is a special kind of item.
  6. Abstraction (Part 3) - For billing, an item is a name, a price and a barcode. The bill offers “add item” and “give total”, nothing more.
  7. Encapsulation (Part 4) - The lines and the total are inside the bill, only addItem() can change them, so the total is always equal to the sum of lines.
  8. Inheritance (Part 5) - A weighed item is an item, it inherits the name, the barcode and the promise “amount is never negative”, and refines how the amount is calculated.
  9. Polymorphism (Part 6) - The checkout says “pay” to any payment and “apply” to any discount rule. When the mobile wallet comes, checkout doesn’t change.
  10. Relationships (Part 7) - The customer places bills, the bill owns its lines, each line refers to an item and the bill uses the payment gateway.

Notice that each step uses the result of the previous step. We couldn’t decide the abstraction without the kinds, we couldn’t encapsulate without knowing the abstraction and we couldn’t use polymorphism without the kinds keeping the same promises.

The mental model in one table

Find below the full picture of the principles, from the real world to software,

PrincipleIn the real worldPhilosophical rootIn object-oriented thinkingQuestion it answers
ClassificationA child learns “dog”Particulars and universals, genus and differentiaObjects and classesWhat kinds of things are there?
AbstractionA map, Picasso’s bullEssential vs accidental propertiesThe outside view of a class, interfacesWhat matters about this kind?
EncapsulationThe pilot, the pharmacist, the cellAuthority goes with responsibilityPrivate state, behaviour, invariantsWho is responsible for it?
InheritanceDoctor, surgeon, cardiac surgeon”Is a kind of” hierarchySubclass, “is a”, inherited promisesHow is this kind special?
PolymorphismThe orchestra, the power plugOne essence, many formsSubclass and subtype polymorphismCan I treat them all the same?
RelationshipsA family, a team, a house and its rooms”Is a part of” hierarchyAssociation, aggregation, composition, dependencyWho works with whom?

Common misconceptions

With the full picture, it is easier to see why some common beliefs are wrong. Find below few of them,

  • “Abstraction is an abstract class” - Abstraction is deciding the essence, the abstract class is only one way to write it down.
  • “Encapsulation is getters and setters” - Encapsulation is responsibility and trust, getters and setters for everything is the opposite.
  • “Inheritance is for reuse” - Inheritance is for a true “is a kind of” relationship with the same promises. For reuse, prefer composition.
  • “Polymorphism is method overloading” - Overloading is one kind, but the polymorphism at the heart of object-oriented thinking is one request, many forms which keep the same promise.
  • “Object-oriented is always better” - It is one paradigm among many. As we discussed in Thinking Like a Programmer - Part 5, choose the paradigm based on the problem.

How to practice?

Reading is only the start, the mental model becomes yours only when you use it. Follow these steps with a small system of your own, a library, a bus booking or a hospital appointment,

  1. Write the real-world problem in a few sentences, who has the pain and why.
  2. Apply computational thinking, decompose, find the patterns, keep what matters and sketch the main algorithms.
  3. Find the objects with the noun and verb steps from Part 1.
  4. Classify them into kinds, and check that each division uses one principle at a time.
  5. For each kind, write its abstraction, what the outside world sees, and its invariants, what it protects.
  6. Look for true “is a kind of” families, and test each with the “is a” test and the promises.
  7. Find the places where new forms will keep coming, like payment types or fine rules, and design them as one behaviour with many forms.
  8. Connect the objects with the weakest relationship which correctly describes the business, and draw the class diagram.

Keep in mind that the first design is never perfect. Like the scientists with the platypus, refine the classification when the real world doesn’t fit, instead of forcing the real world into your design.

Wrap up

In this article, we have looked at the journey from real-world problem solving to computational thinking to object-oriented thinking, the threads which run through all three, how the principles build on each other as a stack, why all of them are about managing complexity, the whole journey with our shop example and the common misconceptions. With this, we have completed the Object-Oriented Thinking series, and also the journey we started with the Understanding Computers and Programming series. I really appreciate that you took the time to read this series and I hope it provided you some insights into the object-oriented way of thinking, not only the syntax. Try the practice steps with a small system of your own, you will notice all these principles coming together, I have experienced it many times and I hope for you too.

Related Posts