r/programming • • 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/
28 Upvotes

35 comments sorted by

View all comments

12

u/[deleted] 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.

1

u/vattenpuss Aug 12 '15

I don't see how checking that an index is >= 0 could be construed as harder to understand. It makes it pretty obvious that your code only accepts natural numbers.

1

u/[deleted] 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. :)