[SWIFT] [iOS] [MVVM] Should Date to String conversion be done in ViewModel or View?

theme

In an app made with MVVM, suppose there is a value stored in Model (some database) as Date.

When displaying it on the screen,

--Format of yyyy / MM / dd HH: mm --Time zone is Japan

The specifications are as follows.

At this time, ** Should this conversion & formatting be done in the ViewModel layer? Or should it be done in the View layer? ** ** That is the theme covered in this article.

Consideration

The following is my own consideration.

To conclude first, I think ** in principle, it's better to do it in the ViewModel layer ** I think.

It seems to be the responsibility of "how to show", and in practice, it is often a simple code to write an extension, so I think some people think of doing it with View ...

In the case of editing Date → String, in addition to the locale, "Does the time zone match the terminal settings? Is it fixed in Japan?" Or "What if the value coming down from the API is inappropriate as the date and time?" This is because it often includes issues in the domain area that go beyond just "how to show".

The same is true for numbers, for example, if you just edit the number 1234567 with a comma such as 1,234,567, I think that there is no problem as the responsibility of the View layer, but if this is a currency, there is usually a problem in the domain area. Since it will be included, I think it is better to make it the responsibility of the ViewModel layer.

In other words, it is appropriate to classify it as the ViewModel layer in the case of editing processing that includes issues in the domain area, and the View layer ** in the case of simple format editing that does not include it.

By making such a division, I think there is an advantage that ** it becomes easier to write unit tests of logic including issues in the domain area **.

Reference article

Sample MVVM pattern introduced to eliminate FatViewController in large iOS apps

Recommended Posts

[iOS] [MVVM] Should Date to String conversion be done in ViewModel or View?
How many times should string concatenation be changed to StringBuilder?
Introduction to Rakefile that can be done in about 10 minutes