What is a contract - aneffel
Suppose you are interviewing now, the subject is not slowly given the next topic: "Please write a function similar to Strcpy with the C language. Consider the abnormal situation where you can happen." What do you do? " Obviously, the other party is not in examining your programming ability, because the replication string is too easy. The other party is in examining your programming style (habits), or says to see the quality of your coded.
Here are a variety of possible practices:
Void string_copy1 (char * DEST, const char * source) {assert (dest! = null); / * Using assertion * / assert (source! = null); while (* source! = '/ 0') {* dest = * Source; Dest; Source;}
* DEST = '/ 0';}
Void string_copy2 (char * DEST, Const Char * Source) {if (dest! = null && source! = null) {/ * Pair of erroneous muffles * / while (* source! = '/ 0') {* dest = * Source; Dest; Source;
* DEST = '/ 0';}}
INT string_copy3 (char * dest, const char * source) {if (dest! = null&& source! = null) {while (* source! = '/ 0') {* dest = * source; Dest; Source;}
* DEST = '/ 0'; return success; / * Returns the correct value * /} else {errno = E_INVALIDARG; / * Setting error number * / return failed; / * Returns the value of the error * /}} / / C void string_copy4 (char * dest, const char * source) {if (dest == null || Source == null) throw invalid_argument_error (); / * Throw exception * /
While (* Source! = '/ 0') {* dest = * source; Dest; Source;}
* DEST = '/ 0';}
If you are a primary examination, I don't know how to face these four answers, how is your rating? Of course, you can have a "standard answer" in your heart, "Shun my people, and die". But if you face these four answers with a serious attitude, I think many people will be difficult to choose. Because here involves a software development with essential challenge - error handling.
Error handling has always been one of the biggest difficulties faced by software developers. Bjarne Stroustrup said when it comes to the reason, can detect the wrong party does not know how to handle the error, know how to handle the wrong one without the ability to explore the error, and directly use the defensive code to solve it, it will make the normal structure of the program is disrupted It brings more errors. This dilemma is very difficult to deal with - expelling and not necessarily returned. Therefore, more people use ostrich tactics to make mistakes that may happen, and they are natural.
C , Java and other languages have an anomaly mechanism for an error handling problem. This mechanism has opened up a special channel outside the normal program, which is specifically used to report errors between different program modules to solve the contradiction between the above error detection and processing strategy. However, after an abnormal handling mechanism, developers have a tendency to use an exception to handle all errors. I used to discuss this problem in comp.lang.c . Moderated, the result is that there are quite a few people, including many experts in the Boost development group, are considered universal solutions for error handling.
I can't agree with this. And I think abuse is more harmful than unusual harm.
The Pragmatic Programmer is a book that is quite popular in the middle of foreign programmers. When the error is handled, there is a rumor: "It is only used in the real abnormality."
An example of the book, if you need a file named "app.dat" in the current directory, and this file does not exist, then this is not called an abnormal situation, this is what you should anticipate, and explicitly Case. And if you want to find the user.dat file in a Windows directory, it is not found, that is called abnormal situation - because every normal WINDOWS system should have this file.
I am very pressing the advice in the book, but what is the situation of "real abnormal"? This example in the book is obviously just a sense of sensibility, the fable story, has all the common features of all fables - I feel that it is clear, gains big, I can't help you. This example is still unable to help our actual development.
How should I treat an error? How can I best mean?
To be honest, on these two issues, most of the languages we have seen have not given a good answer. C adhering to the consistent style, push all things to the developer; Ada invented an abnormality, but it is tired for an abnormality (know why Is Aliana 5 Rockets fail?); C attempt to integrate ADA's abnormal mechanism In your own system, the results were abnormal as the most difficult thing in C ; Java and C # obviously did not patient reconsider the wrong handling this kind of thing, but simply complete the C unopened mechanism.
Unlike these languages, Eiffel considers the error handling in the core position from the outset, and establishes the entire error handling ideological system with the "contract" thought as the core. In the language I understand, Eiffel is the most profound about this problem, so Eiffel has always enjoyed the reputation of "high quality system development language". (In fact, Bertrand Meyer does not like others to say that Eiffel is "programming language", he repeatedly emphasized that Eiffel is a Software Development Framework. However, this article only involves language characteristics, so it is called Eiffel language.) Eiffel generates the essence of software errors Attributing to the destruction of "contract". Eiffel believes that a software can work properly and complete tasks correctly, is a series of conditions. These conditions include good objective operating environment, operator operation correctly, and the software internal functions are correct. Therefore, the proper operation of the software is the result of cooperation between the environment, operator and the software itself. Corresponding, system errors are also caused by one party in the three do not fulfill their responsibilities correctly. Detained to the interior of the software, each software consists of several different modules, the software error is due to some modules do not perform their duties correctly. To completely eliminate software errors, only the responsibility of each module, and establish a mechanism, urge each module correctly fulfill its responsibility, and then it is possible to do bug-free. (Given the negative relationship between the system, and the limitations of developers' ability to understand the ability, I think that the true error-free system is impossible. However, the quality problems in the current software system are far more serious than that.)
How to ensure that all parties adhere to their duties? Eiffel introduced the contract of Contract. The contract here is similar to what we usually say, there are several features:
1. The two parties of the contractual relationship are equal, and have a common responsibility for the smooth progress of the entire Bussiness. No one can enjoy only the right and do not bear the obligation. 2. Contractual relationships are often mutual, rights and obligations are often bundled with each other; 3. The obligation to implement the contract is in me, and the power of the verification contract is in people; 4. My obligation is your interest. And your obligation guarantees my interests; introducing contractual relations into software development fields, especially after the object of objects, give us a few impacts on the concept:
1. General views, in the software system, the library and component libraries are subject to Server, and the program library is used as a client. Based on this C / S relationship, we tend to make very demanding requirements on the quality of the library procedures and components, forcing them to bear the responsibility of them should be taken, and excessively condolences to the client, and even ask the library procedure to deal with obvious Difficulties caused by Client errors. Objectively leading the design and writing of the library and component libraries, and the quality hidden danger is more; at the same time, the CLIENT one code is much loose, and the quality is poor. In this case, it seems that in an enterprise that is unclear, it will inevitably raise a batch of cruel mens, bitter, a batch of old yellow cattle who does not work. After introducing contract concept, this kind of C / S relationship is broken. Everyone is equal, you need me to provide the service correctly, then you must meet the conditions I proposed, otherwise I don't have to "exclude all difficulties" to ensure completion tasks.
2. Generally speaking to check the wrong status in the module and report it, it is the obligation of the module itself. Under the contractual system, the inspection of the contract is not obligated, and it is actually fulfilled. An obligation, one right, which is very different. For example, the above code: if (dest == null) {...} This is the obligation, its main point is that once the condition is not satisfied, our (volunteer) must be responsible for handling this embarrassing situation, or returns the wrong value Or throw an exception. And: Assert (DEST! = Null); this is an inspection contract, fulfilling his rights. If the conditions are not satisfied, then the error is in the other party without in me, I can immediately "tear the contract", strike, don't do any extra action. This will undoubtedly greatly simplify the development of the library and component libraries. 3. The contract is verified is "Conditions that must be satisfied to ensure the correctness", so when the contract is destroyed, only one thing is: BUG in the software system. Its significance is that some conditions must have been ensured as "true" when it reaches me. Who will make sure? It should be that other modules in the system are ensured. If the contract is not observed in my discovery, then other modules in the system do not perform their obligations correctly. Take the example mentioned above, if there is a module that requires a file *, and finding that the pointer is null in the contract check, it means that there is no module without fulfilling its obligations, ie "checking the file. Whether it exists, make sure the file opens in the correct mode and guarantee the correctness of the pointer. " Therefore, when the contract check fails, we must first know that this means that the programmer is wrong, and it is not a correction contract verifier, but correct the contract provider. In other words, when you find: assert (dest! = Null); When you report an error, you have to do it to modify your String_copy function, but let any code to make sure the DEST pointer is not empty when calling string_copy.
4. We have treated the "Process" or "Function" in the past is: the process of completing a computing task, this view only emphasizes its goals, and does not emphasize its conditions. Under this understanding, our understanding of Exception is very vague and broad: as long as it is unable to complete this calculation process, it can be considered an abnormality, and whether it is my own reasons, or the reason for others (typical clear). It is precisely because this blurry and broad, "When is it going to throw an abnormality," it has become a problem that no one can answer. After the introduction contract, "process" and "function" are defined as: the process of completing the contract. Based on the mutuality of the contract, if the failure of this contract is because other modules have failed to perform the contract, this process only needs to be reported without any other way to react. The real abnormal condition is "the other party fully meets the contract, and I still fail to complete the task". In this way, we have a clear and feasible definition of "abnormal".
5. Generally, in object-oriented technology, we think "interface" is the only important thing. The interface defines the component. The interface determines the system. The interface is the only thing we need to care only. The interface is not only necessary And it is sufficient. However, the contract concept reminds us that only the interface is not sufficient, but only the interface is not enough to convey enough information, in order to properly use the interface, the contract must be considered. Only the object-oriented objective: reliability, scalability, and reuse of reliability. In turn, "There is no contract to reuse," Bertrand Meyer "." As can be seen from the above view, although the Design By Contract advocated by Eiffel is just a systematic assertion mechanism, it is indeed a complete ideological innovation. Just as Ivar Jacoboson said to "Programmer" magazine: "I think Bertrand Meyer direction - Design by Contract - is the right direction, we will move along his footprint. I believe, large manufacturers (Microsoft , IBM, of course, there is still no reason to sit on the achievement of Bertrand Meyer. All these manufacturers will have actions in this direction. "(See" Programmer "2002 No. 11, P22).
Continued articles - a reverse case of contract thoughts MYAN (original)
Just published "What is a contract", suddenly found that it is written by writing theory, there is no instance to prove. So quickly add a reverse case - C iostream. It is not because the iostream library is designed to be unpleasant (it's just the opposite, you can't find a more exciting C library than Iostream design), but want to show, in the ideological system without contract concept, component design will How much cost is paid for an unclear error handler.