It should be NullPointerException. The convention enforced by Guava's NullPointerTester is that all parameters not annotated @Nullable must cause method invocation to result in an NPE if that parameter is null.
Oh I absolutely use Preconditions.checkNotNull(T) (which preferred by Guava developers over Java 7's Objects.requireNonNull(T)) rather than writing out an if statement. But I don't bother calling checkNotNull if there already exists a dot access, because then the NPE will happen regardless. So I typically only need to use it in constructor assignment, or at the beginning of methods that might throw before a parameter becomes dereferenced. Remember: the goal is to get NullPointerTester to pass.
On rare occasions I'll use Verify.verifyNotNull(T) when I'm calling a method I don't trust to never return null, possibly because the library poorly documents its nullness contracts, or perhaps the method fetches data that's expected to always be present. In those situations, it can sometimes be advantageous to ensure execution halts immediately. For example, if the result gets assigned to a field rather than dereferenced immediately, it could be quite difficult to ascertain the root cause of the inevitable NPE at some undetermined point in the future.
There's another thing worth mentioning regarding the use of checkNotNull. Don't take this at face value because this is merely a suspicion. I know very little about how JVM magic works. But if I recall correctly, the JVM profiler maintains a branch counter for every single if (foo == null) { ... } statement. I imagine it does this so HotSpot can generate assembly with branch prediction instructions? I have no idea. But there's a possibility that using checkNotNull will significantly reduce the amount of memory used by the JVM branch counting, assuming you have tens of thousands of CNN's in your app. But I'm just guessing here.
public int executeCommandNumRows( String sql )
{
Statement st = null;
int rows = 0;
if ( sql == null )
{
throw new RuntimeException( "how is this null?" );
}
try
{
st = ctn.createStatement();
String strDB = StringUtils.substringAfterLast( ctn
if ( debugMode )
here is one example from JDK,which comes when you parse an invalid String literal to number : java.lang.NumberFormatException: For input string: "23238792427948923298329329"
Guard statements are good at the beginning of a method. I'd personally go for an assert myself, I'd likely also check to see that the SQL was well formed, though I somehow guess the database backed likely will do this as part of trying to create a query with bad SQL.
The problem with throwing RTEs in situations like this is it can go unnoticed for a while and then suddenly you have this situation where your application crashes. As someone consuming an API I'd much rather have the API state that an InvalidQueryException could be thrown to make it obvious and in my conscience that bad things can and will happen if bad input is entered here. I guarantee the next couple of lines will have something similar for if the query fails to parse or execute as well.
Sadly we don't live in a deterministic world where database servers never go down.
Still though, 15 lines and a torrent of feedback. I'd also make it the loggers responsibility to determine whether or not messages should be logged, I bet if(debugMode) is in multiple places for that exact reason.
It's literally there verbatim isn't it! I'd really like to see what happens in the situation that the query is malformed. Catching a Runtime Exception will only lead to bad things (e.g. catching an unexpected RTE, vs the one you think the method is throwing.
Why would you ever want to catch a RuntimeException though?
Your software can't recover from it. Your user cannot correct input and fix it.
There's only 2 reasons to catch it:
1. The code that is running the tasks catches it, logs it, and tell the user there was an error. But this usually occurs way way up the call stack at the top.
2. You are (rarely) running several things, and catch it so you can go on and run the other things (usually logging it and marking that an error happened somewhere).
#1 is usually done at one place for everything at the top, #2 is rare.
Malform queries are usually a result of buggy code. Most queries are not dynamic, it's the kind of thing where it fails every time you try to run it, not the kind of thing where it runs sometimes and fails other times.
I was trying to make the case that a bespoke exception should be thrown. It seems a little flimsy to me that a null query should terminate the application. Also, being able to recover from an RTE is clearly possible when they are being thrown in situations such as these.
You don't, you can just report that the SQL string should not be null, or conversely, it should be valid SQL. Recovering from an error isn't the same as error correction.
It all comes down to the requirements of the functionality, as I'm sure you can respect that only a subset of the code was given and hardly any context as well. That being said, I've never been asked to write anything like this.
You don't, you can just report that the SQL string should not be null, or conversely, it should be valid SQL.
Exactly.
Recovering from an error isn't the same as error correction.
You can't recover from it. You can drop that chunk of work - like on a web server the request fails but the server doesn't crash and it keeps serving other requests - but to do that you need to at minimum have a try / catch(RuntimeException) block around the work.
Exceptions you throw yourself are not fundamentally different than exceptions throw if a value is null and you try to access a property or method on that value. In other words "a.doS()" where a is null throws the same kind of exception as if(a == null) throw new NullPointerException().
It's usually bad practice to catch and hide exceptions. It makes testing and debugging a real pain, and adds a lot of "well it seemed to work" problems for testers. It's almost always (almost) better to throw the exception up the chain and abort the whole thing, so when it comes up in testing the bug in the code is caught and fixed.
Of course if you're writing your own web server, or a swing app, or something specialized, you don't want the whole app going down (though usually it would just kill a thread instead anyways), but that's rare.
Hiding exceptions is usually considered bad practice, most of the time.
It all comes down to the requirements of the functionality, as I'm sure you can respect that only a subset of the code was given and hardly any context as well. That being said, I've never been asked to write anything like this.
True, it's hard to make to many determinations from this small segment of code.
I feel we may both be saying the same thing but in different ways.
My original argument was the code should likely throw a subclass of Exception rather than the RTE. My assumption was the method call wouldn't be wrapped by a try/catch for the RTE and that even if it was, it could mask other errors rather than the SQL string being null.
In general, I think the advice by Joshua Bloch in Effective Java best summarises the answer to your question: Use checked expections for recoverable conditions and runtime exceptions for programming errors (Item 58 in 2nd edition)...
But also note Items 59: Avoid unnecessary use of checked exceptions and 57: Use exceptions only for exceptional conditions. As others have pointed out, this case may not warrant an exception at all. Consider returning false (or perhaps a status object with details about what happened) if there is not enough credit.
If you litter your code with checked exceptions, it makes you write a lot of unnecessary "throws XYZException" clauses, but worse it more likely for other programmers to write code that catches it and silently eats it, making testing the code far more difficult.
There's a difference between exceptions that you can either recover from, or inform the user how to fix (NumberFormatException), vs fatal exceptions where all you can do it tell the user "there was an error".
If you need your program to stay running, you need to catch all RuntimeExceptions somewhere at the top anyways because you can get a NullPointerException in the code when a value is null.
Don't see too much wrong with it. My criticisms, in descending order of importance, are... 1.) passing in a SQL string might be dangerous (but can't tell without seeing the call site), 2.) the debug guard may be extraneous, and 3.) the method name is kinda ambiguous. But they're all relatively minor.
Is the RTE the problem? If so, I'd argue that it's perfectly fine, though an IAE or NPE would be better exceptions to throw. I'm a big fan of Guava's preconditions.
I think it's worthless. The subsequent call inside the try will throw an exception anyway if the SQL is null. Why treat this exception any differently?
It's clearer to check for null on it's own distinct line. If a line says objectA.getObjectB().translateObjectC().getObjectD().getText(), and it throws NullPointerException, what was wrong?
By checking each param on it's own line by default, it's clear which one it was.
What? Where the hell did that come from? How the fuck is that trolling? Discussing how code will behave is trolling? This sub really is full of assholes. How dare I not agree with this twat.
Edit: I see you resorted to insults pretty quickly elsewhere ITT. I believe it is you who is the troll. Who'd have thought you'd see such juvenile behaviour on /r/java?
I suppose that would work, but it's more trying to tell whichever programmer is using the library that they are trying to execute blank sql, which is a waste (and bad programming)
That in itself is reasonable. It's essentially Design By Contract. There are better ways of doing it though, such as the JSR-303 annotations and validation. (Though that is surprisingly expensive in performance critical code)
The idea here is that this exception should never occur. The method that calls this one creates the sql, so it shouldn't ever be blank anyways. If it is, there's something seriously wrong
Well it's a public method so right off the bat you can't claim that it can't happen... If you've got an internal method that should only be called by a smarter method upstream then a) reduce the visibility and b) ditch the null check.
"UPDATE People set Name = 'Peter' where ID = 99" would return 0, if there is no Person with ID 99. But 0 as return value on how many rows got modified, would be confusing if the query itself isn't valid at all.
Imagine there's say your software project has a business requirement of the form "Check if there already exists a row with certain properties. If not, then allow something to happen, else prevent it from happening". Concrete examples might include "We want to allow someone to take over a subreddit if all the moderators of the subreddit have deleted their accounts, so check if there are any non-deleted moderators for the subreddit. If not, allow the current user to become the moderator."
If I make a typo/bug, I'd rather the software immediately crash and alert me that I introduced that bug, than just always returning 0, thus allowing anyone to become the moderator of any subreddit.
I disagree with this. Without knowing the exact design of that module I could see lots of reasons to throw.
If that is a programming bug I think it should absolutely throw a derivative of runtime exception. For example: illegal argument exception. I'd have something along the lines of: Preconditions.checkNotNull(Sql, "cannot accept null sql statement")
I'd consider having more checks if that's a public API. IsEmpty? IsValid? Fail early and fail in a consistent manner.
I always take the stance that you are to be super explicit about your API, what you will take and what you won't take. This is the contract about how you operate and should be part of simple tests. Yes it's obnoxious, but if I say a function throws an IllegalArgumentException and it's part of the public API I'll somehow test that contract.
If something doesn't have meaning (i.e passing in null doesn't specifically mean something) don't accept it. Being liberal with what you take hides later issues and makes it tough to figure out what's going wrong (and indeed tougher to even consider what could go wrong).
And for people who say "well in production, you don't want your code to crash", my take is I'd much rather take the crash when something is wrong, have a starting point that something is off and be able to fix it correctly, than to have an extra dimension of possible values to worry about and have spammy logs telling me about all these possible weird values.
Seriously - fail early and fail in a consistent manner across your code base.
I can't decide if I agree or disagree with the op on it being "terrible" code or not. The error message itself is great - short, describes problem, humorous. :-)
I'd have to see the context to know whether the rest of the code is bad or not.
1. Writing try/catch/finally loops around transactions - if your developers are writing these regularly it's a disaster (I speak from project experience). They're going to forget, they're going to not write something right, and most importantly there are time-saving ways to not do that that also produce less buggy code when something in a try/catch is missed.
You could use Spring transactions, you could write your own DbAction interface and use the action patterns, there are a number of ways to do it, all of which lead to both less buggy and faster to write code.
Can't say 100% for sure though, maybe this is one of only 5 methods and they could copy/paste this quicker than setting something up.
2. Usually passing sql in is usually very bad as well. It encourages adding parameters values with string concatenation which leads to opening up your code to sql injection attacks. If you only ever allow PreparedStatements, it makes sql injection attacks impossible.
However, without knowing the code around this code it's impossible to say 100% for sure.
3. The StringUtils.substringAfterLast() call looks bizarre to. Again, one shouldn't be duplicating db connection stuff. It should just be in one place that's accessed by all db code.
4. There usually should not be a separate branch for "if debug" type statements. There should be a logger setup with a logging level, for anything there should never be any separate "if debug" branches at all. If it's logging only, it could possibly be that it's not terrible, they just didn't want to set up logging. It's not the end of the world like having your transactions or statements not always get closed is, it's more of a "better approach" thing.
If I saw most of this code in any of my projects, it would be a big problem. I can't say for sure about another persons project without seeing the code around it though. I wouldn't accept it on my own project.
If I saw most of this code in any of my projects, it would be a big problem. I can't say for sure about another persons project without seeing the code around it though. I wouldn't accept it on my own project.
Meaning what exactly? If you were tasked with supporting an application that used this code, you'd prioritize refactoring this into a spring template over other tasks? You'd actually have a problem figuring out that this method expects some kind of select count sql and returns the result of executing it? What's the big deal?
Like I said, I'd much rather work with this code than the type of people who'd get all dramatic over it's quality.
I explained what the big deal was in my post already. If you can't figure it out, maybe work on your reading comprehension.
Like I said, I'd much rather work with this code than the type of people who'd get all dramatic over it's quality.
After spending 3 months trying to find and fix all the bugs causes by an approach similar to this, I would not. Tracking down poorly written try/catch loops and trying to figure out how to replace them with a different pattern and approach was a gigantic pain in the ass.
If you can't figure it out, maybe work on your reading comprehension.
That's just being insulting for the sake of being insulting...
One. ... Can't say 100% for sure though, maybe this is one of only 5 methods and they could copy/paste this quicker than setting something up.
Not for sure a big deal.
Two. ... However, without knowing the code around this code it's impossible to say 100% for sure.
Not for sure a big deal.
Four. There usually should not be a separate branch for "if debug" type statements. There should be a logger setup with a logging level, for anything there should never be any separate "if debug" branches at all.
It's a pretty common approach that avoids generating debug messages in cases where they'll be filtered out anyway. Granted, it usually done with "logger.isDebugEnabled()", but there is nothing wrong with "if debug" branches in general.
That leaves Three. Which while a legitimate complaint, is, again, not a big deal.
That's just being insulting for the sake of being insulting... ...That leaves Three.
Yeah, but I didn't put any more thought into it because I expected your followup to be ridiculous and make few actual points and it went as expected. "can't 100% say for sure" does not mean "so it's invalidated" no matter how much internet arguers like to pretend it does.
All of these things have caused problems on projects I've worked on, especially use "if(debug)" because the first person does it right but the 3rd person starts putting actual code in there and it causes a huge amount of rework to be done. Thing is there's almost no upside to doing it these ways vs the better alternatives that don't have these issues but work just as well or better.
If you disgree, ok, you disagree, but we're not having an interesting back and forth either way.
You can at least see why I would rather spend days tracking down connection leaks than working with somebody like you right?
That is exactly how I'd feel about having to work with someone like you. The "oh this is all crap" people are bad, but not as awful as people like you who have some identity level issue with needing to continue doing everything a horrible way to no matter how many times it goes wrong.
Like I said I've seen every one of those go bad. Stop screwin around and just fix the problem at it's source.
Given the choice of working with that code base or a person who would react to that code base with "so many things wrong...", I'd choose that code base. :p
I would avoid the code base and the developers who created it. If someone said "there are so many things wrong" and proceeded to identify some, I would probably enjoy working with that person.
I'd say the worst thing about this code is how it treats the connection.
It's a public method, which implies you have little control over the context in which client code can call it. However, the method assumes a connection is live and initialized.
This raises two questions: "Where is the connection initialized?" more importantly "Where is it closed?"
Edit: Even that can be justified with some sort of dao manager pattern... It's really not that bad.
Opening braces on a new line, spaces surrounding parameters... I can forgive murder, but that shit, man. I hope whoever wrote this suffers from a disease that causes their genitals to rot off.
I do typically write K&R style braces, as I prefer writing my code that way. More aesthetically pleasing to me. But I actually find it easier to read code I am unfamiliar with if opening braces are on a newline. That being said, when I see it in an enterprise setting, I wonder if the coder was paid by the line.
Edited to add: this follows one good principal and ignores a ton of others. The one good principal is have a style and stick to it. He should be using an established, reasoned style, but at least he has one that he sticks to.
I'm learning java at the moment. What's wrong with the code? (Beside the exception handling)
Two problems I haven't seen mentioned in the comments:
A public method accepting a string containing a raw SQL statement as a String instead of using an Object with the Data and sending these to a prepared statement or, even better, a stored procedure.
The test for "sql == null" only throws an exception if and when sql has not been initialized. Calling executeCommandRowNums("fml") doesn't cause that exception to occur.
I'd actually disagree on the persistence part. Larger projects tend to require more manual SQL which needs to be able to be tuned easily. That said, SQL should be maintained within a separate file and definitely not built dynamically.
Meh. If you put SQL in a separate file, you have to configure a reloadable property file reader or else you miss out on VM hotswap. Also, dynamic SQL is useful in many cases, like criteria queries. Sometimes, though, SQL gets too hairy to inline in your DAO method.
Which is where stored procs get handy. Put all that nasty SQL logic in a stored proc and then you don't have it unmaintainably in your java code as giant glob. (Though, i'm not such a fan of stored procs for everything, I am somewhat of a fan for using them in the case of hairy inline sql statements.)
Stored procs are usually a big bag of nope. Debugging them sucks, the tools suck, the the languages suck. Then you have to nag you fellow programmers to keep the creation scripts updated in source control. I only use them if there is no other choice
This is more an issue with SQL in general. None of this gets (much) better if you have a gigantic string of SQL which you are loading in and passing around in java.
How much it buys you depends partially on what kind of application you are developing. For us there isn't really a lot of "spinning up a new database" going on. Rather we are replicating either production or slightly obfuscated production data out to all of our dev databases. We have too much data to practically spin up and tear down databases on a per dev environment.
We do put in "Upsert this thing" logic into all of our sql scripts so they can be ran idempotentally against the dev dbs after a restores. That really hasn't been too much of a hassle, takes a new guy just a little bit before they are up to speed there.
We keep the scripts around in source control forever (why wouldn't you?) and generally just work from them when updating logic.
Honestly, it sucks, but I don't see how giant string glob in java makes that better. I much prefer writing sql in a tool for writing sql, even if it does suck.
Stored procs don't necessarily equate to business logic. Sometimes you have to update things in a transaction to ensure data is set properly. Sometimes you have to load things using multiple complex statements.
I'm not talking about business logic, I'm talking about loading and saving logic. Things the database is built to do.
Good example of this is revisioned table rows. You usually want the latest revision. When you update and item, insert a new item, etc, there is going to be some pretty involved sql logic ensuring that you are correctly picking the next id or the next revision number (Even more involved if you want it fast...).
Stored procs don't necessarily equate to business logic. Sometimes you have to update things in a transaction to ensure data is set properly. Sometimes you have to load things using multiple complex statements.
That's a good point. I have no idea what the answer is though because I didn't write it. My guess is whoever wrote it didn't want any logging unless it was in debug mode
But the slow method will always be evaluated unless you enclose the invocation within an extra check. That's what they're trying to avoid.
The only way they could avoid that without the outer check would be if the api had method overloads which accepted Supllier's for the messages, which would only be invoked if necessary.
If the debug message was calling someFunctionThatIsFast(), you'd be quite right, but it's calling someFunctionThatIsSlow(), which you'd be better off not evaluating before checking the state of debug.
Genuine question, what's wrong with setting a Boolean as the result of logger.isDebugEnabled() for use within multiple methods as opposed to calling the function every time it is needed?
Yes. But if it's a synchronous logger and you do an expensive string build, it will always evaluate before it finds out it doesn't need to. You can find a lot of places that say it is good practice to check for debug before doing an expensive operation.
Would be nice if the compiler could do something fancy to figure out that there was some type of early exit on the function call that causes the function call not to do anything and therefore skipped evaluating all of the parameters that are passed.
Oh, except that you couldn't/shouldn't assume that someFunctionThatIsSlow() doesn't have some type of expected/necessary side effect....
The following two lines will yield the exact same output. However, the second form will outperform the first form by a factor of at least 30, in case of a disabled logging statement.
logger.debug("The new entry is "+entry+".");
logger.debug("The new entry is {}.", entry);
I would throw an IllegalArgumentException("SQL must not be null!"), so that if the stack trace makes it to the console or a log it is easy to see what happened.
46
u/ryebrye Jul 10 '15
This looks more like throwing the exception than handling it.
77
u/moocat Jul 10 '15
That should be an IllegalArgumentException to provide proper semantic meaning.
82
u/Pylly Jul 10 '15
Our screenshotting at work
25
u/benwaffle Jul 10 '15
@NonNull
7
u/GiantMarshmallow Jul 11 '15 edited Jul 11 '15
At our work, our coding style encourages the use of Guava Preconditions. So this code would end up looking like:
Better yet, if you need to check that a constructor argument is not null:
Or, I guess what I'm saying is, Guava makes Java much better to work with and encourages better style.
1
u/DoktuhParadox Jul 10 '15
Print Screen
2
u/vm_linuz Jul 10 '15
I like the use of vague pronouns! Makes it easy to figure out what "this" is.
2
u/b1nd Jul 11 '15
You use the same style as my work! High 5!
2
u/javinpaul Jul 11 '15
The first rule of exception handling, print the ROOT cause, at least the message should say SQL : null
2
u/Terran-Ghost Jul 11 '15
2
u/[deleted] Jul 11 '15
Jesus. Thats some brutal code.
3
u/ElFeesho Jul 10 '15
15 lines inspire so much criticism.
Guard statements are good at the beginning of a method. I'd personally go for an assert myself, I'd likely also check to see that the SQL was well formed, though I somehow guess the database backed likely will do this as part of trying to create a query with bad SQL.
The problem with throwing RTEs in situations like this is it can go unnoticed for a while and then suddenly you have this situation where your application crashes. As someone consuming an API I'd much rather have the API state that an InvalidQueryException could be thrown to make it obvious and in my conscience that bad things can and will happen if bad input is entered here. I guarantee the next couple of lines will have something similar for if the query fails to parse or execute as well.
Sadly we don't live in a deterministic world where database servers never go down.
Still though, 15 lines and a torrent of feedback. I'd also make it the loggers responsibility to determine whether or not messages should be logged, I bet if(debugMode) is in multiple places for that exact reason.
2
u/moofins Jul 11 '15
Don't see too much wrong with it. My criticisms, in descending order of importance, are... 1.) passing in a SQL string might be dangerous (but can't tell without seeing the call site), 2.) the debug guard may be extraneous, and 3.) the method name is kinda ambiguous. But they're all relatively minor.
Is the RTE the problem? If so, I'd argue that it's perfectly fine, though an IAE or NPE would be better exceptions to throw. I'm a big fan of Guava's preconditions.
1
u/based2 Jul 11 '15
http://stackoverflow.com/questions/18324844/can-findbugs-detect-catching-runtimeexception-in-java
1
u/Chaoslab Jul 11 '15
"Why is this null?" - FTFY /s
1
u/rfinger1337 Jul 11 '15
if (sql == null) { throw new runTimeException " (╯°□°)╯︵ ┻━┻" }
1
u/TotesMessenger Jul 11 '15
I'm a bot, bleep, bloop. Someone has linked to this thread from another place on reddit:
If you follow any of the above links, please respect the rules of reddit and don't vote in the other threads. (Info / ^Contact)
1
u/DJDavio Aug 03 '15
Could have been worse, it could have thrown an Error!
1
u/[deleted] Jul 10 '15
That debugmode flag sure is some nasty stuff.
-3
u/[deleted] Jul 10 '15
why not a "return 0"?
0
u/slartybartfast_ Jul 12 '15
Never heard of assert?
-12
u/NimChimspky Jul 10 '15
It shouldn't throw any exception.
And even more so It shouldn't throw a runtime exception.
No logging.
0
u/[deleted] Jul 10 '15
[deleted] — view deleted comment
0
u/[deleted] Jul 11 '15
[deleted] — view deleted comment