<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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
我用Spring5的aop应用时报这个错误Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from file [D:\ecliple\web5\WEB-INF\applicationContext.xml]; nested exception is java.nio.file.NoSuchFileException: WEB-INF\applicationContext.xml,他说我的applicationContext.xml文件不存在,可是我明明有这个文件,另外我的web.xml需要更改吗<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <context-param> <param-name>contextConfigLocation </param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <display-name>Struts2</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>struts2</filter-name> <filter-class> <!--2.5版本的写法 --> org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter </filter-class> </filter> <filter> <filter-name>OpenSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>OpenSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/* </url-pattern> </filter-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> </web-app>
05-30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值