android10 / Android-CleanArchitecture

This is a sample app that is part of a series of blog posts I have written about how to architect an android application using Uncle Bob's clean architecture approach.
Apache License 2.0
15.52k stars 3.32k forks source link

Mapper and the GC #145

Open FBisca opened 8 years ago

FBisca commented 8 years ago

I really liked how you organized this architecture, so I tried to implement it myself.

It was going fine at first, but when I came across large JSON objects trees I started to think if it's a bad practice to use the Mapper pattern.

It's a good practice avoid object instantiation, specially in Android, where the GC runs in the UI Thread.

I'm using GSON for JSON parser and with that some of my objects have a lot of children objects in this properties tree. A single object request instantiate a bunch of other objects just to go from Data to Presentation using the Mapper Pattern. But practically it could be achieved with, I don't know, 1/3 of the objects.

A simple solution that I thought, was to transform Model Domain classes into Interfaces, with this solution I removed one unnecessary instantiation, but I still kept the Model contract and flexibility for Data Entities.

In Kotlin it's very easy do that, but it could be done in Java as well. Here follow some simple snippets

interface User {
    val id: Long
    val uuid: String
}

class UserNetworkEntity(val userId: Long, val userUuid: String) : User {
  override val id: Long
    get() = userId
  override val uuid: String
    get() = userUuid
}

class UserRealmEntity(val data_id: Long,val data_uuid: String) : User {
  override val id: Long
    get() = data_id
  override val uuid: String
    get() = data_uuid
}

class UserRepository {
  fun getUser(): Observable<User> {
    return Observable.just(UserDataSource().getUser())
  }
}

class UserDataSource {
  fun getUser(): UserNetworkEntity {
    return UserNetworkEntity()
  }
}

What problems this implementations brings? We can still achieve performance with the Mapper Pattern?

android10 commented 8 years ago

In this case I would argue that early optimization is bad unless is a core/key part of your business. The idea behind this approach is to be completely decoupled and accomplish the dependency rule, which of course will facilitate testability and scalability.

In past experiences I made the mistake of reusing or sharing models between layers and you end up having big model because you need certain data that is only useful in a certain layer and so forth.

Other than that, I don't see any problems of using other approaches (this one too). Actually that is the purpose of this repo, so we acquire knowledge from other people facing problems and we get better and improve as professionals :).

@FBisca Very interesting. I would definitely encourage you to share your experiences if you go for this solution (or any other).