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.
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:
The other is much the same but in an instantiated class:
Sometimes you see a Singleton pattern to get an instance but only ever have one instance:
(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.