32

I am reading the book Java Concurrency in Practice and getting a little bit confused with these terms:

  1. Pre condition
  2. Post condition
  3. Invariants

Can someone please explain me them (with an example, if it's possible)?

MarianD
  • 9,720
  • 8
  • 27
  • 44
Inquisitive
  • 6,637
  • 13
  • 46
  • 56
  • with an inclination to help you post more proper questions on SO , please ask specific questions , something that shows your own research/work into the subject, adding value to your question. Things which you can find discussed on internet in general as such do not make good questions on SO. PS : havent downvoted you myself. – Bhaskar Jul 04 '12 at 15:42
  • 10
    That's a bit harsh... – yshavit Jul 04 '12 at 16:16
  • 8
    How is the question ambiguous? He wanted clarification on what those terms mean with a code example. And he showed research because he's reading the darn book. Sometimes SO just grinds my gears. Ugh. – Ungeheuer Apr 06 '17 at 05:43
  • Also Assume when Unit Test and Given in BDD are examples of real world use of pre-conditions, and Assert & BDD Then clauses are examples of post-conditions. – Martin Spamer Mar 25 '19 at 19:34

1 Answers1

58

You'll have a lot of problems writing Java, especially multi-threaded code, if you can't understand these simple ideas:

  1. Pre-conditions are the things that must be true before a method is called. The method tells clients "this is what I expect from you".
  2. Post-conditions are the things that must be true after the method is complete. The method tells clients "this is what I promise to do for you".
  3. Invariants are the things that are always true and won't change. The method tells clients "if this was true before you called me, I promise it'll still be true when I'm done".

They're all part of an idea called "programming by contract". It was invented by a guy named C.A.R. Hoare. Bertrand Meyer built an object oriented language called Eiffel around it. No one uses it much, but he had a day in the sun because of it.

Eiffel isn't very popular. There are over four million questions on SO as I write this, but only 32 of them are tagged "eiffel".

Update: There were 11,966,392 question on SO on 29-Jun-2016. Only 92 of them were tagged "eiffel". The percentage of Eiffel questions is staying roughly constant at ~0.00077%.

I stand corrected - thank you, flamingpenguin. I've updated my answer.

duffymo
  • 293,097
  • 41
  • 348
  • 541
  • 1
    http://en.wikipedia.org/wiki/Hoare_logic – lexicalscope Dec 04 '12 at 11:43
  • So, when I'm writing a method with certain pre-conditions, would I check to see if those pre-conditions are satisfied, or am I to assume that the client is smart enough to not violate the pre-condition? – Ungeheuer Apr 06 '17 at 05:46
  • Your choice, but the whole idea is to validate and prevent errors. Ask yourself how consumers will know your contract. – duffymo Apr 06 '17 at 07:26