6
\$\begingroup\$

I have class that handles HTTP requests:

public final class RestHttpClient {

    /*there is no fields*/

    /**
     * @param mhttp - HTTP request that need to send
     * @return HttpResponse, that contains information about server response
     */
    public HttpResponse sendRequest(final HttpRequestBase mhttp) throws IOException {
        /*do stuff and get response from server*/

        return response;
    }

    /*there a few more helpful methods*/
}

For the one hand - there is no need in instance of class, so I can use static methods. But for another hand singleton looks more reusable. So, I'm not sure which way to choose.

What is more readable and reusable? Static or singleton? Or should I just don't care about it and allow user to create instance of class?

\$\endgroup\$
1

3 Answers 3

7
\$\begingroup\$

This:

Or should I just don't care about it and allow user to create instance of class?

If you plan to write unit tests, which is recommended these days: for your class AND the code that will use it.

http://googletesting.blogspot.co.uk/2008/05/tott-using-dependancy-injection-to.html

\$\endgroup\$
2
  • \$\begingroup\$ Yes, I'm planning, but doesn't have experience yet. Read this article, but will there be problems with static methods? \$\endgroup\$ Mar 30, 2012 at 17:01
  • \$\begingroup\$ Basically it will be hard to mock static methods. And mocking would be an appropriate way of testing this kind of functionality. Google "singleton static mock" and read opinions of people who have more experience than me. \$\endgroup\$
    – Den
    Mar 30, 2012 at 20:45
4
\$\begingroup\$

If you don't need instance variables (even singularly) then go static methods, it will simplify your code since you won't have to deal with the logistics of singletons. Also, since your example is about http traffic, it will already have a distinct start and stop. So I would either use static methods or just a standard class if you need special awareness of the user.

\$\endgroup\$
3
\$\begingroup\$

According to your replies, I think answer should be:

It's shouldn't be static methods. Because:

  1. static is something common for all instances. Of course, their do the same task, but each instance should do it's own (just for clarification).
  2. There will be a problems with inheritance and unit tests.

It's definately shouldn't be singleton. Because:

  1. There is no need in such limitations.
  2. Problems with inheritance

So, looks like I should use instances.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.