Business Validation Logic Code Smell

后端 未结 14 1127
醉酒成梦
醉酒成梦 2021-01-17 17:54

Consider the following code:

partial class OurBusinessObject {
    partial void OnOurPropertyChanged() {
        if(ValidateOurProperty(this.OurProperty) ==          


        
14条回答
  •  臣服心动
    2021-01-17 18:21

    I would highly recommend refactoring it to validate before setting the property.

    You could always have a method that was more like:

    T GetValidValueForProperty(T suggestedValue, T currentValue);
    

    or even:

    T GetValidValueForProperty(string propertyName, T suggestedValue, T currentValue);
    

    If you do that, before you set the property, you could pass it to the business logic to validate, and the business logic could return the default property value (your current behavior) OR (more reasonable in most cases), return the currentValue, so setting had no effect.

    This would be used more like:

    T OurProperty
    {
        get
        {
            return this.propertyBackingField;
        }
        set
        {
            this.propertyBackingField = this.GetValidValueForProperty(value, this.propertyBackingField);
        }
    }
    

    It doesn't really matter what you do, but it is important to validate before you change your current value. If you change your value before you determine whether the new value is good, you're asking for trouble in the long term.

提交回复
热议问题