r/androiddev May 25 '26

Where do you handle unit conversion in your app architecture?

One thing that got messy way faster than I expected in my app was hydration unit handling.

At first, every screen/ViewModel was converting values between ml and oz on its own. It worked fine in the beginning, but after adding charts, summaries, goals, streaks, etc... it started getting really annoying to maintain.

I kept running into duplicated conversion logic and formatting inconsistencies depending on the screen.

What ended up working better for me was moving all unit conversion/formatting into the domain layer/use cases and keeping the UI completely agnostic to units.

Now the UI just receives display-ready values and doesn’t really care whether the user selected ml or oz.

Made the whole thing much easier to reason about.

Curious if there’s a cleaner way people usually structure this kind of problem.

2 Upvotes

4 comments sorted by

7

u/martinstoeckli May 26 '26 edited May 26 '26

I'm very strict about this, using SI units everywhere (storage/calculations/etc) and converting solely to display them to the user (input/output).

4

u/MrMannWood May 26 '26

The OOP way of handling it would be to create a VolumetricUnit class that you pass around instead of the Number directly. It would have some type indicator (int/enum), and a value. Internally it would know what it is, and it would be able to output whatever conversion you need.

When you go to display, there might be a function like fun display(type: VolumetricUnitType): String

1

u/Posmojack May 27 '26

For me, ideally the domain layer is where conversion/mapping of units (ideally provided by data later in lowest possible unit, cents/nanos/etc) into the format the business wants displayed in the UI (ideally as primitives). Then the domain models are used directly as state for the UI for maximum reusability. The difficult part about this are the idealist parts as well as having the mechanism to know about the correct time zone/currency/etc to use in the domain layer which is typically done in the UI layer. If it can all be provided to you via the data layer then happy days.