Java Solaris Communities Sun Store Join SDN My Profile Why Join?
 
Bug Database
Bug Detail
Quick Lists
Top 25 Bugs
Top 25 RFE's
Recently Closed Bugs
Printable Page Printable Page


Bug Database
Bug ID: 4449383
Votes 586
Synopsis Support For 'Design by Contract', beyond "a simple assertion facility"
Category java:specification
Reported Against 1.3
Release Fixed
State 4-Defer, request for enhancement
Priority: 5-Very Low
Related Bugs
Submit Date 23-APR-2001
Description


java version "1.2.2" and 1.3
Classic VM (build JDK-1.2.2_007, native threads, symcjit)

This request should not be considered a duplicate of Bug ID
4071460, entitled "Please add assert capability to the Java Language". I am,
herein, requesting support for the principles of 'Design by Contract' (DBC),
as described in chapter 11 of Bertrand Meyer's 'Object-Oriented Software
Construction, Volume II", where Meyer clearly states that DBC is not the
simple "assert" mechanism of C/C++ (which is essentially identical to
the "simple assertion facility" being included with the merlin-beta release of
Java). I find it a shame that all the requests for DBC support were considered
satisfied/closed by the addition of this "simple assertion facility". We don't
want a "simple assertion facility", we want full support for DBC : a software
reliability mechanism that is both extremely powerful and incredibly elegant.

  Description of DBC, by Bertrand Meyer:
"Design by Contract, summarized in the following lines, states:

that one should not write a class without a specification - a contract. The
contract lists the internal consistency conditions that the class will maintain
(the invariant) and, for each operation, the correctness conditions that are
the responsibility of the client (the precondition) and those which the
operation promises to establish in return (the postcondition).

Writing a class without its contract would be similar to producing an
engineering component (electrical circuit, VLSI chip, bridge, engine...)
without a spec. No professional engineer would even consider the idea.

Main DBC features:

Notion of "assertion" : An expression that can be evaluated as true or false.

Notion of "class invariant" : consistency constraints placed on every instance
of a class whenever it is "externally visible" (basically, after creation and
in between every client method invocation). For example, a Person class with
and age attribute may have the assertion "age >= 0" as part of it's invariant.

Notion of "method precondition" : An assertion attached to a method, which must
be guranteed by every client prior to any call to that method. For example, a
method setSSN(String ssn) of our Person class may have the
precondition "ssn.length() == 7".

Notion of "method postcondition" : An assertion attached to a method, which
must be guaranteed by the method's body on return from any call to the method
in which the precondition was satisfied on entry. For example, method setSSN
(String ssn) of our Person class may have the postcondition "getSSN().equals
(ssn)".

"check" or "assert" construct : a language construct that would take an
assertion as input, effectively allowing a programmer to state that he believes
the assertion to hold. For example, "check(ssn.length() == 7)" or "assert
(ssn.length() == 7)". Note that this is not even 1/3 of the facilities of DBC!

So, the elements of a contract are specified using assertions. These assertions
appear as parts of one of three language constructs : invariant, precondition,
postcondition. These are optional constructs. It is up to the runtime system
(when monitoring of the relevant DBC construct is "turned on" via a compilation
option) to verify that the relevant assertions hold at the relevant times (for
example, it should verify that the invariants of a method's precondition hold
before execution of that method). This way, code is not cluttered up with lots
of mindless statement of the following form.

        if (! some_precondition_assertion)
                throw new PreconditionException();

Method bodies can then stay focused on the main task of the routine.

So please, give us the ability to specify precise, unambiguous, and enforceable
details about the behavior of Java objects, that we may increase the quality of
software developed using this language.

(Review ID: 121146) 
======================================================================
Posted Date : 2006-07-21 12:30:06.0
Work Around




Develop software in Eiffel.
======================================================================
Evaluation
I don't expect full design by contract to be supported in the
foreseeable future. The decision was made, in the context of the 
assert statement, not to take that route.


  xxxxx@xxxxx   2002-09-24
DBC is an excellent feature. By way of history, Oak had 'assertions' whereby field values could be constrained and the constraints were enforced at entry and exit of every public and protected method of the class. Methods could have their own pre- and post-conditions too, which were inherited but not redefinable in a subclass. Proving that a method in a subclass has a weaker pre-condition (c.f. contravariance) and a stronger post-condition (c.f. covariance) than the overridden method in a superclass is non-trivial.

It is not too late for DBC in Java. It is not a showstopper that the core API has no contracts, nor is the inclusion of contracts in Javadoc particularly hard. The performance hit for class invariants which are enforced all the time (as opposed to just public method entry/exit) is a concern, but many implementation techniques exist.

However, just because DBC could happen in the future does not mean it will happen now. Given the existence of assert(), it is hard to justify DBC in JDK7 in place of other, new, language features. As such, I am deferring this RFE. DBC is a perfect candidate for development by the OpenJDK community; a starting point is a source-level mapping from:
  int foo()
    pre  ASSUME_EXPR
    post ENSURE_EXPR
  {
    BODY
  }

  int foo() {
    assert ASSUME_EXPR;
    try {
      BODY
    } finally {
      assert ENSURE_EXPR;
    }
  }
(though this doesn't let the post-condition examine the return value)
Posted Date : 2007-11-30 23:29:31.0
Comments
  
  Include a link with my name & email   

Submitted On 02-MAY-2001
jonathanfinn
The preconditions/postconditions should also be inherited 
and be able to be strengthened or weakened in the 
appropriate way, which is half the point of DBC. (Analogous 
to the automatic calling of superclass 
constructors/destructors.)

Perhaps someone familiar with Eiffel (unlike me!) can 
suggest how this should be done in Java.


Submitted On 03-MAY-2001
mikedunbar
Yes, that is very important. I wrote this RFE in a hurry, and forgot to mention that preconditions, 
postconditions, and class invariants should all be inherited and be able to be strengthened or weakend as 
appropriate. Javadoc should also support DBC by including pre/post conditions and invariants in the 
generated documentation for a class.


Submitted On 04-MAY-2001
Ixchel
It may be quite difficult to implement this unless feature 
request #4211070 ("Java should support const parameters, 
like C++, for code maintenance") is also approved.

I would also like to see a way to declare certain object 
references (fields, method parameters, local variables, 
etc.) to be guaranteed to be non-null. This could be part 
of a design-by-contract proposal, or a separate proposal. 
It would be supported by data flow tracing in the compiler 
(similar to what's used now to detect unassigned final 
variables) to detect possible violations. For instance:

notnull String foo = "abc"; // foo can never be null
foo = null; // Compiler error here
foo = "def"; // No Compiler error here
String bar = getSomePossiblyNullString();
foo = bar; // Compiler error here
if (bar != null)
    foo = bar;  // No compiler error here


Submitted On 04-MAY-2001
schapel
Another Workaround: use iContract
http://www.reliable-systems.com/tools/

There's also lots of interesting information about Design 
by Contract programming in Java at
http://www.elj.com/eiffel/feature/dbc/java/ge/

One of the most interesting tidbits on that page is that 
James Gosling originally included DBC in Java (see 
preconditions and postconditions in the Oak 0.2 manual) and 
regrets having removed it to meet a deadline!


Submitted On 04-MAY-2001
abies
One important note - quite obvious, but needs to be said. DBC rules would have to find their place into  
javadocs. I'm by no way for specifying them inside javadoc comments - just placing them into 
html generated by javadoc tool. Probably some extension of doclet interface would be required.

Thing that would need to be investigated is how to fit DBC rules inside reflection scheme.


Submitted On 05-MAY-2001
abies
One more thing - maybe it is totally crazy, but in case this RFE would be accepted, SmallEiffel team could be contacted to create SmallEiffel/java dbc compatibility ? Currently SmallEiffel can target jvm, but only in one direction - common dbc would certainly allow better integration (saving multiple inheritance of course).


Submitted On 07-MAY-2001
MichaelFranz
I guess Sun's development strategy is more accurately described as "test, debug, test, debug - repeat until 
you think it works."


Submitted On 07-MAY-2001
MichaelFranz
As the author of the clearly misinterpreted bug "4071460", I can only add my support for this proposal (just 
voted for it, in fact). 

Nevertheless, I can't help feeling that adding DBC to Java at this stage in the game is just going to prove 
such a monumental task, that I can scarcely believe that Sun would even attempt it. 

For starters, in order to make the Java platform consistent with the new DBC features, the now impressively 
comprehensive Java APIs would surely have to be freshly augmented with semantic declarations. One 
consequence: A massive percentage of classes would have to be extended to include new methods. I'm 
thinking here, for example, of "Object next()" and other "queries" - which simultaneously modify the object's 
state (and which therefore cannot be used as a basis for precondition declarations). And I'm certain that 
DBC would expose hundreds of inconsistencies in these APIs, which would imply extensive re-working of the 
implementations. And what of existing code, which depends on existing "quirky" API semantics? This would 
have to be modified too.

Secondly, does JavaSoft have the personnel capable of implementing DBC satisfactorily? I have exchanged 
several emails with Sun staff (particularly those involved with the simple assert facility), which have lead me 
to believe that they just don't understand DBC is all about. The staff I addressed on the subject clearly had 
no personal experience with DBC - apparently thinking, for example, that it was a mere extension of the 
basic assert concept.

Thirdly, I suspect strongly that to add DBC would amount to an admission from which is essentially a 
C++-culture that Bertrand Meyer was right all along - and that just isn't likely to happen. It is interesting to 
note that when the likes of Gossling, Ritchie and Stroustrup are addressed on the issue of language design - 
then DBC doesn't even get a mention. Similarly, when Guy Steele emphasises the importance of the 
"interface" in OOD/OOP, he totally ignores interface semantics (really: we'd be laughing if it weren't so 
tragic!) Have these guys never heard of DBC? Not likely. "Object-Oriented Software Construction" is such a 
monumental contribution that it requires a conscious decision and effort to ignore it and it's implications.

Lastly, Sun has emphasised on more than one occasion it's strategy for obtaining software quality: Test, 
test, test and test. The result: a reasonably stable suite of APIs, and an implied self-gratification that one 
can seemingly write stable software with Java. Yet the fact that a sledgehammer testing approach is simply 
too labour intensive expensive for most organisations (it can typically only be justified for library or 
framework efforts) is quietly ignored.

Like I said, it gets my vote, but this is for the principal rather than practicality, as I basically believe that 
the damage done by not including DBC from the outset is now most likely irreparable.


Submitted On 08-MAY-2001
dkf
Interesting; not voting for this at the moment though, as my
votes are for various aspects of genericity and types. (I
suppose you could say they were part of the contract, but
those systems I've seen that formalized this relationship
were usually a bit ugly to use.)

Any reason why a third-party system (iContract maybe? I've
not had time to look into it) is not sufficient here?


Submitted On 08-MAY-2001
opinali
I voted in the original bug, but I am not renewing my vote 
here, basically for the reasons exposed by Michael Franz.  
It's just too late to add full DBC.  Tools like iContract 
can be updated to take advantage of the new assert.  Now, I 
guess we should lobby for more specific items, like const 
parameters; if we need the full DBC, external tools could 
implement them much better after having such prerequisites 
implemented.

But we are never going to have contracts in the standard 
libraries. Eiffel# is gonna try doing this by having 
wrappers that add contracts to the existing .NET libraries 
(as much DBC-friendly as Java's), but I am very skeptic 
about this until I see it working.

And I don't agree that the query-command separation is such 
a great thing.  It seems more like a wag-the-dog situation 
to me; this language feature helps writing contracts, but 
it *sucks* for anything else: makes caller code more 
complex as two invocations are required where one would 
have one; makes callee code more complex because commands 
which produce result values sometimes need to store them in 
the object's state... but this is not thread-friendly, so 
you end up duplicating the production of said results when 
doing the query... argh.  Please consider that Eiffel did 
not support threading at all when introduced, and it still 
barely and crudely supports threads compared to Java (last 
time I checked anyway).

Another big problem is IDE support; I cannot put up with 
any compicated edit-compile-debug cycle... I want to edit 
code in its high-level form in a powerful IDE (VisualAge, 
Forte, etc.) and I want everything to work seamlessly: 
syntax highlight, compilation, source control, debugging, 
browsing.  If I need to export sources, run preprocessors, 
re-import sources, and then debug some ugly tool-generated 
code instead of my original source, then I (and thousands 
of other developers) will never consider adding a DBC tool 
(as well as many other things, e.g. AspectJ) to serious 
projects, because the productivity hit is huge.  We really 
need IDEs which are enough extensible to accommodate tools 
that require source or bytecode transformations, and 
grammar changes.


Submitted On 08-MAY-2001
hwc
I would like to be able to specify "precise, unambiguous, and enforceable
details about the behavior of Java objects" but these rules need to hold
in a multi-threaded program.

In a pre-emptive multi-tasking environment, the state of any object is
externally visible unless all its variables are private and all its public
methods are synchronised.  Having beta-tested Parasoft's JContract,
I was glad to see that it could check class invariants at run time,
rather than just on entry to or exit from its methods, but that's still
a far cry from verifiable correctness.

Unlike in Java, concurrent programming in Eiffel seems closely linked
to its its pre- and post-conditions (see, for example:
http://www.eiffel.com/doc/manuals/technology/concurrency/short/page.html)

All the same, I hope this RFE stays open for discussion.  I would very much
like to be able to add conditions to Java Interfaces.


Submitted On 08-MAY-2001
abies
I might sound a little bit heretic here, but I don't think
that we need extensive dbc inside core library. It is
already guarded quite heavily with runtime check and let it
be so - no real need to change to dbc here (especially that
it would change behaviour depending on runtime dbc switches)

I would like to have dbc to develop my own code. I find it
very useful during design phase to code small skeleton 
classes, thinking about exact invariants etc. For me
'contract' part of dbc is same important as being able to
doublecheck class integerity during it's development.

Contract with core lib can be enforced using current way -
runtime checks. User code would be free to use normals ifs
or dbc if they would want to. Given current spec of java,
where almost all implementation details are well hidden,
it is not so important to have dbc for inheritance from core 
classes. Of course it would be nice, but it is not critical.

Upcoming APIs could slowly migrate to dbc. There still will
be need for some runtime checks (especially at edge of
native code - no way of allowing crash by turning dbc off).
But some code could be written new way.


Submitted On 21-MAY-2001
MichaelFranz
Why doesn't this appear in the top 25 RFE's? The 25th entry has 49 votes (to date) and this has 75.


Submitted On 23-MAY-2001
mikedunbar
I am working with / bugging Sun to fix the top 25 RFEs 
page. They are looking into the problem.


Submitted On 07-JUN-2001
enicholas
I'd have to respectfully disagree with the fire and 
brimstone types that think it's too late to do real DBC.  
Sure, you wouldn't want to retrofit ten thousand classes in 
the core API to have all kinds of invariants and so forth - 
but who cares? Don't we already trust the core APIs to work
well?  They can add DBC a little bit at a time -- there's
no reason that compiler/VM support means they also have to
immediately change the entire universe to take advantage
of it.

I'd get a lot more value from DBC in my own code, where I
don't have a team of fifty testers working round-the-clock
to make sure it works.  There's absolutely no reason to 
think that it's too late to add it, and unlike most of you
I'm actually glad it hasn't been added yet.  DBC exists in
something like six or seven different third-party tools
right now, and they all do it differently and frankly I feel
that none of them have it quite right.  If six or seven 
different people can do it six or seven different ways,
and I'm not completely happy with any of them, perhaps 
that's an indication that we should let the designs
gel a little while until we can agree on one of them that
"feels right".  Assuming I'm not the only one who feels that
way, at least...

I'm personally a fan of JavaDoc DBC, the way iContract does
it, although I would change the expression syntax of
iContract a bit.  What's everybody else's feeling on the
Right Way to do DBC in Java?


Submitted On 10-JUN-2001
MichaelFranz
An excellent interview (thanks Bill!) and, in particular, some revealing statements from JG on contracts:

http://www.artima.com/java/intv/gosling3b.html#a

Maybe there's hope afterall!


Submitted On 13-JUN-2001
mikedunbar
One thing I came to know is that we may be barking up the 
wrong tree trying to get DBC into the language via an RFE. 
A more direct approach would be through the JCP (Java 
Community Process). Someone can submit a JSR (Java 
Specification Request) and then the executive commity will 
vote to approve or disapprove it. With an RFE, I think SUN 
has to like the idea and then submit a JSR, and then the 
process is the same. So, we have an unnecessary layer. Any 
volunteers to write a JSR! I am sure all the details are at

http://www.jcp.org


Submitted On 29-JUN-2001
MichaelDJames
I disagree with one of the examples used to justify this.

> For example, a method setSSN(String ssn) of our 
> Person class may have the precondition 
> "ssn.length() == 7".

The "setSSN" method shouldn't accept a String
in the first place!  It should accept a datatype
class such as "SocialSecurityNumber."  

The SocialSecurityNumber constructor (which might 
accept a String) should define what constitutes
a valid SocialSecurityNumber and refuse to build
an invalid object.  

That way, any method which declares it accepts a
SocialSecurityNumber can assume it's been validated.

Regardless of the other merits of design by contract,
this particular example can be solved by using strong 
typing properly.


Submitted On 04-JUL-2001
thomas.sievers@gmx.de
I fully agree to this request. The simple assertion 
facility in 1.4 is NOT sufficient to realize a DBC as 
proposed by Meyer. Building large-scale Enterprise 
Application with reusable componants, what we do here at 
the WestLB in Germany (which I do not officialy represent), 
require DBC.


Submitted On 06-JUL-2001
tedbigham
I agree with "MichaelDJames" and was just about to enter 
the exact same comment.


Submitted On 27-JUL-2001
mikedunbar
I also agree with the point that MichaelDJames has made. 
However, I think the example precondition (or something 
similar) and possibly others would still be useful - it 
would just move to the constructor for the 
SocialSecurityNumber class. Then, the precondition for the 
setSSN() method of the example person class might simply 
become something like ssn != null, if we desired such a 
constraint. The whole point is that we a way need to 
express in our interfaces what constraints are required for 
a method to execute properly (precondition), and what 
effect such execution has on the target instance 
(postcondition). It is also desirable that the runtime 
system take on the burden of detecting violations in both 
preconditions and postcondition, freeing the programmer 
from such boring and tedious tasks. Design by Contract is 
one such facility. 


Submitted On 28-AUG-2001
finking
I agree that DBC is extremely useful even without existing 
JFC classes getting contracts. Like constness, it's useful 
for finding bugs in your own code. Sure you'd find more bugs 
if the JFC classes had contracts, but it's far from 
essential.

Currently weighing up which is more important to vote for,
this or enums.


Submitted On 09-OCT-2001
dkf
<not_serious> But you've *got* to allow ssn to be null; how
else will you be able to hire illegal immigrants?
</not_serious>

(BTW, I find examples with SSNs to be highly irritating,
particularly as mine - well, the UK analogue - is nine
characters long and non-numeric.  OK, I see the point of it,
but the use of such an example is just another instance of
code that is very difficult-to-impossible to deal with in an
international context.  At least an SSN class could be made
more aware of the issuing authority, though you have to bear
in mind that people might legally end up with a set of such
unique identifiers, though only one per issuing authority. I
just suppose this shows how hard it is to write good
software in the first place.  :^)


Submitted On 18-OCT-2001
jpschewe
I've been looking for something to do this and I've 
implemented a pre-processor that does it, although it's 
still got a few buts and the compiled code is much slower 
than the original, but it is accurate.  Take a look at 
http://mtu.net/~jpschewe/JonsAssert/index.html


Submitted On 29-JAN-2002
robi
I've voted for DBC in the past, but I'm not sure it makes 
sense to add to Java at this point. In the near term, the 
1.4 assert mechanism plus the established conventions of 
argument checking and JavaDoc achieve many, if not all the 
goals of DBC. Yes I know it doesn't offer everything 
Eiffel does, but it's far better than the average 
practice, which seems to be poorly defined or non-existent 
enforcement of contracts.

Longer term, DBC would probably best be implemented as 
part of Aspect oriented programming. Rather than push for 
DBC now, why not let AOP mature for a couple of years and 
then vote for something even more powerful; aspects in the 
core Java language.


Submitted On 14-MAR-2002
darted
I too think DBC should be lower priority with the third party tools doing it.
IContract, JTest, just to name two major players.  To be honest I can code DBC into the method and 
comment in the JavaDoc without any changes to the language.


Submitted On 17-MAR-2002
phraktle
The simple assertion facilities combined with aspect 
oriented programming (eg. www.aspectj.org) provides pretty 
much everything that's useful in DBC. I'm hereby removing 
my votes for this RFE :)


Submitted On 20-MAR-2002
mlackner
KJC is a Java compiler entirely written in Java which
already enables programming by contract. Method pre- and
postconditions and class and interface invariants can be
used as in Eiffel. Contracts are implicitly strengthened or
weakened in the appropriate way but it requires no changes
of the JVM. The Java class file of the super type is enough
information to use its contract in a subclass. It is very
convenient to use without any limitations of the
portability. KJC is part of the official GNU project Kopi
and is available under www.dms.at/kopi. Information about
the translation of the assertions is available there too.


Submitted On 15-MAY-2002
jaysonjc
This is not required. I wish there is something like vote 
against!


Submitted On 18-MAY-2002
Ixchel
I would like to point out that just because third party 
tools are doing some DBC support doesn't mean that it 
shouldn't be standardized in Java. For instance, a lot of 
DBC support could be implemented as JavaDoc comments, but 
this is terrible if every third party tool supports a 
different syntax for them. At least standardizing the 
syntax (using @pre vs. @require, etc.) should be attempted. 
Otherwise, it becomes nearly impossible to move from using 
one DBC tool to another, and third party libraries cannot 
be shipped with this support built into them, as they would 
need to support ALL tools SIMULTANEOUSLY. Without 
standardization of DBC, we have a "tower of Babel" without 
any tool interoperability possible.
Even if DBC is implemented solely as comments, we need 
there to be a standard!


Submitted On 31-MAY-2002
macchia
I agree to have this capability in java; the market trend 
for component-based software is too much interesting to 
avoid this opportunity for java. It is clear that the pre-
condition and the post condition must be follow the 
inheritance principles. However, it should be avoided 
the "mandatory usage" of pre-conditions and post-
conditions, since the compatibility with existing programs 
must be guaranteed. I would suggest to reccomend the usage 
of the pre-condition and post-condition, since this allow a 
DBC and then a good marketing for the components.
Now a question, since I am new to the process of this  "Bug-
ID Forum": The standardisation should be proposed by us or 
someonelse should take care of this?

Giovanni Macchia


Submitted On 31-MAY-2002
shrink_laureate
(is there a single RFE that somebody doesn't want to vote 
against?)

As people have said, simple pre- and post- conditions can 
be coded and documented without any changes to the 
language.  However, this seems to be missing the point of 
DbC.

I'm far more interested in the ability to check the truth 
of the contract at compile time.  Some of it would be taken 
care of such things as not-null and read-only references, 
if only the RFE for consts could ever be approved.  I'd 
like to add even more, that such conditions as "x > 0" be 
placed in the contract, such that all code using it would 
need to guaruntee this before even being allowed to call 
the method.  The compiler follows the life of a variable 
and knows what the potential ranges in a certain case are, 
in an extension of the way that it checks such things as 
final members now.

This could, I know, get incredibly annoying.  However, if a 
contract is well defined and uses this sparingly it could 
successfully prevent component misuse, even in unexpected 
cases.


Submitted On 26-SEP-2002
alvint
sorry, wrong bug number above; it should be 4748349.


Submitted On 26-SEP-2002
alvint
you may wish to hold off on this until bug 4746786 is
resolved on way or another...


Submitted On 17-JAN-2003
shrink_laureate
4748349 and 4639379 are duplicates of 4222792.  All three 
ask for multiple return types.  Could people voting for either 
of the first two shift their votes please?


Submitted On 04-FEB-2003
kjkj1234
I agree  . . . votes should be shifted.


Submitted On 22-FEB-2003
verdy_p
Can't the jUnit test framework be used as a work around, to 
allow specifying those pre and post conditions in separate 
tests that can be automated to verify that an implementation 
meets the requirements of a DBC design ?
Advantage: won't clutter the implementation with many 
conditions verified at run-time in the released application
Cons: requires a separate development for the test framework.
However there already exists some development environments 
that allow you to specify an interface with its condition, and 
that will build a skeleton for the implementation, and a test 
class for the jUnit project...
jUnit is a great tool, when used correctly, to verify the quality 
of any implementation and meet some desing requirements, 
because those jUnit tests are not blocking. It is also a good 
tool to reproduce past known bugs that have been solved at 
one time, so that there will be no more regression in a 
modified or extended implementation.


Submitted On 24-JUN-2003
jduprez
I feel ashamed to use the recurring threat: "If you don't do
it, .Net will", but it might become true : Microsoft has
already invited DBC-theorist Bertrand Meyer in the .net
bandwagon; and this bright researcher and teacher has
already given quite a few speeches and interviews supporting
.net architecture.

As far as I am concerned, I put predictability and
reliability as the top criterion for software quality.
(I'm cheating a bit, since some other main concerns, such as
features and performance, are reducable to predictability :
 "I guarantee that my software does this provided that...".
Plus, still other main concerns, such as development time
and maintainability, certainly benefit from predictability.)

If either Java or C# offered even partial compile-time
guarantee of semantics, or automated runtime-test
verification of contracts, that would give their respective
architecture a huge push towards predictability/reliability.

If C#/.Net ever stacked up or above Java/J2EE in these terms
of predictability and reliability, then I'd see no
(technical) point to stick to a Java/J2EE paradigm.


Submitted On 26-AUG-2003
finking
Re verdry_p's post, unit testing and DBC complement each 
other, rather than being a substitute for each other. DBC (or 
indeed use of ordinary assertions) makes your unit tests more 
effective. The point about DBC constraints is that they 
*always* apply. The power of them on their own is great, but 
add some decent unit tests which push the boundaries of the 
API and test rare cases and you can start to have a lot of 
confidence in your code.


Submitted On 07-DEC-2003
carstenklein1
In a way I believe that DBC is a way of refactoring
conditional and constraints checks and making them external
to either classes and instances (the invariants) or instance
methods. I personally believe that much of what is requested
here, can be done with AspectJ. Of course, AspectJ
introduces changes to the language in a way not all people
will feal comfortable with, but it can be done. As to
runtime performance, I cannot say, since I didn't have tried
it out yet. And personally, I believe that when DBC is
imposed prior to deployment it should be active for
deployment as well, since it would make no sense in the real
world to switch off conditions and constraints checking to
get faster executables. In a distributed environment with
multiple components contacting services, where those
components do not necessarily come from the same developing
party, it is nearly impossible to have all requirements (pre
and postconditions) met, except through DBC.

But, I don't think that it is a question of language
enforcement or support. I believe that it can be done
externally without requiring SUN to work over the complete
Java APIs. Instead, when doing it externally, you will have
a given set of classes you will use from the Java APIs, so
then you could do wrappers which would support the notions
imposed by DBC. Or, more simplier, use AspectJ for the
purpose of pre and postcondition checking.

A word on ...net, since one of the former posters has had
the courage to mention it here. personally I don't believe
that it is worth to mention this C# Java clone thingy in
this forum, since we all know what happened to MS
technologies in the past, most of them faded away, causing
great changes in requirements on the developers trying to
hunt after the new technologies, which then, as soon as
people were capable of adopting them, faded away, to be
replaced by something newer...I, for one, does not like
these changes imposed to me, requiring me to adopt old
software written in the past to the new technologies because
some company cannot stay compatible to its own technologies
and standards...

What SUN did with the generics was a very tough and well
done job. They are backwards-compatible in that old code
remains functioning and they open up new worlds to discover.

And I think, that they could do it the same way with DBC, if
they had the notion of ever trying to implement it. But it
is not an absolute necessary requirement. Using strong
typing (XML based , schema aware datatypes would do) and
perhaps AspectJ for the other aspects of the DBC will surely
complement each other  for the benefit of having DBC and
would not require any new paradigma for the Java programming
language.

Just my 2 cents...


Submitted On 12-FEB-2004
gberche
Wouldn't the new availability of the JDK 1.5 Metadata 
facility a good opportunity to reevaluate introduction of 
design by contract in Java.  When I see 
java.lang.annotation.overrides it really looks like its 
beginning. 

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Overri
des.html

I hope we can get close to something like that pretty 
soon!


Submitted On 17-FEB-2004
cowwoc
Adding design-by-contract into Java at this point should be
very cheap!

Simply modify the compiler (no need to modify the runtime)
to insert assert() statements automatically in order to
simulate pre-conditions, post-conditions and class invarients.


Submitted On 25-MAR-2004
jduprez
to carstenklein1 again:
Thinking about it, admittedly, AOP could also be used to 3)
handle assertions that are common in several methods'
contracts, enabling e.g. to simply refer to an aspect
NotNegative  in several methods' contracts, and implementing
NotNegative as an aspect.

Other points are open to debate though, see  you in the
forums!...


Submitted On 25-MAR-2004
jduprez
Reply to carstenklein1:
- about .Net : I am by no means a supporter of Microsoft's
practice. I am just pragmatically observing that if .Net
enabled to create more reliable apps, this would be a
technical superiority, and there would be good technical
reasons to move to .Net. I'm not saying there wouldn't be
other reasons (economical,political,...) not to move! Just
that it'd be sad that .Net proved superior to Java/J2EE...
- about AOP : as far as I know it, AOP enables to factor out
of the main source code concerns that are either/both
redundant in various classes and methods, or/and orthogonal
to the business logic, enabling to keep methods focused on
business logic, and keep hardly-related aspects separate.
It is very different from DBC where the contract is an
inherent part of each method or class. A vast part of the
contracts can't really be factored out of the methods (maybe
class invariants), and even though, you wouldn't want to
externalize them, as it is important for maintainance to
keep the contract specs next to the method body.
Where aspects could be involved would be:
1) for class invariants, verified before/after each method
invocation
2) as an implementation means to verify pre and post at runtime

In all cases this is an implementation choice, I don't see
where it helps in terms of specifying contracts.
Plus, it helps only for the runtime part of DbC
(theoretically the only one supported). This doesn't help
static analysis.

Reply to gberche:
Yes, Metadata can enable to formally express contracts at
the syntactic level, and keep some form available in the
compiled .class files. But this provides no semantics,
people and tools still need to agree on a standard semantics
of contracts and what to do with them.

To everyone : I encourage you to discuss the topic on one of
the JDC's forums (e.g. "OO Design and Patterns"), instead of
here, where the form is both cumbersome and inapropriate.



Submitted On 27-APR-2004
glauco_vinicius
With JSR 175 we can extend the language to include 
invariant expressions for classes and modules, and 
pre- and post-condition expressions for functions and 
methods. With this Java will support 'Design by 
Contract', beyond "a simple assertion facility". This can 
be a better workaround. 


Submitted On 22-JUL-2004
chrisNorthBear
An implementation of DbC based on AspectJ and xdoclet is available on http://barter.sourceforge.net. It's outdated and inactive, but it may be a good starting point.

I'm pretty sure if we could update it and wrap it as plugins for the major IDEs it would make it!


Submitted On 10-AUG-2004
kbarthel
Everything has already been said.


Submitted On 22-AUG-2004
musheno
This can be achived via assertains, on every method that has impact, not handled dynamicly, follow the full contract, and you'll get it, dont be too lazy.


Submitted On 23-AUG-2004
daniel7
> Submitted On 07-JUN-2001
enicholas

> Sure, you wouldn't want to retrofit ten thousand classes in 
> the core API to have all kinds of invariants and so forth - 
> but who cares? Don't we already trust the core APIs to 
> work well? 

Maybe, but they're not documented as precisely as sometimes needed.



Submitted On 23-AUG-2004
daniel7
> Submitted On 31-MAY-2002
shrink_laureate

> I'd like to add even more, that such conditions as "x > 0" 
> be placed in the contract, such that all code using it would
> need to guaruntee this before even being allowed to call 
> the method.  

Yes, having subtypes (e.g., range restrictions) as in Pascal, 
Ada, VHDL, and W3C XML Schema would be nice.



Submitted On 25-AUG-2004
caseyhelbling
I would argue the that the contract you need to code to are the testcases.  Constructing software and constructing circuits or bridges are completely different things and should be treated as such.


Submitted On 28-SEP-2004
lindsayP
This feature would really put Java in a new league. We struggled for more than a year with iContract before its inadequate implementation forced us to drop it - but we still define our pre/post/invariants as it's very effective code documentation, even if the contracts can't be executed at the moment, and we live in hope.... 


Submitted On 07-NOV-2004
sgcjr
DBC people: just write code test-first.  The tests are the expectations and define the contracts.  No need to futz with the language (or use AOP).


Submitted On 30-NOV-2004
carstenklein1
@sgcjr

It is not necessarily about DbC and assertions in general, it is about decomposition and moving such code that, as in XML Schema and schema type facets, can be applied to classes that pre-existed to what we develop in the future, just the same as AOP is about. Write a class and introduce pre- and post-conditions later on. This is about re-use of existing and yet to be developed classes and of decomposition of logic that would otherwise be directly implemented into some class of which' you are not the owner. But, as jduprez put it, we should discuss this topic in some of the forums, presumable the oo design and patterns, hope to see you all there ;-)  


Submitted On 02-MAR-2005
micrond
Now that third party tool (like iContract) are out of business or not maintained, those who want to use Design By Contract in Java are really out of luck. Like all of those I follow this RFE with much greater interest. I hope it will be done right (not like JDK 1.4 assert) and soon (we wait for this since August 1997 when the original 4071460 RFE  was first posted but never really fixed). 

After the great work in Java 5.0, Sun proved that major enhancements can be added to the Java Language while maintaining compatibility. Here is another great opportunity to repeat the exploit !


Submitted On 06-APR-2005
gnovos
couldn't you just use AspectJ to build in this stuff for you without a "core" language rewrite?


Submitted On 02-JUN-2005
abies
It would be quite hard to get invariants/postconditions done correctly with AspectJ. While preconditions could be argued to be placed in separate file, as a kind of external contract documentation, probably postconditions and for sure invariants fit only inside the class you are checking. You mainly use invariants to doublecheck constraints given by your specific implementation - it doesn't really fit to be placed in another file.

AspectJ compiler/runtime could certainly be used as a seed for DBC framework - most of tools to get it working are already there. But I don't think that you can just easily map AspetcJ constructs to DBC 1 to 1 in elegant way.


Submitted On 29-AUG-2005
micrond
Some news.

I tried to setup a project to implement DbC in Java on java.net.  We gather representants of all the main DbC implementation for Java. However, peoples at Sun Microsystems clairly indicate that they have NO INTENTION to implement design by contract in Java. The more than 500 votes for this 4449383 request seams to mean nothing for them.

The dbc.dev.java.net project has since been closed. No idea what to think of this. 


Submitted On 21-OCT-2005
alternative language (JVM based - and interoperable with java) which does provide DBC (with inheritance, etc) and not-null classes (+ other goodies) is Nice ( see http://nice.sf.net ).


Submitted On 06-DEC-2005
Antonielly
The support for Design by Contract in the language itself would be a VERY WELCOME feature for Java! I am anxiously looking forward to see it in the next versions of the language.
Of course, there is the backward compatibility requirement. My suggestion is that classes developed prior to Java X (where X is the number of the version where DbC will finally appear) will have by default the precondition = true and the postcondition = true. This would probably be a good initial step to ensure backwards compatibility.


Submitted On 12-JAN-2006
kaffiene
I wonder if fully-fleged DBC wouldn't add quite a lot of complexity to a languages which has already become increasingly complex?



Submitted On 20-JAN-2006
With regards to the issues surrounding weakening and
strengthening pre- and post-conditions in the presence of a
class/ interface hierarchy, let me point out that Eiffel and all
of the 3rd-party DBC tools for Java get this wrong.

The short version of the story is that they implicitly assume the
code written by the programmer properly respects the
class/interface hierarchy without actually checking it.

To really check contracts properly in a language like java, the
contract checker must watch for 3 kinds of violations:
pre-condition violations, post-condition violations (as before),
and hierarchy violations, ie a subclass whose pre-condition is
not weaker than its superclass's, or a subclass whose
post-condition is not stronger than its superclass.

I've written more about this in OOPSLA & FSE, here are the
relevant links:

http://www.ccs.neu.edu/scheme/pubs/#oopsla01-ff
http://www.ccs.neu.edu/scheme/pubs/#fse01-flf


Submitted On 04-APR-2006
astroivan
The inclusion of metaprogramming in the Java language has pretty much guaranteed that this RFE will be done now anyway, except it will be done a million times over, by different people in different ways.

I think it might be time to revisit this RFE, post Dolphin.


Submitted On 01-JUN-2006
jhan2092
How about a new evaluation?
(1) The last one was done 3.5 years ago; (2) this is #3 RFE.
It is okay to say Sun still thinks the same, but it should be updated. 


Submitted On 19-JUN-2006
micrond
A lot of work has been done in recent years on program validation. I agree that a new evaluation is needed by Sun. Especially as this RFE is now #2. Difficult to say you listen if nothing is done at this point over the "In progress, request for enhancement" which has been their since version 1.3. Come on Sun... Work at the JML team is promising altough still too complexe for mainstream on my point of view. But, it's still something that works were Sun may starts. 


Submitted On 29-JUN-2006
narfT
At MIT, this functionality was present in CLU, 25 years ago.  See Guttag and Liskov's book.  There is no reason not to support this.  Backwards compatibility is a non-issue, just like all the new stuff that came with 1.5.  Done well, it's strictly a compiler issue, the VM need not change.
 


Submitted On 02-JUL-2006
fbrueg
The combination of an annotation-based syntax and the use of AspectJ's load time weaving capability as found in Contract4J seems to be a reasonable workaround at this point (no impact on the build process as with precompilers etc.), although inheritance support is not complete (yet). See http://www.contract4j.org/contract4j (I have no relation to the project or author).


Submitted On 22-JUL-2006
Voted for DBC. I only hope that the full DBC is implemented not such ill-fated versions like the assert. A main feature of DBC is that it announces publicly what contract is required. The assert is a hidden non-public features (and not inherited) unless you can and do read the source code. Hence any mention of assert in one breath with DBC completely misunderstands & misrepresents DBC.

I am wary of using annotations to implement it; I'd prefer proper language support as done for threads and the like.

Summary: DBC in all its Eiffel glory. It's possible, long considered and time to get into active development.


Submitted On 25-JUL-2006
cadrian
#2 in Top25 RFE's and still not implemented?! DbC is CAPITAL for proper software development.

That's a pity that despite having so many libraries and real cool things, Java cannot be my favorite language because of the lack of DbC.

SmartEiffel is.


Submitted On 21-AUG-2006
lfschuck
A must! I see no good enough reason to let this out...


Submitted On 24-FEB-2007
Jodeleit
Now it's the top RFE (2007-02-24), marked as "In progress" and still nothing happend. jsr-305 resigned to do anything in the direction of DBC saying "it's out-of-scope". What a shme for java, the jcp, and sun!


Submitted On 02-APR-2007
jamesdcarroll
Sounds great as long as its simple and optional. If its not both, then don't do it.


Submitted On 16-MAY-2007
javierbds
Well, maybe this can get some "reactive" traction (Spec# mentioned in blogs ...)
http://blogs.msdn.com/progressive_development/archive/2007/05/15/motley-says-contracts-do-me-no-good-at-run-time.aspx


Submitted On 27-FEB-2008
People in need for DBC facilities should really take a closer look at JML:

http://www.cs.ucf.edu/~leavens/JML/

I worked with JML a couple years ago, and back then it didn't support Java 5, which I thought was a let down. Personally, I don't feel that DBC should be built into the Java language. It is only really useful for domains with high safety or security requirements where the additional time and effort required to spec everything in the source code is reasonable.

Other than that, unit testing frameworks should do just fine.


Submitted On 10-MAY-2008
DWilches
I would also like to see this feature in Java's core. I've used the design by contract approach for a while in my Computers Science Master, using JML, and I've found that it simplifies the debugging of the program, and decreases the need to make test cases for yourself, as there are tools that, based on the contract of the methods/classes, executes automatic tests.
I also think that this is one feature that will start kicking C# out.


Submitted On 10-MAY-2008
DWilches
I think that this is a feature that will satisfy the needs of many of the JUnit users, because we could run automated tests on the classes based solely on its contract.



PLEASE NOTE: JDK6 is formerly known as Project Mustang