GhostCat
GhostCat

Reputation: 140467

How to avoid code duplication without turning to boolean switch parameter?

I just found the following code:

public ThingId foo1(Map<String, Object> properties) {
  checkSomething();
  validateA(properties);
  validateB(properties);
  ...
  validateX(properties);
  return createTheThing(properties);
}

and

public ThingId foo2(Map<String, Object> properties, MoreStuff stuff) {
  checkSomething();
  validateB(properties);
  ...
  validateX(properties);
  return createTheThing(properties, stuff);
}

So the two method bodies were almost identical, besides foo2() not calling validateA().

Trying to reduce code duplication, I turned to

private void checkAndValidate(Map<String, Object> properties, booelean validateA) {
  checkSomething();
  if (validateA) {
    validateA();
  }
  validateB(properties);
  ...
  validateX(properties);
}

So that foo1() and foo2() can both use that new method. But I really dislike that boolean parameter there.

Any idea, anybody?

Upvotes: 1

Views: 276

Answers (2)

Jens
Jens

Reputation: 69450

You can put the validations in a new method:

private void foo3(Map<String, Object> properties) {
  validateB(properties);
  ...
  validateX(properties);    
}


public ThingId foo1(Map<String, Object> properties) {
  checkSomething();
  validateA(properties);
  foo3(properties);
  return createTheThing(properties);

}

public ThingId foo2(Map<String, Object> properties,MoreStuff stuff) {
  checkSomething();
  foo3(properties);
  return createTheThing(properties,stuff);
}

Upvotes: 2

Antony Dao
Antony Dao

Reputation: 425

Nice question! I also wonder about this. Below is what I usually do, not the best but can reduce a half times call method with boolean parameter.

private void checkAndValidate(Map<String, Object> properties, booelean validateA) {
  checkSomething();
  if (validateA) {
    validateA();
  }
  validateB(properties);
  ...
  validateX(properties);
}

private void checkAndValidate(Map<String, Object> properties) {
    checkAndValidate(properties, false);
}

Upvotes: 2

Related Questions