luckysing_noobster
luckysing_noobster

Reputation: 2013

avoid using if clause

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.

Upvotes: 0

Views: 152

Answers (3)

JnRouvignac
JnRouvignac

Reputation: 787

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

Upvotes: 0

nucleon
nucleon

Reputation: 1158

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.

Upvotes: 0

Ali Helmy
Ali Helmy

Reputation: 794

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

Upvotes: 4

Related Questions