Finding Classes and Responsibilities
Learn how to decide which things in a problem become classes, how to give each class the right jobs, and how to spot a class that does too much.
Many beginners think that finding the right classes needs talent or luck. It does not. There are simple, repeatable tools for it. In this lesson you will learn three of them: reading the nouns to find classes, reading the verbs to find methods, and using a CRC card to check that each class has a clear, small job.
We will use one example throughout: a food delivery app. Keep it in your mind. A customer orders food from a restaurant, the restaurant prepares it, and a delivery agent brings it to the customer's address. The customer pays online.
01Start with the nouns
Read the description again and underline every noun:
A customer orders food from a restaurant. The restaurant prepares the order and a delivery agent brings it to the customer's address. The customer pays online.
That gives us a list of candidates: customer, food, restaurant, order, delivery agent, address, payment (the customer "pays", so a payment exists in the story).
A candidate is not yet a class. Nouns are only suggestions. Now we filter them.
02Class, field or ignore?
For each candidate, ask three questions:
- Does it have behaviour or rules of its own? (Can it do things or protect a rule?)
- Does it hold several pieces of data that belong together?
- Does the system need to track it over time, or can it exist and change on its own?
If the answer is "yes" to one or more, it is probably a class. If it is just a single value such as a name or a price, it is a field inside another class. If it is only part of the story and has nothing to do with the system, ignore it.
| Candidate | Decision | Reason |
|---|---|---|
| Customer | Class | Has a name, contact details and a history of orders |
| Food | Class, named MenuItem | Has a name, a price and an availability; the restaurant changes it |
| Restaurant | Class | Owns a menu and prepares orders |
| Order | Class | The centre of the system: links the customer, the items and the status |
| Delivery agent | Class | Has a location and a status such as free or busy |
| Address | Small class | Holds street, city and PIN code together, and can validate them |
| Payment | Class | Has a method, an amount and its own status such as paid or failed |
| "online" | Ignore | Not a thing in the system; it describes how, not what |
Two choices deserve a comment. We renamed Food to MenuItem, because a class name should describe the role it plays in the system, not just the everyday word. And we made Address its own small class, because it holds several related values and has its own rule (a valid PIN code). If the app only stored one line of address text, a String field would be enough. The decision depends on the requirements, which is why Step 1 of the method comes first.
03Now the verbs: who does what
Next, underline the verbs: orders, prepares, brings, pays. These become methods, and the question is always the same: which class owns the information needed to do this?
A useful rule: put a method on the class that owns the data it needs. Let us test it with a small question: "who calculates the total price of an order?"
The total needs the list of items and their prices and quantities. Which class holds the items? Order. So Order calculates its own total.
public class Order {
private final List<OrderItem> items = new ArrayList<>();
private OrderStatus status = OrderStatus.PLACED;
public void addItem(MenuItem item, int quantity) {
items.add(new OrderItem(item, quantity));
}
public long totalInCents() {
long sum = 0;
for (OrderItem line : items) {
sum += line.priceInCents() * line.quantity();
}
return sum;
}
}Now see what happens when the logic is in the wrong place:
public class Restaurant {
// The restaurant reaches into the order to do the order's own job
public long calculateTotal(Order order) {
long sum = 0;
for (OrderItem line : order.getItems()) {
sum += line.getPriceInCents() * line.getQuantity();
}
return sum;
}
}The second version looks harmless, but it has hidden costs. Order must now expose all its items through getters so that others can reach inside. Tomorrow you need to add a discount, and you must hunt for every place that calculates a total. The rule is spread out, so it is easy to forget one place and get two different totals in two screens.
This idea is sometimes called the Information Expert rule: give a responsibility to the class that has the information. It is one of the most useful habits in LLD.
04CRC cards: a simple tool to check your classes
A CRC card is a small card you write for each class. CRC stands for Class, Responsibilities, Collaborators. You can do it on paper, on a whiteboard, or just in your head during an interview.
- Class: the name at the top.
- Responsibilities: a short list of what the class knows and does.
- Collaborators: the other classes it needs to do its job.
A CRC card gives you two quick checks:
- Too many lines under Responsibilities (more than five or six)? The class is doing too much. Split it.
- Almost nothing under Responsibilities? The "class" may just be a field of another class.
And the Collaborators column is a ready-made list of lines for your class diagram: Order connects to Customer, MenuItem and Payment. In the next lesson, you will learn how to draw them.
05The God class smell
Sometimes one class grows to do everything. People call it a God class because it "knows everything and does everything". In our app it might look like this:
public class OrderManager {
public void placeOrder(/* ... */) { /* validate, price, charge card, send email, save */ }
public void cancelOrder(/* ... */) { /* refund, send email, restore stock, save */ }
public void assignAgent(/* ... */) { /* find agent, update location, notify customer */ }
// and dozens more methods
}Why is this bad?
- Hard to understand. To read one rule you must read hundreds of lines.
- Hard to test. To test the pricing you must set up payments and emails too.
- Hard to change. A change in how emails are sent forces you to edit the same class that handles prices, and you may break one while fixing the other.
- Hard for a team. Two people editing the same class cause conflicts.
The fix is to give each job to a class that owns it:
| Job | Better owner |
|---|---|
| Keep items, calculate the total, track the status | Order |
| Charge the customer | PaymentService |
| Tell the customer something happened | NotificationService |
| Save and load orders | OrderRepository |
| Choose a delivery agent | AgentAssigner |
Each class now has one clear reason to change. This idea, one class, one reason to change, is the first SOLID principle, and you will study it in a later module.
06Names matter
A good name saves a hundred words of explanation.
- Use nouns for classes:
Order,Customer,DeliveryAgent. - Use verbs for methods:
addItem,calculateTotal,assignAgent. - Say what the class is, not only what it holds.
Orderis better thanOrderData. - Be careful with vague words such as
Manager,Helper,UtilandHandler. They often hide a class that does too many things. Ask yourself: what does it really do? Then use that word in the name.
07Common mistakes
- Turning every noun into a class. A price or a name is a field. Too many tiny classes make the design hard to read.
- Classes that only hold data. If a class has only getters and setters and all the rules live somewhere else, the rules are in the wrong place.
- Putting a rule in the class that is easiest to reach. Always ask which class owns the data that the rule needs.
- Finding classes from the technology, not from the problem. Start from the real things in the problem. Add technical classes, such as a repository, only when you need them.
- Never revisiting. Your first list is a draft. Walking through scenarios will show you what to add or merge.
08In the interview
- Where do you put logic that needs data from two classes? First check whether one class can own it, because it holds most of the data. If it truly involves two, create a small coordinating class, often called a service, whose only job is to combine them.
- What is a God class and how do you fix it? A class that does many unrelated jobs, so every change touches it. Fix it by moving each job to a class that owns it, so each class has one reason to change.
- Is a small class with only two fields too small? Not if it holds a rule, such as an address that validates its own PIN code. It is too small only if it is just a single value with no rules.
09Check your understanding
Quiz · 4 questions
0 of 4 answered
1. When is it reasonable to make Address its own class instead of a plain String field?
2. Where should the method that calculates the total price of an order live?
3. What is a warning sign that a class is a God class?
4. On a CRC card, what do the Collaborators tell you?