Catch up on stories from the past week (and beyond) at the Slashdot story archive

 



Forgot your password?
typodupeerror

Design by Contract in C++? 114

Posted by Cliff
from the take-from-one-language-for-use-in-another dept.
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++?"
This discussion has been archived. No new comments can be posted.

Design by Contract in C++?

Comments Filter:
  • In C++ (Score:3, Funny)

    by revlayle (964221) on Friday September 22, 2006 @05:50PM (#16163972) Homepage
    I call that "using interfaces" and "strict polymorphism" (and "bunnies"!!!)
    • Re:In C++ (Score:5, Insightful)

      by bheilig (516136) on Friday September 22, 2006 @07:17PM (#16164344)
      Here are some pitfalls you might run into:

      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)

        by Coryoth (254751) on Friday September 22, 2006 @08:03PM (#16164531) Homepage Journal
        Besides the many very good points you mention there's also the question of documentation - good DbC systems are integrated into the autogenerated documentation elegantly. All that said, you do have more options then Eiffel if you want to use contracts. If you use Java you can use JML [iastate.edu] which I believe covers all your points, and my point about documentation. If you use Ada you can use SPARK [praxis-his.co.uk] which again, covers your points quite well. Both SPARK and JML also offer (via ESC/Java2 [secure.ucd.ie] for JML) extended static checking as well as the usual runtime checking of contracts. Finally for C# there's Spec# [microsoft.com], but I don't know too much about that one.

        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.
      • by neves (324086)
        I think you only have two choices. Use Eiffel or don't use contracts.

        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

        • by jgrahn (181062)

          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.

          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.

          • by Lally Singh (3427)
            An assert failure's supposed to break right in the programmer's console or in the debugger -- d'tors aren't necessary, as it just slows the debugging process down.

            You do disable assert() in release builds, right?
      • The invariant should only be checked when the code exits out of the class boundary. e.g. If I have two classes A and B. B calls a function on an object of class A. This function then calls another method on itself. It is only when the call come back to B, that the invariant needs to be checked. This is difficult to implement without help from the compiler. It is also interesting to compare assertions and unit tests. Assertions have a big advantage over unit tests. They are tested every pass through the
  • by Anonymous Coward on Friday September 22, 2006 @05:51PM (#16163977)
    ...but I'm sure Java + XML is the answer.
    • Re: (Score:3, Funny)

      by WilliamSChips (793741)
      Anything is a better answer than C++ for anything. Except maybe COBOL and shell script.
      • by EsbenMoseHansen (731150) on Saturday September 23, 2006 @05:57AM (#16166145) Homepage

        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.

        • by psykocrime (61037)
          For the worst language I have tried yet, I nominate PL/I.

          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).
        • by zsau (266209)
          For loosely typed, ... I haven't tried ... that functional language that is so popular these days, but I will get around to it.

          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
          • 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

            • by zsau (266209)
              I was thinking more about the way two completely different things (like chars and ints) can be converted between. (Well, converting between '1' and 1 without casting wouldn't surprise me too much in the way that converting between 3.0 and 3 doesn't; but in C++ as in C you can use the same bit of memory as both '1' and ... 0x31 iirc.)

              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
              • 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

                • by zsau (266209)
                  Primitive types don't have to be an abomination in any language. You simply forbid something like 'a' + 3 from being valid syntax, and that solves one part of the problem. Creating a Character class in C++ would not be as efficient, and it can be, and do the right thing. And (worse) it means that all those things that are defined for chars, I have to define again. (I'm a little confused about where your 2.my_int_method() comment is meant to go; being able to do that sounds like it's merging the boundaries b
                  • 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 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:

          unsigned i = -1;

          is not strongly typed. In fact and just for good measure:

          #include <iostream>

          int
          main ()
          {
          unsigned i = -1;

          std::cout << i;

          return i;
          }

          >g++ test.cpp -o test
          /tmp Linux martin@linux2 Mi Sep 27 20:47:18 standart
          >./test
          4

          • 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

            • The mistake you are making (and you are not alone here) is to assume that strongly impies static. But that is not true - the typing system is 4 dimensional:

              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
              • *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

                • by krischik (781389)
                  The strongest typed language which I am aware of is Ada - and Ada indeed does not allow implicid type convertins between types. However Ada also has the concept of subtypes and will implicidly convert between them and allows for explicid type conversion. See:

                  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
        • by jgrahn (181062)
          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).

          You mean "my favorite statically typed language". And yes, I know what you mean.

        • by koreaman (835838)
          Defend your assertion that C is an assembler.
          • From wikipedia:

            High-level assemblers provide high-level-language abstractions such as:
            Advanced control structures
            High-level procedure/function declarations and invocations
            High-level abstract data types, including structures/records, unions, classes, and sets
            Sophisticated macro processing

            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

    • by AuMatar (183847)
      I'm not sure about the answer, but thats usually the problem.
  • by creimer (824291) on Friday September 22, 2006 @05:51PM (#16163978) Homepage
    It must be a conspiracy with the technical publishers to keep coming up with new technology fads to create a demand for new editions of old books. I stopped buying doorstoppers years ago because of this.
    • Re: (Score:2, Insightful)

      by Anonymous Coward
      You know, not _every_ programming design method or management method is necessarily a "fad". Some of these things are popular because they are useful.

      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
      • by Gr8Apes (679165)
        I'm sorry, but you must be somewhat mistaken. Eiffel sounds like a johnny come lately - yes, I know it's been around for a while. However Java, and C++ before it, had this concept called interfaces, and I'm sure something somewhere had the concept of Design by Contract long before then.

        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
        • by Molt (116343)

          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

          • For example any accessor method can, by specifying invariants, be guaranteed not to change any of an object's state.

            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.

      • 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).

        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)

    by dch24 (904899) on Friday September 22, 2006 @05:54PM (#16163989) Journal
    In the development environment I work in, we use entirely C++, and combine embedded Linux, desktop Linux, and several server OSes. There are six engineers working on my part of the project (the embedded part), and a similar number working on the other parts.

    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)

      by eln (21727) *
      If you make the contract long and detailed enough, it provides something to beat coders with when they violate the contract.
    • Re: (Score:2, Interesting)

      by NovaX (37364)
      What you're thinking of is more on the lines of a UML as blueprint vs. UML as sketch. DBC is purely code-level and is simply a good practice. Good programmers will at least check all preconditions (e.g. if (param == null) {throw new IllegalArgumentException("Param=NULL")}). That's step one of the DBC philosophy. Having the whole process built into the language simply makes it cleaner reduces LOC.

      Design by Contract basically means that someone takes the responcibility to make sure inputs and outputs are vali
    • "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."

      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
  • by Anonymous Coward on Friday September 22, 2006 @05:56PM (#16163993)
    I place a one line comment above each of my C++ functions that I want to have Eiffel like design by contract features:

    - // Note: If you don't pass reasonable values to this function I will fucking kill you
    -
    - void
    - DoSomething(...)
    - {
    - }

    PS F Ghandi
    • Don't do that. It is insensitive, and people will simply ignore your comment!

      Those comments go on the header (.h), not the source...

    • ...I will fucking kill you

      Oh great; now Steve Ballmer is going to come after your company for trademark infringment!

  • C++0x (Score:4, Informative)

    by DreadSpoon (653424) on Friday September 22, 2006 @05:56PM (#16163994) Journal
    One of the proposed additions for C++0x includes Contract Programming functionality built into the core language/library.

    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)

      One of the proposed additions for C++0x includes Contract Programming functionality built into the core language/library

      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
  • by Psionicist (561330) on Friday September 22, 2006 @05:56PM (#16164000)

    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)

      by mustafap (452510)
      >I suggest you read it.

      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 :o)

      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.
  • The kind of design by contract you can get in some langauges is hard to replicate in C++. You can however get a long way, and I believe do a lot of useful work, but ASSERTing on all conditions at the start of functions, and on the return value, where approriate.

    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
    • I mostly agree with you, but there's one key difference. You should never use assertions in place of input validation. You must always code as if the assertions aren't there.

      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
      • No, you definatly shouldn't use asserts to check input validation, I should have been more clear about that, sorry.

        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 :)
    • by pla (258480)
      You can however get a long way, and I believe do a lot of useful work, but ASSERTing on all conditions at the start of functions, and on the return value, where approriate.

      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
      • by Cassini2 (956052)
        I use the following rule when determining if an ASSERT should be used or an if-statment should be used:

        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
      • by ultranova (717540)

        Imagine an ATC system just randomly shutting itself down, not because of an unrecoverable error, but because of a design methodology buzzword... People die and programmers go to prison for bugs like that.

        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)

    by LLuthor (909583) <lexington.luthor@gmail.com> on Friday September 22, 2006 @06:23PM (#16164126)
    I have only every used AspectJ, not AspectC so take this with a grain of salt. AOP is basically the holy grail of design by contract. You can decide and implement powerful contracts and assertions and apply them at compile time or runtime with very little effort. They can be maintained with the code itself or as a separate aspect implemented at a higher level.

    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]
  • Design by Contract in C++?...
    Eiffel?
    Uh? Who? What? ...for how many cookies? I get the impression I need to get into more mainstream developement. I have not a clue what this is all about.

    Article: +10 (Obscure to a VFP Programmer)
  • How about D (Score:2, Informative)

    by Hyram Graff (962405)

    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.

    • by doti (966971)
      I second that.

      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)

      by Anonymous Coward
      You mean the programming language which it's author keeps on spamming the C++ newsgroups about how great D is and how everyone should drop C/C++ and move to D?

      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
      • by myzz (690332)
        You seem trollish, but anyway...

        For god's sake, the man claims that C++ doesn't have resizeable arrays, built-in strings, garbage collection or even class properties!

        • Resizeable arrays - quote from D website:

          Part of the standard library for C++ implements resizeable arrays, however, they are not part of the core language. A conforming freestanding implementation of C++ (C++98 17.4.1.3) does not need to provide these libraries.

          Although std::vector has always been good enough for me.

        • Garbage collection -
  • Maybe you just want to start here [wikipedia.org].

  • Several options (Score:5, Informative)

    by Coryoth (254751) on Friday September 22, 2006 @07:09PM (#16164312) Homepage Journal
    There are several options. You can simply use macros [eventhelix.com] as many people do. It's clunky and tends to have issues with inheritance and documentation, but it gets the job done. Alternatively you can try the digital mars c++ compiler [digitalmars.com] which supports design by contract, or if your co-workers are willing to stretch a little bit you can try the D programming language [digitalmars.com] from digital mars which is very similar to C++ but offers native contracts as well as a host of other nice features. Otherwise you can go the proprietary route and get C2 [aechmea.de] which is a C++ code generator that uses comment annotations to manage contracts and is a little slicker than the macro approach.
  • I can see it now: write contracts in a new template language, use template parameters to control run-time checking, and since it's all pure C++ (no macros), you can produce the contract documentation from the output of gccxml.

    I mock, but now I really want to try it. Off to hack my own half-assed version -- Friday nights rule!
  • Having only very passing familarity with Eiffel, I'm not sure if I'm missing something, but I don't understand any significant benefit Eiffel's capabilities have over C++'s or a host of other languages with respect to design by contract.

    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
    • by Coryoth (254751)
      As someone else pointed out, Eiffel, or anything that takes design by contract seriously, adds more than just keywords. Good design by contract should ahve contracts behave properly with respect to inheritance (preconditions can only be weakened, and postconditions and invariants can only be strengthened) with contracts being inherited properly even in overidden methods. Eiffel also allows much more fine grained control of runtime checking of contracts than asserts and ifdefs can give you unless you spend a
      • Good design by contract should ahve contracts behave properly with respect to inheritance (preconditions can only be weakened, and postconditions and invariants can only be strengthened) with contracts being inherited properly even in overidden methods.

        You can get most of that in C++ by using the idiom of public non-virtual functions calling private virtual functions:

        class Base
        {
        public:
        int something(int whatever)
        {
        // check preconditions
        int result = do_something(whatever);
        // c

        • by Coryoth (254751)
          It's a nice idea, but then you run into the problem of strengthening or weakening contracts in sub-objects, and if you have lots of classes, and hence lots of different base classes, then turning runtime checking of contracts on and off is not so easy. That's not to say it isn't a good idea and doesn't have value, especially in a language that just doesn't have any DbC facility, but it isn't a replacement fr good DbC.
  • by Anonymous Coward
    Here's this guy working for a company that exists, apparently has cashflow, and at least has some products that are actually working and that customers are buying. So he watches this video that talks about some cool shit, and wants the other programmers at his work to switch over to this cool shit, that may be cool and may also be shit for what they're doing.

    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
  • in Digital Mars C++. See contracts [digitalmars.com].
    • by GRNXNM (204086)
      Man Walter, your compilers are sweet! I've been a fan of them since you single-handedly wrote Zortech C++ (the world's first native C++ compiler). I was VERY happy to abandon my Cfront preprocessor in favor of a native compiler. And Zortech was one speedy compiler too.

      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!
  • I have seen a number of articles on DBC & C++ on Artima [artima.com]

    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]

  • The first thing to understand is that eiffel's design-by-contract features sound a lot nicer than they are. They could be very good, but most (all?) current compilers pretty much just translate them to a bunch of run-time precondition and postcondition assertions, which I find pretty yawn-worthy. Of course, I'm *VERY* far from an Eiffel expert, so feel free to politely correct me if the above is bunk.

    I've been happy ensuring that:

    - Every non-trivial object has a private invariant() method that is called at
    • by Coryoth (254751)

      The first thing to understand is that eiffel's design-by-contract features sound a lot nicer than they are. They could be very good, but most (all?) current compilers pretty much just translate them to a bunch of run-time precondition and postcondition assertions, which I find pretty yawn-worthy. Of course, I'm *VERY* far from an Eiffel expert, so feel free to politely correct me if the above is bunk.

      What you want, I think, would be some sort of extended static checking using the contracts and an automated

  • I one wrote an article about that in magazine and described a schema which I used a while.

    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:
  • I have been using contracts in C++ since 1991, so I have some experiences to report.

    First off, I wrote a little paper [baliset.com] on it at the time.

    I implemented it with macros. The main issues were:

    • It required a funny return macro, to guarantee exiting through the postconditions
    • Compilers started to complain about gotos crossing over my variable declarations. (I tried to put pre and post conditions at the top of the function, jump past the postconditions, and then on return jump back to the postconditions to exe

I've never been canoeing before, but I imagine there must be just a few simple heuristics you have to remember... Yes, don't fall out, and don't hit rocks.

Working...