I work at an application that receives data from user and I try to write a validator function for it, but I'm not sure if this is the correct way to proceed.
Example: The user will input a number (as string, don't ask why I don't use an int, let it be a string), let's say "103", and I'will use this number inside a function, but first, at the beginning of that function I call a validator function:
private bool ValidateCommandCode(string code)
{
bool isValid = false;
byte commandByte = new byte();
if (byte.TryParse(code, out commandByte))
{
isValid = true;
}
else
{
Log.Error($"Command number {CommandCode} for the request is not valid!");
isValid = false;
}
return isValid;
}
private async void MainFunction()
{
if (ValidateCommandCode(CommandCode) == false)
return;
// ... do the magic with the CommandCode ...
}
in the same manner, I want to validate another field filled by the user: e.g of data: 000A000B
private bool ValidateRequestData(string data)
{
bool isValid = false;
if (!String.IsNullOrEmpty(Payload) && !String.IsNullOrWhiteSpace(Payload))
{
if (Payload.Trim().Replace(" ", "").Length % 2 != 0)
{
Log.Error($"Payload (Data) {Payload} for the request doesn't have an even number of bytes!");
isValid = false;
}
else
{
isValid = true;
}
}
else
{
isValid = true;
}
return isValid;
}
Is this a good way to proceed? Aren't so many flags "isValid" too confusing?