Beta
×

Welcome to the Slashdot Beta site -- learn more here. Use the link in the footer or click here to return to the Classic version of Slashdot.

Thank you!

Before you choose to head back to the Classic look of the site, we'd appreciate it if you share your thoughts on the Beta; your feedback is what drives our ongoing development.

Beta is different and we value you taking the time to try it out. Please take a look at the changes we've made in Beta and  learn more about it. Thanks for reading, and for making the site better!

Why Is "Design by Contract" Not More Popular?

Cliff posted more than 7 years ago | from the puzzling-outcomes dept.

Programming 178

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?"

cancel ×

178 comments

Sorry! There are no comments related to the filter you selected.

Because... (0)

Anonymous Coward | more than 7 years ago | (#18297940)

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

Management (4, Insightful)

Bottlemaster (449635) | more than 7 years ago | (#18297944)

I don't know, but I can tell you why design-by-contract isn't as popular is Extreme Programming. With DBC, there's little role for management except to the developers to start using it. Buzzwords are great, but nothing beats letting the managers participate in a revolutionary development paradigm. Design-by-contract, unlike other next generation techniques, distinctly lacks this synergy between management and developers.

Re:Management (0, Troll)

rednip (186217) | more than 7 years ago | (#18298058)

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.

Re:Management (3, Insightful)

ShieldW0lf (601553) | more than 7 years ago | (#18298150)

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.

Re:Management (1)

rednip (186217) | more than 7 years ago | (#18298194)

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.

Re:Management (4, Interesting)

Anonymous Brave Guy (457657) | more than 7 years ago | (#18298890)

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.

Re:Management (1)

Propaganda13 (312548) | more than 7 years ago | (#18299178)

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.

Re:Management (1)

ShieldW0lf (601553) | more than 7 years ago | (#18299446)

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.

Contracts (2, Funny)

VGPowerlord (621254) | more than 7 years ago | (#18297974)

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

Re:Contracts (0, Troll)

Nutria (679911) | more than 7 years ago | (#18299894)

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?

Re:Contracts (1)

VGPowerlord (621254) | more than 7 years ago | (#18300586)

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

Re:Contracts (1)

Nutria (679911) | more than 7 years ago | (#18301088)

Darl McBride, CEO of SCO.

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

Re:Contracts (1)

Richard Steiner (1585) | more than 7 years ago | (#18301128)

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

Some folks [groklaw.net] still do... :-)

Who cares? (2, Insightful)

jrockway (229604) | more than 7 years ago | (#18298012)

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

Re:Who cares? (2, Insightful)

heinousjay (683506) | more than 7 years ago | (#18298132)

You win the topic. Everything else is masturbation.

Re:Who cares? (1)

Haeleth (414428) | more than 7 years ago | (#18298694)

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.

Re:Who cares? (1)

heinousjay (683506) | more than 7 years ago | (#18300424)

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.

Re:Who cares? (4, Insightful)

Just Some Guy (3352) | more than 7 years ago | (#18298176)

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.

Re:Who cares? (1)

rednip (186217) | more than 7 years ago | (#18298262)

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.

no bang for your buck (3, Insightful)

majiCk (264238) | more than 7 years ago | (#18298018)

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.

Re:no bang for your buck (4, Insightful)

barrkel (806779) | more than 7 years ago | (#18298090)

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 [msdn.com]

Re:no bang for your buck (2, Interesting)

Tablizer (95088) | more than 7 years ago | (#18301002)

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.

Re:no bang for your buck (1)

mattpalmer1086 (707360) | more than 7 years ago | (#18302764)

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.

Re:no bang for your buck (3, Insightful)

Coryoth (254751) | more than 7 years ago | (#18298634)

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 [inf.ethz.ch] or Quickcheck [chalmers.se] sometime, they are suprisingly powerful and have found bugs in established production code that had already undergone extensive standard testing.

Re:no bang for your buck (1)

ozone_sniffer (778249) | more than 7 years ago | (#18301316)

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

Re:no bang for your buck (1)

Coryoth (254751) | more than 7 years ago | (#18301874)

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.

Re:no bang for your buck (0)

Anonymous Coward | more than 7 years ago | (#18301054)

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.

Extreme Programming (4, Funny)

andy314159pi (787550) | more than 7 years ago | (#18298036)

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.

Mod parent up (0, Offtopic)

lewp (95638) | more than 7 years ago | (#18298174)

+1 accurate description of extreme programming

Design by Contract (2, Informative)

VGPowerlord (621254) | more than 7 years ago | (#18298080)

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.

Sometimes more complexity is worth it (1)

Anonymous Brave Guy (457657) | more than 7 years ago | (#18298956)

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

It needs serious language support (5, Informative)

Animats (122034) | more than 7 years ago | (#18298140)

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#, [microsoft.com] 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.

But what kind of language? (2, Insightful)

Anonymous Brave Guy (457657) | more than 7 years ago | (#18299022)

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.

Re:It needs serious language support (0)

Anonymous Coward | more than 7 years ago | (#18299574)

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.

Re:It needs serious language support (1)

timeOday (582209) | more than 7 years ago | (#18299986)

It's been done well for Modula and Java
By whom? I'd like to look into it for my Java projects.

Re:It needs serious language support (2, Informative)

Coryoth (254751) | more than 7 years ago | (#18300110)

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 [secure.ucd.ie] which uses JML [iastate.edu] as annotation markup. I actually listed this as the Java DbC implementation in the article description.

Re:It needs serious language support (0)

Anonymous Coward | more than 7 years ago | (#18302454)

Don't forget the D programming language [digitalmars.com] .

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

Too many layers (3, Insightful)

Geoffreyerffoeg (729040) | more than 7 years ago | (#18298186)

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.

Re:Too many layers (1)

Coryoth (254751) | more than 7 years ago | (#18298594)

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

Re:Too many layers (0)

Anonymous Coward | more than 7 years ago | (#18299220)

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.

Re:Too many layers (1)

Geoffreyerffoeg (729040) | more than 7 years ago | (#18301320)

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.

misleading title (0)

Anonymous Coward | more than 7 years ago | (#18298220)

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

people do (1, Insightful)

oohshiny (998054) | more than 7 years ago | (#18298226)

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.

If you can contract it it's coded already (2, Insightful)

IICV (652597) | more than 7 years ago | (#18298256)

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.

Re:If you can contract it it's coded already (2, Insightful)

Coryoth (254751) | more than 7 years ago | (#18298704)

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.

Re:If you can contract it it's coded already (1)

poopdeville (841677) | more than 7 years ago | (#18302996)

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.

Re:If you can contract it it's coded already (1)

Coryoth (254751) | more than 7 years ago | (#18303556)

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. [yorku.ca]

Re:If you can contract it it's coded already (1)

UlfJack (868219) | more than 7 years ago | (#18299470)

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.

DbC? Unit testing? Boring and costs time. (0)

cerberusss (660701) | more than 7 years ago | (#18298304)

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.

Re:DbC? Unit testing? Boring and costs time. (0, Flamebait)

DaveV1.0 (203135) | more than 7 years ago | (#18298370)

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.

Re:DbC? Unit testing? Boring and costs time. (1)

cerberusss (660701) | more than 7 years ago | (#18298698)

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?

Re:DbC? Unit testing? Boring and costs time. (0)

Anonymous Coward | more than 7 years ago | (#18300158)

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.

Re:DbC? Unit testing? Boring and costs time. (0)

Anonymous Coward | more than 7 years ago | (#18302650)

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.

Boring and costs time, but necessary. (1)

DJ Rubbie (621940) | more than 7 years ago | (#18299024)

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.

Re:Boring and costs time, but necessary. (1)

cerberusss (660701) | more than 7 years ago | (#18300034)

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.

Re:Boring and costs time, but necessary. (1)

mattpalmer1086 (707360) | more than 7 years ago | (#18303102)

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!

I'd like to use DbC, but... (1)

Sircus (16869) | more than 7 years ago | (#18298318)

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.

Re:I'd like to use DbC, but... (4, Informative)

Coryoth (254751) | more than 7 years ago | (#18298746)

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 [iastate.edu] and ESC/Java2, and Spec# [microsoft.com] , because you would be interested.

Re:I'd like to use DbC, but... (1)

Sircus (16869) | more than 7 years ago | (#18299306)

Then you really need to check out JML [iastate.edu] and ESC/Java2, and Spec# [microsoft.com] , because you would be interested.
Thanks - I'll check out JML and ESC/Java2 (we're using Java throughout, both client and server-side).

Re:I'd like to use DbC, but... (1)

5pp000 (873881) | more than 7 years ago | (#18302268)

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.

Re:I'd like to use DbC, but... (2, Insightful)

Tablizer (95088) | more than 7 years ago | (#18302378)

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.
     

DBC requires more formalism in your approach (1)

spagetti_code (773137) | more than 7 years ago | (#18298420)

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.

Re:DBC requires more formalism in your approach (1)

NovaX (37364) | more than 7 years ago | (#18298502)

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.

Re:DBC requires more formalism in your approach (1)

Coryoth (254751) | more than 7 years ago | (#18298768)

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 [yorku.ca] which are specifically designed for doing XP in Eiffel using contracts. Try reading one of the ESpec papers on XP programming with ESpec [yorku.ca] . 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).

Already mostly done (3, Informative)

Todd Knarr (15451) | more than 7 years ago | (#18298452)

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.

Re:Already mostly done (1)

Coryoth (254751) | more than 7 years ago | (#18298816)

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.

been doing that for years already (5, Insightful)

imbaczek (690596) | more than 7 years ago | (#18298572)

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.

Or, better yet... (4, Informative)

Chemisor (97276) | more than 7 years ago | (#18299438)

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

Re:Or, better yet... (0)

Anonymous Coward | more than 7 years ago | (#18299572)

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

Re:Or, better yet... (0)

Anonymous Coward | more than 7 years ago | (#18302038)

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.

Re:Or, better yet... (0)

Anonymous Coward | more than 7 years ago | (#18303524)

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.

Re:been doing that for years already (1)

Coryoth (254751) | more than 7 years ago | (#18300184)

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.

Glorified Validation (1)

Tablizer (95088) | more than 7 years ago | (#18300940)

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.

Re:Glorified Validation (0)

Anonymous Coward | more than 7 years ago | (#18302148)

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.

Re:Glorified Validation (1)

Tablizer (95088) | more than 7 years ago | (#18302330)

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.
       

Re:Glorified Validation (1)

Javaman59 (524434) | more than 7 years ago | (#18303094)

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.



Programmers don't find it easy (2, Informative)

smcleish (118335) | more than 7 years ago | (#18298652)

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.

DbC and Unit Tests cover similar ground (2, Insightful)

FrnkMit (302934) | more than 7 years ago | (#18298752)

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 [onestepback.org] and particularly the postscript.

Re:DbC and Unit Tests cover similar ground (1)

FrnkMit (302934) | more than 7 years ago | (#18298780)

But see also http://onestepback.org/articles/TddMeetsDbc [onestepback.org] 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.)

Re:DbC and Unit Tests cover similar ground (1)

chromatic (9471) | more than 7 years ago | (#18301542)

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 [wikipedia.org] so it's easy.

Design by contract is 25+ years old (0)

Anonymous Coward | more than 7 years ago | (#18298922)

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

Glass

Re:Design by contract is 25+ years old (3, Funny)

Waffle Iron (339739) | more than 7 years ago | (#18299680)

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);

Side Effects (2, Insightful)

somepunk (720296) | more than 7 years ago | (#18298924)

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.

Re:Side Effects (1)

Watson Ladd (955755) | more than 7 years ago | (#18302972)

Like a compiler [haskell.org] ? 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.

The real reason why it is not more popular (1)

rollingcalf (605357) | more than 7 years ago | (#18299070)

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

MOD PARENT UP (1)

Deef (162646) | more than 7 years ago | (#18301108)

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.

I use it all the time! (1)

Nappa48 (1041188) | more than 7 years ago | (#18299226)

//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?)

You need to have a contract first (1)

khchung (462899) | more than 7 years ago | (#18299360)

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.

Re:You need to have a contract first (1)

chromatic (9471) | more than 7 years ago | (#18301562)

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.

Very simple (2, Insightful)

jilles (20976) | more than 7 years ago | (#18299800)

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.

Re:Very simple (1)

Coryoth (254751) | more than 7 years ago | (#18300252)

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.

Re:Very simple (1)

jilles (20976) | more than 7 years ago | (#18302732)

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.

Use is subtle (1)

Ksigpaul (665724) | more than 7 years ago | (#18299914)

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

What didn't take off, now? (1)

stonecypher (118140) | more than 7 years ago | (#18300500)

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.

Why not? Because most code is RAD (1)

smcdow (114828) | more than 7 years ago | (#18301044)

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.

Tough to define the contract (1)

corecaptain (135407) | more than 7 years ago | (#18301176)

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

   

Several reasons... (1, Insightful)

Anonymous Coward | more than 7 years ago | (#18301772)

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.

useful tools attract users; overhead doesn't (0)

Anonymous Coward | more than 7 years ago | (#18302132)

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.

Re:useful tools attract users; overhead doesn't (0)

Anonymous Coward | more than 7 years ago | (#18302322)

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.

It's Trademarked (1)

sohp (22984) | more than 7 years ago | (#18302864)

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.
Load More Comments
Slashdot Login

Need an Account?

Forgot your password?

Submission Text Formatting Tips

We support a small subset of HTML, namely these tags:

  • b
  • i
  • p
  • br
  • a
  • ol
  • ul
  • li
  • dl
  • dt
  • dd
  • em
  • strong
  • tt
  • blockquote
  • div
  • quote
  • ecode

"ecode" can be used for code snippets, for example:

<ecode>    while(1) { do_something(); } </ecode>