Validate Property Values - MATLAB & Simulink (original) (raw)

Property Validation in Class Definitions

MATLAB® property validation enables you to place specific restrictions on property values. You can use validation to constrain the class and size of property values. Also, you can use functions to establish criteria that the property value must conform to. MATLAB defines a set of validation functions and you can write your own validation functions.

The use of property validation is optional in class definitions.

Additional Information on Property Validation

For more information on property validation, see Property Class and Size Validation, Property Validation Functions, and Metadata Interface to Property Validation.

Validation Syntax

The highlighted area in the following code shows the syntax for property validation.

Properties block with validation syntax

Property validation includes any of the following:

Using Property Validation

Use property validation for public properties to control the values user code assigns to the properties.

If you want to restrict property values to a fixed set of identifiers, create an enumeration class for these identifiers and constrain the property to this class. For information on enumeration classes, see Define Enumeration Classes.

MATLAB type conversion rules apply to property validation. For example, MATLAB can coerce from one to another numeric type. Therefore, restricting a property value to a specific numeric type, such as double does not prevent the assignment of other numeric types to the property.

To ensure that a property can be assigned only a specific type of value, restrict the property to a type that supports only the desired type conversions or use a validation function to specify the exact class allowed for the property instead of specifying the property type. MATLAB evaluates the type specification before executing any validation functions. For more information, see Order of Validation.

Specify Valid Default

Ensure that any default value assigned to the property meets the restrictions imposed by the specified validation. If you do not specify a default value, MATLAB creates a default value by assigning an empty object of the specified class or by calling the default constructor if size restriction does not allow the use of an empty default value. The default constructor must return an object of the correct size.

Sample Class Using Property Validation

The ValidateProps class defines three properties with validation.

classdef ValidateProps properties Location(1,3) double {mustBeReal, mustBeFinite} Label(1,1) string {mustBeMember(Label,["High","Medium","Low"])} = "Low" State(1,1) matlab.lang.OnOffSwitchState end end

Validation at Instantiation

Creating an object of the ValidateProps class performs the validation on implicit and explicit default values:

a =

ValidateProps with properties:

Location: [0 0 0]
   Label: "Low"
   State: off

When creating the object, MATLAB:

For information on how MATLAB selects default values, see Default Values Per Size and Class.

Order of Validation

When a value is assigned to the property, including default values that are specified in the class definition, MATLAB performs validation in this order:

Property Validation Errors

The ValueProp class uses size, class, and function validation to ensure that an assignment to the Value property is a double scalar that is not negative.

classdef ValueProp properties Value(1,1) double {mustBeNonnegative} = 0 end end

This statement attempts to assign a cell array to the property. This assignment violates the class validation.

Error setting property 'Value' of class 'ValueProp': Invalid data type. Value must be double or be convertible to double.

This statement attempts to assign a 1-by-2 double array to the property. This assignment violates the size validation.

Error setting property 'Value' of class 'ValueProp': Size of value must be scalar.

This statement attempts to assign a scalar double to the property. This assignment fails the function validation, which requires a nonnegative number.

Error setting property 'Value' of class 'ValueProp': Value must be nonnegative.

The validation process ends with the first error encountered.

Abstract Property Validation

You can define property validation for abstract properties. The validation applies to all subclasses that implement the property. However, subclasses cannot use any validation on their implementation of the property. When inheriting validation for a property from multiple classes, only a single abstract property in one superclass can define the validation. None of the superclasses can define the property as concrete.

Objects Not Updated When Changing Validation

If you change the property validation while objects of the class exist, MATLAB does not attempt to apply the new validation to existing property values. However, MATLAB does apply the new validation when you make assignments to the properties of existing objects.

Validation During Load Operation

When saving an object to a MAT file, MATLAB saves all nondefault property values with the object. When loading the object, MATLAB restores these property values in the newly created object.

If a class definition changes the property validation such that the loaded property value is no longer valid, MATLAB substitutes the currently defined default value for that property. However, the load function suppresses the validation errors that occur before assigning the default value from the current class definition. Therefore, validation errors are silently ignored during load operations.

To illustrate this behavior, this example creates, saves, and loads an object of the MonthTemp class. This class restricts the AveTemp property to a cell array.

classdef MonthTemp properties AveTemp cell end end

Create a MonthTemp object and assign a value to the AveTemp property.

a = MonthTemp; a.AveTemp = {'May',70};

Save the object using save.

Edit the property definition to change the validation class for the AveTemp property from cell array to containers.Map.

classdef MonthTemp properties AveTemp containers.Map end end

Load the saved object with the new class definition on the MATLAB path. MATLAB cannot assign the saved value to the AveTemp property because the cell array, {'May',70}, is not compatible with the current requirement that the property value be a containers.Map object. MATLAB cannot convert a cell array to a containers.Map.

To address the incompatibility, MATLAB sets the AveTemp property of the loaded object to the current default value, which is an empty containers.Map object.

load TemperatureFile a a.AveTemp

ans =

Map with properties:

    Count: 0
  KeyType: char
ValueType: any

The loaded object has a different value assigned to the AveTemp property because the saved value is now invalid. However, the load process suppresses the validation error.

To prevent loss of data when changing class definitions and reloading objects, implement a loadobj method or class converter method that enables the saved values to satisfy the current property validation.

For more information on saving and loading objects, see Default Save and Load Process for Objects.