You are on page 1of 27

Advanced Programming Techniques

Prof. Dr. Phillipp Torkler


Summer Semester 2023

Deggendorf Institute of Technology,


Faculty of Computer Science
Brief Object-Oriented Programming (OOP) Recap

Learning Objectives:
• Overall OOP-concept

• Classes

• Encapsulation and abstraction

• Interfaces, abstract classes and polymorphism


Object-Oriented Programming In A Nutshell

• Object-oriented programs are made up of objects. An object packages data and methods that operate on
that data.
• The difficulty of object-oriented software design is to decompose systems into objects. Factors like
dependency, granularity, reusability and performance influence the software design, often in conflicting and
contradicting ways
• Objects in object-oriented designs often do not have a real world counterpart to make design flexible and
useful for future changes of the software.

Gamma E., Helm R., Johnson R., and Vlissides J., Design Patterns: Elements of Reusable Object-Oriented Software, 1995
Prof. Dr. Phillipp Torkler Advanced Programming Techniques 1
Classes

Class
Defines an object’s interface and implementation. Classes consist of attributes and methods to bundle data and
specifying the object’s internal data, representation and operations the object can perform. A concrete class has
no abstract definitions and can be instantiated.

1 class Student :
2 institue = " DIT "
3
4 def __init__ ( self , sid , firstname ) :
5 self . sid = sid
6 self . firstname = firstname
7
8 def say_hello ( self ) :
9 print ( f " { self . firstname }: I am a student at the { self . institue } and my id is { self . sid }. " )

Objects are created by instantiating a class. It is said that the object is an instance of the class.

Prof. Dr. Phillipp Torkler Advanced Programming Techniques 2


Classes

Class
Defines an object’s interface and implementation. Classes consist of attributes and methods to bundle data and
specifying the object’s internal data, representation and operations the object can perform. A concrete class has
no abstract definitions and can be instantiated.

1 class Student :
2 institue = " DIT " # Class attribute : shared by all objects
3
4 def __init__ ( self , sid , firstname ) :
5 # Instance attributes : unique per object
6 self . sid = sid
7 self . firstname = firstname
8
9 def say_hello ( self ) :
10 print ( f " { self . firstname }: I am a student at the { self . institue } and my id is { self . sid }. " )

Objects are created by instantiating a class. It is said that the object is an instance of the class.

Prof. Dr. Phillipp Torkler Advanced Programming Techniques 2


Classes

Class
Defines an object’s interface and implementation. Classes consist of attributes and methods to bundle data and
specifying the object’s internal data, representation and operations the object can perform. A concrete class has
no abstract definitions and can be instantiated.
1 class Student :
2 institue = " DIT " # Class attribute : shared by all objects
3
4 def __init__ ( self , sid , firstname ) :
5 # Instance attributes : unique per object
6 self . sid = sid
7 self . firstname = firstname
8
9 def say_hello ( self ) :
10 print ( f " { self . firstname }: I am a student at the { self . institue } and my id is { self . sid }. " )

>>> s1 = Student(1, "Peter")


>>> s2 = Student(2, "Bob")
>>> s1.say_hello()
Peter: I am a student at the DIT and my id is 1.
>>> s2.say_hello()
Bob: I am a student at the DIT and my id is 2.
Prof. Dr. Phillipp Torkler Advanced Programming Techniques 3
Encapsulation

Encapsulation
Hiding representations and implementations in an object. Representations are not visible and cannot be modified
directly from outside the object. Only methods are provided to access or modify representations of an object.

1 class Student :
2 def __init__ ( self , sid , firstname ) :
3 self . sid = sid
4 self . firstname = firstname
5 self . _email = " " # ’ private ’ attribute .
6
7 def get_email ( self ) :
8 return self . _email
9
10 def set_email ( self , email ) :
11 if self . verifyEmail ( email ) :
12 self . _email = email
13 # TODO : raise an error if no valid email address is provided
14
15 def verifyEmail ( self , email ) :
16 # TODO : check if a string is a valid email address .
17 return True

Note: a true encapsulation does not exist in Python! By convention, method and attribute names starting with an
underscore are considered being private in Python, but technically they can be accessed and modified.
Prof. Dr. Phillipp Torkler Advanced Programming Techniques 4
Abstraction

Abstraction
The concept of abstraction in computer science is to hide/ignore complex details of a system and focus on the
high-level operation of a system. Complexity is reduced by hiding details.

Prof. Dr. Phillipp Torkler Advanced Programming Techniques 5


Abstraction

Abstraction
The concept of abstraction in computer science is to hide/ignore complex details of a system and focus on the
high-level operation of a system. Complexity is reduced by hiding details.

1 class BankManager :
2 def __init__ ( self ) :
3 self . finance_data = None
4 def _connect ( self ) :
5 print ( " Establish connection to your bank account . " )
6 def _ g e t _ f i n a n c e _ d a t a ( self ) :
7 print ( " Retrieve financial data . " )
8 def _ tr an s fo rm _d a ta ( self ) :
9 print ( " Rearrange financial data into a proper format . " )
10 def _disconnect ( self ) :
11 print ( " Close connection to the bank account . " )
12
13 # Keep all ’ complicated ’ internals private and only expose
14 # desired functions to other objects .
15 def get_finances ( self ) :
16 self . _connect ()
17 self . _ g e t _ f i n a n c e _ d a t a ()
18 self . _t ra n sf or m_ d at a ()
19 self . _disconnect ()
20 return self . finance_data

Prof. Dr. Phillipp Torkler Advanced Programming Techniques 5


Abstraction

Abstraction
The concept of abstraction in computer science is to hide/ignore complex details of a system and focus on the
high-level operation of a system. Complexity is reduced by hiding details.

Benefits of using abstraction and encapsulation:

• By hiding implementation details, the implementation can be changed without a↵ecting other parts of an
application.
• Maintainability is increased since implementation details are kept at a single point and are not scattered
throughout an application.

Prof. Dr. Phillipp Torkler Advanced Programming Techniques 5


Interfaces and Abstract Classes

Signature
A signature defines a method’s name, parameters (and types) and return values.

Interface
An interface is the set of all signatures of an object. An interface describes the set of all requests an object can
respond to.

Type
A type is a name of a particular interface.

Abstract class
An abstract class defines an interface for its subclasses. Abstract classes cannot be instantiated.
Implementations of abstract classes are deferred to subclasses that inherit from the abstract class.

Prof. Dr. Phillipp Torkler Advanced Programming Techniques 6


Interfaces and Abstract Classes

Abstract class
An abstract class defines an interface for its subclasses. Abstract classes cannot be instantiated.
Implementations of abstract classes are deferred to subclasses that inherit from the abstract class.

1 import abc
2
3 class UIControl ( abc . ABC ) :
4 @abc . abs tractme thod
5 def display () :
6 pass
7
8class Button ( UIControl ) :
9 def display ( self ) :
10 print ( f " Display a button . " )
11
12 class CheckBox ( UIControl ) :
13 def display ( self ) :
14 print ( f " Display a checkbox . " )

Prof. Dr. Phillipp Torkler Advanced Programming Techniques 7


Interfaces and Abstract Classes

Abstract class
An abstract class defines an interface for its subclasses. Abstract classes cannot be instantiated.
Implementations of abstract classes are deferred to subclasses that inherit from the abstract class.

Interface
An interface is the set of all (method) signatures of an object. An interface describes the set of all requests an
object can respond to.

1 class Nonsense :
2 pass

>>> issubclass(Button, UIControl)


True
>>> issubclass(CheckBox, UIControl)
True
>>> issubclass(Button, Nonsense)
False
>>> issubclass(CheckBox, Nonsense)
False
Prof. Dr. Phillipp Torkler Advanced Programming Techniques 8
Polymorphism

Polymorphism
”Poly” means ”many” and ”morphism” means shape or form. Objects with matching interfaces can be
substituted at run-time.

Interface
An interface is the set of all (method) signatures of an object. An interface describes the set of all requests an
object can respond to.

1 def displayUI ( element : UIControl ) :


2 element . display ()

>>> displayUI(Button())
Display a button.
>>> displayUI(CheckBox())
Display a checkbox.

Objects of type Button and CheckBox are subclasses of the abstract class UIControl. UIControl can take many
di↵erent forms at run-time. Since an abstract class defines the interface of an object, it is guaranteed that Button
and CheckBox will have an implementation of the display() function.
Prof. Dr. Phillipp Torkler Advanced Programming Techniques 9
Interfaces, Abstract Classes and Polymorphism

Interfaces are fundamental in object-oriented systems:

• Objects are known only through their interface.


• Interfaces do not specify an implementation:
• Objects of di↵erent classes can share an identical interface (Polymorphism).
• Objects that share the same type can only share parts of their interface.

Benefits from using interfaces in programs:

• The ability to define behavior that can be implemented by a group of unrelated classes without forcing them
to share a common class hierarchy.
• A class can be exposed through its interface, e↵ectively hiding its implementation details by forcing all
communication to be through its public interface methods
• Existing systems are easily modified to provide new functionality within their current class hierarchy.

Prof. Dr. Phillipp Torkler Advanced Programming Techniques 10


Program To An Interface, Not An Implementation

All classes derived from an abstract class will share its interface. ”There are two benefits to manipulating objects
in terms of the interface defined by abstract classs:

1. Clients remain unaware of the specific types of objects they use, as long as the objects adhere to the
interface that clients expect.
2. Clients remain unaware of the classes that implement these objects. Clients only know about the abstract
class(es) defining the interfaces.

This reduces implementation dependencies between subsystems that it leads to the following principle of
object-oriented design:

Program to an interface, not an implementation.”1

1 Gamma E., Helm R., Johnson R., and Vlissides J., Design Patterns: Elements of Reusable Object-Oriented Software, 1995

Prof. Dr. Phillipp Torkler Advanced Programming Techniques 11


Design Patterns

Learning Objectives:
• Introduction to design patterns

• Definition

• Motivation

• ”Gang of Four”
Design Patterns: Definitions

Design Patterns
A design pattern systematically names, motivates and explains a general design that addresses a recurring design
problem in object-oriented systems. It describes the problem, the solution, when to apply the solution and the
consequences.

A design pattern should...

• ... solve one or more real problems


• ... serve as best practice
• ... be based on real designs
• ... not be obvious
• ... highlight potential architectural problems
• ... allow for deeper insight in a system

Prof. Dr. Phillipp Torkler Advanced Programming Techniques 12


Design Patterns: Motivation

Why should I have a look at design patterns? Designing OOP software is hard, and designing flexible and reusable
OOP software is even harder. Design patterns...

• ... make software more flexible, modular and reusable.


• ... help to identify less-obvious abstractions.
• ... help to reuse successful designs.
• ... increase the design vocabulary and introduce a common language that eases discussions about designs.
• ... have evolved over long period of time and contain the results of experience developers.

Design patterns are NO algorithms or data structures.

Prof. Dr. Phillipp Torkler Advanced Programming Techniques 13


Reference And Literature

• Frequently and successfully used patterns have been


gathered into a catalog of 23 software patterns for
the first time.
• Authors are also known as ”Gang of Four” (GoF).
• Despite its age, the patterns and the book are still a
primary resource for design patterns and the
described patterns are (still) used throughout
software systems today.
Erich Gamma, Richard Helm, Ralph Johnson, and John
Vlissides ”Design Patterns: Elements of Reusable
Object-Oriented Software” (1995), Addison-Wesley
Longman Publishing

Prof. Dr. Phillipp Torkler Advanced Programming Techniques 14


The 23 GoF Design Patterns

Creational: Structural: Behavioral:


• Abstract Factory • Adapter • Chain of Responsibility
• Builder • Bridge • Command
• Factory Method • Composite • Interpreter
• Prototype • Decorator • Iterator
• Singleton • Facade • Mediator
• Flyweight • Memento
• Proxy • Observer
• State
• Strategy
• Template Method
• Visitor
Note, design patterns should only be applied if necessary! Design patterns o↵er flexibility by adding additional
levels of abstraction or indirection that can complicate an overall design.

Prof. Dr. Phillipp Torkler Advanced Programming Techniques 15


Adapter Pattern
Adapter Pattern

Adapter Pattern
Convert the interface of a class into another interface clients expect. The adapter pattern lets classes work
together that couldn’t otherwise because of incompatible interfaces.

Participants:
• Target
Target • defines the interface that Client uses.
C lient

request() • Client
• works with objects conforming to the Target interface.
• Adaptee
• an existing interface that does not match to the
Adapter
Adaptee Target interface and needs adapting.
adaptee
nonm atching_request()
• Adapter
request()
• adaptes the interface of Adaptee to the Target
interface.

Prof. Dr. Phillipp Torkler Advanced Programming Techniques 16


Adapter Pattern

Adapter Pattern
Convert the interface of a class into another interface clients expect. The adapter pattern lets classes work
together that couldn’t otherwise because of incompatible interfaces.

Applicability:

• Use the adapter pattern when you want to (re)use an existing class, and its interface does not match the one
you need.
• Use the adapter pattern when you want to create a reusable class that cooperates with unrelated or
unforeseen classes, that is, classes that don’t necessarily have compatible interfaces.
• Use the adapter pattern when existing classes cannot be modified or are too complex to modify.

Benefits and Drawbacks:

• Allows a constant way of using objects.


• Middle-layer structure to access legacy code.

Prof. Dr. Phillipp Torkler Advanced Programming Techniques 17


Composite Pattern
Composite Pattern

Composite Pattern
Compose objects into trees to represent part-whole hierarchies. Composite lets clients treat individual objects
and compositions of objects uniformly by using a common interface.

Participants:
• Component:
• specifies the interface for objects that are identical for
Component
C lient simple and complex objects in the composition.
operation() • Composite
• defines behavior for components having children.
• stores child components.
• delegates work to child elements.
Com posite • Leaf
Leaf
• has no children and defines behavior for primitive
operation()
operation() add() objects in the composition.
remove() • typically performs the most work since requests are
delegated to a leaf.
• Client
• stores and manipulates the composition.
Prof. Dr. Phillipp Torkler Advanced Programming Techniques 18
Composite Pattern

Composite Pattern
Compose objects into trees to represent part-whole hierarchies. Composite lets clients treat individual objects
and compositions of objects uniformly by using a common interface.

Applicability:
Use the Composite pattern when:

• you have to implement a tree like structure / part-whole hierarchies.


• to treat simple and complex objects in the tree uniformly.

Benefits and Drawbacks:

• Open-closed-principle. New types can be added to a tree without a↵ecting any previous objects.
• Depending on the elements it might be difficult to find an interface common to all elements.

Related Patterns:

• The Iterator pattern can be used to specify tree traversal.


• The Flyweight pattern can be used to save memory on shared elements.

Prof. Dr. Phillipp Torkler Advanced Programming Techniques 19

You might also like