java design by contract - java

Why
1) you can test postconditions with assertions in both public and non public methods
but, you are advised to
2) not use assertions to check the parameters of a public method(preconditions)?
I understand that 2) is caused by :
- convention: the method guarantees that it will always enforce the argument checks(e.g. with checked exceptions) so it must check its arguments whether or not the assertions are enabled.
- the assert construct does not throw an exception of the specified type. It can throw only an AssertionError, which is not quite user friendly
But I don't understand why 1) is available for public methods as well ?
Thanks.
The above questioned rephrased :)
A contract is made of two parts :
- requirements upon the caller made by the class
- promises made by the class to the caller
Why Sun advises you to not use assertions as preconditions for public methods because the assertions could be disabled and then you are not checking the requirements imposed on the caller, but allows you to use assertions to test postconditions for public methods(test the return value to see you are returning a correct result) is still an enigma for me.
Put in other words, you must be very careful when enforcing requirements, but you can close an eye when verifying the promises.
Is there a technical reason for this metaphorically called "lack of ethics" that you demostrate when you enforce your client to respect the requirements, but you are not so harsh with yourself in respecting the promises ? :)

Point 2) states you shouldn't use assertions because they might not be turned on. Instead, it appears to recommend using checks which are performed every time and throw a checked exception.
If you want to throw different exceptions when assertions are enabled you can do
boolean assertions = false;
assert assertions = true;
if (assertions && myCheckHere) throw new MyExceptionOrError();
Technically, a method has parameters e.g. String name, a method is invoked passing arguments e.g. "Hello", So its the argument you want to check, the compiler will check the parameters.

You are using "assert" keyword to assert your assumptions and in case of public methods the pre-conditions should be always true (so that the method has correct data to perform its task) whether running in production or not.
Since assert will be disabled in production you can't use the assert keyword to enforce the pre-conditions of a public method so you should be throwing a unchecked exception. Now, coming to the post-conditions there is no such contract for the method (say f1) performing the task. The output of this f1() method might be a input to another method (say f2), in which case the pre-conditions in f2() might enforce the assumptions.
On a side note, I suggest looking at the google-guava library's Preconditions class for checking pre-conditions and throwing unchecked exceptions, both using a simple and intuitive API.

Not sure where you got this information, but assertions are excellent for checking the parameters of public methods. They enforce the very contract that the method claims to live up to.

It's not a technical reason but a reflection of the fact that asserts aren't a design by contract implementation, which is something they say in the guide.
On balance, we came to the conclusion that a simple boolean assertion
facility was a fairly straight-forward solution and far less risky.
Not everyone sees things the way that Meyers does, and Java has language goals which conflict with Eiffel's in some places. In Program Development in Java, Liskov stresses defensive programming, that is, if something can go wrong, contract-related or not, you check for it as you go. Contracts are "asserted" in comments that go at the top of the method body. Now, that book predates the addition of boolean asserts to Java, and who knows what they would have said if it had been written a couple of years later. My point is that
more than one treatment of contracts exists
asserts are primitive and probably best used where they're practical, instead of trying to do real DbC with them
As you noted, the designers suggest that you could do some DbC with postconditions, nonpublic preconditions, occasional invariant checks, but they don't sound all that serious about it. Is it unethical? I understand the objection, but it's not a given that everyone will want to program with contracts in the first place.

Java assertions are worthless, in my opinion.
If you read Meyer's "Object-Oriented Software Construction", he makes the case about how assertions should always be enabled - especially for production code. So, if they were always enabled by default, no matter what, it would be much better. Maybe I'm niggling with that fact a bit too much, but it's definitely a detriment - a static method is "safer" since you know it will always execute... and you can still control that with a system property. thus the default is always 'safe mode'.
DbC - It seems kind of like it would be hard to fit into the Java language - we can't put preconditions/postconditions on an interface and have them automatically work on any implementation. There are some frameworks that attempt to provide this behavior, but I haven't managed to use them in any of my projects.
I instead write my own "Contract" class full of static methods, and use a lot of assertions throughout the production code. It has methods called 'precondition' and 'postcondition', but really all you care about is assert(). there is no mechanism in Java's design whereby you can implement 'pre' and 'post' hooks on an inheritor's code. that's why some of the frameworks out there use a precompiler or AOP...

Related

How can I mark a method as discouraged in java?

I'm programming a Config class that reads a file and provides config parameters as a Map.
Parameters can be accessed by conf.get("LogLevel") or conf.getLogLevel().
The first function just reads from the map and returns the value (that can be null or invalid) while the second function converts the value to a LogLevel and returns a default value when no valid value is given.
Therefore I want to discourage Programmers from using the genereral get(), but there are special cases where this method is useful so I cant just make it protected.
Right now I use #Deprecated but I dont think this is a good solution because it is only ment for methods that will be removed in the future. (Correct me if I'm wrong there, thats what SonarLint told me about the #Deprecated annotation)
/**
* #Deprecated When possible, use the key-specific getter instead
*/
public String get(String key) {
return values.get(key);
}
public int getLogLevel() {
return Log.getLogLevel(values.get(LOG_LEVEL), Log.getLogLevel(defaultValues.get(LOG_LEVEL)));
}
Well, if #Deprecated is not the solution, you are left with only one option. Put message that notes that the usage is "discouraged" (except for the special cases) into the javadocs ... and hope that people are going to read the javadocs.
Defining your own custom annotation will not help because you can't get your users to use an annotation processor that will recognize it.
Likewise, you can't do it via custom rules for FindBugs, PMD, Sonar and so forth because that requires your users to customize their installations of those products.
(Though ... if this is an in-house product and all of your users use a common CI server ... you could possibly do the checks in the CI server. It depends if you can define custom rules that can reliably distinguish the general "discouraged" use-cases from the special cases. This will also entail convincing your co-workers that this is a good idea.)
In my opinion, the #Deprecated tag would be better than all of the above. For the special cases, encourage people to judiciously add #SuppressWarning("deprecation") in the cases where the usage is necessary.
I don't think this is a good solution because it is only meant for methods that will be removed in the future.
This is incorrect. Possible future removal is only one of the example reasons for deprecation listed in the #Deprecated javadoc (Java 11 version). Other reasons listed there are:
"the tagged element's usage is likely to lead to errors",
"it may be changed incompatibly [...] in a future version",
"it has been superseded by a newer, usually preferable alternative", or
"it is obsolete".
Note that these are listed as example reasons ... which means that you could deprecate for other reasons.
This is also consistent with the older "when to deprecate" guidance here.
IMO, your "discouraged" scenario is covered by that.
If you arrived here and looking for android solution there's #Discouraged annotation in androidx

Why doesn't Delayed provide a default method for compareTo?

The interface Delayed requires any
implementation of this interface [to] define a compareTo method that provides an ordering consistent with its getDelay method.
However I'm wondering, why there isn't a default implementation in Java 8, as compareTo is required by contract to depend solely on getDelay.
Is there a specific reason why this is left for the implementing class? Or is it impossible to create a default method when overwriting a super interface?
Edit: To make my question more understandable, here is an example:
interface Delayed extends Comparable<Delayed> {
long getDelay(TimeUnit unit);
#Override
default int compareTo(Delayed o) {
// might not be the perfect "compareTo" implementation, but you get the point
return o == this? 0:
Long.compare(this.getDelay(TimeUnit.NANOSECONDS), o.getDelay(TimeUnit.NANOSECONDS);
}
}
The simple answer is that Delayed exists since 1.5 and default methods exist since 1.8. So in order to provide the compareTo method as default method, the interface has to be deliberately changed.
If that doesn’t happen, there are several possible reasons:
It might be that simply no-one ever considered it
It might have been considered but dropped because either:
There might be possible compatibility issues
The expected benefits are not high enough to justify an API change
There were things with higher priority to do before the release
To me, it doesn’t look like a high-priority issue. Most of the time you encounter Delayed implementations in the context of ScheduledExecutorServices provided by the JRE and these implementations already exist and therefore won’t benefit from such a change.
I don’t think that you will encounter custom Delayed implementations in application code very often, but even if you see it different, the JRE developers obviously decided to focus on additions whose usefulness is more obvious (or less debatable).
Thinking about it, incorporating the discussion about the getDelay() contract combined with the Comparable contract, it would have been better, if Delayed never extended Comparable at all. After all, it’s not hard to sort objects by a property using a Comparator or similar design pattern.

Would a Mandatory<T> be a useful addition alongside Guava's Optional<T>?

I was looking at Guava's Optional class and its justification, and I wondered whether a similar class to fail-fast when representing values that must not be null would be helpful. I can't find any discussion of this idea so I thought I'd ask here.
My first attempt would try to stay in the style used by Guava, a Mandatory<T>, exposing a static factory of(T t). This method throws NullPointerException if called with a null argument.
My particular interest is nailing down the semantics of interface methods in respect of null handling. I think that whether to accept null arguments or not is a design decision that should be specifiable in the interface so that client code can be designed accordingly and can avoid duplicating precondition checking logic. As such, an interface using this class might have methods like
fire(Mandatory<Employee> employee);
and a client might call
fire(Mandatory.of(unfortunateEmployee));
I suspect that the Mandatory type would be quite easy to find using aspects and the like to hook in further checks before invocation if it was absolutely vital that such marked method arguments should not be null.
I've also considered annotation-based approaches such as fire(#NotNull Employee employee) but the implementations I've seen require additional wiring up of validators.
So, the questions... does this idea exist anywhere already? If not, have I missed something obvious that undermines it? Or a better idea to achieve this?
fire(Mandatory<Employee> employee);
If you had a method with this signature, you could still call fire(null); it'd just be that you'd have a null of type Mandatory<Employee> instead of type Employee. You haven't actually improved safety at all; you've just added a redundant layer of wrapping.
If you want to enforce that a parameter is required, good practice is to use e.g. Preconditions.checkNotNull as the first thing in your method to immediately throw a NullPointerException if the value is null.
adding a Mandatory.of method that throws NPE
Using your T variable will already throw a NullPointerException, so what's the point?
How to specify that a parameter is required as part of the contract?
Javadoc has been used for this for a long time.
Yeah, but I want to enforce it.
You have too much time on your hands. That aside...
#NotNull is the "new way". You can use AOP to wire not-null validation automatically for the desired methods. Here are a couple of great implementations:
http://blog.solidcraft.eu/2010/09/getting-rid-of-null-parameters-with.html
http://janistoolbox.typepad.com/blog/2009/12/aopvalidationnotnull.html

Homegrown utility methods

Static utility methods are generally frowned up by OO purists.
I was wondering however what people feel about utility methods that are used to avoid something simple like a null check throughout the application.
String.trim() throws a NPE when invoked on a null String. So I have to do:
if(str!=null)
setValue(str.trim());
else
setValue("");
What if I create a utility method that checks for the null?
setValue(myTrim(str));
public static String myTrim(String str) {
if(str==null) return ""
else return str.trim();
}
The one problem I have encountered with methods like these is that some developers on the team might not like/not know this utility and might be doing staight calls after doing a null comparison.
Is this something that you do your framework too? If yes, what are the other common utility general use methods that people have created and are using in their applications?
What do you feel are the pros and cons of either approach?
I'd be inclined to replace the homegrown uses when an existing library (like Apache Commons Blah Blah Blah) already has written it. Code you can offload to someone else lets you focus on the important parts of the software that truly differentiate your work from everyone else's. But yes, utility classes with static methods are great, if they need to be written by you at all.
FYI, take a look at StringUtils.trimToEmpty(). Good luck.
some developers on the team might not like/not know this utility
That's what communication is good for. And I don't mean e-mail.
Talks about these kind of functions, probably other team members are doing the same and by not communitating you're duplicating code and efforts.
You may find a way to use these utility methods or even some more experienced developer migth have already develop a more mature lib or used a 3rd party.
But by all means, communicate with your team
I'm not an OO purist. So i love stuff like this. Anything that makes it easier to write code that reflects my intentions without getting bogged down in irrelevant details.
Write it. Use it yourself. Don't be shy - demonstrate how much cleaner it makes your code. Worst case, at least there'll be a bit less repetition in your code...
In terms of a design principle, there are some things that are just more logically static methods. If the utility class that you're writing doesn't really have any "state", and it feels more logical to make it uninstantiable with a bunch of static methods, then do it like that. But make sure your class is genuinely uninstantiable (give it a private constructor; I've seen people declare the class as abstract, but that's no good because people can override it).
The problem that you then get into is that if your class is project-wide, you need to treat it as a library class. And writing libraries is different from writing general code:
in general code, you should profile rather than prematurely optimising; but in a library method, you can't predict how people will use your call in the future;
you need to be very careful to document or clearly name what your method does;
you need to give it generic behaviour, and not be blinded by some specific feature that you need at that moment (e.g. if you have a method to "tokenise a string", what do you do with empty tokens? if you need to ignore them, will other callers to your method?)
I have a few classes that just contain fave static methods - they do make sense to have. You can put together extensive unit tests checking any and all boundary conditions.
In the case you described though - wouldn't it be better to make the setValue method accept any string sent to it? The method could then apply a default null string, trim it or even throw an exception if the value was incorrect.
The JavaDoc on that routine can then clearly state what inputs are valid/invalid and what happens to invalid inputs.
Not saying this is right - just another viewpoint
I use a lot of utility functions. There are some things that just don't need "objects", but I don't like the particular example you have of trim().
A reference to string that is null is very different from an empty string. Unless the app is very simple, and you know you always want to read a null reference as "", I wouldn't do it. For this case, I prefer:
setValue((str != null) ? str.trim() : "")
For me, an uncaught NPE is a good indication that there's a major error going on in the application!

Is writing "this." before instance variable and methods good or bad style?

One of my nasty (?) programming habits in C++ and Java is to always precede calls or accesses to members with a this. For example: this.process(this.event).
A few of my students commented on this, and I'm wondering if I am teaching bad habits.
My rationale is:
Makes code more readable — Easier to distinguish fields from local variables.
Makes it easier to distinguish standard calls from static calls (especially in Java)
Makes me remember that this call (unless the target is final) could end up on a different target, for example in an overriding version in a subclass.
Obviously, this has zero impact on the compiled program, it's just readability. So am I making it more or less readable?
Note: I turned it into a CW since there really isn't a correct answer.
I think it's less readable, especially in environments where fields are highlighted differently from local variables. The only time I want to see "this" is when it is required, for example:
this.fieldName = fieldName
When assigning the field.
That said, if you need some way to differentiate fields for some reason, I prefer "this.fieldName" to other conventions, like "m_fieldName" or "_fieldName"
This is a very subjective thing. Microsoft StyleCop has a rule requiring the this. qualifier (though it's C# related). Some people use underscore, some use weird hungarian notations. I personally qualify members with this. even if it's not explicitly required to avoid confusion, because there are cases when it can make one's code a bit more readable.
You may also want to check out this question:
What kind of prefix do you use for member variables?
I'd never seen this style until I joined my current employer. The first time I saw it I thought "this idiot has no idea and Java/OO languages generally are not his strong suit", but it turns out that it's a regularly-occurring affliction here and is mandatory style on a couple of projects, although these projects also use the
if (0 == someValue)
{
....
}
approach to doing conditionals, i.e. placing the constant first in the test so that you don't run the risk of writing
if (someValue = 0)
by accident - a common problem for C coders who ignore their compiler warnings. Thing is, in Java the above is simply invalid code and will be chucked out by the compiler, so they're actually making their code less intuitive for no benefit whatsoever.
For me, therefore, far from showing "the author is coding with a dedicated thought process", these things strike me as more likely to come from the kind of person who just sticks to the rules someone else told them once without questioning them or knowing the reasons for the rules in the first place (and therefore where the rules shouldn't apply).
The reasons I've heard mainly boil down to "it's best practice" usually citing Josh Bloch's Effective Java which has a huge influence here. In fact, however, Bloch doesn't even use it where even I think he probably should have to aid readability! Once again, it seems to be more the kind of thing being done by people who are told to do it and don't know why!
Personally, I'm inclined to agree more with what Bruce Eckel says in Thinking in Java (3rd and 4th editions):
'Some people will obsessively put this in front of every method call and field reference, arguing that it makes it "clearer and more explicit." Don't do it. There's a reason that we use high-level languages: They do things for us. If you put this in when it's not necessary, you will confuse and annoy everyone who reads your code, since all the rest of the code they've read won't use this everywhere. People expect this to be used only when it is necessary. Following a consistent and straightforward coding style saves time and money.'
footnote, p169, Thinking in Java, 4th edition
Quite. Less is more, people.
3 Reasons ( Nomex suit ON)
1) Standardization
2) Readability
3) IDE
1) The biggie Not part of Sun Java code style.
(No need to have any other styles for Java.)
So don't do it ( in Java.)
This is part of the blue collar Java thing: it's always the same everywhere.
2) Readability
If you want this.to have this.this in front of every this.other this.word; do you really this.think it improves this.readability?
If there are too many methods or variable in a class for you to know if it's a member or not... refactor.
You only have member variables and you don't have global variables or functions in Java. ( In other langunages you can have pointers, array overrun, unchecked exceptions and global variables too; enjoy.)
If you want to tell if the method is in your classes parent class or not...
remember to put #Override on your declarations and let the compiler tell you if you don't override correctly. super.xxxx() is standard style in Java if you want to call a parent method, otherwise leave it out.
3) IDE
Anyone writing code without an IDE that understands the language and gives an outline on the sidebar can do so on their own nickel. Realizing that if it aint' language sensitive, you're trapped in the 1950's. Without a GUI: Trapped in the 50's.
Any decent IDE or editor will tell you where a function/variable is from. Even the original VI (<64kb) will do this with CTags. There is just no excuse for using crappy tools. Good ones are given away for free!.
Sometimes I do like writing classes like this:
class SomeClass{
int x;
int y;
SomeClass(int x, int y){
this.x = x
this.y = y
}
}
This makes it easier to tell what argument is setting what member.
More readable, I think. I do it your way for exactly the same reasons.
I find that less is more. The more needlessly verbose junk you have in your code, the more problems people are going to have maintaining it. That said, having clear and consistent behavior is also important.
In my opinion you are making it more readable. It lets potential future troubleshooters know for a fact where the function you are calling is.
Second, it is not impossible to have a function with the exact same name global or from some namespace that that gets "using"'ed into conflict. So if there is a conflict the original code author will know for certain which function they are calling.
Granted that if there are namespace conflicts some other rule of clean coding is being broken, but nobody is perfect. So I feel that any rule that does not impede productivity, has the potential to reduce errors(however minuscule a potential), and could make a future troubleshooters goal easier, is a good rule.
There is a good technical reason to prefer to use or avoid this - the two are not always equivalent.
Consider the following code:
int f();
template <typename T>
struct A
{
int f();
};
template <typename T>
struct B : A<T>
{
int g()
{
return f();
return this->f();
}
};
Now, there are two f() calls in B<T>::g(). One would expect it to call A<T>::f(), but only the second one will. The first will call ::f(). The reason behind this is that because A<T> is dependent on T, the lookup does not normally find it. this, by being a pointer to B<T>, is also dependent on T however, so if you use it, the lookup will be delayed until after B<T> is instantiated.
Note that this behavior may not be present on some compilers (specifically, MSVC) which do not implement two-phase name lookup, but nonetheless it is the correct behavior.
Python folks do it all the time and almost all of them prefer it. They spell it 'self' instead of 'this'. There are ways around it putting explicit 'self' in, but the consensus is that explicit 'self' is essential to understanding the class method.
I have to join the 'include this' camp here; I don't do it consistently, but from a maintenance standpoint the benefits are obvious. If the maintainer doesn't use an IDE for whatever reason and therefore doesn't have member fields and methods specially highlighted, then they're in for a world of scrolling pain.
I use this for at least two reasons:
Fallacies reasons
I like to have consistent code styles when coding in C++, C, Java, C# or JavaScript. I keep myself using the same coding style, mostly inspired from java, but inspired by the other languages.
I like also to keep a coherence inside my code in one language. I use typename for template type parameters, instead of class, and I never play mixer with the two. This means that I hate it when having to add this at one point, but avoid it altogether.
My code is rather verbous. My method names can be long (or not). But they always use full names, and never compacted names (i.e. getNumber(), not getNbr()).
These reasons are not good enough from a technical viewpoint, but still, this is my coding way, and even if they do no (much) good, they do no (much) evil. In fact, in the codebase I work on there are more than enough historical anti-patterns wrote by others to let them question my coding style.
By the time they'll learn writing "exception" or "class", I'll think about all this, again...
Real reasons
While I appreciate the work of the compiler, there are some ambiguities I'd like to make UN-ambiguities.
For example, I (almost) never use using namespace MyNamespace. I either use the full namespace, or use a three-letters alias. I don't like ambiguities, and don't like it when the compiler suddenly tells me there are too functions "print" colliding together.
This is the reason I prefix Win32 functions by the global namespace, i.e. always write ::GetLastError() instead of GetLastError().
This goes the same way for this. When I use this, I consciously restrict the freedom of the compiler to search for an alternative symbol if it did not find the real one. This means methods, as well as member variables.
This could apparently be used as an argument against method overloading, perhaps. But this would only be apparent. If I write overloaded methods, I want the compiler to resolve the ambiguity at compile time. If a do not write the this keyword, it's not because I want to compiler to use another symbol than the one I had in mind (like a function instead of a method, or whatever).
My Conclusion?
All in all, this problem is mostly of style, and with genuine technical reasons. I won't want the death of someone not writing this.
As for Bruce Eckel's quote from his "Thinking Java"... I was not really impressed by the biased comparisons Java/C++ he keeps doing in his book (and the absence of comparison with C#, strangely), so his personal viewpoint about this, done in a footnote... Well...
Not a bad habit at all. I don't do it myself, but it's always a plus when I notice that someone else does it in a code review. It's a sign of quality and readability that shows the author is coding with a dedicated thought process, not just hacking away.
I would argue that what matters most is consistency. There are reasonable arguments for and against, so it's mostly a matter of taste when considering which approach.
"Readability"
I have found useful the use "this" specially when not using an IDE ( small quick programs )
Whem my class is large enough as to delegate some methods to a new class, replacing "this" with "otherRef" it's very easy with the most simple text editor.
ie
//Before
this.calculateMass();
this.perfornmDengerAction();
this.var = ...
this.other = ...
After the "refactor"
// after
this.calculateMass();
riskDouble.calculateMass();
riskDouble.setVar(...);
this.other = ...
When I use an IDE I don't usually use it. But I think that it makes you thing in a more OO way than just use the method.
class Employee {
void someMethod(){
// "this" shows somethings odd here.
this.openConnectino() ; // uh? Why an employee has a connection???
// After refactor, time to delegate.
this.database.connect(); // mmhh an employee might have a DB.. well..
}
... etc....
}
The most important as always is that if a development team decides to use it or not, that decision is respected.
From a .Net perspective, some of the code analysis tools I used saw the "this" and immediately concluded the method could not be static. It may be something to test with Java but if it does the same there, you could be missing some performance enhancements.
I used to always use this... Then a coworker pointed out to me that in general we strive to reduce unnecessary code, so shouldn't that rule apply here as well?
If you are going to remove the need to add this. in front of member variables, static analysis tools such as checkstyle can be invaluable in detecting cases where member variables hide fields. By removing such cases you can remove the need to use this in the first place. That being said I prefer to ignore these warnings in the case of constructors and setters rather than having to come up with new names for the method parameters :).
With respect to static variables I find that most decent IDEs will highlight these so that you can tell them apart. It also pays to use a naming convention for things like static constants. Static analysis tools can help here by enforcing the naming conventions.
I find that there is seldom any confusion with static methods as the method signatures are often different enough to make any further differentiation unnecessary.
I prefer the local assignment mode described above, but not for local method calls. And I agree with the 'consistency is the most important aspect' sentiments. I find this.something more readable, but I find consistent coding even more readable.
public void setFoo(String foo) {
this.foo = foo; //member assignment
}
public doSomething() {
doThat(); //member method
}
I have colleagues who prefer:
public void setFoo(String foo) {
_foo = foo;
}
less readable unless of course your students are still on green screen terminals like the students here... the elite have syntax highighting.
i just heard a rumour also that they have refactoring tools too, which means you don't need "this." for search and replace, and they can remove those pesky redundant thisses with a single keypress. apparently these tools can even split up methods so they're nice and short like they should have been to begin with, most of the time, and then it's obvious even to a green-screener which vars are fields.

Categories

Resources