How to encapsulate the helper functions(commonly u

2019-05-13 20:33发布

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

what's the best practice to deal with them?

7条回答
Anthone
2楼-- · 2019-05-13 21:37

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.

查看更多
登录 后发表回答