I have declared a simple method to try converting input from a text box into an int like so:
int TryConvertTextToInt(TextBox box)
{
//do try catch
}
My IDE (SharpDevelop) tries to give me some refactoring advice; specifically, that the box parameter could be declared as a base type (the two options the tool gives me are TextBoxBase and Control). I know I won't want to use this method with anything other than a TextBox, and if I do change my mind down the road, the parameter type being specific will remind me that the method may need to be changed slightly to accommodate a wider range of inputs. I don't see the value in changing the type right now, since I don't anticipate the latter case and the project is a small one.
Is there a reason I would want to do this that I'm missing, or is the IDE just being overly helpful?
In your particular case, it probably doesn't make too much of a difference. Given that you're passing a TextBox
, you probably won't ever want to pass anything other than a TextBox
.
However, speaking in the more generalized case, it is often best practice to have the most basic parameter types and the most specific return types possible for methods. The idea is, as your IDE suggests, to allow for use of the method in a variety of places later down the road.
As an example, we can look at the classic case of a collection. Many developers will write code that accepts a List<T>
as a parameter, then do a foreach
through that. That's great, if they only ever deal with List<T>
, but if they then want to, down the road, expand out to incorporate some LINQ expressions in there, suddenly they're dealing with an IEnumerable<T>
. Nothing in that foreach
loop would require a List<T>
, but because they didn't bother to use the base class (or interface in this case, which is often better), they'd now either have to change the method signature--a non-breaking change but still never a nice one to have to make--or add a .ToList()
to their LINQ, which disrupts many of the advantages to using LINQ (since suddenly they have to loop through the collection probably at least three times).
You always want to make sure you're accepting the minimal class or interface you can, that still provides the members that you are going to need. Of course, don't be too conservative: if there's a right way and a generalized way, choose the right way, but if those are the same, generalized is best.
But again, in your case, I don't think it's much of a big deal. The chances are likely higher that you'll want to use other members that TextBox
provides, than that you'd want to pass other inheritors of TextBoxBase
or Control
to your method. Really, it's all just dependent on your application. Review what you have and what you need, then build your response to this warning off of that. To me, it sounds like you're rightfully happy leaving it, and that's what you should do. But for future reference, this is the idea.