Singleton without any state

anti-patternsdesign-patterns

I worked on a project and found a working solution, but now I got some questions on how I solved some problems in the code. First of all, I am no expert in design patterns, but I know the (anti-)pattern of singletons and normally I avoid them. But what I use quite often, are static helper / utility methods.

So the project I've been working on is based on the Atlassian Plugin SDK. I implemented servlets, accessed some data via Atlassian components, all pretty straight forward. When it comes to the point of rendering pages, the Atlassian platforms use Apache Velocity. So I build my context map and access the objects in Velocity, everything is fine. At some point, I want to generate URLs to link to other servlets or pages. So, I create a class with static url generation methods. Sadly, I cannot access those methods in Velocity, because there is no instance I could pass to the Velocity context (which defines the scope). But Velocity allows me to use static methods via instances of the class. The resulting class looks like this (java code):

public class Urls {
    private static Urls Singleton = new Urls();

    public static Urls getInstance() {
        return Singleton;
    }

    private Urls() { }

    public static String getBaseUrl() { ... }

    public static String forUserProfile(ApplicationUser user) { ... }

    ...
}

Now, in my regular java code, I can simple use the static method:

String myUrl = Urls.forUserProfile(myUser);

But I can also pass my singleton to the velocity context …

context.put("urls", Urls.getInstance());

… to use it in my Velocity template:

<a href="$urls.forUserProfile($myUser)">User profile</a>

I used this 'pattern' or similar ones several times in my project. Is there any name for something like this? I assume this is kinda rare, because normally one could simply access the static methods. Do you think there are any big disadvantages I forgot? Any reason not to use this way? Any better ways?

Best Answer

A singleton is a fancy kind of global state.

Your Urls isn't usefully a singleton, because it has no state. You may as well just not instantiate it in normal code.

public class Urls {
    public Urls() { }
    // static methods ...
}

context.put("urls", new Urls());