These functions may be hard to fit into a specific class,
what's the best practice to deal with them?
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).
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.
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.
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.
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...
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.
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
来源:https://stackoverflow.com/questions/2487429/how-to-encapsulate-the-helper-functionscommonly-used-apis-in-a-oop-language-li