370 likes | 564 Views
Object Interconnections. CMPS 2143. Object Interconnections. Past 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
E N D
Object Interconnections CMPS 2143
Object Interconnections • Past 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 dependency
Visibility • Characterization of names • or handles by which objects are accessed • Related 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’ methods • Apple Object Pascal: all instance variables are visible if class is visible
Dependency • Relates one object or class to another • If an object cannot exist meaningfully without another, it is dependent • A child class is almost always dependent on its parent class • Dependency can be more subtle though.
Coupling and Cohesion • Good modular design that requires • Low coupling • High cohesion • Coupling – describes the relationships between classes • Cohesion – describes the relationships of the members withina class • Well-designed classes • Should have a purpose • All elements should be associated with a single task
Varieties of Coupling (Worst to Best) • Internal Data Coupling • Instances of one class can directly modify instance variables in an instance of another class • Global Data Coupling • Two or more classes rely on some common global data structure • Solution – 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) Coupling • An instance of one class must perform operations in a fixed order, but that order is controlled elsewhere • When unavoidable, object assures ops performed in correct order • Component Coupling • An instance on a class has-a member data field that is an instance of another class • Ideally the relationship should be only one way • Examples: Set used a List and Bag used a Dictionary
Varieties of Coupling (Worst to Best) • Parameter Coupling • An 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 returned • Common, easy to see, easy to verify statically • Example: void List::insertInOrder (String s); • Will have to call String equals method • Subclass Coupling • Particular to OOP • Relationship a class has with its parent class
Varieties of Cohesion (Weakest to Best) • Coincidental • When elements of a class are grouped for no apparent reason • Often result of “modularizing” a large program arbitrarily • Logical • When there is a logical connection among elements, but no actual connection in either data or control • Example: Math class
Varieties of Cohesion (Worst to Best) • Temporal • When elements are bound together because they all must be used at approximately the same time • Example: program initialization or finalization • Communicational • When methods in a class are grouped because they all access the same I/O data or devices • Class acts as a “manager” of the data or device
Varieties of Cohesion (Worst to Best) • Sequential • When elements in a class are linked by the necessity to be activated in a particular order • Usually the result of avoiding sequential coupling • Functional • Desirable type of binding of elements when they all relate to the performance of a single function • Data • Class defines a set of data values and makes public methods that manipulate the data abstraction
Give-a-ways for estimate degree of coupling • Purpose statement of class is a compound sentence • Containing commas or more than one verb • Probably sequential or communicational coupling • Purpose statement of class refers to time • First, next, then, after, when, start • Probably sequential or temporal coupling • Purpose statement does not contain a single, specific object following a verb • Edit all data logical binding • Edit source data functional binding • Purpose statement contains words initialize, clean-up • Probably temporal binding
Style Guidelines for Modular Programming • Style guidelines range from abstract to direct • “Modules should exhibit low coupling and high cohesion” • “No 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 Demeter • In any method, M, in a class, C, only methods defined by the following classes may be used • The 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 Form • In a method, M, permitted to access or send messages only to the following objects • Arguments associated with method M (including self) class C { public void M (Someclass s) { s.somemethod();} } • Instance variables for the receiver of the method • This data members and parent data members • Allows for protected • Global variables • Temporary variables created inside the method
Law of Demeter – Strong Form • In a method, M, permitted to access or send messages only to the following objects • Arguments associated with method M (including self) • Instance variables defined in the class containing M • Cannot access instance variables of parent classes except through their accessor functions • Does not allow for protected • Eliminates subclass coupling • Global variables • Temporary variables created inside the method
Class-level versus Object-level Visibility • Classes can have multiple instances • Class-level visibility • C++ control visibility on this level • Treats all instances of a class in the same manner • Provides range of visibility controls • Even with private data fields, an instance of a class permitted access to data fields in other instances of class • Example: Copy constructors
Class-level versus Object-level Visibility • Object-level visibility • Smalltalk – no object is permitted access to inner state of another object, even if they are instances of the same class
Subclass clients and User clients • Subclass clients can access parent’s public and protected members • Assuming language has class visibility and protected access modifier • User clients can only access public members of another class
Control of Access and Visibility • Smalltalk • Instance variables are always private • Methods are always public • Java • public and private refers to class, not instance of class • Sibling members of the same class permitted to access each other’s private data fields. • protected refers to package • A protected feature accessible anywhere within package • final • A final class can not be subclassed • A final instance variable cannot be assigned to
Control of Access and Visibility • C++ • Has public, private and protected • Instance variables and methods are by default private • Access modifiers define properties of class, not of instances • Sibling instances (other objects of same class) may access each other’s member data • Example: operator + for ComplexNumber • Weak form of Law of Demeter supported by protected • Strong form of Law supported by private
Control of Access and Visibility • C++ • public vs private class inheritance (default is public) • public class inheritance corresponds to inheritance for specialization (that is subclass is subtype) • Supports principle of substitution • Can use polymorphism • private class inheritance corresponds to inheritance for construction
Friendship • Another 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 friends • Friend functions • Friend classes
Friendship • Friendship 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 Functions • To 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 definition’s body and do not precede them with any access specifier
Friend Function Example class Count { friend void setX(Count & c, intval); public: Count(): x(0) {} void print() const {cout<<x<<endl;} private: int x; };
Friend Function Example void setX(Count & c, intval){ c.x=val;} void main(){ Count counter; counter.print(); setX(counter, 8); counter.print(); }
Friend Class Example #include <iostream> using namespace std; class A { friend class B; int x; public: A(): x(0){} intget() const{return x; } void set(int y){x=y; } };
Friend Class Example class B { int z; public: void set(A & a) {a.x=20; } intget() const {return z; } };
Friend Class Example void main(){ A a1; B b1; b1.set(a1); cout<<a1.get()<<endl; }
Other friend examples • Prototypes for overloaded << and >> friend functions can be declared inside of ComplexNumber class (but they are NOT methods) • Can put the definition in the .cpp file, BUT do NOT precede it with friend ComplexNumber:: • class Node can be a friend class of LinkedList • Can put it in Node.h and Node.cpp files now
Concerns about friends • Powerful tool • Easy to abuse • Introduce data couplings • Avoid them! Use them ONLY when no other tool will work.
C++ Namespaces and Java Packages • Reduce proliferation of global names • Static can limit scope of a name to a single file • Use Namespaces and Packaged when name is needed in two or more files and avoiding global variables
C++ Namespaces namespace myLibrary { int x; class A { }; class B { }; } using namespace myLibrary; using myLibary::B; myLibrary::A anA;
Java Packages package myPackage; //first statement //in the file import myPackage.*; import myPackage.B; myPackage.AanA = new myPackage.A();
Intentional Dependency • Most programmers attempt to avoid dependency • Some situations, it is unavoidable Example: • A viewer (such as a graphical display component) associated with underlying data component (or model) • Every time values change, the display needs to be updated • Can use a dependency manager as a go-between • Model need only know about the dependency manager • Viewers “register” with dependency manager • When model changes, it sends a single message to dependency manager…who subsequently notifies all dependents • COMMON DESIGN PATTERN Model-View-Controller
Study • pg. 461: 2, 9-14