Separating Data model from View Model - ios

I have an approach in designing MVC components which is to separate the Data Model (DB persistence) from the View Model of my component despite they represent theoretically the same element. I just map later the two models.
Do you think it's a good approach? Or I should try to make only one model?

When I run into issues like this, I try to create only the necessary classes that I need. This will help to keep the project smaller and to avoid confusion as to what class or object you are supposed to be using. I always try to picture the next guy coming and working on my code and what he would think of and where he would stumble in my logic. I would only use a ViewModel if you are creating objects from multiple Models you retrieved from the database.

Based on your statement it seems that you've created a duplicate data model which is mapped to a second model and would like to know if this is an optimal approach.
Recommendation
I don't think this is necessarily an optimal solution, but a lot depends on your use-case. What I typically do is create a data model that represents unique entities. Then I create a data management class that handles the interactions and use-cases of the data. The data manager would cover things like adding/removing custom objects from a collection. The approach I take is basically a lightweight approach to Apple's use of it's Core Data Framework (docs).
So for example one could use a dictionary, array, or set (or some combination of these) to manage the collection of custom objects together with a shared singleton object acting as a data manager and leveraging built-in archiving/unarchiving capabilities to handle a data graph requirements for an app. Actually,y the result is about the same as a simple use of Core Data, so I'd definitely recommend you get familiar with the standard approach used by Apple (it's embedded into every project template by default).
The good news is that once you choose an approach and develop it very carefully you could end up with a sharable resource that can be reused in many different projects. So for example, the data manager class might encapsulate the movement of data internally (files, local urls, etc) and externally (urls, soa, etc) and even deal with caching, serialization, etc.

I use only classes with get / set methods that operate a mapping of the DB and the VIEW. These are development policies. Using hybrid objects have a greater lightness of the project is in development at runtime. In some scenarios, there may be redundancy in the classes. It is important to aspire to the perfection of the code :-)

Related

managed objects vs. business objects

I'm trying to figure out how to use Core Data in my App. I already have in mind what the object graph would be like at runtime:
An Account object owns a TransactionList object.
A TransactionList object contains all the transactions of the account. Rather than being a flat list, it organizes transactions per day. So it contains a list of DailyTransactions objects sorted by date.
A DailyTransactions contains a list of Transaction objects which occur in a single day.
At first I thought Core Data was an ORM so I thought I might just need two tables: Account table and Transaction table which contained all transactions and set up the above object graph (i.e., organizing transactions per date and generating DailyTransactions objects, etc.) using application code at run time.
When I started to learn Core Data, however, I realized Core Data was more of an object graph manager than an ORM. So I'm thinking about using Core Data to implement above runtime object relationship directly (it's not clear to me what's the benefit but I believe Core Data must have some features that will be helpful).
So I'm thinking about a data model in Core Data like the following:
Acount <--> TransactionList -->> DailyTransactions -->> Transaction
Since I'm still learning Core Data, I'm not able to verify the design yet. I suppose this is the right way to use Core Data. But doesn't this put too many implementation details, instead of raw data, in persistent store? The issue with saving implementation details, I think, is that they are far more complex than raw data and they may contain duplicate data. To put it in another way, what exactly does the "data" in data model means, raw data or any useful runtime objects?
An alternative approach is to use Core Data as ORM by defining a data model like:
Account <-->> Transactions
and setting up the runtime object graph using application code. This leads to more complex application code but simpler database design (I understand user doesn't need to deal with database directly when using Core Data, but still it's good to have a simpler system). That said, I doubt this is not the right way to use Cord Data.
A more general question. I did little database programming before, but I had the impression that there was usually a business object layer above plain old data object layer in server side programming framework like J2EE. In those architectures, objects that encapsulate application business are not same as the objects loaded from database. It seems that's not the case with Core Data?
Thanks for any explanations or suggestions in advance.
(Note: the example above is an simplification. A transaction like transfer involves two accounts. I ignore that detail for simplification.)
Now that I read more about the Core Data, I'll try to answer my own question since no one did it. I hope this may help other people who have the same confusion as I did. Note the answer is based on my current (limited) understanding.
1. Core Data is an object graph manager for data to be persistently stored
There are a lot articles on the net emphasizing that Core Data manages object graph and it's not an ORM or database. While they might be technically correct, they unfortunately cause confusion to beginner like me. In my opinion, it's equally important to point out that objects managed by Core Data are not arbitrary runtime objects but those that are suitable for being saved in database. By suitable it means all these objects conform to principles of database schema design.
So, what' a proper data model is very much a database design question (it's important to point out this because most articles try to ask their readers to forget about database).
For example, in the account and transactions example I gave above, while I'd like to organize transactions per day (e,g., putting them in a two-level list, first by date, then by transaction timestamp) at runtime. But the best practice in database design is to save all transactions in a single table and generating the two-level list at runtime using application code (I believe so).
So the data model in Core Data should be like:
Account <->> Transaction
The question left is where I can add the code to generate the runtime structure (e.g., two-level list) I'd like to have. I think it's to extend Account class.
2. Constraints of Core Data
The fact that Core Data is designed to work with database (see 1) explains why it has some constraints on the data model design (i.e., attribute can't be of an arbitrary type, etc.).
While I don't see anyone mentioned this on the net, personally I think relationship in Core Data is quite limited. It can't be of a custom type (e.g, class) but has to be a variable (to-one) or an array (to-many) at run time. That makes it far less expressive. Note: I guess it's so due to some technical reason. I just hope it could be a class and hence more flexible.
For example, in my App I actually have complex logic between Account and its Transaction and want to encapsulate it into a single class. So I'm thinking to introduce an entity to represent the relationship explicitly:
Account <->> AccountTranstionMap <-> Transaction
I know it's odd to do this in Core Data. I'll see how it works and update the answer when I finish my app. If someone knows a better way to not do this, please let me know!
3. Benefits of Core Data
If one is writing a simple App, (for example, an App that data modal change are driven by user and hence occurs in sequence and don't have asynchronous data change from iCloud), I think it's OK to ignore all the discussions about object graph vs ORM, etc. and just use the basic features of Core Data.
From the documents I have read so far (there are still a lot I haven't finished), the benefits of Core Data includes automatic mutual reference establishment and clean up, live and automatically updated relationship property value, undo, etc. But if your App is not complex, it might be easier to implement these features using application code.
That said, it's interesting to learn a new technology which has limitation but at the same time can be very powerful in more complex situations. BTW, just curious, is there similar framework like Core Data on other platforms (either open source or commercial)? I don't think I read about similar things before.
I'll leave the question open for other answers and comments :) I'll update my answer when I have more practical experience with Core Data.

When modelling my app can I reuse NSManagedObject subclass?

I think this is a common scenario.
I'm defining class models of my app, I will use Core Data for caching so I would like to take advantage of the NSManagedObject generated subclass to "reuse" it as a model to pass to different classes.
Is that advisable?
Let's say I get some data from the network I want to build an object model with same instance variables as the Core Data model generated, use it when needed and maybe cache it on the DB.
What is the common approach there?
Can I use a category on Core Data model?
Core Data subclass? Encapsulation? New class ?
Thanks for any tips on that.
Core Data is not, at its heart, a database, but rather an object graph manager.
In many scenarios, it is a very good idea to handle your objects with Core Data, and you can use a fast in-memory store.
In a way, I think that by attempting NOT to use Core Data to handle your objects, you are destined to re-implement a lot of its functionality. Just use it.
You say that you are downloading a JSON that represents a given item; and you're using this item in your views, and then persisting it in a database. Core Data excels at this; take advantage of its full set of features instead of trying to avoid it.
(And, again, using mogenerator will be very helpful, although it is certainly not required).
Matt Gallagher has a nice blog article about the differences between Core Data and a database - I suggest that you read it, it's valuable information.
Cocoa With Love: The differences between Core Data and a Database

Implement model portion of the MVC

I have a simple game made, still working on some of the additional portions of the game. I am not sure how/where to store my game data (scores, settings, etc)
I've been using a singleton with all of the data that I'll use in the program synthesized for ease of access, but I don't know if this is a good method? It seems to me it would make settings and such quite easy, because I can just share the singleton among the menu view and the game view, without having to copy the data.. Is there another way? Every book I've read so far seems to skip over the model and just combine it with the controller portion of the MVC.
Singletons while appealing for their simplicity generally make the code base less flexible to changes. They also do not encourage a clear separation of functionality in the model.
An alternative is to use core data for the model. You would have a managed object for game,scores, settings etc and pass around references to the objects. With Core Data you get persistence for free along with fast/efficient mechanisms for sorting and presenting data.

Rails fat model example, is this the right way of thinking?

If I have two tables in a DB User and Userinfo (split for normalisation purposes) I generate the two models User, UserInfo and use them as normal via relationships.
Later on I have section of my application that reads and writes to both, however, there is a fair amount of business logic on creating entries for example looking up other tables for conditional rules, string building etc.
Would it make sense to make a third model (a non-database-backed model) to handle all this and to create/save via the other two models? or should I keep this in the controller?
Another example could be importing a CSV file where all the data is split between different tables, separate models as used by the rest of the application. Could I use a model defining each row that handles saving the imported data via the other models. Or again should this be in the controller?
I am interested in the best practices when developing large rails applications.
Sounds like you're normalizing (minimizing redundancy) rather than de-normalizing.
I don't know your application, so please take this as something to consider rather than a recommended best practice: what I typically like do in a situation like this is hide the Userinfo behind the User, so that the User is the only part of the application that even knows there is a Userinfo. This keeps things simple and consistent and DRY across the other clients of the code (controllers, other models, and you when you interact with it in the console).
Introducing a third model might serve the same purpose, but it's also adding conceptual weight to the application.
The answer depends on why you split the user data into two tables in the first place - what problem was it supposed to solve. Figure that out and try to apply the same logic to the models.
In any case, I agree that it makes sense to create a third model that encapsulates the complexity of working with the other two. This lets you present a simpler interface to other layers of the application (controllers, views). However, you'll have to watch carefully how far you're going with this. If you find yourself re-implementing most of ActiveRecord::Base by delegating calls to your encapsulated components, then it may be time to reconsider.
BTW, what you did isn't de-normalization. De-normalization in the context of a relational database means creating redundancy (check out the Wikipedia article on normalization, de-normalization is the opposite). This is usually done in order to improve performance by reducing the amount of joins required.

ruby on Rails dto objects - Where do you store them?

Does anyone here use DTO's to transfer data from the controller to the view? If so, where would you recommend storing those files? /apps/dtos, and then let them mirror the views dir structure? Any recommendations on testing these animals with rspec?
Please don't listen to the other answers. They are terrible. Rails helpers are terrible. Using rails models everywhere is terrible. I am begging you, design your application properly and decide if you need DTOs or not. Decide if you actually want to have rails models to handle things other than communication with the database. Decide if you actually want to not have a layer between your app and rails and so on and so forth. Rails design is suitable for only small apps or apps that have to be developed super quickly. But if it's not something trivial and you expect to develop it for some time, please invest your time into proper design. Don't be afraid to break Rails conveniences. And may the force with you.
The Rails convention is not to use distributed tiers for controller and view layers. The separation is there, but it is logical and relatively thin/lightweight compared to the types of frameworks you see in Java land.
The basic architecture is that the controller sets instance variables that are available in the corresponding view. In the general case, the instance variables will be model instances or collections of model instances (coming from the database). Models should be the core of your business logic. Controllers coordinate flows of data. Views display it. Helpers are used to format display values in the view ... anything that takes a model value and does something just for display purposes (you may find that a helper method used repeatedly may actually be better off on the model itself).
However, if you find that a view needs knowledge of many different models, you might find it easier to wrap models into another object at a higher-level of abstraction. Nothing prevents you from creating non-active-record objects that collect and coordinate your actual AR models. You can then instantiate these objects in the controller, and have them available to the view. You generally have to be at a pretty dense level of complexity in the controller to need this type of thing.
I would tend to throw such objects into apps/models - Rails already loads everything in this directory, keeps things easy from a config/expectation point of view.
If you're coming from a .NET or J2EE background you may be thinking about patterns like DTO. You may or may not be surprised (and possibly happy) to learn that Rails doesn't do things that way by convention.
In particular there is no need at all to formally transfer (or store) serialized objects between the controllers and views. Instance variables (typically model attribute values) created in the controller are available within the view for free as provided by the framework without any additional programming effort needed.
What I've been told is that generally, this is work that is handled by 'helpers'. They basically help you format your model objects for view consumption from within the view. So it's definitely not a 1-1 mapping of concepts, but that's the thinking in the rails world

Resources