0

If I have class with two methods, that do different things, but class properties are not changed each time I call these methods, is that class a good candidate to be a singleton ?

For example:

class Foo {

    public function doFirst($params);

    public function doSecond();

}

If I call doFirst() method in my controller, and doSecond() in my view. Does it make sense for this class to be a singleton ? What I am thinking is this: if I do not change the class properties ( the class state ), then I do not need two instances of it. Is this correct way of thinking ? Also, singleton classes can be configured only once, right ? So if I configure my class once and then call 2 of its methods, it can be a singleton. But if I need to reconfigure the class before calling second method it can not be singleton ?

I hope that you understand my question, because I am so confused and do not know how to ask it better.

Anita
  • 159
  • 2
  • 11
  • I'd just pass the object on to the view from the controller. – Björn Tantau Sep 04 '17 at 09:45
  • That was just simple example, I am not solving that. My question is about singletons and object life cycle. The view where I am calling doSecond do not necessarily belong to the controller where I called doFirst – Anita Sep 04 '17 at 09:46

1 Answers1

1

You seem to think that as long as methods are not mutating the state, or only one state is needed, a class can be a singleton.

However, the aim of the singleton pattern is used to create a globally mutable state, which is already quite "code-smelly" on its own. If your state is immutable, then static (or Shared in VB) members will do just fine.

If your Foo class only has those two methods, I would mark them as static (or Shared in VB). Because they seem to just be "helper" methods that does not need any "state" to function.

If you want to mutate the state before calling the second method, I would suggest you use another pattern like dependency injection instead of singleton.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Thank you, I understand what you say. What if I want to create object that is not mutable, but I want to use DI Container, so that I can "instantiate" only interface throughout my code, so I can change implementation easy. Does that make any sense ? – Anita Sep 04 '17 at 10:14
  • @Anita That's ok. Use DI then. – Sweeper Sep 04 '17 at 10:16