julian
julian

Reputation: 4714

Should it be a singleton, static or just a regular class?

Consider a class called Effects that has a static ArrayList called effects.
The class contains a few static functions that are called across all the program, for example the static function: Effects.addEffect(effect) which adds an effect to the ArrayList effects

According to this, the class Effects has the following points:

According to good programming practices, should I make this class singleton, static or just a regular class with which I should pass an instance across all the program?

Upvotes: 1

Views: 102

Answers (3)

Bryan Menard
Bryan Menard

Reputation: 13384

It all comes down to what is "good programming practices" and what is the broader context.

For bigger, more robust solutions that require testing and mocking components, having a static class is quite hindering since it cannot be easily substituted. Some will argue that following these guidelines - avoiding static classes and making sure components are easily testable - make for better designs (TDD being a good example of this kind of philosophy).

However, note that "carrying" an instance everywhere, lets call it IEffects, can make your design "heavier" and laborious to maintain if you are not using Inversion of Control (IOC) and dependency injection (DI) for resolving dependencies.

These are some questions I generally ask myself when I face this kind of dilemma:

  • Will I ever want to switch implementations of this component (e.g. StandardEffects vs HighDefinitionEffects)
  • Will I ever want to fake or mock this component when testing other components dependent on this one?
  • Is it relatively easy/hassle-free to use an interface (coupled with a singleton in your case) instead of a static class?

Answering Yes to any of these questions generally leads to using the interface approach instead of the static class approach.

Upvotes: 2

Nisheeth Shah
Nisheeth Shah

Reputation: 608

As you have stated, you should have just static method in your Effect class.

You have only static variable that stores all the effects. It is still going to add the the effect in the same variable. Then why to create object for that every time you want to use? Simply add a static method instead. If you have multi-threading problem then you can handle it using Lock or synchronization. Making instance variable or instance method to access the static variable does not make sense. Are you talking about singleton pattern or Singleton class?

Upvotes: 0

maniacneron
maniacneron

Reputation: 424

A singleton class is an object can implement interfaces you can pass around the object for delegates and callbacks. If you don't need any of these make it a static class.

Upvotes: 1

Related Questions