Вы находитесь на странице: 1из 16

Chapter 1 - Object-Oriented Fundamentals

Object-Oriented Thinking
Understanding when and why using object-oriented languages can be beneficial will
show its real value as projects grow in scale and require changes.

Given a scenario of baking a cake, we can illustrate it in both procedural and


object-oriented programming.

Baking a cake in a procedural way is similar to following a recipe in a cookbook written


as a long series of operations to execute - mix the ingredients together, pour them into a
cake pan, and put it in the oven, and you will have a cake. Procedural programming
might be organized into named functions or subroutines to make the code modular and
maintainable, but the end goal is really just to get from Point A to Point B to complete
some task - a straightforward approach.

Baking a cake in an object-oriented manner is rather than describing the sequence of


steps, objects used in baking will be described, like the pan, the oven, and the mixer, and
what each one can do. Instead of writing a single large program, the object-oriented code
is split apart into several self-contained objects. Almost like several mini programs where
each object contains its own data and logic to describe how it behaves and interacts with
other objects. The idea here is discussing and using these programmed objects similar to
objects in the real world.

4
Both methods of baking the cake will have the same result, but they are differently
approached and organized. Now, neither of these two approaches is better than the other
all of the time. Each has its own advantages and disadvantages that apply to different
situations. One advantage of using an object-oriented approach is code reusability. In
baking a muffin, the functionality to mix and bake things in the mixer and oven already
exists and can be reused. One new object we need to define to make the muffins is a
muffin tray. The cake pan object and the muffin tray have the same use as holding the
batter that goes into the oven, so we can derive the muffin tray object from the cake pan
object. Realize that object-oriented programming is not itself a language.

Object orientation is referred to as a programming paradigm. A set of ideas that’s


supported by many languages. There are other programming paradigms beyond just
procedural and object orientation. Some programming languages that demonstrate other
paradigms such as logic programming from Prolog, or functional programming like
Haskell, each live in their very specialized environment and have their specific usage.

5
For the practical, pragmatic world of creating web applications, mobile apps, desktop
applications, or game development, object-oriented programming languages are being
used. In fact, all of the top high demand languages today are object-oriented. Now, many
of those languages support multiple paradigms. Using object-oriented programming
languages on small and lightweight programs might seem bloated and way beyond the
scope of those projects, and procedural programming may be more practical and efficient.
But as projects grow in scale and require changes, the real value of object orientation will
appear.

Object
The idea behind object-oriented computing is that it makes thinking about and discussing
programming similar to thinking about the real world. An object is anything that has a
name, characteristics, and behaviors or functions. Some objects may have similarities, but
they are not the same. They are separate objects, each with its own existence and identity
that is independent of all other objects.

Every object has characteristics, inherent properties that describe its current state. For
example, a mug can be full, empty, or somewhere in between. Filling one mug with
something does not mean all of the mugs in the world get filled. The current state of this

6
mug being full is independent of this other empty mug because they are separate objects.
Other attributes can be size, color, and shape. Most objects will have multiple attributes.
Some attributes can remain constant, others are likely to change over time. The terms
attributes, properties, characteristics, states, fields, variables are being used
interchangeably. Their meaning may differ slightly depending on the situation and
specific context through language.

Being an object has nothing to do with complexity. It is possible for one object to contain
other objects, either dependent on each other, or can still be independent when separated.

Objects also have behaviors that tell how it functions or does something. A behavior is
specific only to the same kind or family of objects, but cannot be shared or used on other
kinds of objects.

Objects can be referred to any tangible object (mug, pen, etc.) or any intangible object
(bank account, computer files, etc).

In identifying objects in a problem, make sure that they are nouns. It can be things,
people, places, ideas, or concepts. Putting the word “the” in front of a word can help in
identifying objects in a scenario.

Behaviors of objects are simply verbs or action words that describe its function.
Identifying verbs makes a program useful because it demonstrates its behaviors.

But as the name object-oriented implies, when it comes to structuring an object-oriented


program, it focuses on the noun first.

7
Classes
Objects are created from classes. A class is a code-template for creating program objects.
It is a detailed description, the definition, the template of what an object will be, but it
isn’t the object itself.

There are three components that make up a class in object-oriented programming.


1. Name - type, identity
2. Attributes - describes the object; properties; data
3. Behaviors - the things that objects can do; operations

Behaviors when written as code, it is called a method. It is a block of code or procedure


that can be called to perform some actions, and may return a value. Methods are basically
functions with the key difference that methods are defined as part of a class, and can only
access data that is known to that object.

8
Creating objects from a class is called instantiation. Each object that has been created can
have its own name, and attributes that distinguish it from others. Objects created from the
same class will have the same behavior and base attributes, which can be changed during
the lifetime of the object.

To create objects, a class should exist first. Fortunately, most object-oriented languages
come with a collection of predefined classes to start creating objects right away. Basic
useful things like strings, dates, and arrays are often included as provided classes so
programmers don’t have to begin each program by defining the same common classes
over and over again.

These classes are defined and then gathered together into frameworks or libraries. In
Java, the Java Class library contains about 6,000 classes available. The .NET Framework
for C# and VB.Net has even more than Java’s. C++ has the C++ Standard Library, and
Ruby also calls its default library The Standard Library, as does Python.

9
Abstraction
There are four fundamental ideas in object-oriented programming to keep in mind when
creating classes. Abstraction, Polymorphism, Inheritance, and Encapsulation. (APIE).

Abstraction means focusing on the essential qualities of something rather than one
specific example. It is also the idea or concept of an object that is completely separate
from any specific instance. (Generalization)

Encapsulation
The idea of encapsulation is about containing the elements of an object. Not just to keep
them together, but to also protect them. An object’s attributes or data are bundled along
with the methods that operate on that data within the same unit or the same class. One
reason for doing that is to restrict access to some of the object’s components.

10
Why need to restrict?
1. Nothing should be able to reach in and directly change properties in the class.
2. Avoid providing invalid values that may cause the program to crash.
3. Limit actions to minimal changes.

To make necessary changes, a method is set to be accessible from other parts of the
application that can be called to modify class attributes accordingly.

One of the principles of encapsulation is that an object should not make anything about
itself available except what is absolutely necessary for other parts of the application to
work. That is the concept called “black boxing.” The actual implementation of a method
can be unknown to others as long as it provides the necessary output.

One of the main benefits with object orientation is that it allows programmers to more
safely change the way the object works without changing the rest of the application.

Hiding codes does not necessarily be secretive. It is about reducing dependencies


between different parts of the application. The change in one place won’t cause a domino

11
effect and require multiple changes elsewhere. Different languages have different levels
of support for hiding properties and methods. But the general rule is to encapsulate as
much as possible.

Inheritance
Creating a new class may not always be necessary to build it from scratch. If a program
has an existing class that is similar to the requirement, then using inheritance to base the
new class on that existing one is the way to go.

Inheritance bases a new object or class on an existing one. It enables a new class to
receive or inherit the attributes and methods of existing classes using the same
implementation which is a great form of code reuse.

A customer and employee class with the defined attributes and behaviors. Notice that
both have similar attributes and behavior. Applying the abstraction, creating a new class
that will hold those common attributes and behaviors will be better, in that case a Person
class.

12
This Person class will be the base class from which the Customer and Employee class
inherits everything about the Person class. Then each child class can add their additional
attributes and behaviors that will distinguish them as a Customer or an Employee.

The term superclass refers to the originating, base, or parent class, and subclass refers to
the derived or child class.

13
If another type of person is needed, it can inherit everything from the Person class, and
add its own attributes and behaviors to identify itself as a new class.

If a new attribute is needed to be added on the base class, that attribute will automatically
be inherited by its children classes without doing code changes on each of the child
classes. Changing code in one place is much easier than having to change in three.

14
A few languages like Python and C++ allow inheritance from more than one superclass.
Bringing in attributes and behaviors from multiple other classes. However, multiple
inheritance can get confusing so it’s much more common to see single inheritance where
a subclass only inherits from one parent or superclass. Languages like Java, C#, Swift,
and Ruby enforce single inheritance with classes. Single inheritance is the focus of this
course.

Polymorphism
Polymorphism simply means having many forms. There are multiple forms of
polymorphism.
1. Dynamic (or run-time) Polymorphism - allows access to methods using the same
interface on different types of objects that may implement those methods in
different ways. Take the example of a basic coffee maker as a class with a method
to brew a coffee. That method accepts ground coffee beans and water as its input
parameters. The user waits a bit for it to brew and the output is a fresh cup of
coffee. On the other hand, another type of coffee maker, a French press, also has a
brew method with the exact same input and output like the basic coffee maker.
However brewing coffee is different in both classes. The basic coffee maker uses
a filter, while the French press strains the coffee with a metal strainer/plunger.

15
Implementing dynamic polymorphism can vary. One example is in the photo
below where French press inherits everything from the basic coffee maker but
then overrides the brew() method with its own implementation.

2. Static or compile-time polymorphism - uses a feature called method overloading


which allows programmers to implement multiple methods within a class that
have the same name, but different set of input parameters. Going back to the
brew() method of the French press which originally accepts coffee and water as
its input, we can implement another brew() method that accepts tea leaves and
water as its input parameters that will output a cup of tea.

16
Analysis, design, and programming
In object orientation, these three words are needed for developing a working solution.
These are all connected and refer to the idea that develop any piece of software.
● Analysis - Understand your problem
● Design - Plan your solution
● Programming - Build it

Although listed as two separate steps, analysis and design are usually talked about
together because they encompass everything that should happen before you write a single
line of code.
● Analysis - answers the question “What do you need to do?”, “What’s the problem
to solve?”
● Design - “How are you going to do it?”

Analysis and design are the entire process used to produce the conceptual design that
developers can take and use to build a solution. Conceptual is the key word, meaning
writing codes is out of place, but methods like drawing diagrams, whiteboard sketches, or
written descriptions, or combination of any of it will be used.

The general idea of the analysis and design methodologies are the following:
1. Gather requirements. Figure out what our application needs to do. Flesh out the
problem to be solved.
2. Describe the application. Build a narrative in plain, conversational language for
how people will use it.
3. Identify the main objects. Identify the most important objects, which is the
starting point for identifying actual classes.

17
4. Describe the interactions. After identifying the objects, formally describe the
interaction between them, understanding each other’s responsibilities, the
behaviors they need to have, and when they interact with other objects.
5. Create a class diagram. This will serve as the main output from the five-step
process. The class diagram is a visual representation of the classes in the
application, and creating it is where the object oriented principles like inheritance
and polymorphism really come into play.

Unified Modeling Language (UML)


Unified Modeling Language (UML) is not a programming language, but a graphical
notation for drawing diagrams to visualize object-oriented systems. Some of it will be the
focus of this course.
1. Class diagram - a simple graphical representation of a class. It has three sections;
the name of the class, its attributes or fields, and its behaviors or methods. It
allows developers to quickly sketch out an idea that’s readable and understandable
regardless of which programming language to be used. It is a type of structural
diagram.
2. Use case diagram - portray a user’s interaction with the program. A type of
behavioral diagram.

UML is not the goal in this course and knowing more UML will not necessarily make a
better object-oriented developer. In fact, knowing a little UML may actually be more
useful than knowing a lot of UML because knowing a lot of UML can lead to an over
emphasis on the diagrams themselves. These diagrams should be a quick, useful
communication tool. A support system for your brain.

With that said as a project matures and grows in size, it can be useful to capture those
UML diagrams in an electronic format to facilitate sharing amongst team members.

18
Things to consider for selecting UML Tools:
● Commercial or open source
● Support platforms
● Diagram drawing capabilities
● Code generation capabilities

Best reference for UML Tools comparison: Wikipedia page List of Unified Modeling
Language tools
Diving deeper into UML: UML Distilled by Martin Fowler.

19

Вам также может понравиться