Singletons: Pros,Cons, Design Concerns [closed] - ios

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I admit it. I am using singletons. I know what you may all say, and frankly, seeing all these answers on the Internet, saying about the bad aspects of singletons, and advising against them really made me question my programming practices.
I have already read some posts in StackOverflow regarding Singletons, but I post this question not only to ask about them, but to see some insights about the way I use them in my programs.
I feel I must really clarify some things here and ask fore directions.
So lets consider some cases where I use singletons a lot:
To create accessors to global variables, like my root view controller, specific and always existing view controllers, application state, my global managed object context... stuff like that
To create utility classes whose job is to handle data application-wide. For example, I create a Singleton that will operate my caching database, which relies on Core Data. Since I need to create caches and other stuff to be put in the database in different views, it somehow felt better to create a class that will handle database ins/outs (being careful about thread safety).
Handling network sessions. Actually, I use it to keep alive a connection and sending something like a PINg to a server each XX seconds.
I think that about sums it up. I would really like opinions from other developers on the matter.
Do you think that there are better solutions for these problems above?
Do you think that there are always better alternatives to singletons and that they should be avoided?
Is it better in terms of multithreading to forget about singletons?
Any recommendations and thoughts would be useful, and most welcome.

Singletons are certainly not always evil, but as you mention you have to be careful about thread safety (on that topic, check out this blog post on singleton initialization).
One reason why singletons are often decried as evil is that they can make it harder to "scale" parts of a program if they rely too much on a singleton and its behavior. You mention database access, a server or desktop application might start out with singleton implementation to handle all database needs and then later try to use multiple connections to speed up independent requests, etc. Breaking up such code can be very hard.
Even in an iOS application using CoreData it can be useful to not rely on a global ManagedObjectContext on your application delegate or some root view controller.
If you pass each view controller a reference to a ManagedObjectContext you can gain some flexibility. Most of the time you'll just pass the same context from one view controller to the next, but if you ever decide to in the future, you can for example create a new ManagedObjectContext for an editing view where you can use the undo features of the context but only merge the changes back into the "root" context if the user decides to save them or easily discard them otherwise. Or maybe you want to do some background processing on a whole set of objects. If everything operates on the same context, you'll end up with synchronization issues.

To create accessors to global variables, like my root view controller, specific and always existing view controllers, application state, my global managed object context... stuff like that
Singletons are globals. Wrapping a global with another global doesn't really help anything.
To create utility classes whose job is to handle data application-wide. For example, I create a Singleton that will operate my caching database, which relies on Core Data. Since I need to create caches and other stuff to be put in the database in different views, it somehow felt better to create a class that will handle database ins/outs (being careful about thread safety).
Sure, but this probably doesn't need to be a singleton. Indeed, part of the design of Core Data is that it is valid to have multiple MOCs that talk to the same store.
Handling network sessions. Actually, I use it to keep alive a connection and sending something like a PINg to a server each XX seconds.
This should be a singleton if the server might enforce some n-connections-per-user/IP-address limit. Otherwise, it probably does not need to be a singleton.
As I mention in my aforelinked blog post, the solution I prefer is to have each object own each other object. For example, your MOC and connection objects would each be owned by any object(s) that need to work with them. This improves memory and resource management (singleton objects never die) and makes the overall design of the application that much more straightforward.

Related

Which data layer / handling architecture or pattern to choose for a non-enterprise web application? (MVC / EF) [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I need some help in making a design choice for my application. It’s a fairly straightforward web application, definitely not enterprise class or enterprise-anything.
The architecture is standard MVC 5 / EF 6 / C# ASP.NET, and the pages talk to a back-end database that’s in SQL server, and all the tables have corresponding entity objects generated from VS 2013 using the EF designer and I don’t see that changing anytime in the near future. Therefore creating super abstract “what if my database changes” etc. separations is possibly pointless. I am a one-man operation so we're not talking huge teams etc.
What I want is a clean way to do CRUD and query operations on my database, using DbContext and LINQ operations – but I’m not good with database related code design. Here are my approaches
1. Static class with methods - Should I create a static class (my DAL) that holds my datacontext and then provide functions that controllers can call directly
e.g. MyStaticDBLib.GetCustomerById(id)
but this poses problems when we try to update records from disconnected instances (i.e. I create an object that from a JSON response and need to ‘update’ my table). The good thing is I can centralize my operations in a Lib or DAL file. This is also quickly getting complicated and messy, because I can’t create methods for every scenario so I end up with bits of LINQ code in my controllers, and bits handled by these LIB methods
2. Class with context, held in a singleton, and called from controller
MyContext _cx = MyStaticDBLib.GetMyContext(“sessionKey”);
var xx = cx.MyTable.Find(id) ; //and other LINQ operations
This feels a bit messy as my data query code is in my controllers now but at least I have clean context for each session. The other thinking here is LINQ-to-SQL already abstracts the data layer to some extent as long as the entities remain the same (the actual store can change), so why not just do this?
3. Use a generic repository and unitofwork pattern – now we’re getting fancy. I’ve read a bit about this pattern, and there’s so many different advises, including some strongly suggesting that EF6 already builds the repository into its context therefore this is overkill etc. It does feel overkill but need someone here to tell me that given my context
4. Something else? Some other clean way of handling basic database/CRUD
Right now I have the library type approach (1. above) and it's getting increasingly messy. I've read many articles and I'm struggling as there's so many different approaches, but I hope the context I've given can elicit a few responses as to what approach may suit me. I need to keep it simple, and I'm a one-man-operation for the near future.
Absolutely not #1. The context is not thread safe and you certainly wouldn't want it as a static var in a static class. You're just asking for your application to explode.
Option 2 is workable as long as you ensure that your singleton is thread-safe. In other words, it'd be a singleton per-thread, not for the entire application. Otherwise, the same problems with #1 apply.
Option 3 is typical but short-sighted. The repository/unit of work patterns are pretty much replaced by having an ORM. Wrapping Entity Framework in another layer like this only removes many of the benefits of working with Entity Framework while simultaneously increasing the friction involved in developing your application. In other words, it's a lose-lose and completely unnecessary.
So, I'll go with #4. If the app is simple enough, just use your context directly. Employ a DI container to inject your context into the controller and make it request-scoped (new context per request). If the application gets more complicated or you just really, really don't care for having a dependency on Entity Framework, then apply a service pattern, where you expose endpoints for specific datasets your application needs. Inject your context into the service class(es) and then inject your service(s) into your controllers. Hint: your service endpoints should return fully-formed data that has been completely queried from the database (i.e. return lists and similar enumerables, not queryables).
While Chris's answer is a valid approach, another option is to use a very simple concrete repository/service façade. This is where you put all your data access code behind an interface layer, like IUserRepository.GetUsers(), and then in this code you have all your Entity Framework code.
The value here is separation of concerns, added testability (although EF6+ now allows mocking directly, so that's less of an issue) and more importantly, should you decide someday to change your database code, it's all in one place... Without a huge amount of overhead.
It's also a breeze to inject via dependency injection.

Data Accessor object singleton or some other pattern? (Objective C)

It seems to satisfy the three requirements here: On Design Patterns: When to use the Singleton?
I need it to exist only once.
I need to access it from all over the source base.
It handles concurrent access, i.e. Locks for writes, but can handle concurrent reads.
Hi all,
I've been reading a lot of no doubt intelligent educated and wise gems of advice that Singletons are 'Evil' and singletons are anti patterns or just plain bad news.
With the argument that logging makes sense but not much else.
Just interested to know if the case of essentially a persistent data store context makes sense for a singleton, i.e. Reading/Writing from disk to memory and referencing an object graph.
And if not, how do people normally tackle this issue, I don't currently have any problem with it, I know it's created only once, it's fast and the accessor logic is in one place. Meaning it takes me one line of code to do anything data model related.
Which leaves the only argument that it's bad for testing, in that it's a hard coded production implementation to data, but couldn't I just write a method swizzle through a category or in the test code to create the test version of the singleton?
And the final argument from DI testers, is that it is a hard coded implementation, rather than simply an interface to something, which I do get but I don't really have a major drive to use a DI framework given that I can use protocols for implementation, and use separate init methods for setting up an objects state in testing. There's only ever going to be two types of state for the singleton, or realistically one type...production.
Making it (in my opinion) much easier to read and faster to develop.
Change my view SO?
Yup, for some singletons are Evil. For the new developers who has little MRC knowledge and more ARC it sounds scary because they need to mess with memory,volatile,synchronize etc.
However it is not against to use them, they indeed has their own purpose to use with some are below.
when sharing large data models like arrays and dictionaries etc between multiple screens (VC's) we can't prefer storing them in UserDefaults (because userdefaults is permanent storage and storing such large entries make app start lazily) instead singletons are best since they stay only current app context and restarting app creates new one.
when we need a stable db connection to be accessible allover the app without messing up with connecting and closing in every business classes we can go for it.
when we wanted an ability to app for theming itself dynamically we would need to create a singleton class which holds all the color,image instances etc. and use that instance in application VC/Views etc so no code duplication and re-processing theme occurs in all places.
You dont have to change your view but tweak it a bit to get some positive intention towards singletons.
Hoping this clears it out, thanks

Why is subclassing undesirable? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
Why does the UIApplication class need a delegate to have "things" done on its behalf? Why can't this class do "things" directly without the need for an intermediate object such as a delegate? What is the purpose of that principle?
In the same way I ask myself: why isn't it possible to directly access the keyboard in order to dismiss it? Why is there a need for signaling the view controller as a delegate in order to resign first responder?
Delegation is a core design pattern. It allows for the seperation of responsibilities between parts of your program. The idea is that the part of your program that, for example, draws to the screen probably shouldn't be talking to your database. There are several reasons for this:
Performance: if the same object that draws to the screen access your data store, you're going to run into performance problems. Period. Full stop.
Code maintanence: it's easier to conceptualize code that is properly modularized. (For me, anyway)
Flexibility: If you subclass in your code, that's great - until you start running into monolithic classes that have all sorts of undesired behavior. You'll reach the point where you have to overload behaviors to turn things off, and your property namespace can become polluted. Try categories, delegatation, and blocks for altrnatives. As king Solomon says in Ecclesiastes, paraphrased: There's a time and place for everything under the sun.
To make it easier to write, read, iterate upon, and maintain your program, it is strongly advised that you follow certain practices. You're welcome to subclass many classes, and Apple won't reject your app for poor code, provided that it runs as advertised. That said, if you don't abide by specific tried and true practices, you're digging your own grave. Sub passing isn't inherently bad, but categories, protocols, and blocks are so fascinating, that I'd prefer them anyway.
Why is subclassing undesirable?
Subclassing isn't undesirable. It's just that it's not always the right solution, and it's often better to use composition instead of inheritance. Lots has been written on this on Stack Overflow already, to the point that your title puts this question in danger of being closed as a duplicate. Rather than trying to repeat, I'll just point to one of the more popular questions covering this topic: Prefer composition over inheritance?
Why does the UIApplication class need a delegate to have "things" done
on its behalf? Why can't this class do "things" directly without the
need for an intermediate object such as a delegate? What is the
purpose of that principle?
It provides a much looser coupling that allows Apple to change or replace the application object without breaking existing code.
Delegates are very useful but they also have their place and time. It is also very possible to go about without using delegates. There are certain instances though, where delegates are important. For instance, when you use the uiTextview delegate, it is important for the controlling class to know when the text changes so it can handle it. And, because different classes may want to handle this event in different ways (limit characters, capitalize letters, etc) its easiest to use a delegate.
You may be saying: Yes, but why not just make a subclass with desired behavior? Well, this is possible, but there are a few reasons why you should not proceed this way. Firstly, you may override a behavior that is happening before the delegate is called. Next, it can be dangerous because you might accidentally override a function which was necessary. Third, it is a lot more work and more code, so it will be harder to debug. Imagine you have a form with 100 textboxes and they all have different behaviours. you would not want to create 100 subclasses... its much easier to do a switch case and delegate appropriately.

Is using a singleton as a data manager class bad?

I commonly create apps that require storage of data, and this data is used across the entire program. It's not much, though, so I usually use NSUserDefaults to load/save this data. However, the saving/loading code, along with packing/unpacking the data, takes up space, and I thought moving this code to reusable methods inside a global singleton would be a good idea. It seems to have worked well.
Even so, I've read a lot lately on the evils of singletons and global objects, and I've started to have second thoughts. People often say that the use of singletons is almost always an indications of poor design. For the most part, I'd disagree (I think simple uses like this are a good design pattern), but I'm certainly no expert on the matter.
So, is using singletons even in a simple way like this bad? If so, what's the better alternative?
I definitely don't agree that singletons are evil. They are sometimes overused perhaps but on some occasions are just perfect for the job. In some applications it makes sense to have some kind of general data manager. The singleton pattern is used extensively in the SDK itself (app delegates, shared managers, default centers and so on). Most often these are not "pure" singletons, as in you can access a shared instance but can also create new instances if necessary.
The question you need to ask yourself is whether it would be useful to have access to a single instance of a data manager from anywhere at anytime, if it isn't then a singleton is probably not needed. If you are going to be using singletons in multi-threaded environments however, you do need to worry about race conditions (can one thread modify a resource while another is accessing it), the documentation has good explanations on how best to achieve this in Cocoa.
Let me try to explain with an example - Am using some code from a game I wrote. Let's say you have a GameMap class and a Tile class. The GameMap represents a 2 dimension grid of Tile objects.
GameMap *gameMap = [[GameMap alloc] init];
NSArray *theTiles = gameMap.tiles;
The instance of the GameMap owns the grid of tiles, and creates the tiles when the game map is created. No singleton needed.
You may say "but I only have one GameMap at a time, what's the big deal?". What about loading saved games, or loading new levels? Well that becomes as easy as:
// In whatever class object owns the game map
self.gameMap = [[GameMap alloc] initWithSaveData:saveData];
In conclusion, create an instance of a class that has code to manage other instances of things. Keep as little global as possible and your code will be more scalable and maintainable.

Couple of questions about asp.net MVC view model patterns [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I'm new to MVC.
I have read this short bit detailing three ways of dealing with the view model in MVC:
http://geekswithblogs.net/michelotti/archive/2009/10/25/asp.net-mvc-view-model-patterns.aspx
The gist of it seems to me that:
Method 1, pull an object out the database and use it as your view model. Quick and simple, but if you want data from multiple tables you're totally screwed (I can't think of a way around it without Method 2).
Method 2, create a class that has references to multiple objects, and use this as your view model. This way you can access everything you need. The article says that when views become complicated it breaks down due to impedance mismatch between domain/view model objects... I don't understand what this means. Googling impedance mismatch returned a lot of stuff, the gist of it being that you're representing database stuff using objects and stuff doesn't map across cleanly, but you'd presumably have this problem even with Method 1. Not sure what I am missing. Also seems to me that creating a class for each View to get the data you want isn't ideal from a maintenance point of view, not sure if you have a choice.
Method 3, I am still getting my head around it, but I don't quite understand why their checkbox example wouldn't work in method 2, if you added a bool addAdditional to your class that wasn't connected to the domain model.
Method 3 seems to say rather than return the domain stuff directly, just pull out the properties you specifically need, which I think is nicer but is gonna be harder to maintain since you'll need some big constructors that do this.x = domain.x, this.y = domain.y etc.
I don't understand the builder, specifically why the interface is used, but will keep working on it.
Edit: I just realised this isn't really a question, my question is, is my thinking correct?
The problem I've run into with #2 is that I have to do one of these two things:
Include every single field on every single object on the form -- those that aren't going to be displayed need to be included but hidden.
Only include the specific fields I need but use AutoMapper or something similar to map these fields back onto the actual objects.
So with #2 I see a mismatch between what I want to do and what I'm required to do. If we move on to #3, this mismatch is removed (from what I understand, briefly glanced at it). It also fixes the problem that a determined hacker could submit values like id fields or similar when using method #2 that unless I was very careful could be written to my data store. In other words, it is possible to update anything on any of the objects unless one is very careful.
With method #3 you can use AutoMapper or similar to do the dirty work of mapping the custom object to the data store objects without worrying about the security issues/impedance exposed by method #2 (see comment for more details on security issues with #2).
You're probably right about impedance mismatch being present in both Methods 1 and 2 - it shows up anywhere you're going between objects in code and DB objects with relational mapping. Jeff Atwood writes about it, and cites this article, which is a fantastic discussion of everything dealing with Object-Relational mapping, or "The Vietnam of Computer Science". What you'll pretty much end up doing is weighing the pros and cons of all these approaches and choose the one that sounds like it fits your needs the best, then later realizing you chose the wrong one. Or perhaps you're luckier than I am and can get it right the first go 'round. Either way, it's a hairy problem.

Resources