How to prevent the arrowhead anti-pattern

后端 未结 13 1361
南旧
南旧 2020-12-05 06:37

I\'m a bit confused about how to best refactor my code into something more readable.

Consider this piece of code:

var foo = getfoo();
if(foo!=null)
{         


        
13条回答
  •  广开言路
    2020-12-05 07:02

    try
    {
      if (getcow(getmoo(getbar(getfoo()))) == null)
      {
        throw new NullPointerException();
      }
    catch(NullPointerException ex)
    {
      return; //or whatever you want to do when something is null
    }
    
    //... rest of the method
    

    This keeps the main logic of the method uncluttered, and has just one exceptional return. Its disadvantages are that it can be slow if the get* methods are slow, and that it is difficult to tell in a debugger which method returned the null value.

提交回复
热议问题