I have a class that contains insurance benefits. There are many values, such as coverage level percentages, maximums, deductibles, etc. Most of the time, I only need a handful of display friendly properties, which are aggregates of all of the other properties. Other times, I need the values to perform more in-depth calculations.
Currently I use viewmodels to aggregate the properties into a display friendly values. However, each time I use the display friendly properties in a new app, I have to recreate the viewmodel. If I want to change how it's displayed, I have to revisit every app.
I considered either 1)creating a 'ForDisplay' property in the class which is, in effect, a built in view model of sorts. I've also considered a shared viewmodel where I pass the class(model) through a shared view model for transformation.
Is there a better way to make my class maintain it's detail AND it's display friendly values without visiting every app if I need to change something?
-
1Maybe implementing helper classes for display conversion may help.πάντα ῥεῖ– πάντα ῥεῖ09/09/2019 19:29:07Commented Sep 9, 2019 at 19:29
1 Answer 1
Hard to give really detailed advice based on the information given, but I sometimes solve similar problems with simple inheritance;
In the contrived example below, I can pass around MyModel throughout code and use the 'detailed' parts. When I want to simplify properties for display, I create an instance of the child model from the parent. This is nice because I don't necessarily have to re-write the properties of the model class. Also, I can add reader only simplification to the child class without adding noise to the model that is used elsewhere.
A disadvantage is that it does expose all parent properties in the display model. If that doesn't fit your needs then this may not be a good choice for you.
Also, the method "from_my_model" uses a primitive copying technique. If your parent model is complex, and you want to copy all of its complexities, you will need to investigate better ways of copying the parent class.
class MyModel:
def __init__(self, interest=3.124569):
self._interest = interest
@property
def interest(self):
return self._interest
class MyDisplayModel(MyModel):
def __init__(self):
super().__init__()
@property
def interest(self):
return round(self._interest, 2)
@staticmethod
def from_my_model(parent):
instance = MyDisplayModel()
instance.__dict__ = parent.__dict__.copy()
return instance
if __name__ == '__main__':
parent = MyModel()
print(parent.interest)
display = MyDisplayModel.from_my_model(parent)
print(display.interest)