aspose file tools*
The moose likes Beginning Java and the fly likes Reducing nesting: A good practice? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Reducing nesting: A good practice?" Watch "Reducing nesting: A good practice?" New topic
Author

Reducing nesting: A good practice?

Yiyan Shou
Greenhorn

Joined: Jan 19, 2012
Posts: 2
Hello everyone,

After reading through John Smiley's Learn to Program With Professor Smiley I decided to register for an account here. Having taught myself Java out of this book, I feel that I may be missing knowledge about good programming practices and style. I have heard that code with more than three levels of nesting should be rewritten to improve readability. Below is a particularly nested part of my code (The nature of this question demands a rather large snippet of code. You can skip it if its too long). I tried to make maximal use of else statements to reduce the number of conditions I needed in the if statements. Would it have been better to delegate the logical function of the else statements to additional conditions in if statements instead to reduce nesting? If anyone is wondering, this is part of a method that prompts the user to enter a mathematical expression and checks the input for syntax errors.



Rameshwar Soni
Ranch Hand

Joined: Feb 03, 2011
Posts: 247
Welcome to JavaRanch

Nesting can be done on many things like loops, classses and the conditional statement (if-else) which you have done.

I really don't know whether nesting has to do something with the performance i.e. whether it is a good practice or not, and i think it also depends on the program which you are writing
i.e. at some places we don't have any choice and have to use nesting

But it is always better to use switch statement instead of nested if-else
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 13868
    
  10

Welcome to the Ranch.

One thing that I notice in your code is that you are using | and & for "or" and "and" operations. You should normally use || and && instead. The single | and & are bitwise operators, that also work on boolean expressions. The difference between the single-character and double-character versions is that the double versions are short-circuiting, while the single versions are not.

That means if you do for example "A && B", and A is false, Java will not evaluate B at all, since if A is false, it already knows that the result of the expression is going to be false (no matter if B is true or false). If you do "A & B", Java will always evaluate both A and B, which is normally not necessary.

I would write an if-statement like this:

in a shorter way, for example like this:

This means: if the character is not a digit and if it is not one of the characters in the string ".+-*/()"

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19541
    
  16

Jesper de Jong wrote:

String.contains isn't overloaded to take a char, only a CharSequence. There are two fixes:



SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

[quote=Rameshwar Soni
But it is always better to use switch statement instead of nested if-else

No, that's not true.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Yiyan Shou wrote:I have heard that code with more than three levels of nesting should be rewritten to improve readability.


Just be aware that that's just a guideline. There's no need to be strict about "no more than N levels of nesting." The point is if you see a lot of nesting in your code and notice that it's getting hard to read, that should be a red flag suggesting you might want to refactor a bit.

Would it have been better to delegate the logical function of the else statements to additional conditions in if statements instead to reduce nesting?


I'm not going to comment on this particular code, but in general, a more common way to reduce nesting is to break out the next nesting level into its own method.

If you're talking about doing


then IF A, B and C can be expressed simply (like by a single variable each), and IF your logic is such that you can do that, then, yes, the single if is more readable than multiple nested ifs. However, that conversion isn't always possible:


In this case, the logic isn't simply "if A && B, do stuff". Sure, you could break it out into "if (A && B) { ... } else if (A && !B) { ... }" but that gets hard to follow as well. This is when you may want to break out deeper levels of nesting in to their own methods. (Though for the simple 2-level if above, I wouldn't consider it necessary. I just wanted a simple example to show how some cases don't structurally map to a simple if statement.)
Wendy Gibbons
Bartender

Joined: Oct 21, 2008
Posts: 1106

I know it isn't relevant to your question but i would extract response.charAt(i) and response.charAt(i-1) to suitably named variables, like currentChar and prevChar.

it would have made it much easier for me to read.
dennis deems
Ranch Hand

Joined: Mar 12, 2011
Posts: 808
One thing about your code that jumps out at me is the amount of repetition. In several places you are making same evaluation. When I see this in my code, my first thought is that I should see whether this logic could be moved into a common method. Almost invariably, this enhances readability. When this repetition occurs in a series of conditionals, there's a good chance we are making unnecessary evaluations. For example, at line 30 it is already known whether the char is '(' or ')', because this is the first thing the code determined about the char.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Dennis Deems wrote:One thing about your code that jumps out at me is the amount of repetition. In several places you are making same evaluation. When I see this in my code, my first thought is that I should see whether this logic could be moved into a common method. Almost invariably, this enhances readability. When this repetition occurs in a series of conditionals, there's a good chance we are making unnecessary evaluations. For example, at line 30 it is already known whether the char at i is '(' or ')', because this is the first thing the code determined about the char.


Absolutely.

In general, if you find you're executing the same 2 or 3 steps more than once (basically anything more than evaluating a single variable or calling a single method), there's a good chance you'd be better off moving that code into its own method, or creating a variable to hold that expression's value. It makes your code easier to read (encapsulating multiple smaller steps in one higher-level step) and easier to maintain (you only need to change it in one place to enhance it or fix a bug).

Additionally, it may be the only way to get correct behavior. For instance, when you call BufferedReader.readLine(), if you need to use that result more than once, you'll have to put it in a variable. You can't just call readLine() again because you won't get the same result. (readLine() is not idempotent.)

Finally, though this is less common, you may get a performance improvement by not calling the same method multiple times. Most of the time, this is not a valid reason to avoid additional method calls, but if the method is very expensive (we're talking billions of CPU cycles) or does a lot of I/O, it may benefit your app's overall performance if you don't make unneeded duplicate calls.
Yiyan Shou
Greenhorn

Joined: Jan 19, 2012
Posts: 2
Thank you for all the valuable input. I might have gotten too entrenched in trying to make each method perform one complete function and overlooked ways to break a function into multiple methods as means of simplification. I will keep these things in mind.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Reducing nesting: A good practice?
 
Similar Threads
I am lost
why doesn't this work?
need help with method
Code Snippet Help
Printing a String object without using loop