简体   繁体   中英

Stateless service-centric approach vs stateful rich models

Say I have set of items defined. Those items have to be grouped into different sets. Eg Items can be like

public Item {
    public int id;
    public String name;
}

and sets have their own settings like which items belong to this set, what is set's name etc. Now all that stuff is stored in, say xml structure.

My first idea would be to write following elements:

  • xml parser to get set's data and transform to MySet pojo

  • xml parser to get all items and transform to list of Item pojos

  • stateless service-like class say ItemsSetCreator computing final ItemsSet object containing definition of set based on MySet and list of items like

     class ItemsSetCreator { public ItemsSet createItemsSet(List<Item> items, MySet set) { // ... } } 

But another approach would be to enrich model a bit and write sht like:

  • MySet class being able to get all the items, apply internal logic to them based on xml-data and provide final ItemsSet as a result

  • etc.

I don't know which is better one. I know eg Spring promotes more service centric approach, but there is a lot of buzz recently about avoiding anemic models.

It all depends on your use case and granularity, so it's hard to answer your question definitively. Enriching models can be a good thing, but you don't want to go down that slippery slope either.

If I had to choose between highly-coupled spaghetti-code "rich" models and boring anemic models, I'd have to go for anemic models. But using reductio ad absurdum here doesn't solve anything, so we're back to my original point: it depends on your use case. Sometimes you want/need models to have behavior. Sometimes you don't. Most of the time you're somewhere in the middle.

It's your job as a developer and architect to find out how much behavior models truly need.

I would add that if whatever you're working on is distributed, I would advise against stateful models - sharing state between nodes (avoiding deadlocks and race conditions) is nontrivial.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM