Lecture-Design Pattern

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 114

Software Design Pattern

Lecture 1:
Basic object-oriented
development and design
pattern concepts
Basic object-oriented development(OOD)

OOD is concerned on object-oriented software model which will be reusable


and pluggable along with that it reduce development time. Definitely it meet end
user requirements.
In the phase software design, software decomposition is happened by object-
oriented concept by avoiding the procedural or functional development
approach.
In a conclusion,

▪ This approach reduce time and cost


▪ OOD is creates reusable development module
▪ Easily Pluggable to another software or modules
▪ Highly testable and Maintainable
▪ Provide a competitive advantage to organizations that use it.
Object Oriented Development
What is Object ?
Object-oriented development is a partial-lifecycle software development method in which
the decomposition of a system is based upon the concept of an object. This method is
fundamentally different from traditional functional approaches to design and serves to help
manage the complexity of massive software-intensive systems.
Explore CAR Object
Explore Vehicle Object
The concept of an object is central to object-oriented development and so the
properties of an object are discussed. The mapping of object-oriented techniques
to Ada using a design case study is considered.
Explore Principals
The four main principles of object-oriented programming (abstraction, inheritance, encapsulation,
and polymorphism). The core principle is abstraction. Without it, the others couldn't exist.
Object-oriented Programming Principle
Object design is comprised of 3 parts

Only learning the programming aspect makes


confused about :
• What good design looked like ?
• How to turn requirements into objects? and
• When and why to use concepts like
abstraction, encapsulation, inheritance, and
polymorphism?
After knowing when and why to use them was
unclear to me.
Object-oriented development Process
Explanation of steps
1 Define the use case diagram :
Identifies the actors and the major events initiated by the
actors. Define use
Draw Use case diagram to show actors related event relate case
using UML
2 Activity Diagrams and Sequence Diagram:
Draw Activity Diagrams, which illustrate all the major
Develop Draw Activity
activities in the use case. and Diagrams &
After that sequence diagrams is drawn showing the document Sequence
activities and their related information. the system Diagram
Analyst will create one or more sequence diagrams for each
use case.
3 Develop class diagrams:
The nouns in the use cases are objects that can potentially
be grouped into classes.

Develop
4 Draw state chart diagrams: Systems
class
The class diagrams are used to draw state chart diagrams, design
which help in understanding complex processes that diagrams
cannot be fully derived by the sequence diagrams.
5 Systems design: Draw state
Systems design means modifying the existing system and chart
that implies modifying the diagrams drawn in the previous diagrams
phase. These diagrams can be used to derive classes, their
attributes, and methods. The analyst will need to write
class specifications for each class including the attributes,
methods, and their descriptions.
6 Develop and document the system:
UML is, of course, a modeling language. An analyst may
create wonderful models, but if the system isn’t developed
there is not much point in building models.
Example : Vehicle Rental System
A Car Rental System is an online booking system tailored to the demands of car rental firms, travel agencies,
and companies. It provides a full-featured booking system which allows consumers to check vehicle availability
and make online reservations directly from the website.
Step 1 : Define the use case diagram
Use cases represent high-level functionalities and how a user will
handle the system.

Use-case diagram notations:


A use case represents a distinct functionality of a system, a component, Use
a package, or a class. It is denoted by an oval shape with the name of a case
name
use case written inside the oval shape.

An actor is an entity that initiates the use case from outside the scope of
a use case. It can be any element that can trigger an interaction with the
use case. One actor can be associated with multiple use cases in the system.

Following rules must be followed while drawing use-case for any system:

▪ The name of an actor or a use case must be meaningful and relevant to


the system.
▪ Interaction of an actor with the use case must be defined clearly and in an
understandable way.
▪ Annotations must be used wherever they are required.
▪ If a use case or an actor has multiple relationships, then only significant
interactions must be displayed.
Step 1 : Define the use case diagram
Step 2.A: Activity diagram

Activity diagram is basically a flowchart to represent the flow from one activity to another
activity. The activity can be described as an operation of the system. Activity is a particular
operation of the system. Activity diagrams are not only used for visualizing the dynamic nature
of a system, but they are also used to construct the executable system.

The purpose of an activity diagram can be described as −

▪ Draw the activity flow of a system.


▪ Describe the sequence from one activity to another.
▪ Describe the parallel, branched and concurrent flow of the system.
Step 2.A: Activity diagram
The activity diagram describes how the client chooses a car, what is required from the client, and when the car
is rented and returned to the company. The diagram depicts when the payment is deducted from the client's
card and what happens when the car is returned damaged.If the driver's license is not valid, or the credit card
payment is not successful, the rental system refuses to provide the car for a rental.

Three UML swimlanes:


Customer - represents a client who
wants to rent a car.

CABApps - represents an information


system of a car rental company.

Server- represents a car rental


representative who offers cars for
rent.
Step 2.B: Sequence diagram Car rental system
Sequence diagrams, commonly used by developers, model the interactions between objects in a single use
case. They illustrate how the different parts of a system interact with each other to carry out a function, and
the order in which the interactions occur when a particular use case is executed. The sequence diagram
below shows how the objects in the system interact with each other to perform the function .
3. Draw Class diagrams:
Class diagram represents the static view of an application. Class diagram is not only used for
visualizing, describing, and documenting different aspects of a system but also for constructing
executable code of the software application. The purpose of the class diagram can be summarized as:
▪ Analysis and design of the static view of an application.
▪ Describe responsibilities of a system.
▪ Base for component and deployment diagrams.
▪ Forward and reverse engineering.
4. Draw state chart diagrams:
Define different states of an object during its lifetime and these states are changed by events. Statechart
diagrams are useful to model the reactive systems. Reactive systems can be defined as a system that
responds to external or internal events. Following are the main purposes of using Statechart diagrams −
▪ To model the dynamic aspect of a system.
▪ To model the lifetime of a reactive system.
▪ To describe different states of an object during its lifetime.
▪ Define a state machine to model the states of an object.
Expected Benefits of OOD

• Faster Development: OOD has long been touted as leading to faster development. Many of
the claims of potentially reduced development time are correct in principle, if a bit overstated.
• Reuse of Previous work: This is the benefit cited most commonly in literature, particularly in
business periodicals. OOD produces software modules that can be plugged into one another,
which allows creation of new programs. However, such reuse does not come easily. It takes
planning and investment.
• Increased Quality: Increases in quality are largely a by-product of this program reuse. If 90% of
a new application consists of proven, existing components, then only the remaining 10% of the
code has to be tested from scratch. That observation implies an order-of-magnitude reduction
in defects.
• Modular Architecture: Object-oriented systems have a natural structure for modular design:
objects, subsystems, framework, and so on. Thus, OOD systems are easier to modify. OOD
systems can be altered in fundamental ways without ever breaking up since changes are
neatly encapsulated. However, nothing in OOD guarantees or requires that the code
produced will be modular. The same level of care in design and implementation is required to
produce a modular structure in OOD, as it is for any form of software development.
• Client/Server Applications: By their very nature, client/server applications involve transmission
of messages back and forth over a network, and the object-message paradigm of OOD
meshes well with the physical and conceptual architecture of client/server applications.
• Better Mapping to the Problem Domain: This is a clear winner for OOD, particularly when the
project maps to the real world. Whether objects represent customers, machinery, banks,
sensors or pieces of paper, they can provide a clean, self-contained implication which fits
naturally into human thought processes.
Lecture 2:
Elements of design pattern,
Description of a design
pattern
What Is A Design Pattern?

In software engineering, design pattern is a description or template for how to solve a problem
that can be used in many different situations .A design pattern isn't a finished design that can be
transformed directly into code. Repeatable solutions of commonly occurring problem in software
design.

• Patterns allow developers to communicate using well-known, well understood names for
software interactions.

• Common design patterns can be improved over time, making them more robust than ad-hoc
designs.

• Patterns provide common design vocabulary, improve communication, ease implementation &
documentation

• A standard solution to a common programming problem


• A technique for making code more flexible

• Not a finished design that can be transformed directly into code.


Design Pattern
In software engineering, design pattern is a Repeatable solutions of commonly occurring problem
in software design. Description or template for how to solve a problem that can be used in many
different situations .A design pattern isn't a finished design that can be transformed directly into
code. Or Simply

Why is it used ?

▪ A standard solution to a common programming problem


▪ A technique for making code more flexible
▪ Not a finished design that can be transformed directly into code.

▪ Patterns allow developers to communicate using well-known, well understood names for
software interactions.

▪ Common design patterns can be improved over time, making them more robust than ad-
hoc designs.

▪ Patterns provide common design vocabulary, improve communication, ease implementation


& documentation
Essential Elements of Design Pattern
Each design pattern has four essential elements in general:
▪ Pattern name: The handle we can use to describe a design problem,
its solutions, and consequences in a word or two.
▪ Problem: The situations when we should apply the pattern.
▪ Solution: The ins and outs of the design including its elements, their relationships,
responsibilities, and collaborations.
▪ Consequences: The results and trade-offs of applying the pattern.
Benefits of Using Design Patterns

▪ With carefully tested and proven development paradigms, design patterns can help speed
up your software development process. Instead of tearing your hair out trying to come up
with a suitable design by yourself, just find a design pattern that matches your
requirements and apply it.
▪ Reusing design patterns helps to prevent subtle issues that can cause major problems and
improves code readability for coders and architects familiar with the patterns.
▪ Design patterns provide general solutions, documented in a format that doesn't require
specifics tied to a particular problem.
▪ Design patterns allow ease of communication between software developers.
History and evolution of design Patterns

The four authors of the book famously know as


Gang of four are the ones who brought the
concepts of design patterns in their book
“Elements of reusable Object-Oriented
software” .

Gang of Four has divided the book into two parts


with first part explaining about the pros and cons
of object-oriented programming and the second
part describes the evolution of 23 classic
software design patterns into three main
categories: Creational Patterns, Structural
Patterns, and Behavioral Patterns.
Basic kinds of design patterns:

• Structural patterns generally deal with relationships between entities, making it easier
for these entities to work together. If you want to form larger structures from different
classes and objects as well as provide new functionalities to them, structures design
patterns are all that you need.

• Creational patterns provide instantiation mechanisms, making it easier to create


objects in a way that suits the situation. As a developer, we spend most of our time on
creating classes and objects. Those patterns below can be used to get the job done
effectively.

• Behavioral patterns are used in communications between entities and make it easier
and more flexible for these entities to communicate. Behavioral design patterns really
come into play if you want to deal with communication between objects.
Creational Patterns

• Problem: Constructors in programming language are not flexible


o Always return a fresh new object, never reuse one
o Can’t return a subtype of the class they belong to
• Solution: Creational patterns!
STRUCTURAL PATTERNS
BEHAVIORAL PATTERNS
Creational Patterns: Sharing

• The old way: Constructors always create a new object


• Singleton: only one object exists at runtime
• Interning: only one object with a particular (abstract) value exists at
runtime
• Flyweight: separate intrinsic and extrinsic state, represents them
separately, and interns the intrinsic state
Case Study : OOD
▪ Analysis of OOD analysis
▪ UML Diagram : Use case , Sequence , Activity and Class Diagram
Lecture 3
Designing for change, Code
smells and Refactoring
Code smells
Code smell is not a bug, but it is a
sign of bad construction of program.

Code smell is language and


application-independent; this means
we can have code smell in any
language and any application.

Code smells does not certainly mean


that the software won’t work, it would
still give an output, but it may slow
down processing, increased risk of
failure and errors while making the
program vulnerable to bugs in the
future.
Refactoring to Avoid Code Smells
Refactor means to restructure the source code (of program/software) so that it can
improve the structure or performance of the software without altering existing
functionalities. Developers usually make micro changes to clean up the code.
What are objectives of refactoring?
▪ Refactoring improves or standardized the design of software,
▪ Makes the source code easily understandable,
▪ Helps to find out bugs or performance bottle necks
▪ Better performance of software
Code smells
Code smell differs from project to project and developer to developer, according to the
design standards that have been set by an organization. For higher code quality, we have
jotted down common types of smells as a cheat sheet so you can identify and classify
them easily.

Application-Level Smells
Mysterious Naming Perhaps the most common refactoring's Change Function
Declaration (124) (to rename a function), Rename Variable (137),
and Rename Field,(244). People are often afraid to rename things,
thinking it’s not worth the trouble, but
a good name can save hours in the future
Duplicate Code Similar code in more than one location, Duplication means that
every time you read these copies, you need to read them carefully
to see if there’s any difference.
Shotgun Surgery Avoid Making any modifications requires that you make many
small changes to many different classes.
Code smells
Class Level Smells
Large Class Class trying to do too much and has too many instance variables

Freeloader Class doing too little

Feature Envy Class with a method that seems more interested in other class than the one
it is in
Divergent Code A class that suffers many kinds of changes to bring a change in a system

Data Clump Bunches of data that clump together in lots of places

Inappropriate Intimacy A class that has dependencies on implementation details of other class

Middle Man Class with lots of methods delegated to other class

Downcasting Typecast that breaks the abstraction model

Parallel Inheritance Every time you make a subclass for a single class, you are needed to make
Hierarchy subclass for others

Refused Bequest Subclass not using methods and data of superclass


Cyclomatic Complexity Class with too many branches and loops
Code smells

Method Level Smells


Long Method Long procedures that are hard to understand

Speculative Generality Methods whose only users are test cases

Message Chains Method calling a different method which calls a different method which
calls a different method… and on and on
Too Many Parameters A very long list of parameters

Oddball Solutions When multiple methods are used to solve the same problem in one
program creating inconsistency
God Line An excessively long line of code

Excessive Returner A method that returns more data than what its caller needs

Identifier Size The identifier is excessively short or long


How to get rid of code smell?
• Once all types of smells are known, the process of code review begins. Two or more developers
may use the primary method, the ad-hoc code review process to try and identify such smells
manually. Many smells are not possible to be found by manual reviewing and automated code
review tools are used for identifying such bad smells.
• Code smells knowing or unknowingly are introduced in the source code, and may also form if
you are solving other smells. Developers discard most of the smells consciously because they
seem to have a marginalized effect or are just too hard to explain.
• When developers find a smelly code, the next step they do is refactoring. Refactoring is the
process of changing a software system in such a way that it does not alter the external behavior
of the software yet improves its internal structure. It may be the single most important technical
factor in achieving agility.
• The goal is to stay within reasonable operating limits with limited continual damage. By staying
within these limits, you keep costs low, because costs relate nonlinearly to the amount of repair
necessary. Refactoring is a process in which the code is divided into smaller sections according
to the identified smells
• A decision is then made to either remove them or replace them with a better series of code that
may increase code quality and enhance some nonfunctional quality – simplicity, flexibility,
understandability, performance. After refactoring, run tests to ensure things still work correctly.
Sometimes this process has to be repeated until the smell is gone.
Automated Code Review tools

Identifying and removing code smells, as seen above, is a tiresome and indefinite
process with no particular result if the software would be smell free or not. Also, as it’s near
impossible to find and remove all smells manually, using automated code review tools that
can identify smells becomes a necessity. Many code review tools help in such operations,
but most of them are either dedicated to one programming language or are not decisive
enough. CodeGrip is one such tool that is focused on improving code quality, having a
feature to identify and display code smells within minutes.

CodeGrip analyses your repositories from Github, BitBucket, and other platforms and
displays the number of code Smells under the maintainability tab also displaying technical
debt to remove these smells. CodeGrip’s state of the art, suggestive engine helps you
classify and resolve code smells easy and individually one at a time. It also organizes each
code smell based on severity and time to resolve, so that developers can schedule and
solve these issues easily while suggesting a solution as well. CodeGrip makes removing
code smells easier than ever, increasing efficiency and decreasing workload.
Eliminating code smells with refactoring
Code refactoring is one of the most effective ways to eliminate code smells and maintain good
code. Refactoring is a restructuring process that attempts to make code cleaner, more concise and
more efficient without altering its core functionality. Refactoring helps ensure that code meets a
team's guidelines (Architecture/design guideline, Coding concentration etc. ) and aligns with a
defined architecture.
Refactoring is a process of improving your codebase without creating new functionality. It helps
you clean up your code and simplify design.
”Refactoring is the process of changing a software system in such a way that it does not alter the external
behavior of the code yet improves its internal structure. It is a disciplined way to clean up code that
minimizes the chances of introducing bugs. In essence when you refactor you are improving the design of
the code after it has been written.” - Martin Fowler

When to do it ?
It is good practice to clean up existing code before programmers add any new code. Another good
time to refactor code is after a team has deployed code into production.Then developers would
have more time to clean up code before they're assigned a new task or a project. Make sure there
is complete test coverage before refactoring an application's code. Otherwise, refactoring process
may work on incomplete application code for no gain.
Lecture 4
Designing for change, Code
smells and Refactoring
When to Refactoring?
When adding features:
The best time for refactoring is before adding new features or updates to existing code.
Doing so can help improve the product's quality. By cleaning the code base before adding
new features or updates, it helps to make the product more robust and easier to use in the
future.
Rule of Three:
✓ 1. When you doing something for the first time just get it done.
✓ 2. The second time around, you may be a bit faster, but the code still won't be as clean
as it should be.
✓ 3. When you do something for the third time, start refactoring.

During a code review:


This is the last chance to clean up the code before the product is launched. Doing so can
help you identify areas of the code that are worth fixing.
It's also a good time to start refactoring after the product has been launched. Since many
developers start working on code refactoring after the product has been released, it allows
them to get more work done before going on to the next project.
Aspects of the code is refactoring aimed
▪ Unused code - unused variables or methods that are in the code base

▪ Duplicates - identical functions or variables. And there can also be identical methods in
objects but described in each of them separately.

▪ Functions and variables with unclear names

▪ An excessive amount of text in one method

▪ A superfluous amount of comments

▪ Incorrectly formatted code fragments - functions and loops not written correctly, extra
spaces from the beginning of a line, etc.
Refactoring Techniques
Refactoring encompasses a number of specific code hygiene practices.
When it comes to eliminating code smells, however, there are three
particularly effective techniques:
▪ Composing methods : Focuses on methods,
▪ Simplifying method calls : Focuses on the method calls and
▪ Refactoring by abstraction: Focuses on classes.

Composing methods :
Writing a long methods that are very hard to change. This technique is
mainly used in cases where the code is extremely hard to understand.

1. Extraction breaks down the code into smaller chunks to find and Extraction
extract fragments. It then moves the fragments to a new method
and calls it. The fragments are then moved to a new method and
replaced with new content.

2. Inline refactoring is a technique that aims to reduce the number of


methods .Broken or unnecessary methods are identified, as well as
the calls to those methods. The method calls are replaced by the
method's actual code, and the original method is deleted into a
separate method.
Refactoring Technique
Simplifying method calls:
Over time, large amount of unwanted code has generated which makes scared and confused. Beside
that logic simplification opportunities has come out. It can also involve removing or replacing old
methods and clauses.
This approach simplifies the interface between classes and method calls. For example, we can
introduce new parameterizations, remove method calls, and preserve the whole object. There are
many ways to simplify the logic of conditional statements. Some of these include consolidating
conditional expressions, replacing conditional fragments, and so on.

Refactoring by abstraction
Finally, refactoring by abstraction comes into play when large chunks of code contain duplications
or redundancies. There are two techniques that constitute this approach, both of which focus on
class inheritance:
1. Pull up: It pulls code parts into a superclass and helps in the elimination of code duplication.
2. Push down. Method code that lives within a superclass but is only used by a few of the
subclasses is pushed down to those respective subclasses.
Refactoring Technique: Refactoring by Abstraction
The IsLogMessageValid method
returns true if the log message is not
considered valid if it contains a null or
empty string.
• The log message is considered invalid
if it contains any sensitive data, such
as a Social Security or credit card
number.Unfortunately, this approach
is a little redundant.
• Programmers would need to write
the same logic twice -- one for each
of the two classes -- to check if the
log messages are valid. A better way
is to refactor these two classes and
create an abstract class.
In the code segment below, notice how
the IsLogMessageValid method has
moved to an abstract class, which helps
mitigate potential code redundancy.
WHY SHOULD WE REFACTOR?
▪ Functions and variables with unclear names
▪ An excessive amount of text in one method
▪ A superfluous amount of comments
▪ Incorrectly formatted code fragments - functions and loops not written correctly,
extra spaces from the beginning of a line, etc.
▪ Refactoring Improves the Design of Software:
Without refactoring, the internal design—the architecture—of software tends to decay.
As people change code to achieve short-term goals, often without a full understanding
of the architecture, the code loses its structure. It’s quite imposable to review the design
looking on the code also harder to prevent. Loss of the structure of code has a
cumulative effect. Regular refactoring helps keep the code in shape and an important
aspect of improving design is to eliminate duplicated code. It’s not that reducing the
amount of code will make the system run any faster. Make a big difference in
modification of the code. The more code there is, the harder it is to modify correctly and
time consuming.
WHY SHOULD WE REFACTOR?
▪ Refactoring helps to find Bugs :
After Refactoring one can get clear understanding what the code does, and easy to put
that new understanding right back into the code. By clarifying the structure of the
program, one can clarify certain assumptions Also he can’t avoid spotting the bugs.
Refactoring helps much more effective at writing robust code.
▪ Refactoring Helps for Program Faster:
Refactoring helps to develop code more quickly. Because of sounds counterintuitive
code. It improves quality. Better internal design, readability, reducing bugs—all these
improve quality. Every new feature requires more and more time to understand how to
fit it into the existing code base, and once it’s added. Software with a good internal
design allows me to easily find how and where I need to make changes to add a new
feature.
▪ Refactoring Makes Software Easier to Understand:
When change come developer need to understand the code written by different people.
Refactoring helps me make the code more readable. Before refactoring, code that works
but is not ideally structured. A little time spent on refactoring can make the code better
communicable and clearly to understand .
Case Study : Code Smells
Fixing and Avoiding the Message Chain Code Smell
Message chain consist of a chain of method calling which creates code smells.

Write down few lines of source code as an example (in any preferred OO
programming language) as an example and explain and analyze, why to avoid ?
Lecture 5
Designing for change, Code
smells and Refactoring
Refactoring legacy code
The goal of refactoring legacy code is to make it easier to understand and work with. It
aims to improve the structure of the code by reducing redundant or erroneous entries.
One of the main advantages of refactoring in legacy code is that it can be done on any
software architecture. It allows developers to focus on improving the quality of the code
without the need for unnecessary downtime.
Project is dealing with legacy PHP core functionalities; it is important to identify how well-
documented and operationally robust the software is.
Refactoring legacy code
There are plenty of tooling options available to automate the code refactoring process,
including SonarQube, Visual Studio IntelliCode, Rider and Eclipse IDE. Many of these tools
enable programmers to execute code restructuring alongside the actual development
process, which can help teams speed up release cadences when needed.

Splitting the Choose Refactoring legacy


An audit is also monolith code into Before you start architecture. The software is an
an integral part focused classes, thinking about right software excellent strategy
of any project test, and release the architecture architecture can for businesses that
that's dealing the code after the of the project, play a huge role want to keep their
with legacy refactoring. it's essential to in the success of existing applications
code. It can help Splitting code is a consider the the project. It running smoothly. It
identify technique that various aspects can help can help improve
potential issues helps developers of the software, determine the the efficiency of
and gain focus on the such as its various factors their processes,
viability into the modules that are scalability and that might affect increase their
existing code. important to the component the productivity, and
development of interactions. implementation provide them with a
their projects.. of your competitive
software. advantage.
The role of testers in refactoring
▪ It’s required to ensure that code is testable before refactoring begins. This includes
unit tests, regression tests and integration tests.
▪ Involve the testing team throughout the refactoring process, as tests might fail once
development teams start to change the code.
▪ It's also valuable for testers to learn about the code restructuring process, since it
can help them improve existing test cases and procedures.
▪ This may even help them write better test automation code and cut down on manual
maintenance tasks..
▪ Regression testing is particularly important in refactoring, as it ensures that the
application's functionality remains intact
▪ Refactoring should be a recurring activity, and it's a collaborative effort.
▪ By regularly performing code hygiene tasks together, software teams can create
centralized strategies to identify code smells and learn from mistakes.
Best Practices for code refactoring
Understand the code
Before you start refactoring the code, it's important to thoroughly review the source code to ensure that
you understand the various components of the application. Having a sequence diagram will help you
understand the various steps in the code.
Set defined objectives
Before beginning the code refactoring process, it's also important to set goals and schedule specific tasks
that align with the current workflow. These goals should also be well-defined and not dependent on other
tasks. This will help avoid delays.
Time planning
One of the most challenging parts of code refactoring is choosing the time to finish it. You should then
determine the exact steps that will allow you to complete the project within a reasonable timeframe.
Although cleaning up the code is very time-consuming, it's also beneficial to refactor once you're
convinced that the code can be made more efficient and maintainable. Doing so will help avoid accruing
more technical debt in the future.
Always test
Although code refactoring doesn't alter the functionality of the program, it still requires testing to ensure
that the new code doesn't introduce new bugs. The testing stages are critical during the code refactoring
process. Doing so helps avoid making changes to the code and inadvertently affecting the product's
functionality.
It's also a good idea to involve your testers and QA in the code refactoring process.
Automated Tools for Refactoring
It's also essential to use tools that can help speed up the code refactoring process and
minimize the chances of issues that can get overlooked. Modern tools also help ensure that
the code is consistent and accurate. For example:

▪ Visual studio intellicode


▪ Eclipse IDE
▪ Spring Tool Suite 4
▪ Rider
▪ IntelliJ IDEA

▪ It's a discipline that helps keep the code running smoothly and without introducing
bugs. Another benefit of refactoring is that it allows the developers to focus on the
details that will drive the implementation of the solution instead of just the code itself.

▪ With the proper refactoring techniques, you can get rid of outdated software
applications and improve their overall functionality without compromising their current
state.
Case Study : Code Refactoring
Fixing and Avoiding the Message Chain Code
View the below example :

person.GetBirthDate(20128, 5).GenerateReport().ConvertToSpreadsheet().Print();

▪ How can we avoid Message Chains Code smell using refactoring ?


▪ Explain and analyze below point:

✓ Complexity level is high


✓ Methods become tightly Coupled
✓ Difficult to test individual methods for testability
✓ Reduce the code robustness
Lecture 6
Designing for change, Code
smells and Refactoring
Case Study : Code Smells

What to Do if You Discover a Code Smell


Case Study : Code Smells

What to Do if You Discover a Code Smell like “Shotgun Surgery ” ?


Lecture 7
Understanding the design
pattern catalog
Design Patterns
A design pattern in the context of software engineering is a template or reusable solution
to common problems occurring in software design. This is usually represented with the
classes and objects, interfaces, etc. The one application of a design pattern is “Reusability
of Solutions”, By using the proven solution, users can solve software development issues
that enable the development of highly cohesive modules with coupling.

Gang of Four ( Gamma, Helm, Jonson, and Vlissides are commonly known GOF) noticed
some design problems and solutions are always very common in a specific context.Key
objectives are using design pattern are :
Need of Design pattern
▪ Enables efficient communication between designers.
▪ Solves an issue just by referring to pattern name.
▪ Improves code readability for coders.
▪ Reduce the time to find the solution by reusing tested and proven development
paradigms.
▪ Reduce the time for coders.
▪ Introduces additional levels of indirection to achieve flexibility.
▪ Reduce the time for understanding the design.
▪ Avoid those alternatives which avoid reusability thereby reducing variations.
▪ Improves design understandability and documentation.
▪ Helps to understand the basics of object-oriented design more easily and quickly.
Essential Element of Design Pattern:
There are four essential elements of a design pattern. They are as follows:
• Pattern Name: It is a unique name that describes a design problem. Pattern name being concise
and meaningful, Improves communication, among developers and helps to design patterns at
higher levels of abstraction.
• Problem: It states the problem and its context such as how to represent the algorithm as
objects (It ensure when the pattern is applicable and what condition should be met before the
pattern is used.
• Solution: It provides a Description of elements that make the design pattern such as their
responsibility, relationship, and collaboration). Pattern solutions cant describe a particular
implementation because patterns are like templates that are applicable to several similar
situations. The solution gives a generic arrangement of classes and objects to solve a problem.
• Consequences: As the name implies these highlight the result, pros and cons of applying the
patterns, etc,(It Describes the impacts on the system’s portability, extensibility. They determine
the costs and evaluate design alternatives of pattern, language, and implementation issues.
Organization of design patterns

Design pattern can be categorized in three main categories.


The Catalog of Design Patterns:
The Design Patterns are organized into a form of a catalog. These Design Patterns collectively assist
in software engineering by finding objects, specifying objects implementations, objects interfaces,
determining objects granularity, implementing reuse mechanisms, etc. The Intents specify what the
design pattern does. Some of the patterns with their names and intents are as follows,

Abstract Factory: It Indicates what factory is to be instantiated, provides an interface to create


families of objects(related / dependent) without any specification of their concrete classes.

Adaptor: Id Adapt or converts an interface of a class into another one according to the client
expectation and hence, overcomes the problem of incompatible interfaces thereby enabling the
classes to work together.

Bridge: It Separates abstraction from its implementation to make them independent.

Builder: It Separates the complex objects constructions from their representation in order to create
different representations with the same construction process.
The Catalog of Design Patterns:
Chain Of Responsibility: It Enables the handling of command objects by passing them to other
objects by using the logic present in the processing of objects. In other words, Its decouples sender
and receiver by formatting a chain of receiving objects to pass the request until the request is
handled by an object.

Command: It encapsulates the action and its parameters and hence, enables to parameterize the
different requests of the clients such as long or queue requests. It also assists undoable operations.

Composite: It represents the objects in a tree structure where each object represents the same
interface. This enables clients to treat individual objects and their compositions uniformly.

Decorator: It Adds additional functionality to a class at runtime. This Enables flexibility to subclass
for adding functionality.

Facade: It creates a simplified/unified interface of existing interfaces in the subsystems so as to


handle common tasks easily.
The Catalog of Design Patterns:
Factory Method: It Focuses on objects creation of specific implementation. lets the subclass decide
as to which class to be instantiated.

Flyweight: It Performs sharing of common objects properties by a large number of objects to save
space.

Interpreter: It Deals with the implementation of a specified computer language that solves specific
problems. It interprets sentences in language by representing the grammar of language along with
an interpreter.

Iterator: It Enables sequential aggregate objects elements by hiding their underlying


representations.

Mediator: It provides a unified interface to the set of interfaces in a subsystem. It provides loose
coupling which enables objects to refer to each explicitly and also varies objects interaction
independently.
The Catalog of Design Patterns:
Momento: It supports the rollback mechanism by enabling the objects, to restore to their previous
state without violation of encapsulation.

Observer: Whenever an object changes its state, it raises an event that notifies other objects and
updates them automatically. This defines a one-to-many dependency between the objects.

Prototype: Here Prototypical instance determines the type of objects to be created. Further new
objects are created by cloning this prototype.

proxy: It provides an illusion by applying placeholder to other objects in order to have control over it.

Singleton: It Provides restrictions on instantiating a class to a single object and also makes it globally
accessible.

State: It Permits an alteration in the object’s behavior with alteration in its state .i.e allows objects
type to change at runtime.
The Catalog of Design Patterns:
Visitors: It Describes the skeleton of a program, enables subclasses to define some steps of the
algorithm, and also to redefine certain steps without affecting the structure of the algorithm.

Strategy: It defines the Family of algorithms and their selection based upon the clients.
Lecture 8
Detailed pattern study:
Singleton, Abstract Factory
Singleton
▪ “Objects may access them globally, which means
an object can have a global scope.”

Singleton pattern involves a single class which is responsible to


create an object while making sure that only single object gets
created. A Singleton is an elegant way of maintaining global state.
Singleton is to control object creation, limiting the number to one
but allowing the flexibility to create more objects if the situation
changes. Since there is only one Singleton instance, any given
time, a Singleton will occur only once per class, just like static
fields.

Singleton pattern offers several advantages over global variables


because it does the following:
▪ Enforces that only one instance of the class can be
instantiated.
▪ Allows control over the allocation and destruction of the
object.
▪ Provides thread-safe access to the object's global state.
▪ Prevents the global namespace from being polluting.
Singleton
Disadvantages of a Singleton Pattern:

▪ Unit testing is more difficult (because it introduces a global state into an application).
▪ This pattern reduces the potential for parallelism within a program, because to access the singleton in
a multi-threaded system, an object must be serialized (by locking).

Singleton class vs. Static methods :

▪ A Static Class cannot be extended whereas a singleton class can be extended.


▪ A Static Class can still have instances (unwanted instances) whereas a singleton class prevents it.
▪ A Static Class cannot be initialized with a STATE (parameter), whereas a singleton class can be.
▪ A Static class is loaded automatically by the CLR when the program or namespace containing the
class is loaded.
Implementation
The Singleton Design Pattern is a very useful mechanism for providing a single point of object access
in an object-oriented application. Basically, a singleton is a class which only allows creation of a single
instance of it (the class) and gives simple access to that instance.

The following are the common characteristics of a Singleton Pattern.


1. A single constructor, which is private and parameterless. This will prevent creation of an instance
of the class.
2. The class is sealed.
3. A static variable which holds the reference of the created instance.
4. Public static methods.
Implementation
Create a singleton class and have its constructor as “private” so that the class cannot be instantiated.
Then create a private instance of this singleton class inside the class itself. Then we have a special
public method getInstance () that returns a singleton object to the outside world.

Step 1 :

Let's think about a class which has private constructor. It becomes a class that can't be instantiated
because it has private constructor.

class SingletonObject {
private:
getInstance(){}
};

Step 2 :
We need to have an instance of the class to call it, but we can't have an instance because no other
class can't instantiate it. We can use the constructor from an object of type MyClass but we can never
instantiate that object because no other object can use:
new MyClass();
Implementation
Step 3:
using a static method
Singleton

• Would you prefer eager or lazy instantiation for an HTTPRequest class?


o handles authentication
o definitely needed for any HTTP transaction
• Would you prefer eager or lazy instantiation for a Comparator class?
o compares objects
o may or may not be used at runtime
Abstract Factory
Abstract Factory - Provide an interface for creating families of related or dependent objects
without specifying their concrete classes.

Abstract Factory patterns work around a super-factory which creates other factories. This factory
is also called as factory of factories. This type of design pattern comes under creational pattern
as this pattern provides one of the best ways to create an object.

In Abstract Factory pattern an interface is responsible for creating a factory of related objects
without explicitly specifying their classes. Each generated factory can give the objects as per the
Factory pattern.
Abstract Factory Implementation
We are going to create a Shape interface and a concrete class implementing it. We create an abstract factory class
AbstractFactory as next step. Factory class ShapeFactory is defined, which extends AbstractFactory. A factory
creator/generator class FactoryProducer is created.
AbstractFactoryPatternDemo, our demo class uses FactoryProducer to get a AbstractFactory object. It will pass
information (CIRCLE / RECTANGLE / SQUARE for Shape) to AbstractFactory to get the type of object it needs.
Implementation

1 2

3 4
Lecture 9
Detailed pattern study:
Builder
Builder Design Pattern:
The Builder Design Pattern builds a complex object using many simple objects and using a step-
by-step approach. The Process of constructing a complex object should be generic so that the
same construction process can be used to create different representations of the same complex
object.

So, the Builder Design Pattern is all about separating the construction process from its
representation. When the construction process of your object is very complex then only you
need to use to Builder Design Pattern. If this is not clear at the moment then don’t worry we will
try to understand this with an example.

Please have a look at the following diagram. Here, Laptop is a complex object. In order to build a
laptop, we have to use many small objects like LCD Display, USB Ports, Wireless, Hard Drive,
Pointing Device, Battery, Memory, DVD/CD Reader, Keyboard, Plastic Case, etc. So, we have to
assemble these small objects to build laptop complex objects.
Builder of Design Pattern:
Let us understand the builder design pattern with one real-time example. Suppose we want to
develop an application for displaying the reports. The reports we need to display either in Excel or in
PDF format. That means, we have two types of representation of my reports. In order to understand
this better, please have a look at the following diagram.
Builder of Design Pattern:
As you can see, in the above image, we are generating the report either in Excel and PDF. Here, the
construction process involves several steps such as Create a new report, setting report type, header,
content, and footer. If you look at the final output we have one PDF representation and one Excel
representation. Please have a look at the following diagram to understand the construction process
and its representation.
Builder of Design Pattern:
Let us understand the class diagram and the different components involved in the Builder Design
Pattern. In order to understand this please have a look at the following diagram.
Builder of Design Pattern:
To separate the construction process from its representation, the builder design pattern Involve four
components. They are as follows.

Builder: The Builder is an interface that defines all the steps which are used to make the concrete
product.
Concrete Builder: The ConcreteBuilder class implements the Builder interface and provides
implementation to all the abstract methods. The Concrete Builder is responsible for constructs and
assembles the individual parts of the product by implementing the Builder interface. It also defines
and tracks the representation it creates.
Director: The Director takes those individual processes from the Builder and defines the sequence to
build the product.
Product: The Product is a class and we want to create this product object using the builder design
pattern. This class defines different parts that will make the product.
Lecture 10
Detailed pattern study:
Adapter
Adapter design pattern
The Adapter design pattern is a structural pattern that allows incompatible interfaces to work together.
Adapters are used when incompatible interfaces are involved.
In a situation , object wants to call a method but it is not able to because the interface which our client
object can use, is not available with the code which our client object wants to call. Based on what an
adapter does the adapter design pattern is also called wrapper pattern, translator pattern. Let’s look at
the various participants (objects, interfaces) involved in an adapter pattern.

ITarget: This is the interface which


is used by the client to achieve
functionality.<o:p>
Adaptee: This is the functionality
which the client desires but its
interface is not compatible with the
client.<o:p>
Client: This is the class which wants
to achieve some functionality by
using the adaptee’s code.
Adapter: This is the class which
would implement ITarget and
would call the Adaptee code which
the client wants to call.
Adapter Pattern Implementation
Convert the interface of a class into another interface clients expect. Adapter (or Wrapper) lets classes
work together that couldn't otherwise because of incompatible interfaces. Adapter pattern's motivation
is that we can reuse existing software if we can modify the interface.A class adapter uses multiple
inheritance to adapt one interface to another.

1. Adapter pattern relies on object composition.


2. Client calls operation on Adapter object.
3. Adapter calls Adaptee to carry out the operation.
4. In STL, stack adapted from vector:
5. When stack executes push(), underlying vector does vector::push_back().
Implementation

1.The client thinks he is talking to a Rectangle


2.The target is the Rectangle class. This is what the client invokes
method on
3. Rectangle *r = new RectangleAdapter(x,y,w,h);
4. r->draw();
3
5.the adapter class uses multiple inheritance
6.The Adapter RectangleAdapter lets the LegacyRectangle responds
to request (draw() on a Rectangle) by inheriting BOTH classes.
7.The LegacyRectangle class does not have the same methods (draw())
as Rectangle,
but the Adapter(RectangleAdapter) can take the Rectangle method
calls and turn around and invoke method on
the LegacyRectangle, oldDraw()
Lecture 11
Detailed pattern study:
Prototype
Prototype Design Pattern:
A prototype pattern is basically to copy the objects to save time and resources while creating new
instances. This pattern is the part of Creational Pattern.Prototype Design Pattern gives us a way to
create new objects from the existing instance of the object. That means it clone the existing object
with its data into a new object. If we do any changes to the cloned object (i.e. new object) then it
does not affect the original object.

GoF Definition, “Prototype Design Pattern specifies the kind of objects to create
using a prototypical instance, and create new objects by copying this
prototype”.

Prototype pattern as being based on prototypal inheritance in which we create objects that act as
prototypes for other objects. The prototype object itself is effectively used as a blueprint for each
object the constructor creates. If the prototype of the constructor function used contains a property
called name for example (as per the code sample that follows), then each object created by that
same constructor will also have this same property
Explore How Prototype Pattern Works ?
Try to copy one object to another object using the assignment (=) operator, then both the objects will
share the same memory address. And the reason is the assignment operator (=) copies the reference, not
the object except when there is a value type field. This operator will always copy the reference, not the
actual object. Please have a look at the following image.

As you can see in the above image, we have one Employee class. Then we create an instance of Employee
class (i.e. emp1) and set its Name and Department properties. Then we create another employee instance
(i.e. emp2) by assigning the existing employee object (i.e. emp1). When we change the Name of emp2
then it also changes the name of the emp1.
Explore How Prototype Pattern Works ?
Developers use Prototype design pattern when the Object creation is an expensive undertaking and requires a
ton of time and assets and you have a comparative item previously existing. Prototype pattern gives a
component to duplicate the first item to another object and afterwards adjust it as per the requirements.
When we talk about object cloning it means it is all about the call by value. So, if we do any changes to one
object then it will not affect the other object. Let us see how to clone the object to another object.

Step 1:
Employee class, we created one method i.e.
GetClone and as part of that method, we are
returning a clone object using
theMemberwiseClone method.
Step 2:
First we are creating a new instance of the
Employee class and assigning the properties with
some values.
Step 3:
Next, creating the second object by calling the
GetClone method which in turn returns a new
complete copy of the emp1 object.

Now, both the objects (i.e. emp1 and emp2) are


independent and if we do any changes to any
object, then it will not affect other objects.
Difference between Shadow and Deep Cloning
A shallow copy copies all reference types or value types, but it does not copy the objects that the references refer to.
The references in the new object point to the same objects that the references in the original object points to.(Only
Parent Object is cloned here).

Shallow Copy stores the references of objects to the first


memory address. Shallow Copy reflects changes made to
the new/duplicated object in the first object.

In contrast, a deep copy of an object copies the


elements and everything directly or indirectly
referenced by the elements.(Parent Object is
cloned along with the containing objects)
The clone method will make sure that a new instance
in the memory will be created. And any changes made
in the original object will not reflect in the copy object
because they are purely independent of each other.
Advantages:
Prototype Design Pattern:
Creates deep copy of the complex object hierarchy:
In order to create a deep copy of the complex object composition, this pattern helps to ease out the work
provided every object in the composition should implement ICloneable interface.
This is a very useful design pattern to copy objects such as trees.
Reduced load of initialization:
Every new object created using the clone method reflects the exact object state of the original object. If we
create many objects of the same class or structure by calling the class constructor and then initialize every
property explicitly for each object, this will increase the number of repetitive lines needed to properly
initialize every property of every object created.
This need of initialization can be reduced drastically by using this pattern. We can always create a clone of the
existing object created in the application to have the objects readily initialized to the non-default/default
state (Constructors are sufficient to initialize the object to default state).
Reusability - Optimized coding efforts:
One object created in the system and initialized to the either default or non-default state is sufficient to
create the similar object copies again and again.
If there are only few properties that differ from object to object, we need not write the code again and again
to initialize the rest of the properties. This will optimize the coding efforts of writing the code to initialize the
properties that are different between objects of the same class or structure.
Simplified object copy process:
Since the object copying is done recursively by calling the Clone method on every member composition
object, this makes the program structure easier to understand and maintain.
Implementation

1
2
Application of Prototype Design Pattern:
There are many practical scenarios where this design pattern really helps. Here follows few of them.
• Session replication from one server to another server:
In an enterprise level application managing a server pool, the application will monitor and
maintain the optimum load on individual server in the pool. In case of the catastrophic failure,
one server may invalidate thousands of client connections. The enterprise application managing
the server pool can take the responsibility of cloning the sessions from one server to another
without disturbing the clients.
• Generating the GUI having many numbers of similar controls:
This is a quiet frequent scenario. One can have a form or GUI that hosts many similar controls.
In order to maintain the consistency, one needs to initialize every object to the same standard
state. This process of initialization gets repeated again and again for each control increasing the
number of lines of code. In order to optimize this part of the code, one can one have an object
of a control initialized to a standard state and then replicate the same object to create as many
controls needed.
Lecture 12
Detailed pattern study:
Decorator
Decorator Design Pattern:
Decorator design pattern, it will add additional
functionalities or behaviors to an existing object
at run-time.

The Gang Of Four (GOF) defines the Decorator


pattern as "Attach additional responsibilities to
an object dynamically. Decorators provide a
flexible alternative to subclassing for extending
functionality.“

The idea of the Decorator Pattern is to wrap an


existing class, add other functionality to it, then
expose the same interface to the outside world.
Because of this our decorator exactly looks like
the original class to the people who are using it.
It is used to extend or alter the functionality at
runtime. It does this by wrapping them in an
object of the decorator class without modifying
the original object. So it can be called a wrapper
pattern.
Real Life Example

Suppose you want to prepare either chicken pizza


or vegetable pizza. Then what you need to do is,
first you need to prepare the plain pizza. Then
what the Pizza Decorator will do is, it will add
chicken to the plain pizza if you want chicken pizza
or it will add vegetables to the plain pizza if you
want vegetable pizza. So, you are getting chicken
pizza or vegetable pizza by adding chicken or
vegetable to the plain pizza by the Pizza decorator.

So, as per the decorator design pattern, it will add


additional functionalities or behaviors to an
existing object. So, in this case, Plain pizza is the
existing object and adding chicken or vegetable
(based on the type of pizza you want) by pizza
decorator is the additional functionality.

So, if you want vegetable pizza, then the pizza


decorator will add vegetables to the plain pizza
and return veg pizza. In the same way, if you want
chicken pizza, then the pizza decorator will add
chicken to the plain pizza and return chicken pizza.
This is one of the best examples of Decorator
Design Patter.
Real Life Example

How can we solve this using the decorator


design pattern?

1.Firstly, we will define a component (Pizza


Class) which will then be extended by
concrete components (Thin Crust and Thick
Crust Pizzas).

2.Then we will define a decorator that will


extend the main component.

3.The decorator then will be used to extend


the state of the main component by adding
new functionalities to it.
How it works ?
1. Abstract Pizza Class (The main component)
• decorator design pattern in java example : Main
Component
• This Pizza class will be used as the base to create
other types of pizza. This is the main component of
our system.

2. Concrete components

decorator design pattern in java example:


Concrete Component (Thin crust Pizza)

• decorator design pattern in java example:


Concrete Component (Thick Crust Pizza)
• The concrete components are the ones that
will have dynamically added behaviour at run
time. For example, “Thin crust pizza with,
tomato sauce, cheese, olives”.
How it works ?
3. Decorators
decorator design pattern in example: Topping Decorator
abstract class or interface
• As you can see the decorator implements the same
abstract class (Pizza) that they will decorate. This is
where the real game begins.
4. Implementing decorator objects

decorator design pattern in java example: Olives


decorator design pattern in java example: Cheese Decorator
Decorator

the decorators have reference to the instance variable that they will decorate, in this case it is Pizza. It can be any
type of pizza, all it should be is of the type pizza. Additionally, they have their own extension of description and
cost.
How it works ?
Everything wraps up, pizza has instance of ThincrustPizza() that has its own cost and description. The next line has
“composed” Cheese and ThincrustPizza objects, Cheese class acts as a decorator for the Thincrust Pizza , so now we
have ThincrustPizza with Cheese. Same applies to greekPizza. At the end ThinCrustPizza, Cheese and Olives have been
composed. As mentioned earlier, “composition refers to containing instances of other classes that implement desired
functionality”.In our case greekPizza has contained the reference of cheesePizza that has its own functionality, also
cheesePizza has contained the reference of pizza. Thus, creating a “Thin crust Pizza with tomato sauce, cheese ,
olives”. This is how decorators work.

▪ Decorator pattern solved the class explosion problem. We did not create subclasses for every type of pizza.
▪ We can easily extend code without modifying other classes. Say, if we want Onion Pizzas with olives, we just
need to extend the Topping decorator with Onion Pizza class and compose them like we did in the above
example.
▪ We can wrap the components with any number of decorators i.e. if we want onion pizza with olives and cheese,
we simply need additional wrapping and not another subclass with this feature.
How it works ?
The idea of the Decorator Pattern is to wrap an existing
class, add other functionality to it, then expose the
same interface to the outside world. Because of this our
decorator exactly looks like the original class to the
people who are using it.

▪ Component: It defines the interface of the actual


object that needs functionality to be added
dynamically to the ConcreteComponents.
▪ ConcreteComponent: The actual object in which
the functionalities could be added dynamically.
▪ Decorator: This defines the interface for all the
dynamic functionalities that can be added to the
ConcreteComponent.
▪ ConcreteDecorator: All the functionalities that can
be added to the ConcreteComponent. Each
needed functionality will be one
ConcreteDecorator class.
Advantages of Decorator Pattern
▪ Adds functionality to existing objects dynamically
▪ Alternative to sub classing
▪ Flexible design
▪ Supports Open Closed Principle

When to use Decorator Pattern


▪ Legacy System
▪ Contorls
▪ Sealed Classes
Implementation

2
1

3
Lecture 13
Detailed pattern study: Chain
of Responsibility
Chain of Responsibility Design Pattern:
The Chain of Responsibility Pattern describes how we handle a single request by a chain of multiple
handler objects. The request has to be processed by only one handler object from this chain.
However, the determination of processing the request is decided by the current handler. If the
current handler object is able to process the request, then the request will be processed in the
current handler object; otherwise, the current handler object needs to shirk responsibility and push
the request to the next chain handler object. And so on and so forth until the request is processed.

The Gang of Four defines the Chain of Responsibility pattern as follows:


“Avoid coupling the sender of a request to its receiver by giving more than one object the chance to
handle the request. Chain the receiving objects and pass the request along the chain until an object
handles it.”
How it works ?
Chain of Responsibility to the rescue! Let’s create a series
of handlers, each of which will respond to a specific request.
We will chain these handlers together, passing the request
from one handler to another until the request is dealt with.
If a specific handler can’t handle the request, it passes it on
to the next handler in the chain.
▪ This pattern decouples classes by passing a request
from one class to another until the request is
recognised. The receiving objects are chained, and the
request is passed along the chain until a specific object
handles it. Each object in the chain is given a chance to
handle the request.
▪ The Chain of Responsibility pattern allows us to define
separate handler objects that all conform to a particular
interface. This ensures that handlers are independent
from each other and loosely coupled.

when a user clicks a button, the event propagates through the chain of GUI elements that starts with the button,
goes along its containers (like forms or panels), and ends up with the main application window. The event is
processed by the first element in the chain that’s capable of handling it. This example is also noteworthy because it
shows that a chain can always be extracted from an object tree.
How it works ?
when a user clicks a button, the event
propagates through the chain of GUI
elements that starts with the button,
goes along its containers (like forms
or panels), and ends up with the main
application window. The event is
processed by the first element in the
chain that’s capable of handling it.
This example is also noteworthy
because it shows that a chain can
always be extracted from an object
tree.
Implementation

2
Lecture 14
Review class for Mid Term
Examination

You might also like