This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

Validate Property Values

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.

Validation Syntax

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

Property validations any of the of the following:

  • Size — The length of each dimension, specified as a positive integer or a colon. A colon indicates that any length is allowed in that dimension. The value assigned to the property must conform to the specified size or be compatible with the specified size. For more information, see Property Size Validation.

  • Class — The name of a single MATLAB class. The value assigned to the property must be of the specified class or convertible to the specified class. Use any MATLAB class or externally defined class that is supported by MATLAB, except for Java® and COM classes. For more information, see Property Class Validation.

  • Functions — A comma-separated list of validation function names. MATLAB passes the value assigned to the property to each the validation functions after applying any possible class and size conversions. Validator functions throw errors if the validation fails, but do not return values. For more information, see Property Validation Functions.

    For a list of MATLAB validation functions, see MATLAB Validation Functions.

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 among numeric types in most cases. 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, define a class that supports only the desired type conversions or use a validation function to specify the exact type allowed for the property.

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
      Location(1,3) double {mustBeReal, mustBeFinite}
      Label(1,:) char {mustBeMember(Label,{'High','Medium','Low'})} = 'Low'
      State(1,1) matlab.lang.OnOffSwitchState
  • Location must be a 1-by-3 array of class double whose values are real, finite numbers.

  • Label must be a char vector that is either 'High', 'Medium', or 'Low'.

  • State must be an enumeration member of the matlab.lang.OnOffSwitchState class (off or on).

Validation at Instantiation

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

a = ValidateProps
a = 

  ValidateProps with properties:

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

When creating the object, MATLAB:

  • Initializes the Location property value to [0 0 0] to satisfy the size and class requirements.

  • Sets the Label property to its default value, 'Low'. The default value must be a member of the allowed set of values. The empty char implicit default value would cause an error.

  • Sets the State property to the off enumeration member defined by the matlab.lang.OnOffSwitchState class.

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:

  • Class validation — This validation can cause conversion to a different class, such as conversion of a char to string. Assignment to properties follows MATLAB coercion rules for arrays.

  • Size validation — This validation can cause size conversion, such as scalar expansion or conversion of a column vector to a row vector. Assignment to a property that specifies a size validation behaves the same as assignment to any MATLAB array. For information on indexed assignment, see Array Indexing.

  • Validator functions — MATLAB passes the result of the class and size validation to each validation function, in left to right order. An error can occur before all validation functions have been called, which ends the validation process.

  • Set method — MATLAB performs property validation before calling a property set method, if one is defined for that property. Assignment to the property within a property set or get method does not apply the validation again. Often, you can replace property set methods using property validation.

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
      Value(1,1) double {mustBeNonnegative} = 0

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

a.Value = {10,20};
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.

a.Value = [10 20];
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.

a.Value = -10;
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 nonAbstract.

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
      AveTemp cell 

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

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

Save the object using save.

save TemperatureFile a

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

classdef MonthTemp
      AveTemp containers.Map

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

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 Save and Load Process for Objects.

Related Topics