Skip to content

Instantly share code, notes, and snippets.

@thieux
Last active October 9, 2018 21:32
Show Gist options
  • Save thieux/ef943b7fd925d71b17a506466b4911c4 to your computer and use it in GitHub Desktop.
Save thieux/ef943b7fd925d71b17a506466b4911c4 to your computer and use it in GitHub Desktop.
Simplified refactoring

Refactoring from real life

Nested duplicate

Response foo(a.Error error) {
  if (error == a.OK) {
    response = new Response()
    process(response)
    response.setId(id)
    response.setError(b.OK)
  } else {
    response = new Response()
    if (error == a.ERROR1) {
      response.setId(id)
      response.setError(b.ERROR1)
    } else if (error == a.ERROR2) {
      response.setId(id)
      response.setError(b.ERROR2)
    } else {
      response.setId(id)
      response.setError(b.UNKNOWN_ERROR)
    }
  }
  return response
}

=>

Response foo(a.Error error) {
  response = new Response()
  if (error == a.OK) {
    process(response)
  }
  response.setId(id)
  response.setError(mapToB(error))
  return response
}
b.Error mapToB(a.Error error) {
  if (error == a.OK) {
    return b.OK
  }
  if (error == a.ERROR1) {
    return b.ERROR1
  }
  if (error == a.ERROR2) {
    return b.ERROR2
  }
  return b.UNKNOWN_ERROR
}

Wrongly correlated values

if (amount == null) {
  response.setFooAmount(null)
  response.setBarAmount(null)
} else if (fooRate == 0.0) {
  response.setFooAmount(null)
} else if (barRate == 0.0) {
  response.setBarAmount(null)
} else {
  response.setFooAmount(amount / fooRate)
  response.setBarAmount(amount / barRate)
}

Changes semantics

=>

response.setFooAmount(compute(amount, fooRate))
response.setBarAmount(compute(amount, barRate))

double compute(Double amount, Double rate) {
  if (amount == null) {
    return null
  }
  if (rate == 0.0) {
    return null
  }
  return amount / rate
}

Composed map

stream.map(x -> (x + 1) * 2).collect(Collectors.toList())
stream.map(x -> x).map(x -> (x + 1) * 2).collect(Collectors.toList())
stream.map(x -> x + 1).map(x -> x * 2).collect(Collectors.toList())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment