




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、计算与软件工程II Ch14 “面向对象”的模块化丁二玉南京大学软件学院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等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 第05讲 热机-人教版九年级《物理》暑假自学提升讲义
- 菲律宾外汇投资管理办法
- 西安市东郊供热管理办法
- 衡阳市惠农资金管理办法
- 西宁市重点车辆管理办法
- 西班牙斗牛饲养管理办法
- 许昌商品房销售管理办法
- 证监会资金归集管理办法
- 财务性金融投资管理办法
- 贫困村共享单车管理办法
- 2025年村干部公务员试题及答案
- 煤矿采矿制图培训课件
- 羊水栓塞个案护理
- 2024年萍乡市县区事业单位引进人才笔试真题
- 2025-2030中国透明无色聚酰亚胺薄膜行业发展动态及应用趋势预测报告
- 2025中国白酒酒业市场中期研究报告
- 紧急疏散培训课件
- 2024年石嘴山市直机关遴选和选调公务员笔试真题
- 17.2 直角三角形 课件
- 2025年安全教育培训考试应急救援知识题库高频试题
- 高等数学导数及其应用教案
评论
0/150
提交评论