managing NSUserDefaults - cocos2d-iphone

I would like to know of it's right to set NSUserDefaults everywhere they need to be used as compared to having a central place where they are managed. For example, in my game, in the GamePlayScene class I set NSUserDeflaults for the score and level and in the Settings class I set NSUserDefaults for the sound effects. These are just a few of the NSUserDefaults I set. If having a central place (class) where they are managed is a good idea, where should it be located (class) and how should I manage them. Thanks.

NSUserDefaults is a keyed archive. A good design would likely use one of these approaches:
Declare const NSString* objects (the keys) in a global header and access NSUserDefaults directly from any code using the const strings instead of in-place #".." strings (prone to typos).
Write a simple wrapper around NSUserDefaults with class methods like +(void)setScore:(int)score to set the score without needing to know which key is used to store the score.
The more complex your project the better the second approach becomes, as the overhead of creating additional methods is reduced in favor of fewer errors, usually by using the wrong key for a value (ie storing score with the level key).

The UserDefaults are cached in memory and are only written when you synchronize them. You can write to them anywhere you wish. Centralising this can make things more complex than is needed.
The important thing is to synchronize them at the correct moments. When the app is deactivated or killed.
The UserDefaults already IS a centralised place to do it in my opinion.

[[NSUserDefaults standardUserDefaults]setObject:#"stringValue" forKey:#"strkey"];
[[NSUserDefaults standardUserDefaults]synchronize];
NSString *str=[[NSUserDefaults standardUserDefaults]objectForKey:#"strkey"];
NSlog(#"string is-%#",str);

Related

How to partly initialize c++ objects when I don't need all values from the database?

I’m trying to cut down on the amount of network queries in my c++ program (to increase speed), and when displaying search results, I don’t want each (of the sometimes thousands) of objects found in the search to initialize themselves completely from the database when I only need to display part of this information.
It is much faster to perform one bigger query where I get all the information I want to display about the objects at once in the query (for example, for each object/row I select the id, the name and the location), passing them to a bigger constructor, and letting all other members be default values. Previously, and in other cases where I need the complete object, I just pass the ID to the object, then call initializeFromDatabase() directly to set all the other values.
//current solution (problem is, I might need many constructors like this for different purposes)
auto *myobject = new MyObject(345, "ObjectName", "Europe");
//no further (costly) initialization since I only need the following 2 values for my search results.
myobject->getName();
myobject->getLocationName();
//prevous solution (resulting in too many queries)
auto *myobject = new MyObject(345);
myobject->initializeFromDatabase();
myobject->getName();
myobject->getLocationName();
//I could also query the other 30 or so members here, everything is set.
This doesn’t feel like good practice though, I would need other custom constructors for say, another search window displaying other kinds of data about the objects.
Are there any general best practices / a suitable design pattern to solve this sort of problem? Should I create a “Search object” that is its own class and that can then be used to create the complete object when needed? Or always initialize with only the database ID (setting a flag that the object is not initialized yet) and use the setters I need?
I found that a solution to this would be to use some sort of Lazy Loading, since I want to quickly load part of the object for the list, then load all of it if a user clicks on one of the objects. For example, a Virtual Proxy or the Ghost Design pattern would be suitable. I simply create a proxy object for displaying the search results (and for other lists in the program) that can create the full object on demand. Every proxy object has one constructor so I avoid the problem of using lots of different constructors for different purposes.
See Chapter 11 of Patterns of Enterprise Application Architecture by Martin Fowler (published by Addison-Wesley Professional, 2002)

The Registry pattern: to use or not to use

I am considering using the Registry pattern in my application to store weak pointers to some of app's windows and panes. The general structure of the application is shown below.
The application has one MainFrame top level window with few child panes within it. There can be many of TabPane type based tabs. I need to reference the ParamsPane panel from all of my TabPane tabs, so I need a pointer to the ParamsPane object to be stored somewhere. There can be a plenty of options, but the most obvious ones are (1) to store the pointer within the Application singleton object or (2) to create a simple registry class. Something like:
class Registry {
public:
static MainApp* application;
static MainWindow* mainWindow;
};
Is this a good practice? What are the benefits and caveats of such an approach?
It depends on why you want to reference ParamsPane. I can think of two reasons and two different solutions.
You want to update data in ParamsPane because data in TabPane changed.
If this data is completely separatable from the view, what you should probably do is separate it. This means following the Model-View-Controller pattern. Both ParamsPane and TabPane instances can access the model separatly. So there is no direct reference between the two.
There is some strong link between the two, irrelevant of data.
If the previous mentioned point isn't relevant, and there is a really strong link between the two panels you could consider writing a specific TabPane class which stores a reference to a ParamsPane class.
I feel both these solutions are better than a Singleton or 'Registry' approach. Beware that I haven't heard of this pattern before, but I believe I understand its intent. More info on why global state objects (more specifically singletons) are a bad practice can be found here.
In terms of testability, it may not be a good idea to use the Registry Pattern. To repost from this article:
Unit testing is predicated on the assumption that you are testing small, discrete units of code that do not have dependencies. This requires that developers do everything they can to either remove dependencies or mock them in such a way that the dependencies are neutralized as contributors to the failure of the unit being tested. In PHP 5, objects are not copied when assigned; instead, their address in a hash table is copied. This means that if you retrieve an object from the registry, and then modify it, every subsequent retrieval from the registry will reflect that modification.
The reason this creates a significant issue is that it prevents you from testing a discrete unit of code. Now, instead of one thing being the variable in a test failure, there are two: the unit of code being tested and the object it retrieved from the registry. Any time there is more than one possibility for failure, the effectiveness of the unit testing is diminished.
Your Registry class and Singleton are OO-ways of global variables. Prefer to make the Params Pane in the MainFrame and to pass it as reference to the tab-panes.

Worth using getters and setters in DTOs? (C++)

I have to write a bunch of DTOs (Data Transfer Objects) - their sole purpose is to transfer data between client app(s) and the server app, so they have a bunch of properties, a serialize function and a deserialize function.
When I've seen DTOs they often have getters and setters, but is their any point for these types of class? I did wonder if I'd ever put validation or do calculations in the methods, but I'm thinking probably not as that seems to go beyond the scope of their purpose.
At the server end, the business layer deals with logic, and in the client the DTOs will just be used in view models (and to send data to the server).
Assuming I'm going about all of this correctly, what do people think?
Thanks!
EDIT: AND if so, would their be any issue with putting the get / set implementation in the class definition? Saves repeating everything in the cpp file...
If you have a class whose explicit purpose is just to store it's member variables in one place, you may as well just make them all public.
The object would likely not require destructor (you only need a destructor if you need to cleanup resources, e.g. pointers, but if you're serializing a pointer, you're just asking for trouble). It's probably nice to have some syntax sugars constructors, but nothing really necessary.
If the data is just a Plain Old Data (POD) object for carrying data, then it's a candidate for being a struct (fully public class).
However, depending on your design, you might want to consider adding some behavior, e.g. an .action() method, that knows how to integrate the data it is carrying to your actual Model object; as opposed to having the actual Model integrating those changes itself. In effect, the DTO can be considered part of the Controller (input) instead of part of Model (data).
In any case, in any language, a getter/setter is a sign of poor encapsulation. It is not OOP to have a getter/setter for each instance fields. Objects should be Rich, not Anemic. If you really want an Anemic Object, then skip the getter/setter and go directly to POD full-public struct; there is almost no benefit of using getter/setter over fully public struct, except that it complicates code so it might give you a higher rating if your workplace uses lines of code as a productivity metric.

Building an index: Copies or pointers?

I have a data structure that stores ... well, data. Now, I need to access various pieces of data in slightly different manner, so I'm essentially building an in-memory index. But I'm wondering: should the index hold pointers or copies?
To elaborate, say I have
class Widget
{
// Ways to access the list of gears...
private:
std::list<Gears> m_gears;
};
Now, I have two Widgets, and there exists between these two a mapping between their Gears. Currently, this is
boost::unordered_map<Gear, Gear>
but Gear is a fairly hefty class, and I feel like making so many copies is poor design. I could store a pointer, but then the mapping is only valid for the lifetime of the corresponding Widgets, and you start getting ->s... (And if that std::list ever changes to a std::vector, it gets more complex...)
Pertaining to the copies, it's actually slightly worse: There's two boost::unordered_maps, one for each direction. So, for each Gear, I'm making up to 2 copies of it.
Alternatively, I could put the index inside the Widget class, but I feel like this violates the responsibilities of the Widget class.
You might try Boost Pointer Container Library: http://www.boost.org/doc/libs/1_43_0/libs/ptr_container/doc/ptr_container.html
I think it addresses exactly the problem you are facing.
Could you store all gears in one place, like statically in the gears class, and then have each mapping AND widget store only the reference/index to it?
You would have to keep track of references to each gear so you know when you can dispose them, but that should be easy enough.

C++ class design from database schema

I am writing a perl script to parse a mysql database schema and create C++ classes when necessary. My question is a pretty easy one, but us something I haven't really done before and don't know common practice. Any object of any of classes created will need to have "get" methods to populate this information. So my questions are twofold:
Does it make sense to call all of the get methods in the constructor so that the object has data right away? Some classes will have a lot of them, so as needed might make sense too. I have two constrcutors now. One that populates the data and one that does not.
Should I also have a another "get" method that retrieves the object's copy of the data rather that the db copy.
I could go both ways on #1 and am leaning towards yes on #2. Any advice, pointers would be much appreciated.
Ususally, the most costly part of an application is round trips to the database, so it would me much more efficient to populate all your data members from a single query than to do them one at a time, either on an as needed basis or from your constructor. Once you've paid for the round trip, you may as well get your money's worth.
Also, in general, your get* methods should be declared as const, meaning they don't change the underlying object, so having them go out to the database to populate the object would break that (which you could allow by making the member variables mutable, but that would basically defeat the purpose of const).
To break things down into concrete steps, I would recommend:
Have your constructor call a separate init() method that queries the database and populates your object's data members.
Declare your get* methods as const, and just have them return the data members.
First realize that you're re-inventing the wheel here. There are a number of decent object-relational mapping libraries for database access in just about every language. For C/C++ you might look at:
http://trac.butterfat.net/public/StactiveRecord
http://debea.net/trac
Ok, with that out of the way, you probably want to create a static method in your class called find or search which is a factory for constructing objects and selecting them from the database:
Artist MJ = Artist::Find("Michael Jackson");
MJ->set("relevant", "no");
MJ->save();
Note the save method which then takes the modified object and stores it back into the database. If you actually want to create a new record, then you'd use the new method which would instantiate an empty object:
Artist StackOverflow = Artist->new();
StackOverflow->set("relevant", "yes");
StackOverflow->save();
Note the set and get methods here just set and get the values from the object, not the database. To actually store elements in the database you'd need to use the static Find method or the object's save method.
there are existing tools that reverse db's into java (and probably other languages). consider using one of them and converting that to c++.
I would not recommend having your get methods go to the database at all, unless absolutely necessary for your particular problem. It makes for a lot more places something could go wrong, and probably a lot of unnecessary reads on your DB, and could inadvertently tie your objects to db-specific features, losing a lot of the benefits of a tiered architecture. As far as your domain model is concerned, the database does not exist.
edit - this is for #2 (obviously). For #1 I would say no, for many of the same reasons.
Another alternative would be to not automate creating the classes, and instead create separate classes that only contain the data members that individual executables are interested in, so that those classes only pull the necessary data.
Don't know how many tables we're talking about, though, so that may explode the scope of your project.