Skip to content

Recipe to extract the common code if both if and else start with the same statement #681

@greg-at-moderne

Description

@greg-at-moderne

What problem are you trying to solve?

Code readability.

What precondition(s) should be checked before applying this recipe?

  • Only applicable if the if condition doesn't have any side-effects. Or this needs special handling

Describe the situation before applying the recipe

        if (score >= 50) {
            System.out.println("Checking eligibility...");
            System.out.println("You passed!");
        } else {
            System.out.println("Checking eligibility...");
            System.out.println("You failed.");
        }

Describe the situation after applying the recipe

        System.out.println("Checking eligibility...");
        if (score >= 50) {
            System.out.println("You passed!");
        } else {
            System.out.println("You failed.");
        }

Context

  • Similarly, the same could be done for trailing statements.
  • As a very special case, if both branches have the same code, this would eventually get rid of the if.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Recipes Wanted

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions