Design by Contract in C++? 114
An anonymous reader asks: "I have read some of the stuff on Eiffel, watched their tutorial videos about design by contract, and the entire thing sounds like a pretty good idea. However, the problem is that we don't use Eiffel at work, and I highly doubt I could get people to come around to the idea of switching to it. Although we use a lot of C++, I can imagine that a lot of the ideas from Eiffel can be applied there. I have looked around on the net and found a few articles talking about different ways of applying design by contract using assert statements and the like. I also found the dlib C++ library on SourceForge which, among other things, puts a design by contract face on a lot of API calls. So, there are obviously people doing it. What is everyone's experience with Design by Contract in C++? What tools are there that help make it a workable system? Lastly, are there any pitfalls to taking this approach in C++?"
In C++ (Score:3, Funny)
Re:In C++ (Score:5, Insightful)
1. Real DBC inherits the contracts from ancestor versions. Preconditions are or-ed together and postconditions are anded together. Invariants are also anded together. If you just use assertions you won't get this.
2. Eiffel allows you to disable the run-time execution of contracts at a fine level of detail. Again, if you use assertions you can only enable all or disable all.
3. There is no 'old' keyword in C++. Therefore you can't use 'old' in assertions.
4. According to DBC, a routine is in a transitional state during the execution of a routine. What happens if a routine calls another routine in the same class? Should it check the invariant? The answer is no. There are other cases as well.
5. It's difficult to implement a loop variant with an assertion. Not a big deal since most Eiffel code I've seen doesn't use loop variants.
If you don't want to use assertions, you can try some of the class pre-processors that are out there. You will see mixed results. In particular, I don't know of one that can handle 4. This is a show stopper.
I think you only have two choices. Use Eiffel or don't use contracts.
Brian
Re:In C++ (Score:5, Insightful)
Still, Eiffel is actually an extremely elegant language with powerful DbC built into at the core. If DbC is something that's important to you Eiffel probably is your best choice.
Re: (Score:2)
The fact that you can't use all of DbC specifications, doens't mean that using a macro/asserts in C++ won't have any utility.
We use a lot of pre/pos-conditions and they more than payed for themself. Each time a new feature crashes because a index was out-of-bounds, a variable wasn't initialized, or an invalid value was detected, we can solve it right away. It clears a lot of comunication problems between who codes and who uses a funct
Re: (Score:2)
I suspect that you can do some, but not all, of the Meyer design-by-contract stuff by using clever template programming. The Boost people have a collection of assertions, but I don't know whether there's anything DBC-related. If there isn't, there should be.
The C assert() macro should be avoided in C++ code -- destructors will not be executed when an assert() fails.
Re: (Score:2)
You do disable assert() in release builds, right?
Re: (Score:1)
I don't understand the question... (Score:4, Funny)
Re: (Score:3, Funny)
Re: (Score:2, Funny)
Re:I don't understand the question... (Score:5, Funny)
I must strongly object to your use of the term "natural" in that statement.
Re: (Score:2)
Re: (Score:2)
Re:I don't understand the question... (Score:4, Interesting)
Strange. After trying dozens of languages, I still return to C++, and I still think it is my favorite strongly typed language (yeah, I know, nobody can agree on strongly typed, but you know what I mean).
For loosely typed, I'm more torn. Ruby is nice, so is Perl. Python seems a bit limited to me, and the indention thing is just braindead, but maybe that is just a matter of adjustment. I haven't tried Scheme or that functional language that is so popular these days, but I will get around to it.
I do have 3 gripes with C++: No closures, no closures and no closures. Oh yeah, a way to statically initialize arbitrary objects would be nice. I have seen few other valid complaints with it, but lots of silly ones.
For the worst language I have tried yet, I nominate PL/I. For the worst that anybody still uses for new projects, Java, especially it's "let's throw all our type info away" implementation of templates, sorry, generics. And no closures there either. Horrible language.
For best assembler, I nominate C.
As for the question, doing real design by contract would require a pre-processor or manual insertion of suitable code in the beginning and end for every function. Neither is exactly pretty, but I believe lots of other languages do it this way. Personally, I think that excessive preconditions is a sign of poor OO design, but testing invariants do make sense for certain cases. Postconditions are better handled with an ordinary testframework.
And remember that lots of ideas looks awsome on paper, and turns out to be more bother than they are worth in real life.
Re: (Score:2)
I'll see your PL/I and raise you an RPG/III (or, really, anything in the RPG family except *maybe* the ILE flavor of RPG/400).
Re: (Score:2)
Re: (Score:2)
I'm not sure which you're referring to, but most non-lispy functional languages (that I know of) are actually strongly typed. For instance, Haskell is so strongly & statically typed that you don't always need to specify the types of a function or variable; it is obvious from the context that it takes only these types as arguments, and will only return this type.
On the other hand
Re: (Score:2)
Yeah, I was thinking of Haskell... which turns out to be strongly typed. Oh, well, I still want to try it out some day :)
As for strongly typed... I don't usually take it to degrees :) C++ has lots of built-in conversions, but still a function takes types as parameters, and the compile will fail if an appropriate conversion cannot be found. (I find that this typed function is the most important part of the strongly typed system, as it is here most mistakes are made.) I have yet to encounter a language with
Re: (Score:2)
Incidentally, I'm not actually sure that Haskell does do implicit typecasting; I don't know it well enough, but rather than being an integer, the literal 3 has the type of (Num
Re: (Score:2)
About the C++... primitive types are an abomination in any language (except C, which I regard as an assembler). I never consider them when I talk about strongly and loosely typed languages. It's the way that languages handles objects, which I am happy to see that most of the newer languages sees it this way too, thus 2.my_int_method() or equivalent is legal, like it should be. In your example, it would be relatively easy to make Character in C++ which would do the correct thing, quite unlike char :)
As for
Re: (Score:2)
Re: (Score:2)
Making a class is just as efficient as using primitives, at least in C++. The end assembler code would be identical. Anyway, 'a'+3 makes pefect sense... it should be 'd' if it is a character or if it is a number (such as in C++), it should be 'a'+3. Why? Because a+3 = (((a+1)+1)+1)=(b+1)+1)=c+1=d. That is how it works for page numbers, e.g. What makes it hard in C++ is the shorthand 'a' for the "the character code for a". It does not mean the character a, which is *not* in accordance with the principle of l
dynamic/static (Score:1)
dynamic/static is what you mean. Try some reading:
http://en.wikipedia.org/wiki/Type_system#Types_of_ Types [wikipedia.org]
Of corse C++ adcocates change the C++ entry to there liking faster then you can corect it but as far as I see it a language which allows:
is not strongly typed. In fact and just for good measure:
Re: (Score:2)
I am very much aware of the dynamic/static issue. C++ is (almost, if you ignore dynamic_cast and friends) statically typed language. That is hardly the point.
A strongly typed language is a very poor term, as it is used for so many things. The Java crowd, especially, uses it as a bagde of honour, even though Java allows some implicit casts (which is usually their definition, strangely enough) But the definition I use is that a language is strongly (statically) typed, if a) every variable has a type b) conv
4 Dimensional Typing System (Score:1)
static/dynamic: Can a variable change type?
strong/weak: Are types converted implicidly?
safe/unsafe: Are data convertions save? This includes dangling pointers!
nominative/structural: Are types bound to the a more or to the structure?
Some combinations are more common then other but in theory any combination is possible. And quite
Re: (Score:2)
*Sigh* I already wrote once that I am well aware of these distinctions. I admit to not be 100% exact, but my usage of the word is very common (it's the top suggestion on wikipedia e.g.), and anyway, it was not important. Strongly typed languages in your sense are too impractical as far as I can see. I don't know any offhand.
And 4-dimensional? You could go on. E.g, some type systems have const/non-const capabilities, which are othogonal to everything mentioned above.
As for the 100%, all those except the fl
Re: (Score:1)
http://en.wikibooks.org/wiki/Ada_Programming/Type_ System [wikibooks.org]
All in all I consider the Ada type system very praktical indeed. It allows me express my typing needs in a way I have never seen in any other programming language.
Martin
Re: (Score:2)
You mean "my favorite statically typed language". And yes, I know what you mean.
Re: (Score:2)
wikipedia on strongly typed [wikipedia.org]. Check the first item on the list :p But I agree, I should have used the much more precise term, statically typed.
Re: (Score:1)
Re: (Score:2)
Seems to fit the bill :p
More to the point, when I need to know exactly which machine I will get, I use C. Or maybe really simple C++. Once, I would have used an assembler for this, but with a solid grasp of C and as
Re: (Score:2)
Must Buy New Book For Latest Proggramming Fad! (Score:3, Informative)
Re: (Score:2, Insightful)
For what it's worth, design by contract is *very* useful when you are writing software for things that absolutely need to work, guaranteed (eg; medical, aviation, energy, etc). Eiffel is so good at this particular way of describing software that it literally changes how you think about programs.
Maybe you should take a look at it before going off about conspira
Re: (Score:1)
Also, if you've done anything regarding integration like, say, EDI, then you've been designing by contract since the 60s.
I just don't think this is as big a deal as the story makes out, and Eiffel certainly isn't the centerpi
Re: (Score:2)
Interfaces are not Design by Contract. Design by Contract is setting some conditions which are required to be true before a method can be called (preconditions), conditions which are in turn guaranteed to be true when the method returns (postconditison), and conditions which are guaranteed to be true all the way through a method's execution (invariants). Design by Contract can even be done in none-OO languages too.
For example any accessor method can, by specifying invariants, be guaranteed not to change
Re: (Score:3, Interesting)
Re: (Score:2)
No. Invariant conditions define what constitutes valid state for an object of the type in question. All objects should therefore satisfy their type's invariant conditions at all times, other than during updates when the object is in between two valid states. However, this is a very different concept from saying that the object's state must not vary.
Re: (Score:2)
But the language feature in such contexts is of limited value unless the checks are done at compile-time. Discovering at run-time that you're about to fry a patient is good only in the sense that you can diagnose that you screwed up and kick off any emergency shut-down procedure that is available. That's still better than not noti
Verbal Contracts (Score:5, Interesting)
Although we have enough freedom to switch over to a Design By Contract if we all agree to do it, we currently use documentation as a semi-formal contract, starting with design meetings where we verbally define the contract, which we write up piecemeal as we implement sections of code. Obviously, when multiple companies are collaborating on a business system, Design By Contract may be necessary to nail down the project requirements for each participating company. But in-house, what are the advantages of a formalized system over verbal, face-to-face communication? Wouldn't the meetings be held and the documentation be written anyway? As the project evolves, design changes can be implemented in an organized way, but again, the formal definitions would be redundant with the design change meetings.
Re: (Score:3, Funny)
Re: (Score:2)
Now that is a damned good reason for DbC.
But then, in the gov't contractor world, we do this all the time with the relevant agencies, no matter what the implementation language.
Re: (Score:2, Interesting)
Design by Contract basically means that someone takes the responcibility to make sure inputs and outputs are vali
Might as well ask why we type variables. (Score:2)
Yea, we have meetings anyway. Let's just make every variable in the system of no specific type. Let's use them as we need them, how we need them. We can verbally agree th
Re: (Score:2)
Using the Z3 CA the type of an object is irelevant. Does it implement the necesary interface? If yes, cool, if not, write an adaptor with a class factory that would implements that interface.
And come on, python it's not php. If you do: mystring = 10 + "something", that's not gonna work.
Re: (Score:2)
Simple Solution - Violence (Score:5, Funny)
-
-
- void
- DoSomething(...)
- {
- }
PS F Ghandi
Re: (Score:2)
Don't do that. It is insensitive, and people will simply ignore your comment!
Those comments go on the header (.h), not the source...
Re: (Score:2)
Oh great; now Steve Ballmer is going to come after your company for trademark infringment!
C++0x (Score:4, Informative)
Do a Google search for "c++ std wg" to find the working group page, which includes a list of papers and proposals.
Re: (Score:2, Interesting)
In addition to assertions, there are a number of helpful ideas that can greatly improve the readability of the language and follow the intent of the programmer, as well as improve the generated code. For instance, a "pure" keyword that specifies that a function is deterministic and has no side-effects; e.g.,square root, or returning an inverted matrix. (So if the function is called twi
The Pragmatic Programmer (Score:4, Informative)
The book The Pragmatic Programmer [amazon.com] by Andrew Hunt and David Thomas has a chapter about Design by Contract. As it's a very good book (almost a classic) about lots of different things, I suggest you read it. Check out the reviews at Amazon, they are true.
Re: (Score:3, Insightful)
I agree. It's a great read. Made me glad to be a programmer.
I'd also recommend "Code Complete".
Read both once a year
Design by contract, like all the others, are just tools. Treat them as such, and use them when you feel appropriate. No matter how good a screwdriver you have, one is never enough.
ASSERTing gets you a long way (Score:2)
I have a lot of this kind of code in my programs and it really helps find bugs, and more importantly find them where they first appear. The big advantage of using C++ and a tiny spot of macros is that they all the ASSERTs can be removed in your final
Never use assertions to check input (Score:3, Informative)
BUT, and this is important, there are times when you can have a legitimate business decision to skip input validation when the cost of the checking is higher than the cost of a mistake, esp. when these are internal methods that should never get unsanitized input. In those cases you may want to have contractual assertions without a co
Re: (Score:2)
In general, I program with the aim that no assert should ever fire under any cercumstance. Of course, it turns out they then end up firing annoyingly often
Re: (Score:2)
Do ANY of you work in the "real" world?
"assert", in C, counts as a frickin' obscenity for anything that makes it out the door (now, for debugging, sure, throw 'em in like candy on Halloween, but make sure to remove every last one before release).
End-users will, for the most part, deal with "odd" behavior. They tweak, however, when
Re: (Score:1)
Does the condition you are testing for provably not exist in the release build?
If the problem might occur in the release build, you need an if-statment. Somehow, I either succeed in proving I don't need the ASSERT or if at all (because the condition will not happen), or I put in an if-statment. Asserts have very limited value if you are building real-time code where every fault is significant, must be pr
Re: (Score:2)
If someone's life depends on the program working as should, then don't use C. In fact, don't use any stack-based language, since stack-based languages don't have any inherent upper limit for memory use of a given program, so you could run out in some strange circumstances. For the same reason you don't
Use AOP (Score:3, Informative)
Best of all, you can use as little or as much as you want and it will not interfere with your current code.
AspectC++ [aspectc.org]
Re: (Score:1, Troll)
What the...? (Score:1)
Article: +10 (Obscure to a VFP Programmer)
How about D (Score:2, Informative)
The D programming language [digitalmars.com] seems to support the idea of design by contract as a standard. From the litle I know about D, the language is close enough to C++ that a switch would be easy.
Re: (Score:2)
I have heard of D before, but now I went for a closer look, and just fell in love with it.
I'm currently writing a Qonk [liekens.net] clone in D, it's very elegant and comfortable to work with.
The major problem is that it can't bind with C++ libraries (plain C works ok, my game even uses SDL, and I already tested a small OpenGL program too.)
See an overview of D [digitalmars.com], and read about it's contract [digitalmars.com] implementation.
Re: (Score:1, Informative)
Do you mean the programming language which the author, trying to compare it to other languages in terms of features, insists on ignoring obvious functionality and features of the other languages and insists on ignoring and not correcting the comparissons even when hordes of messages informing and demonstrating him that his comparisson are full bullshi
Re: (Score:1)
For god's sake, the man claims that C++ doesn't have resizeable arrays, built-in strings, garbage collection or even class properties!
Although std::vector has always been good enough for me.
DBC for C++ (Score:1)
Maybe you just want to start here [wikipedia.org].
Several options (Score:5, Informative)
Just wait for Boost to get around to it (Score:2)
I mock, but now I really want to try it. Off to hack my own half-assed version -- Friday nights rule!
What's so special about Eiffel's capabilities? (Score:1)
So it has funky keywords to specify what the pre-conditions, post-conditions and invariants are, but is this really any different to putting assert() statements at the begin and end of your functions?
The obvious improvement in this area would be mathematically proving the pr
Re: (Score:2)
Re: (Score:1)
!a is the same as a?false:true
a&&b is the same as a?b:false (even the shortcut behaviour is right!)
a||b is the same as a?true:b (again, with the correct shortcut behaviour)
a==b is the same as a?b:b?false:true
a!=b is the same as a?b?false:true:b
Especially the latter ones are probably quite nice for IOCCC
Re: (Score:2)
Re: (Score:2)
Re: (Score:2)
You can get most of that in C++ by using the idiom of public non-virtual functions calling private virtual functions:
Re: (Score:2)
Nobody said the obvious! (Score:1, Interesting)
It's not just a matter of adding yet more lipstick to that pig, and it's not just a matter of using another language instead. There's an entire infrast
Design by Contract already implemented (Score:2, Informative)
Re: (Score:1)
Has anyone out there been following Walter's new language: D
It also supports contract programming, as well as a host of other sweet features. Very nice!
Artima (Score:2)
A quick google came up with:
http://www.artima.com/cppsource/deepspace.html [artima.com]
though search the Artima site and I'm sure you'll find lots more.
Another one:
http://www.ddj.com/184405997 [ddj.com]
A few simple techniques (Score:2)
I've been happy ensuring that:
- Every non-trivial object has a private invariant() method that is called at
Re: (Score:2)
What you want, I think, would be some sort of extended static checking using the contracts and an automated
It does matter (Score:2)
The current Eiffel compilers essentially convert pre- and post- condition sections to assertions. Faults are not detected until runtime when that code is excersised. A comprehensive test suite with full code coverage is necessary.
In other words, they don't do anything better than assertions used according to suitable conventions - except look prettier.
I'm not sure what you're getting at with respect to "a million cryptic asserts all over the place (which will perforce be bound to yo
Use macros and Condition classes (Score:2)
First: all conditions are classs that inherit from an abstract base class that defines the methods checkPecondition and checkPostcondition, the methods do the same, just checking the condition but throwing different exceptions. (Basically you overwrite only the checkCondition method and implement the constructor to call the checkPrecondition() method.)
Example:
class BaseCondition {
public:
my 2 cents on 15 years (Score:1)
First off, I wrote a little paper [baliset.com] on it at the time.
I implemented it with macros. The main issues were: