8

DotNetDave Says… All Data Coming into a Type Must Be Validated! – dotNetTips.com

 2 years ago
source link: https://dotnettips.wordpress.com/2021/12/08/dotnetdave-says-all-data-coming-into-a-type-must-be-validated/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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.

Tagged dotNetDave Says

I live in San Diego, Ca USA View all posts by dotNetDave


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK