When you start designing an object model from scratch, how do you decide what the classes should be?
You start from the language of the business, not from the database tables and not from the code. You write down the nouns, you check which ones have rules of their own, and those are your classes.
the step what you do
-------------------------------- --------------------------------------------
1. write down the nouns the things the business talks about
2. write down the verbs the things that can be done to them
3. pair them up each verb belongs to one noun
4. look for the rules the things that have rules are
the classes
5. look for the value objects the things that are just a value
are records
And the test for a class is the sentence test. If you can say "a StockLevel has a rule about how many items are left" then it has a rule and it wants to be a class.
the thing does it have a rule? the answer
---------------------------- --------------------- ----------------------
a product no, it is a name and a record
a price
a stock level yes, it cannot go a class
below zero
an order yes, it has lines and a class
a total
a date no, it is a value a record
And there are three mistakes that people make at the start, and they are worth knowing about.
the mistake what goes wrong
-------------------------------- --------------------------------------------
one class for everything you get a god object
a class for every noun you get a class with no behaviour
copying the database tables the model cannot change
And the first one is the most common. So the business talks about products, stock levels, orders and customers, and somebody puts all four into one class called Shop. And then it grows until it has fifty methods.
And the second mistake is the opposite one. So there is a class for the product and a class for the price and a class for the quantity, and each one has two getters and nothing else. That is three files that say nothing.
And the third mistake is the one that hurts the most later. The model is a copy of the database tables, so every column is a field and every table is a class. And then the business asks for something that does not fit the tables and you have to change the database as well.
And there is one more thing that is worth knowing about, and it is the order to do the work in. Start with the behaviour, not with the data. So write down what the system does, in sentences, and then ask which object each sentence belongs to.
the sentence the object it belongs to
----------------------------- ----------------------------------
"the order can be shipped" the order
"shipping needs a stock level" the stock level
"the stock level cannot go the stock level
below zero"
So the rule to remember is this. Take the nouns from the business, take the rules with them, and leave the values as records.
The next two questions in this topic show a small model and the common mistakes.