Where should the code processing the state of the object be?

Viewed 31

I have a class as follows:

data class ProductState(
  val id: Int,
  val products: MutableMap<Int, MutableSet<Int>> = mutableMapOf(),
  val customerTopics: Topic = Topic()
)

It is basically a data class.
Now I have a function that among other things, processes the products and customerTopics and creates some output based on the processing.
But it seems to me that it is not a good idea to have the logic in the function.
My question is:
Do we create methods inside the data class for the processing of the object'state? If so would it be some companion object? Or is there some other design pattern that deals with this better?

1 Answers

In kotlin you have several options:

  • Additional method on the data class (if it should be called in multiple other places);
  • Public extension method in the same file as the data class (if it should be called in multiple other places but you want to keep your data class simple and have the handling methods separated);
  • Private extension method in the same file as the only place where it is called (this only applies if this processing is to be called in a single place in your code);
  • Private method in the only place where this processing is needed.

The best place really depends on what the processing is (is it very specific to ProductState or does it need additional data? If it is very specific then it may make sense to keep it as a ProductState method or an extension function) and in how many places it will be triggered (if in a single very specific place, then maybe keeping it along-side that piece of code as a private extension function or private method might be the best option).

Related