2

I have a singleton class that basically interface all my HTTP requests. So it pretty much looks like this:

Server <--> Singleton <---> view controllers --> views

Is it bad? Why do people tell me that singleton breaks modularity? I think it's a good way to implement http requests, since I need to do some stuff with the JSON response, and I don't want my view controllers to handle those.

Enrico Susatyo
  • 19,372
  • 18
  • 95
  • 156

2 Answers2

1

Yes, this is a good idea. In fact, your singleton is simply a controller which talks to other controllers. This is not bad MVC.

Also, this is handier if you have multiple output formats (JSON, XML, HTML, etc). You can let the Singleton handle this. Plus it's DRYer.

  • +1 For promoting Singletons. Didn't get the JSON comment though - it *shoud* go into the view controllers (too specific for the singleton, and not view-related). – Eiko Jun 27 '11 at 10:49
  • @Eiko my answer had a giant edit, I'm not sure if your comment is still applicable. :) –  Jun 27 '11 at 10:51
  • Thanks very much! I was going to refactor 60% of my code base... Because the singleton is getting bigger and bigger, however if I split the singleton up into several pieces, I'd have to keep track of more stuff... (What's DRYer btw?) – Enrico Susatyo Jun 27 '11 at 11:25
  • 1
    @the_great_monkey: DRY means Don't Repeat Yourself. In fact, this means you don't reuse code too much, but e.g. write a function and call that. Your approach is DRY because you only convert things to JSON in the Singleton, and not in all individual view controllers. –  Jun 27 '11 at 11:33
  • 1
    There's a lot of blind singleton hate out there. There certainly are ways people abuse them, but this is an entirely fine use. If there's a function (or piece of data, or representation of a resource) that you want to exist only once, a singleton is a perfectly valid way to go. – Dan Ray Jun 27 '11 at 12:08
1

I think, you are using good approach, Instead of Creating multiple instances to deal with HTTP, It's nice to have an single gateway.

You could further internally have two more class one for constructing the HTTP requests by sending the appropriate type and other will handle your JSON parsing stuff and pass an well structured JSON data to your ViewConrollers.

Jhaliya - Praveen Sharma
  • 31,697
  • 9
  • 72
  • 76
  • Well I'm actually leaving another bit in my diagram. I'm using an SDK that provides the HTTP request, so my singleton controller is not dealing with those things :) – Enrico Susatyo Jun 27 '11 at 11:26