Question

List list = new ArrayList();
MyObj mine = new MyObj();
list.add(mine); 

I like to add object to list before manipulating the object so that i don't forget to add it later, may be i work in crazy enrichment logic where i like this way more

mine.setXXX(stuff);

This is the way I always used to add objects in a list,

Just now i have a use case where TreeSet make more sense, so naturally I wanted to do something like this:-

Set set = new TreeSet();
MyObj mine = new MyObj();
set.add(mine);
mine.setXXX(stuff); // add setters here

but the issue here is that Treeset needs to have variables used in compareTo methods to be initialized before adding object to the list.

Ok, I can take care of it.

But my worry and question is:- Is there a way i can enforce to the developer who may be using my models where I have used Treeset to not repeat my mistake. i.e. to enforece them to intiate the myObject variables before adding the object to the set. Though developers should know this and should take care of it, but still is there a way force it or some best practice around that.

Was it helpful?

Solution

No, there is not a general way to enforce this. The best way to do so is to put immutable objects in the set only that cannot be modified. Rather than having a setXXX method on your object, make it configurable through the constructor and not editable.

OTHER TIPS

Simple: the values for the fields that are mandatory should be passed along in the object's constructor, and never provide a constructor that doesn't include at least all the mandatory fields. Then you can set them in the constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top