Utils classes are belongs to which layer in MVVM architecture?

267 views Asked by At

I'm currently working on an Android project following the MVVM architecture pattern. While organizing my code, now I'm confused about placement of utility classes. In which package i should place utils classes?

I want to create some utility classes like Custom Toast class , Network state checking class by pinging the api website that im using in my project. and also creating static methods in these classes will be bad practice? and using these class directly in the activities will be bad practice for maintaining mvvm architecture? as im updating my activities data through viewmodel and livedata observer.

as we know in MVVM, we have the model layer, view layer, and view model layer.In some article i saw some developer saying utils bilongs to model layer and somewhere i saw utils belongs to view layer.

Additionally, I'm also interested in understanding how the placement of utility classes can impact the overall maintainability, scalability, and testability of the codebase. Are there any best practices or guidelines that can help in making this decision?

Any guidance or experiences shared would be greatly appreciated. Thank you in advance for your help! My packages:

enter image description here

1

There are 1 answers

0
Egor On

A practice I like to follow is to choose the most narrow scope for your utility code and expand it only when necessary.

Let's say you want to introduce a function that returns the last 3 characters of a string - what would be the best place to put that function? If it's only used by a single class in your codebase - just make the function private in that class. If there are multiple classes in the same package that need this function - you can move it to a separate file in that package. If it's used everywhere (which is rare) - it can probably live in a file inside a "utils" package.

I'd suggest placing utils closer to where they're used: the custom Toast class will live in the "views" package, while the Network state checking class can live in the "network" package. Imagine at some point you wanted to split your codebase into separate Gradle modules that would depend on each other and have 3rd party dependencies: having networking utils in the "views" module would mean that module now needs a dependency on Retrofit, which isn't ideal. Hence a better place for it would be the "network" module, for which having a Retrofit dependency feels more natural.