As asked in title, can I make a 'common' public Class and some public static foo()
in it? Thanks!
views:
80answers:
5Thanks! I've tried it and it works. However, I just want to find other possibilities to fullfill it. Following answers gave me some clues.
herbertD
2010-10-18 06:49:43
+2
A:
A common way is to declare a utility class like this
package my.package;
public class Utility {
private Utility() {
}
public static void foo() {
}
}
If this class is on your classpath you always can do from everywhere
my.package.Utility.foo();
PeterMmm
2010-10-18 06:22:24
+2
A:
Yes, you can.
Where exactly do you see difficulties?
You can see the popular utility classes (such as StringUtils) in Jakarta Commons Lang for an example. Chances are that some of the very common function you are thinking of are already present in one of the Commons family of libraries.
Thilo
2010-10-18 06:23:12
As In OO programming, Object is the first thing we should manipulate, so what I am concerning is: is it 'ok' to use a `public static function()` without instantiate a real object? Thanks a lot!
herbertD
2010-10-18 06:56:43
Yes, it is okay. OO is not appropriate for everything. Or rather, in the case of StringUtils, these methods should probably have been methods on java.lang.String, but since they are not there, the best you can do is a static method somewhere else.
Thilo
2010-10-18 07:19:29
A:
If you have the slightest doubt that your requirements may change, that you might need different versions of some methods for testing etc., then use an interface and a class, e.g.:
public interface Utils {
public final static Utils INSTANCE = new MyUtils();
Foo makeFoo();
Bar transform(Foo foo)
}
public class MyUtils implements Utils {
public Foo makeFoo() { return new Foo(); }
public Bar transform(Foo foo) { return new Bar(foo); }
}
This makes it easy to switch to other implementations. And you will have less problems when you decide to start using a DI framework like Guice:
public class Client {
private final Utils util;
@Inject
Client(Utils utils) { //<--- Here Guice will inject for you what you specified
this.utils = utils;
}
}
Landei
2010-10-18 07:53:26
Dependency injection is whole new idea for me, and it too advanced to solve my problem. ^_^. Thanks!
herbertD
2010-10-18 09:44:04
My suggestion is independent from DI, I included it just as another reason why you should avoid utility classes when you are not sure. Without DI, you can simply write `Utils.INSTANCE.makeFoo()` instead of `Utils.makeFoo()`, and it gives you the same functionality as a normal utility class, just with more flexibility.
Landei
2010-10-18 12:15:00
Excuse me, you mean "without DI, I can use Utils.INSTANCE.makeFoo() that is simpler? I think Utils.makeFoo() is simpler. Thanks a lot!
herbertD
2010-10-20 07:31:30
I didn't say it is simpler, I said it is more flexible: easier testable, easy to refactor if you need different implementations etc.
Landei
2010-10-20 11:43:29