DotNetDave Says… All Data Coming into a Type Must Be Validated!

Do you use object-oriented programming? If so, do you validate data coming into your types? If not, then you have broken the first pillar of OOP which is encapsulation. I have spoken and written about this for most of my career. Sadly, even in the code base I am currently working on, most code I review does not do this at all.

dotNetDave Says... All Data Coming Into a Type MUST be validated.
Examples

Take the following example:

public static string GenerateFile(string fileName, int fileLength = 1000)
{
    var fakeText = GenerateWord(fileLength);

    File.WriteAllText(fileName, fakeText);

    return fileName;
}

In this case, the problem is fileName and fileLength are not  being validated. What if fileName is null? What if fileLength is -100?

Here is how the method actually appears in one of my OSS assemblies:

public static string GenerateFile([NotNull] string fileName, int fileLength = 1000)
{
    Validate.TryValidateParam(fileLength, 1, int.MaxValue, nameof(fileLength));

    var fakeText = GenerateWord(fileLength);

    File.WriteAllText(fileName, fakeText);

    return fileName;
}

In this case, I am using the [NotNull] attribute for fileName. Then I am using a validation method from my OSS called TryValidateParam() where I am ensuring that fileLength is 1 to the max value of int. In either case the proper exception type is thrown if the data is not valid.

The first lines of any method or property must have validation code, or you are breaking encapsulation and OOP.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.