Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception Handling - is this good practice?

I am wondering if what i am going to do is good or bad thing. I have that class:

public class Element : IElement
{
    public float? Max { get; private set; }

    public float? Min { get; private set; }

    public float? Average { get; private set; }

    public bool HasValue { get; private set; }


    public void SetRange(float? min, float? max)
    {
        if (min >= max)
        {
           throw new WrongElementValueException("Min must be greater than max!");
        }
        else if (min < 0f || max < 0f)
        {
           throw new WrongElementValueException("Min/max must be greater than 0!");
        }
        else if (min > 100f || max > 100f)
        {
           throw new WrongElementValueException("Min/max must be lesser than 0!");
        }
        else
        {
            Min = min;
            Max = max;
            Average = (min + max)/2f;
            HasValue = true;
        }
    }
}

The user will set the values using SetRange() method. But he has some constraints like Min must be bigger than Max, and neither of them should be bigger than 100 or lesser than 0.

Should I use those exceptions in this place? Or is there any better method to handle wrong user input? I hope my question isn't to general.

like image 357
bartosz.baczek Avatar asked Dec 25 '22 17:12

bartosz.baczek


1 Answers

This is an appropriate practice, yes.

Though I imagine consuming code would be expecting an ArgumentException rather than this exception type, but that may be a relatively minor point.

When the input is invalid, and the object has no way of meaningfully continuing otherwise, then throwing an exception is an appropriate and expected response. It's up to consuming code to use the object properly, handle errors, report back to the user, etc.

The alternative is for this object to "try to figure out what to do" which often leads to some pretty bad coding practices. For example...

  • Suppose you instead want to return an error message instead of throwing an exception. What if consuming code doesn't check for that error message? The object would be left in an unknown and invalid state and could quietly introduce bugs. Whereas if consuming code didn't check for the exception then the program would clearly and obviously fail and would need to be appropriately corrected. Clear and obvious failures are a lot easier to support than subtle and unnoticed ones.
  • Suppose you want to "show a message to the user" instead. That would requiring tightly coupling this object to a presentation layer, which defeats object oriented principles and makes the code very rigid and difficult to maintain.

This object does one thing, and only that one thing. If it's invoked in such a way that it can't do that one thing, an exception is an expected and appropriate failure condition.

like image 72
David Avatar answered Dec 31 '22 13:12

David