views:

197

answers:

7

These functions may be hard to fit into a specific class,

what's the best practice to deal with them?

+1  A: 

The common practise is to create a class with static methods.

I prefer not to do this, but rather instantiate a class and then call the methods on it. Why ? Because I can then customise that instance in various fashions. To do this with static methods would require you to pass the customisation in with each method call.

My thinking about utility classes is that I don't particularly like them. Whenever I create one, I stop and think carefully as to whether this utility actually belongs in one of the objects I'm modelling, and if it's not a nice fit, perhaps my modelling isn't correct.

Brian Agnew
+1  A: 

I would recommend creating a Util class and dumping any static function that doesn't fit any where else. You should still divide the functions into groups based on what they're used for. Like GUI API, Database API, etc...

jex
Can you illustrate how to group the functions?
+2  A: 

For short and obvious helper functions, I find that the method itself provides encapsulation enough. And where else would you put them other than a dedicated static class? Yes, many source checkers admonish you for having all-static classes, but if they can't suggest anything better, you should just ignore that. Objects and classes are tools, there is no reason to apply them religiously as the One True Way - there very seldom is one anyway.

Kilian Foth
A: 

The first thing to do, of course, is try to find an (appropriate) place for them to fit within a class structure.

But if there is none, don't shoe-horn, create a third class with helpers. There are two primary strategies for this:

The first strategy employs static methods:

public class FooHelper
{
    public static Bar doSomething(Foo) {
    }
    /* ... */
}

// usage:
Bar b = FooHelper.doSomething(fooInstance);

The other is much the same but in an instantiated class:

public class FooHelper
{
    public Bar doSomething(Foo) {
    }
    /* ... */
}

// usage:
FooHelper fh = new FooHelper();
Bar b = fh.doSomething(fooInstance);

Sometimes you see a Singleton pattern to get an instance but only ever have one instance:

public class FooHelper
{
    private static FooHelper theInstance = new FooHelper();

    public static FooHelper getInstance() {
        return theInstance;
    }

    public Bar doSomething(Foo) {
    }
    /* ... */
}

// usage:
FooHelper fh = FooHelper.getInstance();
Bar b = fh.doSomething(fooInstance);

(Note that that's the simplistic Singleton implementation, which of the Singleton implementations is probably appropriate for helpers. It's not appropriate for all Singleton classes.)

There are some substantial advantages to instantiated classes over static functions, not least that helpers can be extended just like any other class. Think of the helper as a thing in its own right, a facilitator. And we model things as classes with instances in the class-based OOP paradigm.

T.J. Crowder
+2  A: 

Depending on the purpose of those helper functions, you may want to take a look at under each Apache Commons. If those are for example functions which should remove java.lang.* related boilerplate code, then have a look at Commons Lang (Javadocs here). The same exist for java.io.* boilerplate in flavor of Commons IO (Javadocs here) and java.sql.* by DbUtils (Javadocs here).

If those helper functions have really specific purposes and can't reasonably be reused in completely different projects, then I would go ahead with Esko's answer as provided in this topic.

BalusC
Are they all static methods or object methods?
It's mixed. But usually you'd pick one of the Apache Commons instead of homegrowing "helper functions". I name, DbUtils http://commons.apache.org/dbutils/apidocs/index.html, IO http://commons.apache.org/io/apidocs/index.html and Lang http://commons.apache.org/lang/api-release/index.html The classes ending with "Utils" contain only static methods. E.g. DbUtils, IOUtils, StringUtils, etc.
BalusC
I have to downvote recommending Apache Commons in general since it's really a 50:50 chance on if you find something useful or not. There's certainly a lot of gems in there but there's also lots of bad and outdated stuff too, for example the worrying lack of Generics at this point is just inexcusable - even Java 5 which introduced them has reached EOL!
Esko
@Esko: there's indeed outdated stuff in between, but that doesn't apply on DbUtils, IO and Lang. The lack of generics is in fact only in majority applicable on Commons Collections, but for that we nowadays have Google Collections http://code.google.com/p/google-collections/
BalusC
@BalusC: And Google Collections is part of Guava http://code.google.com/p/guava-libraries/. I wouldn't mind seeing a complete structural rewrite of Commons with modern paradigms but I also know that's like hoping for someone to change all cars to electric ones overnight - it's just not going to happen.
Esko
@Esko: True. I wasn't trying to insinuate that there's not another option, if you (or others) thought that.
BalusC
@BalusC: Didn't mean that at all, I'm just one of those who get a bit should I say aggravated when people repeat patterns in their answers without much -if any- explanation, even if the provided pattern is very likely to be common knowledge. This isn't a personal attack against you, there's just some things that really pull the wrong strings in me.
Esko
@Esko: you're right. It's sunday, I just waked up with little headache and I was been too lazy to post a bit more detail into the answer. This is by the way also not the average way I post answers.
BalusC
BalusC uses Edit Post! It's super effective! BalusC gains +1 upvote!
Esko
Rofl, thank you :)
BalusC
+4  A: 

I suppose you mean methods instead of functions? You should really imagine the word static doesn't exist in Java world, there really isn't a case where static would actually do you anything good in the long run.

I'm actually currently facing a similar problem, I have a whole bunch of API methods I want to give out for users to meddle with but I want to hide the actual methods underneath to hide the implementation details.

The problem of course is that if I just cram everything into one class, it becomes humongous and hard to use even with the best autocompletion tools available. The problem you have most likely really isn't about where to put those methods but how to present them to the user.

To solve that I'd suggest you create a hierarchy of objects where you access your helper methods by calling myUtil.someGroup().someMethod(param1, param2); This is actually how some API:s already work, for example popular Web framework Apache Wicket is configured by using Settings object which uses composition to allow itself to have multiple groups of distinct features.

To really flesh out this from theory to a working example, lets assume you have a bunch of image manipulation methods which either transform the image's dimensions or change its properties like color, brightness and contrast. Instead of having this

public class ImageUtil {

    public static BufferedImage adjustHue(float difference,
                                          BufferedImage original) {
        /* ... */
        return adjusted;
    }

    public static BufferedImage adjustBrightness(float difference,
                                                 BufferedImage original) {
        /* ... */
        return adjusted;
    }

    public static BufferedImage adjustContrast(float difference,
                                               BufferedImage original) {
        /* ... */
        return adjusted;
    }

    public static BufferedImage setHeight(int newHeight,
                                          BufferedImage original) {
        /* ... */
        return adjusted;
    }

    public static BufferedImage setWidth(int newWidth,
                                         BufferedImage original) {
        /* ... */
        return adjusted;
    }

}

you should instead have these interfaces to describe each set of operations

public interface IImageColorOperations {

    BufferedImage adjustHue(float difference, BufferedImage original);

    BufferedImage adjustBrightness(float difference, BufferedImage original;)

    BufferedImage adjustContrast(float difference, BufferedImage original);

}

public interface IImageDimensionOperations {

    BufferedImage setHeight(int newHeight, BufferedImage original);

    BufferedImage setWidth(int newWidth, BufferedImage original);

}

and an accompanying separate class for each interface which you instantiate in your "main" image utility class like so

public class ImageUtils {

    private final IImageDimensionOperations dimension;
    private final IImageColorOperations color;

    public ImageUtils() {
        this(new ImageDimensionOperations(),
             new ImageColorOperations());
    }

    /**
     * Parameterized constructor which supports dependency injection, very handy
     * way to ensure that class always has the required accompanying classes and
     * this is easy to mock too for unit tests.
     */
    public ImageUtils(IImageDimensionOperations dimension,
                      IImageColorOperations color) {
        this.dimension = dimension;
        this.color = color;
    }

    /* utility methods go here */

}

But wait, this isn't all! There's now two paths to go, you can decide for yourself which one you'd like to take.

First, you can use composition to expose the interface methods directly:

public class ImageUtils implements IImageDimensionOperations,
                                   IImageColorOperations {

    private final IImageDimensionOperations dimension;
    private final IImageColorOperations color;

    public ImageUtils() {
        this(new ImageDimensionOperations(),
             new ImageColorOperations());
    }
    /* etc. */
}

With this, you just need to delegate the the calls to various methods to the actual operation class. Downside to this is that if you add another method, you have to modify both this utility class and the underlying implementation class.

Your second choice is to expose the operation classes themselves directly (that's why I added those finals there!):

public class ImageUtils {

    public final IImageDimensionOperations dimension;
    public final IImageColorOperations color;

    public ImageUtils() {
        this(new ImageDimensionOperations(),
             new ImageColorOperations());
    }    

    public ImageUtils(IImageDimensionOperations dimension,
              IImageColorOperations color) {
        this.dimension = dimension;
        this.color = color;
    }

    /* Nothing else needed in this class, ever! */

}

by doing this you get those nice looking calls such as

BufferedImage adjusted = imageUtils.color.adjustHue(3.2f, original);

and when you add some method to either of the interfaces, you already have them available in your image utility class without any additional modification. Yes, generally public fields are a big no-no in Java, however I do think that in this case that's not such a bad thing, especially with the finals marking the fields as unmodifiable (at least in theory).

Esko
That's an interesting twist.
BalusC
A: 

You should take a look at Google Collections and Guava as they have some features which were normally provided as static methods in complete OO style, like

Willi