Generalization. Example CachPaymentCreditPaymentCheckPayment Paymentamount sale Attribute...
-
Upload
bennett-stephens -
Category
Documents
-
view
215 -
download
0
Transcript of Generalization. Example CachPaymentCreditPaymentCheckPayment Paymentamount sale Attribute...
ExampleExample
CachCachPaymentPayment
CreditCreditPaymentPayment
CheckCheckPaymentPayment
PaymentPayment
amountamount
salesale
AttributeAttribute
RelationshipRelationship
Each sub class inherit the attribute and RelationshipEach sub class inherit the attribute and Relationship in super classin super class
Representing GeneralizationRepresenting Generalization• GeneralizationGeneralization
• Abstraction of common features among Abstraction of common features among multiple classes, as well as their relationships, multiple classes, as well as their relationships, into a more general classinto a more general class
• SubclassSubclass• A class that has been generalizedA class that has been generalized
• SuperclassSuperclass• A class that is composed of several generalized A class that is composed of several generalized
subclassessubclasses
A.3A.3
Is – a RuleIs – a Rule
• All the members of sub type set must be All the members of sub type set must be member of their super type setmember of their super type set
• In In natural language this can usually be natural language this can usually be infomally tested by forming the statementinfomally tested by forming the statement
• Subtype is a Super typeSubtype is a Super type
Representing GeneralizationRepresenting Generalization• DiscriminatorDiscriminator
• Shows which property of an object class is being Shows which property of an object class is being abstracted by a generalization relationshipabstracted by a generalization relationship
• InheritanceInheritance• A property that a subclass inherits the features from A property that a subclass inherits the features from
its superclassits superclass• Abstract ClassAbstract Class
• A class that has no direct instances, but whose A class that has no direct instances, but whose descendents may have direct instancesdescendents may have direct instances
• Concrete ClassConcrete Class• A class that can have direct instancesA class that can have direct instances
A.5A.5
Representing AggregationRepresenting Aggregation• AggregationAggregation
• A part-of relationship between a component object A part-of relationship between a component object and an aggregate objectand an aggregate object
• Example: Personal computerExample: Personal computer• Composed of CPU, Monitor, Keyboard, etcComposed of CPU, Monitor, Keyboard, etc
A.8A.8
Characteristics of Good DesignCharacteristics of Good Design
• Component independenceComponent independence• High cohesionHigh cohesion• Low couplingLow coupling
• Exception identification and handlingException identification and handling• Fault prevention and fault toleranceFault prevention and fault tolerance
Slide 11
CouplingCoupling
• The interdependence or interrelationships of The interdependence or interrelationships of the modulesthe modules
• Interaction couplingInteraction coupling• Relationships with methods and objects Relationships with methods and objects
• through message passingthrough message passing
Coupling criteriaCoupling criteria
SizeSize
- refers to the number of connections between - refers to the number of connections between modules, it is less work to connect other modules modules, it is less work to connect other modules to a module with a smaller interfaceto a module with a smaller interface
Coupling: Degree of dependence Coupling: Degree of dependence among componentsamong components
No dependencies Loosely coupled-some dependencies
Highly coupled-many dependencies
High coupling makes modifying parts of the system difficult, e.g., modifying a component affects all the components to which the component is connected.
Levels of couplingLevels of coupling
Content Coupling
2.Common Coupling
3.Control Coupling
4.Stamp Coupling
5.Data Coupling
Uncoupled
High CouplingHigh Coupling
Low CouplingLow Coupling
Slide 15
Types of Interaction CouplingTypes of Interaction CouplingLevelLevel TypeType DescriptionDescription
GoodGood No Direct CouplingNo Direct Coupling Methods don't call each otherMethods don't call each other
DataData Calling method passes object, called method uses the entire objectCalling method passes object, called method uses the entire object
StampStamp Calling method passes object, called method uses only part of the objectCalling method passes object, called method uses only part of the object
ControlControl Calling method passes a control variable whose value controls the execution of Calling method passes a control variable whose value controls the execution of the called methodthe called method
Common or GlobalCommon or Global Methods refer to a "global data area" that is outside of the individual objectsMethods refer to a "global data area" that is outside of the individual objects
BadBad Content or Content or PathologicalPathological
A method of one object refers to the hidden part of another object.A method of one object refers to the hidden part of another object.
Content couplingContent coupling
• Definition: One component references Definition: One component references contents of anothercontents of another
• Example:Example:• Component directly modifies another’s dataComponent directly modifies another’s data• Component refers to local data of another Component refers to local data of another
component in terms of numerical displacement component in terms of numerical displacement • Component modifies another’s code, e.g., jumps into Component modifies another’s code, e.g., jumps into
the middle of a routinethe middle of a routine
Example of Content Coupling-1Example of Content Coupling-1
Part of program handles lookup for customer.Part of program handles lookup for customer.
When customer not found, component adds customer by When customer not found, component adds customer by directly modifying the contents of the data structure directly modifying the contents of the data structure containing customer data.containing customer data.
Example of Content Coupling-2Example of Content Coupling-2
Part of program handles lookup for customer.Part of program handles lookup for customer.When customer not found, component adds customer by When customer not found, component adds customer by directly modifying the contents of the data structure directly modifying the contents of the data structure containing customer data.containing customer data.
Improvement:Improvement:When customer not found, component calls the When customer not found, component calls the AddCustomer() method that is responsible for AddCustomer() method that is responsible for maintaining customer data.maintaining customer data.
Common Coupling Common Coupling
• Definition: Two components share dataDefinition: Two components share data• Global data structuresGlobal data structures• Common blocksCommon blocks
• Usually a poor design choice becauseUsually a poor design choice because• Lack of clear responsibility for the dataLack of clear responsibility for the data• Reduces readabilityReduces readability• Difficult to determine all the components that affect a data Difficult to determine all the components that affect a data
element (reduces maintainability)element (reduces maintainability)• Difficult to reuse componentsDifficult to reuse components• Reduces ability to control data accessesReduces ability to control data accesses
Example-1Example-1
Each source process writes directly to global data store. Each sink Each source process writes directly to global data store. Each sink process reads directly from global data store.process reads directly from global data store.
Process control component maintains current data about state of operation. Gets data from multiple sources. Supplies data to multiple sinks.
Example-2Example-2
Each source process writes directly to global data store. Each source process writes directly to global data store. Each sink process reads directly from global data store.Each sink process reads directly from global data store.ImprovementImprovement
Data manager component is responsible for data in data Data manager component is responsible for data in data store. Processes send data to and request data from data store. Processes send data to and request data from data manager.manager.
Process control component maintains current data about state of operation. Gets data from multiple sources. Supplies data to multiple sinks.
Control CouplingControl Coupling
• Definition: Component passes control Definition: Component passes control parameters to coupled componentsparameters to coupled components..
• May be either good or bad, depending on May be either good or bad, depending on situation. situation. • Bad when component must be aware of internal Bad when component must be aware of internal
structure and logic of another modulestructure and logic of another module• Good if parameters allow factoring and reuse of Good if parameters allow factoring and reuse of
functionalityfunctionality
ExampleExample
• AcceptableAcceptable: Module p calls module q and q passes : Module p calls module q and q passes back flag that says it cannot complete the task, then q back flag that says it cannot complete the task, then q is passing datais passing data
• Not AcceptableNot Acceptable:: Module p calls module q and q passes Module p calls module q and q passes back flag that says it cannot complete the task and, as back flag that says it cannot complete the task and, as a result, writes a specific message.a result, writes a specific message.
Stamp CouplingStamp Coupling
• One component passes more data then One component passes more data then needed to another needed to another
void swap(int v[], int i, int j);void swap(int v[], int i, int j);
double calcsalary(Employee& e);double calcsalary(Employee& e);
● ● Often involves records (structs) with lots of Often involves records (structs) with lots of fieldsfields
● ● Entire record is passed, but only a few fields Entire record is passed, but only a few fields are usedare used
Example-1Example-1
The print routine of the customer billing accepts a The print routine of the customer billing accepts a customer data structure as an argument, parses it, and customer data structure as an argument, parses it, and prints the name, address, and billing information.prints the name, address, and billing information.
Customer billing system
Example-2Example-2
The print routine of the customer billing accepts a The print routine of the customer billing accepts a customer data structure as an argument, parses it, and customer data structure as an argument, parses it, and prints the name, address, and billing information.prints the name, address, and billing information.
ImprovementImprovementThe print routine takes the customer name, address, The print routine takes the customer name, address, and billing information as an argument.and billing information as an argument.
Customer Billing System
Data CouplingData Coupling
• Definition: Two components are data coupled if Definition: Two components are data coupled if there are homogeneous data itemsthere are homogeneous data items..
• Every argument is simple argument or data Every argument is simple argument or data structure in which all elements are usedstructure in which all elements are used
• Good, if it can be achieved. Good, if it can be achieved. • Easy to write contracts for this and modify Easy to write contracts for this and modify
component independently. component independently.
Key Idea in Object-Oriented Key Idea in Object-Oriented ProgrammingProgramming
• Object-oriented designs tend to have low Object-oriented designs tend to have low coupling.coupling.
CohesionCohesion
• Definition: The degree to which all elements of a Definition: The degree to which all elements of a component are directed towards a single task and all component are directed towards a single task and all elements directed towards that task are contained in a elements directed towards that task are contained in a single componentsingle component..
• Internal glue with which component is constructedInternal glue with which component is constructed• All elements of component are directed toward and All elements of component are directed toward and
essential for performing the same taskessential for performing the same task• High is goodHigh is good
Slide 30
CohesionCohesion• ““Single-mindedness of a module”Single-mindedness of a module”• Method cohesionMethod cohesion
• A method should do just a single taskA method should do just a single task
• Class cohesionClass cohesion• A class should represent just one thingA class should represent just one thing
• Generalization/specialization cohesionGeneralization/specialization cohesion• Addresses inheritanceAddresses inheritance• Should represent "a-kind-of" or "is-a"Should represent "a-kind-of" or "is-a"
Levels of cohesionLevels of cohesion
7.Functional
7.Informational
5.Communicational
4.Procedural
3.Temporal
2.Logical
1.Coincidental
High CohesionHigh Cohesion
Low CohesionLow Cohesion
Slide 32
Types of Method CohesionTypes of Method CohesionLevelLevel TypeType DescriptionDescription
GoodGood FunctionalFunctional A method performs a single taskA method performs a single task
SequentialSequential Method performs two tasks, the output of the first is the input of the Method performs two tasks, the output of the first is the input of the secondsecond
CommunicationalCommunicational Method combines two functions that use the same attributes (calc current Method combines two functions that use the same attributes (calc current and final GPA)and final GPA)
ProceduralProcedural Method supports many loosely related functions (calc current GPA, print, Method supports many loosely related functions (calc current GPA, print, calc final GPA, print)calc final GPA, print)
Temporal or ClassicalTemporal or Classical Method supports multiple functions related in time (initialize all variable, Method supports multiple functions related in time (initialize all variable, print all reports)print all reports)
LogicalLogical Method supports many functions controlled by a passed control variableMethod supports many functions controlled by a passed control variable
BadBad CoincidentalCoincidental Method's purpose cannot be determined, or it supports multiple unrelated Method's purpose cannot be determined, or it supports multiple unrelated functionsfunctions
Slide 33
Types of Class CohesionTypes of Class CohesionLevelLevel TypeType DescriptionDescription
GoodGood IdealIdeal Class has none of the mixed cohesionsClass has none of the mixed cohesions
Mixed-RoleMixed-Role Class has some attributes that relate to other classes on the same layer, but the Class has some attributes that relate to other classes on the same layer, but the attributes are unrelated to the semantics of the classattributes are unrelated to the semantics of the class
Mixed-Mixed-DomainDomain
Class has some attributes that relate to classes on a different layer.Class has some attributes that relate to classes on a different layer.
WorseWorse Mixed-Mixed-InstanceInstance
Class represents two different types of objects. Should be decomposed into two Class represents two different types of objects. Should be decomposed into two classes.classes.
Coincidental Cohesion Coincidental Cohesion
• Definition: Parts of the component are only Definition: Parts of the component are only related by their location in source coderelated by their location in source code
• Elements needed to achieve some Elements needed to achieve some functionality are scattered throughout the functionality are scattered throughout the system.system.
• AccidentalAccidental• Worst formWorst form
ExampleExample
• Print next linePrint next line• Reverse string of characters in second Reverse string of characters in second
argumentargument• Add 7 to 5Add 7 to 5thth argument argument• Convert 4Convert 4thth argument to float argument to float
Logical CohesionLogical Cohesion
• Definition: Elements of componentDefinition: Elements of component are related are related logically and not functionallylogically and not functionally..
• Several logically related elements are in the Several logically related elements are in the same component and one of the elements is same component and one of the elements is selected by the client component.selected by the client component.
Example-1Example-1
• A component reads inputs from tape, disk, and A component reads inputs from tape, disk, and network. All the code for these functions are in the network. All the code for these functions are in the same component. same component.
• Operations are related, but the functions are Operations are related, but the functions are significantly different.significantly different.
Example-2Example-2
• A component reads inputs from tape, disk, and A component reads inputs from tape, disk, and network. All the code for these functions are in the network. All the code for these functions are in the same component. Operations are related, but the same component. Operations are related, but the functions are significantly different.functions are significantly different.
ImprovementImprovement• A device component has a read operation that is A device component has a read operation that is
overridden by sub-class components. The tape overridden by sub-class components. The tape sub-class reads from tape. The disk sub-class sub-class reads from tape. The disk sub-class reads from disk. The network sub-class reads from reads from disk. The network sub-class reads from the network.the network.
Temporal Cohesion Temporal Cohesion
• Definition: Elements of a component are Definition: Elements of a component are related by timing. related by timing.
• Difficult to change because you may have to Difficult to change because you may have to look at numerous components when a change look at numerous components when a change in a data structure is made.in a data structure is made.
• Increases chances of regression faultIncreases chances of regression fault• Component unlikely to be reusable.Component unlikely to be reusable.
Example-1Example-1
• A system initialization routine: this routine contains A system initialization routine: this routine contains all of the code for initializing all of the parts of the all of the code for initializing all of the parts of the system. Lots of different activities occur, all at init system. Lots of different activities occur, all at init time.time.
Example-2Example-2
• A system initialization routine: this routine contains all A system initialization routine: this routine contains all of the code for initializing all of the parts of the system. of the code for initializing all of the parts of the system. Lots of different activities occur, all at init time.Lots of different activities occur, all at init time.
ImprovementImprovement• A system initialization routine sends an initialization A system initialization routine sends an initialization
message to each component.message to each component.• Each component initializes itself at component Each component initializes itself at component
instantiation time.instantiation time.
Procedural CohesionProcedural Cohesion
• Definition: Elements of a component are Definition: Elements of a component are related only to ensure a particular order of related only to ensure a particular order of execution.execution.
• Actions are still weakly connected and unlikely Actions are still weakly connected and unlikely to be reusableto be reusable
ExampleExample
......
Read part number from Read part number from data basedata base
update repair record on update repair record on maintenance file.maintenance file.
......
• May be useful to abstract May be useful to abstract the intent of this the intent of this sequence. Make the data sequence. Make the data base and repair record base and repair record components handle components handle reading and updating. reading and updating. Make component that Make component that handles more abstract handles more abstract operation.operation.
Communicational CohesionCommunicational Cohesion
• Definition: Module performs a series of actions Definition: Module performs a series of actions related by a sequence of steps to be followed related by a sequence of steps to be followed by the product and all actions are performed by the product and all actions are performed on the same dataon the same data
ExampleExample
• Update record in data Update record in data base and send it to the base and send it to the printer.printer.
• database.Update database.Update (record).(record).
• record.Print().record.Print().
Sequential CohesionSequential Cohesion• The output of one component is the input to The output of one component is the input to
another.another.• Occurs naturally in functional programming Occurs naturally in functional programming
languageslanguages• Good situationGood situation
Informational CohesionInformational Cohesion
• Definition: Module performs a number of actions, Definition: Module performs a number of actions, each with its own entry point, with independent code each with its own entry point, with independent code for each action, all performed on the same data.for each action, all performed on the same data.
• Different from logical cohesionDifferent from logical cohesion• Each piece of code has single entry and single exitEach piece of code has single entry and single exit• In logical cohesion, actions of module intertwinedIn logical cohesion, actions of module intertwined
• ADT and object-oriented paradigm promoteADT and object-oriented paradigm promote
Functional CohesionFunctional Cohesion
• Definition: Every essential element to a single Definition: Every essential element to a single computation is contained in the component.computation is contained in the component.
• Every element in the component is essential to Every element in the component is essential to the computation.the computation.
• Ideal situation.Ideal situation.
Cohesion in codingCohesion in coding
refers to the degree to which component’s refers to the degree to which component’s instructions are functionally related instructions are functionally related
Levels of cohesionLevels of cohesion
Coincidental cohesionCoincidental cohesion
occurs when the operations in a routine have no occurs when the operations in a routine have no discernable relationship to each otherdiscernable relationship to each other
Levels of cohesion - coincidentalLevels of cohesion - coincidental
FUNCTION A
FUNCTION C
FUNCTION B
FUNCTION D
FUNCTION F
functions have little or functions have little or no relationship to one no relationship to one anotheranother
Levels of cohesion - coincidentalLevels of cohesion - coincidental
multiple completely unrelated actionsmultiple completely unrelated actions
short printNextLine(String inStr, short x, short y) {short printNextLine(String inStr, short x, short y) {
System.out.println(inStr);System.out.println(inStr);
resetScreen();resetScreen();
return x+y;return x+y;
}}
Can you tell what printNextLine intend to do?Can you tell what printNextLine intend to do?
Levels of cohesionLevels of cohesion
Logical cohesionLogical cohesion
occurs when several logically related operations occurs when several logically related operations are stuffed into the same module and only one of are stuffed into the same module and only one of the operations is selectedthe operations is selected
Levels of cohesion - logicalLevels of cohesion - logical
FUNCTION A
FUNCTION C
FUNCTION B
logic
functions appear to be functions appear to be related because they fall related because they fall into the same logical into the same logical class of function (they class of function (they perform a set of related perform a set of related actions)actions)
Levels of cohesion - logicalLevels of cohesion - logical
a series of related actions, one is selected by the callera series of related actions, one is selected by the caller
short eval(short opCode, short x[], short y[]) {short eval(short opCode, short x[], short y[]) {
short m1,m2;short m1,m2;
switch (opCode){switch (opCode){
case 1 : m1=max(x); return m1;case 1 : m1=max(x); return m1;
case 2 : m1=max(x); m2=max(y); return (m1>m2?m1:m2);case 2 : m1=max(x); m2=max(y); return (m1>m2?m1:m2);
case 3 : m1=min(x); return m1;case 3 : m1=min(x); return m1;
case 4 : m1=min(x); m2=min(y); return (m1<m2?m1:m2);case 4 : m1=min(x); m2=min(y); return (m1<m2?m1:m2);
default: return 0;default: return 0;
}}
}}
Levels of cohesionLevels of cohesion
Temporal cohesionTemporal cohesion
occurs when operations are combined into a occurs when operations are combined into a module because they are all done at the same module because they are all done at the same timetime
Levels of cohesion - temporalLevels of cohesion - temporal
TIME TO
TIME TO + 2X
TIME TO + X
functions are grouped functions are grouped together because of together because of “time” (actions related “time” (actions related in time)in time)
Levels of cohesion - temporalLevels of cohesion - temporal
a series of actions related in timea series of actions related in time
void init() {void init() {
openAccountDB();openAccountDB();
openTransactionDB();openTransactionDB();
resetTransactionCount();resetTransactionCount();
System.out.println(“Balance update in progress…“);System.out.println(“Balance update in progress…“);
return;return;
}}
Levels of cohesionLevels of cohesion
Procedural cohesionProcedural cohesion
occurs when operations in a module are done in a occurs when operations in a module are done in a specified order, the operations in procedural specified order, the operations in procedural cohesion do not share the same datacohesion do not share the same data
Levels of cohesion - proceduralLevels of cohesion - procedural
FUNCTION A
FUNCTION C
FUNCTION B
functions accomplish functions accomplish different tasks, yet have different tasks, yet have been combined because been combined because the actions correspond the actions correspond to the sequence of steps to the sequence of steps in some operationin some operation
Levels of cohesion - proceduralLevels of cohesion - procedural
a series of actions related by sequence of steps to be a series of actions related by sequence of steps to be followed by the result (a series of actions sharing followed by the result (a series of actions sharing sequence of steps)sequence of steps)
void sumOfTran() {void sumOfTran() {
DB[0]=0; DB[0]=0;
CR[0]=0;CR[0]=0;
for (short i=1; i<= noAcct; i++){for (short i=1; i<= noAcct; i++){
DB[0] += DB[i]; DB[0] += DB[i];
CR[0] += CR[i];CR[0] += CR[i];
}}
return;return;
}}
Levels of cohesionLevels of cohesion
Communicational cohesionCommunicational cohesion
occurs when a sequence of steps, related to some occurs when a sequence of steps, related to some operation, operate on the same dataoperation, operate on the same data
Levels of cohesion - Levels of cohesion - communicationalcommunicational
FUNCTION A
FUNCTION C
FUNCTION B
functions perform functions perform operations on the same operations on the same body of data (data is body of data (data is passed between passed between functions)functions)
Levels of cohesion - Levels of cohesion - communicationalcommunicational
a series of actions related by sequence of steps to be a series of actions related by sequence of steps to be followed by the product followed by the product andand if all the actions are if all the actions are performed on the same data (a procedural cohesion performed on the same data (a procedural cohesion but on the same data)but on the same data)
short stackPop2() { short stackPop2() {
short next = stack[top--];short next = stack[top--];
short nextNext = stack[top--];short nextNext = stack[top--];
return (next+nextNext); return (next+nextNext);
} }
Levels of cohesionLevels of cohesion
Informational cohesionInformational cohesion
occurs when a module contains independent occurs when a module contains independent actions that must be performed on the same data actions that must be performed on the same data structure (gives structure (gives the ability to "package" all of the the ability to "package" all of the functionality that relates to a given data structurefunctionality that relates to a given data structure))
Levels of cohesion - informationalLevels of cohesion - informational
FUNCTION A
FUNCTION C
FUNCTION B
functions are related by functions are related by the fact that they the fact that they perform actions on a perform actions on a single data structuresingle data structure
Levels of cohesion - informationalLevels of cohesion - informational
a number of actions, each with its own entry point and a number of actions, each with its own entry point and independent code, all performed on the same dataindependent code, all performed on the same data
short op(char opCode, short x, short y) {short op(char opCode, short x, short y) {
switch (opCode){switch (opCode){
case ’+’ : return (x+y); case ’+’ : return (x+y);
case ’-’ : return (x-y); case ’-’ : return (x-y);
case ’*’ : return (x*y); case ’*’ : return (x*y);
case ’/’ : return (x/y); case ’/’ : return (x/y);
default: return 0;}default: return 0;}
}}
Levels of cohesionLevels of cohesion
Functional cohesionFunctional cohesion
strongest and best kind of cohesion – when a strongest and best kind of cohesion – when a module performs one and only one operationmodule performs one and only one operation
Levels of cohesion - functionalLevels of cohesion - functional
FUNCTION A, part 1
FUNCTION C, part 3
FUNCTION B, part 2
functions work functions work collectively to collectively to accomplish a single well-accomplish a single well-define actiondefine action
Levels of cohesion - functionalLevels of cohesion - functional
performs exactly one action or achieves a single goalperforms exactly one action or achieves a single goal
short sumOfArray(short number[]) {short sumOfArray(short number[]) {
short result = 0;short result = 0;
for (short i=0; i< number.len; i++)for (short i=0; i< number.len; i++)
result += number[i];result += number[i];
return result;return result;
}}
Dynamic Modeling:Dynamic Modeling:State DiagramsState Diagrams
• StateState• A condition during the life of an object during A condition during the life of an object during
which it satisfies some conditions, performs which it satisfies some conditions, performs some actions or waits for some eventssome actions or waits for some events
• Shown as a rectangle with rounded cornersShown as a rectangle with rounded corners
• State TransitionState Transition• The changes in the attribute of an object or in The changes in the attribute of an object or in
the links an object has with other objectsthe links an object has with other objects• Shown as a solid arrowShown as a solid arrow• Diagrammed with a guard condition and Diagrammed with a guard condition and
actionaction
• EventEvent• Something that takes place at a certain point Something that takes place at a certain point
in timein timeA.72A.72