Wednesday 5 October 2022

Paving the on-ramp

Brian Goetz wrote an interesting article1 about what Java could do to lessen the big bulk of context needed for first-timers to write a simple Hello-World program in java. The whole "public static void main(String[] args)" conundrum.

I especially like the following quote (out of context) in de article:

“We will never be able to satisfy programmers’ insatiable appetite for typing fewer keystrokes, and we shouldn’t try, because the goal of programming is to write programs that are easy to read and are clearly correct, not programs that were easy to type.”

So I went and tried to see what's the absolute minimum that still compiles in Java. Of course, the "real" main method is hidden in the Main class. And the class below is in the nameless package.

class MyProgram extends Main {
  void main() {
    println("Hello, world.");
  }
}

The hidden "Main" class looks like this, and can be safely ignored (for now) by new programmers:

/**
 * Hello world!
 */
public class Main {

  public void println(Object x) {
    System.out.println(x);
  }

  public static void main(String[] args) {
    new MyProgram().main();
  }
}

Added benefit, you can simply "run" this class, as its parent class has a "public static void main(String[] args)".

Also, the parent class has a "println" method, so we do not need to import System.out.println as well.

Admittedly, this is all a bit "hacky", where we just hide what we don't want beginning programmers to know in another class. But hey, hiding implementation details that are not important to the current "thing", is one of the core principles of Software Design, isn't it?

Updated 2023/04/17

An example in JDK 21

The reference [1] is implemented in JDK 21, using reference [2].

A simple program can now look like this:

void main() {
    System.out.println("Hello, World!");
}

Updated 2024/02/20

References

[1] Paving the on-ramp (Brian Goetz September 2022)
https://openjdk.org/projects/amber/design-notes/on-ramp
[2] JEP 445: Unnamed Classes and Instance Main Methods (Preview)
https://openjdk.org/jeps/445

No comments:

Post a Comment