Class Design Principles

xiaoxiao2021-03-06  89

Oo Analysis and Design

8. Class Design Principles

Separation of Concerns Abstraction Accessors Law of Demeter Styles of Reuse Inheritance as Reuse Liskov's Principle of Substitution Is-a vs Has-a Slicing Polymorphism and Virtual Functions Containers Behaviour Restriction Foundation Classes Class Refactoring Formal Notions

Separation of Concerns One of the goals of the software architect is separation of concerns, that is, to break the problem into issues that are as independent (or orthogonal) as possible. The idea of ​​separation of concerns is that the less that issues interact, the easier it is to grapple with their solution. Concerns are intellectual encapsulations of issues. It may not necessarily be possible to localize the addressing of a concern into a single spot. Some concerns are diffused over the entire system. For example, instrumenting every method with entry and exit timing code. Such concerns are called aspects, and are associated with aspect-oriented programming. The goal of language and methodology designers is to at least localize the descriptions of concerns and their solutions, even if the actual solution is spread out Over the entire system. a reasonable Question to ask Is What Are The Kinds of Concerns That Object-Orientation Addresses Well, And What Other Kinds Is It Poor At. AB straction Abstraction is the architectural principle of hiding complexity inside a well-defined container, and accessing that complexity though a well-defined interface One way of thinking about abstraction is to consider what is being hidden Most abstraction involves two kinds of hiding..:

information hiding - hide how we represent the data control hiding - delegating the details of behaviour Modules, abstract data types, objects, systems, files, processes, and many other notions of computing are examples of using abstraction to hide complexity To be general,. we call any such kind of abstraction a unit, and the things inside a unit we call elements. A system is a collection of units. The two main measures of the quality of a collection of abstraction units are coupling and cohesion. Coupling is the measure of the strength of association established by a connection from one unit to another. Strong coupling complicates a system because understanding one unit requires understanding another. The goal is to reduce coupling as much as possible, which is accomplished by minimizing the relationships between elements not in Same unit. cohesion is the measure of the strength of a unit. cohesion can be measure, informally and nonlinearly, by . Asking why a collection of elements appears in a unit, that is, what binds them together Possible (but not exhaustive) kinds of binding, in increasing degree of cohesiveness, can be:

Coincidental - the elements are related only because they appear in the unit Logical -.. The elements are present in the unit because they appear together under some logical view of the system For example, they all have something to do with the user interface Under. a different view they may not be related temporal -. the elements are related because the are activated at roughly the same time For example, they are all initialized at once temporal binding is logical binding under a temporal view communicational -... the elements are together because they share some common repository of information Collaborative -. the elements of the unit are together because they collaborate to perform some process For example, all or portion of a workflow Functional -.. the elements of the unit are together because they collaborate to Perform Some Well-Defined Function. A Good Architecture Strives for Loose Coupling and Strong & Strong Cohesness. Acessors Instance Variables of Objects Should Always BE Private. Provide accessor functions to set and get the value of the instance variables. using accessors allows you to

restrict access to data, such as allowing only read access, to control access to data, such as not allowing a read when the data is locked, instrument access to data, such as keeping a log of who has accessed it, seamlessly use computed values or derived data as if it was an actual attribute. Law of Demeter One of the key measures of a design is how much one object needs to know about another object or the system context in order to operate. The Demeter project, of Karl Liebeeerherr and ian Holland, http://www.ccs.neu.edu/home/lieber/demeter, has identified some desireable properties associated with message dispatch. The idea is that you do not want to encode too many details of the class structure in the method implementations, otherwise when structure is changed, many methods will also have to be changed. In general, public methods of derived classes should invoke only their own private and public methods, or the public methods of their parents. This preserves encapsulation of the ir parents, and allows parent implementations to be changed without breaking the children A guideline for minimizing this kind of coupling is expressed by the Law of Demeter:. A supplier object to a method M is an object to which a message is sent in M. Law of Demeter: An object O in response to a message M should send messages only to the following preferred supplier objects: O itself, objects sent as arguments of message M, objects O creates as part of its reaction to message M, objects which are directly accessible instance variables of O, objects which provide global services to O. Styles of Reuse There are many ways in which existing designs and implementation can be reused in a different context Here is a simply taxonomy.:

Via Composition / Aggregation Composition (or aggregation) is achieved by using existing objects as parts of a new object. The new object contains instances of a previously defined class, that is, it owns the instances, and when the larger object is destroyed, so are all its contained parts. As an implementation concern, the parts can be contained by value in which case they are actually a part of the object, or by reference in which case they are pointed to by references in the larger object. We can distinguish two kinds of composition (has-a): Additive - in which the new object is the sum of its parts For example, an order containing a number of detail objects Projective - in which the purpose of the new object is to wrap an.. Existing Object in Order to Hide Some Behaviour and Expose Others. An Example Is The Square / Rectangle Problem That Follows. VIA Patterns Examples of Patterns:

templates - parameterized generation of new program elements (classes, algorithms, etc.) interfaces - allow many different implementations of the same abstraction references -.. allow deferred binding of data to the algorithm Rather than using an existing class, patterns are mechanisms for taking a general structure, parameterized by one of more abstract classes, and generating a specific instance. for example, container classes are typically generated by patterns because there is no type-safe way of constructing an abstract base-class for a container. This is true . even simple containers like arrays and lists Via Inheritance Inheritance is the reuse innovation of OO like all powerful tools, it is susceptible to misuse This is partly due to it being used in two ways..:

by extension in which derived classes obey the principle of substitution. That is, a derived class can always be used like its ancestors because the derived class extends the base classes functionality. A derived class is-a ancestor class. by exception in which derived classes limit the functionality of their ancestors in some way. in this case a derived class is not necessarily substitutable for an ancestor. This is often seen when representing catalogs, where descending the inheritance hierarchy results in more and more specialized classes. Polymorphism can only be fully Used on classes create as reuse when we we take a class c and construct a new class d from it, Possibly by Having D inherit from C, We Have To ask:

is class D augmenting the behaviour of C? is class D restricting the behaviour of C? or both? This is very important, as it affects class design considerably. Of course to answer this question we need a reasonably precise description of the behaviour of the class One way of doing this is to follow the philosophy of:. Design By Contract:. Every attribute and method within the class should be documented with pre-conditions, post-conditions, exceptional-conditions, invariants, and side-effects If possible , assertions about these should be incorporated into the code and left enabled in production releases Design Principle:.. You should try to build your class hierarchy so that factoring of parent classes does not affect interfaces and implementations of derived classes that is, derived classes should NOT LOOK ATHOW Their Ancestors Provide Services, But Only at The Interface To Those Services, and Should Not Explicitly Mention Where Services Are Located. Design PrinciPle: Do Not Use inheritance to reuse implementation (code). It should only be employed to reuse and extend functionality. Liskov's Principle of SubstitutionIf a class D is "just like" a class C except for extensions, then it should be possible to use a D object anywhere you AN Use An C Object. That IS, A Child Should Be Able To Be.com.

Design Your classes to Preserve this property unless do otherwise.

Design PrinciPle: Suppose Class D Is Derived from Class C. Then Derived Class D Is-a C. That IS, WhatVER An Object of Super-Class C can do, so shop an Object of sub-class D. The Principle of Substitution IS designed to preserve the relation that a derived class is-a class of the same kind as all of its ancestors Is-a vs Has-a Design Principle:.. Roles are acquired via attributes, not by subclassing.Full Size Consider this example The first diagram shows how a Person can be subclassed into Manager, Employee, or Student. This is the wrong way to assign a role. It implies that a person can only have one role, and can never change their role. The problem is that the inheritance hierarchy for Person is being confused with the inheritance hierarchy for Role. The second diagram is a better way. Now a resonable question is how does a person know what function they can do? That is, how do they know what the capabilities of their CURRENT ROLE IS? And if Some Other Object Needs a Person Wit H THOSE CAPABILITIES, HOW Do The Locate One? SLICING Suppose That Class D Is Derived from Class C. We can Think of D AS C. IN Terms of Data, D Has All The Data That C HAS, and possible more. In terms of methods, D can not hide any methods of C, and may have additional methods. In terms of existing methods of C, the only thing that D can do is to override them with its own versions. If x is An Object of Class D, THEN We can Slice X with respect to c, by Throwing Away All of the Extensions That Made Xa D, And Keeping Only The c Part. The result of the sliant is always an Object of class C.

Full Size Design Principle: Slicing an object with respect to a parent class C should still produce a well-formed object of class C. That is, the state invariants for D should imply the state invariants for C. Usage Warning: Even though D is -A C, You Must Be Careful. If you have an argument type tria is a c and you supply call by value, pointer, or reason. Watch out for the slash = Operator, IT CAN Make The LHS Inconsistent. Also, The = Operator is Never Virtual, IT Wouldn't Make Sense. For Example, Suppose Classes A, B Are Both Subclasses of Class C. Just Because An a is a c, And a B is a C, it does not mean you can assign a B object to an A object Without run-time type information you can not make a safe assignment Principle of substitution (again):.. Suppose that x is an object of class C, AND y is an Object of class d, and That x is a c slice of y. That IS, the c Parts of x and y Are Identical. Suppose That M Is A Method of class c.when it is legal to perform x.m, then since d is-a c, it will be legal to perform y.m. That IS

Preconditions for M in C IMPLY PRECONDITIONS for M in D

When Y.M is Performed Legally, THEN SINCE D IS-A C, THE C SLICE OF THE RESULD BE COMPATIBLE with THE Definition of M IN C. That IS

Postconditions for M in D Imply Postconditions for M in C

The objects of class C and D have state, and that state must be consistent with the invariants for the class. For class D to be substitutable for C requires that every operation of D preserve the invariants, not only for D, but as they are stated for C. Otherwise, it would be possible to put an object of class D into a state that was not possible for objects of class C, and substitution would be clearly impossible. Note that the C slice of yM need not be equivalent to xM , that is, doing something in D might generate a different result than in C, yet both satisfy the postconditions and maintain the invariants. For example, the operation M might have the postcondition that M increases the value of attribute d1. But M in D might increase it by 1, while M in C increases it by 2. in both cases, the invariant that d1 is positive is preserved. Also note that the principle of substitution is relative to the method M. There may be other methods that don ' T Obey Substitution, and these Should not be used polymorphically, or in circumstances where they might invalidate the invariants needed for substitution of other methods. Polymorphism and Virtual Functions Suppose that class D has been derived from C in a way that preserves substitution. Can a D be simply substituted for a C ? A sliced ​​D will certainly work as a C, but the effect of performing a method on the slice could be to make the object internally inconsistent. This is where you need virtual functions. Virtual functions achieve polymorphism by allowing any derived class to substitute for The base class.

All Methods of C Declared Virtual, Except Constructionors. All Methods of C Correctly Implement In Derived D. WHENEVER A D IS SUBSTITED For A C, THE D '

ness is preserved, and the corresponding virtual method of D is executed Virtual functions must have the same signatures An abstract base class, that is, one that defines an interface without implementing anything, has all methods pure virtual Design Principle:... If one method is virtual in a class, all of them should probably be virtual, including the destructors (Except for those methods that would never be overridden by a derived class.) Design Principle:. Do not, if at all possible, inspect an object to . determine its class Sometimes this is necessary, for example when building a wrapper class that has to inspect the kind of class provided to it in order to achieve the correct transformation of the interface -. this typically occurs with generic callback mechanisms Containers We frequently need To Collect Objects Together Into Conta Conta Containers. a CONTAINER for Class C Is a class whose purpose is to contain Objects from Class C or ITS Descendents. Design PrinciPle: Container Classes should be generated by template substitution, not inheritance. Suppose D is a subclass of C. A container for D is not a container for C. That is, containers violate the principle of substitution. For example, although the apple class is-a fruit Class, And A Bag Containing Apples IS-A Bag Containing Fruit, An Apple Bag Is Not A Fruit Bag --- IF IT WAS, You Could Put A Banana Into It. Behaviour Restriction Design Principle: IF A New Class D Is Like AN existing class C, but with restrictions on its behaviour, then D should not be derived from C via inheritance Why:... because restriction violates the principle of substitution Instead, class D should contain an instance of class C (aggregation) Most of D '

s behaviour is directly delegated to C, with only a few methods being suitably restricted.Full Size Example: A square is not a rectangle Suppose that we have a class Rectangle that has two attributes l, w and a method SetSize (l, w. ) which sets l and w. It is tempting to derive a new class Square, that is like a Rectangle except that it overrides SetSize (l, w) to only allow cases where l = w. This violates the principle of substitution, because the pre-condition for calling SetSize on a Rectangle does not imply the pre-condition for calling SetSize on a Square. It is better to define Square in terms of containing a Rectangle, and giving Square a method SetWidth (x) which calls SetSize (x , x) on its contained Rectangle. All other properties of Square that are Rectangle-ish, such as its color, or position in space, can be delegated to the contained Rectangle. If both Square and Rectangle are subclasses of a graphics Figure, then The Draw Method for Square Is Delegated to The Draw Method for ITS contained Rectangle Design Principle:. If a derived class does not use data or methods in the parent class, you should check if this is an instance of behaviour restriction Foundation Classes Consider the following inheritance diagram.

Full Size If C is being used as a foundation class, then the derived classes are always going to be used on their own. That is, they will always be used in situations where their type will be declared as a D or E. We will never want to manipulate them abstractly as C's. In this case, the substitution rule could be relaxed. A class derived from C is free to redefine the methods of C as it sees fit. Usually the purpose of C is to provide some basic services that need to be extended or modified a bit. If you do violate the substitution rule, it is important that the resulting D and E classes promise never to be used in a situation where they might be asked to substitute for a C. Slicing could make the internal state inconsistent. This said, you can still argue that foundation classes obey the substitution rule. Simply set the pre-condition of method M in C to be false, and the post-condition of M in C to be true. The pre in C, IE False, Always Implies Any Possible Pre in D. Similarly, P OST I.E. POST I.E. POST IN C. Because The Precondition of M IN C Is Always False, IT IS NEVER Supposed To Be Called ON A C, AND Respects the promise above. Class Refactoring

Full Size Consider the following inheritance diagram. The idea is that the base Shape class provides an interface for manipulating shapes. The original class has a very flat inheritance hierarchy, with every basic shape descending from the main shape. In an attempt to generalize, squares were derived from rectangles, and ellipses from circles. This was ok so long as the original size of the shape was set on creation time, and only altered by magnification later. But a new method ChangeAspect was added to allow rectangles and ellipses to have their aspect ratios changed. This broke the polymorphism, because now squares and circles do not obey the principle of substitution. Often a method can be moved up or down the hierarchy to preserve substitution. So a third refactoring was done to devide the shapes into reshapable and NOT. THIS Means That Not Every Shape Can Haves Impossible To Polymorphical Operate ON Shapes with Respect To Changing Their aspect ratio (this affects the graphics editing menu for example). Impossible, that is, unless we introduce a method, IsStretchable, in the base class and make the pre-condition of ChangeAspect to be that IsStretchable is true. Then the polymorphic operation becomes GUARDED WITH A TESTABLE PRE-CONDITABILITABLE PREERVED BY PROVIDING A TESTABLE preserved by Provinceing a testable preserved by provike a testable preserved by provike.

Full Size Another kind of refactoring can occur along service lines. For example, the shape class above might be used to construct a 2 dimensional model of a system, for example a UML diagram. Using components like the shape class above, the model has two roles: to maintain the mathematical stucture that describes the system, and also to render the visual representation of the system This means that the model and view roles are tightly coupled In particular, an element of the model (eg a class description) is.. tied to a graphical icon (like a square). But in many cases, one wants to interact with the model non-graphically. for example a code analyser might want to construct a UML model of an existing system for reverse engineering purposes. Service refactoring in this case means to separate out the two roles into different services:. one for maintaining the model, another for providing a view of the model This way, many different views can be generated of the model, while preserving the core class structure Formal Notions One can describe the relationships discussued above using the notions of category theory In brief:.. Reuse NotionCategory Theory Notioncompositionco-varianceinheritancecontra-variancetemplatesin-variance

8. Class Design PrincipleSAL / DAC / GHFY / 2.2.3

转载请注明原文地址:https://www.9cbs.com/read-122570.html

New Post(0)