Slashdot Mirror


Why Is "Design by Contract" Not More Popular?

Coryoth writes "Design by Contract, writing pre- and post-conditions on functions, seemed like straightforward common sense to me. Such conditions, in the form of executable code, not only provide more exacting API documentation, but also provide a test harness. Having easy to write unit tests, that are automatically integrated into the inheritance hierarchy in OO languages, 'just made sense'. However, despite being available (to varying degrees of completeness) for many languages other than Eiffel, including Java, C++, Perl, Python, Ruby, Ada, and even Haskell and Ocaml, the concept has never gained significant traction, particularly in comparison to unit testing frameworks (which DbC complements nicely), and hype like 'Extreme Programming'. So why did Design by Contract fail to take off?"

178 comments

  1. Because... by Anonymous Coward · · Score: 0

    It mentions the word contract, and as Mike TV's dad said "contracts are strictly for suckers"

  2. Comment removed by account_deleted · · Score: 4, Insightful

    Comment removed based on user account deletion

  3. Contracts by VGPowerlord · · Score: 2, Funny

    Darl put it best: "Contracts are what you use against parties you have relationships with."

    I don't have relationships with random other programmers (even if they are female and cute).

    --
    GLaDOS for President 2016! "Well here we are again. It's always such a pleasure." -- GLaDOS, 2011
    1. Re:Contracts by Nutria · · Score: 0, Troll
      Darl put it best: "Contracts are what you use against parties you have relationships with."

      Who's Darl?

      I don't have relationships with random other programmers (even if they are female and cute).

      Was this supposed to be funny?

      --
      "I don't know, therefore Aliens" Wafflebox1
    2. Re:Contracts by VGPowerlord · · Score: 1

      Darl put it best: "Contracts are what you use against parties you have relationships with."

      Who's Darl?

      Darl McBride, CEO of SCO.

      I don't have relationships with random other programmers (even if they are female and cute).

      Was this supposed to be funny?

      Yes. I made a second, more serious post in this discussion as well. Any time I have a really bad joke, I do that so that the real post doesn't get dragged down by the moderation on the joke post. :P
      --
      GLaDOS for President 2016! "Well here we are again. It's always such a pleasure." -- GLaDOS, 2011
    3. Re:Contracts by Nutria · · Score: 1
      Darl McBride, CEO of SCO.

      Oh, him. Does anyone actually pay attention to him anymore?

      --
      "I don't know, therefore Aliens" Wafflebox1
    4. Re:Contracts by Richard+Steiner · · Score: 1

      Oh, him. Does anyone actually pay attention to him anymore?

      Some folks still do... :-)

      --
      Mainframe/UNIX Bit Twiddler and long time Windows/Linux Hobbyist.
      The Theorem Theorem: If If, Then Then.
  4. Who cares? by jrockway · · Score: 2, Insightful

    Who cares if it's popular? If it solves your problem, use it.

    --
    My other car is first.
    1. Re:Who cares? by heinousjay · · Score: 2, Insightful

      You win the topic. Everything else is masturbation.

      --
      Slashdot - where whining about luck is the new way to make the world you want.
    2. Re:Who cares? by Just+Some+Guy · · Score: 4, Insightful

      Who cares if it's popular? If it solves your problem, use it.

      Two reasons: first, the more people use it, the wider it will be supported. It's nice to be involved with something on the upswing that more people are interested in than bored with. Second, it's nice to know why something's unpopular. Maybe it's hard to use, but you're a genius and will be able to put it to work. Or, maybe, everyone else realized that it's awful and moved on to something less heinous.

      --
      Dewey, what part of this looks like authorities should be involved?
    3. Re:Who cares? by rednip · · Score: 1

      Who cares if it's popular? If it solves your problem, use it. Key word is 'if'. Also only 'if' one designs the contract perfectly, and only 'if' one is able to test it to perfection.
      --
      The force that blew the Big Bang continues to accelerate.
    4. Re:Who cares? by Haeleth · · Score: 1

      You win the topic. Everything else is masturbation.
      You're missing the point that it's not just about me solving my problems. Other people's problems are also relevant to me, since I have to use software written by other people every day. So it is perfectly sensible and valid for me to be interested in whether other people are making full use of the problem-solving tools available to them, because if they do, the software I have to use will be cheaper, available sooner, and more reliable.
    5. Re:Who cares? by heinousjay · · Score: 1

      No, you're missing the point, apparently. What you're hinting at comes dangerously close to dictating other people's programming methodology. Making full use of the tools available doesn't mean everyone has to do it the one true way. There are many ways to solve many problems, and everyone has a different set of balanced requirements which are best solved by different tools. You don't know everyone's answer better than everyone else.

      Which all boils down to: if it works for you, go for it. Waiting for it to be popular is for people who listen to Britney Spears. Popularity has nothing to do with merit in engineering.

      --
      Slashdot - where whining about luck is the new way to make the world you want.
    6. Re:Who cares? by cyclop · · Score: 1

      Are you sure you aren't confusing "dictating" with "understanding" or "advising"?

      --
      -- Patent no.123456: A way to personalize /. comments with a sig attached to the end.
  5. no bang for your buck by majiCk · · Score: 3, Insightful

    Design by contract seems like a lot of extra work and runtime cost for something that might once in a while catch a bug in already-deployed code. Lighter weight methods like static typing catch (certain kinds of) errors before the code is even compiled; unit testing is usually done before code is deployed, and with the express aim of exposing incorrect behavior in corner cases.

    Just what niche is design-by-contract supposed to fill? It's heavyweight, costly at runtime, undirected, and likely to catch bugs only after deployment -- too-little-too-late. Maybe it's unpopular because it's a poor tradeoff.

    1. Re:no bang for your buck by barrkel · · Score: 4, Insightful

      In a phrase, the niche is professional coders, rather than hack-a-day cowboys.

      Assertions, whether invariants, preconditions or postconditions, can be viewed as extensions to the type system [1]. Since they are expressions of a boolean type and don't modify state (at least, no sane ones would mutate state), they're very easily analysed.

      Combine that with a runtime like .NET or the JVM. Compilers and analysers can use such contracts to perform extra typechecking of e.g. arguments to methods, where the methods have preconditions. "Runtime cost" doesn't exist if the runtime has support, especially where verification also exists. Consider the old conundrum: do you check your parameters, or do you expect your caller to check the arguments before they're passed? What if the parameters being wrong leads to a subtle error that manifests later rather than a dramatic failure? With properly stated contracts, these checks can be inserted at the lowest level and automatically propagated higher statically by the compiler or dynamically by the runtime as necessary.

      The niche that DbC is supposed to fill is formalising what is already recognised good practice - stating your assumptions while writing your code. If you have much experience as a programmer, you'll know that it's useful to use assert, ASSERT, or some other feature of your environment at choice places where you make certain assumptions that you think can't be broken. And if you've read The Pragmatic Programmer, you'll know why you'll want to leave those assertions in the final release.

      Most popular languages, such as C#, Java, C++ etc., capture very little programmer intent in their type systems. There's a lot more potential there - preconditions and postconditions can e.g. state that a variable will be in a certain range dependent on the values of other variables, and then automatically detect range mismatches with e.g. loop invariants. Basically, assertions are really useful extensions to the type system.

      [1] For example, consider that a 'requires x != null' constraint and a notional non-nullable reference type from C# or Java, analogous to 'MyType!' in C-w (C Omega):
      http://blogs.msdn.com/cyrusn/archive/2004/06/03/14 7778.aspx

    2. Re:no bang for your buck by Coryoth · · Score: 3, Insightful

      Design by contract seems like a lot of extra work and runtime cost for something that might once in a while catch a bug in already-deployed code. Lighter weight methods like static typing catch (certain kinds of) errors before the code is even compiled; unit testing is usually done before code is deployed, and with the express aim of exposing incorrect behavior in corner cases. DbC doesn't incur any runtime cost if you choose not to bother - any good contract system allows you to turn off contract checking for production code. That is, DbC provides a test harness during testing but needn't do any checking of finished code after testing is complete. Moreover good contract systems like JML and Spec# are smart enough to allow static checking which allow you to catch a whole host of errors before compilation that static types just aren't going to be able to catch. And I have to admit that I am unsure how DbC is "a lot of work" given that you should be writing unit tests anyway, and if you have constraints or invariants then you ought to be checking those with unit tests - writing the constraint as a contract is less work than writing the equivalent unit test. Finally DbC enables testing that for which unit tests of corner cases simply can't compare - by using the contracts as a test oracle you can do automated randomised testing of several integrated units. That is to say, you can automatically generate data to search the input space delimited by preconditions, and use postconditions, invariants, and preconditions of any called code, to test that several units all work together correctly and potentially catch weird interelated corner cases that you hadn't anticipated. Honestly, check out AutoTest or Quickcheck sometime, they are suprisingly powerful and have found bugs in established production code that had already undergone extensive standard testing.
    3. Re:no bang for your buck by Tablizer · · Score: 2, Interesting

      In a phrase, the niche is professional coders, rather than hack-a-day cowboys.

      I think you are being naive. In the real world they often want as many features as possible with the smallest staff possible. This means that things like formal testing are glossed over. It is an art-form to deliver tons of features on the cheap. Of course, it depends on the nature of the business. If it is the Space Shuttle or medical equipment, then you better spend the extra money or you will get sued up the wazoo. An intranet app will also have a different Q.A. profile than packaged software, since the ratio of users per line-of-code is different. The US's comparative advantage is being nimble, not formal, such that the beurocracy for Q.A. is often bypassed to keep up. If the idea becomes a commodity idea such that requirements and thus testing it is easy and stable, development gets shipped overseas.

    4. Re:no bang for your buck by Anonymous Coward · · Score: 0

      MMC 3.0 uses 'some' DBC ideas for its snap-in model. It works great for 3rd party devs to find bugs in their code after MMC has shipped. However, it is not at a block level, it is only at the public interfaces. DBC is no excuse not to have a good add-in architecture.

    5. Re:no bang for your buck by ozone_sniffer · · Score: 1

      DbC doesn't incur any runtime cost if you choose not to bother - any good contract system allows you to turn off contract checking for production code. Runtime checks should be left turned on even on production environment, methinks. The performance hit you suffer is not that great, generally. If it *really* is that great, you should be somehow able to identify where the runtime check is mostly contributing for the performance hit and disable the checks only in those most affected modules. By using such strategy, you are then able to take the most advantage (i.e. greater return of your investment) from that checking code you wrote (by using assertions, DbC, or whatever else will do the type of checking you need).
    6. Re:no bang for your buck by Coryoth · · Score: 1

      I agree, my point was simply that it needn't cost you any runtime performance in production if you don't want it to. As you say, it is easier to leave checking on for all but the expensive portions which, with a good DbC system, is easy to do.

    7. Re:no bang for your buck by mattpalmer1086 · · Score: 1

      In the "real world" you're right, unfortunately. However, you shouldn't discount it out of hand. The "real world" methodologies you use, like structured programming and object oriented programming were once regarded as ridiculous overheads - but the thing is, they actually reduce programming effort overall by making code more robust. I don't think I've used a GOTO in a long time.

      Someone once said (can't remember who) that making a program was like piling 100 bricks on top of one another, but using OO programming was like dividing those bricks into 10 piles of 10. It's more stable, but at the cost of additional overhead in setting up those structures. Not only that, by forcing a more structured approach, many untested assumptions get flushed out by the design.

      That's why the question posed by this topic is interesting. DbC offers another way to provide better semantics in the code - but it hasn't taken off. Maybe the benefits aren't generally worth it for your average code - I certainly can't speak from experience here.

    8. Re:no bang for your buck by barrkel · · Score: 1

      Software development is a wide field. Sometimes developers are writing business rules, in which cases sometimes I can agree, implementing as many features as possible with as small a staff as possible, will produce low-quality code. But that code would be low quality whether or not DbC was implemented. You can have any two of (low cost, high quality, short development). It doesn't really change things.

      My experience is in application server runtimes and compilers. In those cases, I've learned that, for want of a less common term, a stitch in time saves nine. Assertions written into the codebase find bugs sooner than users report them, and it's certainly better to find those assertions before corruption occurs that could cause far worse problems.

    9. Re:no bang for your buck by xero314 · · Score: 1

      Design by contract seems like a lot of extra work and runtime cost... DBC in use is actually a lot less work and a lot less runtime cost. DBC, if used properly, produces software that has a much shorter testing and debugging period. Regression testing is much faster as the contract will not have changed on any of the prior built parts. The though that there is a performance reduction effect of DBC, which is what I assume is meant by "runtime cost" is a lack of understanding DBC. There is nothing in DBC that says there needs to be any runtime checking of the contract. In fact it is supposed to reduce the need for such runtime checking. Since both sides of any messaging has agreed to the interface contract and all it's restrictions, there is no need to runtime check. If my contract states the pre conditions are a whole number between 1 and 10 the consumer agrees to only supply a whole number between 1 and 10 and the effect of anything else need no be defined. It's a good thing to have those check available, such as through Java's assertions or through languages like Eiffel but these should only be turned on during testing and not in an actually production system. And yes it is possible to check against DBC conditions at compile time as much as you can in any other design methodology since there is nothing saying you can't use static type checking (which is a whole other problem in it's own right).

      [DBC]'s heavyweight, costly at runtime, undirected, and likely to catch bugs only after deployment... DBC allows much faster development cycles than other methodologies. By enforcing interface contracts, including, pre/post conditions and invariants, you can actually test your program before the costly effort of actual development takes place. Using DBC you can reduce the very costly effects of re-factoring written code, which is very common in most of todays agile methodologies.

      Also try and realize that DBC is nothing new as it has been used for hundreds maybe even thousands of years, it just happens to be new to software. But as I have said many times before if we would move away from software development and toward software engineering DBC wouldn't even be in question, it would be the norm. But then again if we engineered software bugs would be the exception rather than the norm as it is today. (I will note that this applies to Business Application Software and not more life critical systems that are often well designed and use most of the tenants of DBC).
    10. Re:no bang for your buck by xero314 · · Score: 1

      In the real world they often want as many features as possible with the smallest staff possible. I think you are being even more naive than the parent commenter. What businesses, including governments, want in the real world, is software that produces the most monetary benefit with the least monetary cost over the life of the system. Sometimes there are certain intermediary goals that effect this, but ultimately what I just said is the goal. If your are a software developer and are not attempting this same thing you are doing your client or employer a disservice at best, and at worst stealing. This being said, processes such as DBC are very good at reducing total cost over a life time by reducing maintenance cost dramatically, and having at least a noticeable effect by reducing unnecessary functionality. It just so happens that because we have a bunch of console jockeys as opposed to engineers running software projects most clients are never given the knowledge they need to make valid decisions about how to approach a software project. Luckily it has not gotten so bad as to make everyone believe the hype that off shoring actually cost less than domestic development.
    11. Re:no bang for your buck by Anonymous+Brave+Guy · · Score: 1

      In the real world they often want as many features as possible with the smallest staff possible.

      I think what they usually want is the best return on investment, which isn't necessarily the same as what you wrote there.

      In any case, I think your entire post is backwards, though I've heard the same argument many times before. If you want to get lots of features working quickly, the only way to achieve it is to do the development properly. Neglecting QA is a false economy, as is dropping other defensive programming and active testing approaches earlier in the development process, which if anything are more valuable, because they find problems sooner. This is why the whole "pick two of good, fast and cheap" thing is quite misleading: while the up-front costs for people who can do good and fast can be a lot higher than those of code monkeys, they'll give you a much better product that is likely to cost far less measured over its entire lifetime.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    12. Re:no bang for your buck by berenddeboer · · Score: 1
      In "Design by Contract to Improve Software Vigilance" (IEEE Transactions on Software Engineering August 2006) the authors prove that, unlike your assertion, there is a lot of bang for the buck. Conclusion:

      It appeared that efficient contracts significantly contributed to improving the quality of the systems, but also that their efficiency is more important than their quantity.
      --
      If I had a sig, I would put it here.
    13. Re:no bang for your buck by Tablizer · · Score: 1

      I agree that unit tests and other formalisms would help a system be more maintainable, but I cannot agree with OOP doing it. You compare OO like going from unstructured (goto) code to structure. I don't believe in that leap. OOP tends to compete with the database, not so much application code techniques. It is a navigational model of "domain nouns" versus a relational model.

    14. Re:no bang for your buck by Tablizer · · Score: 1

      implementing as many features as possible with as small a staff as possible, will produce low-quality code.

      You are assuming a fixed target. Like I said, the US's comparative advantage is changing faster than 3rd-world countries doing the same thing with cheaper staff. Thus, bending with new requirements is more important than being bug-free. Many of the formal methods put too much e-beurocracy around code, making it labor-intensive to change. Many of the formal techniques assume a stable interface but a bubbling implementation. Often it is the other way around.

      The best way to do this IMO is the keep the abstractions light, lightly coupled, and tossable; not build overarching frameworks that you have to marry.

    15. Re:no bang for your buck by mattpalmer1086 · · Score: 1

      I would say that almost any formalism that moves the semantic intention of the code closer to the domain it models more maintainable. So in this sense, the move to OO programming is definitely comparable to the move to structured programming. This has nothing to do with whether a database is involved or not.

      However, you do raise an important point, in that we have different models for data and code, and thus there is an "impedance mismatch" between them. In this sense, combining OOP and relational is difficult and ends up creating all sorts of complicated artifacts that detract from the intention of the code.

      It's not that OOP competes with a database, any more than aspect oriented programming competes with structured programming, or functional programming competes with declarative programming. They are simply different models, that offer their own advantages and disadvantages. Code that has to address more than one model will always introduce artificial and difficult constructs, unless they have some kind of essential compatibility between the models.

    16. Re:no bang for your buck by Anonymous+Brave+Guy · · Score: 1

      Thus, bending with new requirements is more important than being bug-free.

      You write as if they are mutually exclusive. Why?

      Many of the formal techniques assume a stable interface but a bubbling implementation. Often it is the other way around.

      That makes no sense. The whole point of the interface/implementation separation is that you can change the implementation without changing the interface. If you change the interface, you will necessarily change the implementation at least enough to match.

      I'm also curious about your repeated reference to "formal" techniques. What do you mean by this? Do you also consider unit tests a formal technique? Commenting code? Structured programming? Where do you draw the line between what is helpful and what is a burden?

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    17. Re:no bang for your buck by epine · · Score: 2, Insightful

      In a phrase, the niche is professional coders, rather than hack-a-day cowboys.

      Unfortunately, hack-a-day cowboys gained control of both the house, the senate, and the clone army, so hack-a-day coding practices are now the accepted norm, and people look at you funny when you pinch your brow in abject frustration.

      The problem with DbC is that the benefits are best understood by an examination of the system as a whole, rather than the culturally ascendant analysis that permits the cable companies and telcos to put forward the view, in all seriousness, that the demise of net neutrality increases their incentive to invest in their network infrastructure, whereas game theory shows that it has precisely the opposite effect. Most people--in any professional context--are heavily invested not in full systems analysis, but careerist analysis whose principle arguments reference the power hierarchy rather than the behaviour of the system in which the power hierarchy is embedded. The careerist analysis that DbC is relatively worthless is accurate enough in its own scope: after all, the cowboys now rule the world.

      I incorporated DbC principles into a large and complex C application (at that time still MSDOS based) shortly after the Meyer book was published in 1988. I never believed that DbC can only be practiced in a language that directly supports it (I regard that as outright language bigotry propoganda). DbC is an intellectual practice. What you can't achieve in a language that doesn't support DbC is the imposition of DbC on participants who don't otherwise choose to participate voluntarily. However, managing to impose DbC on a participant who wouldn't do so voluntarily is at best a hollow victory: compliance over enthusiasm rarely produces the best results.

      We imposed DbC by a different tactic. Anyone caught tracing through code in the symbolic debugger was subject to anyone walking past making police siren noises. "How am I supposed to concentrate on debugging this code if everyone is making stupid sound effects?" Answer: "If you have to concentrate that hard to understand your code, you aren't doing it right." Time spent in a debugger produces no asset to the code base, yet it requires the greatest level of concentration. How could that be right?

      After we instituted DbC principles, we didn't get many bug reports. Over a three year period, about half of all our bug reports pertained to *one* module written before DbC was instituted. No one wanted to rewrite that module because it involved an external file format which needed to remain compatible, but the exact requirements of the file format were hard to reverse engineer from the conceptually-damaged code base.

      The other critical aspect of that situation is that I vetoed many design choices where DbC would have been less beneficial. Some design approaches don't mesh well with DbC. You can still go through the motions, but the conditions you can actually express never catch what you really want to catch at the moment it most needs to be caught. For DbC to work well, you need to choose designs where consistency is a local property of your data structures rather than a global property that can only be enforced by some kind of global fsck. If you have sideways paths into a recursive data structure, you have no hope of checking invariants on the nested context you didn't descend through.

      When we did have a bug report, it never took us long to find the code responsible. Most of the plausible theories were eliminated immediately because we shipped with the vast majority of DbC assertions enabled. "This bug would result if function foo returned NULL, but wait, there is a live assertion right here that proves this never happens." Then when we did find the right chunk of code, we rarely felt we needed to test the change for a week or more before shipping out the patch to the affected customer: there was so many assertions in so many directions, it was hard to construct a theory

    18. Re:no bang for your buck by Tablizer · · Score: 1

      I would say that almost any formalism that moves the semantic intention of the code closer to the domain it models more maintainable. So in this sense, the move to OO programming is definitely comparable to the move to structured programming.

      I've never seen a good argument that clearly shows that OOP better models the "real world". There are no consensus metrics for such, and it usually turns into an unsettlable psychology debate. Worse, much in my domain is not even based on the real world, but things like intellectual property, laws, marketing promotions, etc. It is not comparable to modeling tugboats and loading docks. As far as your other sentence, Goto's actually model the real world better than structured blocks. Blocks are to help it fit human programmers, not fit the real world.

      It's not that OOP competes with a database, any more than aspect oriented programming competes with structured programming, or functional programming competes with declarative programming. They are simply different models, that offer their own advantages and disadvantages.

      I disagree. OOP and databases (or at least relational theory) overlap enough to cause headaches. Nobody has described a good consensus approach to showing where one ends and the other starts. The relationship between OO and relational is still a messy problem after being recognized for about 13 years. When push comes to shove, I find the database is a better choice over OOP. Set theory better fits my domain than the network graphs that OO offers, at least better fits the way I think about it. Thinking in sets will change the way you view OOP. Try it for a while.

    19. Re:no bang for your buck by Tablizer · · Score: 1

      That makes no sense. The whole point of the interface/implementation separation is that you can change the implementation without changing the interface. If you change the interface, you will necessarily change the implementation at least enough to match.

      My experience is that you cannot maximize both of these at the same. A technique that favors implementation changes will tend to deminish those that favor interface changes (due to changing requirements). Implemenation swapping frequency is exaggerated in most literature in my opinion. I believe this comes from OOP hype, with shape, animal, and device driver examples being overused.

      Where do you draw the line between what is helpful and what is a burden?

      That is my point. One has to weigh the tradeoffs. There is no free lunch. The weights you assign to each competing factor or technique should depend on the domain (company needs and environment).

    20. Re:no bang for your buck by mattpalmer1086 · · Score: 1

      I've also never seen a good argument that it models the real world - I've heard some hard-core OO people try to argue that, but I don't agree. By the way, I didn't say it models the entire real world better, just some domains. It's certainly good at modeling some things I've worked on better than structured programming. There are cases where encapsulation and polymorphism is useful! However, the mere fact of aspect-oriented programming shows that there are still plenty of cases where it falls down in trying to model things naturally. Most things don't really naturally fit into a simple hierarchy.

      I have to say, I can't see how gotos model anything much at all outside of the programming language itself - they're just jumps to another code location, but I'm prepared to learn, if you can show me what they are good at modeling. Structured blocks can at least be used to model things outside of itself - although it certainly doesn't insist that they do.

      I completely agree with you that the mismatch between relational and pretty much any other form of coding - not just OO - causes headaches. It's a mistake to pin that only on OO though, IMHO, although OO does seem to have a particularly rough time with it.

      By the way, I've been working heavily with relational databases for about 15 years, and I've just completed a masters dissertation which is mostly about certain practical applications of set theory. It doesn't change the way I think of OO - they are just different models - give it another go!

    21. Re:no bang for your buck by ioshhdflwuegfh · · Score: 1

      Does anything more need to be said about why "bang for buck" cowboys don't practice this method? You mean other than that they get more bang for less buck?
    22. Re:no bang for your buck by Anonymous Coward · · Score: 0

      I seriously doubt you were using "Design by Contract" without language support or some additional pre-compiler.

      I suspect what you were actually using was a little thing we normally call "assert".

      Did your pre/post-conditions get automatically inherited by subclasses?

      Could you weaken your pre-conditions and strengthen your post-conditions?

      Copying and pasting code doesn't count either, as you can change the pre/post-conditions to say anything you want in the subclass, which eliminates the benefit.

      Good for you for using asserts so religiously, but don't confuse it with DbC.

    23. Re:no bang for your buck by Tablizer · · Score: 1

      I have to say, I can't see how gotos model anything much at all outside of the programming language itself - they're just jumps to another code location, but I'm prepared to learn, if you can show me what they are good at modeling. Structured blocks can at least be used to model things outside of itself - although it certainly doesn't insist that they do.

      I meant that the real world is chaotic, and if you drew lines between concepts we encounter in the real world, you will generally get a bunch of pointers/arrows, Go-To like. Nested blocks don't reflect the real world, they are just human work aids.

      I completely agree with you that the mismatch between relational and pretty much any other form of coding - not just OO - causes headaches. It's a mistake to pin that only on OO though,

      I still disagree. Non-trivial OO tends to build data structures built out of objects (OO "composition" for example). These data structures tend to mirror the RDBMS more or less, or at least compete with it. If you do the work with queries, you often don't need to do the same work by allocating and traversing object pointers. (Some tools let you create local or temporary tables if need be.)

      It doesn't change the way I think of OO - they are just different models - give it another go!

      I believe OO is a subjective preference. It does not work smooth for me. If you can show *objective* evidence it is better, I am all ears/eyes. If you like it personally, fine. Enjoy it. To each their own.

    24. Re:no bang for your buck by mattpalmer1086 · · Score: 1

      I meant that the real world is chaotic, and if you drew lines between concepts we encounter in the real world, you will generally get a bunch of pointers/arrows, Go-To like.

      Good points. Although the lack of constraint imposed by goto makes it more of a modeling mechanism than a useful model in its own right, IMHO.

      Nested blocks don't reflect the real world, they are just human work aids.

      I agree they don't reflect the real world, but wouldn't you agree that the ability to group things that do common tasks and give them names can help in modeling? Local state also provides encapsulation that limits the temptation to use global variables, so it also improves code stability.

      I still disagree. Non-trivial OO tends to build data structures built out of objects (OO "composition" for example). These data structures tend to mirror the RDBMS more or less, or at least compete with it.

      I think I see where we disagree. You're talking about cases where OO is specifically used to interface with a database oriented application. I agree that OO doesn't fit the relational world very well at all. I still shudder when I remember how much effort it was to create an OO-relational mapping layer for a non-trivial database application back in 2001. So I think I know what you mean here.

      The thing about OO is, there are applications and services that don't interface with databases, and wouldn't benefit from doing so. Things where the world really does consist of directed object graphs - then OO really shines, and the relational world struggles.

      I believe OO is a subjective preference. It does not work smooth for me. If you can show *objective* evidence it is better, I am all ears/eyes. If you like it personally, fine. Enjoy it. To each their own.

      Fair enough - we all have our likes and dislikes, and we all work on different things. I actually like both, but for different things.

    25. Re:no bang for your buck by Tablizer · · Score: 1

      You're talking about cases where OO is specifically used to interface with a database oriented application.

      Not really. Please reread.

      The thing about OO is, there are applications and services that don't interface with databases, and wouldn't benefit from doing so. Things where the world really does consist of directed object graphs - then OO really shines, and the relational world struggles.

      Outside of performance and hardware constraints, I have not seen very many such situations. Relational builds more disciplined and consistent structures than graphs (maps of map pointers in OO's case) in most cases. The exceptions are not many, and often traceable to specific implementations of relational rather than the concept itself flunking.

    26. Re:no bang for your buck by mattpalmer1086 · · Score: 1

      Having re-read, I'm still not sure where we disagree! Are you saying that even if the application wasn't interfacing with an RDBMS, a relational model would be better than taking an OO approach? You do specifically refer to RDBMSs earlier, so that's where I got the database from.

      Do you have any examples of a system that doesn't interface with a database but that could still be considered relational in some sense? I don't know any coding systems that are relational outside of databases. Or are you saying that just using structured programming would be better than OO in most cases? Or that anything would be better than OO?!

      It's true that you can build appallingly horrible structures in OO, but you can build appalling models using a relational approach too - I've seen lots of examples of both myself. Anyway, as I said, I like both - we'll just have to disagree about which is the one model to rule them all!

    27. Re:no bang for your buck by Tablizer · · Score: 1

      I used to use a lot of dBASE-dirivatives (FoxPro, Clipper, etc.) now known collectively as xBase. Although xBase had some annoying language flaws, it did make working with tables so easy and directly that after a while one starts "thinking in tables". The seperation between application language and "database" generally didn't exist: they were intimately integrated and intertwined. It was a great idea that needed a little clean-up to scale a bit better. It is hard to get the same integratedness with today's tools/styles.

    28. Re:no bang for your buck by mattpalmer1086 · · Score: 1

      Ahhh.. I remember dbase. I used foxpro and dbase tables a bit myself, but ended up having to use Borland's Paradox for most desktop database applications. I didn't get into client-server until much later. Paradox was a bit sucky, I have to say.

      It would be interesting to dig them all out again and run them in an emulator or something. I remember there was this whole thing about database 4GLs at the time.

    29. Re:no bang for your buck by Tablizer · · Score: 1

      I never grew too fond of Paradox. There is something odd about it that I cannot quite put my finger on. Maybe if I used it longer. Plus, it's GUI seemed to ignore expected Windows conventions in order to be cross-platform, driving users bats, and thus had many of the same GUI flaws as Java GUI's.

    30. Re:no bang for your buck by try_anything · · Score: 1

      Implemenation swapping frequency is exaggerated in most literature in my opinion.

      I have to say that in my experience, the messiness of the real world is what forces implementation swapping. Half a dozen input file formats, misimplemented variations on those formats, the need to support both local and distributed processing, the need to interface with different forms of flow control, a long list of optional data filters, motley assortments of hardware peripherals that act differently but serve the same function -- we have to use exactly the ones available in the machine, even if they are of several different kinds --, etc. Polymorphism is the only thing that keeps my code readable, and the partial ignorance enabled by polymorphism is the only way I can wrap my head around the whole thing.

      I don't doubt that other domains have different demands, but in my case, I am constantly faced with things that serve the same function but have very different implementations.

  6. Extreme Programming by andy314159pi · · Score: 4, Funny

    I employ what is known as "Extreme Programming." It mostly involves alot of screaming at the monitor and yelling at my coworkers. I get fired alot but I never have a hard time getting a new job with my Extreme Programming skills that I write all over my resume.

    1. Re:Extreme Programming by moderators_are_w*nke · · Score: 1

      As a porofessional developer, I find swearing at the monitor and ranting at my coworkers to be pretty effective and as yet, it hasn't got me fired. I have recently joined an XP shop (the company formally known as Connextra) so I could now try the extreme approach you describe.

      --
      "XML is like violence. If it doesn't solve your problem, use more." - Anonymous Coward
    2. Re:Extreme Programming by ioshhdflwuegfh · · Score: 1

      As a porofessional developer, I find swearing at the monitor and ranting at my coworkers to be pretty effective and as yet, it hasn't got me fired. I have recently joined an XP shop (the company formally known as Connextra) so I could now try the extreme approach you describe. Next thing you'll tell me is that your ranting is part of the negotiating of contracts with your DbC team.
  7. Re:Management by rednip · · Score: 0, Troll

    Agreed fully, but I'll add one half-drunk observation: Fucking Business analysts are bull-shit artists who don't know objects, nor functions if they got smacked in the heads with them. 90% of the time they bill is a complete waste of company money. Also, 60% of 'Architects' fall into the same category.

    --
    The force that blew the Big Bang continues to accelerate.
  8. Design by Contract by VGPowerlord · · Score: 2, Informative

    Design by Contract adds more complexity to code, particularly if you're dealing with a language that doesn't natively support it.

    Of course, you don't actually need special constructs to check values on input then tossing an exception/returning an error when the data is not in the expected range. In fact, you should go back to remedial programming classes if you're not already doing this.

    The last thing you should do is try to figure out what the caller really meant if the value is out of range. Assuming a default works in some cases (which, btw, wouldn't work with Design by Contract as I understand it), but most of the time it's just better to fail and make the programmer fix their mistake.

    --
    GLaDOS for President 2016! "Well here we are again. It's always such a pleasure." -- GLaDOS, 2011
    1. Re:Design by Contract by berenddeboer · · Score: 1
      Perhaps you should read up a bit on DbC as you're confused about its usage. Design by Contract should not be used for input testing!! As Bertrand Meyer states in his seminal "Object-Oriented Software Construction":

      Assertions are not an input checking mechanism ... To avoid a common misunderstanding, make sure to note that each of the contracts discussed holds between a routine (the supplier) and another routine (its caller): we are concerned about software-to-software communication, not software-to-human or software-to-outside-world. A precondition will not take care of correcting user input.
      --
      If I had a sig, I would put it here.
    2. Re:Design by Contract by VGPowerlord · · Score: 1
      You should re-read what you quoted. Here, I'll bold the relevant word.

      Assertions are not an input checking mechanism ... To avoid a common misunderstanding, make sure to note that each of the contracts discussed holds between a routine (the supplier) and another routine (its caller): we are concerned about software-to-software communication, not software-to-human or software-to-outside-world. A precondition will not take care of correcting user input.

      It is in fact used for input testing, to make sure that the inputs have a value within a valid range.
      --
      GLaDOS for President 2016! "Well here we are again. It's always such a pleasure." -- GLaDOS, 2011
  9. It needs serious language support by Animats · · Score: 5, Informative

    If you're serious about design by contract, you need to use a language that supports it. Eiffel does, of course, and so does "Spec#", Microsoft's verifiable variant of C#, but other than that, "support" is a collection of half-baked add-ons that don't provide any strong assurances.

    If you're going to take object invariants seriously, you have to take object invariance seriously. Objects can't be allowed to change other than when control is inside them, and when control is inside the object, no public method of the object can be called. This means you have to be able to catch cases where object A calls object B which then calls a public method of A. The invariant of A isn't established at that point, and so, calls into A are illegal. This strict notion of inside/outside is fundamental to class invariants, but many so-called "design by contract" approaches gloss over it. You need a way to explicitly say "control is now leaving this object temporarily" when calling out of an object, and the object's invariant must be true at that exit.

    Threading and locking have to be handled in the language. The language needs to know which locks protect what data, or invariants aren't meaningful.

    Then there's the problem of how to express an invariant, entry, or exit condition. Are quantifiers provided, or what? How do you talk about concepts like "forward and back pointers of the tree must be consistent"? There's known formalism for that sort of thing, but it's not something you can express cleanly in, say, C or C++.

    Without smarts in the compiler, run time checking tends to be too expensive. The compiler needs to know that member function F can't change member variables X and Y, and therefore, invariants concerning X and Y don't have to be rechecked. Without optimizations like that, you end up rechecking everything on every call to every access function.

    I'd like to see more design by contract, and I'd like to see it work well enough that when something breaks, you know which side of the interface to blame. I used to do proof of correctness work, and it's quite possible to do this. But you can't do it in C or C++; the languages are too loose. It's been done well for Modula and Java, and a DEC R&D group had a very nice system going just before Compaq canned DEC's Palo Alto research labs. The rise of C killed off verification work; the decline of C may bring it back.

    1. Re:It needs serious language support by Anonymous Coward · · Score: 0

      you have to take object invariance seriously.

      Most "bolt on" DbC setups appear to deal with correctness only at the function level anyways, which means that the contract is guaranteed to be accurate when a function starts and when a function ends.

      The other way (and in my opinion, better) to do it is as the sibling said: contractual variable values. This guarantees at any instant in the execution the state (in variables) is contractually correct. This would be done for instance by extending variable types with the contractual information, for instance a "charge" type could be created from a fixed-point variable with 2 decimal places and guaranteed to have a value greater or equal to zero, while the "refund" data type would be a fixed-point 2 decimal place variable whose value is less than zero.

    2. Re:It needs serious language support by timeOday · · Score: 1

      It's been done well for Modula and Java
      By whom? I'd like to look into it for my Java projects.
    3. Re:It needs serious language support by Coryoth · · Score: 2, Informative

      By whom? I'd like to look into it for my Java projects. DEC R&D made ESC/Java (Extended Static Checking for Java) that used a theorem prover and specification annotations to verify contracts. Development stopped, but it is now open source as ESC/Java2 which uses JML as annotation markup. I actually listed this as the Java DbC implementation in the article description.
    4. Re:It needs serious language support by Anonymous Coward · · Score: 0

      Don't forget the D programming language.

      Although rudimentary it does support a limited design-by-contract right in its C-like language.

  10. Re:Management by ShieldW0lf · · Score: 3, Insightful

    A good business analyst will answer the question "What is it that we (the client) need." They help make sure that the excellent code you write, when it's doing as you were hired to write it to do, solves problems instead of making them.

    A good architect will help establish clear separation of authority, giving team members more autonomy to go do what they're good at without having other peoples fingers in their pies or needing to leave their area of scope.

    There are a lot of people with pieces of paper from a school that are terrible at these things, and they muddle along leaving wreckage behind them. But that doesn't dismiss the value of having someone competent in those roles when you can find them.

    --
    -1 Uncomfortable Truth
  11. Mod parent up by lewp · · Score: 0, Offtopic

    +1 accurate description of extreme programming

    --
    Game... blouses.
  12. Too many layers by Geoffreyerffoeg · · Score: 3, Insightful

    You know the aphorism about how any CS problem can be solved by another layer of indirection -- except the problem of too many layers of indirection. That's what design-by-contract is. Instead of having the intrinsic type-safety checks and the social trust that the code author has run unit tests if necessary and makes the code do something reasonable, design-by-contract formalizes all this and makes you specify conditions on the code manually. That's quite a bit of effort for relatively little advantage. The popular design-by-informal-agreement works almost as well and doesn't have the extra, unneeded layer of indirection.

    1. Re:Too many layers by Coryoth · · Score: 1

      Instead of having the intrinsic type-safety checks and the social trust that the code author has run unit tests if necessary and makes the code do something reasonable, design-by-contract formalizes all this and makes you specify conditions on the code manually. DbC doesn't force you to do anything. You can say as much, or as little, as you like for contracts (nothing at all if you prefer). The point, however, is to get benefits out of the situation where things can be expressed as a contract. You suggest that writing unit tests to assure code does something reasonable is a good idea, and it is. Writing contracts is no different, and complementary to unit tests if used properly. If your test an be expressed as a constraint then you write it as a method contract or invariant, and if your test is onl expressible in terms of a particular output given a particular input (that is, as a specific test case) then you write a unit test. Then, when it comes to testing you are still testing everything for each unit - the unit tests fail if there's something wrong for particular test cases, and the contracst fail if the constraint are ever violated. That means writing constracts is no harder than writing unit tests (shorter really, because you don't have to write the boilerplate code involved in a test, just the constraint), and isn't any more indirection than unit tests. The advantage you get is that constraints as contracts can be automatically added to documentation (all good DbC systems support this), are statically checkable (many good DbC systems support this), which provides an extra layer of assurance, and provide a test oracle for randomised/state-space-search based testing (some good DbC systems like Eiffel via Autotest and QUikcheck for Haskell support this).
    2. Re:Too many layers by Anonymous Coward · · Score: 0

      Your post is making no sense at all. DbC is nothing more than extending strong typing: instead of simply saying that an argument is an integer, you are saying that it is an integer from 0 to 10, and that the return value is not just a string; it is a string of exactly length 4 and all uppercase.

      There certainly isn't any "layer of indirection" about it. Really it's just extending formal typing.

    3. Re:Too many layers by Geoffreyerffoeg · · Score: 1

      Your post is making no sense at all.

      I wrote it about 15 seconds before falling sound asleep.

      DbC is nothing more than extending strong typing

      Precisely. If my function can be written as

      uppercase_char[4] foo(int(0...10) x) {...}

      I'd use it. If I can define my function as

      char[4]:isUpper foo(int x:(lambda (x) (0

      then I might consider it. If I have to write my function as

      string foo(int x) {
        assert(0

      then there's no way I'm using it. I already have my language do the strong type checking for me. I'm not going to implement my own type system on top of it.

    4. Re:Too many layers by Anonymous+Brave+Guy · · Score: 1

      I think Slashdot cut off part of your post there. You might like to repost what you originally intended.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  13. Re:Management by rednip · · Score: 1

    A good business analyst ..., A good architect, There are a lot of people with pieces of paper from a school that are terrible at these things, and they muddle along leaving wreckage behind them. But that doesn't dismiss the value of having someone competent in those roles when you can find them.

    So very true, but I (generally) haven't seen it. The problem is that people think that one can 'graduate' with the knowledge they need to produce good results. The last module that I worked specked out by a power-point presentation from the business analyst, and when we insisted on 'use cases' the 'architect' started poorly (from our template), and got worse with every function. Sorry, but it takes real experience and insight to properly design a system, the the best never think that they got it perfect. People have a tendency to confuse bluster and arrogance with ability and experience.

    --
    The force that blew the Big Bang continues to accelerate.
  14. misleading title by Anonymous Coward · · Score: 0

    I thought this was going to be about some deity being contracted out to create humans.

  15. people do by oohshiny · · Score: 1, Insightful

    Design by Contract, writing pre- and post-conditions on functions, seemed like straightforward common sense to me.

    Yes, it is, and that's why everybody does it. It simply isn't called "design by contract" by most people, since it isn't actually design and isn't a contract. You also don't need language support for it. And people generally do this sort of thing in two parts: some conditions are always checked, but most are only checked in test frameworks.

  16. If you can contract it it's coded already by IICV · · Score: 2, Insightful
    Or, in other words, it's because we're lazy.

    I feel that the reason why design by contract (DBC from now on) isn't popular is because the entire point of the paradigm is that it doubles or triples your code length without adding any actual information; first, you tell the computer what should be true so you can do what you're going to do, then you tell it what to do, then you tell it what you should have done. That's a lot of typing just to make sure the computer fucks up in exactly the way you told it to.

    Admittedly, I haven't programmed much in any language that has built in support for DBC, but from exercises in classes (I'm a CS major) I've found that generally it's sort of a waste of time at worst and a duplication of effort at best.

    Regardless, the theory remains: if you can write pre- and postconditions for a function, you already know what the function is supposed to be doing so you might as well have spent your time writing the function and doing something else.

    For instance, consider some list class's addElement function, with some (sorta) DBC assertions:

    (And I apologize for no indenting, but the tabs got stripped out in preview so I'm assuming they're not there when I post)

    class List<E>{
    ...
    void addElement(E whatever)
    {
    assert(!full() && canExpand());
    int oldSize = size();
    if(full())
    {
    expand();
    }
    myArray[last+1] = whatever;
    assert(size() == (oldSize+1));
    assert(getElement(currentIndex+1) == E);
    }
    };

    Of course, this is an overly simple example and I'm probably not even doing it right; however, hopefully it's close enough that you can see what I mean. All of the assertions are semantically redundant; they don't add any meaning to the code. In fact, I don't think it's possible for that to be true in DBC; if an assertion somehow adds information to the code, it's not an assertion any more.

    1. Re:If you can contract it it's coded already by Coryoth · · Score: 2, Insightful

      Regardless, the theory remains: if you can write pre- and postconditions for a function, you already know what the function is supposed to be doing so you might as well have spent your time writing the function and doing something else. Do you document your code at all? Do you test your code at all? That's all DbC is doing, it is just doing both at once for any tests that can be written as constraints. And remember DbC is as much about other people knowing what a function does as about you knowing - it provides clear conditions for anyone calling your code as to what they must provide, and what they can expect of any returned results, information that, for any decent DbC system, is automatically included in API documentation. You, the original coder, might know what the function does, but it would be useful if someone else who wants to use your code could get that information (or, at the least, soem useful constraints of the function) without having to dig through the source code to try and find out. If you're coding a project entirely by yourself for CS class then you won't see the advantages of DbC. If you're part of a large coding team, where you only ever understand a small part of the entire codebase, and are relying on other peoples code (which you don't have time to read) doing what you expect, then DbC starts to make more and more sense.

      The other point is maintenance. You know what the function is supposed to do now, and you'll probably still remember tomorrow. A year from now, or later, however, that might not be so obvious. The code isn't going to help because the code only tells you what it does, not what it was intended to do, so how can you tell whether it is functioning as intended, or not? You could, of course, write comments that help explain this, but then writing a contract that states intention is hardly any more work than a comment, and provides testing and potentially extra static checks into the bargain. DbC only does work that you should be doing anyway (again, if it's a small project you're coding entirely yourself that you don't expect to maintain, then okay, DbC doesn't make sense) in terms of documenting an testing your code, so it shouldn't be any extra work.
    2. Re:If you can contract it it's coded already by UlfJack · · Score: 1

      DbC is rather like the difference between these two addElement methods which both disallow null entries in the list:

      void addElement(E whatever)
      {
          if (whatever == null)
          {
              throw new NullPointerException("whatever must not be null");
          } ...
      }

      @precondition(whatever != null)
      void addElement(E whatever)
      { ...
      }

      As you can see, the second version is even shorter than the first. And even better, imagine someone writes the following code:

      list.addElement(null);

      Then the compiler can already flag this _at compile time_!
      Now this is an obvious mistake, to make the example clear, but there are many examples, where this isn't as obvious:

      Element e = null;
      if (condition1)
      { ...
          e = new Element(); ...
      }
      else if (condition2)
      { ...
          e = new Element(); ...
      }
      addElement(e);

      If the code is a little longer, then you can't immediately see that e may indeed be null when addElement is called. The compiler nevertheless can easily perform this kind of analysis.

      I can easily think of many many more examples where it's useful to have the compiler check your parameters for you.

    3. Re:If you can contract it it's coded already by poopdeville · · Score: 1

      Do you document your code at all? Do you test your code at all? That's all DbC is doing, it is just doing both at once for any tests that can be written as constraints. And remember DbC is as much about other people knowing what a function does as about you knowing - it provides clear conditions for anyone calling your code as to what they must provide, and what they can expect of any returned results, information that, for any decent DbC system, is automatically included in API documentation.

      Yes, I document my code. Very clearly, in fact. Usually by documenting the method's specification, including it's "intention" (computes sin x, for instance), what it expects as input, what it returns. I base my unit tests on that specification.

      In some ways, I see DbC as a very good thing. And most competent developers do it anyway, in the way I've described. Similarly, competent developers know to not violate "the contract" and mess around with API internals. But formalizing these methods seem to required a big, upfront design. In my experience, upfront designs are counter-productive.

      Type safety just isn't worth all this effort. Duck typing is fine by me.

      --
      After all, I am strangely colored.
    4. Re:If you can contract it it's coded already by Coryoth · · Score: 1

      But formalizing these methods seem to required a big, upfront design. In fact it doesn't. DbC can actually help you be more agile. Consider an Agile framework built for Eiffel.
    5. Re:If you can contract it it's coded already by GileadGreene · · Score: 1

      Type safety just isn't worth all this effort. Duck typing is fine by me.

      Whether or not the effort of type-safety is worth it largely depends on your application domain. Duck typing may be fine by you, but for embedded code in a mission-critical application static type-checking buys you a lot of peace of mind.

      That said, DbC is not the same as type safety. It provides both less (runtime checks only), and more (much more expressive constraints). Of course, some DbC systems do provide static checking of contracts as well. But the result is (with the possible exception of Eiffel) layered on top of the type system of the language, rather than being integrated with it.

      And most competent developers do it anyway, in the way I've described.

      So why not give them tools to make the job easier? You can do OO in C, but it's much easier in a language designed to support objects. Similarly, while it's possible to do ad hoc DbC in most languages, it becomes much easier if you have tools and facilities in place to support it.

    6. Re:If you can contract it it's coded already by poopdeville · · Score: 1

      So why not give them tools to make the job easier? You can do OO in C, but it's much easier in a language designed to support objects. Similarly, while it's possible to do ad hoc DbC in most languages, it becomes much easier if you have tools and facilities in place to support it.

      What's easier than typing '#' followed by a comment? I would honestly rather read English than any programming language I know of. Even if it doesn't buy me fancy run time checks.

      And I'm not so sure those run time checks are really all that valuable (though I'll concede your point regarding application domains).

      --
      After all, I am strangely colored.
    7. Re:If you can contract it it's coded already by Fareq · · Score: 1
      Do you document your code at all?

      Personally, I'd rather read

      {
      // If the array is full, then expand it (or fail if we can't)
          if(full())
          {
              if(expandable())
                  expand();
              else
                  throw range_error("The array is full, but we can't expand it");
          }
       
      //add the new item to the position after the current last element
      //and make lastElement point at the new element
          array[++lastElement] = newElement;
        }
       
      }
      instead of

      {
          ASSERT(!full() || expandable());
          if(full())
          {
              expand();
          }
       
          array[++lastElement] = newElement;
          ASSERT(lastElement == oldLastElement+1);
          ASSERT(array[lastElement] == newElement);
      }
      because the comments in example #1 are in a different language than the code...

      If I could read all C++ code snippets and instantly understand the purpose and nuances, then comments (including the ASSERT()s would be totally unnecessary, since the code itself would tell me the purpose and all of the details.

      Because, however, I can't always figure out exactly what's going on in the C++ code, I prefer to have comments that, typically in more informal and higher-level terms, explain to me the sense of what's going on, pointing out any unexpected but important details.

      If the code is simple enough to be self-documenting... then it doesn't need "documentation" in the form of extra code to get in the way. If, on the other hand, documentation is necessary, then comments in english are better than ASSERT()s which could be just as confusing, or hide just as much complexity, as the rest of the code.
    8. Re:If you can contract it it's coded already by GileadGreene · · Score: 1

      What's easier than typing '#' followed by a comment?

      Heh. Took me a moment to realize that you weren't talking about preprocessor #defines there :-) Why that's relevant will become obvious shortly. Anyway, I'd posit that typing '//', '--', or '%', followed by a comment is about as easy.

      As for whether comments are "easier" than contracts, it depends on (as I said before) your application domain, and also what your timescale and environment is like. Example: I recently wrote some code in which I encoded some constraints on values as preprocessor #if statements (kind of an ad hoc static type system, since I couldn't say what I needed to within the standard C type system, and other languages are not an option at this point). Now, I could have just written some comments describing the constraints. In fact, that's initially what I did. But then I realized that encoding them as "contracts" of a sort ensures that neither I (working at some distant time in the future), nor another coder working on the same code-base, can inadvertently break the constraints without generating a compiler error. The comments are still there, to explain what's going on. But in the long term, it's "easier" to provide assurance that the program will work as intended by having a compile-time check which ensures that I or someone else can't alter the code in a way that violates the assumptions which underly the operation of the program than it is to provide some kind of external social guarantee that every coder working on the code in question will be careful enough to avoid violating constraints.

    9. Re:If you can contract it it's coded already by Coryoth · · Score: 1
      of course there's always:

      require
          not_full_or_expandable: not full or expandable -- require that elements may be added
      do
          if full then expand end
          last_index = last_index + 1
          put(new_element, last_index)
      ensure
          last_index_increased: last_index = old(last_index) + 1 -- ensure length of the array has increased by one
          new_element_added: item(last_index) = new_element -- ensure new_element is the last element
      end
      Of course with a simple example like this some of the contracts are obvious from looking at the code - but then this is also added to the API documentation, along with the comments, so we don't have look at the code to know what will happen. Better still our documentation isn't going to fall out of date - if code gets refactored such that these constraints aren't met any more then the refactored code will fail testing unless the contracts, and hence the documentation, are also changed.

      I agree that throwing asser around isn't gaining you a lot. The point, however, is not to just stick assert in your code, it is to have a DbC system, which means as well as just expressive syntax for expressing constraints you also have tools to make use of those constraints, for docuemntation, for testing (fine grained control over which level of checks are included in compilation), and for the language - that means contracts are inherited, and preconditions cna only be weakened and postconditions strenghtened. Once you have all the extra support to really make use of contracts you start to see their value.
    10. Re:If you can contract it it's coded already by John+Courtland · · Score: 1

      I'm curious, why did you give your contracts identifiers? Are they treated as first-class objects or am I missing something?

      --
      Slashdot is proof that Sturgeon's Law applies to mankind.
    11. Re:If you can contract it it's coded already by Anonymous+Brave+Guy · · Score: 1

      Actually, in your example I'd prefer the following. (Apologies for losing the indentation; how do you get Slashdot not to do that?)

      if(full())
      {
      if(expandable())
      expand();
      else
      throw range_error("The array is full, but we can't expand it");
      }

      array[++lastElement] = newElement;

      The comments in English add no value at all: they simply repeat, in a more verbose and less precise fashion, what the code already says.

      I'm not really sure what you're trying to demonstrate with the assertions in this case. Your first condition is testing for something that sounds like it could legitimately go wrong at run-time, i.e., something that is not a logic error. That isn't really a very good use of pre/postconditions, which are (IMHO) best reserved for things that should never go wrong. The later tests are restating what you've already stated immediately above them, and again they add no real value.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    12. Re:If you can contract it it's coded already by Raenex · · Score: 1

      Apologies for losing the indentation; how do you get Slashdot not to do that? Plain Old Text with <ecode> does the trick.

      It took me awhile to figure this out, as there is no obvious link to help on formatting your posts (eventually found some help via Google).

      Up until now I've been using HTML Formatted, since Plain Old Text sounded un-web like. <ecode> doesn't work very well with HTML Formatted, because it doesn't preserve the space and you can't add them with &nbsp;. Turns out Plain Old Text is what I wanted all along anyways. Just hit return twice when you want a new paragraph, once when you want a line break. No more <p> tags!

      Actually, now that I look at Preview, Plain Old Text inserts two <br>'s instead of <p>, which doesn't look quite as nice and is definitely un-web like. Oh well, convenience wins out.
    13. Re:If you can contract it it's coded already by Coryoth · · Score: 1

      Eiffel let's you give contracts names which are then used for documentation and logging of contract violations during testing etc.

    14. Re:If you can contract it it's coded already by Anonymous+Brave+Guy · · Score: 1

      Great, thanks.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  17. DbC? Unit testing? Boring and costs time. by cerberusss · · Score: 0

    I'm surprised no one answers thruthfully on this. It looks like everyone wants to appear like they use every technique under the sun and still deliver in time. In my opinion, these methods all cost time and are quite a bore. To top it off, most projects don't require that kind of quality at all.

    --
    8 of 13 people found this answer helpful. Did you?
    1. Re:DbC? Unit testing? Boring and costs time. by DaveV1.0 · · Score: 0, Flamebait

      To top it off, most projects don't require that kind of quality at all.


      That statement is why most software and almost all FLOSS suck ass.

      It is also why most engineers sneer at the idea of a software engineer.
      --
      There is no "-1 offended" or "-1 you don't agree with me" mod options for a reason.
    2. Re:DbC? Unit testing? Boring and costs time. by cerberusss · · Score: 1

      That statement is why most software and almost all FLOSS suck ass. It is also why most engineers sneer at the idea of a software engineer.
      Then what are your experiences with design by contract and unittesting?
      --
      8 of 13 people found this answer helpful. Did you?
    3. Re:DbC? Unit testing? Boring and costs time. by Anonymous Coward · · Score: 0

      There are real software engineers out there. Anyone can be a programmer. When I graduated high school I was a programmer. That was easy. But to spend time working out requirements and know how to write proper design documents takes way more work, but it's worth it.

      Software engineering is at a point now where Strutural engineering was 67 years ago when the Tacoma narrows bridge failed.

      Someday software engineers will fit in well with all the "real" engineers. That day will be when "reboot" is no longer a valid fix for software.

    4. Re:DbC? Unit testing? Boring and costs time. by Anonymous Coward · · Score: 0

      There *are* real software engineers out there, at least in Canada. Here 'engineering' is a protected title, not just any idiot can call themselves an engineer software or not ,like in some other countries.

      Software engineering has been a real engieering discipline in Canada for 5-10 years now.

      Software engineers take the regular engineering math, science, and multi-disciplinary courses that all the other disciplines take. (as well as comp-sci courses, for 'fun').

      We know damn well, that if we don't design it right, people will die, or at the very least our LICENSES will be revoked. Programmers/Developers/Code Monkeys on the other hand, can be content for now, adding their easter-eggs, and 'features' to their little programs.

    5. Re:DbC? Unit testing? Boring and costs time. by Anonymous Coward · · Score: 0

      It is also why most engineers sneer at the idea of a software engineer.

      depends, I wouldn't want an electrical engineer designining the software controlling my ABS system, or a civil,chemical, or worse yet a mechanical.

      real software engineers do exist, those take the same math and science courses as any other engineer.

      Who would you trust designing a mission critical software system with, the electrical engineer who can barely figure out how his calculator works?

    6. Re:DbC? Unit testing? Boring and costs time. by Anonymous Coward · · Score: 0

      Unit testing works. I ran a 18-month study for a Fortune 10 company, where we found that unit tested code had 7x fewer customer defects. In the real world that translates to big $$$.

    7. Re:DbC? Unit testing? Boring and costs time. by cerberusss · · Score: 1

      Suppose I create software for one team (two to five persons). Or for a department (up to twenty persons). Does the lowering of customer defects still translate to big bucks? A bit, but not by the thousands.

      I'm getting a bit tired of hearing "YOU MUST DO UNIT TESTING OR THE XP CABAL WILL COME AND RAPE YOUR DOG". The Wikipedia article reads like a goddamn advertisement. I'm not against it, I'm just pointing out that there are situations where it's a lot less useful.

      --
      8 of 13 people found this answer helpful. Did you?
  18. I'd like to use DbC, but... by Sircus · · Score: 1

    I took a glance at Eiffel a while ago - but mainly with the intent of answering one question: is it checking these contracts compile-time or runtime? It turns out (on page 68 or so of their manual) that it's at runtime.

    I don't want my software to fail in the field (at my day job, we write stock trading software - reliability is key because lack of availability can quickly become very expensive). If I could define a number of pre- and post-conditions for each function and have the compiler check these for me, I'd be happy. (Yes, I realise that this is quite a tricky problem of static or dynamic analysis, depending on how far you want to take it.) If the conditions are only going to be checked at runtime, then I'm going to have to write unit tests anyway - otherwise, the failure's going to be beautifully detected and localised and so forth, but crucially, it's going to be one of my customers that detects it. If I'm writing unit tests anyway, why bother with DbC?

    When there's a DbC language or add-on that checks the contracts at compile time, I'll be interested.

    --
    PenguiNet: the (shareware) Windows SSH client
    1. Re:I'd like to use DbC, but... by Coryoth · · Score: 4, Informative

      I don't want my software to fail in the field (at my day job, we write stock trading software - reliability is key because lack of availability can quickly become very expensive). If I could define a number of pre- and post-conditions for each function and have the compiler check these for me, I'd be happy. And indeed, this can be done, and is available for a number of DbC systems. Check out JML which has ESC/Java2 to provide static contract checking for Java, Spec# (C# with contracts) which uses the Spec# verifier for static checking of contracts, and Eiffel with ESpec-Verify for static checking of Eiffel contracts.

      If the conditions are only going to be checked at runtime, then I'm going to have to write unit tests anyway - otherwise, the failure's going to be beautifully detected and localised and so forth, but crucially, it's going to be one of my customers that detects it. If I'm writing unit tests anyway, why bother with DbC? The difference between DbC and unit tests (and really, you should be doing both) is that if a test can be expressed as a constraint then it is useful to simply express that as a contract, while if the test is a specific input to output matching test then it is going to be useful as a separate unit test. When you run your unit tests the contract constraints will automatically get checked. More importantly they will help isolate exactly where the error occured when testing integrated systems. Furthermore, by putting constraints as contracts you have improved your API documentation (any decent DbC system includes automated inclusion of contract information in API documentation) which helps other people use your code correctly, and makes maintenance easier.

      Finally contracts allow automated testing. That's where you automatically generate data to pass to the code and let the contracts act as a test oracle to catch and locate problems. With something like AutoTest for Eiffel the data generation can be purely random (constrained by preconditions of course), or designed to sample the input according to best coverage via genertic algorithms, etc. The result is that you find corner cases that you might not have anticipated with your unit tests - and you would be surprised how often that happens, AutoTest found a number of subtle bugs in Eiffel's base libraries which had been production code for years.

      When there's a DbC language or add-on that checks the contracts at compile time, I'll be interested. Then you really need to check out JML and ESC/Java2, and Spec#, because you would be interested.
    2. Re:I'd like to use DbC, but... by Sircus · · Score: 1

      Then you really need to check out JML and ESC/Java2, and Spec#, because you would be interested. Thanks - I'll check out JML and ESC/Java2 (we're using Java throughout, both client and server-side).
      --
      PenguiNet: the (shareware) Windows SSH client
    3. Re:I'd like to use DbC, but... by 5pp000 · · Score: 1

      Check out JML which has ESC/Java2 to provide static contract checking for Java, Spec# (C# with contracts) which uses the Spec# verifier for static checking of contracts, and Eiffel with ESpec-Verify for static checking of Eiffel contracts.

      While these systems can statically verify certain relatively simple kinds of contracts, nobody knows how to build a theorem prover powerful enough to verify most interesting contracts without human guidance.

      Specifically, we can build fully automatic provers for first-order logic; but most interesting contracts have inductive proofs, and induction is inherently higher-order, and nobody knows how to build a fully (or even mostly) automated prover for higher-order logic.

      Personally, I think it's one of the most interesting problems in all of AI, and I'm surprised that not many people seem to be working on it.

      --
      Your god may be dead, but mine aren't!
    4. Re:I'd like to use DbC, but... by Tablizer · · Score: 2, Insightful

      if a test can be expressed as a constraint then it is useful to simply express that as a contract,

      Us table-heads who like to shift the processing burden to the database instead of application languages would point out that this resembles database constraints and triggers.

  19. DBC requires more formalism in your approach by spagetti_code · · Score: 1

    DBC has a greater requirement towards designing everything up front.
    XP allows you to be more flexible in your approach, and supports the need
    to constantly refactor your code.

    In my experience, at the start of a complex project, we are never sure of
    all the answers. The ability to pull together small pieces, to constantly
    refactor as we learn more and to work in a close team outweighs the
    big-systems sort of approach where everything is specified to the last
    detail before you start.

    Tried both, DBC stuck in the throat.

    1. Re:DBC requires more formalism in your approach by NovaX · · Score: 1

      Wow, that's so utterly wrong. You write contracts against methods, and thus express in the code explicitly the method's intent. This makes it easier to refactor because the code is clearer and the callers can't abuse it. You have an easier time refactoring this type of code because you know it is correct. And its easier to test after you've refactored because it won't hide bugs by spitting out wrong answers, but instead make them known. People who put the tiny amount required will have enough pride in their work to make their code clear, simple, and beautiful.

      But if you think that argument checking is too much design effort and XP is all about slinging code, then I'm damn glad I don't work with you. I've seen to much crappy code and new frameworks written to replace old ones because the poor programming practices seeped out and corrupted more and more code. Contracts promote clean, robust code.

      The fact is DbC isn't used because most programmers don't act like professionals. They program lazily, spitting out just enough to get past QA and leaving suttle bugs for the next group to deal with. They get so caught up with designing that they treat coding as the ugly step child, allowing it to get hidious. They forget that code is the design, hence bad code infects and creates a bad design. If programmers treated their profession with respect and took pride in their work, something as simple as DbC wouldn't create an almost unanimious response of rejection.

      --

      "Open Source?" - Press any key to continue
    2. Re:DBC requires more formalism in your approach by Coryoth · · Score: 1

      DBC has a greater requirement towards designing everything up front. XP allows you to be more flexible in your approach, and supports the need to constantly refactor your code. That DbC is up front design is simply not true. You can do "Contract Driven Design" as well as you can do "Test Driven Design" (though of course combining tests and contracts, using each where they make sense - contrct for constraints, tests for explicit input to output mappings - is the best bet). Indeed there are even frameworks like ESpec which are specifically designed for doing XP in Eiffel using contracts. Try reading one of the ESpec papers on XP programming with ESpec. Think of it this way - DbC is about writing testable constraints early. That doesn't mean those constraints have to be finalised - contracts can evolve and be added to. With DbC you can get your constraints written and tested faster since you don't even have to have written the all code, just the contracts, to be able to test whether the constraints are sufficient to get the output you want (again, I'll refer you to the paper on Agile DbC using ESpec for details).
  20. Already mostly done by Todd+Knarr · · Score: 3, Informative

    As has been noted, most programmers already do design-by-contract, they just don't call it that. They call it argument checking. The first thing most routines do is validate their arguments, and return an error if any of them are invalid. The last thing done is to check the results and return an error if the results aren't valid. The calling code then checks for error codes or invalid results (eg. a search function returning a null pointer indicating the item wasn't found).

    In the real world I often skip this overhead when the conditions are enforced elsewhere. For example, a data structure needed by an internal function may not have to be checked for existence since if it hadn't been created my initialization function would've detected this and signaled an error and the program would've exited. In cases like that, I either omit the check or wrap it in an ifdef so it's only done during development and ignored by the compiler during the release build.

    Don't make the mistake of confusing the name of a concept with the concept itself. You'll find quite often that that nifty shiny-new concept someone's presenting as their own has actually been around for 30-40 years and they've just added some chrome, filed off the serial numbers and changed the name to keep you from noticing this.

    1. Re:Already mostly done by Coryoth · · Score: 1

      As has been noted, most programmers already do design-by-contract, they just don't call it that. They call it argument checking. The argument against this is that it is confusing implementation and specification. A contract is separate from the code implementing the function, and is automatically included in the API documentation for the function. That makes it easier for other people to use the code (they don't have to have access to the source code, or bother reading through all your code, just to be able to know they are calling your code correctly and what they can expect of the result), and for you to maintain your code. There's also the expressivity issue (particularly true of postconditions): to do certain checks, particularly involving, say, old values of variables (at the time of entry to the function), will involve extra useless implementation code to save variables and other hoop jumping. This is needlessly complicating your implementation. The advantage that having a system specifically designed to handle pre and post conditions is that it provides extra syntax so as to be suitably expressive with regard constraints.

      In cases like that, I either omit the check or wrap it in an ifdef so it's only done during development and ignored by the compiler during the release build. And a good DbC system offers the ability to do just that (Eiffel offers excellent fine grained control over what checks get included in compiled code, from everything for testing, to nothing for finalized production code) without having to salt your code with ifdefs.

      ...they've just added some chrome, filed off the serial numbers and changed the name to keep you from noticing this. No, I'm pretty sure I knew exactly what it was, and no real attempt was made to hide this. The point is that they've added a lot of chrome. A good DbC system takes advantage of the expectation of such checks existing/being written, and provides excellent support to help you write checks, analyse checks, use checks, document your code with checks, etc. Let's face it C is just prettied up assembler and a good IDE is just notepad with a little chrome and the serial numbers filed off. If the chrome actually adds significant value then it is worth using.
  21. been doing that for years already by imbaczek · · Score: 5, Insightful

    assert(condition) is your friend. It's not called a contract, it's not design (but a very good practice!) and it does the job well.

    1. Re:been doing that for years already by Coryoth · · Score: 1

      assert(condition) is your friend. It's not called a contract, it's not design (but a very good practice!) and it does the job well. I agree that asserts do the job well. I'm just trying to point out that a good DbC system, such as some of the ones mentioned in the article, provide significant tool support which makes contracts considerably better than asserts. For example, DbC systems will have compilers that understand contracts, and extended syntax designed specifically for expressing constraints such and post conditions. A simple postcondition like x > old(x) is harder to manage with assert statements - you need extra code to save the initial value of the variable which gets mixed in with your implementation and things get messy. DbC systems also involve documentation, allowing API documentation to be automatically generated, and including contracst in that documentation. DbC systems also have controls over whether contracts checks are compiled in or not, meaning you don't have to sprinkle your code with ifdefs everywhere. DbC systems also allow for static checking of contracts with theorem provers, something asserts just can't do. In other wors, a good DbC system takes the practice of using asserts, formalises it a little, and then provides excellent tool support to make it more powerful and easier to use. It's the difference between doing OO programming in straight C, or in C++ or Java, both are possible, but the latter languages provide a few extra constructs (that, in Java's case IDEs can mae the most of) that make it easier and more powerful.
    2. Re:been doing that for years already by Edward+Kmett · · Score: 1

      A good design by contract system can and should catch a lot of these errors at compile time.

      That is the difference.

      If you only catch something at runtime with an assert it is already too late.

      Among the Haskell programming community there is a tongue-in-cheek saying, "if it compiles it is correct." This happens because the type system is so strong, it is hard to write a program that compiles, but doesn't do what it is designed to do.

      Design by contract offers similar benefits to more imperative languages.

      Though, even the Haskell community sees benefits in contracts: http://www.cl.cam.ac.uk/~nx200/research/escH-hw.ps

      I personally find classic Eiffel style contracts or Extended Static Checking dovetail nicely with unit testing, improving coverage.

      --
      Sanity is a sandbox. I prefer the swings.
    3. Re:been doing that for years already by ivan256 · · Score: 1

      Nine times out of 10, a failed assert is implemented as a hard exit.

      Please, do the people using and maintaining your code a favor, and return status instead of crashing when your assert fails.

      (This isn't necessarily directed at you. I'm just making a general point.)

  22. Programmers don't find it easy by smcleish · · Score: 2, Informative

    I do some teaching on an Open University course here in the UK which uses the concept, and my experience is that many students, including experienced programmers, find it difficult to do. Common errors include:

    - confusing the signature of the function (in terms of the types of permitted input) with the pre-condition. It may be true for some implementations of pre-conditions that you need to include information of the form "input is a string" but it isn't for the way we do it in the course.
    - ignoring input cases (e.g. giving a post-condition which only makes sense when the input is a non-empty string, but using a "true" pre-condition); students know theoretically that every possible permitted input needs to have an appropriate output in the post-condition but can't put this into practice
    - difficulty in creating conditions which are precise; this is both in the early part of the course, which uses English language conditions, and later on when algebraic conditions are introduced
    - designing tests which use inputs which fail the pre-condition (which is partly because the testing tool used in the course doesn't check the validity of the pre-condition, so invalid inputs can produce sensible looking outputs)
    - confusion between pre- and post- condition rules: they often want to restrict the input by changing the post condition

    It seems to be the case that it is at a particular level of abstraction vs practicality that many find difficult to cope with.

    --
    You can rent this space for $5 a week.
    1. Re:Programmers don't find it easy by PurplePhase · · Score: 1

      In order of the original post (you should number them next time 8)

      1. Parameter typing is in fact a precondition, it just happens to be built into several languages, though none of them do it correctly (though I've limited experience). Java has a partial solution by allowing Interfaces to be defined, but doesn't allow the extensive polymorphism required. Ruby is advertised as duck-typing but has no explicit typing and no compile time to express type warnings so falls even shorter in usability. If we were smarter the typing preconditions would be generated from code by listing all messages that a parameter must be able to respond to. I'm still upset that Dave Thomas promoted Ruby's lack of typing (except that it does, and not that gracefully), but no one has filled the gap with my suggestion of automatically generated tests of this type of typing.

      2. Are you teaching a methodology to help them do so? Effectively they should be listing out all possible parameter input conditions and then either eliminate them from the list when they exclude them with a precondition, or later generate all combinations and list those (eg. "if X && Y && (Z || !Z) then A") as the postconditions. Or if you define postconditions differently, maybe the postconditions need to be the union or intersection of all A's, whereas the set of full statements become the tests.

      3. Precise conditions require knowledge not only of the problem space (including all factors), but also of the solution space and expectations. Typically these are both too implicit in problems, and trying to engender introspection and insights can take much pendantitry and is hard for an instructor because it is too easy to lose sight of what your own assumptions are.

      4. Generate them from #2

      5. Again, give them a framework for considering the whole problem by dividing up the problem space as described in #2. Use whatever tools or visualizations help: 2-column chart for before(pre) and after(post), use a tool (any exist?) to facilitate these definitions and warn of overlaps, consequences, and where responsibilities should be, even anthropomorphize the concept and have a person be a function refusing to deal with anything that doesn't meet the preconditions and if someone wants to know what they can do they list their postconditions and say "I can't do anything else!"

      I agree with other posts that a better tool - both a language and interactive IDE - are required to find the sweet spot for DBC. But as with any method it can also require practicing. I disagree with other posts which says the DBC concept requires all requirements up front (ie. Waterfall Method). Personally with current tools I would include the useful ones when writing the functions and pedantic ones only between the application working and the final code review... if any clients were ever willing to pay for it. Which they aren't.

      I'm a little tickled by this thread, actually, as back before 2000 I was writing Java code and explicitly stating @precondition and @postcondition in my javadocs as I knew they were needed for my own edification even if the limited Visual Age IDE couldn't enforce them.

      8-PP

  23. DbC and Unit Tests cover similar ground by FrnkMit · · Score: 2, Insightful

    Apart from "it's too hard", I think Unit Testing has overtaken DbC as an approach.

    - You can write unit tests in any language, with or without a framework. (I saw a "mini-framework" for C that consisted of three macros and a coding convention.)

    - In a test, you can specify assertions before and after each method call. It's a little more tedious to represent classic DbC assertions, but the Abstract Test pattern among others allows you to collect common code.

    - You can strip out assertions in production code simply by leaving test code out of the product.

    - Unit tests also run scenarios automatically, without an extra "test driver".

    The one thing Unit Testing *can't* do is check production code as it's running. On the one hand, that's great at catching conditions you never thought of. On the other hand, customers tend to get annoyed if their app shuts down. I'm sure there's some work on partial in the Eiffel world, but so far I haven't seen any.

    See also http://onestepback.org/index.cgi/Tech/Programming/ DbcAndTesting.html and particularly the postscript.

    1. Re:DbC and Unit Tests cover similar ground by FrnkMit · · Score: 1

      But see also http://onestepback.org/articles/TddMeetsDbc by the same author, who presents a combined DbC/Unit Testing framework for Ruby. (Unfortunately, it relies on Ruby syntax to create a mini-language within Ruby itself.)

    2. Re:DbC and Unit Tests cover similar ground by chromatic · · Score: 1

      The one thing Unit Testing *can't* do is check production code as it's running.

      It certainly can, at least with well factored code. Create a delegate object that contains the real object, then override all of the standard methods to run pre- and post-tests, calling the real object's methods in between. If you use a factory to create the objects, you can create the testing delegate once every hundred or thousand requests, or once every hour, or however often you want to run these tests against live request.

      You do need to use a test mechanism with separate reporting and analysis, but I use TAP so it's easy.

  24. Re:Management by Anonymous+Brave+Guy · · Score: 4, Interesting

    People have a tendency to confuse bluster and arrogance with ability and experience.

    They do, yet in my experience, these things are inversely correlated. This applies to all guidance/oversight roles, including business analysts, software architects, consultants, and indeed managers themselves. As I've commented here before, you can always identify a good leader by three characteristics:

    • They can set a clear direction and convey this to others.
    • They organise adequate resources and set realistic expectations.
    • Having done the above, they get out of the way as much as possible.

    The third one is usually the easiest way to identify morons. If you come across a leader in software development who places more value on reports and metrics so they can track things than they do on supporting the developers and test teams working for them, then you know you're dealing with an incompetent.

    And yes, that does mean many leaders in software development organisations today are incompetent. That's why the genuinely good people are worth so much.

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  25. Design by contract is 25+ years old by Anonymous Coward · · Score: 0

    We call it include files and C coders have been doing it for ages. You noobs and your silly OO languages.

    Glass

    1. Re:Design by contract is 25+ years old by Waffle+Iron · · Score: 3, Funny

      We call it include files and C coders have been doing it for ages. You noobs and your silly OO languages.

      I especially like contractual gems such as:

      char *gets(char *s);

    2. Re:Design by contract is 25+ years old by Anonymous+Brave+Guy · · Score: 1

      Well, just because you've got a contract, that doesn't mean it will do anything useful when you enforce it. ;-)

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  26. Side Effects by somepunk · · Score: 2, Insightful

    A lot of functions in real world programs just don't fit this model. Especially in GUIs. Or functions that manipulate internal data structures. Only the most trivial programs (or contrived exercizes of academics) strictly fit the functional, no-side-effects model for all functions. And if you can't apply this method to your entire program, you are going to find a more flexible way to verify behavior.

    --
    Those people who think they know everything are a great annoyance to those of us who do. (Isaac Asimov)
    1. Re:Side Effects by Watson+Ladd · · Score: 1

      Like a compiler? If your functions don't fit the model, change your functions, not your model. Functional programing makes errors reproducible, tractable, and fixable. And you can do it any language.

      --
      Inventions have long since reached their limit, and I see no hope for further development.-- Frontinus, 1st cent. AD
  27. Sometimes more complexity is worth it by Anonymous+Brave+Guy · · Score: 1

    Design by Contract adds more complexity to code, particularly if you're dealing with a language that doesn't natively support it.

    Sure, but so do writing explicit interfaces to modules, writing unit tests, and for that matter, writing comments. It's just a question of whether introducing that complexity at the time you write (and maintain) the code brings compensating benefits down the line.

    Only a small proportion of development time is typically spent physically writing code, so these defensive programming techniques can be used pretty much on auto-pilot. The implementation costs are therefore relatively small. Given that they can prevent many bugs or save much time during later development, I would argue that they are well worth adopting, unless you already have something in place that provides similar benefits via some other means.

    (This isn't to say that the parent poster's point isn't valid, or that aiming to keep your code as simple as possible is a bad thing, of course.)

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  28. But what kind of language? by Anonymous+Brave+Guy · · Score: 2, Insightful

    I'd agree with much of your post, but I think there's an unwritten assumption about programming style in what you wrote: you seem to be restricting your scope to imperative languages with mutable state (talking about locks and threading, for example).

    If you're working in a language that doesn't permit generally mutable state, it's much easier to use concepts of design by contract, essentially because all you have to do is check that when you've finished constructing a new value, it is valid for whatever type it has. Of course, such languages have disadvantages as well.

    I suspect that a great deal of work in programming languages over the next few years is going to focus on how to identify and localise side-effects more explicitly. Pure functional languages that don't allow mutable state at all seem to be quite inefficient, and have fundamental problems for high performance applications that have yet to be resolved. Things like the monads widely used in Haskell today provide some powerful features like mutability but built on a much sounder base than many of today's imperative languages, but at the cost of horrendous syntactic overheads, which kinda spoils one of the big advantages of adopting a functional language: conciseness.

    However, multi-core and multi-processor machines are fast becoming mainstream, and loose imperative programming languages have failed to provide satisfactory tools to take advantage of these architectures. I expect this to drive a general move towards more declarative rogramming styles in the industry. Meanwhile the academics, who have seen it all before, will be working on more powerful models of scoping and side effects, well beyond the glorified block scope/lambda calculus stuff that most of today's mainstream programming languages are effectively built on. Once we start getting programming languages with more powerful ways to signify when it is acceptable for what sorts of side effects (including changes in state) to occur, we'll have the sort of foundation needed for your ideas about being inside/outside an object, and compilers will have the sort of framework needed to optimise DbC checks so they're only applied when they're really needed and don't carry unfortunate performance penalties.

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  29. Boring and costs time, but necessary. by DJ+Rubbie · · Score: 1

    I know what Design by Contract (played with it while at school), but as the poster of the article and other comments have pointed out, there isn't much real language support out there. However, unit testing is something I've been told to do; rather than having informal test cases, I wound up writing a fairly formal testsuite for a library I have written that tests every code path a few times. While doing them, I uncovered some funny results that I might not have otherwise saw, which is great, because it formalizes things and there is a proof that it works.

    Quality. What makes you think most projects don't need that kind of quality? You realize how much crap code is out there? If I got an XML/RDF parser I expect it to parse things correctly and tell me when something is not right with the file, and not silently miss/omit something which makes me question my own code and wasting my time because it's not in my code. If I have a multimedia file encoder I want the files generated fits the spec so it can be played by other players that follow the same standard. If I have a web browser I expect it to render things right and not have any security violations. Web applications - I expect all inputs to be checked, no SQL injection or cross site scripting permissible. If you say there are many projects that don't require that kind of quality, how about giving some examples.

    Right, cost and time issues. Sure, it makes development potentially twice as long therefore twice the cost, but wouldn't not having customers coming back saying the code doesn't work, or it broke, translate into savings? For open source stuff, why not spend time to make things correct and have a proof of it to increase your reputation? There are no good reasons not to have some sort of unit testing in place in any code (or binary - test cases for the code that created the binary) that is to be released for public consumption.

    --
    Please direct all bug reports to /dev/null
    1. Re:Boring and costs time, but necessary. by cerberusss · · Score: 1
      Thank you for an excellent reply, with some excellent points. I've put you on my friends list, so I'll see your future posts with a +5 friend modifier. Anyway:

      If you say there are many projects that don't require that kind of quality, how about giving some examples.
      I was talking about the brunt of the custom developed applications that are really specialized front-ends for databases. Actually, I'm of the opinion that automatic testing of most user interfaces could be done much faster, cheaper and better by a human with a test plan.

      If you're talking about libraries, hardware interfacing or the like, then I'd say yeah, these are suitable candidates for a large flock of unit tests.

      Right, cost and time issues. Sure, it makes development potentially twice as long therefore twice the cost, but wouldn't not having customers coming back saying the code doesn't work, or it broke, translate into savings?
      That's a difficult decision and it needs to be checked for each and every project. However, I dare say that the decision to not create unit tests (which is equal to not deciding anything) is made much more often. And why? Because the costs are not worth it. I have some experience with maintaining a suite of unit tests and I found the following: the more tests, the larger the maintenance work. The older the tests, the less useful they are.

      Tests are the most useful when they find bugs. That's what tests are for. When tests are repeated, as in regression testing, their usefulness slowly diminishes. So at one point, you might decide that the tests aren't worth maintaining. And I find that people often forget the cost and especially the discipline involved.
      --
      8 of 13 people found this answer helpful. Did you?
    2. Re:Boring and costs time, but necessary. by mattpalmer1086 · · Score: 1

      You make good points, but I do disagree with you. It's not so much that a decision is made not to test, it's just that most places and programmers do not have a culture of creating them. The decision, if a decision is made at all, is usually to unit test in the first place. Not testing is the default position.

      I also disagree that test are primarily for finding bugs, and that regression tests diminish in usefulness as they are repeated. Tests do find bugs occasionally, which is nice, but mostly what they do is force the programmer to think about what is valid and what isn't in the code - if they're written along with the code rather than afterwards, that is.

      Regression tests give confidence that you haven't broken the code as it changes. It's the repeatability that makes them valuable! If your regression tests never expose a bug introduced by new code, then your programmers are awesome!

  30. The real reason why it is not more popular by rollingcalf · · Score: 1

    Most programmers aren't interested enough in technology to even know what Design By Contract is.

    --
    ---------
    There is inferior bacteria on the interior of your posterior.
  31. Re:Management by Propaganda13 · · Score: 1

    A business analyst will answer the question "What is it that we (the analyst)think they (the worker) need?"


    Fixed

    Ask the people who actually use the stuff next time.
  32. I use it all the time! by Nappa48 · · Score: 0

    //pre-condition: unvalidated code
    //post-condition: validated code
    [code that does none of the above]
    Woohoo, done.
    See, now that wasn't that hard, was it?

    (yes, i do know what DbC is, but this is how we were taught DbC in college... shocking isn't it?)
  33. You need to have a contract first by khchung · · Score: 1

    To do DbC, you have to have a contract first. That means you know exactly how your function is supposed to be called and what values are valid, etc. Now trace from one function to its caller, and to it caller's caller, etc, and eventually you either reach the user interface or some business logic. Knowing how the user interface and business logic calls other functions and what values are valid means you have a complete set of user requirements on hand.

    Now, I don't know about you, but I have never seen a project with a set of user requirements at the beginning of the project that remains the same at the end of the project. I.e. either they are incomplete to be begin with, or they change in the course of the project, or both. So that means any "contract" you added into your code is likely to become wrong during the course of the project, rendering it more an development obstacle than a development aid.

    In contrast, XP and other "Agile" approaches recognizes and accepts the fact that requirements change, rather than hoping in vain to nail the requirements down.

    --
    Oliver.
    1. Re:You need to have a contract first by chromatic · · Score: 1

      Knowing how the user interface and business logic calls other functions and what values are valid means you have a complete set of user requirements on hand.

      Why do you need a complete set of user requirements? If you don't know what the function should do right now, how can you possibly write it? Why can you not modify the contract as the requirements become more clear? I assume you can do the same for the code that implements the contracts.

      You might as well complain that you can't do automated unit testing, because the tests may have to change during development, or that you can't write code because that code might have to change during development.

    2. Re:You need to have a contract first by khchung · · Score: 2, Insightful

      Why do you need a complete set of user requirements? If you don't know what the function should do right now, how can you possibly write it?

      How interesting for you to put these 2 questions together! Didn't your 2nd question just answered your first question (at least in theory)?

      Now in practice, we obvious will be start developing before we got a complete set of requirements, which bring us to...

      You might as well complain that you can't do automated unit testing, because the tests may have to change during development, or that you can't write code because that code might have to change during development.

      The big difference between code + unit tests vs contracts (at least from my understanding and experience), is that code and tests are "constructive" in nature, while contracts are mainly "prohibitive" in nature. By "constructive", I mean code and tests tell you something the program will do, vs "prohibitive" which means what the program will not do.

      A piece code to parse a string "1234" into an integer 1234 and with test to call it using "1234" and asserting the result == 1234, now that tells you what the code does. The test does not tell you what other things the code might also do, such as it maybe the code can also handle -ve numbers ("-1234"), or formatted numbers ("1,234"), or even decimals "1,234.56" (if the return type is general enough to support it, such as returning type Number in Java).

      When you put in assert() into the code, however, it tells what the code does not do. assert(result is integer) tells us the parse does not handle decimals, assert(string contains only numbers) tells us the code does not handles formatted strings, etc.

      Comparing the two, code and tests are "constructive" as they give more features to your program, while contracts are "prohibitive" as they restrict what you program can do. More contracts you add, more things you prohibit your code from doing.

      When the requirements change ("we have to handle dollar signs in front too, but no more decimals"), the now unused decimal feature and its tests can be ignored, but any contract ("string only contains [0123456789.,-]") that blocks the new requirement has to be removed. Guess which one, tests or contracts, make more problem for the team as the development progress and requirements change?
      --
      Oliver.
  34. Or, better yet... by Chemisor · · Score: 4, Informative

    > assert(condition) is your friend.

    And assert(condition && "Explanation of why it's bad and what to do to fix it") is even better. Don't make me read your code and figure out why the hell you put some obscure assert(n != 455) in there.

    1. Re:Or, better yet... by Anonymous Coward · · Score: 0

      Wow, I hope someone mods you up. That's very clever! Usually it's a bit of a non-issue with me since I write code for my own purposes, so I'm the one who sees the asserts. But still, cool use of the && operator :)

    2. Re:Or, better yet... by Anonymous Coward · · Score: 0

      The only problem is, whatever you put in the "..." it is likely to not make sense when the assertion fails. If you knew the reason *why* the assertion has become false, you would not need the assertion in the first place. If you are only interested in the immediate cause of failure, you can look it up in the source code without the "..." part. You will have to, anyway. A source code comment near the assertion may give you more space to explain why you believed that the assertion should be true.

    3. Re:Or, better yet... by Anonymous Coward · · Score: 0

      A source code comment near the assertion may give you more space to explain why you believed that the assertion should be true.
      The source comment will not help you when the code fails in production. At least with && "Comment" the end user might be given a clue as to the failure. I always make sure my assertions are either clearly logged or popped up in a window.
    4. Re:Or, better yet... by Anonymous+Brave+Guy · · Score: 1

      Or, just use assert (n != UNINITIALISED_DATA) instead of magic numbers, and avoid the obscure idiom. :-)

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  35. Re:Management by ShieldW0lf · · Score: 1

    That's what business analysis is, going around asking people and writing it all up in a report. You think the executives that are signing the contracts and paying the bills know what the people on the ground need? They're salesmen, they don't.

    --
    -1 Uncomfortable Truth
  36. Very simple by jilles · · Score: 2, Insightful

    Design by contract, like most formal method approaches, doesn't scale to interesting levels. If you are working on a 200KLOC project on a tight schedule, the last thing you can afford yourself is increasing time spent per line of code by equipping classes, loops and methods with pre & post conditions. And you would need to do this on a substantial scale to make a significant impact on overall quality. I'm sure most projects could boost quality significantly if you double their budgets but then doing so is unacceptable in most real life situations. Good enough involves balancing a lot of factors and quality is just one of them.

    It's great if you can specify that a piece of code is a 100% correct implementation of a given specification but in real life the requirements are sketchy at best & keep changing during development. So, you are likely to end up with the wrong system if you don't adjust your interpretation of them to reality during development. Besides, pre and post conditions need maintenance too if you are doing maintenance on your code, so effectively they increase the cost of what is the single most expensive development activity already: maintenance.

    Besides there are other, much more useful tools for improving code quality: unit testing, integration testing, static code checkers, compile time type checking, inspections & reviews are all part of the toolkit of an experienced software engineer and largely remove the need for more formal approaches. Additionally clustering and redundant setups are a far cheaper way of guaranteeing uptime than proving the system to be correct. Risk management is better than trying to avoid risk at all cost.

    And finally, the value of 100% correctness is overrated. Most commercial software functions acceptably despite the approximately 10 bugs per kloc. In theory disaster could strike any second, in practice it is a rare event that it does and the consequences are quite manageable usually. Of course things do go spectacularly wrong sometimes and usually people then find out a lot was wrong with the overall development process aside from not applying design by contract. So even then, the added value of design by contract is very questionable. You can't compensate for general incompetence with a couple of pre and post conditions.

    --

    Jilles
    1. Re:Very simple by Coryoth · · Score: 1

      Design by contract, like most formal method approaches, doesn't scale to interesting levels. If you are working on a 200KLOC project on a tight schedule, the last thing you can afford yourself is increasing time spent per line of code by equipping classes, loops and methods with pre & post conditions. Well obviously if you're doing it post hoc it is going to be expensive, but that's a silly complaint. You should be developing contracts at the same time as you're developing code. That shouldn't be costing you much extra time because you are supposed to be writing documentation and tests for your code anyway, and contracts are as simple as writing the documentation of a function as constraints in the programming language itself (suitably extended with more expressive syntax for riting constraints) instead of in English as a comment. As a bonus you've also just done most of the work of writing a test for the code. If you're finding writing contracts as you go much extra work I have to question how well documented/commented your code is.

      At the same time you get immediate benefits from writing contracts as you go that make things easier. When everyone on the team is writing contracts that are automatically getting included in the API documentation then you have a clearer idea, just by reading the docs, and without having to fish through someone elses code, of what a function or method is intended to do - what you have to provide, and what you can expect in return. That makes integrating things much smoother. You also have the huge benefit that, when it comes to testing, any bugs that crop up are very nearly isolated and located by the contract system, allowing you to find the source of the problem much faster. Debugging code that has been well instrumented with contracts is remarkably easy and involves far less time sitting in a debugger stepping through code trying to find the original point where things started going wrong. The time savings in integration and testing more than make up for any minor extra time spent writing the contracts while developing the code. The reality is that in practice for large complex systems something like DbC can allow you to develop code faster, and get it through testing faster - it isn't more expensive, it's cheaper.
    2. Re:Very simple by jilles · · Score: 1

      Well sounds nice in theory but I don't see it in practice. I'm aware of numerous very large projects with automated test suites. I'm aware of none (as in 0) very large projects with design by contract practices in place (except maybe for places like NASA which accept rediculously high cost in exchange for better quality).

      I don't know what you mean by post hoc writing of contracts. Generally the idea of a contract is that you write the contract first and then the code. Generally the contract writing bit is actually considered to be part of the design process (hence ocl in uml). Maybe you have some alternative interpretation where you write the code first and then do documentation. Not bad, this is actually the practice in the real world of very large software systems. Except there people only document the non trivial bits of code (i.e. the things that need explaining). Dbc requires much more fine grained assertions to be of any use, hence it is much more work then regular after the fact documentation writing (which is expensive already). Anyone claiming otherwise is talking bullshit. Writing detailed contracts for a few hundred kloc is a costly affair whether you do it before, during or after coding. This is the main reason for a near total lack of adoption of dbc in the real world. The reality is that the advertised qualities of dbc have yet to be demonstrated convincingly in large to very large projects. Consequently it is not used for such work, at all (as far as I know), which in itself is a pretty convincing argument against dbc considering it has had a few decades to prove itself in practice.

      --

      Jilles
    3. Re:Very simple by Anonymous+Brave+Guy · · Score: 1

      Design by contract, like most formal method approaches, doesn't scale to interesting levels. If you are working on a 200KLOC project on a tight schedule, the last thing you can afford yourself is increasing time spent per line of code by equipping classes, loops and methods with pre & post conditions.

      By a similar argument, we should all give up with unit and integration testing, because the additional effort required to write automated tests for individual modules and then for interactions between them is prohibitive. And yet, I suspect we would agree that automated unit and integration tests can be very useful and provide a good return on investment.

      It's great if you can specify that a piece of code is a 100% correct implementation of a given specification but in real life the requirements are sketchy at best & keep changing during development. So, you are likely to end up with the wrong system if you don't adjust your interpretation of them to reality during development.

      Hmm... Wouldn't it be great if we had a mechanism that could make sure our code always met current expectations, and which could automatically notify us if loopholes started to creep in as the requirements changed and bits of code here and there were modified to keep up?

      Besides there are other, much more useful tools for improving code quality: unit testing, integration testing, static code checkers, compile time type checking, inspections & reviews are all part of the toolkit of an experienced software engineer and largely remove the need for more formal approaches.

      You're quite right about using a variety of tools, of course, but some of them are much cheaper than others. For example, it costs less to find a bug using static code analysis that can be performed automatically every check-in than to find the same bug using human intervention during a formal code inspection.

      In theory disaster could strike any second, in practice it is a rare event that it does and the consequences are quite manageable usually.

      Is it really that rare? Or are you just so used to shoddy software that you've come to accept it without realising?

      A huge proportion of the computers connected to the Internet are now part of botnets, mainly caused by basic security failings in the operating system and networking software installed on those machines. The net loss of quality of life and financial cost to business as a result of a relatively small number of bugs in that area is staggering.

      We now have quite advanced software in many consumer goods. What is the cost in quality of life if a new PVR fails to record one programme for every consumer who buys it, or a new washing machine occasionally randomly sets the temperature to 90 when it should have been 40 and ruins a whole load of clothes?

      It is an unfortunate reality that most businesses depend on a few very widely used pieces of software. What is the cost of a little UI bug in Word, if it wastes 30 seconds of time for 10 million users?

      Not so long ago, someone at the UK HQ of our organisation sent out a mail that was supposed to have the latest phone list in it. Unfortunately, due to some gremlin somewhere, the data generated included a significant amount of other, supposedly confidential, information about every employee in the UK, which was sent to every other employee in the UK. I don't know whether that was human error, but it's the sort of thing that could easily enough be caused by a small mistake in whatever script was used to generate the report, and a huge amount of bad feeling was generated amongst the entire UK employee base as a result.

      I could go on, but hopefully my point is made by now.

      Perhaps it's just wishful thinking, but I can't help noticing an increasing number of comments among my friends and family recently about just wanting

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  37. Use is subtle by Ksigpaul · · Score: 1

    I'm not a DBC expert but when developing and designing projects I OFTEN use this paradigm when two or more developers are working on code. We separate the work that needs to be done and create "contracts" (in java we just use stubbed out classes that return dummy data) so that we can both work in tandem and integrate later. If the project is larger and involves web services there is the obvious WSDL contract that is always negotiated before-hand. If you're building your web-service and generating your wsdl then you've made a choice not to negotiate your contract and hopefully are not a very large producer because small changes in your framework could cause your clients to be forced to upgrade (this isn't a large application best-practice).

  38. What didn't take off, now? by stonecypher · · Score: 1

    Design by contract did, in fact, take off. Almost every language in the list given is older than DbC; it's not in those languages for lack of a time machine, simple as pie. In other news, many languages now include contracts as a fundamental part of the language, and as the article author points out, libraries are available to hack contracts into just about every other major language.

    If by "take off" you mean "why isn't every programmer doing it," well, for the same reason that every programmer doesn't do other things they should be doing, like API documentation. Many programmers are lazy, poorly trained, or think it's not worth the time. Some programmers believe in alternatives to contracts, or think contracts are destructive. Some programmers would insist that contracts have been a fundamental part of C/C++ since day one, in the form of ASSERT().

    Programmers are (barely) people. There's nothing we all do. Contracts are one of the most popular methods for testing things. Why are unit tests and regression tests more popular? Because it's easier to see what value they provide, if you've never used any testing. They're not better or worse; they're just easier to understand from a position of being a novice.

    Contracts are more common than for which you give them credit.

    --
    StoneCypher is Full of BS
  39. Glorified Validation by Tablizer · · Score: 1

    It is little more than glorified validation, such as IF statements that check input parameter ranges, etc. I don't think we need to add every new fad feature into languages if existing constructs already can do it.

    1. Re:Glorified Validation by Anonymous Coward · · Score: 0

      Have you ever redefined a method from a base type in a subtype? If you are going to use simple 'if' statements to check your contracts, you will have to repeat exactly the same condition in the subtype. If you decide to change the contract of the base type some day, you will have to find all subtypes and manually fix your 'if's there. I'd also like to know whether and where you are going to check representation invariants with your 'if' statements.

      But wait... you are the guy who does not need OO, so I guess "inheritance" or abstract data types are not needed either in your world.

    2. Re:Glorified Validation by Tablizer · · Score: 1

      Have you ever redefined a method from a base type in a subtype? If you are going to use simple 'if' statements to check your contracts, you will have to repeat exactly the same condition in the subtype.

      Doesn't this depend on the language? Languages with lots of meta ability can intercept both ends of the inheritance tree.

      But wait... you are the guy who does not need OO, so I guess "inheritance" or abstract data types are not needed either in your world.

      You are right about that. Philosophers have shown that most of the world is not truely tree-shaped, and I have only confirmed it by my own observation. Sets are more powerful (or at at least cleaner) for "variation management" I have to say. Inharitence, and to a slightly lessor extent ADT's, depend on a tree-shaped pattern of variation and change.

    3. Re:Glorified Validation by Javaman59 · · Score: 1

      If you are going to use simple 'if' statements to check your contracts, you will have to repeat exactly the same condition in the subtype.

      Good point!
      I would also add that reading

      void SquareRoot(int x) {
        Assert(x > 0);
      ...
      Is much easier to read than...

      void SquareRoot(int x) {
        if (x <= 0) {
            throw new MyCustomException();
      ...

      I have used assertions like this for years, whether endorsed by project standards or not, and have always found them to be a net gain in maintaining my own code.


      btw, what system do you use that enables pre-conditions to be inherited? Eiffel? I haven't encountered that yet, but it looks like a useful technique to have.



      --
      I'm a software visionary. I don't code.
    4. Re:Glorified Validation by Anonymous Coward · · Score: 0

      > btw, what system do you use that enables pre-conditions to be inherited? Eiffel? I haven't encountered that yet, but it looks like a useful technique to have.

      It is one of the basic features which distinguishes "real" DbC environments from just using assertions. Eiffel supports it (of course), as does JML. Generally, you need an ability to relax preconditions and strengthen postconditions in subtypes, not just inherit them.

      The JML syntax /*@ requires x > 0; */ is also quite readable.

    5. Re:Glorified Validation by Tablizer · · Score: 1

      One could write an "assert" function to do just that if we don't need a custom exception. You did it the wordy way. However, it may depend on how much introspection the language offers, which gets back to my original point that the more meta features a language offers, the less you have to add new gimmicks to languages when a new fad or technique comes along.

  40. Why not? Because most code is RAD by smcdow · · Score: 1

    Most projects are RAD, and as such, there's no time/room/whatever for DbC.

    Don't fool yourselves. Even if the code is supposed to be into production it'll still end up being RAD, no matter what the design gooroos tell you how it should be.

    As the famous quote goes: "In every project, it eventually becomes time to shoot the engineers and begin production".

    Think I'll make that my sig.

    --
    In the course of every project, it will become necessary to shoot the scientists and begin production.
    1. Re:Why not? Because most code is RAD by Anonymous+Brave+Guy · · Score: 1

      Most projects are RAD, and as such, there's no time/room/whatever for DbC.

      Most software projects also produce crap at the end. As with much in life, you get what you pay for.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  41. MOD PARENT UP by Deef · · Score: 1

    I've seen this over and over again -- most programmers have no idea what DBC is. If the language they used supported it natively, they would probably have learned it, but otherwise they will have no idea what it offers.

  42. Tough to define the contract by corecaptain · · Score: 1

    I think contracts are one of those things that seems to make sense when they are applied
    to very simple example problems such as the oft used Account class with debit/credit/transfer methods.

    The real test is whether the technique/methodology still makes sense when you are writing code on an actual project. Take test driven development, at first apply this can take some getting used to - for many (like myself) it is getting use to writing any tests at all!!!! But really, at its simplest TDD is asking you to do something that you should already be doing, only with more opinions on HOW and WHEN to do it. So it works.

    Design By Contract on the other hand is something quite different. Firstly, for the most part we humans do not think in terms of contracts or pre/post conditions. We might use contracts for some things - contracts that most of us never read nor understand, I might add - but for the most part I think we operate by assumptions - we don't think about a list of pre conditions before doing something and then a list of post conditions after doing something...like they say at Nike - we Just Do It.. This is not to say that the pre/post conditions don't exist - they do - but we only notice them when their violation causes us some obvious consequence - like oops, my account is over drawn! So when a developer is writing code this same type of thinking is in operation.... I need to code a function that returns a loan payment amount for a given interest rate, loan term, and loan amount - I first think about the formula that calculates this and coding it in my favorite language ... putting it in some class, giving it a good name, naming the parameters, implementing the function... I am just doing it!! I am NOT thinking about pre/post conditions such as "loan amount > zero" - So this is one reason, we just don't think this way.

    Secondly, in real systems that much of the code just doesn't lend it self to being described by pre/post conditions.... Subscriptions.get_expired() ... Seems pretty straightforward, get me a collection of expired Subscriptions...What kind of Contract would I use....

    pre-conditions: Are there none?
    post-conditions: All returned subscriptions are expired.....hmmm seems to be stating the obvious....

    1. Re:Tough to define the contract by Coryoth · · Score: 1

      Secondly, in real systems that much of the code just doesn't lend it self to being described by pre/post conditions.... Subscriptions.get_expired() ... Seems pretty straightforward, get me a collection of expired Subscriptions...What kind of Contract would I use....

      pre-conditions: Are there none?
      post-conditions: All returned subscriptions are expired.....hmmm seems to be stating the obvious.... It seems simple enough to me. Presuming you don't already have an invariant to cover it you might end up with

      require
          has_subscriptions: Current /= Void and subscription_array.size > 0
      do
          deferred
      ensure
          results_are_expired: Result.for_all(agent(subscr : SUBSCRIPTION) do Result := subscr.expired end)
          all_expired_in_results: not subscription_array.exists(agent(subscr : SUBSCRIPTION) do Result := subscr.expired and not Result.has(subscr) end)
      end
      But perhaps some of the Eiffel idioms are not helping there, so how about in JML for Java

      //@ require self != Null and subscr_array.length > 0
      //@ ensure (\forall 0 &lt;= i < \result.length; \result[i].expired())
      //@ ensure (\forall 0 &lt;= i < subscr_array.length; !subscr_array[i].expired() ==> (\result.indexOf(subscr_array[i]) == -1)
      Or something similar (it depends on the implementation as to the exact details of course). This isn't redundant information from a maintenance, refactoring, or API documentation standpoint. Perhaps because the example is simple it doesn't appear that useful, but as soon as you get much more complicated...
    2. Re:Tough to define the contract by GileadGreene · · Score: 1

      ...but for the most part I think we operate by assumptions...

      Right. And that's a huge source of bugs. Bad assumptions, or assumptions that get violated during some calls are precisely the kind of things that produce produce behavioral errors. What DbC lets you do is state your assumptions, and do so in a format that is automatically checkable (either statically or at runtime). Note that you don't have to write contracts. But if, as you're coding, you realize that you're making a particular assumption about a precondition to the call, or that you intend to guarantee some kind of postcondition, you might as well encode those assumptions and intentions as a contract.

      I am just doing it!! I am NOT thinking about pre/post conditions such as "loan amount > zero"

      <sarcasm>Yes, god forbid anyone should actually think about what they're coding before they start cutting code. That would be a recipe for disaster...</sarcasm> That said, again, you don't have to write contracts. Just as you don't have to write unit tests. But both things are good practices that are going to help you find bugs.

      Secondly, in real systems that much of the code just doesn't lend it self to being described by pre/post conditions.... Subscriptions.get_expired() ... Seems pretty straightforward, get me a collection of expired Subscriptions...What kind of Contract would I use....

      I could just as well say: "...in real systems much of the code just doesn't lend it self to being checked by unit tests.... Subscriptions.get_expired() ... Seems pretty straightforward, get me a collection of expired Subscriptions...What kind of unit test would I use...." Seriously, stop and think about what kind of unit tests you would define for Subscriptions.get_expired(), and you're likely to be well on your way to figuring out what the preconditions (if any) and postconditions of the operation are.

    3. Re:Tough to define the contract by Todd+Knarr · · Score: 1

      Translating the contract:

      1. We can't be a null object.
      2. The subscription list can't be empty.
      3. All entries in the result list must be expired.
      4. All expired entries in the subscription list must be in the result list.
      The third and fourth are simply a summary of the function's definition. The first lacks sense in a lot of languages because if the current object was null the method call itself would've generated an error. The second is an invalid requirement, the subscription list can very well be empty and the result should be an empty list (exactly equivalent to having no expired subscriptions in the subscription list).

      The two post-conditions, though, show why DbC never took off: they're utterly redundant code. First you scan the subscription list to find all expired subscriptions. Then you scan the list you just built to ensure all subscriptions in it are expired. Well, if they aren't, why were they added in the first place? If you made a mistake in the test for expiration in the result-building code, you're going to make the same mistake in the post-condition. Then you scan the subscription list and, for each expired item, make sure it's in the result list. Um, isn't this what you just did building the result list? So you have 3 iterations of exactly the same thing. And what you're checking isn't even a run-time check, it's a coding-time check on whether the expired() method actually returns the correct results. Worse, the DbC stuff doesn't even eliminate the need for that desk-check, since if the expired() method is wrong the post-condition checks will still succeed even though the results are wrong.

    4. Re:Tough to define the contract by Coryoth · · Score: 1

      I think you're missing the point of contracts. It isn't to tell you what the function does when you write it (though stating your intentions doesn't hurt to clarify your thoughts), it is to tell other people what the function does, and to tell yourself in a years time. Contracts go in the documentation so you can read them instead of having to fish through code. More importantly, for functions less trivial than the one you happened to specify, contracts can and do describe functionality and requirements far more succinctly than implementation code does. I can tell you what contracts a sort function must meet much more easily than I can explain the details of a particular sorting implementation. All you're doing is saying "here is a really simple example for which the implementation is as short as the contract, therefore contracts are always useless" which is nonsense. I can write a function for which the type signature is essentially the same as the implementation, that doesn't mean static typing is of no value. Degenerate cases don't prove ineffectiveness in general.

  43. Several reasons... by Anonymous Coward · · Score: 1, Insightful

    Here are several reasons why DbC has not caught on, ordered descending by importance:
    1. Writing a contract is often just as difficult as writing its implementation, with the same potential for mistakes. Also, there seem to be no guidelines whether contracts for higher-level procedures should repeat some of the stuff already present in contracts for lower-level procedures which they invoke. The required case-by-case decisions are arbitrary and annoying.
    2. Lack of language support. Without language support and inheritance, you will be forced to copy-paste contracts, increasing the risk of inconsistency. Unofficial language extensions like JML do not integrate well with development tools.
    3. Lack of education. DbC is relatively unknown, increasing the risk that future maintainers will be baffled by your code. DbC requires deeper understanding of OO and a more systematic approach than informal unit testing.
    4. Personality of the inventor. Meyer's strong opinions and attempts to push Eiffel/DbC onto the market made other academics hold back their endorsement.

  44. useful tools attract users; overhead doesn't by Anonymous Coward · · Score: 0

    Creators and maintainers of code, ever what you want to call them (programmers, developers, software engineers, saboteurs...), are just like other folks, really. If you make available to them a tool which enables them to do their jobs "fbc" (faster/better/cheaper) according to how they want to or have to do their jobs, they will be all over that tool like flies on used dog food. Alternatively, like so many other purported improvements to systems which claim to enable fbc work (usually promised in toto, not at the moment at hand), DbC is additional overhead (viz., "more work") for the individual at the moment (which is how adoption decisions are made).
    I have seen many laments about supposedly great systems not being adopted. Most seem to me to really be complaints by someone that others don't want to work the way s/he would like them to.

    Folks are smart. If something is an improvement, adoption happens.

    1. Re:useful tools attract users; overhead doesn't by Anonymous Coward · · Score: 0

      While I agree with your explanation of the adoption barriers (folks looking for instant gratification), I disagree with your last statement:

      > Folks are smart. If something is an improvement, adoption happens.

      If this were the case, everyone would be using the same, optimal technology. But they are not. Foresight is a skill which is often required and lacking. Paying or taking risks today to reap benefits tomorrow is called 'investment'. I speculate that not many 'coder folks' who make decisions about technology are talented investors and they managers do not necessarily have a clue either. In other words, folks are not that smart.

      This is not to say that DbC necessarily provides great returns.

    2. Re:useful tools attract users; overhead doesn't by petermgreen · · Score: 1

      Folks are smart. If something is an improvement, adoption happens.
      folks are dumb, if something takes extra time in the short term then they are unlikely to adopt it regardless of its long term advantages.

      most programmers (and i know i'm guilty of this myself) work on the assumption that fixes are easy and so quality doesn't matter much. This is true up to a point but trouble is people don't count the costs the bugs cause in the time between initially becoming apparent and being fixed. Nor the cost of tracing a bug that happens apparently randomly in production use or only on servers that run for months or whatever. How much does a MS security hotfix cost MS and thier customers? I don't have figures (probablly noone has figures for what it costs thier customers in agregate) but I bet its a VERY large sum of money.

      In other engineering disciplines the costs are more obvious and the methodologies better developed.

      --
      note: i'm known as plugwash most places but i screwd up registering that here somehow in the past and now can't register
  45. It's Trademarked by sohp · · Score: 1

    A little research on the part of the OP might have turned up the following fact, pretty well known to those of us who are familiar with the technique, from Wikipedia: Design by Contract(TM)" is a trademark of Eiffel Software, the designers of Eiffel.

    So the short answer is, DbC is extremely common, but it can't be called that by anyone but Bertrand Meyer and his licensees.

    On the other hand, from my experience writing good unit tests gives you most of the benefits of DbC and a whole bunch of other benefits that DbC doesn't give, so of the two, I'd rather spend my time writing unit tests.

    1. Re:It's Trademarked by John+Hasler · · Score: 1

      > So the short answer is, DbC is extremely common, but it can't be called that by anyone
      > but Bertrand Meyer and his licensees.

      It can be called that by anyone who is not using it as a label to sell something.

      --
      Warning: this article may contain humor, sarcasm, parody, and perhaps even irony. Read at your own risk.
    2. Re:It's Trademarked by Anonymous Coward · · Score: 0

      It is not only trademarked, it is useless.

      Suppose you have 3 methods: f, g and h, defined like this:

      void f( int a, int b )
      {
            g( a );
            h( b );
      }

      void g( int a ) { ... }
      void h( int b ) { ... }

      Suppose g contract is a > 0 and h contract is b > 5.

      Then if f contract is a > b, there are some values of a and b that will satisfy f contract, but not g and h contracts. The DBC model does not specify how the DBC compiler will take care of that, so eventually the problem occurs at runtime when the program has been deployed.

    3. Re:It's Trademarked by Coryoth · · Score: 1

      I think your example mostly shows how little you know about DbC systems. For example, code those contracts in Eiffel and run ES-Verify over it and it will happily inform you that the contracts on g and h cannot be guaranteed. Likewise code it in Java with JML and run ESC/Java2 over it and it will tell you the contracts on g and h cannot be satisfied, and it will even be kind enough to explain why. Fix the precondition on f to specify that that you also require a > 0 and b > 5 and all of a sudden it will verify in both systems. Which is to say that, in fact, DbC systems will let you catch precisely the sort of error you give as an example.

      Even if you don't use verifiers then the problem will likely be found in testing (rather than production), and given the contract violation and the call stack you can quickly see that f will require further constraints for the pre-conditon. Running again the problem will naturally bubble up through anymore call layers if you have something calling f unsafely.

      Contrary to your claims DbC is far better at catching errors such as you suggest, and is clearly going to be a vast improvement over no contracts at all.

  46. A Question of Approach by JoeRandomHacker · · Score: 1

    I think the main reason DbC isn't more popular is the approach that most programmers take to programming: getting the computer to do something. When you write a program, most think about what they want the computer to do when it is done. This is why imperative languages have flourished while functional and logic languages marginalized. Coming up with valid and useful contracts is mental work that doesn't get you closer to usable code, especially in a Less Is More world.

    If, on the other hand, you do a complete analysis of the problem, build a conceptual model of the entities and operations involved, and code to that, then you are getting closer to the realm of mathematics, and DbC might be for you.

    The middle ground is where we get things like type checking, objects/classes, a variety of code analysis tools, and probably a pile of things I've forgotten or I'm unaware of.

    1. Re:A Question of Approach by DragonWriter · · Score: 1

      think the main reason DbC isn't more popular is the approach that most programmers take to programming: getting the computer to do something. When you write a program, most think about what they want the computer to do when it is done. This is why imperative languages have flourished while functional and logic languages marginalized.


      Seems to me that imperative languages have flourished for the last several years largely by competing with each other to borrow the most features from functional languages (logic languages not as much, yet); IMO, 20-30 years ago, imperative languages flourished because they were more efficient because they were structurally closer to machine code, and hardware constraints meant that, outside of certain, fairly narrow problem domains, functional and logic languages (and, to a lesser extent, even OO languages) were too inefficient (either in code overhead or performance) to be practically attractive.

      Over time, both with more power available and a shift in the kinds of problems software is sought to address, OO features were first borrowed from existing OO languages and grafted on to popular imperative languages, and then OO features along with imperative features became part of the common core in new general purpose languages. Now, we're seeing much the same thing happening with functional programming features. Maybe logic programming features will be next.

      But your explanation, I don't think, holds up, . Logic and functional languages tend to express things in the closest way to thinking about what you want the result to be, so if that was the driving force behind language popularity, I'd expect them to be most popular, and imperative lnaguages, which focus instead the process rather than the expected results.

  47. No language supports design by contract by angel'o'sphere · · Score: 1

    In contrary to the authors post, languages like C++ / Java etc. do not support design by contract.

    To have DbC you need to use 3rd party tools and ugly hacks. That basically means 2 compile steps, one where the standard compiler compiles your source language, e.g. Java, to byte code, and a second step where the extra tool analyzes the source code, the comments or the annotations and enhances/augments the byte code then.

    OTOH, test driven development or Extreme Programming where the focus is on having so many tests that every single method is tested, basically are exactly the same as DbC. It does not matter for the ordinary developer wether he can write his pre- and postconditions directly inside the code, or if he has a test which checks the pre-and postconditions in well defined test harnesses.

    OTOH, as soon as Java has pre- and postconditions the language only needs 3 more things: multiple inheritance, templates and operator overloading.

    angel'o'sphere

    --
    Cost free eBook I read (by iBook/Kobo/Amazon/ObookO/Gutenberg etc.): "The Green Odyssey" by Philip Jose Farmer.
  48. Almost right by so far away by bill_mcgonigle · · Score: 1

    The first thing most routines do is validate their arguments

    Let me modify that just a little bit: "The first thing most routines should do is validate their arguments."

    A large majority of the security and stability problems we see in software occur precisely because (lazy|busy|rushed|incompetent) programmers didn't do this. When you're faced with that problem having the language force you to do the right thing can be helpful.

    Also many languages don't have all the right tools to make argument checking easy. I find this easiest with languages like Perl which excel at matching, but doing the same task in ANSI C might take 10x the LOC.

    I know *I* write better code when Java makes me catch exceptions, etc. - I admit to resembling the above group of programmers at times. Note to self: go check out the java version of design by contract again...

    --
    My God, it's Full of Source!
    OUTSIDE_IP=$(dig +short my.ip @outsideip.net)
    1. Re:Almost right by so far away by Coryoth · · Score: 1

      Just because you're interested I'll do a little boosterism for the Java DbC system because it is actually pretty cool. First I'll admit the downside: it works by embedding annotations for contracts in comments (like JavaDoc comments basically) which makes it a little bit hacked on, but you take what you can get. The upsides include: good tool support, so not only do you get a compiler that converts annotations into runtime checks, but a version of JavaDoc that incorporates annotations into the auto-generated API documentation, and a tool that can read the contract annotations and generate a corresponding JUnit class, along with automated data generation schemes (to which you can add if you wish). If you throw in ESC/Java2 which does static checking of the contracts and can catch a lot of subtle errors statically, and Daikon which exercises your code and tries to statistically infer likely invariant properties (spitting out results in form that can be added directly as annotations), and Eclipse plugins and the whole thing starts to look quite nice. Here's a journal entry I made on the subject.

    2. Re:Almost right by so far away by bill_mcgonigle · · Score: 1

      Cool. Thanks for the reply and journal link. I haven't read the whole thing yet, but I'll review it for a new project I'm starting work on soon. I'm funding this one myself, and somehow that makes design by contract much more appealing. :)

      --
      My God, it's Full of Source!
      OUTSIDE_IP=$(dig +short my.ip @outsideip.net)
    3. Re: Almost right by so far away by gidds · · Score: 1
      [fx: gets on hobbyhorse] Actually, I think you still overstate the case. It's not just that developers don't bother to validate their arguments; it's that they haven't worked out what those preconditions are, or even realised that there are preconditions!

      It's not even laziness: it's the mindset. I've worked in a few IT departments, and IME most developers don't (can't?) see much beyond the code they're writing. They never think about who might be calling their function, who might be using their class, what that person might need to know in order to make proper use of it -- and, just as importantly, what they don't need to know. About the Big Picture(TM).

      That might mean documentation/comments; it might mean setting up preconditions and invariants; it might mean picking meaningful names; it might just mean stopping and thinking about what you're writing.

      The result: we end up with systems that are unnecessarily hard to maintain, where in order to understand any part of it you have to understand every other part as well, where each new developer has to reinvent the wheel because the tens of existing ones can only be used by their authors.

      So maybe the biggest benefit of DbC isn't actually in the conditions, it's simply that it gets developers to think about them in the first place!

      --

      Ceterum censeo subscriptionem esse delendam.

    4. Re: Almost right by so far away by bill_mcgonigle · · Score: 1

      So maybe the biggest benefit of DbC isn't actually in the conditions, it's simply that it gets developers to think about them in the first place!

      Very well put.

      --
      My God, it's Full of Source!
      OUTSIDE_IP=$(dig +short my.ip @outsideip.net)
  49. Re: Absolutely not "Already mostly done" by berenddeboer · · Score: 1
    I wonder who voted your post to five informative, as you seem to be quite uninformed on the topic. DbC isn't argument checking. As Bertrand Meyer states in his seminal "Object-Oriented Software Construction":

    Non-Redundancy principle: Under no circumstances shall the body of a routine ever test for the routine's precondition.

    This rule is the reverse of what many software engineering or programming methodology textbooks advocate, often under the name of defensive programming -- the idea that to obtain reliable software you should design every component of a system so that it protects itself as much as possible. Better check too much.... A redundant check might not help, but at least it will not hurt.

    Design by Contract follows from the opposite observation: redundant checks can and indeed will hurt.

    I really suggest you read Bertrand Meyer's book before making claims on what Design by Contract is in the real world.
    --
    If I had a sig, I would put it here.
  50. Because it's not legally binding by Anonymous Coward · · Score: 0

    The party to the contract with all the power never wants to abide by their side of the contract.
    Often, but not always "management".

  51. Re:Management by drgonzo59 · · Score: 1
    Good point.

    The problems is that developers, users and managers all speak somewhat different languages. It's all English but they all see things in a different way and that leads to confusion. In general developers should spend a considerable amount of time with the users in their domain to really understand the needs of those users.

    Case in point, I worked for a CAD firm and our developers would be sent to different companies to observe how the engineers use our product. We would invite many of those engineers to our headquarters and let them just spend time with the developers. It worked great, especially as far as the user interface of our systems was concerned. To an average non-engineer Joe it would look totally ugly and counter-intuitive but the engineers (our real customers) loved the user interface. When the company was bought out and new management came in they decided to single-handedly change to interface to make it more Windows-like. It ended up sucking and every single real user of our product hated it and refused to upgrade to the new version. The company went downhill after that. I quit too...

  52. It's because it's tied to a specific language by Anonymous Coward · · Score: 0

    DbC failed because it was tied to Eiffel.

    You can do XP with any language.

    Also unit testing can do the same thing as DbC. Don't want null to be passed into a function? Make a unit test to make sure it doesn't happen.

    1. Re:It's because it's tied to a specific language by Coryoth · · Score: 1

      Don't want null to be passed into a function? Make a unit test to make sure it doesn't happen. Heh. I'd be interested to see that "unit" test, since you'll essentially need to be checking that all code that calls that function can't result in the parameter passed being null - you'll be testing every unit that calls that code, and you won't cover all possible code paths, just the few you happen to test. But worse is that you're exporting the problems with one unit (that you want to have a non-null parameter) to everything else. What happens if you write another unit that also happens to call that code? You'll have to remember to write an extra unit test for the new unit to ensure if won't pass in a null value. It makes much more sense to localise the checking with a single contract on the function that will flag an error if a null ever gets passed - you're writing the "test" once, and it is directly associated with the point where the problem will occur.
  53. Re:Management by Anonymous Coward · · Score: 0

    Indeed. "use cases" alone totally suck for stating requirements. Give me a good old-fashioned SRS or SDD anyday.

  54. Re: Absolutely not "Already mostly done" by Todd+Knarr · · Score: 2, Insightful

    Unfortunately Mr. Meyer runs up against the halting problem. If the definition of a function, or the contract, says that a parameter must never be the NULL pointer, there are two choices: the code must check whether that pointer is NULL, or it must be proven that that pointer can never possibly be NULL. The second is, with the current state of the art, impossible no matter what language constructs are around to help. That means the check has to be done, the only question is whether it's done by the caller or the called function. And the first rule I learned is to eliminate redundancy, which means that given a choice of doing a check in one place or doing it in a large number of places you do it in the one place.

    Design by contract is many things, a large number of them good, but it is not a replacement for error-checking.

  55. Re:Management by Anonymous Coward · · Score: 0

    People have a tendency to confuse bluster and arrogance with ability and experience.



    They do, yet in my experience, these things are inversely correlated. This applies to all guidance/oversight roles, including business analysts, software architects, consultants, and indeed managers themselves. As I've commented here before, you can always identify a good leader by three characteristics:



    • They can set a clear direction and convey this to others.
    • They organise adequate resources and set realistic expectations.
    • Having done the above, they get out of the way as much as possible.


    The third one is usually the easiest way to identify morons. If you come across a leader in software development who places more value on reports and metrics so they can track things than they do on supporting the developers and test teams working for them, then you know you're dealing with an incompetent.



    And yes, that does mean many leaders in software development organisations today are incompetent. That's why the genuinely good people are worth so much.

    I couldn't agree with your three characteristics more, (or the parent poster's opinions as well), which is why, as a business analyst, I plan to ask for a raise this week as a part of my annual review. Not just the shitty 3% raise mind you, more than 10%. Why? Because I have my B.S. in Computer Engineering, have been doing this job for about 4 years now, HAVE the 3 characteristics of a good leader mindset and do my best to fulfill it (although oftentimes not wonderfully), and yet I'm STILL better than half the people I've ever met doing the 'Architect' or 'Business Analyst' job descriptions, because as you say, the good people are hard to find. Arrogant of me to consider myself "better than the rest"? Maybe, but if my management accepts my raise request, then either I am better than most, they're more clueless than most, both, or neither (I am a moron and they're great leaders). In any case, I figure the worst I could possibly do is to NOT get the raise, in which case I'll likely begin considering other alternatives to this job, or find another way to get my raise. This will have the effect (in my mind, anyways) of either confirming my work at this company, why I'm working for these people, and the way I'm going about doing my work; OR give me pause to consider who I'm working for, how I'm working, and whether it's worth sticking with these people, division, or company. Either way, I win.

    My point is that, if you're reading this post (or the previous two parent posts), and finding that you agree... well, why are you also not asking for a raise? Quit whining about the job market and off-shoring, and ask for what you want!
  56. Re:Management by try_anything · · Score: 1

    People have a tendency to confuse bluster and arrogance with ability and experience.

    They do, yet in my experience, these things are inversely correlated.

    I have a math degree and am now taking CS classes. It seems to me that in contrast to mathematics and physics training, the CS curriculum makes computing seem easier than it really is. There's a pervasive "it's simple" attitude that is enabled by focusing on solved problems and simple situations. I wonder if that has anything to do with why inexperienced developers get themselves into trouble with their arrogance.

  57. Re:Management by try_anything · · Score: 1

    And let me add that I include many experienced managers in the category of "inexperienced developers." A programmer comes out of college thinking, "Everything is easy; these guys must not be too bright if they're having problems." If he makes it into management without having an attitude adjustment, he's going to blame all his failures on the fact that his developers are missing some wonderful insight that he possesses. Then he grabs onto different fads as ways of making his programmers see the light. If the great new thing is just a repackaging of something he already knows, so much the better, since he already knows everything.