Short Notes
Short Notes
By: Salman Fazal
By: Salman Fazal
Contents
Contents
SE Overview
SE Overview
……….………
……….………
.
.
1
1
(Objectives, Principles, Methodologies)
(Objectives, Principles, Methodologies)
Architectural Design patterns
Architectural Design patterns
………
………
8
8
GRASP
GRASP
………
………
12
12
OO Design Principles
OO Design Principles
……….
……….
17
17
GoF Design Patterns
GoF Design Patterns
……….
……….
21
21
Data Mapping Patterns
Data Mapping Patterns
………
………
25
25
Anti-design Patterns & Exam Topics
Software Engineering Overview
Software Engineering Overview
11The process of solving customers’ problems by the systematicThe process of solving customers’ problems by the systematic and organised development of high- and organised development of
high-quality software systems within cost, time and
quality software systems within cost, time and other constraints.other constraints.
2
2It’s a discipline that is concerned with all aspects ofIt’s a discipline that is concerned with all aspects of software production, including;software production, including;
o
o Software development processSoftware development process o
o Project ManagementProject Management o
o Tools, methods and theories adoptedTools, methods and theories adopted
Validation
Validation – – Test if Test if the product is specified to the product is specified to the user’s actual needs.the user’s actual needs. Verification
Verification – – Test if the product follows the specification (i.e. do the product meet all use cases?). Test if the product follows the specification (i.e. do the product meet all use cases?). OBJECTIVES: OBJECTIVES: To produce software: To produce software: 1. 1. On timeOn time 2. 2. To budgetTo budget 3.
3. WithWith required qualityrequired quality. Eg:. Eg:
-- MaintainabilityMaintainability: Software should be able to : Software should be able to meet needed changes.meet needed changes. -- ReliabilityReliability: Software must be trustworthy, dependable.: Software must be trustworthy, dependable.
-- EfficiencyEfficiency: Software should not make waste : Software should not make waste of system resourcesof system resources
-- UsabilityUsability: Software must be usable by the users (specifically designed for).: Software must be usable by the users (specifically designed for). PRINCIPLES:
PRINCIPLES:
Principles form the basis of
Principles form the basis of methods, techniques, methodologies and toolsmethods, techniques, methodologies and tools Definitions: Definitions:
-- Methods & Techniques:Methods & Techniques: A (systematic) A (systematic) way of doing things; general guidelines. way of doing things; general guidelines. -- Methodologies:Methodologies: A certain approach to A certain approach to solving a problem by selecting the solving a problem by selecting the methods & techniques to be used. methods & techniques to be used. -- Tools:Tools: Developed toDeveloped to supportsupportthethe application of methods, techniques and application of methods, techniques and methodologies.
methodologies.
Seven important principles of software engineering for the success of a software project. Seven important principles of software engineering for the success of a software project.
Principle 1.Principle 1. Separation of ConcernsSeparation of Concerns
Principle 2.Principle 2. ModularityModularity
Principle 3.Principle 3. IncrementalityIncrementality
Principle 4.Principle 4. AbstractionAbstraction
Principle 5.Principle 5. GeneralityGenerality
Principle 6.Principle 6. Anticipation of ChangeAnticipation of Change
Principle 1:
Principle 1: Separation of ConcernsSeparation of Concerns “
“ Divide and Conquer Divide and Conquer ” ”
Tackles with the complexity of large systems, by separating different issues to concentrate on one at Tackles with the complexity of large systems, by separating different issues to concentrate on one at a time. This
a time. This minimizes interdependenceminimizes interdependence (connection) and (connection) andincreases reusabilityincreases reusability.. Issues/Concerns can be
Issues/Concerns can be
i.
i. FunctionalFunctional (views) (views) – – Describes what the system will Describes what the system will
do. (Layer separation (MVC), data, network, etc)
do. (Layer separation (MVC), data, network, etc)
ii.
ii. Non-functionalNon-functional(qualities)(qualities) – – Concerns how well the Concerns how well the
system provides functional requirements (efficiency,
system provides functional requirements (efficiency,
reliability, usability, etc).
reliability, usability, etc).
More in the extras.
More in the extras.
Example: Example:
Web 1.0: HTML, CSS and Javascript all in the same Web 1.0: HTML, CSS and Javascript all in the same HTML code.
HTML code.
Web 2.0: All three separated into different segments. Web 2.0: All three separated into different segments.
Principle 3:
Principle 3: IncrementalityIncrementality “Grow, don’t build”
“Grow, don’t build”
Process proceeds in separate stages (increments) Process proceeds in separate stages (increments) - delivers
- deliverssubsets of a systemsubsets of a system at early stages or a prototype for feedback from the clients or at early stages or a prototype for feedback from the clients or expected users, from which new features are
expected users, from which new features are added incrementallyadded incrementally - Deals with functionality first, then comes performance.
- Deals with functionality first, then comes performance.
Prototyping model:Prototyping model: quick design focusing on aspects of software, organised and evaluated andquick design focusing on aspects of software, organised and evaluated and
refined through iteration refined through iteration
Principle 5:
Principle 5: GeneralityGenerality “If you think you have al
“If you think you have already discovered a solution, think again…but with a more open mind!” ready discovered a solution, think again…but with a more open mind!” While solving a problem, try to discover if it is an occurrence of a
While solving a problem, try to discover if it is an occurrence of a more general problemmore general problem whosewhose solution can be
solution can be reusedreused in other cases ( in other cases (ie. similar patterns). Sometimes, a general problem is ie. similar patterns). Sometimes, a general problem is easiereasier to solve than a special case.
to solve than a special case.
Component-based Development Model
Component-based Development Model
This approach is based on
This approach is based on systematic reuse where systems are integrated from existing componentssystematic reuse where systems are integrated from existing components
or COTS (Commercial-off-the-shelf) systems. Process stages include:
or COTS (Commercial-off-the-shelf) systems. Process stages include:
Component analysis;Component analysis;
Requirements modification;Requirements modification;
System design with reuse;System design with reuse;
Development and integration.Development and integration. Reuse is now the standard approach
Reuse is now the standard approach for building many types of for building many types of business system.business system.
Principle 6:
Principle 6: Anticipation of ChangeAnticipation of Change “Software changes all the time!” “Software changes all the time!”
Anticipates potential future changes with ability to support software evolution. Anticipates potential future changes with ability to support software evolution.
CAREFUL! That is not about try to implement what users will MAYBE need in the future. That is CAREFUL! That is not about try to implement what users will MAYBE need in the future. That is about to be prepared to change!
about to be prepared to change!
Principle 7:
Principle 7: Rigor and FormalityRigor and Formality
Software engineering is a creative design
Software engineering is a creative design activity, BUT…activity, BUT… It must be It must be practiced systematicallypracticed systematically Rigor:
Rigor: the quality or state of being very exact, careful, or strict.the quality or state of being very exact, careful, or strict. Enables repeatability and allows teams to avoid
Enables repeatability and allows teams to avoid problems experienced in past projects.problems experienced in past projects. Formality:
Formality: the highest degree of rigorthe highest degree of rigor –
– Software process driven and Software process driven and evaluated by mathematical laws;evaluated by mathematical laws;
E.g. mathematical analysis of program correctness for a software product. E.g. mathematical analysis of program correctness for a software product.
METHODOLOGIES METHODOLOGIES
A methodology defines an approach to be used in software development to produce high-quality A methodology defines an approach to be used in software development to produce high-quality and cost-effective software in a
and cost-effective software in a systematic manner.systematic manner. -- Structured (function-oriented)Structured (function-oriented) -- Object-orientedObject-oriented
-- AgileAgile Structured
Structured −
− Processes manipulate data and show Processes manipulate data and show how they transform data objects that how they transform data objects that flow through theflow through the system.
system. −
− The program is represented as a logical structure, the flow of execution of the program is The program is represented as a logical structure, the flow of execution of the program is dependent on the structure of the
dependent on the structure of the program.program. Example of a modelling technique is Flowcharts. Example of a modelling technique is Flowcharts.
Object-oriented Object-oriented −
− Based on the concept of objects in which data is encapsulated with the functions that act on the Based on the concept of objects in which data is encapsulated with the functions that act on the data
data −
− The program is written as a collection of objects which communicate with each other. The basic The program is written as a collection of objects which communicate with each other. The basic entity is object, each computation is performed using objects only.
entity is object, each computation is performed using objects only. Example of a modelling technique is
Example of a modelling technique isUMLUML (Class diagrams, use cases, sequence diagrams). (Class diagrams, use cases, sequence diagrams). UML (Unified Modelling Language):
UML (Unified Modelling Language): a standard language for visualising, specifying, constructing anda standard language for visualising, specifying, constructing and documenting software artefacts.
AGILE AGILE −
− Agile processes use feedback, driven by Agile processes use feedback, driven by regular tests and releases of evolving software.regular tests and releases of evolving software.
Agile:
Agile: SCRUMSCRUM
Scrum is an iterative and incremental agile framework for managing software projects that helps Scrum is an iterative and incremental agile framework for managing software projects that helps team deliver projects very early and often in a highly predictable manner.
team deliver projects very early and often in a highly predictable manner. Applies to techniques, such as:
Applies to techniques, such as:
-- SprintsSprints: A fixed time frame for each of the iterations: A fixed time frame for each of the iterations
-- Product BacklogProduct Backlog: A prioritized list of functionalities to develop: A prioritized list of functionalities to develop -- Daily ScrumDaily Scrum: A daily meeting headed by the scrum master: A daily meeting headed by the scrum master
-- IterativeIterative: through sprints in which: through sprints in which software process and activities are software process and activities are repeated in iterations
repeated in iterations (image 1)(image 1) -- IncrementalIncremental: a working: a working
functionality is delivered at the end functionality is delivered at the end of each sprint
Agile:
Agile: Extreme Programming (XP)Extreme Programming (XP)
Improve software quality and responsiveness to changing customer
Improve software quality and responsiveness to changing customer requirements.requirements.
-- Frequent releases in short development cycles. Development delivery ofFrequent releases in short development cycles. Development delivery of smallsmall increments of functionality.
increments of functionality.
-- Improve productivity and regular checkpoints with Improve productivity and regular checkpoints with the customerthe customer
-- Paired programmingPaired programming – – demands that every bit of the code is developed by a pair of demands that every bit of the code is developed by a pair of programmers, one is involved in the actual building of the code, and the other programmers, one is involved in the actual building of the code, and the other supports and reviews.
supports and reviews. Extras
Extras
Functional Requirements
Functional Requirements – – something the system must do something the system must do
Non-functional Requirements
Non-functional Requirements – – a property or quality the system must have: a property or quality the system must have:
PerformancePerformance – – speed or response time of speed or response time of the system.the system.
SecuritySecurity – – e.g. resistance to attacks. e.g. resistance to attacks.
AvailabilityAvailability – – minimal downtime. minimal downtime.
UsabilityUsability – – system meets user needs and tasks to system meets user needs and tasks to undertake. Usability should achieve theundertake. Usability should achieve the
effectiveness, efficiency and user satisfaction of
effectiveness, efficiency and user satisfaction of the tasks undertaken.the tasks undertaken.
Reverse Engineering
Reverse Engineering: the process of analysing an existing system to identify its components and: the process of analysing an existing system to identify its components and
create representations of the system in another fo
create representations of the system in another form.rm.
-- Decompilation,Decompilation, a type of a type of reverse engineering, to convert executable program codereverse engineering, to convert executable program code
into a form of higher-level programming language readable by human.
into a form of higher-level programming language readable by human.
Forward Engineering
Forward Engineering: traditional software engineering approach : traditional software engineering approach starting with requirements analysisstarting with requirements analysis
and progressing to implementation of a
and progressing to implementation of a system.system.
-- If existing source code, youIf existing source code, you reconstructreconstructthe existing system to improve its overallthe existing system to improve its overall
quality or performance.
quality or performance.
Round-trip Engineering
Round-trip Engineering: Combination of reverse and forward engineering. It: Combination of reverse and forward engineering. It synchronisessynchronises two or two or
more related software artefacts, such as source code, models or other documents. It performs a
more related software artefacts, such as source code, models or other documents. It performs a
continuous alignment between source code and the models/diagrams.
continuous alignment between source code and the models/diagrams.
Re-engineering
Re-engineering: process of reorganising and: process of reorganising andmodifyingmodifyingthe existing system to make them morethe existing system to make them more
maintainable. This is modified by
maintainable. This is modified by first reverse engineering, then code reconstructing the finallyfirst reverse engineering, then code reconstructing the finally
forward engineering.
Software Application Architecture
Software Application Architecture
- The process of defining a
- The process of defining a structured solutionstructured solution that meets all of the technical and operational that meets all of the technical and operational requirements.
requirements.
- Involves optimizing common quality attr
- Involves optimizing common quality attr ibutes such asibutes such as performance performance,, security security , and, and manageability manageability .. - Focuses on how components within an application interact with each other within the application. - Focuses on how components within an application interact with each other within the application. Application Architectural Designs
Application Architectural Designs 2-TIER ARCHITECTURE
2-TIER ARCHITECTURE
Separates the system into two applications, c
Separates the system into two applications, c lient and server. Client computers directly connect tolient and server. Client computers directly connect to and request results from database server, and
and request results from database server, and server sends response directly to client.server sends response directly to client. Tiers: Presentation Tier and Database Tier
Tiers: Presentation Tier and Database Tier
Advantages: Advantages:
-- Easy to maintain and modification is bit easyEasy to maintain and modification is bit easy -- Communication is fasterCommunication is faster
Disadvantages: Disadvantages:
-- In two tier architecture application performance willIn two tier architecture application performance will be degrade upon increasing the
be degrade upon increasing the users.users. -- Cost-ineffectiveCost-ineffective
2-Tier Peer-To-Peer (P2P) 2-Tier Peer-To-Peer (P2P)
Every peer (node) are interconnected with each Every peer (node) are interconnected with each other and share resources with each other without a other and share resources with each other without a central controlling server.
central controlling server.
3-TIER ARCHITECTURE 3-TIER ARCHITECTURE An application tier
An application tier exists between the client and the database server. Clients make requests to theexists between the client and the database server. Clients make requests to the application server, which then sends the request to
application server, which then sends the request to the database server. The database sends thethe database server. The database sends the response back to the middle tier which sends the results to the client.
response back to the middle tier which sends the results to the client. Tiers: Presentation (Client) Tier, Business (Application) Ti
This architectural design evolved from
This architectural design evolved from 2-Tier to address issues with better:2-Tier to address issues with better:
- Maintainability: Tiers are independent to each other; updates or changes can be carried out - Maintainability: Tiers are independent to each other; updates or changes can be carried out without affecting the application as a whole.
without affecting the application as a whole.
- Scalability: Application servers can be distributed on many machines and database no longer - Scalability: Application servers can be distributed on many machines and database no longer requires a connection from every client. Thus easy to scale out.
requires a connection from every client. Thus easy to scale out. - Flexibility:
- Flexibility: Each tier is managed independently therefore it’s more Each tier is managed independently therefore it’s more flexibleflexible.. N-TIER ARCHITECTURE
N-TIER ARCHITECTURE
A client-server architecture in which,
A client-server architecture in which, the presentation, the application processing and the the presentation, the application processing and the datadata management are logically separate processes. N is a number, can be 1 or above.
management are logically separate processes. N is a number, can be 1 or above.
COMPONENT-BASED ARCHITECTURE COMPONENT-BASED ARCHITECTURE
Decomposes application into Decomposes application into reusable functional or logical reusable functional or logical components. This would require components. This would require well-defined communication well-defined communication interfaces
LAYERED ARCHITECTURE LAYERED ARCHITECTURE
Partitions the concerns of the application into stacked groups (layers). Partitions the concerns of the application into stacked groups (layers). Layered vs. Tiered architecture:
Layered vs. Tiered architecture: the layers of an application may be present in on the same physical the layers of an application may be present in on the same physical computer (the same tier) or may be
computer (the same tier) or may be distributed distributed over separate computers (n-tier). over separate computers (n-tier).
−
− Client presenter layer:Client presenter layer: contains the presentation logic, i.e. contains the presentation logic, i.e. how business objects are displayed tohow business objects are displayed to users, e.g. the pop-up screens or
users, e.g. the pop-up screens or drop-down menusdrop-down menus −
− Business layerBusiness layer (also domain layer)(also domain layer):: handles and encapsulates all of business domains ahandles and encapsulates all of business domains a nd rules.nd rules. −
− Persistence layer:Persistence layer: handles the read/write of the business data to the data access layer (DAL). handles the read/write of the business data to the data access layer (DAL). −
− Data access layer:Data access layer: an external data source, e.g. a database. an external data source, e.g. a database. The
The Static ModelStatic Model of a software design incof a software design includes three stereotypes that differentiate the roles objectsludes three stereotypes that differentiate the roles objects can play:
can play: −
− Boundary classes:Boundary classes: to handle communication with actors. Basically, the user interface and windows to handle communication with actors. Basically, the user interface and windows classes.
classes. −
− Entity/data classesEntity/data classes: to represent something (from the : to represent something (from the application domain) about which the application domain) about which the systemsystem must
must store informationstore information.. −
− Control classes:Control classes: mediates (controls & coordinates) mediates (controls & coordinates) between boundary and entity classes.between boundary and entity classes.
Deal with business/application logic, such Deal with business/application logic, such as register new patients.as register new patients.
4 Layered Architecture 4 Layered Architecture User Interface Layer
User Interface Layer – – contains boundary classes (e.g. GUI objects) to handle input and output with contains boundary classes (e.g. GUI objects) to handle input and output with the external actors.
the external actors. Application Logic Layer
Application Logic Layer – – control classes are added to coordinate the application logic for each use control classes are added to coordinate the application logic for each use case.
case.
Domain/data Layer
Domain/data Layer – – data objects contained in data classes. data objects contained in data classes. Data Access/Persistence Layer
MVC ARCHITECTURE MVC ARCHITECTURE Model
Model
–
–
viewview–
–
controller (MVC) is a software design pattern for implementing user interfaces oncontroller (MVC) is a software design pattern for implementing user interfaces on computers. It divides a given sofcomputers. It divides a given software application into three interconnected parts, The Model, tware application into three interconnected parts, The Model, ViewView and Controller.
and Controller.
−
− ModelModel: represents an object or data : represents an object or data (the database)(the database) −
− ViewView: represents the visualization of the : represents the visualization of the data that model contains (what end data that model contains (what end user sees).user sees). −
− ControllerController: controls the data : controls the data flow into model object and flow into model object and updates the view whenever data changesupdates the view whenever data changes (Receives requests from the view and sends back data from the model).
(Receives requests from the view and sends back data from the model).
Benefits: Benefits: −
− Support multiple views: Support multiple views: user interface can display user interface can display multiple views of the same multiple views of the same data at the same time data at the same time −
− Accommodate changes: Accommodate changes: Changes to the user Changes to the user
interface (theme, layouts) interface (theme, layouts) does not affect the model. does not affect the model.
GRASP (Design Pattern)
GRASP (Design Pattern)
Pattern
Pattern – – A principle used that provide guidance in the creation of software. Have a name, problem A principle used that provide guidance in the creation of software. Have a name, problem description and problem solution.
description and problem solution. Design Pattern
Design Pattern – – a general repeatable solution a general repeatable solution to a commonly to a commonly occurring problem in occurring problem in softwaresoftware design. A design pattern isn't a finished design that can be transformed directly into code. It is design. A design pattern isn't a finished design that can be transformed directly into code. It is aa description
description oror template template for how to solve a problem that can be used in many different situations. for how to solve a problem that can be used in many different situations. o
o Architectural PatternsArchitectural Patterns – – Presenting an essential structural schema for Presenting an essential structural schema for a software system.a software system. E.g. MVC
E.g. MVC o
o Design PatternsDesign Patterns – – Providing a scheme for refining the components of a software system. Providing a scheme for refining the components of a software system. -- General patterns (guidelines) for assigning responsibility to General patterns (guidelines) for assigning responsibility to classes and objects.classes and objects.
E.g. the ‘GRASP’ set of patterns. E.g. the ‘GRASP’ set of patterns. The GRASP Patterns
The GRASP Patterns GRASP
GRASP ( (GGeneraleneralRResponsibilityesponsibilityAAssignmentssignmentSSoftwareoftwarePPatterns) encompass nine object‐orientedatterns) encompass nine object‐oriented design principles related to creating responsibilities for classes and defining objects.
design principles related to creating responsibilities for classes and defining objects. Grasp Patters:
Grasp Patters:
Controller, creator, indirection, information expert, high
Controller, creator, indirection, information expert, high cohesion, low coupling, polymorphism,cohesion, low coupling, polymorphism, don’t
don’t talk to strangers, and pure fabrication. All these patterns answer some software problem. talk to strangers, and pure fabrication. All these patterns answer some software problem. GRASP Pattern: Cohesion & Coupling
GRASP Pattern: Cohesion & Coupling Cohesion
Cohesion refers to what the class will do. refers to what the class will do. Low cohesionLow cohesion means the class does a great variety of means the class does a great variety of actions and is not focused on what is should do.
actions and is not focused on what is should do. High cohesionHigh cohesion means that the class is focused on means that the class is focused on what it should be doing
what it should be doing Low
Low Cohesion Cohesion High High CohesionCohesion ---| | Staff Staff || ---| | checkEmail() checkEmail() || | | sendEmail() sendEmail() || | emailValidate() | | emailValidate() | | | PrintLetter() PrintLetter() || --- ---| | Staff Staff || ---| | -salary -salary || | | -emailAddr -emailAddr || ---|
| setSalary(newSasetSalary(newSalary) lary) || |
| getSalary() getSalary() || |
| setEmailAddr(nesetEmailAddr(newEmail) wEmail) || |
| getEmailAddr() getEmailAddr() ||
---Coupling
Coupling refers to how two classes are refers to how two classes are related to each other.related to each other. Low couplingLow coupling means changing means changing something major in one class should not affect the other. High coupling would make it difficult to something major in one class should not affect the other. High coupling would make it difficult to make the changes.
make the changes.
A good software design will go for
GRASP Pattern: Controller GRASP Pattern: Controller This is an object
This is an object just below the UI layer that just below the UI layer that controls the systems operations.controls the systems operations. Problem:
Problem: Who should be responsible for handling UI events? (Ie. ‘Who should be responsible for handling UI events? (Ie. ‘End Sale’, ‘Make End Sale’, ‘Make Payment’, ‘EnterPayment’, ‘Enter Item’
Item’ in a POS system)in a POS system) Solution:
Solution: Assign responsibility to receive or handling a system events in one of these ways:Assign responsibility to receive or handling a system events in one of these ways: -- Façade controllerFaçade controller: One class that : One class that represents and control the entire systemrepresents and control the entire system
-- Role ControllerRole Controller: One class that represents a role (an actor) and controls all functionality by: One class that represents a role (an actor) and controls all functionality by that actor.
that actor.
-- Use Case ControllerUse Case Controller: One class represents a use case (within which a system event occurs): One class represents a use case (within which a system event occurs) and controls its functionality.
and controls its functionality.
*Façade is suitable when there ar
*Façade is suitable when there are no too many events, however it’s a e no too many events, however it’s a less desirable solution as itless desirable solution as it leads to low cohesion and high coupling.
leads to low cohesion and high coupling. GRASP Pattern: Information Expert GRASP Pattern: Information Expert
This is a class that has information necessary to fulfil some responsibility. This is a class that has information necessary to fulfil some responsibility. Problem
Solution
Solution: Assign responsibility to the class that has the information necessary to fulfil it (the: Assign responsibility to the class that has the information necessary to fulfil it (the information expert).
information expert). Example: Consider, Example: Consider,
Which class should be responsible for calculating the grand total of the Which class should be responsible for calculating the grand total of the sale?sale? While the Product class
While the Product class can determine the value of an can determine the value of an individual items, they cannot determine theindividual items, they cannot determine the final mark. The Sale class should be assigned this responsibility since it knows about all of the final mark. The Sale class should be assigned this responsibility since it knows about all of the SaleSale Detail class. The Sale class will rely on the Product class to determine the individual prices.
Detail class. The Sale class will rely on the Product class to determine the individual prices.
The Expert pattern has a real-world analogy, who do you ask about X, you ask the expert who knows The Expert pattern has a real-world analogy, who do you ask about X, you ask the expert who knows about X.
about X.
GRASP Pattern: Creator GRASP Pattern: Creator
Who creates a particular object? Who creates a particular object? Problem:
Problem: Who’s responsible to create an instance of class A?Who’s responsible to create an instance of class A? Solution:
Solution: Assign B to create an instance of A if one the following is true:Assign B to create an instance of A if one the following is true: -- B contains/aggregates AB contains/aggregates A
-- B records AB records A -- B closely uses AB closely uses A
-- B has data needed to create an A object.B has data needed to create an A object.
In the above diagram, which class should be responsible for creating the Sale Detail object? In the above diagram, which class should be responsible for creating the Sale Detail object? Since the Sale aggregates Sales Detail, Sale should be the creator.
Since the Sale aggregates Sales Detail, Sale should be the creator. GRASP Pattern: Polymorphism
GRASP Pattern: Polymorphism
Usually means the use of a super (parent) class. Usually means the use of a super (parent) class. Problem
Problem: How to handle : How to handle related but varying elements based on element type? How to crelated but varying elements based on element type? How to c reatereate pluggable software components? (Replace one component without
pluggable software components? (Replace one component without affecting the main component).affecting the main component). Solution
GRASP Pattern: Pure fabrication GRASP Pattern: Pure fabrication Problem
Problem: How to assign responsibilities when you do not want to violate High Cohesion and Low: How to assign responsibilities when you do not want to violate High Cohesion and Low Coupling (solutions offered by Information Expert are not appropriate)?
Coupling (solutions offered by Information Expert are not appropriate)? Solution
Solution: : Assign Assign thethe responsibility to an artificial class that doesn’t belong to the domain model –responsibility to an artificial class that doesn’t belong to the domain model – something made up in order to support high cohesion, low coupling and reuse.
something made up in order to support high cohesion, low coupling and reuse. Example;
Example;
-- Suppose we need to save instances of SaleClass in a database, which class do we assign thisSuppose we need to save instances of SaleClass in a database, which class do we assign this responsibility to?
responsibility to?
-- To manage data going to and from a database will require numerous operations,To manage data going to and from a database will require numerous operations, insert,insert, delete, update, select, commit …
delete, update, select, commit …
-- The information expert suggests that SaleClass is the The information expert suggests that SaleClass is the expert so the functions should be expert so the functions should be inin that class. However, we would end up adding a lot to SaleClass which is not really related. that class. However, we would end up adding a lot to SaleClass which is not really related. -- Pure Fabrication suggests to create a new class for these responsibilities.Pure Fabrication suggests to create a new class for these responsibilities.
<- Class is fabricated (made up), and is not found in the domain <- Class is fabricated (made up), and is not found in the domain model.
model.
SaleClass remains well-designed (high cohesion, low coupling). SaleClass remains well-designed (high cohesion, low coupling).
GRASP Pattern: Indirection GRASP Pattern: Indirection Problem
Problem: Where to assign a responsibility, to avoid direct coupling between two (or more) things?: Where to assign a responsibility, to avoid direct coupling between two (or more) things? How to decouple objects so that low coupling is supported and reuse potential remains higher? How to decouple objects so that low coupling is supported and reuse potential remains higher? Solution
Solution: Assign the responsibility to : Assign the responsibility to an intermediate object to mediate between other componentsan intermediate object to mediate between other components or services so that they are not directly coupled.
GRASP Pattern: Law Of Demeter GRASP Pattern: Law Of Demeter
Don’t talk to strangers. “Each class should only talk to its friends (close ones)” Don’t talk to strangers. “Each class should only talk to its friends (close ones)” The Law of Demeter places co
The Law of Demeter places constraints on what objects you should nstraints on what objects you should send messages to within asend messages to within a method.
method. It states that within a meIt states that within a method, messages should only be senthod, messages should only be sent to the following objects:t to the following objects: 1.
1. TheThe thisthis object (or self). object (or self). 2.
2. A parameter of the method.A parameter of the method. 3.
3. An attribute of this.An attribute of this. 4.
4. An element of a collection which is an attribute of this.An element of a collection which is an attribute of this. 5.
5. An object created within the method.An object created within the method.
Notes Notes _____________ _______________________________________________________________________________________________________________________________________________________ _____________ _______________________________________________________________________________________________________________________________________________________ _____________ _______________________________________________________________________________________________________________________________________________________ _____________ _______________________________________________________________________________________________________________________________________________________ _____________ _______________________________________________________________________________________________________________________________________________________ _____________ _______________________________________________________________________________________________________________________________________________________ _____________ _______________________________________________________________________________________________________________________________________________________ _____________ _______________________________________________________________________________________________________________________________________________________ _____________ _______________________________________________________________________________________________________________________________________________________ _____________ _______________________________________________________________________________________________________________________________________________________ _____________ _______________________________________________________________________________________________________________________________________________________ _____________ _______________________________________________________________________________________________________________________________________________________ _____________ _______________________________________________________________________________________________________________________________________________________
OO Design and Principles
OO Design and Principles
ABSTRACTION ABSTRACTION
The developer and other objects in the
The developer and other objects in the system have a high-level summary view (an abstract vsystem have a high-level summary view (an abstract v iew) ofiew) of what data items are and operations provided. The details of how the
what data items are and operations provided. The details of how the datadata and methods ( and methods (procedureprocedure)) are stored and coded are ignored.
are stored and coded are ignored. Types of abstraction:
Types of abstraction: 1.
1. DataData – – (Summary of data items). Contains only the required information about the object. (Summary of data items). Contains only the required information about the object. 2.
2. ProceduralProcedural – – (Summary of operations). Sequence of instructions that have a specific and (Summary of operations). Sequence of instructions that have a specific and limited function. The details and how the methods are coded are ignored.
limited function. The details and how the methods are coded are ignored.
ENCAPSULATION ENCAPSULATION The
The attributes (data)attributes (data) relating to an object and the relating to an object and the methodsmethods that manipulate them are that manipulate them are encapsulated encapsulated inside a single software capsule (unit). This keeps both (public variables and methods) safe from inside a single software capsule (unit). This keeps both (public variables and methods) safe from outside interference and misuse.
outside interference and misuse. Encapsulate components via
Encapsulate components via aggregationaggregation andand compositioncomposition.. Aggregation
Aggregation – – child can exist independently without parent. Eg. Library and students child can exist independently without parent. Eg. Library and students Composition
INFORMATION HIDING INFORMATION HIDING Data Hiding
Data Hiding – – the developer and other objects in the developer and other objects in the system have no direct access to the system have no direct access to the attributesthe attributes (which are private) or the detail of how the attributes are stored.
(which are private) or the detail of how the attributes are stored. Procedural Hiding
Procedural Hiding – – The developer or other objects in the system do not know the detail of how the The developer or other objects in the system do not know the detail of how the methods work. The name of a method is public but the code body of the method is private.
methods work. The name of a method is public but the code body of the method is private. They access the data via
They access the data via accessor methodsaccessor methods (get methods) and modify the data via(get methods) and modify the data via mutatormutator methods
methods (set methods)(set methods)
SEPERATION OF CONCERNS SEPERATION OF CONCERNS
Any complex problem can be more easily handled if it is subdivided into pieces. Separation of Any complex problem can be more easily handled if it is subdivided into pieces. Separation of
Concerns is the idea of dividing an application into distinct components that overlap in functionality Concerns is the idea of dividing an application into distinct components that overlap in functionality as little as possible. Eg. Layered architecture or MVC
MODULARITY MODULARITY
(Relating to separation of concerns). A complex software may be divided into smaller (Relating to separation of concerns). A complex software may be divided into smaller components/modules according to functionality and
components/modules according to functionality and responsibility.responsibility.
Supports application of separation of concerns. When dealing with a module we can ignore details of Supports application of separation of concerns. When dealing with a module we can ignore details of other modules. Modules should be
other modules. Modules should be highly cohesivehighly cohesive andand closely related. closely related. Example:
Example:
In a student registration system, the system is
In a student registration system, the system is separated into classes (i.e. modules), Student andseparated into classes (i.e. modules), Student and Courses according to their functionality and responsibilities. When dealing with the Student class, Courses according to their functionality and responsibilities. When dealing with the Student class, the details of other classes are ignored.
the details of other classes are ignored. HIGH COHESION
HIGH COHESION Cohesion
Cohesion refers to what the class will do. refers to what the class will do. Low cohesionLow cohesion means the class does a great variety of means the class does a great variety of actions and is not focused on what is should do.
actions and is not focused on what is should do. High cohesionHigh cohesion means that the class is focused on means that the class is focused on what it should be doing.
what it should be doing.
A class should only have attributes and operations closely related to its objects or a group of clearly A class should only have attributes and operations closely related to its objects or a group of clearly defined processes that are related in terms of functionality.
defined processes that are related in terms of functionality.
LOW COUPLING LOW COUPLING Coupling
Coupling refers to how two classes are refers to how two classes are related to each other.related to each other. Low couplingLow coupling means changing means changing something major in one class should not affect the other. High coupling would make it difficult to something major in one class should not affect the other. High coupling would make it difficult to make the changes.
make the changes. Classes should exhibit
Classes should exhibit low coupling.low coupling. Classes should have low interactions with others, in terms of Classes should have low interactions with others, in terms of messages an object send to another object
REUSABILITY REUSABILITY
Reusability is a principle whose importance derives from the desire to avoid duplication in Reusability is a principle whose importance derives from the desire to avoid duplication in undertaking classes of inherently similar tasks.
undertaking classes of inherently similar tasks.
A group of classes is encapsulated collectively for a reuse subassembly, as a complex whole is made A group of classes is encapsulated collectively for a reuse subassembly, as a complex whole is made of similar components (parts); more parts can be added to the whole component.
of similar components (parts); more parts can be added to the whole component. It also allows the
It also allows the creation of new specialised classes when needed, as new creation of new specialised classes when needed, as new specialised subclasses willspecialised subclasses will inherit the characteristics of
inherit the characteristics of existing generalised super-classes.existing generalised super-classes.
<= Aggregation with reusability: <= Aggregation with reusability:
Initially the system is designed with University, Initially the system is designed with University,
Department and Professor which forms an aggregation Department and Professor which forms an aggregation association. Later when a Lecturer needs to be added to association. Later when a Lecturer needs to be added to the system, it can be
the system, it can be added via aggregation, enhancingadded via aggregation, enhancing reusability.
reusability.
NOTES NOTES Overload
Overload – – method name method name having several alternative implementations (compile having several alternative implementations (compile time)__________time)________________ Override
Override – – child class provides child class provides alternate implementation for the parent class method (ralternate implementation for the parent class method (r untime)____untime)____ _____________ _______________________________________________________________________________________________________________________________________________________ _____________ _______________________________________________________________________________________________________________________________________________________ _____________ _______________________________________________________________________________________________________________________________________________________ _____________ _______________________________________________________________________________________________________________________________________________________ _____________ _______________________________________________________________________________________________________________________________________________________ _____________ _______________________________________________________________________________________________________________________________________________________ Inheritance with reusability
‘Gang of Four’ Design Patterns
‘Gang of Four’ Design Patterns
Recap Recap
Design patterns represent the best practices used by
Design patterns represent the best practices used by experienced OO software developers. Designexperienced OO software developers. Design patterns are solutions to general problems during
patterns are solutions to general problems during OO software development.OO software development. Design patterns
Design patterns provide a provide a descriptiondescription of the interactions between objects and of the interactions between objects and classes that areclasses that are adapted to solve general problems within a given context of software design.
adapted to solve general problems within a given context of software design. There are 23 Design patterns which are categorised into three groups;
There are 23 Design patterns which are categorised into three groups;
CreationalCreational patterns patterns – – manages manages creationcreation of classes and objects. of classes and objects.
StructuralStructural patterns patterns – – describes describeshow how classes and objects are connected together classes and objects are connected together to buildto build
structured (complex) objects. structured (complex) objects.
BehaviouralBehavioural patterns patterns – – specifies the way objects specifies the way objects communicatecommunicate with each other. Describes with each other. Describes
how code is organized, to assign responsibility or roles to certain classes. how code is organized, to assign responsibility or roles to certain classes.
CREATIONAL PATTERNS CREATIONAL PATTERNS
Deals with initializing and configuring classes and objects. They help in isolating how objects are Deals with initializing and configuring classes and objects. They help in isolating how objects are created, composed and represented from the rest of
created, composed and represented from the rest of the system.the system. Creational
Creational – – Factory Method Factory Method
Defines an interface for creating objects but lets the sub-classes decide which of those to instantiate. Defines an interface for creating objects but lets the sub-classes decide which of those to instantiate.
-- One or more methods are declared within the Factory class which create the object.One or more methods are declared within the Factory class which create the object. -- Methods are then instantiated within the subclass based oMethods are then instantiated within the subclass based o n clients information.n clients information.
Useful when requiring the creation of many different types of objects, all derived from a common Useful when requiring the creation of many different types of objects, all derived from a common base type.
Creational
Creational – – Abstract Factory Method Abstract Factory Method
The abstract factory method provides one layer of abstraction above factory method, they work The abstract factory method provides one layer of abstraction above factory method, they work around a super-factory which creates other factories.
around a super-factory which creates other factories.
In abstract factory pattern, an interface is responsible for creating a factory or related objects In abstract factory pattern, an interface is responsible for creating a factory or related objects without explicitly specifying their classes.
without explicitly specifying their classes.
Abstract Class
Abstract Class – – cannot be instantiated, but other classes can inherit from them cannot be instantiated, but other classes can inherit from them Interface
Interface – – Method with no implementation. Method must be overridden by the Method with no implementation. Method must be overridden by the implementedimplemented classes.
classes.
Creational
Creational – – Singleton Singleton
The singleton ensures that a class
The singleton ensures that a class has only one possible instance.has only one possible instance.
-- Private static attribute and constructorPrivate static attribute and constructor – – to ensure the class cannot be instantiated or to ensure the class cannot be instantiated or manipulated elsewhere outside of the class definition.
manipulated elsewhere outside of the class definition. -- Public static accessor method (getter).Public static accessor method (getter).
Singleton Implementation: Singleton Implementation:
-- Lazy initializationLazy initialization – – delaying the creation of a field until its value it needed the first time. delaying the creation of a field until its value it needed the first time. -- Lazy class loadingLazy class loading – – class class loaded into memory only where they’re first referenced.loaded into memory only where they’re first referenced.
Creational
Creational – – prototype prototype
This design pattern is used for creating new objects (instances) by cloning (copying) other objects This design pattern is used for creating new objects (instances) by cloning (copying) other objects and this way we can improve the performance. The pattern uses Java cloning to copy the object. and this way we can improve the performance. The pattern uses Java cloning to copy the object. E.g. we
E.g. we need to load an object from a DB then modify its data in our program multiple times, it’s notneed to load an object from a DB then modify its data in our program multiple times, it’s not a good idea of creating objects (using new keyword) by loading all the data from the DB. A better a good idea of creating objects (using new keyword) by loading all the data from the DB. A better approach is to clone the existing object to a new one and then manipulate its data.
approach is to clone the existing object to a new one and then manipulate its data.
STRUCTURAL PATTERNS STRUCTURAL PATTERNS
Concerned with how classes and objects are
Concerned with how classes and objects are composed to form larger structures.composed to form larger structures. Structural
Structural – – proxy proxy
Proxy provides a placeholder for another object to control access to it. Proxy means ‘represent’ or Proxy provides a placeholder for another object to control access to it. Proxy means ‘represent’ or ‘on behalf or’.
‘on behalf or’.
Provide a class which limits/controls access to the original class. Provide a class which limits/controls access to the original class.
E.g. an ATM class has several methods, one being setting the cash. The proxy class will represent the E.g. an ATM class has several methods, one being setting the cash. The proxy class will represent the ATM class and will not have the setCash method. The client accesses the proxy instead of ATM class. ATM class and will not have the setCash method. The client accesses the proxy instead of ATM class.
-- Remote proxyRemote proxy – – provides a local representation of the object which is present in the provides a local representation of the object which is present in the different address location.
different address location.
-- Smart proxySmart proxy – – provides additional layer of provides additional layer of security by interposing some actions when thesecurity by interposing some actions when the object is accessed.
object is accessed.
-- Protective proxyProtective proxy – – acts as an authorisation layer to verify if the actual user has access to acts as an authorisation layer to verify if the actual user has access to appropriate content.
appropriate content.
-- Virtual proxyVirtual proxy – – useful to save expensive memory resources when there useful to save expensive memory resources when there is an expensiveis an expensive operation, multiple proxies can be c
operation, multiple proxies can be created and pointed to the huge size memory coreated and pointed to the huge size memory co nsumingnsuming object for further processing.
object for further processing. o
o Example a real image contains a huge size data which clients needs to access.Example a real image contains a huge size data which clients needs to access. o
o Solution:Solution:
Image interface which has operation display().Image interface which has operation display().
RealImage runs on the different system and contains the image informationRealImage runs on the different system and contains the image information
is accessed and loaded from the database. is accessed and loaded from the database.
ProxyImage which is running oProxyImage which is running on a different system can represent then a different system can represent the
RealImage in the new system. RealImage in the new system.
IcecreamCache IcecreamCache
BEHAVIOURAL PATTERNS BEHAVIOURAL PATTERNS Behavioural
Behavioural – – observer observer
A design pattern in which an object, called
A design pattern in which an object, called the subjectthe subject, maintains a lost of its dependants, called, maintains a lost of its dependants, called observers
observers, and notifies them automatically of any state changes, usually called by one of their, and notifies them automatically of any state changes, usually called by one of their methods.
methods. This defines a
This defines a one-to-manyone-to-many dependancy between objects so that when o dependancy between objects so that when o ne object changes state, allne object changes state, all of its dependants are notified and updated automatically.
of its dependants are notified and updated automatically. Real world example: (online shopping)
Real world example: (online shopping)
-- 3 people (3 people (observersobservers) want to buy a certain item but) want to buy a certain item but its out of stock, they click on the ‘notifyits out of stock, they click on the ‘notify when in stock’ option
when in stock’ option; meaning they are; meaning they are registeringregistering themselves to that option (themselves to that option (the subjectthe subject).). -- Once item is in stock, the status changes to ‘available’ & theOnce item is in stock, the status changes to ‘available’ & the subjectsubject notifies the 3 observers.notifies the 3 observers.
Data Mapping & Patterns
Data Mapping & Patterns
Layered architecture review: Layered architecture review:
Data Persistence in OO: Data Persistence in OO: 1.
1. Transient Data/ObjectTransient Data/Object (temporary data)(temporary data):: -- Stored in the computers RAM. When aStored in the computers RAM. When a program completes, the data is de
program completes, the data is de-allocated.-allocated. 2.
2. Persistent Data/ObjectPersistent Data/Object (permanent data):(permanent data): -- Permanent data stored in a file or database,Permanent data stored in a file or database, data still available when program
data still available when program completes.completes. -- Must exist between executions of differentMust exist between executions of different applications or be shared among different
applications or be shared among different instances of applications.
instances of applications. Persistence Mechanisms
Persistence Mechanisms
Data hold in files of databases.Data hold in files of databases.
DBMSDBMS
-- Relational DBMS: holds tables of dataRelational DBMS: holds tables of data
-- Object DBMS: holds objects (with attributes)Object DBMS: holds objects (with attributes)
-- Object-Relational DBMS: combines relational (simplicity) Object-Relational DBMS: combines relational (simplicity) and object databasesand object databases (complexity)
(complexity)
-- NoSQL: non-relational data - (open source, schema-NoSQL: non-relational data - (open source, schema-less, distributed …)less, distributed …).. Mapping Objects
Mapping Objects
The data access layer connects to an external data source (e.g. Database), there is a need to map the The data access layer connects to an external data source (e.g. Database), there is a need to map the objects in the application to tables in the database.
objects in the application to tables in the database.
Sometimes mapping individual classes to separate database tables may
Sometimes mapping individual classes to separate database tables may be simple, however, if a cbe simple, however, if a classlass structure is more complex, then mapping must be carefully considered to allow data to be
structure is more complex, then mapping must be carefully considered to allow data to be represented and accessed as efficiently as possible.
represented and accessed as efficiently as possible.
Object-relational mapping basically manages the translation of
Object-relational mapping basically manages the translation of objects into relational databases, andobjects into relational databases, and vice versa. It answers questions of
vice versa. It answers questions of how object-oriented constructs like inheritance, aggregation, orhow object-oriented constructs like inheritance, aggregation, or relations can be mapped to the semantics of a relational database.
relations can be mapped to the semantics of a relational database. 1. Foreign Key Mapping (one-to-many)
1. Foreign Key Mapping (one-to-many)
Maps an association between objects to a
Maps an association between objects to a foreignforeign key reference between tables.
key reference between tables.
<- an album can have many tracks. Multivalued <- an album can have many tracks. Multivalued attributes are moved to a
attributes are moved to a separate table.separate table. To implement one-to-many relationships, you To implement one-to-many relationships, you simply have to include the key of one table in the simply have to include the key of one table in the other table.
2. Association Table Mapping (
2. Association Table Mapping (many-to-many)many-to-many)
Saves an association as a table with Saves an association as a table with foreign keys to the tables that are linked foreign keys to the tables that are linked by the association. Works as a
by the association. Works as a junction/linking table.
junction/linking table.
To implement many-to-many To implement many-to-many
relationships, you simply create a table relationships, you simply create a table that just contains IDs of foreign keys of that just contains IDs of foreign keys of two tables.
two tables.
3. Mapping Inheritance 3. Mapping Inheritance
Relational databases don’t support inheritance, here are some
Relational databases don’t support inheritance, here are some ways of mapping inheritance:ways of mapping inheritance: a)
a) Single Table InheritanceSingle Table Inheritance
Uses one table to store all Uses one table to store all classes in a hierarchy, with the classes in a hierarchy, with the ability to identify individual ability to identify individual types.
types.
<- include the
<- include the typetypeattributeattribute
b)
b) Class Table InheritanceClass Table Inheritance
Uses one table for each class Uses one table for each class in a hierarchy.
c)
c) Concrete Table InheritanceConcrete Table Inheritance
Uses one table to store each Uses one table to store each concrete class in a hierarchy. concrete class in a hierarchy. Each table contains field Each table contains field from concrete class and all from concrete class and all its super-classes. its super-classes. COMPARISON: COMPARISON: Advantages Disadvantages Advantages Disadvantages Single Table
Single Table - Easier modifications- Easier modifications
- Avoid joins (as all in one table) - Avoid joins (as all in one table)
- Wasted space (as each row has all possible - Wasted space (as each row has all possible subtypes leading to empty columns)
subtypes leading to empty columns) - large size of table with lots of indexes - large size of table with lots of indexes Class Table
Class Table - no attribute duplication (unlike- no attribute duplication (unlike the other two methods)
the other two methods) - no wasted/null fields - no wasted/null fields
- Needs multiple joins to load a single object - Needs multiple joins to load a single object –
– reduces performance. reduces performance. Concrete
Concrete
Table
Table
- Avoid joins (allowing objects to be - Avoid joins (allowing objects to be pulled of a single table)
pulled of a single table)
- inflexible to changes (all tables are - inflexible to changes (all tables are required to be altered if a change in required to be altered if a change in superclass)
superclass)
DATA MANAGEMENT CLASSES DATA MANAGEMENT CLASSES Two methods to data management: Two methods to data management:
a)
a) PersistentObjectPersistentObject: allow all persistent objects to inherit from a: allow all persistent objects to inherit from a PersistentObject classPersistentObject class.. b)
b) Data Broker classesData Broker classes: database broker approach, use: database broker approach, use data storage classesdata storage classes to manage objects. to manage objects. Persistent Object Approach
Persistent Object Approach (direct mapping)(direct mapping) - The persistent Object approach means that
- The persistent Object approach means that individual data classes have to deal with individual data classes have to deal with mappingmapping objects to and from
objects to and from the databasethe database
- Create an abstract superclass (PersistentObject) and make all
- Create an abstract superclass (PersistentObject) and make all persistent classes inherit from it.persistent classes inherit from it. - One PersistentObject to all classes: very strong coupling all data classes at a utility class.
- One PersistentObject to all classes: very strong coupling all data classes at a utility class.
However, these data classes have poor separation of concerns (low cohesion) and thus difficult However, these data classes have poor separation of concerns (low cohesion) and thus difficult to reuse.
The PersistentObject class will have methods to The PersistentObject class will have methods to store, delete and update data to and from the store, delete and update data to and from the database.
database.
The write and read methods are called by the The write and read methods are called by the store, delete and update methods to:
store, delete and update methods to:
-- Break objects into attributes and wrBreak objects into attributes and write themite them to a database
to a database
-- Read the attributes back and reconstruct anRead the attributes back and reconstruct an object.
object.
The write and read methods basically r
The write and read methods basically read/writeead/write to a file or database, they are abstract meaning to a file or database, they are abstract meaning their method bodies are not i
their method bodies are not implemented in themplemented in the superclass. Different persistent classes (i.e. superclass. Different persistent classes (i.e. patient, appointment, dentist, etc) require patient, appointment, dentist, etc) require different implementation, therefore the method bodies are defined in
different implementation, therefore the method bodies are defined in the data class.the data class.
Data Brokers Approach
Data Brokers Approach (indirect mapping)(indirect mapping)
In this approach, there is a good separation of concerns (higher cohesion and l
In this approach, there is a good separation of concerns (higher cohesion and l ower coupling). All theower coupling). All the persistence related methods are in the broker cl
persistence related methods are in the broker cl asses and are not visible to the asses and are not visible to the data classes.data classes. o
o Separates data objects from the data Separates data objects from the data storage classesstorage classes o
o An associated broker class is required for each data class.An associated broker class is required for each data class. o
o The broker class provide mechanisms to materialise objects The broker class provide mechanisms to materialise objects from the database andfrom the database and dematerialise them back.
dematerialise them back.
Example: Example: PatientBroker PatientBroker is is responsible for the responsible for the storage and retrieval storage and retrieval of
of PatientPatient object object instances.
instances.
Data Access Object Pattern Data Access Object Pattern
DAO is used to separate low level accessing operations from high level business services. The idea is DAO is used to separate low level accessing operations from high level business services. The idea is that instead of having the domain logic communicate with the database or any other persistent that instead of having the domain logic communicate with the database or any other persistent storage, the domain logic speaks to the DAO instead, which then communicates the database. storage, the domain logic speaks to the DAO instead, which then communicates the database.
It is an
It is an object/interfaceobject/interface , which is used to , which is used to access/manipulate dataaccess/manipulate data from database of data storage. from database of data storage. The advantage of this layer is, ifyou need to make a change to the persistence mechanism, you only The advantage of this layer is, ifyou need to make a change to the persistence mechanism, you only change it in the DAO layer and not al