Skip to content

Refactor repeated if/else if branches in push logic to loop for maintainability #943

@kheygetyan

Description

@kheygetyan

In the current implementation, the following code repeats almost the same branch logic four times:
Static analyzers report this as a SIMILAR_BRANCHES issue due to the high duplication.

            if (this.tryPattern[direction][0].call(this, itemCollision, gridsterItem)) {
                this.pushedItemsOrder.push(itemCollision);
                pushedItems.push(itemCollision);
            }
            else if (this.tryPattern[direction][1].call(this, itemCollision, gridsterItem)) {
                this.pushedItemsOrder.push(itemCollision);
                pushedItems.push(itemCollision);
            }
            else if (this.tryPattern[direction][2].call(this, itemCollision, gridsterItem)) {
                this.pushedItemsOrder.push(itemCollision);
                pushedItems.push(itemCollision);
            }
            else if (this.tryPattern[direction][3].call(this, itemCollision, gridsterItem)) {
                this.pushedItemsOrder.push(itemCollision);
                pushedItems.push(itemCollision);
            }
            else {
                makePush = false;
                break;
            }

The same logic can be expressed more concisely with a loop, which improves readability and maintainability:

let matched = false;
for (let patternIndex = 0; patternIndex < 4; patternIndex++) {
  if (this.tryPattern[direction][patternIndex].call(this, itemCollision, gridsterItem)) {
    this.pushedItemsOrder.push(itemCollision);
    pushedItems.push(itemCollision);
    matched = true;
    break; // first match found, no need to check the rest
  }
}

if (!matched) {
  makePush = false;
  break;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions