Clamp health with using properties or calling clamp everytime

So I’ve been brushing up on my programming knowledge and I found that that C# has a useful tool called properties. So I’ve been thinking of revisiting some of the scripts and cleaning them up. My current implementation of player and gameobject health calls math.clampf whenever it is modified, something like this:

heal(healAmount){
    health += healAmount;
    health = math.clampf(health, 0, maxHealth);
}
damage(damageAmount){
    health -= damageAmount;
    health = math.clampf(health, 0, maxHealth);
}

I was wondering if it is better/more efficient to make my health a property, something like this:

public float Health {
    get { returm health; }
    set { health = Mathf.Clamp(health, 0, maxHealth); }
}
private float maxHealth;
private float health;

I’m assuming the natural advantage of this would be that I wouldn’t need to call clamp whenever I want to modify health, but do you guys think I’m unnecessarily complicating/damaging readability by using a Properties?

The upper and lower limits are the characteristics of the health, so maybe it’s better to use property

I would prefer the property here as to cut down on repetition (DRY coding principle).

A property’s the better option in this case, as it means Health will always be a valid value, and avoids a lot of potential errors. The performance difference would be minimal, and also a moot point unless you’re setting Health hundreds of times a second.

I (personally) would use a Hurt() or Heal() function like you originally had. Personally I would say that the only risk with putting important game logic as a property (although I appreciate that’s what properties are somewhat for) is that it is easy to forget it exists. Say one day you want to set your player’s health above max health for some reason (e.g. for a quirky powerup or godmode or something), only to find out it doesn’t work and you can’t figure out why because you forgot you put the clamp as a property (this is especially true if you’re coding collaboratively). If it were a function, you would intuitively go to the Hurt() function and realise your mistake. I don’t think people would intuitively check the property. But I think that’s just my OCD ;). Plus, if one day you want to add extra logic to the player getting hurt, you can easily extend the function. You could also extend the property, but then that’s using a property to do a function’s job, which is odd for me. But whatever feels best for you.

1 Like