已阅读5页,还剩17页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
DesignbyContract Practice LanguageSupportinC C 和其他语言相比 C C 特别注重效率 因此不受任何程序员控制的运行期内部检查机制如 指针检查 数组下标检查 运行期类型检查等断言的使用 非关键字 assertASSERT assert 用法 assert宏的原型定义在中 其作用是如果它的条件返回错误 则终止程序执行一般在Debug版有效 在Release版不起作用用法 在函数开始处检验传入参数的合法性每个assert最好只检验一个条件不要使用有副作用的语句assert和后面的语句应空一行 以形成逻辑和视觉上的一致感有的地方 assert不能代替条件过滤 例子 doublesqrt doublex assert x 0 pre condition assert fabs y y x eps post conditionreturny ASSERT和VERIFY 在VC环境下一般使用ASSERT和VERIFY在Debug模式下作用基本一致 二者都对表达式的值进行计算 如果值为非0 则什么事也不做 如果值为0 则输出诊断信息 在Release模式下效果完全不一样 ASSERT不计算表达式的值 也不会输出诊断信息 VERIFY计算表达式的值 但不管值为0还是非0都不会输出诊断信息 因为VERIFY 违反了断言的思想 不能使程序代码和调试代码完全分离 最终可能会带来很多麻烦 因此 建议尽量少用不用这个宏 Assert方式的缺点 不能直观地掌握出错地点不能被捕获和重新处理出错时不一定要中止 可能上层调用能够解决如打开文件在Debug版对性能有一定影响 LanguageSupportinJava assertExpression1 assertExpression1 Expression2 语法 Expression2canbeanyprimitivetype 从J2SE1 4之后 Java提供一些断言的支持 使用assert保留字 Expression1musthavetypebooleanoracompile timeerroroccurs enabledordisabled 两种形式的assert e g itcouldserveasauniqueintegercodefortheassertion Semantics Ifassertionsaredisabledinaclass theassertstatementscontainedinthatclasshavenoeffect Ifassertionsareenabled Expression1isevaluated Ifitevaluatestofalse anAssertionErroristhrown IfExpression1evaluatestotrue Expression2isnotevaluated IfExpression2ispresent thenthisisevaluatedandpassedtotheconstructoroftheAssertionError otherwisetheparameterlessconstructorisused assertExpression1 assertExpression1 Expression2 newAssertionError value returnsanassertionerrorthathasthestringrepresentationofthevalueastheerror sdetailmessage Ifanexceptionisthrownwhileeitherexpressionisbeingevaluated theassertstatementcompletesabruptly throwingthisexception Althoughtheassertconstructisnotafull blownDbCfacility itcanhelpsupportaninformalDbCstyleofprogramming Preconditions 按照Java的约定 public方法的前置条件通常通过显式的检查 explicitchecks 来明确 并抛出特定的 明确的异常 exceptions publicvoidsetRefreshRate intrate Enforcespecifiedpreconditioninpublicmethodif rateMAX REFRESH RATE thrownewIllegalArgumentException Illegalrate rate setRefreshInterval 1000 rate 不适合用assert 如 方法应该一直检查异常 不能被屏蔽 assert不能抛出制定的异常 它只能抛出AssertionError assertions可以被disable 对于nonpublic private 方法 使用assert表示前置条件比较合适 privatevoidsetRefreshInterval intinterval Confirmadherencetopreconditioninnonpublic methodassertinterval 0 Settherefreshinterval 如 Postconditions Postconditionsarebestimplementedasasserts whetherornottheyarespecifiedinpublicmethods ReturnsaBigIntegerofvalue this 1modm publicBigIntegermodInverse BigIntegerm if m signum 0 thrownewArithmeticException Modulusnotpositive m if this gcd m equals ONE thrownewArithmeticException this notinvertiblemod m Dothecomputationassertthis multiply result mod m equals ONE returnresult E g ClassInvariants Theassertionmechanismitselfdoesnotenforceanyparticularstylefordoingso Assertsareappropriateforcheckinginternalinvariants Onewayistocombinemanyconstraintchecksintoasingleinternalmethodthatcanthenbeinvokedbyassertions Returnstrueifthistreeisproperlybalancedprivatebooleanbalanced E g supposewewanttoimplementabalancedtreedatastructureofsomesort Thismethodisaclassinvariant Theinvariantshouldalwaysbetruebeforeandafteranymethodcompletes Tocheckthatthisisindeedthecase eachpublicmethodandconstructorshouldcontaintheline assertbalanced immediatelypriortoeachreturn Wecouldimplementaprivatemethodthatcheckedthatthetreewasindeedbalanced Invariants onclassesandonloops areindicatedwiththekeywordinvariant Pre andpost conditionsareindicatedbythekeywordsrequireandensurerespectively e g LanguageSupportin EiffelprovideslanguagesupportforDbC squareRoot x precisionRequired RealNumber RealNumberis requirex 0andprecisionRequired 10e 9 ensureabs answer answer x precisionRequiredend end invariantradius1 radius2 Variouslevelsofcheckingcanberequestedbycompileroptions e g checkall orcheckpreconditionsonly Eiffelevenenforcestheconstraintsonmaintainingthecontractoninheritance e g anoverriddenversionofsquareRootwhichacceptssmallervaluesofprecisionRequiredmighthavetheprecondition requireelseprecisionRequired 10e 15 keywordsrequireelseareusedforpreconditions andortheoriginalandthenewpreconditions keywordsensurethenareusedforpostconditions andandtheoriginalandthenewpostconditions Eiffel的例子 componentCUSTOMER MANAGERcount INTEGERid active an id CUSTOMER ID BOOLEANadd a customer BASIC CUSTOMER DETAILS requireid not already activenotid active a customer id ensurecount increasedcount oldcount 1customer id now activeid active a customer id name for an id CUSTOMER ID STRINGrequireid active id active anid set name an id CUSTOMER ID a name STRING requireid active id active anid ensurename set name for an id is equal a name invariantcount never negative count 0end Effiel运行时检查 Stoppedinobject 0 xE96978 Class CUSTOMER MANAGERFeature addProblem PreconditionviolatedTag id not already activeArguments a customer BASIC CUSTOMER DETAILS 0 xE9697C CallStack CUSTOMER MANAGER addWascalledbyCUSTOMER MANAGER UIFchange customer 提前崩溃原则 尽早在错误点崩溃便于发现错误便于定位错误不回避错误 避免鸵鸟态度前置条件和后置条件处进行检查断言与单元测试 错误和异常 错误Error应该预料到 一般能在调用的上一级解决函数调用返回值检查系统调用状态检查异常Exception不能预料原因如无法打开必须的文件网络传输错误通常无法在本地解决 以至于不能预计会在调用层次的哪一级 直到用户交互 解决严重失效Fault不能预料出现 而且可能在任何地点出现内存溢出外部硬件错误通常无法在程序内解决 异常处理 非结构化异常处理If then就地处理结构化异常处理throwtry catch可以以类的方式定义异常的类别和层次 重新审视DbC 调用者 应用程序等 和被调用者 库函数 组件库等 是平等的 都有权利和义务的说明
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 外国人聘用合同范本
- 合同以外的口头协议
- 垃圾箱建造合同协议
- 化工总控工中级(流体力学知识)模拟试卷2(题后含答案及解析)
- 2025国家开放大学电大专科《学前教育学》期末试题及答案
- GJB9001C-2025标准及内审员培训考试题答案
- 2025年注册会计师《会计》真题专项训练(含答案)
- 慧飞无人机应用技术培训中心第一章农业无人机应用章测验答案
- 销售合同审批与归档管理工具
- 财务报告编制及解读标准教程模板
- AI工业质检行业现状分析报告
- 热稳定校验计算书
- 美团闪购行业分析
- 岗位应急处置卡
- 消费者心理和行为分析培训课件
- 牛顿第一定律的实验验证
- 《透视学》全套教学课件
- 固化地坪施工合同范本
- 中建防水工程专项施工方案
- 小学三年级语文上册课外阅读叶圣陶芳儿的梦
- 混凝土生产质量控制记录
评论
0/150
提交评论