object interconnections cmps 2143. object interconnections past few chapters: focused on individual...

Download Object Interconnections CMPS 2143. Object Interconnections Past few chapters: focused on individual classes in isolation or classes in parent/child relationships

Post on 13-Jan-2016




0 download

Embed Size (px)


Template Classes

Object InterconnectionsCMPS 2143Object InterconnectionsPast few chapters: focused on individual classes in isolation or classes in parent/child relationships

This chapter: focused on relationships between groups of classes or objects working together

Concern is on visibility and dependencyVisibilityCharacterization of namesor handles by which objects are accessedRelated term is scope of an identifier

Visibility is related to connectedness If an identifier is not visible, it cannot be accessed

Smalltalk for example: identifiers cannot be accessed/modified outside the class, without calling one of the class methodsApple Object Pascal: all instance variables are visible if class is visibleDependencyRelates one object or class to anotherIf an object cannot exist meaningfully without another, it is dependentA child class is almost always dependent on its parent class

Dependency can be more subtle though.Coupling and CohesionGood modular design that requiresLow coupling High cohesion

Coupling describes the relationships between classesCohesion describes the relationships of the members within a class

Well-designed classes Should have a purposeAll elements should be associated with a single taskVarieties of Coupling (Worst to Best)Internal Data CouplingInstances of one class can directly modify instance variables in an instance of another class

Global Data CouplingTwo or more classes rely on some common global data structureSolution create another class to hold and manage this data

BOTH of these BAD because it complicates ability to understand class in isolation

Varieties of Coupling (Worst to Best)Control (or Sequence) CouplingAn instance of one class must perform operations in a fixed order, but that order is controlled elsewhereWhen unavoidable, object assures ops performed in correct order

Component CouplingAn instance on a class has-a member data field that is an instance of another classIdeally the relationship should be only one wayExamples: Set used a List and Bag used a DictionaryVarieties of Coupling (Worst to Best)Parameter CouplingAn instance of one class must invoke services (methods) from another and the only relationships are the number and type of parameters supplied and the type returnedCommon, easy to see, easy to verify staticallyExample: void List::insertInOrder (String s);Will have to call String equals method

Subclass CouplingParticular to OOPRelationship a class has with its parent classVarieties of Cohesion (Weakest to Best)CoincidentalWhen elements of a class are grouped for no apparent reasonOften result of modularizing a large program arbitrarily

LogicalWhen there is a logical connection among elements, but no actual connection in either data or controlExample: Math classVarieties of Cohesion (Worst to Best)TemporalWhen elements are bound together because they all must be used at approximately the same timeExample: program initialization or finalization

CommunicationalWhen methods in a class are grouped because they all access the same I/O data or devicesClass acts as a manager of the data or device

Varieties of Cohesion (Worst to Best)SequentialWhen elements in a class are linked by the necessity to be activated in a particular orderUsually the result of avoiding sequential coupling

FunctionalDesirable type of binding of elements when they all relate to the performance of a single function

DataClass defines a set of data values and makes public methods that manipulate the data abstraction

Give-a-ways for estimate degree of couplingPurpose statement of class is a compound sentenceContaining commas or more than one verbProbably sequential or communicational couplingPurpose statement of class refers to timeFirst, next, then, after, when, startProbably sequential or temporal couplingPurpose statement does not contain a single, specific object following a verbEdit all data logical bindingEdit source data functional bindingPurpose statement contains words initialize, clean-upProbably temporal bindingStyle Guidelines for Modular ProgrammingStyle guidelines range from abstract to directModules should exhibit low coupling and high cohesionNo method should contain more than 60 lines

Direct guidelines easier to follow, but they lull you into a false sense of security and direct attention away from real problem

Are there any good guidelines for OOP?Law of DemeterIn any method, M, in a class, C, only methods defined by the following classes may be usedThe instance variables classes of C (has-a relationships)class C { public void M ( ) { s.somemethod();} private SomeClass s;}

The argument classes of method M (including C)class C { public void M (Someclass s) { s.somemethod();}}

Law of Demeter Weak FormIn a method, M, permitted to access or send messages only to the following objectsArguments associated with method M (including self)class C { public void M (Someclass s) { s.somemethod();}}

Instance variables for the receiver of the methodThis data members and parent data membersAllows for protectedGlobal variablesTemporary variables created inside the method

Law of Demeter Strong FormIn a method, M, permitted to access or send messages only to the following objectsArguments associated with method M (including self)

Instance variables defined in the class containing MCannot access instance variables of parent classes except through their accessor functionsDoes not allow for protectedEliminates subclass coupling

Global variablesTemporary variables created inside the method

Class-level versus Object-level VisibilityClasses can have multiple instances

Class-level visibilityC++ control visibility on this levelTreats all instances of a class in the same mannerProvides range of visibility controlsEven with private data fields, an instance of a class permitted access to data fields in other instances of classExample: Copy constructorsClass-level versus Object-level VisibilityObject-level visibilitySmalltalk no object is permitted access to inner state of another object, even if they are instances of the same classSubclass clients and User clientsSubclass clients can access parents public and protected membersAssuming language has class visibility and protected access modifier

User clients can only access public members of another classControl of Access and VisibilitySmalltalkInstance variables are always privateMethods are always publicJavapublic and private refers to class, not instance of classSibling members of the same class permitted to access each others private data fields.protected refers to packageA protected feature accessible anywhere within packagefinalA final class can not be subclassedA final instance variable cannot be assigned to

Control of Access and VisibilityC++Has public, private and protectedInstance variables and methods are by default privateAccess modifiers define properties of class, not of instancesSibling instances (other objects of same class) may access each others member dataExample: operator + for ComplexNumberWeak form of Law of Demeter supported by protectedStrong form of Law supported by private

Control of Access and VisibilityC++public vs private class inheritance (default is public)

public class inheritance corresponds to inheritance for specialization (that is subclass is subtype)Supports principle of substitutionCan use polymorphism

private class inheritance corresponds to inheritance for construction

FriendshipAnother aspect of visibility in C++ is concept of a friend function.

Friends of a class are not members of the class, yet can access the non-public members of the class

A class can have two types of friendsFriend functionsFriend classes

FriendshipFriendship is granted, not taken-i.e. for class B to be a friend of class A, class A must explicitly declare that class B is its friend.Friendship is not symmetric. For example, if class A is a friend of class B, this does not necessarily mean that class B is also a friend of class A.Friendship is not transitive. For example if class A is a friend of class B and class B is a friend of class C, we cannot infer that class A is a friend of class C.

Friend FunctionsTo declare a function as friend of a class, precede the function prototype in the class definition with keyword friend.Member access notions of private, public etc. are not relevant to friend declaration, so friend declarations can be placed anywhere in a class definition.As a good programming practice, place all friendship declarations first inside the class definitions body and do not precede them with any access specifier

Friend Function Exampleclass Count{ friend void setX(Count & c, int val);

public:Count(): x(0) {}void print() const{cout


View more >