Slashdot Mirror


Google Brings Design-By-Contract To Java

angry tapir writes "Google is developing a set of extensions for Java that should aid in better securing Java programs against buffer overflow attacks. Google has announced that it open sourced a project that its engineers were working on to add a new functionality into Java called Contracts, or Design-By-Contract. 'Contracts exist to check for programmer error, not for user error or environment failures. Any difference between execution with and without runtime contract checking (apart from performance) is by definition a bug. Contracts must never have side effects.'"

134 comments

  1. Finally! by goofy183 · · Score: 2

    There have been several projects that have tried to do this before but the developers never saw it through. When annotations were added in JDK5 this was one of the features I've been looking for. Being able to define invariants on the interface will make implementations much more safe and consistent!

    1. Re:Finally! by mark-t · · Score: 1, Insightful

      I'm probably digressing OT here, but my own main beef with annotations in Java is that they don't actually serve any real functional purpose that I've ever been able to see beyond documentation, while at the same time they break compatibility with older Java compilers which are unable to compile any source code with annotations in it. The exact same effect could have been achieved by having the annotations be embedded in comments, similar to Javadoc, and would not have broken source compatibility.

    2. Re:Finally! by The+Snowman · · Score: 3, Insightful

      I'm probably digressing OT here, but my own main beef with annotations in Java is that they don't actually serve any real functional purpose that I've ever been able to see beyond documentation, while at the same time they break compatibility with older Java compilers which are unable to compile any source code with annotations in it

      Considering annotations are in Java 5, and Java 5 is no longer supported by Sun/Oracle, I don't really care about Java 4 and earlier compilers.

      Annotations can have great benefits in running code, but you need to use reflection. For example, the product I develop at my job uses them for technical designs. We use a custom annotation to mark up classes that are not yet implemented, so we can design a process flow and actually run through it in the application before it is implemented. A factory pattern class replaces these classes with a generic, configurable replacement on the fly. Often, the most difficult part of the process is defining it, not implementing it. This alone has saved us hundreds if not thousands of hours of time fixing bugs and definitely fewer builds into QA.

      --
      24 beers in a case, 24 hours in a day. Coincidence? I think not!
    3. Re:Finally! by Bj�rn · · Score: 1

      Annotations are used extensively in enterprise Java at runtime.

      --
      Never express yourself more clearly than you are able to think. --Niels Bohr
    4. Re:Finally! by Bitmanhome · · Score: 1

      On the contrary, annotations are entirely functional, not decorative. Annotations cannot be in comments; while the code would compile, it wouldn't run correctly (if at all) since the behaviors requested by the annotations would be missing. Look into JAXB and EJB for how annotations can be used well.

      --
      Not that this wasn't entirely predictable.
    5. Re:Finally! by Anonymous Coward · · Score: 1

      Anotations have plenty of purposes... I use them so I don't have to deal with the metadata XML hell that used to be j2ee... Can you say EJB resource injection without having to look at two separate files at the same time? It makes reading the code a lot easier because you don't have to switch what you're looking at all the time to make sense of it. I know this is a "holy war" type thing, but honestly, annotations have made my life a lot easier because now I don't have to maintain tons of XML files on top of my sourcecode... And to get involved in a new project, I don't have to constantly refer back and forth between several different files.

    6. Re:Finally! by Anonymous Coward · · Score: 0

      Annotations can have great benefits in running code, but you need to use reflection.

      That's not entirely true, though reflection is by far the easiest way to access annotations. But you can also use the Mirror API to write code that integrates into the compilation process using the apt.

      Unfortunately, Sun made the Mirror API as painful and confusing as possible and the apt tool is pretty clumsy, so reflection is the more typical route.

  2. BOf in Java? by Lord+Ender · · Score: 2, Insightful

    I did not realize buffer overflows were a problem for apps written in Java. Java has built-in "generic" dynamic data structures which should be suitable for 99% of the software any of us write. Why would we ever be manually managing memory in Java? Doing so should be "considered harmful" to a far greater degree than goto statements.

    --
    A slashdotter who didn't build his own computer is like a Jedi who didn't build his own lightsaber.
    1. Re:BOf in Java? by goofy183 · · Score: 5, Informative

      I think that is a poorly written summary. You can't (in pure java and ignoring JVM bugs) overflow buffers. You can however forget to do sanity checking on inputs based on the business rules of your app. That is where this will help. Codifying even simple things like "The argument should never be null" in an annotation on the interface definition helps both document and consistency for implementations of that interface.

    2. Re:BOf in Java? by nicholas22 · · Score: 1

      They're not. It's the usual un-edited crap in the summary. You cannot possibly do a buffer overflow in the traditional sense of the word in Java. You can in C#.

    3. Re:BOf in Java? by Johnny+Fusion · · Score: 2
      If you took time to read TFA you may have come across this little tidbit.

      "One of the oldest techniques in the attacker's virtual arsenal, buffer overflows remain a problem. In December, Microsoft identified 2.6 million possible attacks that could be waged using a stack-based buffer overflow in the JRE (Java Runtime Engine)".

      --
      There are two kinds of fool. One says, This is old, and therefore good. And one says, This is new, and therefore better.
    4. Re:BOf in Java? by mswhippingboy · · Score: 2

      I did not realize buffer overflows were a problem for apps written in Java.

      In general, they're not. However, there have been a few bugs in the JRE found over the years that resulted in stack buffer overflows which could have led to an exploit . AFAIK, all of these know bugs have long been fixed. However, there is always the potential that a new bug could be found.

      DBC is not about managing memory for Java, it's simply a tool (using annotations) to allow validation (think ASSERTs) of arguments to methods and the values the methods return.

      --
      Sometimes the light at the end of the tunnel is the headlight of an oncoming train.
    5. Re:BOf in Java? by Anonymous Coward · · Score: 0

      Codifying even simple things like "The argument should never be null" in an annotation on the interface definition helps both document and consistency for implementations of that interface.

      Not to mention increase readability/maintainability by reducing boilerplate code

    6. Re:BOf in Java? by Anonymous Coward · · Score: 0

      If you took time to read TFA you may have come across this little tidbit.

      "One of the oldest techniques in the attacker's virtual arsenal, buffer overflows remain a problem. In December, Microsoft identified 2.6 million possible attacks that could be waged using a stack-based buffer overflow in the JRE (Java Runtime Engine)".

      So, they ran a static analysis and reported the raw number of potential issues in the JRE... let me tell you how many there are in the actual windows source code: just about the same amount, in each depot (there are about 14 depots)...

    7. Re:BOf in Java? by medv4380 · · Score: 2

      It's not a poorly written summary. TFA actually mentions that the reason for implementing this is to address the Buffer Overflow attacks that have been used against the JRE. Even though google is well meaning in what they are doing I don't think they understand where the problem is at. Most of the buffer overflow attacks were targeting the JRE and that only has a small set of code written in java. The vast majority of the JRE is written in C and C++. Adding Design by Contract standards to Java won't fix those buffer overflow issues. They'd have to add it to C++ and implement it on the whole JRE and that would be a massive rewrite. It might fix things but adding it to Java only will fix things like when a programmer fails to do sanity checks of user input.

    8. Re:BOf in Java? by blueg3 · · Score: 0

      One of the major sources of security bugs in Java is that the Java standard libraries are primarily native code. The native code is rife with buffer overflows, unchecked pointers, and other vulnerabilities.

    9. Re:BOf in Java? by goofy183 · · Score: 4, Informative

      The problem is TechWorld having no idea what this tool is for. The announcement by Google http://google-opensource.blogspot.com/2011/02/contracts-for-java.html never mentions the word "buffer" and accurately describes this as a tool for pre/post validation of method arguments and return values. Some how TechWorld decided to tie in JVM level buffer overflow issues with a pure Java DbC tool, anyone actually familiar with Java knows at a glance that the two are unrelated.

    10. Re:BOf in Java? by owlstead · · Score: 1

      Yes, and if you dig any further you find out that it is a Java *deployment* issue which exploits features of the underlying operating system. Funny enough, only Windows is affected, who would have guessed? And since nobody in his right mind is going to use Design By Contract for deployers, you can safely ignore the buffer overflow argument used in the article. Pure FUD.

    11. Re:BOf in Java? by owlstead · · Score: 1

      They didn't, they listed the guessed number of actual attacks against (Windows) machines. Finding 2.6 million possible vulnerabilities in the JVM after running code analysis, now that *would* make an interesting Slashdot headline.

    12. Re:BOf in Java? by owlstead · · Score: 2

      The Java standard libraries are *primarily* native code? WTF have you been smoking? You can tell the moderators are not very knowledgeable either.

      If somebody could post the percentage of C/C++ code in the Java RE, please do because we need to get rid of FUD like this.

    13. Re:BOf in Java? by hey! · · Score: 1

      Well, bugs in a particular JRE aside, is your system *exclusively* implemented in Java? You don't, say, save the data to a database that isn't 100% Java, or anything like that? That said, it seems to me that buffer overflow is a relatively minor issue. In any case, if you read TFA, you'll see that contracts aren't about input checking, which should be done in UI code.

      It sounds to me like DbC makes an interesting complement to unit testing. One of the hollow feelings I always feel in the pit of my stomach when I write a unit test is how dang *specific* unit tests are. It'd be nice to be able to say, "I haven't given any thought to values outside this range so make sure you're only using values in this range."

      It also seems to me that this could be a nice safety net for when people try weird and wonderful things to eke out a little more performance, like caching or reusing objects, or having factory methods that return a singleton. Often these strategies are poorly implemented, or have side effects that aren't well thought out. So you might say that a method that returns a connection to some external software service ensures the connection TO be open and NOT TO BE in some kind of error state. You'd just toss that annotation in without much advance thought, because in *your* version of the routine it just won't happen. Later when some genius modifies the method to roll his own connection pooling scheme, the annotation will catch the problem of service connections returned in an inconsistent state to the previously non-existent and still not visible pool. Gosh, I've run across that kind of thing more than once.

      --
      Post may contain irony: discontinue use if experiencing mood swings, nausea or elevated blood pressure.
    14. Re:BOf in Java? by dna_(c)(tm)(r) · · Score: 1

      Funny thing is that since 2002 (Java 1.4) the assertion mechanism is a standard language feature - and intended for Design by Contract

      And so the reinvented wheels of redundancy keep on turning and repeating themselves over and over again, but at least we can now assert that they were turning, will be turning and didn't stop turning in several ways...

    15. Re:BOf in Java? by Anonymous Coward · · Score: 1

      quick basic line count of openjdk 6:

      1328021 lines in .c/.h/.cpp/.hpp files (this is _both_ windows and linux vms)
      4091401 lines in .java files

    16. Re:BOf in Java? by Speare · · Score: 1

      When I heard of Designing by Contract, I recalled a similar public speaking maxim. The maxim goes, "Tell them what youâ(TM)re going to say. Say it. Then tell them what you said." The idea is that reinforcing and rephrasing things will get your point across more clearly to the audience.

      Designing by contract is something seen in the Eiffel language. I haven't looked at it in years, but it seems to follow this maxim religiously. Every function or method had three sections: tell the compiler what you are going to do, do it, then tell the testing apparatus what you did. The grammar was different in each section.

      While I can give high marks for the idea, it really struck me as a huge expense of time and initiative to paraphrase every bit of code into three variations of the same thing. You write functions/methods/modules expressly to avoid code duplication, but apparently they think this kind of code duplication is different somehow. Cumbersome. Cumbersome is the word that comes to mind when I think of designing by contract.

      --
      [ .sig file not found ]
    17. Re:BOf in Java? by nicholas22 · · Score: 3, Informative

      Sorry but you're completely wrong. Java libraries are primarily written in Java you wally.

    18. Re:BOf in Java? by gorzek · · Score: 1

      This seems like the sort of design paradigm that would be useful in situations where you cannot afford any defects. Having to write the same code 3 different ways (or rather, write it 2 ways then write a test to verify it) at least permits automated consistency-checking without having to involve other people.

      Sure, the time spent writing more code isn't free, however this can reduce time spent testing (by QAs), and might obviate code review by peers since the code already "reviews" itself.

      One of the issues I commonly run into is code that doesn't do what was intended. The developer meant for it to work a certain way, but the code as implemented works slightly (or even markedly) differently. Even worse, there's often no documentation so you can't be sure what the developer intended.

      This paradigm, if not completely eliminating the above problem, sounds as though it can go a long way toward addressing it. Even in the absence of documentation, the pre/post validation would tell you a lot about how the program is expected to function.

      That said, I haven't done any design-by-contract, it just sounds very intriguing despite the additional coding it requires.

    19. Re:BOf in Java? by GooberToo · · Score: 1

      accurately describes this as a tool for pre/post validation of method arguments and return values

      Now that makes more sense.

      As a side note, Python is able to do this by means of decorators and now with annotations in Python 3. Here's some example code.

    20. Re:BOf in Java? by sproketboy · · Score: 2

      MOD PARENT DOWN. Retard most of Java is written in Java.

    21. Re:BOf in Java? by Anonymous Coward · · Score: 0

      I did a 5-minute check, I found 123 classes of 7209 with some native functions. Not sure about actual LOC but definitely native code is the minority.

    22. Re:BOf in Java? by Anonymous Coward · · Score: 0

      AWT, the printing subsystem, parts of NIO and networking contain some native code to interop with the underlying OS. But to say the standard libraries are "primarily" native code is far from the truth. They are primarily pure Java, with native code where necessary to interop with the underlying OS.

    23. Re:BOf in Java? by Anonymous Coward · · Score: 0

      in unsafe code only, which is not a typical practice

    24. Re:BOf in Java? by Anonymous Coward · · Score: 0

      I'm a moderator, you insensitive clod!

    25. Re:BOf in Java? by pla · · Score: 1

      You cannot possibly do a buffer overflow in the traditional sense of the word in Java.

      Ahahahahaahhaa...

      Heh.

      <snrrrrk>

      You Java guys. Always cracking me up. "But it runs in more places"... Than GCC used to compile the JRE? "But you can't overflow buffers"... Not within the language (why would you want to compromise a sandbox?), but via the implementation (thus giving "real" access outside the sandbox).

    26. Re:BOf in Java? by nicholas22 · · Score: 1

      I'm not a Java guy you insensitive clod.

  3. Trademarked by D+Ninja · · Score: 4, Interesting

    Actually, Google is bringing Programming by Contract to Java. Design by Contract is trademarked by Eiffel Software (and Bertrand Meyer).

    1. Re:Trademarked by nicholas22 · · Score: 1

      This only applies to the US. The rest of the world can use that moniker. This is because the trademark only applies there. Sorry.

    2. Re:Trademarked by FranTaylor · · Score: 1

      Holy moly what a crappy trademark. It will fail the moment it is challenged. That term has been in common use for many many years. That's not a trademark, it's bad lawyering work.

    3. Re:Trademarked by H0p313ss · · Score: 1

      Prime example of why Eiffel has failed to catch on in the mainstream.

      --
      XML is a known as a key material required to create SMD: Software of Mass Destruction
    4. Re:Trademarked by a_n_d_e_r_s · · Score: 1

      That programming language is 25 years old now so of course its catch phrase have been used for a long time.

      --
      Just saying it like it are.
    5. Re:Trademarked by Anonymous Coward · · Score: 0

      So they haven't maintained their trademark... gp's post is moot.

    6. Re:Trademarked by trollertron3000 · · Score: 2

      Well that should work out well. We'll just call it that everywhere else and make sure no one in the US ever sees it..

      --
      Tiger Blooded Bi-Winning Machine
    7. Re:Trademarked by nicholas22 · · Score: 1

      Stop trolling.

    8. Re:Trademarked by abigor · · Score: 1

      Google is a US company. Sorry.

    9. Re:Trademarked by trollertron3000 · · Score: 1

      Well I did say it in jest it's truthful. It would be tricky naming it two different things. I just call it programming by contract because that's probably more accurate anyway.

      --
      Tiger Blooded Bi-Winning Machine
    10. Re:Trademarked by Anonymous Coward · · Score: 0

      Don't worry, I am in the US and this is probably the last time I will see this.

      (kidding)

    11. Re:Trademarked by Anonymous Coward · · Score: 0

      Primarily because most substandard programmers don't like to be bothered with thinking out interfaces in advance. Global variables, sloppy parameter signatures, and the like, are the stock-in-trade of most software developers. Unfortunately.

    12. Re:Trademarked by H0p313ss · · Score: 1

      I Wes referring to their marketing strategy which seems to be designed to discourage attracting developers.

      --
      XML is a known as a key material required to create SMD: Software of Mass Destruction
    13. Re:Trademarked by shutdown+-p+now · · Score: 1

      Eiffel has failed to catch on because of the steadfast belief of Mr. Meyer that his "software development methodology" is the sole right and proper one, and everyone who disagrees is an idiot. If you've read some papers from the man, they can largely be summed up as "This is how we do things in Eiffel; it's the right way, and Java (C++, ...) are very bad languages that no-one should use because they don't do it like that".

  4. Good news by metamatic · · Score: 1

    I'm sure Oracle will be only too happy to work with Google to add this to the JDK, right? Right?

    --
    GCHQ Quantum Insert installed. If only our tongues were made of glass, how much more careful we would be when we speak
  5. Fail by nicholas22 · · Score: 5, Insightful

    It is a String-based implementation, which is awful in terms of consistency, type-checking, etc. and vulnerable in code refactoring. I would stay away or use something more type-safe and IDE-safe.

    1. Re:Fail by worip · · Score: 1

      I agree, does this not rely on the developer actually specifying the contract? Also, would it not be possible to have bugs in the contract itself?

      --
      A picture is worth exactly 1024 words.
    2. Re:Fail by Anonymous Coward · · Score: 0

      An IDE operates on matching tokens in character-string-based code. I suspect that the content within the Contract annotations being String-based is an implementation artifact that will be a surmountable obstacle for plugin writers.

    3. Re:Fail by Anonymous Coward · · Score: 0

      With an annotation processor, you could make it type-safe and IDE-safe...

    4. Re:Fail by Anonymous Coward · · Score: 0

      E.g. c4j.sourceforge.net defines contracts in java code in a non-intrusive manner.

    5. Re:Fail by sproketboy · · Score: 0

      Modded down? Fucken google fanbois.

    6. Re:Fail by noidentity · · Score: 1

      I agree, does this not rely on the developer actually specifying the contract? Also, would it not be possible to have bugs in the contract itself?

      What would it mean to have a bug in the contract?

    7. Re:Fail by p3d0 · · Score: 1

      Contracts can easily have bugs. That shouldn't be too hard to imagine. You could easily have a postcondition "ensure item[index] == 123" when "index" is out of bounds, or when you meant to write "0x123", or when the array is actually called "items".

      The fact that contracts can have bugs doesn't negate their value any more than the same fact about software negates software's value.

      --
      Patrick Doyle
      I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
    8. Re:Fail by Anonymous Coward · · Score: 0

      I would stay away or use something more type-safe and IDE-safe.

      And because the parent fails to point out alternative solutions (for Java), let me. A good project for Java design by contract would be the Java Modeling Language (JML) produced by Gary Leavens.

    9. Re:Fail by Anonymous Coward · · Score: 0

      Actually there is a standard way to provide validation and even auto-completion of annotation values with Annotation Processors, though I don't think google provides one.

      Anyway, It is much more convenient to write conditions in assert().

    10. Re:Fail by El_Muerte_TDS · · Score: 1

      Nah... stringly-typed languages are perfectly safe.

  6. Pattent problems? by Anonymous Coward · · Score: 0

    By the way, Eiffel already pattented "design by contract". Therefore, it cannot be open sourced.

    1. Re:Pattent problems? by FranTaylor · · Score: 1

      WTF are you talking about? Design contracts have been around since the 70's at least. Come on can't you do any research at all before you post?

    2. Re:Pattent problems? by bunratty · · Score: 1

      No. Eiffel Software trademarked the term Design by Contract. Therefore, whatever scheme you come up with to do something similar, you cannot call it by the same name. You can do exactly what Eiffel does as long as you call it by a different name, such as Programming by Contract. Trademarks protect names. Patents protect inventions.

      --
      What a fool believes, he sees, no wise man has the power to reason away.
    3. Re:Pattent problems? by AvitarX · · Score: 1

      Um, patented things can be open source for certain.

      Section 7 clearly states that it is an issue if you are asked to stop, but not before (though says it is up to you to try it, and not intended to induce infringement).

      Section 8 clearly states you can limit distribution to where patents do not apply and still be compliant.

      GPL V2

      --
      Wow, sent an e-mail as suggested when clicking on "use classic" banner, and got a fast response that addressed my msg
  7. Too fragile by lehphyro · · Score: 3, Interesting

    Using strings instead of compiled code is too fragile. org.apache.commons.lang.Validate or com.google.common.base.Preconditions are much better for this kind of validation.

    1. Re:Too fragile by robmv · · Score: 1

      They are written using a the annotation syntax, they look like a String, but using the annotations processor of the Java 6 compiler that string is compiled to Java bytecode, and by the way, what is code? Strings... from the FAQ

      Is the contract code compiled? I only see strings in annotations!

      The annotation processor takes care of compiling the strings into bytecode and runs along the Java compiler, so you get static syntax and typing errors at compile time, as usual.

    2. Re:Too fragile by lehphyro · · Score: 1

      But you don't get IDE auto-completion and syntax coloring.

    3. Re:Too fragile by robmv · · Score: 1

      Until plugins are developed, and on Eclipse is not that hard, the compiler infrastructure is accessible to plugins developers, but right now without any plugin you get error notifications is you setup the annotation processor

    4. Re:Too fragile by Anonymous Coward · · Score: 0

      Erm, that sounds like a pretty simple IDE change to add support.

    5. Re:Too fragile by Anonymous Coward · · Score: 0

      Is the contract code compiled? I only see strings in annotations!

      The annotation processor takes care of compiling the strings into bytecode and runs along the Java compiler, so you get static syntax and typing errors at compile time, as usual.

      Perhaps, but the IDE won't be able to give you errors immediately. This requires a full compile of the source file to generate errors, which is a lot more fragile than if they avoided using strings and went with a more concrete syntax (like that used in Validate).

    6. Re:Too fragile by Anonymous Coward · · Score: 0

      Actually, Eclipse can do that. See the linked guide from the project page.

  8. Java finally gets assert(3) by Anonymous Coward · · Score: 0

    Is what this sounds like to me. I've always felt an important part of strong C programming was to put a set of asserts at the top of each function that asserts the properties of the function's input (numeric ranges, non-NULL pointers where applicable, etc). Again, not for user input validation, but for validating software design assumptions that make up the contractual interface between caller and callee.

    1. Re:Java finally gets assert(3) by VGPowerlord · · Score: 1

      Yup, because Java didn't have assert before!

      --
      GLaDOS for President 2016! "Well here we are again. It's always such a pleasure." -- GLaDOS, 2011
    2. Re:Java finally gets assert(3) by bunratty · · Score: 1

      Assert detects errors a runtime. Java has had those for years. Design by Contract finds errors at compile time.

      --
      What a fool believes, he sees, no wise man has the power to reason away.
    3. Re:Java finally gets assert(3) by Anonymous Coward · · Score: 0

      If you've been working with this type of system, what percentage of these types of errors are detectable at compile time as compared with run-time? I assert conditions on method/function arguments and run unit tests, and am having trouble thinking of any particular examples in my own work where a compile time check would have caught something before it was caught by unit tests. I think delineating exactly what the method's assumptions are is important, and have no particular objection to the idea in general, but am wondering what practical impact it would have compared with existing working methods. (I wrote Java full time for six years but have been doing Obj-C for the past three. I'm not the GP.)

    4. Re:Java finally gets assert(3) by Nadaka · · Score: 1

      How are you going to detect passing an invalid parameter to a function at compile time?

      You would have to know every place a method is called and every value being passed in.

      1: public members can be called from code you never compile.

      2: You need to be able to know the value of all the objects used as parameters at the time they are called. These values can not be determined explicitly in many cases.

      3: java has strong reflection abilities and run time injection that are used in many libraries that throw an even bigger wrench into the process.

    5. Re:Java finally gets assert(3) by Stevecrox · · Score: 1

      For compile time checking your better off using static code analysis, Coverity is very good at finding reverse/forward null/memory leak problems. Findbugs is good for finding some of these issues as well because it looks at the code from a byte code perspective.

      Personally I use, coverity, findbugs & pmd and don't use things like assert because assert relies on the coder actually knowing what to do and doing it and these tools can be loaded into the IDE. They don't catch everything but they do find 99% of the obvious stuff.

      One of the things which did stun me was running Tomcat 6.0.18 through Coverity it found 529 defects, about 180 were parameter checking ones. I've been tempted to join an open source project and spend my time resolving these kinds of bugs.

  9. Java does not have buffer overflows by naasking · · Score: 1

    Java does not have buffer overflows unless the JVM has a bug, or you're calling out to unsafe code via JNI. The lack of such memory errors is the very definition of memory safety.

    1. Re:Java does not have buffer overflows by FranTaylor · · Score: 1

      You didn't read the article did you? This has nothing to do with buffer overruns.

    2. Re:Java does not have buffer overflows by Anonymous Coward · · Score: 0

      What article are you reading? First paragraph:

      Google is developing a set of extensions for Java that should aid in better securing Java programs against buffer overflow attacks.

      Fourth paragraph:

      Primarily touted as a technique to ease programming, Contracts could also provide an easy way for developers to guard against buffer overflow attacks, the researchers said.

      Fifth paragraph:

      One of the oldest techniques in the attacker's virtual arsenal, buffer overflows remain a problem.

      Seems like it has everything to do with buffer overflows.

  10. Back to the 80's! by FranTaylor · · Score: 1

    The software engineering group at MIT (Liskov, Guttag, etc) have been pushing for this since the early 1980s. Guttag told us in lecture that he tried unsuccessfully to get these concepts built into the Ada specification.

    1. Re:Back to the 80's! by microbox · · Score: 2

      D has had contracts since the get-go. Sometimes I wonder if it would be a better world if all the C and C++ out there was *magically* reimplemented into a better language.

      --

      Like all pain, suffering is a signal that something isn't right
    2. Re:Back to the 80's! by wbhauck · · Score: 2

      There's a subset of Ada called SPARK that has these concepts.

      SPARK (Programming Language)

    3. Re:Back to the 80's! by Anonymous Coward · · Score: 0

      I think Bertrand Meyer was the originator of the idea, or at least the first to realize it in the form of a production-ready programming language. Google "Eiffel programming language".

    4. Re:Back to the 80's! by FranTaylor · · Score: 1

      google "6.170" and you will find that the work at MIT predates eiffel by many years.

    5. Re:Back to the 80's! by subanark · · Score: 0

      The problem with D and similar languages is that programmers are too clever for their own good. D doesn't enforce checking, and is only safer than C if you don't use a good chunk of its extra features. All it takes is one library that wanted to make a shortcut and ends up being faulty for the entire application to not work correctly. C# has the best middle of the road approach where you can use unsafe code, but using it anywhere in your project will require you enable the unsafe code switch, so at least you can be sure that your code is unsafe clean pretty easily.

    6. Re:Back to the 80's! by shutdown+-p+now · · Score: 1

      Yup, .NET has also only got contracts last year (in the standard library; third-party solutions existed earlier), which is a shame. Well, better late than never. Between it being part of .NET core distribution, and backed by a player as big as Google in Java land, let's hope this becomes mainstream soon.

  11. Another one? by quivrnglps · · Score: 4, Informative

    According to Wikipedia there are already quite a few projects doing DbC:

    Java, via iContract2, Contract4J, jContractor, Jcontract, C4J, CodePro Analytix, STclass, Jass preprocessor, OVal with AspectJ, Java Modeling Language (JML), SpringContracts for the Spring framework, or Modern Jass, Custos using AspectJ,JavaDbC using AspectJ, JavaTESK using extension of Java.

    Do we really need an entirely new one? If none of those are sufficient, why not build on top of and improve an existing project? Starting over is not always a good thing...

    1. Re:Another one? by VGPowerlord · · Score: 1

      Do we really need an entirely new one? If none of those are sufficient, why not build on top of and improve an existing project? Starting over is not always a good thing...

      Have you tried reading the links in the summary?

      Contracts for Java is based on Modern Jass by Johannes Rieken.

      -- Google's announcement article, which was the second link in the summary

      --
      GLaDOS for President 2016! "Well here we are again. It's always such a pleasure." -- GLaDOS, 2011
    2. Re:Another one? by Anonymous Coward · · Score: 0

      Google suffers from "not invented here" syndrome

    3. Re:Another one? by Anonymous Coward · · Score: 0

      That's exactly what they are doing idiot.

    4. Re:Another one? by Espressor · · Score: 1
      Still, what's new here? What value has Google added to that existing OSS project - other than marketing power and visibility? Looking at the Google project's FAQ:

      Is this framework related to 'ModernJass' from Sourceforge.net?

      Yes, Cofoja is a significant rewrite of ModernJass. We worked closely with the original author of ModernJass (Johannes Rieken) on this.

      OK...then why not contributing to the OSS project instead of phagocyting it and re-branding it into another Google product? I guess I'm answering my own question here...

      Has anyone found more details? For instance, Modern Jass does not support JML. Is Google going to support it? If not, why didn't they create their own work to implement it?

      I'm just saying, until proof to the contrary, this really feels like Google is trying to make geeks' headlines while bringing nothing new or groundbreaking to the table.

  12. No side-effects AT ALL?! by snowgirl · · Score: 1

    Isn't throwing an error a side-effect?

    --
    WARNING! This girl exceeds the MAXIMUM SAFE standards established by the FDA for BRATTINESS
    1. Re:No side-effects AT ALL?! by FranTaylor · · Score: 1

      Well if you program correctly you will never have to worry about that, will you?

      This is the ENTIRE IDEA.

    2. Re:No side-effects AT ALL?! by pz · · Score: 3, Insightful

      Isn't throwing an error a side-effect?

      No, because it does not mutate a value, but only changes the control flow.

      I wish I had more time to explain in detail, but that isn't going to happen today, unfortunately. Side-effect in this context is a highly specific term that means, essentially, to change the value of a variable through assignment.

      --

      Put my fist through my alarm clock with its ding-dong death inside my ear. - The Blackjacks.
    3. Re:No side-effects AT ALL?! by noidentity · · Score: 1

      If the contract is violated, the program should be terminated immediately. The point is that there are no side-effects when the contracts are observed.

    4. Re:No side-effects AT ALL?! by snowgirl · · Score: 1

      Isn't throwing an error a side-effect?

      No, because it does not mutate a value, but only changes the control flow.

      I wish I had more time to explain in detail, but that isn't going to happen today, unfortunately. Side-effect in this context is a highly specific term that means, essentially, to change the value of a variable through assignment.

      No, the first sentence was sufficient. I am a CS guru. Just previously vague definitions need clarification.

      --
      WARNING! This girl exceeds the MAXIMUM SAFE standards established by the FDA for BRATTINESS
  13. Bah runtime by subanark · · Score: 2

    I'm still waiting for a decent compile time DbC. Runtime checks won't catch an untested control flow, and when the fault does happen you better hope it happens in your lab and not on a client's computer. You can read my analysis of this in my Master's thesis (which focused on unique references that were ensured to be unique at compile time):
    http://www.worldcat.org/title/applying-uniqueness-to-the-java-language/oclc/701244184&referer=brief_results

    1. Re:Bah runtime by FranTaylor · · Score: 1

      So you need to profile your code too! What else is new? This is a tool, not a panacea.

    2. Re:Bah runtime by subanark · · Score: 1

      I'm not sure I follow you. Profiling typically refers to determining places in your code that run slow. A static checker would ensure that there is no set of inputs that would violate the contract, and it would produce errors when you compile your code informing you that some condition may not always hold. For example, in Java if all code paths do not assign a local variable before it is referenced, you will get a compiler error.

    3. Re:Bah runtime by Coryoth · · Score: 1

      You'll want to look into JML and ESC/Java2 which supplies DbC syntax and static checking via theorem provers. It's been around for quite some time and is fairly powerful.

  14. That's the INTENDED effect by fnj · · Score: 1

    It's not a side effect, it's the INTENDED effect.

    Isn't throwing an error a side-effect?

    1. Re:That's the INTENDED effect by Anonymous Coward · · Score: 0

      It's not a side effect, it's the INTENDED effect.

      Isn't throwing an error a side-effect?

      An expression has a side effect, in computer science, if its evaluation changes global state. It has nothing to do with the intent of the expression; this isn't like the side effect of a drug.

      That said, throwing an error isn't normally considered a side effect.

      If you think about it, even evaluating a pure expression affects global state: the runtime is going to mark that the expression was evaluated and that control can now move to the next expression.

      Throwing an error does basically the same thing: the expression is marked as evaluated and control simply moves to an exception handler instead of the next expression.

      If an error message is printed, which is a side effect, that's happening when the exception was caught, which isn't really part of evaluating the exception throwing expression.

    2. Re:That's the INTENDED effect by snowgirl · · Score: 1

      If an error message is printed, which is a side effect, that's happening when the exception was caught, which isn't really part of evaluating the exception throwing expression.

      I think by using levels of abstractions, the idea that it's the exception handling is what has the side-effect rather than the exception thrower misses the point that the exception thrower is still proximally the cause of the side-effect.

      --
      WARNING! This girl exceeds the MAXIMUM SAFE standards established by the FDA for BRATTINESS
  15. It's just syntactic sugar anyway by FranTaylor · · Score: 1

    You can do all of this range checking yourself manually in your code if you want, there is nothing new here.

    These annotations just do the dirty work of pumping out the boilerplate code. You could do it yourself with an emacs macro or some such.

    1. Re:It's just syntactic sugar anyway by noidentity · · Score: 1

      It's all syntactic sugar. The point is to reduce the cost of development. Contracts should be distinct from implementations; a user should be able to consult the contract in order to find his obligations when calling a routine. By optionally checking contracts at run-time, you can be reasonably confident that they are actually being followed.

    2. Re:It's just syntactic sugar anyway by subanark · · Score: 1

      These provide more expressiveness than a typical macro can provide. They also extract the check from your code, so if you find a bug or need to refactor the checking code, you don't need to go though every place you inserted the biolerplate code and change it.

    3. Re:It's just syntactic sugar anyway by p3d0 · · Score: 2

      Actually Design by Contract is a design discipline, not a bunch of error checks. It's a bit like programming without gotos: the benefit comes not from avoiding typing "goto" into your source code, but rather from the style of reasoning you use when you learn the proper alternatives.

      --
      Patrick Doyle
      I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
    4. Re:It's just syntactic sugar anyway by Anonymous Coward · · Score: 0

      I'd rather see the advantage here in the fact that the code invariants are better documented this way --plus you'll get errors if they're ever violated. Bear in mind that reading (and understanding) existing code is by far the most common task programmers will have to perform, so I don't think that it is just sugar. Whether or not to use google's lib or another mechanism --that's another question.

  16. Source code in strings? Really? by Anonymous Coward · · Score: 1


    @Requires({
            "Collections.isSorted(left)",
            "Collections.isSorted(right)"
    })
    @Ensures({
            "Collections.containsSame(result, Lists.concatenate(left, right))",
            "Collections.isSorted(result)"
    })
    List merge(List left, List right);

    Seriously, let's just toss out the whole idea of syntax checking or anything. I could put these into individual asserts and they would be hilighted by my IDE and checked by my compiler, and with a simple //REQUIRES or //ENSURES comment, it would be no less obvious to the reader. Now real DBC also involves checking things like class invariants and making sure that preconditions never narrow and postconditions never expand, but I know Google's little hack doesn't do class invariants, so I kind of doubt it does the latter two either.

    Google has some great Java code -- guava is probably the best collections library out there, for instance -- but this sad little hack is not it.

  17. Give me a paper bag, I'm aboUT TO BLAAARRGH! by elsurexiste · · Score: 1

    I've seen that contract thing being used on a project. It was gruesome, and needless most of the time. I had to remove all the contract enforcements just to understand the underlying code. I guess I'm allowed to be a skeptic on this technique.

    tl;dr Contracts suck.

    --
    I rarely respond to comments. Also, don't ask for clarifications: a brain and Google are faster, believe me!
    1. Re:Give me a paper bag, I'm aboUT TO BLAAARRGH! by Anonymous Coward · · Score: 0

      Does that say more about contracts or you?

    2. Re:Give me a paper bag, I'm aboUT TO BLAAARRGH! by subanark · · Score: 1

      The contract itself is not part of the code. You can understand the code simply by ignoring all the comments (or having your IDE collapse them). However, you will need to understand the contract system if you want to modify the code, as otherwise you can end up violating them with any changes you make.

      Yes, the contracts adds complexity to the language, which is a primary reason that C's preprocessor directives were not included as part of Java.

  18. bury button by Anonymous Coward · · Score: 0

    Where's the bury button? Oh yeah - shitdot doesn't have one.

  19. It would mean the contract has been poorly written by Anonymous Coward · · Score: 1

    A bug in a contract is like a bug in a specification - it might be harmless but it means you are allowing potentially dangerous/poorly working implementations to be given the rubber stamp of approval.

    Contracts are effectively ways of saying "the state of the program before this operation will adhere to rules P" and "after you do this operation I promise that the state of the program will adhere to rules R". Sometimes it is possible to check whether the rules would be broken using a static checker (weeding out certain problems at compile time). Some properties can only be checked at runtime (and thus a runtime exception is thrown giving a better clue as to where the problem lies when it blows up). Contracts are tools to help programmers write correct programs to be written and like a bad test suite, bad contracts won't help you all that much in achieving that.

  20. Re:It would mean the contract has been poorly writ by noidentity · · Score: 2

    The idea of contracts is that clients write their code to work with anything which fulfills the contract. So let's say you have some client code written, but then determine that there's a bug in the contract. What does this mean? The client code is either written for the "buggy" contract, or the client code was ALSO buggy and written for the intended contract. At that point, it seems that the client has failed to grasp what the contract is in the first place. The idea is that the contract cannot be buggy, since it is the definition of correct. If your clients code to the contract, you can't go changing it without breaking clients. The contract may be badly-designed, and it's good to avoid bad designs, but once you have clients, to go in and try to fix a "buggy" contract is to water down what contracts mean in the first place. It encourages clients to ignore contracts and code to what they imagine the routine should do. At that point, you might as well abandon contracts because they aren't being used as the definition of what is correct anymore, just a vague guide as to what the routine might do.

  21. About time... by david.emery · · Score: 1

    Eiffel and Ada have had 'design by contract' as a key language feature for 25+ years, and this is a major contribution to both 'safety' and correctness of design. It's good to see Java catch up.

    1. Re:About time... by shutdown+-p+now · · Score: 1

      Eiffel safety has been broken due to the language fragrant violation of Liskov Substitution Principle by allowing argument covariance on method overrides in derived classes, and by treating all generic types as covariant in all their type parameters - a hole in the type system big enough for a train to ride through.

      Don't get me wrong, DbC is a wonderful idea. It's a pity that it has been tied to the horrible language that is Eiffel for too long - it deserved better.

  22. Re:It would mean the contract has been poorly writ by p3d0 · · Score: 1

    The "definition of correct" is the system working the way it should. I'm not sure what you're suggesting here: that a system should stick with the original, possibly flawed, contracts rather than fix them to operate properly? That once you make an error in a contract, you should live with it forever? I fail to see how that perspective is helpful or realistic, and, forgive me if I'm wrong, but I suspect you may be lacking in practical experience with Design by Contract.

    --
    Patrick Doyle
    I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
  23. DEC did a good one by Animats · · Score: 2

    One of the best ones was the DEC Extended Static Checker for Java in the late 1990s. That project died after Compaq acquired DEC and shut down research. But it formed part of Microsoft's efforts for Spec#, which has a formal verification system.

    Microsoft has had a huge success with formal proof of correctness - the Static Driver Verifier. This is a system which tries to formally prove that a Windows driver can't crash the operating system. All drivers for Windows 7 have to pass this verifier to be signed, It's an impressive system which works by symbolic case analysis. It yields a proof, a counterexample, or times out analyzing too many cases. About 3% of programs time out. (If your kernel driver has undecidable behavior, it needs work.)

    I headed a team that did a proof of correctness system for Pascal back in the early 1980s. That was pushing the limits of what you could do back then; verifying a small program took 45 minutes on a 1 MIPS VAX. Today, with about four orders of magnitude more CPU power, it's a practical technology.

    There have been many attempts to bolt some "design by contract" features onto various languages, but they're usually not very good. The problem is saying things about collections. The hacks that try to do design by contract at run time tend to avoid expressions which examine big data structures, since they have to run them over the whole data structure every time. Real verifiers prove or disprove such things at compile time. It turns out, though, that a few standard cases for collections cover many of the usual things you want to say.

    Another big issue, which Spec# handles and this Google hack apparently doesn't, is the "insideness" issue for object invariants. Object invariants are supposed to be true whenever control enters and exits an object. But what if an object calls one of its own public methods, perhaps through a long chain of calls? Now, control is inside the same object twice. That violates the invariant rule.

    This class of bugs is common in window systems, where all the widget, pane, window, and event objects are frantically calling each other. It also comes up in concurrency, which I don't see Google's hack addressing either.

    1. Re:DEC did a good one by Coryoth · · Score: 1

      One of the best ones was the DEC Extended Static Checker for Java in the late 1990s. That project died after Compaq acquired DEC and shut down research. But it formed part of Microsoft's efforts for Spec#, which has a formal verification system.

      ESC/Java lives on as ESC/Java2 which uses the JML language for annotation. This makes it significantlymore powerful than ESC/Java since you also get the entire JML toolchain as well. ESC/Java2 also has excellent IDE support via Eclipse plugins now. If you like that sort of thing it is well worth looking into.

    2. Re:DEC did a good one by Espressor · · Score: 1

      The hacks that try to do design by contract at run time tend to avoid expressions which examine big data structures, since they have to run them over the whole data structure every time. Real verifiers prove or disprove such things at compile time. It turns out, though, that a few standard cases for collections cover many of the usual things you want to say.

      Very good point, and the irony is that the Google blog uses collections in one of their examples.

      The Google project is based on a library called Modern Jass. I'm not familiar with it since the last time I did research on DbC was in 1999/2000 when the only DbC tool for Java that existed might have been Reto Kramer's iContract. Yet, to call it a hack...is it purely because of this absence of static analysis you mention? BTW what kind of static analysis is implemented in Eiffel?

      As for concurrency, I agree this would need to be addressed as well. There was an interesting article about a decade ago in JavaWorld about how preconditions would sometimes need to be turned into guard conditions. Anyway, I don't know if any of the many DbC tools for Java address this, but after so long I would hope at least one does.

  24. I don't understand what's important about this by EuclideanSilence · · Score: 1

    Does it really require a language extension to throw a runtime error whenever a boolean is met with false? Or is the amazing part that google has found a way to make java even more verbose? I didn't think it could be done.

    1. Re:I don't understand what's important about this by Anonymous Coward · · Score: 0

      Does it really require a language extension to throw a runtime error whenever a boolean is met with false?

      Or is the amazing part that google has found a way to make java even more verbose? I didn't think it could be done.

      The reason that it is important is that given an interface, you can force inject assertions to every implementation of that interface. That is what this is useful for. It is not useful for anything else. Meaning, one source of errors is that implementations of interfaces done by different programmers, don't necessarily contain a consistent set of input validations accross all implementations. This is an attempt to fix that. Useful I say.

    2. Re:I don't understand what's important about this by shutdown+-p+now · · Score: 1

      Contracts are supposed to be part of the public interface, whereas the usual "if (fail) throw ..." code resides in the midst of implementation. You want method contracts to actually appear in your public Javadocs, for example. So it makes sense to make them distinct from normal error checking logic.

  25. out of the API's and into the Java language by Anonymous Coward · · Score: 0

    Securing Java programs against buffer overflow attack implies never to use unbounded strings in code everywhere.
    In order to enforce this, it would be important to have some compile-time mechanisms in the language.
    In Ada, the strength is the deliberate compile-time definition of the range boundaries for the acceptable values. At compile time, many checks are done, but certain types(i.e. unbounded string) and their related services aren't easily compiled unless you are deliberately aware they are being used and are wrapped with all sorts of protection functions to allow the compiler to proceed. At run-time, if the creation/assignment of a particular type is being done, there are inherent range-boundary constraint-checks for the assigned values.

    In Java, similar concepts may be achieved by making Classes/Types which have boundary checking in the constructor functions and in the assignment functions/assignment operator functions which throw exceptions when input values are not valid. That should be adequate. Contracts are may be deliberate descriptions, but in order for it to be more useful, it should be part of the language and not built as an external api for the java language or a precompiler tool for the language. Ada got it right and like you said it's been around for over 25 years. But java language maintainers are listening because they have brought in Ada-like generics, Ada-like enumeration types, and c++ templates into the new versions of the language. The fact that there are different existing apis using different vocabulary and dancing around the same "Design by contract for java" concepts is the subtlety to listen to. If the language designers listen to this, they might admit the java language spec is in some respects still immature in terms of code maintenance stability. It wouldn't surprise me to see in upcoming Java language releases they bring in new Ada-like concurrency, constraint/boundary checking and Eiffel-like Design-by-Contract(i.e. make it difficult to compile with unbounded strings) into the Java Language also.

  26. Misleading article by Anonymous Coward · · Score: 0

    This is one of the most ignorant articles I have read in a while. Some priceless quotes:

    "Primarily touted as a technique to ease programming, Contracts could also provide an easy way for developers to guard against buffer overflow attacks, the researchers said."

    Really?! I'd love to see you explain that one to me. There is no way to guard against buffer overflow attacks in Java because you don't have low-level access to memory in the language, hence you don't need to do any guarding.

    "In December, Microsoft identified 2.6 million possible attacks that could be waged using a stack-based buffer overflow in the JRE (Java Runtime Engine)."

    Actually, no. What Microsoft said was that 2.6 million attacks took advantage of JRE flaws involves buffer overflows, not that there were 2.6 million possibly vulnerabilities in the JRE. There were in fact only 3 and they were patched months ago.

    My 2 cents: I love the idea behind design by contract but sticks code in String annotations is just plain ugly. I'd rather stuck to Asserts, thank you very much.

  27. Re:It would mean the contract has been poorly writ by noidentity · · Score: 1

    Guilty as charged. Still, my point was that in the case you describe, there is a problem with the design of the system, not merely the contract.

  28. About time by Mark+Atwood · · Score: 1

    I was learning Eiffel and had been coding in Ada for a couple of years when Java showed up. I was surprised then that Sun's language designers had given us a language that was already 15 years behind the state of the practice, let alone 30 years behind the state of the art.

  29. contracts./.treaties.again. by Anonymous Coward · · Score: 0

    human seldom subscribes/stick to contracts or stuff like that.
    for performance trade-off..even it's only compile-time.
    and how can human make error-nil contracts?..
    they even can't write code..let alone the checking stuff.
    pls contracts the contracts..ohoh..dead-loop'n'recursive

  30. .Net Contracts are Better! by Kane+Devaid · · Score: 2

    Or you could use the .Net Code Contracts which do all this with static analysis. Therefore you get proof up front that your contracts will never be violated by non exposed code, and without a performance penalty at run time. If a contract cannot be verified, warnings are given. You can then introduce appropriate branching to provide guarantees as necessary. http://research.microsoft.com/en-us/projects/contracts/

  31. Re:It would mean the contract has been poorly writ by p3d0 · · Score: 1

    Ah I see what you mean now. Actually I think you've hit upon the key feature of Design by Contract that most people miss. It's not just tossing assertions all over your code. It's a design discipline that shapes the way you write the system, and that's why it's good at finding design problems.

    --
    Patrick Doyle
    I mod down every jackass who puts his moderation policy in his sig. Oh, wait a sec....
  32. Re:Source code in strings? Really? by Anonymous Coward · · Score: 0

    In fact it does do class invariants, and inheritance with preconditions that never narrow and postconditions that never expand.

    You can also use Eclipse's as-you-type compilation to get instant syntax checking.

    Perhaps you should actually look at the project before you criticize :)