What is object-oriented programming, and what makes a design object-oriented rather than procedural code that happens to live in classes?
Object-oriented programming is a way of arranging your code around the things that the program works with, instead of around the steps that the program performs. Each of those things becomes a class, and each class holds the data about the thing and the actions that can be done to it.
public class Main {
public static void main(String[] args) {
Cart cart = new Cart();
cart.add(new Item("Keyboard", 79.0));
cart.add(new Item("Mouse", 25.0));
System.out.println(cart.total());
}
}
So what makes a design object-oriented rather than procedural code that happens to live in classes? The test is not where the code sits. The test is whether the decisions about behaviour are attached to the data.
the procedural style the object-oriented style
---------------------------- --------------------------------
one class with static a class per thing, and each one
methods that take the data knows how to work with its own data
as arguments
the data and the rules are the data and the rules live
in different places together
adding a rule means editing adding a rule means adding a
the old class new class
And there are three things that make the difference in practice. The rules live with the data, so there is one place to look. The code is extended by adding a new class rather than by editing the old one, so you do not break what already works. And the objects can be passed around and combined, so a cart can hold a list of items without knowing what an item is made of.
And there is a fourth thing that people often forget. Objects can carry behaviour that changes. So the cart can have a discount rule inside it, and you can replace that rule without touching the code that builds the cart. That is what makes the difference between a class and an object, and it is the reason the word "object" is in the name of the idea.
So the rule to remember is this. It is object-oriented when the behaviour belongs to the data, and when you can add a new kind of thing without editing the old ones.
The next two questions in this topic look at the Java specifics and at how to answer the objection about ceremony.