Using conditions again and again or just create different methods [duplicate]
https://softwareengineering.stackexchange.com/questions/270163
-
06-10-2020 - |
Pregunta
I have a method,
function DoThis(bool isHuman)
{
// Do something
if(isHuman)
{
//call his dad
}
else
{
//its a animal - let animal resuce know
}
// add some blah blah code
// some more blah blah code
if(isHuman)
{
//call his mother
}
else
{
heheeee now heeeheee
}
// more code
}
Should I keep Using conditions again and again or just create different methods.
Solución
The obvious refactoring is to remove the duplication like this:
if(isHuman)
{
//call his dad
doCommonStuff()
//call his mother
}
else
{
// do animal stuff
doCommonStuff()
// do more animal stuff
}
Don't be afraid to introduce well-named methods, even if they are only called once. It's the single best way of increasing readability.
Otros consejos
Well if it makes sense you can probably use the visitor pattern or some other trick with double dispatch.
Note, these methods require you send an object since they rely on function overloading. You can maybe use the isHuman
to create dummy object just for the sake of the dispatching, but I guess that if you look at your code at a larger scale, you probably find an object that you want to send instead of the isHuman
and can be used for the design pattern.
If you are not familiar with function overloading you maybe want to start learning about vtable.
The Template Method Pattern applies to such situations.
void DoThis() {
FirstSpecificPart();
common code
SecondSpecificPart();
}
void Human.FirstSpecificPart() {
call(dad)
}
void Animal.FirstSpecificPart() {
call(animal shelter)
}