软件工程-14面向对象模块化课件

上传人:94****0 文档编号:241645814 上传时间:2024-07-12 格式:PPT 页数:61 大小:1.07MB
返回 下载 相关 举报
软件工程-14面向对象模块化课件_第1页
第1页 / 共61页
软件工程-14面向对象模块化课件_第2页
第2页 / 共61页
软件工程-14面向对象模块化课件_第3页
第3页 / 共61页
点击查看更多>>
资源描述
计算与软件工程II Ch14“面向对象”的模块化计算与软件工程II Ch14“面向对象”的模块化1ModulenA piece of codeqMethodsqClassqModule(package)nCoupling:among piecesnCohesion:internal a pieceModuleA piece of code2Whats the difference between Structural methods and OO methodsnCouplingqCoupling is the measure of the strength of association established by a connection from one module to anothernStructural methodsnA connection is a reference to some label or address defined elsewherenOO methodsqInteraction couplingqComponent couplingqInheritance couplingWhats the difference between 3Main ContentsnCoupling of OOqInteraction CouplingqComponent CouplingqInherit CouplingqCoupling Metric of OOnCohesion of OOMain ContentsCoupling of OO4Single interaction couplingnMethod Invoke or Attribute Access between two classnMost similar to the classical definition of coupling between modulesnNot including inheritancenParameter and Attribute not including Class TypeSingle interaction couplingMet5Strength of Single interaction couplingStrength of Single interaction6Principles of interaction couplingnPrinciples from Modularizationq1:Global Variables Consider Harmfulq2:To be Explicitq3:Do not Repeatq4:Programming to InterfacePrinciples of interaction coup7Main ContentsnCoupling of OOqInteraction CouplingqComponent CouplingqInherit CouplingqCoupling Metric of OOnCohesion of OOMain ContentsCoupling of OO8Component couplingnAbstractionqDefine one place,using many placeqClass-Level,Object-LevelnComponent couplingqThe component relationship between classes is defined by the use of a class as domain of some instance variable of another classqNot including InheritanceqUsually Class-Level needednAttribute Type:how to explicitComponent couplingAbstraction9Four Kinds of Component couplingnWhole variable:AggregationnParameter:Method ParameternCreator:Creator in some methods localnHidden:Given by another objectFour Kinds of Component coupli10Hidden Component couplingnThe worst coupling:ImplicitnThe 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 CnA similar problem is encountered if the return value of a method invocation is immediately used as input parameter in another method invocationndisallow the use of cascading messagesqTo be explicit!Hidden Component couplingThe w11Hidden Component couplingHidden Component coupling12The Law of Demeter ExampleThe Law of Demeter Example13Principles of Component CouplingPrinciple 5:The Law of DemeterYou can play with yourself.You can play with your own toys,but you cant take them apartYou can play with toys that were given to you.You can play with toys youve made yourself.Principles of Component Coupli14软件工程-14面向对象模块化课件15Scattered Component CouplingnWe rate two classes C and C as scattered coupled if C is used as domain in the definition of some local variable or instance variable in the implementation of C yet C is not included in the specification of CnCommon and acceptablenAggregation:GlobalnLocal instance:LocalnWhich is better?qMany Connections VS Stronger Single ConnectionScattered Component CouplingWe16Specified Component CouplingnWe rate two classes C and C as specified coupled if C is included in the specification of C whenever it is a component of CnGet Specified,Design by ContractSuffered Interface VS Required InterfaceqSuffered Interface:SpecifiedqRequired Interface:UsednScattered Component Coupling can be improved to Specified component coupling with commentsSpecified Component CouplingWe17Principles of Component CouplingnPrinciple 4:Programming to InterfacenProgramming to Required Interface,not only Suffered InterfacenDesign by ContractqContract of Module/ClassRequired mothods/Provided methodsqContract of MethodsPreCondition,PostCondition,InvariantPrinciples of Component Coupli18Principles of Component CouplingnPrinciples 6:Interface Segregation Principle(ISP)qProgramming to Simpler InterfacenMany 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 of Component Coupli19Principles of Component Coupling ISP ExplainednMultipurpose classesqMethods fall in different groupsqNot all users use all methodsnCan lead to unwanted dependenciesqClients using one aspect of a class also depend indirectly on the dependencies of the other aspectsnISP helps to solve the problemqUse several client-specific interfacesPrinciples of Component Coupli20Principles of Component Coupling ISP Example:UIsUIs are isolated from each otherCan add a UI with changes inServer other UIs not affectedThe Server collects interfacesNew UI Server interface changesAll other UIs recompilePrinciples of Component Coupli21软件工程-14面向对象模块化课件22Main ContentsnCoupling of OOqInteraction CouplingqComponent CouplingqInherit CouplingqCoupling Metric of OOnCohesion of OOMain ContentsCoupling of OO23Inheritance CouplingnParent information is specified for childrennWith a parent reference,how many information a client needed when interacting?qModificationqRefinementqExtensionInheritance CouplingParent inf24Modification Inheritance CouplingnModifying without any rules and restrictsnWorst Inheritance CouplingnIf a client using a parent ref,the parent and child method are all neededqImplicitqThere are two connections,more complexnHarm to polymorphismModification Inheritance Coupl25Refinement Inheritance Couplingndefining new information the inherited information is only changed due to predefined rulesnIf a client using a parent ref,the whole parent and refinement of child are neededq1+connectionsnNecessary!Refinement Inheritance Couplin26Extension Inheritance Coupling nthe subclass only adds methods and instance variables but neither modifies nor refines any of the inherited onesnIf a client using a parent ref,only the parent is neededq1 connectionExtension Inheritance Coupling27How Inheritance reduce coupling?nRemember:in Refinement and Extension inheritance coupling,the interaction coupling between super-class and subclass is ignoredHow Inheritance reduce couplin28Principles of Inherit CouplingAll derived classes must be substituteablefor 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,1996Principle 7:Liskov Substitution Principle(LSP)Principles of Inherit Coupling29LSP:exampleLSP:example30LSP:exampleLSP:example31Inheritance Appears Simple Is a Square a Rectangle?nRect r=new Rect();setWidth=4;setHeight=5;assert(20=getArea();nclass Square extends Rect/Square invariant,height=widthsetWidth(x)setHeight()=xsetHeight(x)setWidth(x)/violate LSP?Inheritance Appears Simple Is32Inheritance Appears Simpleclass Bird /has beak,wings,.public:virtual void fly();/Bird can fly;class Parrot:public Bird /Parrot is a bird public:virtual void mimic();/Can Repeat words.;class Penguin:public Bird public:void fly()error(“Penguins dont fly!”);Inheritance Appears Simpleclas33Penguins Fail to Fly!void PlayWithBird(Bird&abird)abird.fly();/OK if Parrot./if bird happens to be Penguin.OOOPS!n Does not model:“Penguins cant fly”n It models“Penguins may fly,but if they try it is error”n Run-time error if attempt to fly not desirablen Think about Substitutability-Fails LSPPenguins Fail to Fly!void Play34LSP SummarynLSP is about Semantics and ReplacementqUnderstand before you designnThe meaning and purpose of every method and class must be clearly documentednLack of user understanding will induce de facto violations of LSPqReplaceability is crucialnWhenever any class is referenced by any code in any system,any future or existing subclasses of that class must be 100%replaceableLSP SummaryLSP is about Semant35LSP SummarynDesign by ContractqAdvertised Behavior of an object:nadvertised Requirements(Preconditions)nadvertised Promises(Postconditions)When 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,1988Derived class services should require no more and promise no less LSP SummaryDesign by ContractW36软件工程-14面向对象模块化课件37Principle 8:Favor Composition Over InheritancenUse inherit for polymorphismnUse delegate not inherit to reuse code!Principle 8:Favor Compositio38Coads Rules of Using Inheritance nUse inheritance only when all of the following criteria are satisfied:qA subclass expresses is a special kind of and not is a role played by aqAn instance of a subclass never needs to become an object of another classqA subclass extends,rather than overrides or nullifies,the responsibilities of its superclassqA subclass does not extend the capabilities of what is merely an utility classCoads Rules of Using Inherita39Inheritance/Composition Example 1 Inheritance/Composition Exampl40Inheritance/Composition Example 1(Continued)Inheritance/Composition Exampl41Inheritance/Composition Example 2Inheritance/Composition Exampl42class 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 public:virtual void collide(Object objects)/*check and react to collisions with objects*/;class Movable:public Object public:virtual void update()/*update position*/;class Object 43Main ContentsnCoupling of OOqInteraction CouplingqComponent CouplingqInherit CouplingqCoupling Metric of OOnCohesion of OOMain ContentsCoupling of OO44Coupling Metrics between classesnCoupling between object classes(CBO)nA count of the number of other classes:qwhich access a method or variable in this class,orqcontain a method or variable accessed by this classqNot including InheritancenWant to keep this lowCoupling Metrics between class45Coupling Metrics between classesnData abstraction coupling(DAC)nThe number of attribute having an ADT type dependent on the definitions of other classesnWant to keep this lowCoupling Metrics between class46Coupling Metrics between classesnCe and&D(efferent and afferent coupling)qCa:The number of classes outside this category that depend upon classes within this category.qCe:The number of classes inside this category that depend upon classes outside this categorynWant to keep these lowCoupling Metrics between class47Coupling Metrics between classesnDepth of the Inheritance tree(DIT)qthe maximum length from the node to the root of the treeqas DIT grows,it becomes difficult to predict behavior of a class because of the high degree of inheritanceqPositively,large DIT values imply that many methods may be reusedCoupling Metrics between class48Coupling Metrics between classesnNumber of children(NOC)qcount of the subclasses immediately subordinate to a classqas NOC grows,reuse increasesqas NOC grows,abstraction can become dilutedqincrease in NOC means the amount of testing will increaseCoupling Metrics between class49Main ContentsnCoupling of OOqInteraction CouplingqComponent CouplingqInherit CouplingqCoupling Metric of OOnCohesion of OOMain ContentsCoupling of OO50Cohesion of AttributesnSeparableqrepresent multiple unrelated data abstractions combined in one objectnmultifaceted qrepresent multiple related data abstractionsnNon-delegated qSome attribute represent a part of another class:not in third normal formnConcealed qsome attribute and referencing methods which may be regarded as a class of its ownnModel:informational strengthqthe class represents a single semantically meaningful conceptualCohesion of AttributesSeparabl51Cohesion of methodsnMethods of a Class are Common couplingnAll methods serve One ResponsibilityqInformational CohesionqRelative functions(functional Cohesion)qPrinciple 9:Single Responsibility PrincipleCohesion of methodsMethods of 52Single Responsibility Principle(SRP)A class should have only one reason to changeRobert MartinRelated to and derived from cohesion,i.e.that elements in a module should be closely related in their functionResponsibility of a class to perform a certain functionis also a reason for the class to changeSingle Responsibility Principl53SRP ExampleSRP Example54SRP ExampleSRP Example55SRP SummarynClass should have only one reason to changeqCohesion of its functions/responsibilitiesnSeveral responsibilitiesqmean several reasons for changes more frequent changesnSounds simple enoughqNot so easy in real lifeqTradeoffs with complexity,repetition,opacitySRP SummaryClass should have o56软件工程-14面向对象模块化课件57Measure class cohesionnLack of cohesion in methods(LCOM)nWant to keep this lownMany other versions of LCOM have been definedMeasure class cohesionLack of 58Measure class cohesionnIf LCOM=1,then the class should be separatedMeasure class cohesionIf LCOM 59Principles of interaction couplingnPrinciples from Modularizationq1:Global Variables Consider Harmfulq2:To be Explicitq3:Do not Repeatq4:Programming to InterfacePrinciples of interaction coup60More Principlesn4:Programming to Interface(Design by Contract)n5:The Law of Demetern6:Interface Segregation Principle(ISP)n7:Liskov Substitution Principle(LSP)n8:Favor Composition Over Inheritancen9:Single Responsibility PrincipleMore Principles4:Programming 61
展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 办公文档 > 教学培训


copyright@ 2023-2025  zhuangpeitu.com 装配图网版权所有   联系电话:18123376007

备案号:ICP2024067431-1 川公网安备51140202000466号


本站为文档C2C交易模式,即用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。装配图网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知装配图网,我们立即给予删除!