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: Bird,
describe: function() {
console.log("My name is " + this.name);
}
};
Dog.prototype = {
constructor: Dog,
describe: function() {
console.log("My name is " + 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
:
function Animal() { };Dado que
Animal.prototype = {
constructor: Animal,
describe: function() {
console.log("My name is " + this.name);
}
};
Animal
incluye el método de describe
, puedes eliminarlo de Bird
and Dog
:
Bird.prototype = {
constructor: Bird
};
Dog.prototype = {
constructor: Dog
};
eat
se repite tanto en Cat
como en 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.");'
```