jeudi 15 octobre 2015

Is this Android Activity architecture good?

Introduction

Hello! As you may know, in Android "Activity" classes may become huge and contains thousands lines of code and hundreds methods inside. Maybe it's OK to work with it when you have made it by your hands, but becomes very hard and time-consuming when you have to add new functionality to unfamiliar code.

This break "Single responsibility" principle, so I started to work on some architecture, that can help you to organize activities code in Android. I have read about MVC, MVVM and other architecture patterns, but they all seems so different to Android activity structure.

My solution

What I have done is just decomposing one big Activity class into many separate "modules". Every module follow "Single responsibility" principle and contains only methods and fields related to it's purpose. Also every module has reference to activity, so it gives ability to call activity methods and to have access to other modules; and has necessary activity lifecycle methods.

In example you could split activity on modules like:

  • Dialog module - to show any dialogs, toasts, snackbars to user about errors, etc.
  • Event-handler module - to handle network and other events coming from outside
  • Auth module - to logout (and go to login activity), check credentials, prevent activity working without auth data
  • List module - to work with activity's RecyclerView and handle clicks on it
  • ...

After splitting on modules Activity class file only contains: lifecycle methods, references to all modules and calls of module's lifecycle methods. So you will have 5-10-20 well-named class files with 100-200 lines of code and 3-5 fields in each. You can add new functionality by writing new module, adding it in activity as a field and calling it's lifecycle methods.

Question

It feels very naturally in Android for me, but I need to know what other developers would say if they faced it in other's code. I already have found one lack - when you extend this "module activity", it's non trivial to override functionality, because it placed in modules and you have to extend and replace modules instead of methods.

Can you help me to find any other bad or good things about this architecture? And maybe to answer, why some developers continue to write 5000-lines-of-code activities :)

Aucun commentaire:

Enregistrer un commentaire