`

<Java.JavaEE面试整理>(8) --基于什么考虑,Java 1.4中引入Assert???

阅读更多
Q 11: What is design by contract? Explain the assertion construct? DC(基于什么考虑,Java 1.4中引入Assert???)
A 11: Design by contract specifies the obligations of a calling-method and called-method to each other. Design by
contract is a valuable technique, which should be used to build well-defined interfaces.  The strength of this
programming methodology is that it gets the programmer to think clearly about what a function does, what pre
and post conditions it must adhere to and also it provides documentation for the caller. Java uses the assert
statement to implement pre- and post-conditions. Java’s exceptions handling also support design by contract
especially  checked exceptions  (Refer Q39  in Java section for checked exceptions). In design by contract in
addition to specifying programming code to carrying out intended operations of a method the programmer also
specifies:

1. Preconditions – This is the part of the contract the calling-method must agree to. Preconditions specify the
conditions that must be true before a called method can execute. Preconditions involve the system state and the
arguments passed into the method at the time of its invocation. If a precondition fails then there is a bug in the
calling-method or calling software component.  

    On public methods:
        Preconditions on public methods are enforced by explicit checks that throw particular, specified exceptions. You  should not use assertion  to check the parameters of the public methods but can use for the non-public methods.  Assert  is inappropriate because the method guarantees that it will always enforce the argument checks. It must check  its arguments whether or not assertions are enabled. Further, assert construct does not throw an exception of a specified type. It can throw only an AssertionError.  
 
            public void setRate(int rate) {
               if(rate <= 0 || rate > MAX_RATE){
                    throw new IllegalArgumentException(“Invalid rate --> ” + rate);
               }
               setCalculatedRate(rate);  
            }

    On non-public methods
    
        You can use assertion to check the parameters of the non-public methods.
    
            private void setCalculatedRate(int rate) {
                  assert (rate > 0 && rate < MAX_RATE) : rate;
                     //calculate the rate and set it.  
            }
 
        Assertions can be disabled, so programs must not assume that assert construct will be always executed:
 
        //Wrong:
        //if assertion is disabled, “pilotJob” never gets removed
        assert  jobsAd.remove(pilotJob);  
          
        //Correct:
        boolean pilotJobRemoved =  jobsAd.remove(pilotJob);
        assert pilotJobRemoved;

2. Postconditions  – This is the part of the contract the  called-method agrees to. What must be true after a
method completes successfully.   Postconditions can be used with assertions in both public and non-public
methods. The postconditions involve the old system state, the new system state, the method arguments and the
method’s return value.  If a postcondition fails then there is a bug in the called-method or called software
component.
 
        public double calcRate(int rate) {
           if(rate <= 0 || rate > MAX_RATE){
               throw new IllegalArgumentException(“Invalid rate !!! ”);
            }
              
            //logic to calculate the rate and set it goes here
        
            assert this.evaluate(result) < 0 : this; //message sent to AssertionError on failure
            return result;     
        }
 
3. Class invariants - what must be true about each instance of a class? A class invariant as an internal invariant
that can specify the relationships among multiple attributes, and should be true before and after any method
completes. If an invariant fails then there could be a bug in either calling-method or called-method.  There is
no particular mechanism for checking invariants but it is convenient to combine all the expressions required for
checking invariants into a single internal method that can be called by assertions. For example if you have a class,
which deals with negative integers then you define the isNegative() convenient internal method:
 
        class NegativeInteger {
           Integer value = new Integer (-1); //invariant
        
           //constructor
           public NegativeInteger(Integer int) {
                //constructor logic goes here
                assert isNegative();
           }
        
           // rest of the public and non-public methods goes here. public methods should call  
           // assert isNegative(); prior to its return
        
           // convenient internal method for checking invariants.  
           // Returns true if the integer value is negative
        
           private boolean isNegative(){
                return  value.intValue() < 0 ;
            }  
        }

The isNegative() method should be true before and after any method completes, each public method and
constructor should contain the following assert statement immediately prior to its return.
 
        assert isNegative();
        
+++++++++++++++++++++++++++++++++++++++++++++++++++++++
Explain the assertion construct? The assertion statements have two forms as shown below:  
 
        assert Expression1;
        assert Expression1 : Expression2;
 
Where:
        .  Expression1 --> is a boolean expression. If the Expression1 evaluates to false, it throws an AssertionError without any
        detailed message.
        .  Expression2 --> if the Expression1 evaluates to false throws an AssertionError with using the value of the Expression2 as
        the error’s detailed message.


Note:   If you are using assertions (available from JDK1.4 onwards), you should supply the JVM argument to
enable it by package name or class name.
 
        java -ea[:packagename...|:classname] or java -enableassertions[:packagename...|:classname]
        java –ea:Account
分享到:
评论

相关推荐

    cas 配置client 1.0 &2.0 及proxy DEMO 说明

    2.2.1.4 keytool -export -alias tomcatsso -file tomcatsso.crt -keystore cacerts -storepass changeit 2.2.1.5 keytool -import -alias tomcatsso -file tomcatsso.crt -keystore cacerts -storepass changeit ...

    JAVA web.xml配置详解

    &lt;display-name&gt;网站名称&lt;/display-name&gt; &lt;description&gt;网站描述&lt;/description&gt; &lt;!-- icon元素包含small-icon和large-icon两个子元素.用来指定web站台中小图标和大图标的路径. --&gt; &lt;icon&gt; &lt;!--small-icon...

    生活轨迹SSH服务端

    &lt;param-value&gt;UTF-8&lt;/param-value&gt; &lt;/init-param&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;encodingFilter&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;/web-app&gt; 代码不完善,敬请...

    工资管理系统

    &lt;column name="ID" type="java.lang.Integer"/&gt; &lt;/table&gt; -&lt;table schema="SCOTT" name="BIZ_CLAIM_VOUCHER"&gt; &lt;column name="ID" type="java.lang.Integer"/&gt; &lt;/table&gt; -&lt;table schema="SCOTT" name="BIZ_...

    一个在线报名系统

    &lt;display-name&gt;RegisterSy&lt;/display-name&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.html&lt;/welcome-file&gt; &lt;welcome-file&gt;index.htm&lt;/welcome-file&gt; &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt; &lt;welcome-file&gt;...

    框架ssm整合

    &lt;param-value&gt;UTF8&lt;/param-value&gt; &lt;/init-param&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;encodingFilter&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;!-- 解决PUT请求无法提交表单...

    最简化velocity的web工程

    &lt;servlet-name&gt;velocity&lt;/servlet-name&gt; &lt;servlet-class&gt;org.apache.velocity.tools.view.VelocityViewServlet&lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;velocity&lt;/servlet-name&gt; ...

    spring mvc 环境搭建

    Spring MVC 是 Spring Framework 的一个重要模块,主要用于构建基于 Java 的 Web 应用程序。它提供了一个清晰的模型-视图-控制器(MVC)实现,帮助开发者分离业务逻辑与用户界面,简化 Web 应用开发流程。 #### 二...

    javaee.jar,jsf-api.jar,jsf-impl.jar,jstl-1.2.jar

    这四个JAR文件组合在一起,通常用于构建一个基于Java EE的Web应用程序,其中JSF负责用户界面的展示和交互,JSTL提供方便的页面逻辑处理,而javaee.jar提供了整个Java EE平台的基础服务。开发者在使用这些库时,需要...

    JavaEE主流开源框架-Struts部分rmvb格式.zip

    JavaEE主流开源框架-Struts部分rmvb格式. JavaEE主流开源框架-Struts部分rmvb格式. JavaEE主流开源框架-Struts部分rmvb格式. JavaEE主流开源框架-Struts部分rmvb格式. JavaEE主流开源框架-Struts部分rmvb格式. ...

    160G!全新升级版 JAVAEE云计算全栈就业班课程 完美试炼JAVAEE企业级云计算应用

    ├&lt;阶段1 java语言基础&gt; │ ├&lt;1-1-Java基础语法&gt; │ ├&lt;1-2 -面向对象和封装&gt; │ └&lt;1-3-Java语言高级&gt; ├&lt;阶段2 JavaWeb·&gt; │ ├&lt;01 HTML和CSS&gt; │ ├&lt;02 JavaScript&gt; │ ├&lt;03 BootStrap&gt; │ ├&lt;04 XML&gt; │ ├...

    一个简单的Acegi入门实例

    &lt;!!-- web.xml文件 --&gt; &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:...

    serverlet4Json

    &lt;servlet-name&gt;JSON&lt;/servlet-name&gt; &lt;servlet-class&gt;struts2.json.demo.JSON&lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;JSON&lt;/servlet-name&gt; &lt;url-pattern&gt;/&lt;/url-pattern&gt; &lt;/servlet-...

    web xml 详解

    &lt;param-value&gt;UTF-8&lt;/param-value&gt; &lt;/context-param&gt; ``` ##### 4. `&lt;filter&gt;` 定义一个过滤器,它可以拦截请求,并对请求数据进行预处理或后处理。 ```xml &lt;filter&gt; &lt;filter-name&gt;MyFilter&lt;/filter-name&gt; ...

    先电云计算软件服务-云存储网盘JavaEE网络应用开发手册-Cloud-SaaS-Web-v2.0.pdf

    以上内容是基于给定文件标题、描述、标签以及部分内容的综合分析所得出的关键知识点。这些知识点涵盖了JavaEE网络应用开发所需的基本环境搭建流程、数据库配置、项目导入与配置、工程功能需求说明以及技术支持等方面...

    Java实训教程 Java软件开发实战 Java开发框架介绍 webservices-cxf 共30页.pptx

    #### 二、Java中的Web Service技术 - **Java支持的Web Service技术**: - **官方技术**:如JAX-WS(Java API for XML Web Services),它是Sun Microsystems(现已被Oracle收购)提供的官方标准。 - **中间件...

    springmvc+mybatis+oracle

    &lt;param-value&gt;UTF-8&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;forceEncoding&lt;/param-name&gt; &lt;param-value&gt;true&lt;/param-value&gt; &lt;/init-param&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;...

    java和javaEE面试题大全打包-24个文件

    Java和JavaEE是软件开发领域中的重要技术,广泛应用于企业级应用系统开发。这份压缩包包含的24个文件很可能是各种面试题目的集合,旨在帮助求职者准备Java和JavaEE相关的技术面试。以下是根据这些文件可能涵盖的知识...

Global site tag (gtag.js) - Google Analytics