Mapping model classes with Kotlin - android

I'm looking a way to improve the mapping mechanisms between the model classes from the different layers in my App.
I've model classes, the ones that I use in my App, in the business logic layer such as a Presenter. For example a User class.
I've server-side entities, these are the ones that I use to deserialize the responses from the server-side endpoints, through Retrofit or any other technology. These ones usually contain the Gson annotations for the fields. For example a ApiUserResponse class.
And I've DTO entities, these are the ones that represent a DB table in my App. I'm using Realm right now, but I've worked with ORMlite and Room. These types of classes also contain DB related annotations. For example a UserDTO class.
My cache repositories (the ones that fetch data from the DB) and my network repositories (the ones that fetch data from the server-side) both expose RxJava methods, returning the responses wrapped in Observable classes.
What I'm doing right now to parse the DTO entities and the server-side entities is add an extended function to the Observable class which receives a functions as argument. And that's the mechanism that I'm using to parse the DTOs and server-side entities into model classes. For example:
myLoginRepository.getUser("someId")
.mapTo(::myMappingFunction)
...
fun myMappingFunction(userResponse: ApiUserResponse): User {
return User(userResponse.id, userResponse.name, userResponse.lastname)
}
Internally the only thing that the mapTo extended function does is using a flatMap to flat the Observable stream and using a map to parse the collection.
I think that this is a pretty good way to implement the mapping between model-related classes, but I'm looking a way to improve it or do something completely different but that require less coding. Obviously this example is pretty straight forward, but currently I'm having a Mappings.kt file which is growing like crazy with each new mapping function.
Any suggestion?

Maybe http://modelmapper.org/ is something for you. This way you can spare your own mapping functions and you can even specify some sophisticated mapping functions. However it may cost you something in regards to performance (looks like reflection access all the way?).
Note: I didn't use the library myself yet, but it looks promising enough to recommend it. In the last project I helped out, they built their own modelmapper which probably wasn't such a good idea (lots of corner cases forgotten, which then led to strange behaviour later on or manually mapped the wrong fields; however your variant can suffer from that too).
Just found another article regarding mapping frameworks and their performance:
http://www.baeldung.com/java-performance-mapping-frameworks doesn't look that good for ModelMapper
You may also just want to generate your mapping functions. Similar to what you have now. Or just use a live template for it?
Manually writing your mappings may sooner or later introduce mistakes you are not identifying that easily anymore, except you test them all accordingly. Which you do, right? ;-)

You can convert your DTO object to entity or vice versa with converter.
Converter
ConversionService
You can implement Converter interface,It is a functional interface and you must implement convert method, then convert your DTO to entity, Where you want to convert them, just you should inject ConversionService and use convert method.

You should only have one class that representes both the entities and the model class from the network
If you want to use Room database and Retrofit for Api calls you should use like this
#Entity("tableName = something")
data class Something{
#SerializedName("name")
val name : String,
#SerializedName("number")
val number : Int}

Related

Should I use json objects directly?

I have always used a fromJson method to convert my json object to my model object. So let's say that my JSON has a car field which has my car models data, so I always parse the Json. Now I found out that it's also a common practice to use the json objects directly in the application. That has gotten me thinking
should I parse the json back to my models, if yes then why and if no then why not?
It depends but in general - yes, you should have transformation logic to convert your jsons (essentially, DTOs) into your entities (models as you call them). Here is my reasoning:
Your entities will likely be different from corresponding DTOs. As an example, your json model can have date/time information as long UTC msecs, but your entity model will likely be more usable if it has localized Date's
If you're exposing your entities (for example, as part of a library), you'll have much more flexibility in making changes to your remote apis (if such exist of course) without breaking your library's consumers codes
It completely depends on your project structure, if you have POJO classes defined in the models then converting them is the way to go. It makes your code more readable and fulfils your model which makes fetching the data easier. If you use a JSONObject directly then pulling data from it requires a bit more code. In terms of performance they both should have equal impacts since both are 'Objects' and will consume resources equally.
I vote for parsing them back to Models because of the simplicity it
enables for using those values further in your coding.

How to model data when using Room

I am reading up on Room and the way it handles relationships between entities is both understandable, but confusing. I cannot wrap my head around what a "proper" data model should be to make Room happy. The problem is that all the examples I have found show how to handle a simple relationship, but don't address nesting, or entities that contain references to multiple other entities.
Going back to the beginning, my question is how should I model my data to make using Room as easy as possible?
Is it possible to have the data model framework-agnostic? That's something that feels correct to me. A framework should not dictate the way entities are modeled. I want to be able to traverse the data model as I would if there was no database at all.
Assuming I have a deep-ish hierarchy, for example: a Game has multiple Players and multiple Rounds. A Round has multiple Turns. A Turn can have multiple Steps. How do I model this according to Room? Reading about #Relation, it would suggest there should be "wrapper" POJOs. But would that mean that here I would have to create classes TurnWithSteps, RoundWithTurnWithSteps, and GameWithRoundWithTurnWithSteps?
This also seems to imply that whenever working with the entities in code, I have to decide which "view" of that entity to use. So I cannot simply work with Game and use it as if it was a true, nicely modeled class?

RoboSpice and Jsoup

I have an application where I use Jsoup to get HTML file from the internet and parse it into POJOs. I use a custom Content Provider then to persist my POJOs into an SQLite database. It's a lot of code, and certain things are tricky to implement, caching especially (i.e. how to determine that my object is already in database, how to manage expiration, etc.). From looking over the internet I understood that RoboSpice might come to the rescue, since in handles caching transparently. However, I haven't found any example on how to plug in custom parser (my results are neither JSON nor XML, just pure HTML which I'm parsing with Jsoup currently). I'd therefore appreciate if you could point me to some related example.
Here's a more detailed description of what I'm doing. My app reads certain website to get the lists of certain entries. Those entries are calendar-based, and I'm requesting them month by month. Every month's request returns me a list of entries from that month. I want to make those requests cacheable and queryable, therefore I need a database backend, so that I can run custom SQL queries against it. Which RoboSpice configuration should I use, which extensions, and which code samples could I refer to?
Thanks in advance.
It looks like a good idea to use RoboSpice here, but the way you want to use is a bit out of its natural scope.
Usually people annotation a Pojo, let's say for Jackson, and they request a webservice, then the result is parsed via jackson and you get your Pojo. RoboSpice will simply reformat your pojo into json using jackson as parsing / formatting is a considered a bijection.
In your case, you will have to call your own ObjectPersister for your Pojo class and take care of its persistence format yourself. As you store your pojos into a database, the RoboSpice ormlite module may help but it is still experimental.
Have a look at the sample of the ormlite module of RoboSpice.

Modelling To-Many Relation To Superclass Object

I started my work with greenDAO project, which I want to use to simplify database operation in my Android project. So, I would like to create a relation schema in seperated Java generator project.
My aim is to implement a superclass, from which other entities may inherit. Of course, I use a method:
myEntity.setSuperclass("MyCommonBehavior");
for each of inheriting entities. But the question is, how can I set a To-Many Relation to my main ("abstractive") model described in class, instead of setting To-Many Relation to each of specific entities?
GreenDAO doesn't support Polymorphism for now.
See their docs: Modelling Entities
" [...] Note: currently it’s impossible to have another entity as a super class (there are no polymorphic queries either)
Anyway, you could implement it yourself storing the entity type and some interfacing.

Store JSON in an sqlite field?

I'm writing an application that communicates with a web API, which responds with JSON. Currently, I'm translating the JSON objects to Java objects using gson (which is awesome, by the way).
Now, I want to store some of these objects in an SQLite database. However, they have lots of properties that would never be used in queries (i.e. I won't be ORDERing, WHEREing, or anything like that with those properties), so I feel it's unnecessary to create columns for all of them. What I'm thinking of doing is:
Only have columns for the essential data that will be used when querying the database
Have one TEXT or BLOB column (which one do you recommend?) that stores the actual JSON, so I can recreate my Java object from it and access all the data.
This would both make my life easier and streamline my code (I would not have to write very different code when dealing with data from the API vs. data from the database).
However, although I see no downsides, it feels a bit fishy.
What kind of trouble do you think I would run into if I use this technique?
The main thing I wouldn't like about it is relying on the structure of the stored/retrieved JSON to be valid, since it's completely out of the hands of the database. Not that you can't take precautions against possible issues, but if the JSON is somehow truncated or otherwise compromised in a way that trips up the parser, you're then missing the entire object instead of just one invalid or truncated property. If that's an acceptable risk, then it's probably a reasonable technique.

Categories

Resources