开发者

Any easy way to get out of a Java block?

I was just wondering if there is any way to get out of a Java block. It can be any block - if block, for block or even a simple {}. This is because I often come across such situations

{
  retCode = performSomeThing();
  if(retCode == SUCCESS)
  {
    retCode = performSomethingElse();
    if(retCode == SUCCESS)
    {
         . . . 
          . . . 
    }
   }
}

This multiple levels of indentation clutters up the code I write.

Instead I need some way to do this

if((retCode = performSomething()) != SUCCESS)
  GET_OUT_OF_BLOCK
if((retCode = performSomethingElse()) != SUCCESS)
  GET_OUT_OF_BLOCK

Based 开发者_开发知识库on the value of retCode I will perform any required processing outside the block. Would be nice if it doesn't involve writing that block within a try-catch block, creating a new exception type, throwing it and then catching it.


The correct construct to use is return. This implies that what is a block in your example should really be a method, but that is a good idea anyway - methods that are so long that they contain multiple, complicated control flow alternatives are an antipattern. Do yourself a favor and switch to "one objective per method" today! <end of evangelism>


have a look at break and continue


You seem to use the nested ifs here for error handling.

If you switch to structured exception handling, maybe you could get rid of the deeply nested if constructs at all.

This would, however, imply that performSomeThing() and performSomethingElse() would throw exceptions instead of returning error codes.


<again evangelism>

Don't do that. In my opinion the correct way for a bloc is one start at the beginning, one stop at the end, full stop.

Even with a method, you should have only one return at the end.

Inside the bloc, you write the flow of the running instructions with if and so on, from the start to the end, the more simple you can (so, sometimes, you write return or break etc inside it, ok ; it should be exception).

It's best (but not mandatory) to write normal completion statements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜