Enforcing an all static API in ActionScript 3

It is quite common when designing an API or system in Adobe Flex that you will identify certain areas which call for specific classes to contain an all static API.

Typically, all-static classes are utilized as helper, utility and factory classes which provide static methods for performing common utility methods.

A commonly overlooked aspect of such designs is the assumption that an all-static class will not be misused by clients, specifically via instance instantiation, as it is assumed by the designer that an all static class would never be instantiated as there are no instance members available, only static class members. This is a fair assumption. However it is not possible to guarantee this will never occur as ActionScript 3 does not support private constructors (yes, I am back on this subject yet again). Although this is an unfortunate limitation of the language it should not deter you from enforcing such restrictions.

To help facilitate these restrictions in my own designs I have created a very simple, yet effective Abstract class called AbstractStaticBase, which helper and utility classes can extend in order to ensure they are never instantiated.

Classes which contain an all static API can extend AbstractStaticBase in order to ensure they can never be instantiated. This is the only requirement.

AbstractStaticBase is lightweight as it only contains a constructor. The constructor does nothing more than create an Error object and parse the call stack to determine the fully qualified name of the concrete class which has been instantiated, the message property is then set on the Error object and thrown.

Implementation on the clients part is very straightforward as all that is required is to extend AbstractStaticBase.

Consider the following example. CalcUtil is an all static class, to ensure an instance of CalcUtil is never instantiated simply extend AbstractStaticBase as follows:

So if you want to enforce that static classes are never instantiated, simply extend AbstractStaticBase.

{Sorry, Comments are currently Closed! }