Question

Now that I've gotten into a dependency injection groove, I find main methods for different applications all look basically the same. This is similar to stuff you might find on the Guice documentation, but I'll put an example here:

public class MyApp {
    public static void main(String... args) {
        Injector inj = Guice.createInjector(new SomeModule(),
                       new DatabaseModule()
                       new ThirdModule());
        DatabaseService ds = inj.getInstance(DatabaseService.class);
        ds.start();

        SomeService ss = inj.getInstance(SomeService.class);
        ss.start();

        // etc.
    }
}

For multiple applications I have main methods that all look just like that. But now, lets say I want to make a brand new app, that, say, reuses my DatabaseModule. I pretty much have to copy and paste the main method and make appropriate changes... I view copy-paste as a code smell. Further, lets say I realize I should probably be putting shutdown hooks in, now I have to go through and change every main method in all my applications to attach shutdown hooks to each service.

Is there some good way to template this process and minimize the boilerplate?

Was it helpful?

Solution

Nothing about the code example in your question suggests the need for automation. Every Main method is going to be different.

Of course, if you had a database, and you were writing data access code, you might realize that a lot of this code looks almost exactly the same ("CRUD" methods), and you might be tempted to write a code generator that reads your database table schemas and generates classes that correspond to the entities in each table (customers, for example). You would then have the equivalent of an Object-Relational Mapper, arguably a worthy pursuit.

Some programming environments such as Visual Studio have the ability to store code snippets, and even come with a template code generator (T4). But the point of automation is to save time. Consult this chart first, before writing the template:

Is it worth the time?

http://xkcd.com/1205/

Licensed under: CC-BY-SA with attribution
scroll top