HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Refactor to reduce code duplication

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
codeduplicationreducerefactor

Problem

I have four methods like these (here are only two of them):

def checkLeft(clickedIndex: Int): Option[Int] = {
    val leftIndex = clickedIndex - 1
    if (leftIndex >= 0 && clickedIndex % field.width != 0 && isEmptyCell(leftIndex))
      Some(leftIndex)
    else
      None
  }

  def checkRight(clickedIndex: Int): Option[Int] = {
    val rightIndex = clickedIndex + 1
    if (rightIndex < field.size && clickedIndex + 1 % field.width != 0 && isEmptyCell(rightIndex))
      Some(rightIndex)
    else
      None
  }


They all have similar structures. How I can reduce code duplication here?

Solution

For the LEFT case, you're checking that an index is above the low value of zero; for the RIGHT case, you're checking that it's below the high value of field.size. You can't really reconcile these except by combining them into a method that checks both boundaries - and there's nothing wrong with that. Now you've got

if (inBounds(theIndex) && isEmptyCell(theIndex) && ...)
    Some(theIndex)


That ... is questionable to me because you seem to be comparing a different index (clickedIndex or clickedIndex + 1) depending on LEFT or RIGHT.

I think there are errors here that you need to reconcile before going too far down the path of duplication elimination.

Code Snippets

if (inBounds(theIndex) && isEmptyCell(theIndex) && ...)
    Some(theIndex)

Context

StackExchange Code Review Q#28842, answer score: 2

Revisions (0)

No revisions yet.