14 面向?qū)ο蟮哪K化_第1頁(yè)
14 面向?qū)ο蟮哪K化_第2頁(yè)
14 面向?qū)ο蟮哪K化_第3頁(yè)
14 面向?qū)ο蟮哪K化_第4頁(yè)
14 面向?qū)ο蟮哪K化_第5頁(yè)
已閱讀5頁(yè),還剩56頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、計(jì)算與軟件工程II Ch14 “面向?qū)ο蟆钡哪K化丁二玉南京大學(xué)軟件學(xué)院Modulen A piece of codeq Methodsq Classq Module(package)n Coupling: among piecesn Cohesion: internal a pieceWhats the difference between Structuralmethods and OO methodsn Couplingq Coupling is the measure of the strength of association established by a connection

2、from one module to anothern Structural methodsn A connection is a reference to some label or address defined elsewheren OO methodsq Interaction couplingq Component couplingq Inheritance couplingMain Contentsn Coupling of OOq Interaction Couplingq Component Couplingq Inherit Couplingq Coupling Metric

3、 of OOn Cohesion of OOSingleinteraction couplingn Method Invoke or Attribute Access between two classn Most similar to the classical definition of coupling between modulesn Not including inheritancen Parameter and Attribute not including Class TypeStrength of Single interaction couplingInterfaceType

4、 ofType of ComplexityConnectionCommunicationLowSimple,To module,Data Obviousby nameCOUPLINGControlHighComplicated,To InternalHybrid ObscureElementsPrinciples of interactioncouplingn Principles from Modularizationq 1: Global Variables Consider Harmfulq 2: To be Explicitq 3: Do not Repeatq 4: Programm

5、ing to InterfaceMain Contentsn Coupling of OOq Interaction Couplingq Component Couplingq Inherit Couplingq Coupling Metric of OOn Cohesion of OOComponent couplingn Abstractionq Define one place, using many placeq Class-Level , Object-Leveln Component couplingq The component relationship between clas

6、ses is defined by the use of a class as domain of some instance variable of another classq Not including Inheritanceq Usually Class-Level neededn Attribute Type: how to explicitFour Kinds of Component couplingn Whole variable: Aggregationn Parameter: Method Parametern Creator: Creator in some method

7、s localn Hidden: Given by another objectHidden Component couplingThe worst coupling: ImplicitThe coupling between two classes C and C is rated hidden if C shows up neither in the specification nor in the implementation of C although an object of C is used in the implementation of a method of CA simi

8、lar problem is encountered if the return value of a method invocation is immediately used as input parameter in another method invocationdisallow the use of cascading messagesq To be explicit!Hidden Component couplingThe Law of Demeter ExamplePrinciples of Component Coupling Principle 5: The Law of

9、Demeter You can play with yourself. You can play with your own toys, but you cant take them apart You can play with toys that were given to you. You can play with toys youve made yourself.ScatteredComponent CouplingWe rate two classes C and C as scattered coupled if C is used as domain in the defini

10、tion of some local variable or instance variable in the implementation of C yet C is not included in the specification of CCommon and acceptable Aggregation: Global Local instance: Local Which is better?q Many Connections VS Stronger Single ConnectionSpecified Component CouplingWe rate two classes C

11、 and C as specified coupled if C is included in the specification of C whenever it is a component of CGet Specified, Design by ContractSuffered Interface VS Required Interfaceq Suffered Interface: Specifiedq Required Interface: UsedScattered Component Coupling can be improved to Specified component

12、coupling with commentsPrinciples of Component Couplingn Principle 4: Programming to Interfacen Programming to Required Interface, not only Suffered Interfacen Design by Contractq Contract of Module/ Class Required mothods / Provided methodsq Contract of Methods PreCondition, PostCondition, Invariant

13、Principles of Component Couplingn Principles 6: Interface Segregation Principle(ISP)q Programming to Simpler Interfacen Many client-specific interfaces are better than one general purpose interfaceClients should not be forced to depend upon interfaces that they do not use.R. Martin, 1996Principles o

14、f Component Coupling ISP Explainedn Multipurpose classesq Methods fall in different groupsq Not all users use all methodsn Can lead to unwanted dependenciesq Clients using one aspect of a class also depend indirectly on the dependencies of the other aspectsn ISP helps to solve the problemq Use sever

15、al client-specific interfacesPrinciples of Component Coupling ISP Example: UIsUIs are isolated from each other Can add a UI with changes in Server other UIs not affectedThe Server collects interfaces New UI Server interface changes All other UIs recompileMain Contentsn Coupling of OOq Interaction Co

16、uplingq Component Couplingq Inherit Couplingq Coupling Metric of OOn Cohesion of OOInheritanceCouplingn Parent information is specified for childrenn With a parent reference, how many information a client needed when interacting?q Modificationq Refinementq ExtensionModification Inheritance Couplingn

17、 Modifying without any rules and restrictsn Worst Inheritance Couplingn If a client using a parent ref, the parent and child method are all neededq Implicitq There are two connections, more complexn Harm to polymorphismRefinement Inheritance Couplingn defining new information the inherited informati

18、on is only changed due to predefined rulesn If a client using a parent ref, the whole parent and refinement of child are neededq 1+connectionsn Necessary!Extension Inheritance Couplingn the subclass only adds methods and instance variables but neither modifies nor refines any of the inherited onesn

19、If a client using a parent ref, only the parent is neededq 1 connectionHow Inheritance reduce coupling ?n Remember: in Refinement and Extension inheritance coupling, the interaction coupling between super-class and subclass is ignoredPrinciples of Inherit CouplingPrinciple 7: Liskov Substitution Pri

20、nciple (LSP)All derived classes must be substituteable for their base classBarbara Liskov, 1988Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.R. Martin, 1996LSP: exampleLSP: exampleInheritance Appears Simple Is a Square a R

21、ectangle?n Rect r = new Rect(); setWidth = 4; setHeight=5;assert(20 = getArea();n class Square extends Rect/ Square invariant, height = width setWidth(x) setHeight()=x setHeight(x) setWidth(x) / violate LSP?Inheritance Appears SimpleclassBird/ has beak,wings,.public:virtualvoidfly();/ Bird can fly;c

22、lassParrot:publicBird/Parrotis abirdpublic:words.;virtualvoidmimic();/CanRepeatclassPenguin:publicfly()Birdpublic:errorvoid(“Penguinsdontfly!”);Penguins Fail to Fly!voidPlayWithBird(Bird&abird)abird.fly();/ if bird happens/toOKbeif Parrot.Penguin.OOOPS! Does not model: “Penguins cant fly” It models

23、“Penguins may fly, but if they try it is error” Run-time error if attempt to fly not desirable Think about Substitutability - Fails LSPLSPSummaryn LSP is about Semantics and Replacementq Understand before you designn The meaning and purpose of every method and class must be clearly documentedn Lack

24、of user understanding will induce de facto violations of LSPq Replaceability is crucialn Whenever any class is referenced by any code in any system,any future or existing subclasses of that class must be 100% replaceableLSPSummaryn Design by Contractq Advertised Behavior of an object:n advertised Re

25、quirements (Preconditions)n advertised Promises (Postconditions)Derived class services should require no more andpromise no lessWhen redefining a method in a derivate class, you may only replace its precondition by a weaker one, and its postcondition by a stronger oneB. Meyer, 1988Principle 8 : Favo

26、r Composition Over Inheritancen Use inherit for polymorphismn Use delegate not inherit to reuse code!Coads Rules of Using Inheritancen Use inheritance only when all of the following criteria are satisfied:q A subclass expresses is a special kind of and not is a role played by aq An instance of a sub

27、class never needs to become an object of another classq A subclass extends, rather than overrides or nullifies, the responsibilities of its superclassq A subclass does not extend the capabilities of what is merely an utility classInheritance/Composition Example 1Inheritance/Composition Example 1(Con

28、tinued)Inheritance/Composition Example 2class Object public: virtual void update() ; virtual void draw() ;virtual void collide(Object objects) ;class Visible : public Object public: virtual void draw() /* draw model at position of this object */ ; private: Model* model;class Solid : public Object pu

29、blic: virtual void collide(Object objects) /* check and react to collisions with objects */ ;class Movable : public Object public: virtual void update() /* update position */ ;Main Contentsn Coupling of OOq Interaction Couplingq Component Couplingq Inherit Couplingq Coupling Metric of OOn Cohesion o

30、f OOCoupling Metrics between classesn Coupling between object classes (CBO)n A count of the number of other classes:q which access a method or variable in this class, orq contain a method or variable accessed by this classq Not including Inheritancen Want to keep this lowCoupling Metrics between cla

31、ssesn Data abstraction coupling (DAC)n The number of attribute having an ADT type dependent on the definitions of other classesn Want to keep this lowCoupling Metrics between classesn Ce and &D (efferent and afferent coupling)q Ca: The number of classes outside this category that depend upon classes

32、 within this category.q Ce: The number of classes inside this category that depend upon classes outside this categoryn Want to keep these lowCoupling Metrics between classesn Depth of the Inheritance tree (DIT)q the maximum length from the node to the root of the treeq as DIT grows, it becomes diffi

33、cult to predict behavior of a class because of the high degree of inheritanceq Positively, large DIT values imply that many methods may be reusedCoupling Metrics between classesn Number of children (NOC)q count of the subclasses immediately subordinate to a classq as NOC grows, reuse increasesq as N

34、OC grows, abstraction can become dilutedq increase in NOC means the amount of testing will increaseMain Contentsn Coupling of OOq Interaction Couplingq Component Couplingq Inherit Couplingq Coupling Metric of OOn Cohesion of OOCohesion of AttributesSeparableq represent multiple unrelated data abstra

35、ctions combined in one objectmultifacetedq represent multiple related data abstractionsNon-delegatedq Some attribute represent a part of another class: not in third normal formConcealedq some attribute and referencing methods which may be regarded as a class of its ownModel: informational strengthq the class represents a single semantically meaningful conceptualCohesion of methodsn Methods of a Class are Common couplingn All methods serve One Responsibilityq Informational Cohesionq Relative functions (functional Cohesion)q Principle 9: Single Responsibility PrincipleSingle Responsi

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論