C# how to shorten multiple If expressions
The correct implementation of the method should be something like following:
public bool IsProductionReadyToStart()
{
bool isValid = true;
isValid &= !IsComponentsRequired || ValidatedComponents;
isValid &= !IsGeometriesRequired || ValidatedGeometries;
isValid &= !IsPokayokesRequired || ValidatedPokayokes;
isValid &= !IsTechnicalFileRequired || ValidatedTechnicalFile;
isValid &= !IsStandardOperationSheetRequired || ValidatedStandardOperationSheet;
isValid &= !IsOperationMethodRequired || ValidatedOperationMethod;
return isValid;
}
when not uing &= then you erase all previous results you checked instead of combine them.
It looks like a collection
public class Validation
{
public bool Required { get; set; }
public bool IsValid { get; set; }
}
var validations = new[]
{
new Validation { Required = true, IsValid = true },
new Validation { Required = false, IsValid = true },
new Validation { Required = true, IsValid = false },
};
// return true only when all required validations are valid
public bool IsProductionReadyToStart()
{
return _validations.Where(v => v.Required).All(v => v.IsValid);
}
I'd go with:
if (IsComponentsRequired && !ValidateComponents) return false;
if (IsGeometriesRequired && !ValidatedGeometries) return false;
...
return true;
This reads more like a checklist.