避免使用if子句 [英] avoid using if clause

查看:266
本文介绍了避免使用if子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在系统中记录信息。每当记录时,我都会检查一个状态是否有效,然后我记录该信息。 >  //在我的代码库中完成这个记录。 
if(checkIsValid){
Object obj = new Object(string1,Integer2,........ String10);
log(obj);
}

这里的问题是如何重构我的代码,使我不



其中一个解决方案是我可以编写一个这样的补充方法。

 方法(String1,Integer2,... String10){
if(checkIsValid){
Object obj = new Object(string1,整数2,......... String10);
log(obj);
}
}

但缺点是我必须通过/ />

解决方案

如果您使用log4j进行日志记录,您可以扩展logger类,并用自己的验证覆盖日志,调试,错误....等方法。



如果不能,你可以按照你的说法创建一个新的方法如下:

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

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


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.

解决方案

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));
           }
      }

这篇关于避免使用if子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆