avoid using if clause

穿精又带淫゛_ 提交于 2019-12-13 07:04:53

问题


I am trying to log information within my system.Whenever logging I do a check if a state is valid and only then do I log that information.

//doing this logging all over the place in my code base. 
if(checkIsValid){
  Object obj =new Object(string1,Integer2,........String10);
  log(obj);
}

The question here is how do I refactor my code so that I don't have to repeat this block of code everywhere for logging.

One of the solution is I could write a supplementary method like this.

 method(String1,Integer2,......String10){
  if(checkIsValid){
  Object obj =new Object(string1,Integer2,.........String10);
  log(obj);
  }
}

But the downside is that I would have to pass a number of strings as arguments to my method which does not look clean at all.


回答1:


If you are using log4j for logging you can extends the logger class and overwrite the log, debug, error .... etc methods with your own validation.

If not you can do as you say: create a new method as below:

  public void validateAndLog(Object obj){
       if(checkIsValid){
          log(obj);
       }
  }

OR

 public void validateAndLog(String... strs){
           if(checkIsValid){
              log(Arrays.toString(strs));
           }
      }



回答2:


You could use a factory function for your object similar to

public Object createObjChecked(String1,......String10){
    Object obj = null;
    if(checkIsValid(String1, ..., String10)){
        obj = new Object(string1,.........String10);
        log(obj);
    }
    return obj;
}

Then you could check if the object was actually created at usage location.




回答3:


You solution is good. You are only missing passing varargs:

void myLogMethod(String format, Object args){
  if(checkIsValid){
    Object obj = new Object(format, args);
    log(obj);
  }
}

This is the kind of approach taken by slf4j. See http://www.slf4j.org/apidocs/org/slf4j/Logger.html



来源:https://stackoverflow.com/questions/31337243/avoid-using-if-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!