I am wondering whether it is necessary to validate once more the arguments passed to private methods of classes which without using Reflection would only be called by public methods in the same class.
If the private method instantiates an object that needs to be disposed (before something goes wrong because of bad arguments), an exception could be thrown (in which case the object would be disposed anyway), right?
I was viewing some of the source code of .NET (mainly the String
and Stream
classes). I found that some private methods arguments are verified with contracts, but in others no occur check.
Code that does not validate once more the arguments (taken from the String
class). In this case a NullReferenceException
can be thrown because of the trimChars
argument.
[System.Security.SecuritySafeCritical] // auto-generated
private String TrimHelper(char[] trimChars, int trimType) {
//end will point to the first non-trimmed character on the right
//start will point to the first non-trimmed character on the Left
int end = this.Length-1;
int start=0;
//Trim specified characters.
if (trimType !=TrimTail) {
for (start=0; start < this.Length; start++) {
int i = 0;
char ch = this[start];
for( i = 0; i < trimChars.Length; i++) {
// ... more code
A code that validates the arguments twice (once in public and once in private method) is this (taken from Stream
class).
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public virtual Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
{
if (destination == null)
throw new ArgumentNullException("destination");
// ... more code goes here
return CopyToAsyncInternal(destination, bufferSize, cancellationToken);
}
private async Task CopyToAsyncInternal(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
{
Contract.Requires(destination != null);
// ... more code
}
Which is the best practice, or does it depend on the situation - whether it is a class library that is only used in a specific project or it would be used in different contexts that can't be known in advance?
Aucun commentaire:
Enregistrer un commentaire