Checking return values in Java « Trifork Blog / Trifork: Enterprise Java, Open Source, software solutions



Checking return values in Java « Trifork Blog / Trifork: Enterprise Java, Open Source, software solutions

The other day I made a stupid coding error. It took me the better part of an hour to track it down. We all have those moments. Blame it on a bad night’s sleep, a brain fart, or perhaps the fact that your colleague at the next desk has been whistling that tune from Gotye’s “Somebody I used to know” (you know the one) all day, completely driving you crazy and taking your focus off your code.

Anyway. Here’s my coding error:

1// If the finishedTest is an exam or a
2// practiceTest, go to the next chapter or paragraph
3getNextChapterParagraph(chapters, taskContentIdentifier);
4if (taskContentIdentifier == null) return null;
5return new Task(taskContentIdentifier, Type.ASSESSMENT);

And here’s the getNextChapterParagraph() method:

1/**
2 * Returns the next paragraph or chapter given a list
3 * of chapters and the current chapter/paragraph.
4 */
5private ContentIdentifier getNextChapterParagraph(
6    List<Chapter> chapters,
7    ContentIdentifier contentIdentifier) {
8 
9  // Do some stuff.....
10 
11  return new ContentIdentifier(
12    chapter.getStream().getId(),
13    chapter.getContentId(),
14    paragraph.getContentId());
15}

I’ve omitted and simplified some code to stick to the point, but I’m sure some of you have figured out what I did wrong by now. The getNextChapterParagraph() method doesn’t modify the ContentIdentifier instance passed as its second parameter; it returns a new one. Yet I wrote the calling code as if it did change the state of my taskContentIdentifier. D’oh!

A more common case of this is calling methods on immutable objects, like String. For example:

1String string = "this is a test";
2string.substring(10);   // Bad!

Now of course you can catch errors like this in your unit tests, which is how I found the error in the first place. But wouldn’t it be nice if there was some way to find out right when you make this mistake?

What’s wrong?

So what exactly is wrong with the code above? Simply put: the getNextChapterParagraph (and String.substring) method’s sole purpose is to return a value; it doesn’t change the objects whose references were passed to it as parameters, and it doesn’t change the state of the object it’s a method of. In other words, it has no side effects. Because of this, if we call the method, we should always do something with the return value. If not, why did we call it in the first place? (There is actually one reason you might, but I’ll discuss this later on.)

So we’d like to have the compiler or some tool warn us when we call a method that has no side effects, yet discard its return value. Any solution would have two parts:

  1. Mark a method as having no side effects (perhaps it would be possible to determine by static analysis if a method has no side effects, but that’s a different blog post)
  2. Warn when a method with no side effects is called and the return value is discarded (that is, not assigned to a variable, not used in an expression, and not passed to another method).

Enter: FindBugs and @CheckReturnValue


Read full article from Checking return values in Java « Trifork Blog / Trifork: Enterprise Java, Open Source, software solutions


No comments:

Post a Comment

Labels

Algorithm (219) Lucene (130) LeetCode (97) Database (36) Data Structure (33) text mining (28) Solr (27) java (27) Mathematical Algorithm (26) Difficult Algorithm (25) Logic Thinking (23) Puzzles (23) Bit Algorithms (22) Math (21) List (20) Dynamic Programming (19) Linux (19) Tree (18) Machine Learning (15) EPI (11) Queue (11) Smart Algorithm (11) Operating System (9) Java Basic (8) Recursive Algorithm (8) Stack (8) Eclipse (7) Scala (7) Tika (7) J2EE (6) Monitoring (6) Trie (6) Concurrency (5) Geometry Algorithm (5) Greedy Algorithm (5) Mahout (5) MySQL (5) xpost (5) C (4) Interview (4) Vi (4) regular expression (4) to-do (4) C++ (3) Chrome (3) Divide and Conquer (3) Graph Algorithm (3) Permutation (3) Powershell (3) Random (3) Segment Tree (3) UIMA (3) Union-Find (3) Video (3) Virtualization (3) Windows (3) XML (3) Advanced Data Structure (2) Android (2) Bash (2) Classic Algorithm (2) Debugging (2) Design Pattern (2) Google (2) Hadoop (2) Java Collections (2) Markov Chains (2) Probabilities (2) Shell (2) Site (2) Web Development (2) Workplace (2) angularjs (2) .Net (1) Amazon Interview (1) Android Studio (1) Array (1) Boilerpipe (1) Book Notes (1) ChromeOS (1) Chromebook (1) Codility (1) Desgin (1) Design (1) Divide and Conqure (1) GAE (1) Google Interview (1) Great Stuff (1) Hash (1) High Tech Companies (1) Improving (1) LifeTips (1) Maven (1) Network (1) Performance (1) Programming (1) Resources (1) Sampling (1) Sed (1) Smart Thinking (1) Sort (1) Spark (1) Stanford NLP (1) System Design (1) Trove (1) VIP (1) tools (1)

Popular Posts