Design Patterns – Moving Object References in Applications

design-patternsiosobject-oriented-designobjective c

I'm new to Programmers and I am looking to increase my knowledge of programming. Recently, a user on Stack Overflow told me using singletons is a bad idea, that they encourage tight coupling and that they make testing harder.

What prompted this discussion was that every class I've ever written accessed any kind of data through a singleton. For example, a class that handles state data for a game. If any other class wanted to access this data, all they would have to do is get the singletons instance and there it would be. Specifically, instantiating a class on the AppDelegate, then accessing it via: [[[[UIApplication sharedApplication] delegate] gameObject] getScore].

The SO user told me that I should instantiate the 'gameObject' wherever I first need it, then pass that object to every other class that needs it via either a method as an argument, or via a property.

I was discussing these points when someone else pointed out that this information is completely wrong, that singletons are unrelated to coupling and that they do not affect testing at all.

I'm now completely confused as to which person is correct. Could someone please clarify which technique is best for an object to persist for the lifetime of the app, and be accessible to other classes, and also maintain loose coupling. To me, the object passing by method or property to each class seems the most logical, but I do not know!

Thanks in advance for any help!

Best Answer

You won't ever know. Program design is about tradeoffs, and analyzing particular scenarios to produce a solution that is good (not best) given what you know about them. In this particular scenario, the singleton proponent is decidedly incorrect but you're missing the point.

In scenarios where the answer is less clear cut, you're going to need to be able to think things through yourself to judge what is a good or bad approach for the problem at hand. If you know what coupling is, and what a singleton is then you shouldn't really need to ask us. It's important to develop this skill for those many times when the particulars of the scenario mean we can't get you an answer.

Related Topic