0% found this document useful (0 votes)
86 views

01 Object Oriented Design Notes

The document introduces object-oriented programming concepts including objects, classes, class hierarchies, and the four pillars of OOP: abstraction, encapsulation, inheritance, and polymorphism. It explains that objects are instances of classes, with fields to store data and methods to define behavior. Classes can be organized into hierarchies where subclasses inherit from parent classes. The four pillars distinguish OOP from other paradigms, with abstraction modeling real-world objects, encapsulation hiding implementation details, inheritance enabling code reuse, and polymorphism allowing objects to take different forms.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views

01 Object Oriented Design Notes

The document introduces object-oriented programming concepts including objects, classes, class hierarchies, and the four pillars of OOP: abstraction, encapsulation, inheritance, and polymorphism. It explains that objects are instances of classes, with fields to store data and methods to define behavior. Classes can be organized into hierarchies where subclasses inherit from parent classes. The four pillars distinguish OOP from other paradigms, with abstraction modeling real-world objects, encapsulation hiding implementation details, inheritance enabling code reuse, and polymorphism allowing objects to take different forms.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

8 Introduction to OOP / Basics of OOP

Basics of OOP
Object-oriented programming is a paradigm based on the con-
cept of wrapping pieces of data, and behavior related to that
data, into special bundles called objects, which are construct-
ed from a set of “blueprints”, deXned by a programmer, called
classes.

Objects, classes
Do you like cats? I hope you do because I’ll try to explain the
OOP concepts using various cat examples.

This is a UML class diagram. You’ll see a lot of such diagrams in the book.
9 Introduction to OOP / Basics of OOP

Say you have a cat named Oscar. Oscar is an object, an instance


of the Cat class. Every cat has a lot of standard attributes:
name, sex, age, weight, color, favorite food, etc. These are the
class’s Belds.

All cats also behave similarly: they breathe, eat, run, sleep and
meow. These are the class’s methods. Collectively, Xelds and
methods can be referenced as the members of their class.

Data stored inside the object’s Xelds is often referenced


as state, and all the object’s methods deXne its behavior.

Objects are instances of classes.


10 Introduction to OOP / Basics of OOP

Luna, your friend’s cat, is also an instance of the Cat class.


It has the same set of attributes as Oscar. The difference is in
values of these attributes: her sex is female, she has a differ-
ent color, and weighs less.

So a class is like a blueprint that deXnes the structure for


objects, which are concrete instances of that class.

Class hierarchies
Everything Xne and dandy when we talk about one class. Nat-
urally, a real program contains more than a single class. Some
of these classes might be organized into class hierarchies. Let’s
Xnd out what that means.

Say your neighbor has a dog called Fido. It turns out, dogs
and cats have a lot in common: name, sex, age, and color are
attributes of both dogs and cats. Dogs can breathe, sleep and
run the same way cats do. So it seems that we can deXne the
base Animal class that would list the common attributes and
behaviors.

A parent class, like the one we’ve just deXned, is called a


superclass. Its children are subclasses. Subclasses inherit state
and behavior from their parent, deXning only attributes or
behaviors that differ. Thus, the Cat class would have the
meow method, and the Dog class the bark method.
11 Introduction to OOP / Basics of OOP

UML diagram of a class hierarchy. All classes in this diagram are part of
the Animal class hierarchy.

Assuming that we have a related business requirement, we can


go even further and extract a more general class for all liv-
ing Organisms which will become a superclass for Animals
and Plants . Such a pyramid of classes is a hierarchy. In such
a hierarchy, the Cat class inherits everything from both the
Animal and Organism classes.
12 Introduction to OOP / Basics of OOP

Classes in a UML diagram can be simpliBed if it’s more important to show


their relations than their contents.

Subclasses can override the behavior of methods that they


inherit from parent classes. A subclass can either complete-
ly replace the default behavior or just enhance it with some
extra stuff.
13 Introduction to OOP / Pillars of OOP

Pillars of OOP
Object-oriented programming is based on four pillars, con-
cepts that differentiate it from other programming paradigms.

Abstraction
Most of the time when you’re creating a program with OOP,
you shape objects of the program based on real-world objects.
However, objects of the program don’t represent the origi-
nals with 100% accuracy (and it’s rarely required that they do).
Instead, your objects only model attributes and behaviors of
real objects in a speciXc context, ignoring the rest.

For example, an Airplane class could probably exist in both


a Yight simulator and a Yight booking application. But in the
former case, it would hold details related to the actual Yight,
whereas in the latter class you would care only about the seat
map and which seats are available.
14 Introduction to OOP / Pillars of OOP

Different models of the same real-world object.

Abstraction is a model of a real-world object or phenomenon,


limited to a speciXc context, which represents all details rele-
vant to this context with high accuracy and omits all the rest.

Encapsulation
To start a car engine, you only need to turn a key or press a
button. You don’t need to connect wires under the hood, rotate
the crankshaft and cylinders, and initiate the power cycle of
the engine. These details are hidden under the hood of the
car. You have only a simple interface: a start switch, a steering
wheel and some pedals. This illustrates how each object has
an interface—a public part of an object, open to interactions
with other objects.
16 Introduction to OOP / Pillars of OOP

that any object passed to an airport object, whether it’s an


Airplane , a Helicopter or a freaking DomesticatedGryphon
would be able to arrive or depart from this type of airport.

UML diagram of several classes implementing an interface.

You could change the implementation of the fly method in


these classes in any way you want. As long as the signature
of the method remains the same as declared in the interface,
all instances of the Airport class can work with your Yying
objects just Xne.
17 Introduction to OOP / Pillars of OOP

Inheritance
Inheritance is the ability to build new classes on top of exist-
ing ones. The main beneXt of inheritance is code reuse. If you
want to create a class that’s slightly different from an existing
one, there’s no need to duplicate code. Instead, you extend the
existing class and put the extra functionality into a resulting
subclass, which inherits Xelds and methods of the superclass.

The consequence of using inheritance is that subclasses have


the same interface as their parent class. You can’t hide a
method in a subclass if it was declared in the superclass. You
must also implement all abstract methods, even if they don’t
make sense for your subclass.

UML diagram of extending a single class versus implementing multiple


interfaces at the same time.

In most programming languages a subclass can extend only


one superclass. On the other hand, any class can implement
several interfaces at the same time. But, as I mentioned before,
18 Introduction to OOP / Pillars of OOP

if a superclass implements an interface, all of its subclasses


must also implement it.

Polymorphism
Let’s look at some animal examples. Most Animals can make
sounds. We can anticipate that all subclasses will need to over-
ride the base makeSound method so each subclass can emit
the correct sound; therefore we can declare it abstract right
away. This lets us omit any default implementation of the
method in the superclass, but force all subclasses to come up
with their own.

Imagine that we’ve put several cats and dogs into a large bag.
Then, with closed eyes, we take the animals one-by-one out of
19 Introduction to OOP / Pillars of OOP

the bag. After taking an animal from the bag, we don’t know
for sure what it is. However, if we cuddle it hard enough, the
animal will emit a speciXc sound of joy, depending on its con-
crete class.

1 bag = [new Cat(), new Dog()];


2
3 foreach (Animal a : bag)
4 a.makeSound()
5
6 // Meow!
7 // Woof!

The program doesn’t know the concrete type of the object con-
tained inside the a variable; but, thanks to the special mech-
anism called polymorphism, the program can trace down the
subclass of the object whose method is being executed and
run the appropriate behavior.

Polymorphism is the ability of a program to detect the real class


of an object and call its implementation even when its real
type is unknown in the current context.

You can also think of polymorphism as the ability of an object


to “pretend” to be something else, usually a class it extends or
an interface it implements. In our example, the dogs and cats
in the bag were pretending to be generic animals.
20 Introduction to OOP / Relations Between Objects

Relations Between Objects


In addition to inheritance and implementation that we’ve
already seen, there are other types of relations between
objects that we haven’t talked about yet.

UML Association. Professor communicates with students.

Association is a type of relationship in which one object uses or


interacts with another. In UML diagrams the association rela-
tionship is shown by a simple arrow drawn from an object and
pointing to the object it uses. By the way, having a bi-direc-
tional association is a completely normal thing. In this case,
the arrow has a point at each end.

In general, you use an association to represent something like


a Xeld in a class. The link is always there, in that you can
always ask an order for its customer. It need not actually be a
Xeld, if you are modeling from a more interface perspective, it
can just indicate the presence of a method that will return the
order’s customer.
21 Introduction to OOP / Relations Between Objects

UML Dependency. Professor depends on salary.

Dependency is a weaker variant of association that usually


implies that there’s no permanent link between objects.
Dependency typically (but not always) implies that an object
accepts another object as a method parameter, instantiates, or
uses another object. Here’s how you can spot a dependency
between classes: a dependency exists between two classes if
changes to the deXnition of one class result in modiXcations
in another class.

UML Composition. University consists of departments.

Composition is a “whole-part” relationship between two


objects, one of which is composed of one or more instances of
the other. The distinction between this relation and others is
that the component can only exist as a part of the container.
In UML the composition relationship is shown by a line with
a Xlled diamond at the container end and an arrow at the end
pointing toward the component.
22 Introduction to OOP / Relations Between Objects

While we talk about relations between objects, keep in


mind that UML represents relations between classes. It
means that a university object might consist of multiple
departments even though you see just one “block” for
each entity in the diagram. UML notation can represent
quantities on both sides of relationships, but it’s okay to
omit them if the quantities are clear from the context.

UML Aggregation. Department contains professors.

Aggregation is a less strict variant of composition, where one


object merely contains a reference to another. The contain-
er doesn’t control the life cycle of the component. The com-
ponent can exist without the container and can be linked to
several containers at the same time. In UML the aggregation
relationship is drawn the same as for composition, but with an
empty diamond at the arrow’s base.
INTRODUCTION
TO PATTERNS
24 Introduction to Design Patterns / What’s a Design Pattern?

What’s a Design Pattern?


Design patterns are typical solutions to commonly occurring
problems in software design. They are like pre-made blue-
prints that you can customize to solve a recurring design prob-
lem in your code.

You can’t just Xnd a pattern and copy it into your program,
the way you can with off-the-shelf functions or libraries. The
pattern is not a speciXc piece of code, but a general concept
for solving a particular problem. You can follow the pattern
details and implement a solution that suits the realities of your
own program.

Patterns are often confused with algorithms, because both


concepts describe typical solutions to some known problems.
While an algorithm always deXnes a clear set of actions that
can achieve some goal, a pattern is a more high-level descrip-
tion of a solution. The code of the same pattern applied to two
different programs may be different.

An analogy to an algorithm is a cooking recipe: both have clear


steps to achieve a goal. On the other hand, a pattern is more
like a blueprint: you can see what the result and its features
are, but the exact order of implementation is up to you.
25 Introduction to Design Patterns / What’s a Design Pattern?

 What does the pattern consist of?


Most patterns are described very formally so people can repro-
duce them in many contexts. Here are the sections that are
usually present in a pattern description:

• Intent of the pattern brieYy describes both the problem and


the solution.

• Motivation further explains the problem and the solution the


pattern makes possible.

• Structure of classes shows each part of the pattern and how


they are related.
• Code example in one of the popular programming languages
makes it easier to grasp the idea behind the pattern.

Some pattern catalogs list other useful details, such as applic-


ability of the pattern, implementation steps and relations with
other patterns.

 Classi@cation of patterns
Design patterns differ by their complexity, level of detail and
scale of applicability to the entire system being designed. I like
the analogy to road construction: you can make an intersec-
tion safer by either installing some trafXc lights or building an
entire multi-level interchange with underground passages for
pedestrians.
26 Introduction to Design Patterns / What’s a Design Pattern?

The most basic and low-level patterns are often called idioms.
They usually apply only to a single programming language.

The most universal and high-level patterns are architectural


patterns. Developers can implement these patterns in virtual-
ly any language. Unlike other patterns, they can be used to
design the architecture of an entire application.

In addition, all patterns can be categorized by their intent, or


purpose. This book covers three main groups of patterns:

• Creational patterns provide object creation mechanisms that


increase Yexibility and reuse of existing code.

• Structural patterns explain how to assemble objects and class-


es into larger structures, while keeping the structures Yexible
and efXcient.

• Behavioral patterns take care of effective communication and


the assignment of responsibilities between objects.

 Who invented patterns?


That’s a good, but not a very accurate, question. Design pat-
terns aren’t obscure, sophisticated concepts—quite the oppo-
site. Patterns are typical solutions to common problems in
object-oriented design. When a solution gets repeated over
and over in various projects, someone eventually puts a name
27 Introduction to Design Patterns / What’s a Design Pattern?

to it and describes the solution in detail. That’s basically how


a pattern gets discovered.

The concept of patterns was Xrst described by Christopher


Alexander in A Pattern Language: Towns, Buildings, Construc-
tion 1. The book describes a “language” for designing the urban
environment. The units of this language are patterns. They
may describe how high windows should be, how many levels
a building should have, how large green areas in a neighbor-
hood are supposed to be, and so on.

The idea was picked up by four authors: Erich Gamma, John


Vlissides, Ralph Johnson, and Richard Helm. In 1995, they pub-
lished Design Patterns: Elements of Reusable Object-Oriented
Software 2, in which they applied the concept of design pat-
terns to programming. The book featured 23 patterns solving
various problems of object-oriented design and became a best-
seller very quickly. Due to its lengthy name, people started to
call it “the book by the gang of four” which was soon short-
ened to simply “the GOF book”.

Since then, dozens of other object-oriented patterns have been


discovered. The “pattern approach” became very popular in
other programming Xelds, so lots of other patterns now exist
outside of object-oriented design as well.

1. A Pattern Language: Towns, Buildings, Construction:


https://refactoring.guru/pattern-language-book
2. Design Patterns: Elements of Reusable Object-Oriented Software:
https://refactoring.guru/gof-book
28 Introduction to Design Patterns / Why Should I Learn Patterns?

Why Should I Learn Patterns?


The truth is that you might manage to work as a programmer
for many years without knowing about a single pattern. A lot
of people do just that. Even in that case, though, you might be
implementing some patterns without even knowing it. So why
would you spend time learning them?

• Design patterns are a toolkit of tried and tested solutions


to common problems in software design. Even if you never
encounter these problems, knowing patterns is still useful
because it teaches you how to solve all sorts of problems using
principles of object-oriented design.

• Design patterns deXne a common language that you and your


teammates can use to communicate more efXciently. You can
say, “Oh, just use a Singleton for that,” and everyone will
understand the idea behind your suggestion. No need to
explain what a singleton is if you know the pattern and
its name.

You might also like