Drink Remodeling Series [16]--introduced contract design

Source: Internet
Author: User

Overview

Imagine a scenario where you provide some API to a client call, the client passes in some parameters, and then executes the API logic based on these parameters, eventually returning a result to the client.

In this scenario, there are two hidden dangers, namely:

    • When the client invokes the API, whether the passed parameters are accurate, and whether the parameters satisfy the API's execution premise
    • When the API logic finishes executing, the returned results are accurate and the results are consistent with the client's expectations

Both of these pitfalls are related to "accuracy", whether the API requirements (Require) pass in parameters accurately, and it also ensures that (ensure) the results returned are accurate.
The accuracy of the software determines the reliability of the software. In layman's terms, the user will have errors when using the software.

Contract design is a design method to ensure the correctness of software.

Introduction to contractual design

Contractual design (English: Design by contract, abbreviated as DbC), a method of designing computer software. This approach requires software designers to define formal, accurate, and verifiable interfaces for software components, which adds a priori, posteriori, and invariant to the traditional abstract data types. The "contract" or "contract" used in the name of this method is a metaphor, as it is somewhat similar to a commercial contract.

Wiki reference: Contractual design

The core of DBC is assertion (asserition), which refers to an expression that returns a result of Ture or false (the assertion is the core of a unit test), and an assertion that describes the contract.

The purpose is to identify and validate the expected structure of the program development-the corresponding assertion should be true when the program runs to the asserted location. If the assertion is not true, the program aborts the run and gives the error message.

DBC uses three types of assertions, namely, pre-conditions, post-conditions, and invariants.

    • Priori condition (preconditions): requires that the input of a method be a value or type that can be received, otherwise the logic of the method will not be executed
    • Posterior condition (postcoditions): Ensure that the output of the method is reasonable and that no one will output the result
    • Invariant (invariants): This is an assertion about a class, where both preconditions and post conditions are applied to the method, and the invariant acts on the entire class. For example, the total calculation of the Order class: TotalAmount = Sum (Items.amount), regardless of the method that calls the order class, the total calculation should always remain the same.

These three types of assertions can be summed up in three questions:

    • What does the program expect?
    • What is the procedure to guarantee?
    • What is the program to keep?
Example before refactoring

The following code calculates the balance of the ordertotal and the customer, respectively, based on the product and customer information.

public class cashregister{Public    decimal Totalorder (ienumerable<product> products, customer customer)    {        decimal orderTotal = products. Sum (Product = product. Price);        Customer. Balance + = OrderTotal;        return orderTotal;}    }

The main logic of this method is correct, but there are two points that we cannot ensure that the input parameters of the program are empty and that the result returned by the program is a positive number.
When the products parameter is empty or the customer parameter is empty, the program throws a Nullreference exception.
Such anomalies do not allow us to pinpoint exactly. is the products parameter empty? Or is the customer parameter empty? Or the exception that is thrown when executing the program's principal logic?

At. NET 3.5, Microsoft has introduced a contractual design that we did not use in this example. NET comes with the DBC framework.

After refactoring

We have added two transcendental conditions to the Totalorder method, a posteriori condition.
Two priori conditions determine if the products and customer parameters are empty, and throw ArgumentNullException accurately.
A posteriori condition that ensures that the value when returning OrderTotal is a positive number.

These 3 assertions ensure the accuracy of our program, and even if the program goes wrong, we can pinpoint the caller's problem or the program provider's problem.

public class cashregister{Public    decimal Totalorder (ienumerable<product> products, customer customer)    {        if (customer = = null)            throw new ArgumentNullException ("Customer", "Customer cannot be null");        if (products. Count () = = 0)            throw new ArgumentException ("must has at least one product to total" and "products");        Decimal orderTotal = products. Sum (Product = product. Price);        Customer. Balance + = OrderTotal;        if (OrderTotal > 0)            throw new ArgumentOutOfRangeException ("OrderTotal", "Order total should is greater than zero");        return orderTotal;}    }
DbC vs. Unit Test

As mentioned earlier, assertions are the core of DBC and the core of unit test.

When designing a program, does it cause some overlap in design if both DBC and unit Test are used?

In response to this doubt, someone has given a clearer answer to the question on StackOverflow:

Design driven by contract. Contract driven Design.

Develop driven by test. Test driven development.

They is related in that one precedes the other. They describe software at different levels of abstraction.

Does discard the design when you go to implementation? Do you consider the a design document is a violation of DRY? Do you maintain the contract and the code separately?

Software is one implementation of the contract. Tests is another. User ' s manual is a third. Operations Guide is a fourth. Database Backup/restore Procedures is one part of the implementation of the contract.

I can ' t see any overhead from Design by contract.

    • If you ' re already doing design and then your change the format from too many words to just the right words to outline the cont ractual relationship.

    • If you ' re not doing design, then writing a contract would eliminate problems, reducing cost and complexity.

I can ' t see any loss of flexibility.

    1. Start with a contract,

    2. Then

      A. Write Tests and

      B. Write code.

See how the development activities is essentially intertwined and both come from the contract.

Http://stackoverflow.com/questions/394591/design-by-contract-and-test-driven-development

"Attention" Keepfool

Drink Remodeling Series [16]--introduced contract design

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.