QR code

Monikers Instead of Variables

  • Odessa, Ukraine
  • comments

OOPoop

If we agree that all local variables must be final, multiple returns must be avoided, and temporal coupling between statements is evil—we can get rid of variables entirely and replace them with inline values and their monikers.

OSS 117: Cairo, Nest of Spies (2006) by Michel Hazanavicius
OSS 117: Cairo, Nest of Spies (2006) by Michel Hazanavicius

Here is the code from Section 5.10 (Algorithms) of my book Elegant Objects:

public class Main {
  public static void main(String... args) {
    final Secret secret = new Secret();
    new Farewell(
      new Attempts(
        new VerboseDiff(
          new Diff(
            secret,
            new Guess()
          )
        ), 5
      ),
      secret
    ).say();
  }
}

Pay attention to the variable secret. It exists here because we need its value twice: first, as a constructor argument for the Diff, second as a constructor argument for the Farewell. We can't inline the value by creating two separate instances of class Secret, because it really has to be the same object—it encapsulates the number that we hide from the user in a number-guessing game.

There could be many other situations where a value needs to be used multiple times while remaining unmodifiable. Why do we still call these values variables if technically they are constants?

I'm suggesting we introduce "monikers" for these values, assigning them through the as keyword. For example:

public class Main {
  public static void main(String... args) {
    new Farewell(
      new Attempts(
        new VerboseDiff(
          new Diff(
            new Secret() as secret,
            new Guess()
          )
        ), 5
      ),
      secret
    ).say();
  }
}

Here new Secret() is the inlined value and secret is its moniker, which we use a few lines later.

It would be great to have this feature in Java, right?

sixnines availability badge