开发者

Reusing class after calling static methods

开发者 https://www.devze.com 2023-03-25 13:41 出处:网络
Suppose I have a class with several static void methods, for example: class MyClass { public static void doJob() {

Suppose I have a class with several static void methods, for example:

class MyClass {
    public static void doJob() {
        // ...
    }
    public static void doSmthElse() {
         // .开发者_StackOverflow社区..
    }
}

how can I modify it to call my static methods like this:

MyClass.doJob().doSmthElse().doJob();

instead of

MyClass.doJob();
MyClass.doSmthElse();
MyClass.doJob();

I know how to do it with non-static methods (just return this), but how to do it with static fields?


Well, you could do this:

// Horrible, don't do it!
class MyClass {
    public static MyClass doJob() {
        // ...
        return null;
    }
    public static MyClass doSmthElse() {
        // ...
        return null;
    }
}

At that point your code will compile, as Java allows access to static methods "via" references. The fact that you're returning null is irrelevant, because the compiler will only look at the compile-time type of the expression MyClass.doJob() in order to work out which doSmthElse() method to call; the static method will then be called without examining the return value at all.

But please don't do this - it's a really nasty code smell, as your code looks like it's doing one thing when it's actually doing another.

Options:

  • Just live with your more verbose calls
  • Extract the static methods into a class where it makes sense for them to be instance methods (this may well improve testability etc as well)
  • Import the methods statically
  • Create a larger method in MyClass which calls the three methods one after another.


You can make this class singleton and do

return getInstance();

in every method


You can create a dummy instance of you class and return this. You will use static members of class, but return a reference to regular instance (just for fun, just for code style). But I wouldn't like to use this approach.

class MyClass {

    private static int data = 0;
    private static MyClass link = null;

    public static void doJob() {
        // do job with static data such as "data"
        return checkMe();
    }

    public static void doSmthElse() {
        // do someting else with static data such as "data"
        return checkMe();
    }

    private MyClass static void checkMe() {
        if (link == null) link = new MyClass();
        return link;
    }

}


It is immpossible because there is no object you can return.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号