Skip to content

Recipe to simplify code when a similar expression is used in both values of a ternary operator #695

@greg-at-moderne

Description

@greg-at-moderne

What problem are you trying to solve?

Increase code readability.

Describe the situation before applying the recipe

        return s2.length() < s1.length() ? s2.toString() : s1.toString();

Describe the situation after applying the recipe

        return (s2.length() < s1.length() ? s2 : s1).toString();

Context

The change is not always safe to be made. This might result in compilation errors. Sketch of a situation when the change shouldn't be applied as it's illegal:

interface Hotel { int roomNumber(); }
interface Apartment { int roomNumber(); }

class A {
  int count(Object venue) {
     return venue instanceof Hotel ? ((Hotel) venue).roomNumber() : ((Apartment) venue).roomNumber();
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions