Main methods in Python, Ruby, Java stuff

Software

Main Street

I've decided to put my code snippets blog idea on hold because I don't have time to be maintaining a separate blog right now. Had I started it, this would have gone there.

Not having main methods never used to worry me, but since studying Java again I really like being able to have an application kick into action without having to create an instance of it manually.

To illustrate what I mean, here's a crappy Java application that I merely have to execute from the command line for it to display Bender's favourite words.

MainInJava.java:
public class MainInJava
{
  public static void main(String[] args)
  {
    System.out.println("Kiss my shiny metal arse");
  }
}

Now here are roughly equivalent applications written in Ruby (my formerly favourite scripting language) and Python (my formerly favourite scripting language, and now my favourite scripting language again!):

MainInRuby.rb:
#!/usr/bin/env ruby -w
class MainInRuby
  def initialize()
    puts("Hello, world!")
  end
end
MainInPython.py:
#!/usr/bin/env python -3t
class MainInPython:
    def __main__(self):
        print("Hello, world!")

If you were to run either of these example applications, nothing would happen. The initialize and main methods aren't run because merely running the application doesn't do any instantiation. Ruby and Python expect you to create and run an instance of the application in the source.

The proposed workarounds if you really want Java-ish main method equivalents in these languages are to write these lines of boilerplate outside the class.

MainInRuby.rb:
if __FILE__ == $PROGRAM_NAME
  # Put "main" code here
end
MainInPython.py:
if __name__ == "__main__":
    main()

I understand what these functions do, but for scripting languages that pride themselves on making life easier compared to heavy languages like Java, these don't seem all that intuitive or elegant.

I suppose one could argue that I've been corrupted into thinking I need a main method and that I haven't bothered to learn the Ruby or Python way of doing things. They may be onto something ^_^.

__EXIT__

Author bio and support

Me!

Ruben Schade is a technical writer and infrastructure architect in Sydney, Australia who refers to himself in the third person. Hi!

The site is powered by Hugo, FreeBSD, and OpenZFS on OrionVM, everyone’s favourite bespoke cloud infrastructure provider.

If you found this post helpful or entertaining, you can shout me a coffee or send a comment. Thanks ☺️.