Reputation: 225
I know this problem has already been addressed on the site. Though, there are many different opinions and I'd like to understand it deeper to know how to face some particular situations. Let us say I have the following code. I will write in C#, though it isn't a strictly related C# question.
class Player
{
private int dexterity;
public int Dexterity{
get => dexterity;
set{
//Here I need to validate: problem 2
dexterity = value;
UpdateArmorClass(); //Armor class should be modified any time dex is
}
private int armorClass;
public Player(int dex){
Dexterity = dex;
}
private void UpdateArmorClass(){
//Should I validate here? Problem 3
armorClass = 10 + Dexterity;
}
}
//Here is main with user input: problem 1
Let us say a user is asked to input its detxterity, which must be non negative, to create its character. Now I face three situations:
Here's the last method:
public float Hit(int armorClass){
if(armorClass >=0) //calculate probability of being hit
//return probability
}
Bonus question (related to the previous questions of course): is instantiating a new exception really that expensive? Or is it only the try-catch part? To me, it seems like instantiating a new object and that's all. Though, I may be wrong and that's why many say you shuould not use exceptions if not really needed.
Upvotes: 0
Views: 140
Reputation: 614
Here I am facing the big dilemma: use exceptions or not? I'd personally use them to stop the program from generating an invalid object. Though, many discourage exception usage due to its expensiveness.
Use the exception. Exceptions are only expensive when raised and it's always better to raise an exception than to end up with corrupted objects. If your values come from user input, handle invalid values where you acquire it from user, separately. This way, you can safely call those methos/set values from code and you are not raising exceptions when user inputs invalid values. Additionaly, sometimes there are special values that you may want to let to use, that should not be allowed for user to input.
Problem 3:
If your private field is always validated before set, there is no point in checking if its valid on get. In your code example, adding 10
to any non-negative number will always return non-negative value.
Bonus question: All raised exceptions have to be handled somewhere, so I dont think it does matter if its the raising exception part which is expensive, or the catching part.
Upvotes: 2