Let Bash make the birthday wish

One of my colleagues birthday was a few days ago (December 22). He is our network/sysadmin and is a big Linux fan (nothing surprising, all sysadmins of the world tend to be Linux fan). So I decided to write a one line bash script for him and posted it to his Facebook wall.

[ "`date | cut -d ' ' -f 2,3`" == "Dec 22" ] && echo "happy birthday to LL bhai"

What it does? Nothing serious at all. If it is run on December 22 then it will print happy birthday to LL bhai (“LL bhai” is his name, nothing related to bash).

How it does its work? Pretty simple. date command is used to get the system date. Output is piped to the cut command which splits the date string by space and retrieves field 2 and 3. Then that is compared against target "Dec 22" by using [ command which is equivalent (other than the syntactic sugar) to test command. If the comparing is true then the second part of logical and (&&) is executed which is a echo command. And that’s all.

The fun part is if this single line is placed in bash startup file (~/.bash_profile if interactive login shell and ~/.bashec if interactive but not login shell) then on every year our LL bhai will get this wish. Every time bash is run on Dec 22, this wish will be printed. Everybody may forget, but Bash will never forget his birthday.

Just a few ending notes and references:

  • Bash Guide for Beginners and Shell Programming chapter on Beginning Linux Programming might be the best places to start for complete beginners to bash scripting.
  • This is not a great script. It is possible to remove the cut command entirely by using some options to date. No doubt, there are more than one ways to do a single task.
  • It requires some changes to work on other date. First, “Dec 22” is hardcoded, and second, if the date is one digit long then the argument of cut requires changing.

Happy Linuxing.

Advertisements
Posted in Linux | Tagged | 2 Comments

Implement a true Singleton in AS3

Singleton is a design pattern that enforces that a class can have only one instance which is shared by all and provides an easy global access point to this. A few examples are:

  • In iOS the UIDevice class is a singleton which provides information about the device like its unique ID. Obviously there is not more than one device.
  • Every application running in iOS must have a single instance of UIApplication class. Naturally that is a Singleton.
  • In a game generally there is one single GameControl object which manages the main game loop. If someone can create more than one game control and can run the main loop more than once, it can damage a lot.
  • Several design patterns like Abstract Factory, Flyweight uses Singleton in their implementation.

Although Singleton provides a global access, it have two benefits over using global variable. First, it does not pollute the global name space and second, it can be lazy initialized i.e. unlike global variables it can be instantiated only when it is required.

Okay, that’s enough talking. Let’s see how we can implement a Singleton in AS3.

package
{
    public class Singleton
    {
        private static var _instance:Singleton = null;

        public function Singleton()
        {
        }

        public static function sharedInstance():Singleton {
            if (_instance == null) {
                _instance = new Singleton();
            }

            return _instance;
        }
    }
}

This is the most straight forward way to implement a Singleton. First we declare a private static variable _instance in Singleton class and then create a public static method sharedInstace(). In sharedInstance() we check whether _instance is null or not. If it is null, then sharedInstance() is called for the first time. So we instantiate the instance of Singleton. Any further call to sharedInstance() will return the _instance created earlier, instead of creating a new one. As a result every call to sharedInstance() returns the same instance.

We can test this easily.

var a:Singleton = Singleton.sharedInstance();
var b:Singleton = Singleton.sharedInstance();

if (a == b) {
    trace("a and b are same");
} else {
    trace("a and b are not same");
}

Output is naturally a and b are same.

Note that Singleton.sharedInstance() is the global access point to the shared instance that the Singleton is supposed to provide. And also the instance is not created unless sharedInstance() is called, unlike a global variable.

But we have a little problem here. Calling to sharedInstance() will return the shared _instance, but Singleton class does not prevent to create new objects of it. In fact it is fairly easy to create a new Singleton object which is not shared, something that should be enforced by the Singleton pattern.

var c:Singleton = new Singleton();
var d:Singleton = new Singleton();

if (c == d) {
    trace("c and d are same");
} else {
    trace("c and d are not same");
}

Naturally c and d are not same.

The solution of this is to make the constructor of Singleton non-public so that new Singleton() is no longer valid.

private function Singleton()
{
}

And opps, the compiler have problem with this. It is saying “A constructor can only be declared public”. Now we have a big problem. Making the constructor non-public is the approach taken by most of the languages like C++ or Java, but AS3 does NOT support non-public constructor. So in AS3 we cannot prevent the creation of Singleton object in this way. This poses the real difficulty of implementing a true Singleton in AS3.

A few approaches, all equally weird, are available to prevent the creation. Personally I like the following.

public class Singleton
{
    private static var _instance:Singleton = null;

    public function Singleton(caller:Function = null)
    {
        if (caller != preventCreation) {
            throw new Error("Creation of Singleton without calling sharedInstance is not valid");
        }
    }

    private static function preventCreation():void {
    }

    public static function sharedInstance():Singleton {
        if (_instance == null) {
            _instance = new Singleton(preventCreation);
        }

        return _instance;
    }
}

A private static method preventCreation (I wanted to name it weirdMethod) is defined and it is passed to the constructor from sharedInstance. The constructor compares the caller and throws a run time error if the caller is not preventCreation. As preventCreation is private, it is not available outside. So trying to do new Singleton() from outside will fail in run time. However, this method does not force compile time prevention.

The whole demo project can be downloaded from here.

And now some final ending notes:

  • Singleton can be generalized to create ‘n’ number of objects instead of creating 1. But that is not as common as the single instance version where n = 1.
  • Before creating a Singleton make sure that a singleton is really needed. There is a huge debate on whether Singleton should be used or not, and there are people who consider Singleton as an anti-pattern. Those discussions are beyond the scope of this current writing, neither they are specific to AS3. May be in future I will write about that too, but for now check Why Singletons are Evil and Singleton: How should it be used.
  • For a better understanding of Singleton check Design Patterns book by GoF and Wikipedia entry for Singleton.
  • There are other ways, possibly better, to implement Singleton in AS3. Check Singleton Pattern in AS3 which explains another way and discusses two common mistakes.

As always, any feedback and/or suggestion is welcome.

Update: Even this process of creating Singleton can be broken by extending Singleton as explained here. Thanks to Krilnon for pointing this out.

Posted in AS3, Design Pattern | Tagged , | 6 Comments