- Home /
Refactor switch statement
I think I over use switch and if-else statements. But!.. How would You refactor, for example, this code? I am trying to avoid frequent usage of swtiches and if's.
This method recieves PlayersAttackParams class and based on the attack type calls a particular class of enemy damage. One enemy has 6 types of damages and each damage is a independent class.
public void Damage(PlayersAttackParams playerAttackParams)
{
ResetDamageTrigges();
switch (playerAttackParams.attackType)
{
case PlayerAttackType.lightUppercut:
case PlayerAttackType.leg:
enemyDamageEndOfPunchSequence.Damage(playerAttackParams);
break;
case PlayerAttackType.leftHand:
case PlayerAttackType.rightHand:
enemyDamageByHands.Damage(playerAttackParams);
break;
case PlayerAttackType.getUp:
case PlayerAttackType.flyingKick:
case PlayerAttackType.powerUppercut:
enemyHeavyDamage.Damage(playerAttackParams);
break;
case PlayerAttackType.throwGrab:
throwGrab.Damage(playerAttackParams);
break;
case PlayerAttackType.throwHeadPunch:
enemyThrowPunchByHead.Damage(playerAttackParams);
break;
case PlayerAttackType.doThrow:
enemyDoThrow.Damage(playerAttackParams);
break;
}
}
One alternative, which may need the same amount of code but looks nicer, would be to use a dictionary with keys of type PlayerAttackType and values of type Action, which are the response functions.
However, before I post that response, it would be better for you to post your full scripts, as I think using interfaces would be a better choice.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Input.mousePoition for controllers 0 Answers
Brackeys EnemyAi Script 0 Answers