Don't Repeat Yourself (DRY)
. La razón por la cual el código repetido es un problema es porque cualquier cambio requiere un código de corrección en varios lugares. Esto generalmente significa más trabajo para los programadores y más espacio para errores. Observe en el siguiente ejemplo que Bird
y Dog
comparten el método de describe
: Bird.prototype = {El método
constructor: pájaro,
describe: function () {
console.log ("Mi nombre es" + this.name);
}
};
Dog.prototype = {
constructor: perro,
describe: function () {
console.log ("Mi nombre es" + this.name);
}
};
describe
se repite en dos lugares. El código se puede editar para seguir el principio DRY
creando un supertype
(o padre) llamado Animal
: función Animal () {};Ya que
Animal.prototype = {
constructor: animal,
describe: function () {
console.log ("Mi nombre es" + this.name);
}
};
Animal
incluye el método de describe
, puedes eliminarlo de Bird
and Dog
: Bird.prototype = {
constructor: pájaro
};
Dog.prototype = {
constructor: perro
};
eat
se repite tanto en el Cat
como en el Bear
. Edite el código en el espíritu de DRY
moviendo el método de eat
al supertype
Animal
. Animal.prototype
debe tener la propiedad eat
.
testString: 'assert(Animal.prototype.hasOwnProperty("eat"), "Animal.prototype
should have the eat
property.");'
- text: Bear.prototype
no debe tener la propiedad eat
.
testString: 'assert(!(Bear.prototype.hasOwnProperty("eat")), "Bear.prototype
should not have the eat
property.");'
- text: Cat.prototype
no debe tener la propiedad eat
.
testString: 'assert(!(Cat.prototype.hasOwnProperty("eat")), "Cat.prototype
should not have the eat
property.");'
```