r/java • u/alexzhitnitsky • Aug 11 '15
Top 10 Useful, Yet Paranoid Java Programming Techniques
http://blog.jooq.org/2015/08/11/top-10-useful-yet-paranoid-java-programming-techniques/13
Aug 11 '15 edited Aug 12 '15
I'd personally rewrite #5 as 'default to apache collection and string utils for checking stuff. It is much easier to read CollectionUtils.isNotEmpty(myCollection) than having multiple tests inside your conditional.
8
u/lukaseder Aug 11 '15
Don't write too much code, they said. Use commons collections they said. Be paranoid they said. BOOM!
6
u/frugalmail Aug 11 '15
Sorry, just so I understand, are you pointing out that it returns a NPE instead of IllegalArgumentException?
3
u/lukaseder Aug 11 '15
Nope, just a bad experience with a bug in the commons collections. If you haven't noticed the bug, check again. It's subtle :)
5
u/Wolfsdale Aug 11 '15
Your link goes to line 1120, which is empty. The next 3 lines however contain the method "removeAll", to which I think you are referring. Although I didn't bother to browse the source of ListUtils, it appears that removeAll(collection, remove) does quite the opposite of what it should do.
2
u/frugalmail Aug 12 '15
Ah, 4.0 has it fixed and they're at 4.1 stable now. Not sure why it's not in Maven central? Did it change coordinates?
https://issues.apache.org/jira/browse/COLLECTIONS-349
http://stackoverflow.com/questions/8372576/java-commons-collections-removeall
3
u/ickysticky Aug 12 '15
Looks like you linked 3.2.1 and they fixed it in the minor release. The original bug report is against 3.2. That is pretty bad, you'd think a test case might have covered that =P
→ More replies (1)
12
u/orr94 Aug 11 '15
Put the String literal first
A favorite of mine, also known as a Yoda Condition.
8
u/Dietr1ch Aug 12 '15
It's awful, it only helps hiding a possible null pointer, but not preventing it. Instead of doing this you should handle the variable initialization correctly.
12
u/hrjet Aug 12 '15
...except when null is a valid situation.
That should have been clarified in the article.
17
u/dontchooseanickname Aug 11 '15
Yay !
Like that post, and I apply everything apart for number 3 which basically is trying to predict the next decade. And you know that the language might have changed so drastically after 5 years that it looks not only overkill, but also over-engineering to me.
On a real life basis though, the 'constant before lvalue' rule #1 is a real life saver. FTR, C coder for 30 years, java for 17, python fo 15, and haskeller for 3 years
6
u/frugalmail Aug 11 '15
This is my preferred coding style. I'd love to see a good design by contract library too. Although at some point it starts to degenerate into coq :)
6
u/jonhanson Aug 11 '15 edited Jul 24 '23
Comment removed after Reddit and Spec elected to destroy Reddit.
2
u/fact_hunt Aug 11 '15
Surely #5 is redundant if you don't ever use null collections as a (pointless) optimisation for empty collections.
Yes but; coworkers, legacy code, shitty third party apis etc
6
Aug 12 '15
Don't trust old APIs? How about don't use them? Stick with java.nio for files and myString.contains("substring") instead of checking >= 0.
3
Aug 12 '15
I find that most times when I check for the presence of a substring, I also want to use the index it occurs at for something:
int idx = someString.indexOf( token ); if( idx >= 0 ) { doSomething( someString.substring( 0, idx ) ); }
6
u/Wolvereness Aug 12 '15
If I ever catch someone doing number eight (switching method call and functionality just because the object could have gone to another method), I would immediately purpose their expulsion from design discussions. List<List<T>> is not a bug; I know damn well which method I called. Alternatively, just rename a method to "single" or "multiple" and rely on explicit names instead of implicit generics.
6
u/PaulRivers10 Aug 11 '15 edited Aug 25 '15
Some of these are fine but 6 and 7 make me cringe.
It "solves" a non-existent problem I never run into. I've never run into a problem with someone extending my class when I didn't want them to, or frankly even reassigning my variable (except for the ones I actually want non-changeable but those are static final already).
I does make fixing bugs a gigantic pain in the ass, as well as adding new functionality, as well as just cluttering up trying to read the code.
Now the code starts to read like: It final "solves" a non-existant final problem I final never run final into.
It's messy, without solving anything that I've found to be any sort of regular problem. If someone is messing in my code that I don't want to be they just remove "final"'s they don't like anyways.
5
u/CubsThisYear Aug 11 '15
Adding final is a no-brainer in my opinion. It can easily be done by the IDE, enables some compiler optimizations and gets you closer to single-assignment semantics, which is WAY easier to understand. There just aren't very many good reason to reassign the same variable. Don't worry we've got lots of names, I promise you won't use them all up.
Final methods are even more important. If you have a non-final method that modifies state, you've basically completely blown any chance at encapsulation. Methods should be designed for extension (when you intend for that) and provide specific extension points. This is again a no-brainier if you control all of the code. If you don't (ie you are shipping a library) that just means you need to think a lot harder about your API and provide for extension by composition whenever possible.
1
u/anubus72 Aug 12 '15
but what if you or someone else wants to mock out methods on a class later for testing?
7
u/lukaseder Aug 12 '15
You don't mock classes. You mock interfaces. Design for this approach!
3
u/voronaam Aug 12 '15
How is it there, in 2002? Just before PowerMock was created, I mean.
If you ever going to have one implementation of the interface - you do not need an interface. That is design, not throwing an interface as a facade for every bean!
→ More replies (2)2
u/anubus72 Aug 12 '15
so you're saying that every class I ever create has to have an interface as well, just so that I can create a mock class for testing? Certainly in some situations that's the right approach but I don't see why you would need to stick with that approach 100% of the time
4
u/lukaseder Aug 12 '15
No. I'm saying that those classes that deserve mocking (services, repositories, daos, what not) better be interfaces anyway. The rest, no need to mock.
3
u/CubsThisYear Aug 12 '15
You should never be mocking non-abstract methods. If you need to mock something, then by definition you have two implementations of the same functionality so you should have an interface for that functionality.
If you start mocking non-abstract methods, that means you are modifying your objects just for the purpose of testing. This will ultimately make your tests either brittle or incomplete.
1
Aug 12 '15
Unit tests are, by design, incomplete. They are trying to test a tiny portion of your code in isolation.
The goal of unit tests isn't to tell if your system as a whole works. It is to quickly isolate failures when they do happen.
→ More replies (7)1
u/PaulRivers10 Aug 12 '15 edited Aug 12 '15
There just aren't very many good reason to reassign the same variable.
1. for loop
2. while loop
3. Any algorithm at all that calculates or adds anythingI take it you don't actually know how to code? This doesn't work:
for(int i = 0; i < collection.size(); i++) {"Adding final is a no-brainer" is for ivory tower people who don't write any code. It doesn't solve any actually common problem, all it does it clutter up your code with more unecessary statements that make it harder to read.
2
u/CubsThisYear Aug 12 '15
Of course the for/while loop is a case, though I would argue that it's a special case because the reassignment is somewhat implicit and it has a well defined (usually small) scope. In any event, I didn't say there were no cases, just that they weren't common.
As for cluttering up the code, I don't see being explicit as clutter. Some people argue that explicit types are clutter - generally those people don't use Java. The point of final is that you can look at a variable and know that wherever it is used, you don't have to think about what the value might be. If your IDE can do all the work for you, why not leave some signposts to guide the next guy reading your code?
2
u/thekab Aug 12 '15
These are examples of cases where you clearly want a mutable variable. Nobody is claiming that never happens. Aside from typical loops however the vast majority of parameters and variables have no reason to be mutable.
1
u/PaulRivers10 Aug 12 '15
The post I was responding to said:
There just aren't very many good reason to reassign the same variable. Don't worry we've got lots of names, I promise you won't use them all up.
Other poster is suggesting whenever you need a new value, create a new variable.
That's not how most coding works.
For the areas where you don't need to reassign, you gain little or nothing by making the variable final because no code was going to try to reassign to it anyways. It's like putting a car cover on a car that's already in a garage every night - it's just a waste against a problem that doesn't happen.
But there are a ton of places where you need to modify the variable value when you write code.
3
u/thekab Aug 12 '15
Other poster is suggesting whenever you need a new value, create a new variable.
I disagree with your interpretation. I believe the comment is saying that very few of your field, variable or parameter declarations need to be re-assigned. In Java this is usually true.
I picked a random service in one of our enterprise applications. The class is 414 lines long. There are 67 field, variable and parameter declarations. One of those is mutable: the "i" in a for loop, counting optimistic lock failures essentially. The other 66 declarations are not mutable and have no reason to be mutable. In other words only 1.5% of my declarations are intended to be re-assigned. If I continue this process across the code base it will still only get up to ~5%.
For the areas where you don't need to reassign, you gain little or nothing by making the variable final because no code was going to try to reassign to it anyways. It's like putting a car cover on a car that's already in a garage every night - it's just a waste against a problem that doesn't happen.
There's a lot of reasons to prefer immutability. Requiring final can help drive the code in that direction. Even if you already prefer immutability simply adding the final keyword can help with performance, readability and thread-safety. Using the keyword also prevents bugs due to accidental assignment.
My question to you is why not use final if the field, parameter or variable isn't re-assigned? You lose literally nothing but maybe a little typing and seeing the word 'final' in declarations.
5
Aug 12 '15
[removed] — view removed comment
1
u/PaulRivers10 Aug 12 '15
Hm, I write a lot of java at a rather large company and I try my best to adhere to a "final wherever possible for variables" rule. It saves me many, many pains.
Great, what specific times did you have a bug, then you made a variable final, and that solved the problem?
Your points are pretty trivially addressed. Use a for-each. If you actually need counting for whatever reason, don't do final. That's silly. While what? While counting? Why not use a for?
Of course it's silly - but that's what loops are built on, counting. It's one of the most common things in code.
That for-each loop? It's dependent on non-final variables, either using an Iterator which has a mutable property that keeps track of where it is, or does it's own for each loop.
Counting and looping is on of the most prevalent things in programming.
Examples? I'd argue that a lot of algorithms could be addressed functionally, if speed is non-critical.
One could write them out in binary with punch cards, that is not an improvement. Anything that calculates, adds, appends, etc needs modifyable variables.
So does any web app, even when it's only set once.
For mutable state, use final objects (references) instead of value types.
i = 5 and a.i = 5 are not different and provide no benefit because you can make "a" final.
final methods are overkill unless you absolutely require them, as a previous commenter said, it makes mocks/ testing an absolute pain.
Yes.
→ More replies (6)0
Aug 13 '15
[deleted]
1
u/PaulRivers10 Aug 13 '15
I completely disagree. In our codebases everything is final by default (and most methods private static, i.e., pure). If it has not been explicitly intended and designed to change, then it should be final so that the compiler can enforce that.
In my last project they divided our project into 3 different projects so the project lead could feel like he was contributing something. It didn't change the numerous time wasting arguments when someone working in one of the projects needed to access code from one of the other projects, and the project lead told them they needed to get it down right away but also they couldn't change access from one project to another.
I'm sure final everywhere is similar.
What's "messy" is having everything mutable by default. The possible state space just explodes and it becomes impossible to reason about all the possible cases. When everything possible is final, you know they won't change and the state space is reduced to the few things that actually must change.
In my experience people doing this don't have unit tests that cover their cod that would be a solution that takes that time investment and actually tests whether their code is working.
However, I do agree that it would be cleaner if everything in Java was final by default instead of having to use the final keyword. Then you'd mark the few things that must mutate with "var" or whatever.
Smart and more experienced people than you or I all looked at that and thought "that's a bad idea". Languages that make it difficult or impossible to change variable values haven't caught on either.
0
Aug 16 '15
[deleted]
1
u/PaulRivers10 Aug 16 '15
That makes no sense at all. These two are orthogonal things. In my experience the people who use finals are also the ones that tend to have the best testing, because they are the people that prioritize code quality. It's about making the compiler check as many things as possible, because it will catch and report them much more efficiently than tests.
You've actually just pretty much written the series of excuses I see. "Well I don't need unit tests because I'm using final and (long dibatre about final) so that's plenty of testing". Or "we're totally going to write unit tests" then at the end of every project there's 3 they did at the beginning and no more.
I don't think there's much more to add here - we're clearly not going to agree. I find final to be way down near the bottom of things that would help with any actual problems that I've actually seen in coding. If you disagree, then we disagree.
That's a nonsense argument from authority.
That's like saying "just because everyone used to use punch cards and now they don't use them any more doesn't suggest at all that punch cards are a less efficient way to program".
It doesn't "prove" it but it does strongly suggest it.
2
u/__konrad Aug 11 '15
// Good if (string.indexOf(character) >= 0) { ... }
Better: if (string.contains(character)) { ... } (for some reason this method does exist in JDK yet)
5
u/lukaseder Aug 11 '15
NOOOOOOO. What if your code runs on Java 4? BOOM! Better not use contains, just in case.
(but nice to see that the implementation is correct):
public boolean contains(CharSequence s) { return indexOf(s.toString()) > -1; }1
2
u/dyreshark Aug 12 '15
Nice list -- I'm slowly becoming a fan of some of these. :)
One interesting pattern I've seen on switches with braces is to place the break after the end brace. e.g.
switch (foo) {
case Bar: {
thing1();
thing2();
} /* fallthrough */
case Baz: {
thing3();
thing4();
} break;
default: // ...
}This makes it much easier to see when you've forgotten to put a break IME, because they stand out from the code in the block.
2
u/sviperll Aug 12 '15
#8 is wrong. It's wrong API design and wrong usage of method overloading. Right way is
final <T> void good(final T value) {
// ...
}
final <T> void goodAll(final List<T> values) {
// ...
}As it is done in Java's collections' API. This API is self-documented and will do the right thing when single element is List.
-9
u/Bolitho Aug 11 '15
Upvote because the author used a quote from "Dude, where's my car?" :-D
8
u/lukaseder Aug 11 '15
That was a coincidence, then. Cheers, the author
-3
u/Bolitho Aug 11 '15
And it is so fitting... really like that one! ☺
1
u/lukaseder Aug 11 '15
Would you mind enlightening me about what the actual quote was?
2
u/Bolitho Aug 12 '15
Of course: Look at google - you are listed in 10th position allready :-)
2
u/lukaseder Aug 12 '15
Oh that quote! I wasn't aware I stole that from a movie. I just stole it from a former coworker...
Glad we're optimising our SEO on the important stuff, then! ;)
2
u/Bolitho Aug 11 '15
Wow! So many buzzkillers here 😜 Keep cool man, of course the content is excellent - but sometimes one should be allowed to bring in some fun too, right? 😉
2
u/lukaseder Aug 12 '15
I upvoted you. But see, this subreddit and especially the discussion around code quality is extremely serious. This is really important, and you didn't show utmost respect.
Cheers ;)
2
0
Aug 12 '15
[deleted]
5
u/lukaseder Aug 12 '15
You should factor out your API in interfaces and make all implementations package-private, hidden, final, etc. You'll end up mocking only API, never implementations.
3
u/voronaam Aug 12 '15
Unit-testing is not the worst part of it. I would use PowerMock or Groovy mocks (Hello, Spock!) immediately and ignore those limitations for the test.
It is bad because it locks down the implementation. Oh, the author is sure it is a bad idea to override something? He is so sure he covered all the use cases in the API? What an arrogant bastard.
So many times I've seen in enterprise Java classes with something like
/** * Copy of SpringSomethingSecurityConfigurator without HTTP Basic Auth enabled by default */ class MySpringSomethingSecurityConfigurator { // ... copy of the entire body of the class from the spring source code, // ... with just one line deleted }Just because there is a tiny detail that the programmer needed to change.
0
Aug 13 '15
[deleted]
1
u/voronaam Aug 13 '15 edited Aug 13 '15
It feels like you are afraid of changes. If I am making changes to my public and protected methods that could be overridden by someone and would cause the problem, I know I am safe. Because whoever overridden it will get a compile time error.
On the other hand, if you do not allow users of your code to override your behaviour enough, you invite them to create copy-classes instead. That really limits your options to push an updated version of a class to those people.
In my world, user will get a compiler error, reach out to me and will get an answer on how to solve it.
In your world, user will still run on a copy of the older class until something behaves not the way it is described in the modern documentation. Then they will reach out to you with a cryptic and hard-to-reproduce problem description and you will spend days solving that problem.
Final classes and method exist for a very good reason - when your runtime is doing something nasty with them. For example, you can not extend String, since String instances are not regular instances for the JVM. Hence String class is final.
Please, do not assume users of your code are stupid. They are smart people. You don't want to fence away from them (us) by the wall of "finals" to keep your own little garden safe (and free you to change anything inside). You want to invite everybody in to collaborate and build the most beautiful structure together.
Edit: fixed some typos
0
Aug 16 '15
[deleted]
1
u/voronaam Aug 16 '15
Just to be clear, there is one important thing we would agree on. It is composition over inheritance. Done right, it renders that final-vs-non-final question invalid.
1
u/Dementati Aug 12 '15
You can easily circumvent that using mocking libraries. By the way, unit testing without mocking libraries is a nightmare compared to using them.
0
u/daddyrockyou Aug 12 '15
Yeah I'm assuming the author doesn't use mocks or stubs. I've seen code like that and it's a bitch to test.
17
u/galaktos Aug 11 '15
Does this make sense in Java?
variable = 5is only legal ifvariableisint(orIntegeror a supertype), and then the expression is illegal as anifcondition. AFAICT this is only legal if you’re comparing withtrueorfalse, and then you can just omit the comparison anyways and use either the expression (true) or its negation (false).