Wisdom says "don't use globals" - ios

A global is a piece of data that is accessible in every context by name.

You may heard that "there is an exception to each rule".
I have been programming for several years, and before there was this "hip" of singletons, I started using global variables in my programs.
But, eventually, the programs switched to handle most variables as local, wheter classes fields, or methods fields.
It just came naturally, and it seems that a lot of developers, actually came to the same conclusion, before, after, and the same time, than me ;-)
In most O.O. programming languages, the program itself, is considered an object, and therefore a singleton.
Sometimes, several required global variables, wheter objects or non objects fields, can be encapsulated as a singleton.
Singleton as any other "better practice" or "design pattern", should be used wisely,
learn when & why are useful, and when not to apply.
Cheers.

I think the general idea is that there is not really "global" data. You may consider a program's user information (name, password, hair color) to be global, and in practice it may be. But it is conceivable (maybe using sockets) that other users might become active in the same session. You need a class (User) for this information and, now, several instances of it. And when you need this information, you need the right instance of User at hand. (The correct User object must be passed into the method, or must be available in an instance field; just getting the value from MainClass.userInfo won't work anymore.)
If you originally wrote the program with the idea that there might be multiple users and so far it's never been enhanced to handle them, your User class instance is a singleton and, in a sense, a "global" object as well. But your code will be more intelligible, and in the rare event multiple users are needed, easily upgradable.

Related

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

Is it possible to update an F# entity in RavenDB without abandoning immutability?

I have become a great fan of the powerful type system in F# and how it allows you to create some very tight restraints on your domain models (for those interested, see this). I have also become a great fan of RavenDB and how it makes database work very simple in most of the cases I run into. However, there seems to be issues getting the two to play nicely together - at least if you insist on immutable types.
As long as you don't ever have to update your entities, all you need to do is make the id property mutable. While I'm certainly not happy that this is necessary, I can live with it. However, it seems that change tracking is handled in such a way that you must mutate the original object retrieved from the database and it is not possible to attach a new object to the database to represent an updated version of an existing entity. It does seem to be possible to do what I want using the patching API, but the documentation clearly warns against this type of general usage.
Am I missing a part of the RavenDB API that will let me do this without too much fuss or must I abandon the idea of immutable domain models (or perhaps make a feature request for it)?
The problem with immutable in that scenario is that you are actually dealing with mutable data.
The document is being mutated. The fact that you don't mutate it in user space is of little matter here.
What you can do is wrap calls to Advanced.Evict & Store in a StoreUpdated or something like that extension method. But I would call into question the usage of immutable data to represent mutable state.

Identifying/Listing COM Objects and Properties from third party software

I'm trying to design an application that can identify COM objects and their properties on any different application. This is my first time attempting to do so, and I'm not sure where to start even. Ideally, it would be made using Delphi XE2, but I'm open to suggestions.
If I have the CLSID, is there any way to "scan" a running application for what objects were based on it? Or, going another way, is there a better way to list/find active objects in any running application?
Any help is deeply appreciated, as well as any directions towards good documentation on the subject.
Edit: The issue is actually finding out the COM objects in any other application, listing properties and whatever else I need has already been answered in other questions.
There is no way to scan for running COM objects. As soon as they are instantiated - they are just pieces of memory referenced by something else (member interface pointer variables etc).
Sometimes objects are put on Running Objects Table (ROT) and you can retrieve them from there, as already suggested in comments. This attributes for, let's say, <1% of COM object instances, but maybe you are lucky enough to chase for exactly those.
The only way I can think of is hook COM object instantiation in so that you intercept creation and then be able to track your own list of existing instances. This is not an easy way though too (and also it is most likely to be unsafe).
To achieve this you need to either register your class object in the context of running process for the CLSID of your interest and have your class factory receive the instantiation calls. Or, hook CoCreateInstance API, such as with Detours.
Once you are hooking instantiation you have pointers at the moment of object creation and you again need to do something with them. You would want to forward those instantiation calls to the original API, then to track life time of the instances - if you put an extra reference to the object you are likely to alter the original behavior of the application. Otherwise, you have no control to intercept COM object release. Sometimes the COM classes can be created aggregated and you can more or less cleanly embed the original instance in your COM object.
All in all, in general the task does not seem feasible to implement. Having specific CLSID of interest, with a certain luck and quite some effort you might be successful in doing this though.

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.

Questions about application service design

I come from a mostly n-tier background, and I'm trying to move more towards a DDD architecture. I'm trying to find best practices for designing the application service, and after a few searches, am still left with a few questions. Granted, I know I can't be the first person to ask these questions, so if you know where these are answered, just point me the way and I'll happily close this.
Here are my main questions:
How "open" should your signatures be? For example, is it better to be more rigid with your signatures and use simple types as parameters when possible, or is it better to use objects (messages?) that can later be modified without breaking the signature?
If you want to expose variations of a signature, for example, a UserSearch method that returns a list of users based on various (and sometimes optional) search criteria, is it better to:
A. Use overloads
B. Use optional (or nullable) parameters
C. Break each scenario into its own unique method
D. Use messages
I know that some of these answers are subjective, and also depend on what all will be calling your application service. But I'm just trying to get a general direction of things to consider and other best practices at this point.
Thanks in advance.
Good questions. Thinking about the API is obviously important.
1) How open would depend for me would depend on who the consumers are. If this application service is only being used within the context of your own solution and/or team then I think it's fine to have specific messages (or rather their interfaces) or Dtos (data transfer objects). Though if as easy then keeping to simple types is best in my book and definitely better if being consumed by others. If they don't suffice then interfaced messages that provide only just enough. Again if you are going to be distributed to different platforms then simple messages of simple types is not a bad way to go.
2) Why not have a SearchCriteria object as a paramater? It could be a SearchCriteria message of simple types if you are looking at this as a start of a messaging bus.
As you say, your question is a little open but I'd be interested to hear more as it sounds like you are asking the right questions at least.
Jerad, those are tough questions to answer generally, as you noted.
My personal preference is to use primitives in method signatures where possible. If I need to pass 3+ primitives to a method, I define custom data transfer objects.
The thinking being: if multiple values are being passed together, it's likely they represent a concept in your problem space, and thus should become an object. For example, if you are passing X and Y coordinates to a method, I'd recommend creating a Point class or struct that represents that concept.
The only time I'd end up with variations on a signature, it would be to provide convenience methods that provide default values for method parameters. To continue the above example, a Draw method might not require a Point, in which case I'd use (0,0).
So, I'd answer #1 with "not very open" and #2 with A.
I hope that helps.

Resources