Code Over Comments
Comments should be used to add description where it cannot be added in code.
Rationale
Comments distract from writing descriptive and readable code that express intent. If code a code needs commenting to explain it, then it is a smell that the code needs to be made simpler.
Examples
Example that breaks the rule
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
class Pricing {
BigDecimal price(BigDecimal price) {
// if the price is high value then use a lower margin
if(price > 100.0) {
// add 5% margin onto the price
price = price * 1.05;
} else {
// add 10% margin onto the price
price = price * 1.1;
}
// add vat onto the price
return price * 1.2;
}
}
|
Example that doesn’t break the rule
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
class Pricing {
private const BigDecimal HighValueProductThreshold = 100.0;
private const BigDecimal HighValueMargin = 1.05;
private const BigDecimal LowValueMargin = 1.1;
private const BigDeimcal VAT = 1.2;
private boolean isHighValueProduct(BigDecimal price) {
return price > HighValueProductThreshold;
}
private BigDecimal addMargin(BigDecimal price) {
if(isHighValueProduct(price)) {
return price * HighValueMargin;
}
return price * LowValueMargin;
}
private BigDecimal addVat(BigDecimal price) {
return price * VAT;
}
BigDecimal price(BigDecimal price) {
return addVat(addMargin(price));
}
}
|