Conditional logging with minimal cyclomatic complexity

前端 未结 12 1940
情歌与酒
情歌与酒 2020-11-27 10:58

After reading \"What’s your/a good limit for cyclomatic complexity?\", I realize many of my colleagues were quite annoyed with this new QA policy on our project: no more 10

12条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 11:34

    Maybe this is too simple, but what about using the "extract method" refactoring around the guard clause? Your example code of this:

    public void Example()
    {
      if(myLogger.isLoggable(Level.INFO))
          myLogger.info("A String");
      if(myLogger.isLoggable(Level.FINE))
          myLogger.fine("A more complicated String");
      // +1 for each test and log message
    }
    

    Becomes this:

    public void Example()
    {
       _LogInfo();
       _LogFine();
       // +0 for each test and log message
    }
    
    private void _LogInfo()
    {
       if(!myLogger.isLoggable(Level.INFO))
          return;
    
       // Do your complex argument calculations/evaluations only when needed.
    }
    
    private void _LogFine(){ /* Ditto ... */ }
    

提交回复
热议问题