harish.venkat
harish.venkat

Reputation: 139

Should I make the object mutable?

I have a service A which listens for messages from a Queue and calls another service B to get some values assume val1...x.

Assuming my entity is

Entity
|- val1
|- val2
|
... val1n

The values from both the service B populates assume x vals in the entity. And after the service call service A computes some values and populates other fields in the entity.

Possible approaches for modeling the Entity

[1] Make Entity immutable and make every update to the entity copy all values 1...x to make a new object.

[2] Make Entity partially immutable like declaring val1...x final and others non-final, so I can use setters to set the values on them.

EDIT : [3] Keep passing around Builder Object and when all values val1...n has been populated call the build() function.

EDIT2 : [4] Have two separate object (private inner) immutable - val1...x and immutable valx..n. Everytime some update happens on the valx..n I will create new copy of mutable object and refer to the immutable one.

Upvotes: 1

Views: 155

Answers (2)

hzpz
hzpz

Reputation: 7966

Make service B return an immutable value object (let's call it ExtendedEntityInformation), then use the values from service A and that object to create your immutable Entity. You might even just store the ExtendedEntityInformation object in your Entity and if needed, implement getters on Entity that delegate to getters in ExtendedEntityInformation.

Upvotes: 1

szefuf
szefuf

Reputation: 520

If I understand correctly you are willing to create object in one service, populate some of the fields, than pass it to another service, and populate rest of them? After this, the object is complete?

If so, I would use Builder patter, populating fields of builer and once it's complete - build immutable object

Upvotes: 2

Related Questions