Nella documentazione di Java , si afferma:
Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
Da Pulisci codice (pagina 25):
When constructors are overloaded, use static factory methods with names that describe the arguments
For example:
Complex fulcrumpoint = Complex.FromRealNumber(23.0);
is generally better than
Complex fulcrumPoint = new Complex(23.0);
Ma secondo i commenti a questa risposta , quando si tratta di questo codice:
private Weapon(String name, int damage)
{
this.name = name;
this.damage = damage;
}
public void attack(Enemy enemy){ // code to cause damage to enemy }
public static Weapon Sword(String name, damage){
return new Weapon(name, damage);
}
public static Weapon Sniper(String name, damage){
return new Weapon(name, damage);
}
It'll compile and execute, but it violates the Principle of least astonishment.
L'autore di Clean Code ha violato il Principio di Least Astonishment per scrivere quello che è considerato codice pulito?