r/programming • u/[deleted] • 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/3
u/cowinabadplace Aug 12 '15 edited Aug 12 '15
Yo, what's with the if (5=a) business. I don't know why he randomly mentions Javascript. This is not a thing you have to worry about in Java except for boolean literals, which are generally better as enums anyway.
Added to pad to 10?
3
12
Aug 11 '15 edited Aug 11 '15
I'm mostly code in C# and I'm no expert in how different C# is from Java, but it seems like what this article recommends would be bad practice in my view.
It's not like in C++ where reading outside of an array could cause undefined behavior and vulnerabilities. I would take a ArgumentException any day over some function silently ignoring the fact that I provide it with weird or even invalid input.
I sometimes see people adding null-checks which makes no sense. They may be calling a method which can never return null, yet at the call-site they perform null-check. Adding null-checks were not necessary, or checking for >= for the potential -2 which will never happen just leads to code which is harder to understand.
Functions should have a clear contract defining what input they expect and what data they return and if that can not be met, then an exception should be thrown. And that exception is a good thing. For example, if your function expects a non-null string it should throw an exception if null is passed.
In my view, what the article writer isn't useful or paranoid code, it's guidance which leads to more buggy code in the long term.
2
u/Eirenarch Aug 11 '15
I agree with you but what you say only applies to his null checks. Some of his things are valid for C# and the final methods is in fact the default behavior of the language.
0
u/vattenpuss Aug 12 '15
And to be fair, the article really only brings up null checks due to older platform APIs.
1
u/vattenpuss Aug 12 '15
I don't see how checking that an index is
>= 0could be construed as harder to understand. It makes it pretty obvious that your code only accepts natural numbers.1
Aug 12 '15
Because the specification/contract for indexOf states that -1 will be returned if no match is found. Checking if result != -1 is closer linked to the specification than checking for result >=0 in my opinion.
Maybe it's just me. :)
1
u/hu6Bi5To Aug 12 '15 edited Aug 12 '15
I'm mostly code in C# and I'm no expert in how different C# is from Java, but it seems like what this article recommends would be bad practice in my view.
Yeah, a lot of these are bullshit. But some of them are bullshit that have been institutionalised in the warnings of IntelliJ etc... They don't stand to reason.
It’s just never a bad idea to prevent the occasional NullPointerException by putting the String literal on the left side of an equals() comparison as such
Terrible advice. Either the variable is legitimately nullable, in which case you're just hiding that fact, the more verbose
if (v != null && v.startsWith("blah"))would show the intention clearer; or, the variable is not null, and there's no need to make the change."But what if it is null, due to a bug elsewhere?" Well, in that case, I want it to fail. Silently ignoring bugs and hoping for the best just makes debugging harder.
Don’t trust the early JDK APIs
Then goes on to list the JavaDoc that accurately explains the behaviour. A better lesson would be "read the instructions".
That particular example would have probably been better served by throwing an exception if called on a non-directory. Perhaps.
Don’t trust that “-1”
Paranoia combined with voodoo.
Avoid the accidental assignment
This one is an old classic, but is one of the easier ones for IntelliJ (etc.) to warn about.
Whenever you have a collection, array, etc., make sure it’s present AND not empty
Again this is context specific, in exactly the same way the first one was. If it cannot be legitimately null, then don't just silently carry on if it is. Only check for null if it could, legitimately, be null; in practice you should need to do this very rarely.
You can tell me all you want about your open/closed principles, that’s all bollocks. I don’t trust you (to correctly extend my classes) and I don’t trust myself (to not accidentally extend my classes).
Well maybe. But these things should be used for semantic purposes mostly. Or you could just mark the class as final, which achieves the same thing.
Don’t trust generics when overloading
I know what they're saying, but I don't think the example illustrates the point at all well.
Always throw on switch default
Surprised they didn't add "except if it's null, in which case silently ignore it and carry on like points 1 and 5".
Switch with curly braces
Meh.
In summary: these aren't even paranoid practices, these are purely superstitious practices that can cause as many problems as they solve.
0
4
u/minibuster Aug 12 '15
Man, if only we had tools to watch our backs, like imagine an application that wraps a text editor, a compiler, and visual feedback for warnings all in one. Like some sort of... integrated... development... environment. The future sounds amazing.
5
u/robby_w_g Aug 11 '15 edited Feb 15 '26
Lorem ipsum dolor sit amet consectetur adipiscing elit. Quisque faucibus ex sapien vitae pellentesque sem placerat. In id cursus mi pretium tellus duis convallis. Tempus leo eu aenean sed diam urna tempor. Pulvinar vivamus fringilla lacus nec metus bibendum egestas. Iaculis massa nisl malesuada lacinia integer nunc posuere. Ut hendrerit semper vel class aptent taciti sociosqu. Ad litora torquent per conubia nostra inceptos himenaeos.
3
u/valenterry Aug 11 '15
You can also return null values randomly and throw errors randomly from your library. How is it your fault if the callers program breaks? He could have caught the nulls and the errors.
But if you want to write software that does not break so easy, you should better make everything final and thus not use inheritance at all. Also never return null. It helps everyone who uses your code.
Though, Java is a language that can make it quite hard to do those things, because e.g. there is no help for delegating all method calls to an internal object. So not using inheritance means you have to implement all the methods of the interface of the object you want to delegate to yourself. That's kinda annoying, so it might be an excuse still to use inheritance. However it's not an execuse for using Java at all!
3
u/robby_w_g Aug 11 '15 edited Feb 15 '26
Lorem ipsum dolor sit amet consectetur adipiscing elit. Quisque faucibus ex sapien vitae pellentesque sem placerat. In id cursus mi pretium tellus duis convallis. Tempus leo eu aenean sed diam urna tempor. Pulvinar vivamus fringilla lacus nec metus bibendum egestas. Iaculis massa nisl malesuada lacinia integer nunc posuere. Ut hendrerit semper vel class aptent taciti sociosqu. Ad litora torquent per conubia nostra inceptos himenaeos.
1
u/pakoito Aug 12 '15
Also never return null.
I try to abide by this, but what do you do for cases where it's difficult to find an alternative, i.e. convert string to enum by equals.
Optional is Java8, we're working on Java6 still.
1
u/valenterry Aug 13 '15
As I said, if your language puts a spoke in your wheel, change that first. In Java 6 you can still create your own Option type (there are also already defined types you can use (e.g. in Google Guava) but they are of course not as comfortable without lambdas. =/
1
u/lookmeat Aug 12 '15
Think of it more in the lines of YAGNI. But what if I need to overload this method? What if I need to change the value of the input variable? The answer to all those questions is: you probably won't need it, and when you do you can change the signature.
Now if a user writes poor code that breaks your library that is his problem. But what if the user wrote solid good code that breaks your library because your library is poorly written? By making a method final you can work on the assumption that it won't be replaced, so you don't have to worry about different considerations. Then you can make the few areas of your object that can be overridden non-final and then be paranoid around those few methods (allowing your library to work even with poor code, that makes it better than most libraries out there).
With the making parameters and variables final it's meant to work much like functional programming does. It assures us what is being altered and what isn't. Again you could just check on the code and verify it doesn't happen, but why do it when the compiler can do it for you and all for a thing (changing the value of a variable) that you don't really need?
1
u/vitalyd Aug 12 '15
If you agree that virtual extension points are a type of API and APIs need forethought, then you'll likely see why preventing unintended/"undesigned" extensibility is a good default to pick.
0
u/Eirenarch Aug 11 '15
I do follow the all methods are final because in C# that's the default. I guess Anders (Hallowed be His name!) agrees that all methods should be final :)
4
u/sh0rug0ru___ Aug 11 '15 edited Aug 11 '15
<pendantry>
All non-static methods are virtual in Java. Regardless of the pointer you have to the object (whether it is the concrete type or a super type), the same method will be called. Always.
On the other hand in C#, instance methods are by default non-virtual and cannot be overridden. But, that does not mean they cannot be overloaded. Thus, a pointer of the concrete type and a pointer of a super type can actually invoke different methods!
The equivalent to Java's
finalin C# is actuallysealed. Which is not the default!</pedantry>
1
u/Eirenarch Aug 11 '15
What? I am pretty sure final on a method means non-virtual in Java. final on a class means what sealed means in C#
5
u/sh0rug0ru___ Aug 11 '15 edited Aug 11 '15
If you look at the bytecode generated on a method call to a
finalmethod, you will seeinvokevirtual. All instance methods in Java are virtual, evenfinalmethods (except for constructors and private methods -invokespecial, and interfaces, oddly enough thorughinvokeinterface. Oh yes, and nowinvokedynamic). But this would have to be the case. What if you inherited from a non-final method and made your override final? This is exactly whatsealeddoes on a virtual method or property in C#.However, that is only half the story. The JVM can "devirtualize" methods, even non-final methods, based on class-hierarchy analysis. Paper if you're interested.
Thus, final or not final doesn't make a difference in Java at runtime. The JVM will figure out whether or not the method should be virtual or not. I would say
finalis more for enforcing constraints at compile-time.1
u/vitalyd Aug 12 '15
Final allows JIT to skip registering class load dependencies since it knows the target will never change.
0
Aug 11 '15
[deleted]
6
u/lookmeat Aug 12 '15
You know, one day a programmer will come over to your code, not knowing or caring to know what it was trying to do, will assume s/he knows more than you and then will screw everything up. And that programmer will be you.
2
u/isHavvy Aug 12 '15
The programmer has to stop for a moment and think about why it is final. They have to reason that no code will break with the invariant removed, or if it does, they have to fix it.
In code review, it gives the reviewer the impetus to check that too.
1
u/dododge Aug 12 '15
Along these lines, the checkstyle static analyzer has a "design for extension" rule, which requires that all instance methods are final, abstract, or empty. This is useful for ensuring that any meaningful concrete methods don't get shadowed, while still allowing for overrides and inheritance when it's explicitly intended. When I first started using it, it did take a while to get the "final"s in place to get all the warnings to stop, but now I mark most things final without even having to think about it (and even before I started doing Java regularly, my C code was likewise covered in "const" qualifiers).
1
u/alparsla Aug 12 '15
Typical techiques of defensive programming. It may be necessary in legacy, and somewhat critical systems.
https://en.wikipedia.org/wiki/Defensive_programming
The opposite of it is the fail-fast systems.
https://en.wikipedia.org/wiki/Fail-fast
I said "somewhat critical" above, because a critical system must be fail-fast, but sometimes you don't have time and support to do it.
1
u/MrAndersson Aug 12 '15
6. All methods are final ... Yes. It’s final. If that doesn’t work for you, patch it, or instrument it, >or rewrite the byte code. Or send a feature request. I’m sure that >your intent of overriding the above isn’t a good idea anyway.
It might be a valid stance if you are the only user of the code, if you respond to feature requests in one hour or less, or if you always ship all source code to customers. Barring that, those finals should be removed before the software ships. It's not fun to have to add bytecode rewriting simply work around bugs in other peoples code when a classpath update and a couple overrides would have worked.
If we are to write code defensively, we should also be careful to avoid overestimating our own ability to know what other people might have to do with the code/library, and not make it hard for the people paying us to fix their problem when we for some reson can't.
1
u/zimm3r16 Aug 12 '15
Never been a fan of Java but lots of these seem rather over the top.
String literal first? No. Check and log. Provides my info than a silent fail.
Don't trust -1. Yes trust it. Have an else catch or 'drop off' where it logs unexpected errors. Stop silently failing.
Disclaimer: I am no friend to Java ever since I had to deal with people using private. (Yes I know internal, may change, i don't care Android, I want access to my Native C View to resize it and use a java GUI easily!).
1
u/ExplosiveNutsack69 Aug 12 '15
I don't see why there's any reason to do anything other than the >= 0 check. There is literally no situation in which that could go wrong, and for people reading the code that don't understand that a null indexOf() will return -1 (God forbid), it will immediately make more sense. Quite honestly, it's easier to read universally, because we don't think like computers do. Ensuring that it's either a) empty or b) not empty and has indices with the >= 0 check is simpler to process. My two cents.
1
u/zimm3r16 Aug 12 '15
Explicit rather than implicit. You truly only expect -1 or a positive number so your code should reflect that.
1
u/ErstwhileRockstar Aug 11 '15
'final' variables ;-D
1
u/vattenpuss Aug 12 '15
I just don't think you understand what the word variable means.
A variable does not have to change. It's just a name for something that is not constant for every instance of your expression.
P -> Q
Means if P is true, then Q is true. P and Q are variables. P and Q will never change within an expression because that would break the universe.
2
19
u/pakoito Aug 11 '15
No hidden thrown exceptions please. Fail early, fail better. Check for invariants as soon as possible, preferably at the beginning of a method, and throw/return there.