r/java • • Jul 10 '15

Our exception handling at work

http://imgur.com/4wgxCvv
259 Upvotes

135 comments sorted by

46

u/ryebrye Jul 10 '15

This looks more like throwing the exception than handling it.

1

u/[deleted] Jul 11 '15

Came here to say this.

77

u/moocat Jul 10 '15

That should be an IllegalArgumentException to provide proper semantic meaning.

26

u/jart Jul 11 '15

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.

1

u/NosferatuPerrywinkle Jul 11 '15

Just out of curiosity do you prefer writing the statement out or Objects.requireNonNull(T)?

3

u/jart Jul 11 '15

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.

2

u/jart Jul 11 '15

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.

1

u/NosferatuPerrywinkle Jul 12 '15

Very detailed answer, thanks!!

1

u/iliketoworkhard Nov 12 '15

Very fascinating. Compilers are fascinating indeed.

82

u/Pylly Jul 10 '15

33

u/OceanOfSpiceAndSmoke Jul 10 '15

What a coincidence, our screenshooting at work.

25

u/balducien Jul 10 '15

1

u/monknomo Jul 10 '15

7

u/stillalone Jul 11 '15

shallower:

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 )

0

u/__konrad Jul 10 '15

Thanks for the backup. imgur now displays "Error (0) Sorry! There was an error (code: 0)"

25

u/benwaffle Jul 10 '15

@NonNull

7

u/cogman10 Jul 10 '15

javax.annotation.Nonnull is the one true Nonnull.

Optional is also optional.

6

u/DevIceMan Jul 11 '15

Optional implies it may be optionally there or not, though this code seems to suggest it must ALWAYS be there.

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:

Preconditions.checkNotNull(sql);

Better yet, if you need to check that a constructor argument is not null:

this.sql = Preconditions.checkNotNull(sql);

Or, I guess what I'm saying is, Guava makes Java much better to work with and encourages better style.

9

u/[deleted] Jul 11 '15 edited Jul 11 '15

This particular functionality of Guava is in the JDK since 1.7. https://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#requireNonNull%28T,%20java.lang.String%29

String sql = Objects.requireNonNull(param, "An optional Error message");

6

u/GiantMarshmallow Jul 11 '15

Wha...oh my god this is completely new to me. Probably just an artifact of spending most of my time in JRuby land these days. :)

3

u/squealy_dan Jul 11 '15

and much of guava has been coopted into the standard lib in java8

(requireNonNull(), Optional)

1

u/DoktuhParadox Jul 10 '15

Print Screen

1

u/[deleted] Jul 10 '15

I'm on my phone

0

u/[deleted] Jul 11 '15

Imgur.

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

1

u/javinpaul Jul 11 '15

here is one example from JDK,which comes when you parse an invalid String literal to number : java.lang.NumberFormatException: For input string: "23238792427948923298329329"

0

u/RedPill115 Jul 14 '15

I'm just pointing out - since it's checking for null, you know the value, - it's null, lol...

2

u/Terran-Ghost Jul 11 '15
/r/styleformattinggore

2

u/[deleted] Jul 11 '15
if(debugMode)

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.

3

u/KirbzStar Jul 11 '15

I think in this case, an rte is fine

2

u/ElFeesho Jul 11 '15

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.

0

u/RedPill115 Jul 14 '15 edited Jul 15 '15

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.

1

u/ElFeesho Jul 14 '15

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.

0

u/RedPill115 Jul 15 '15

Also, being able to recover from an RTE is clearly possible when they are being thrown in situations such as these.

Ok, I'll bite, how? How do you get the code to figure out what sql string you actually meant to pass in?

1

u/ElFeesho Jul 15 '15

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.

1

u/RedPill115 Jul 15 '15

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.

1

u/ElFeesho Jul 16 '15

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.

1

u/RedPill115 Jul 18 '15

Ok, sure, but in java many different frameworks have gone through this before.

Like Hibernate and Spring:

http://stackoverflow.com/questions/4609870/why-hibernate-changed-hibernateexception-to-runtimeexception-unchecked

http://stackoverflow.com/questions/11490636/why-are-exception-in-spring-and-hibernate-most-unchecked-exception

Or to quote another response here from the book Effective Java:
http://stackoverflow.com/questions/499437/in-java-when-should-i-create-a-checked-exception-and-when-should-it-be-a-runti

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.

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/[deleted] Jul 11 '15

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?

0

u/RedPill115 Jul 14 '15

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.

0

u/[deleted] Jul 15 '15

I don't know that this particular code will throw an NPE. More likely an SQL exception.

0

u/RedPill115 Jul 15 '15

Oh sorry, I see you're just trolling.

1

u/[deleted] Jul 15 '15 edited Jul 15 '15

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?

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"?

6

u/[deleted] Jul 10 '15

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)

5

u/sazzer Jul 10 '15

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)

0

u/[deleted] Jul 10 '15

[deleted]

5

u/[deleted] Jul 10 '15

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

2

u/supercargo Jul 11 '15

Replace throw with a nice System.exit(1) to make whoever passes in a null really sorry for doing something that should never happen ;)

0

u/xienze Jul 10 '15

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.

3

u/[deleted] Jul 10 '15

I never said it can't, only that it shouldn't. That being said I agree, but I didn't write this and it's not something I am supposed to modify anyway

11

u/Pylly Jul 10 '15

Runtime exceptions don't ever have to be caught.

2

u/Feroc Jul 10 '15

"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.

3

u/Nebu Jul 11 '15

I'm generally opposed to silent failures.

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.

1

u/duckrollin Jul 11 '15

Don't know why you got downvoted, this is textbook defensive programming

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.

3

u/brick_wall_mirror Jul 10 '15

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.

-6

u/NimChimspky Jul 10 '15

If the parameter can be null, check and handle it.

If it can't don't worry about it.

1

u/brick_wall_mirror Jul 11 '15

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.

0

u/[deleted] Jul 10 '15

[deleted]

29

u/dablya Jul 10 '15

That's a bit dramatic...

7

u/raxel82 Jul 10 '15

Granted, I don't write in Java, but it doesn't seem anywhere near as bad as he's making it out to be.

0

u/NimChimspky Jul 10 '15

No it's really shit

1

u/[deleted] Jul 11 '15

No, it really isn't, it is completely awful.

0

u/RedPill115 Jul 10 '15

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.

11

u/dablya Jul 10 '15

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.

-3

u/RedPill115 Jul 11 '15

What's the big deal?

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.

3

u/dablya Jul 11 '15

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.

-2

u/RedPill115 Jul 11 '15

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.

1

u/dablya Jul 12 '15

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.

You can at least see why I would rather spend days tracking down connection leaks than working with somebody like you right?

-1

u/RedPill115 Jul 12 '15 edited Jul 12 '15

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.

0

u/[deleted] Jul 11 '15

For one thing the whole exception throwing is unnecessary. Also the method definition is not specifying the it throws an exception.

3

u/[deleted] Jul 13 '15

the method definition is not specifying the it throws an exception

There's no reason why it should declare that a runtime exception may be thrown.

0

u/[deleted] Jul 10 '15

[deleted]

13

u/dablya Jul 10 '15

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

4

u/darksounds Jul 11 '15

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.

0

u/[deleted] Jul 10 '15

[deleted]

7

u/Neebat Jul 10 '15

The test for null doesn't actually change anything except the type of exception generated, for the worse.

I don't know what else vecowski is talking about but that "debugMode" flag worries me a lot!

7

u/dablya Jul 10 '15

The test for null doesn't actually change anything except the type of exception generated, for the worse.

Obviously a better exception and descriptive message would be better, but there is value in failing sooner rather than later.

6

u/dablya Jul 10 '15 edited Jul 10 '15

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.

9

u/RAL_9010_POWER Jul 10 '15

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.

4

u/Nebu Jul 11 '15

Since you're replying to someone who explicitly states that they are learning Java, I feel obligated to point out that RAL_9010_POWER is joking.

2

u/friendlyburrito Jul 10 '15

Could be the prescribed styling as mandated by the company.

3

u/Spoogly Jul 10 '15

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.

1

u/h0uz3_ Jul 11 '15

You are very picky, but I love your nick name! :D

1

u/h0uz3_ Jul 11 '15

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.

0

u/[deleted] Jul 10 '15

[deleted]

12

u/dardotardo Jul 10 '15

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.

11

u/vitingo Jul 10 '15

SQL should be maintained within a separate file

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.

5

u/After_Dark Jul 10 '15

I'm pretty sure there is no proper/good way to do SQL in Java, just less bad ways.

1

u/segv Jul 11 '15

I've found that Guice + MyBatis (3.x line, not the 2.x line) is pretty nice in this regard.

0

u/cogman10 Jul 10 '15

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.)

16

u/vitingo Jul 10 '15

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

3

u/cogman10 Jul 10 '15

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.

9

u/OHotDawnThisIsMyJawn Jul 10 '15

Source control and sane deployment with lots of stored procs is the worst

2

u/[deleted] Jul 11 '15

Nope, putting business logic in stored procedures is pretty horrible.

1

u/cogman10 Jul 11 '15

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...).

1

u/[deleted] Jul 11 '15

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.

Absolutely reasonable uses of stored procedures

3

u/[deleted] Jul 11 '15

He should at least be using PreparedStatement though.

2

u/dardotardo Jul 11 '15

Oh for sure, if they're being dynamically built it's prone to injection, and it's also highly unlikely it's being cached on the database.

1

u/[deleted] Jul 10 '15

We use log4j. The next line after that debug mode flag is logger.debug

2

u/friendlyburrito Jul 10 '15

Why do you need the debug mode flag then? Just put the logger.debug in directly if you're only logging.

0

u/[deleted] Jul 10 '15

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

1

u/psxpaul Jul 10 '15

It can be useful in instances like this:

if(debugMode) {
  logger.debug("Received: " + someFunctionThatIsSlow());
}

10

u/davedontmind Jul 10 '15

Shouldn't that be

if (logger.isDebugEnabled()) {
    logger.debug("Received: " + someFunctionThatIsSlow());
}

?

3

u/Shirkie01 Jul 10 '15

logger.debug already does that. Essentially you just checked logger.isDebugEnabled() twice.

[Debug Ref](https://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Category.html#debug(java.lang.Object))

4

u/eliasv Jul 11 '15

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.

2

u/davedontmind Jul 11 '15 edited Jul 13 '15

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.

1

u/Shirkie01 Jul 11 '15

Ah, you're right. Somehow I missed someFunctionThatIsSlow().

1

u/__notmyrealname__ Jul 10 '15

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?

6

u/dablya Jul 10 '15

I believe loggers can be reconfigured dynamically.

1

u/psxpaul Jul 10 '15

Yeah probably. I don't know what debugMode is in OP's code.

3

u/benwaffle Jul 10 '15

Isn't the point of a logger to allow you to unconditionally log but only see what you want based on the log level?

3

u/juhmayfay Jul 11 '15

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.

1

u/[deleted] Jul 11 '15

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....

3

u/solatic Jul 11 '15

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);

RTFM!

1

u/yawkat Jul 10 '15

logger.isDebugEnabled helps there :)

5

u/brbpizzatime Jul 10 '15

You may want to look into Slf4j. It's a log4j abstraction that handles all that for you

0

u/[deleted] Jul 11 '15

[deleted]

1

u/compdog Jul 11 '15

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.

1

u/[deleted] Jul 13 '15

If null is passed to the JDBC call, you'll get a more descriptive exception than either an NPE or the nonsense in the example.