1934

All static methods or a single instance?

Question:

Sometimes, I come up with situations where a single instance of a class is enough, thanks to collections. An example would be my Decoder class:

public class Decoder { private static final Decoder instance = new Decoder(); private final HashMap<Client, State> states = new HashMap<Client, State>(); private Decoder() { } public Packet decode(Client client, ByteBuffer data) { return null; } }

But I was thinking, why not just make it so it looks something like:

public class Decoder { private static final HashMap<Client, State> states = new HashMap<Client, State>(); public static Packet decode(Client client, ByteBuffer data) { return null; } }

Both designs effectively accomplish the same thing. Is there any practical difference in the two? When would I use one over the other? Thanks.

Answer1:

I would use all static methods, unless you see the need to implement an interface e.g. so you can mock out or replace your instance.

public enum Decoder implements IDecoder { INSTANCE; private final Map<Client, State> states = new HashMap<Client, State>(); public Packet decode(Client client, ByteBuffer data) { return null; } }

or

public enum Decoder {; private static final Map<Client, State> states = new HashMap<Client, State>(); public static Packet decode(Client client, ByteBuffer data) { return null; } }

Answer2:

If you want to unit test a class that uses a Decoder (or any other "utility" object), you may want to mock it out - that is, replace the Decoder with a dummy object whose behaviour is known. That way, your unit test won't break if the Decoder class changes.

This is much easier to achieve if the Decoder is an actual object. If the Decoder is a class full of static methods, you can't really mock it easily (although there are mocking frameworks that can achieve this by mucking around with the byte code).

In short, static methods are a testability anti-pattern. I strongly recommend avoiding them at all costs. If you want to read more about this, try <a href="http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/" rel="nofollow">http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/</a> - there's lots of other good advice about testability on this site too.

Answer3:

I think that use static methods is more short when you code in the client class,

public class Collections { // Suppresses default constructor, ensuring non-instantiability. private Collections() { } public static <T extends Comparable<? super T>> void sort(List<T> list) { ... } }

Then we have,

Collections.sort(list);

Recommend

  • How to get caller pid in zmq (local socket)
  • Rspec2 partial view gives nil:NilClass. Why?
  • How to use Azure Batch in an event based design and terminate/cleanup finished jobs
  • How to join multiple azure databases without rights to configure external tables?
  • Border color change on hover
  • Writing to same file at the very same time
  • why isn't the natural height of a Frame updated immediately?
  • Using HTML/CSS for UI in XNA?
  • Client side validation mvc dropdown
  • CRASH: *** -[__NSArrayM objectAtIndex:]: index 4294967295 beyond bounds [0 .. 9]
  • Why are “sc.addFile” and “spark-submit --files” not distributing a local file to all workers?
  • Comparing user's facebook/twitter friends to site's users in Python/Django
  • Why can't UI components be accessed from a backgroundworker?
  • Perspective projection, 4 points
  • Jquery Knockout: ko.computed() vs classic function?
  • Is there some graphical way to create my own configuration file on SonarLint?
  • android google indoor map
  • Java color detection
  • Firefox Extension - Monitor refresh and change of tab
  • uniform generation of points on 3D box
  • SharedPreferences or SQLite Database?
  • Insert new calendar with SyncAdapter- Calendar API Android
  • Django simple Captcha “No module named fields” error
  • zope_i18n_compile_mo_files doesn't work on a Zeo configuration
  • OOP Javascript - Is “get property” method necessary?
  • Scrapy recursive link crawler
  • Q promise. Difference between .when and .then
  • Azure Cloud Service Web Role web pages do not load
  • How to make a tree having multiple type of nodes and each node can have multiple child nodes in java
  • C# - Serializing and deserializing static member
  • swift auto completion not working in Xcode6-Beta
  • Bug in WPF DataGrid
  • Finding past revisions of files in StarTeam w/ .NET SDK / C#
  • Incrementing object id automatically JS constructor (static method and variable)
  • Cannot Parse HTML Data Using Android / JSOUP
  • Linker errors when using intrinsic function via function pointer
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • C# - Getting references of reference
  • LevelDB C iterator
  • How can i traverse a binary tree from right to left in java?