Method named after its enclosing class
ID |
apex.maintainability.method_same_name_class |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
medium |
Remediation Effort |
low |
Resource |
Naming |
Language |
Apex |
Description
Reports a method whose name is the same as the class that declares it while carrying a return type, which makes it a normal method and not the constructor it looks like.
Rationale
A constructor in Apex is a method with the class’s name and no return type; add a return type and the same line becomes an ordinary method that the compiler will never call on new. The two forms differ by one token, so a constructor that acquires a return type during an edit turns into dead code silently - the object is still constructed, the initialization inside the method never runs, and the fields stay null.
The following code illustrates the pattern detected by this rule:
// FLAGGED: Method named after its enclosing class
public class Invoice {
private Decimal total;
public Invoice() {
this.total = 0;
}
public Decimal Invoice(Decimal amount) {
return amount;
}
}