Saturday, November 15, 2008

Java Hack: creating multiple classes within one file

I know there are plenty of people out there that don't really like java, and also plenty that do. Those that do says Java is easier to program, but the most good point is that java compilers/interpreters must follow a very strict rule of implementation, such that java code can run on any machine without a problem. now that sounds good, but Java is also a very strict programming langauge, and one the things that I have been having some problem with is they don't allow you to create multiple classes within one file, thinking that by having each file a separate class, everything looks more clear. While that is true, it also become a pain in the ass when you're dealing with a huge program with thousands of classes, which implies thousands of files, and each single one of them are listed in your Package Explorer, and some of them are so small you wonder why they have to be listed as a single file at all. so i figured out a trick to convert multiple classes in java into one file, breaking that rule.

the idea of putting multiple classes inside one is to convert a java class into what C++ refers to as a namespace, a live package that has both static and instance of itself, and putting all the other classes you want to conceal into the file as private member classes of the "namespace". This is the key idea of how to break from the one file one class rule. here is the procedure:

1. copy/create a private class inside your "namespace" class
2. write a public class generator function for each private class that is in the namespace class. the generator function will take all the arguments for the constructor and pass it to the private class constructor. it returns the instance once it is generated
3. create a public singleton instance of the namespace class. note that static instance does not work here.

and wala! now whenever you want to create a new class that is declared in the namespace class, just call the singleton instance and its generator function. and my friends, you have just turned a java class into a C++ namespace