I'm brushing on my Android dev skills and have been playing around with the Architecture Components. So I created an entity class using Room
annotations for persistence to the database and implemented Parcelable
on the entity class partly for the purpose of putting the entity object into an Intent
object and passing it between activities/fragments. I just want to know if this is a good practice. Are there any cons of using such approaches such as database leaks or security flaws? Just curious.
I just want to know if this is a good practice.
IMHO, in modern Android app development, no, for a few reasons, including:
Repository pattern: The current pattern in Android app architecture is to isolate data storage and transfer concerns into a "repository" object. The repository knows the details of where the data is coming from and going to (Room, Realm, Retrofit, etc.). The rest of the app neither knows nor cares, as the rest of the app just talks to the repository. With this pattern, you would pass identifiers around between activities and fragments, and the repository would hand over model objects based on those identifiers.
Hide implementation details: Your UI should work with an ideal set of model classes, ones that are not tied to particular implementations of data storage or transfer. That way, should you elect to change your implementation (e.g., from Room to Realm), your changes remain isolated and should have little effect on the UI. If you use a repository, the repository would be responsible for converting from Room entities and Retrofit responses into standardized model objects that the rest of the app knows how to use.
Single source of truth: Once you start passing objects around via Intent
extras, you are making copies. If one part of your app then wishes to modify that model object... how will the rest of the app, holding other copies of the data, know about those changes? Ideally, you have a repository with a reactive API, where the repository is the party that makes the data changes. It can then notify other interested parties about the data changes, delivering an up-to-date rendition of the model object.
IPC memory limits: Every time you use an Intent
with startActivity()
, startActivityForResult()
, setResult()
, etc., the contents of that Intent
are passed to a core OS process... even if the activity being started is in the same process as the code that is requesting that activity be started. There are memory limits for how big an Intent
can be (roughly speaking, 1MB or lower). Passing full model objects around may work fine right now, but later if somebody adds a Bitmap
field or something to the model, you can get in trouble.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With