Object-oriented software development and process (6)-contract-oriented design

Source: Internet
Author: User

Lin Xing (iamlinx@21cn.com)
December 2003
Http://www-900.ibm.com/developerWorks/cn/linux/software_engineering/l-oo/index6.shtml

[Copy to clipboard] [-]

CODE:

Contract Design is a rigorous software design concept, which helps improve the quality of software. Bugs often occur in software design because the required prerequisites or data cannot be met. This problem is solved through a binding method for contract design.

1. Contract Design
We know that modern society is a social society, which is different from the acquaintance society we have known for thousands of years. The relationship between people becomes very complex. How can we ensure the interests of everyone, how to ensure that such complex relationships do not affect social stability. The solution in modern society is to adopt a contract or contract. We need to sign a labor contract with the employer, purchase a commercial housing sales contract, and even purchase a ticket on the bus. The ticket itself is also a contract. Why is the contract so important? Therefore, it defines a relationship between people and defines rigorous responsibilities and rights for such a relationship. Software design is similar. In a large system, the relationships between classes are very complex and Methods call each other. Therefore, we also need a rigorous specification similar to the contract to constrain each class and each method, to ensure the overall stability of the software. This is the essence of contract design.
Eifel is inherently a rigorous, or even conservative language. For example, for public fields in Eiffel, they are read-only by default, so as to ensure improper modification of public attributes. However, Eifel is commendable becauseWhen using the Eiffel language, most of your energy is spent on designing precondition, postcondition, and invariant.. Don't underestimate the functions of the three. Although it looks simple, when you try to design them, you will find that yourClass will become very strong. Why? We all know that a feedback mechanism is required to ensure the correctness of information transmission. How can we introduce this feedback mechanism in software design? Eifel implements this in its own way. The pre-condition check ensures the correctness of the State before the method starts. The post condition and the non-variant pattern ensure that the state we need is obtained after the method is executed. Although we can find many other feedback mechanisms, this mechanism is undoubtedly very effective.
The features of Eiffel look like nothing special. The following is the smallest example:
For an Inc method that adds an internal count value to one, its post condition is

[Copy to clipboard] [-]

CODE:

Count = old count + 1

Here, the old count refers to the value that has not been changed, that is, the old value. You may say, isn't this enough? What the Code itself does is to add one to the other count value, and finally test the result of adding one at a time, which is a waste of machine resources. The example here is very small, so we cannot see more specific ideas. But we know that in object-oriented design, various classes and methods constitute a fine-grained collaborative network. In this case, it is easy to make mistakes. At this time, the fundamental function of the post condition is to force you to find another method to verify that your work was correct. This is like if the methods are the same when we check for a mathematical problem, the result may not be correct. Because the methods are the same, you may have missed some information, however, if we can verify the results from another channel, for example, if we are right at the same table, the possibility of correct results will be much greater, and you will have a lot of confidence. Therefore, the post condition can be viewed as another channel for checking.
Another result is that the mechanism of Eifel is excellent object-oriented software design.The most basic knowledge of object-oriented is the design of tiny classes and methods to complete a simple task.. Unfortunately, programmers who have transformed from non-object-oriented programming still like to write some long code blocks. This is not the case when you use Eiffel. Using these lengthy methods, you cannot implement the preconditions and the postcondition at all. You can naturally learn how to reuse them. Based on this consideration, it is recommended that you learn Eiffel from object-oriented programmers. Your object-oriented design skills will grow greatly.
Eifel is not the focus of this Article. Therefore, this article does not intend to spend too much effort to introduce it. Unfortunately, there is little information about Eifel in China, the Chinese document I learned is the contract-Oriented Design book to be published by the People's post and telecommunications Publishing House.
Another point that needs to be mentioned is that Eiffel is not a popular Chinese development language, but it does not affect us to absorb this excellent idea in other languages. Java introduces the assertion mechanism in its new JDK version, which can be used to implement pre-conditions and post-conditions. Even languages that do not support assertions can easily write their own assertions.
Applications with preconditions and preconditions are also extended to other aspects. For example, both the prefix and Postfix conditions are introduced in the design and use cases. The idea is the same no matter where the application is located. The biggest advantage of the precondition is to exclude invalid input values. The biggest advantage of the precondition is to verify the result to ensure the correctness of the process. The preconditions and preconditions of different applications share two benefits;
Better structure
Better reusability

Like the idea of Eiffel, we regard the actual business objects as composed of basic queries, derivative queries, and operations. At the same time, these three mechanisms can be used to effectively apply the preconditions and the postcondition. Dividing the problems in the problem domain into these three types undoubtedly improves the effectiveness of the problem domain organization, that is, obtaining better structure. In addition, pre-and post-conditions use semi-formal expressions. Therefore, the expressions of problem domains are clear and rigorous.
While gaining the structure, we get better reusability. What should we do? A derived query is composed of basic queries, and two types of queries are used in operations. Since the classification is clear, we can easily reuse it.
Such a statement may be too abstract. Let's talk about a real story. I have been in touch with a vro. In my first class, I learned one of the most important operations, that is, when modifying any configuration, you must check the configuration file, to ensure that the configuration is correct. This is a very basic operation, but I discovered its importance only after I suffered a loss in practice. Viewing the configuration file is actually configuring the post-condition for this operation to ensure the correctness of the configuration operation process. As long as the post-condition is true, the error probability will be reduced. Of course, we can add more post conditions to further reduce the probability. The precondition here is that you have logged on to the vro correctly. This is a basic condition, and the operating system may support this configuration condition.
Preconditions and preconditions are really good, but they are not cost-free. (As a supporter of lean programming, we need to consider costs and benefits when doing everything ). The biggest cost is time. The time spent in the same problem domain is greatly increased, affecting the overall software process, which is terrible for many projects. How do we view this cost? It should be said that, at the beginning of the Application of preconditions and preconditions, it is indeed necessary to pay additional costs. As you get familiar with the application, the cost will gradually decrease. In the future, other benefits brought about by software quality improvement will exceed this cost. Their curves are roughly like this: (unfortunately, we cannot do quantitative analysis for the time being)
Of course, on the one hand, we pay attention to benefits, and on the other hand, we still need to consider minimizing costs. In terms of cost, degree is the most important. This is also the most subtle aspect of prefix and postcondition applications. How many preconditions and preconditions can meet the requirements? How detailed is conditional writing? Do I use the same degree for different applications? These data can only be derived from practical experience. Lack of degree is difficult to express the power of the preconditions and postcondition. Excessive degree also increases investment costs.
The idea of preconditions and preconditions is everywhere in life, and there are more applications in mathematics. For our software developers, it is important to form such an operation idea and Design Stable software. In the Eiffel language, another important feature is non-variant. Due to space limitations, we cannot provide a lot of introductions here. You can refer to the relevant materials. For us, the most important thing is to understand the advantages of contract design and apply them to projects.
As we mentioned at the beginning, contract-based design is a rigorous design concept, and the development cost increases accordingly. Therefore, many software development teams are reluctant to adopt the Eiffel language, the Eiffel language itself is also an existence of spring and snow. However, as the scale of software grows and the quality requirements continue to increase, the concept of contract-based design has gradually entered many languages.
For project developers, the most difficult requirement for quality is how to perform actual operations. Strengthening the strength and strength of testing is certainly a method, but it is expensive. Review is also an effective method, but the requirements and pressure on the reviewers are not small, once the flow of form, it does not have any effect. Implementing the idea of software engineering into code is the topic of this article, and it is no exception here. The contract-based design provides a method that requires programmers to call and design methods according to rigorous methods. Although there is a waste of resources for both the caller and the called to adopt a rigorous design model, the cost is very low. From the perspective of the software engineering culture, but it is very cost-effective to gradually form an efficient coding habit.
2. Specifications
To define a good specification, first we need to clearly understand the purpose of making the specification. First of all, we can be certain that our purpose is not to use the Eiffel language, but to improve the quality of software. So how can we develop standards for this purpose? If you want to introduce contract-oriented design within the organization. Then, you can try to use the iContract tool described below and define your contract-based design specifications according to the iContract method. If you do not want to change the existing development method, but want to learn some knowledge from contract-based design, more importantly, you should consider how to design specifications to constrain the design of classes in terms of basic queries, derived queries, and operations. In this way, you can also benefit from the concept of contract-based design.
3. Skills
Class Design learning. The key to learning contract-based design is to learn how to passThis class is designed in three aspects: basic query, derived query, and operation.
Object constraint language. OCL is a language that describes object-oriented design. It is managed and maintained by OMG. A subset of OCL is used to describe preconditions, postcondition, and non-variant conditions. The key to learning OCL is not the syntax, but the design of objects. If an object is not properly designed, you will find that you cannot describe it using the OCL language. If You Can skillfully use OCL to describe the relationship between classes, you will find that the quality of software will be greatly improved.
4. Process
Contract-based design is part of the design scope. Therefore, it can be easily combined with interface design, testing, and other activities. For example, iContract provides the following examples:

[Copy to clipboard] [-]

CODE:

/**
*/
Public interface IEmployee {
/**
* @ Pre hasOffice ()
*
* @ Return iContract. examples. office_management_system.API.IRoom
*/
Public IRoom getOffice ();
/**
* @ Post return = (office! = Null) // implementation, exposes null
*
* @ Return boolean
*/
Public boolean hasOffice ();
/**
* @ Pre office! = Null
*
* @ Post hasOffice ()
* @ Post getOffice () = office
*
* @ Param office IRoom
*/
Public void setOffice (IRoom office );
}

Similarly, you can perform a key test on the preceding interface descriptions during the test. Test whether the pre-condition is violated and whether the post-condition and non-variant conditions are met.
5. Tools
Eiffel is a very good language, but it is not easy to fully use Eiffel in projects. Except for Eiffel, other languages do not have obvious support for contract design. However, some people do not design support tools for contractual design for the non-Eiffel language. IContract in Java is one of them. IContract is actually a pre-compiler that translates the special mark in the annotation into standard Java code and inserts it into the final code:

[Copy to clipboard] [-]

CODE:

/**
* @ Pre f>; = 0.0
*/
Public float sqrt (float f ){...}

@ Pre is the symbol of the precondition. It indicates the conditions that f must meet the input parameter of the function sqrt. Similarly, there are also identifiers such as @ post and @ inv, which represent the post-condition and non-variant types discussed earlier. In addition, iContract also supports forall, exists, implies, and other OCL syntaxes.
About the author
Lin Xing, Senior Project Manager of the Project Management Group of Chen Xun software studio, has many years of project implementation experience. Chen Xun software studio is committed to the application of advanced software ideas and software technology. Its main research direction is software process ideas, Linux cluster technology, OO technology and software factory model. You can contact him by email iamlinx@21cn.com.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.