Preprocessor blocks

If you’re using Netbeans (and I’m sure you are after reading all my ravings about it) then you can make use of it’s superb preprocessor capabilities. Preprocessing is a way to modify your source code depending on what platform you’re compiling for as target.

Let’s say that you want to use the same java source file and support both newer midp 2 phones and older nokia midp1 phones. In Netbeans, you can easily add an extra configuration to your project to support a different platform. This is also a smooth way to test midlets in different emulators, just switch configuration with a click and the correct emulator will launch when running your midlet. Anyway, in your source code you can define a preprocessor block like this:

//#ifdef Nokia

public class Main extends FullCanvas {

//#else

public class Main extends Canvas {

//#endif

By selecting a project configuration the IDE will automatically “comment-out” the preprocessor blocks that aren’t valid. So if we select our Nokia configuration, the start of the standard Canvas class will be commented. Simple, but really useful! If you want, you can compile all of your configurations at the same time. Netbeans will then compile several .jar and .jad files, a pair for each configuration in different destination directories, and for each compilation it will modify the sorce to include the valid preprocessor blocks. Great when you’re porting your midlet to a lot of obscure phone platforms!

Preprocessor blocks could also easily be used to support different languages, different screen sizes etc.