Card 01/ 10

ConceptDifficulty: Beginner1 min

Giving a Piece of Behaviour a Name You Can Call

The same four lines that work out VAT appear in three places in your file. You fix a rounding mistake in one of them and ship the other two unfixed.

A method is those four lines given a name, written once, and called from wherever they were. What changes is not how much code exists — it is how many places have to be right.

java
double vatOn(double amount) {
    return amount * 0.20;
}

double lineVat = vatOn(19.99);
double deliveryVat = vatOn(4.99);

Three things are happening in that declaration. double says what the method hands back. vatOn is the name callers use. (double amount) says what it needs before it can do anything, and the name in there is used only inside the body.

So a method is a name for a decision about where correctness lives. The rounding fix now happens in one place, and every caller gets it without being touched.