I develop a restful API with nodeJS.
exports.postCreature = function (req, res) {
var creature = new Creature({
name: req.body.name, id_user: req.user._id
});
creature.save(function (err) {
if (err)
res.status(400).send(Error.setError('impossible to save the your creature', err));
else
res.status(201).send();
});
};
//CODE DUPLICATE
exports.createCreature = function(user, callback) {
console.log('Creature created');
var creature = new Creature({
name: user.username, id_user: user._id
});
creature.save(function (err) {
if (err)
callback(err, null);
else
callback(null, creature);
});
}
The two functions execute the same code but not with the same parameters. I would like to avoid duplication in my code.
How can do in order to avoid duplication of my code ?
The polymorphism is a core concept of an object-oriented paradigm that provides a way to perform a single action in different forms. It provides an ability to call the same method on different JavaScript objects. As JavaScript is not a type-safe language, we can pass any type of data members with the methods.
Polymorphism with Functions and Objects: It is also possible in JavaScript that we can make functions and objects with polymorphism.
Polymorphism takes advantage of inheritance in order to make this happen. In the following example child objects such as 'cricket' and 'tennis' have overridden the 'select' method called from parent object 'game' and returned a new string respectively as shown in the output.
Inheritance is one in which a new class is created (derived class) that inherits the features from the already existing class(Base class). Whereas polymorphism is that which can be defined in multiple forms. 2. It is basically applied to classes.
I would create another function to handle the redundancies:
function createCreature (creatureName, user, callback) {
console.log('Creature created');
var creature = new Creature({
name: creatureName, id_user: user._id
});
creature.save(function (err, creature) {
if (err)
callback(err, null);
else
callback(null, creature);
});
}
And then in your other functions:
exports.postCreature = function (req, res) {
createCreature(req.body.name, req.user, function (err, creature) {
if (err)
res.status(400).send(Error.setError('impossible to save the your creature', err));
else
res.status(201).send();
};
};
exports.createCreature = function(user, callback) {
console.log('Creature created');
createCreature (user.username, user, callback);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With