I\'m writing a library that has several public classes and methods, as well as several private or internal classes and methods that the library itself uses.
In the publi
Here are my opinions:
Generally speaking, it is better to check for any invalid inputs before you process them in a method for robustness reason - be it private, protected, internal, protected internal, or public
methods. Although there are some performance costs paid for this approach, in most cases, this is worth doing rather than paying more time to debug and to patch the codes later.
Strictly speaking, however, it is not always needed to do so. Some methods, usually private
ones, can be left without any input checking provided that you have full guarantee that there isn't single call for the method with invalid inputs. This may give you some performance benefit, especially if the method is called frequently to do some basic computation/action. For such cases, doing checking for input validity may impair the performance significantly.
Now the public
method is trickier. This is because, more strictly speaking, although the access modifier alone can tell who can use the methods, it cannot tell who will use the methods. More over, it also cannot tell how the methods are going to be used (that is, whether the methods are going to be called with invalid inputs in the given scopes or not).
Although access modifiers for methods in the code can hint on how to use the methods, ultimately, it is humans who will use the methods, and it is up to the humans how they are going to use them and with what inputs. Thus, in some rare cases, it is possible to have a public
method which is only called in some private
scope and in that private
scope, the inputs for the public
methods are guaranteed to be valid before the public
method is called.
In such cases then, even the access modifier is public
, there isn't any real need to check for invalid inputs, except for robust design reason. And why is this so? Because there are humans who know completely when and how the methods shall be called!
Here we can see, there is no guarantee either that public
method always require checking for invalid inputs. And if this is true for public
methods, it must also be true for protected, internal, protected internal, and private
methods as well.
So, in conclusion, we can say a couple of things to help us making decisions:
private
method is usually where we skip such checking, but there is no guarantee that we cannot do that for public
method as well