0
\$\begingroup\$

I'm making a simple game with sliders, where there is a damage over time function, the main focus of the player is to upkeep the player health as long as possible by clicking corresponding buttons. My question is, should I create a single function called ChangeHealth which will need a float parameter to change it. Or I can make to separate functions where the hp can be altered with an only function.

\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

You could separate them for additional clarity, but the core function of altering the health value itself I think should just be a method called 'AdjustHealth', and you can provide a positive or negative value to change; atleast that's the approach I generally take.

You can then have an independent Heal / Damage method that both call on the AdjustHealth method.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Thank you for clarification, i'll use your approach with some events, that call the heal/damage function \$\endgroup\$
    – koogel
    Dec 25, 2022 at 17:58
2
\$\begingroup\$

I think there is more nuance to this than just "whichever works best in code". For example, you might want to have certain events in your game fire when a character is healed or take damage, e.g. an ability might heal you for 10% of the damage you deal, so it listens to the OnDamaged event which is fired when you call DealDamage(Number) from code.

Of course you could do this with a generic ChangeHealth(Number) function as well by calling OnDamaged when the value is < 0 and OnHealed when the value is > 0, but what if we want to fire the OnHealed event even if we are healed for a negative value (so effectively taking damage)? Then our logic of checking for <0 or >0 inside the ChangeHealth function would not work; it would call the wrong function when we are healed or damaged for a negative value.

In my opinion I would design two explicit functions, one DealDamage and one ApplyHealing, that way if you ever need to do explicit logic for one of the two cases there is never any ambiguity about what the caller meant to do. Of course, if changing health in your codebase is more complex than doing health -= damage you might want to extract the health-changing logic into its own separate private utility function that is only used internally by the two other functions.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .