HGSETGETPLUS – an extension to HGSETGET
One of my favorite features in MATLAB is the object-oriented programming (OOP) system. It’s great for building complex GUIs, creating components to share with other people, and for managing large projects. A particularly useful feature of the OOP system in MATLAB is the ability to create classes that behave like Handle Graphics objects, with a SET/GET interface. To do this, you write a class that inherits from “hgsetget”, a built-in MATLAB class.
This week’s pick is a very useful extension to the hgsetget class that started out as a MATLAB Answers post by Andrew. Using inheritance, Andrew wanted to extend the hgsetget class to add an easy validation and enumeration interface for property values. Jiro shared some more of the background story:
After some dialog and feedback from Jiro, the end result was a new MATLAB class called “hgsetgetplus”. It allows you to easily constrain the set of values that properties in your class can assume, and to notify the user what those values are. To see how this can be useful, consider the behavior of built-in Handle Graphics objects in MATLAB:
You can certainly implement behavior like this in your own classes. However, you must write a “set” method for each property, and include tedious validation code to produce the error. Andrew’s “hgsetgetplus” class makes this easy. When you write your own classes, you simply inherit from the “hgsetgetplus” class, and define the attributes of your class’s properties with this simple clean interface:
This is what happens when we manipulate an object from the above class:
Andrew’s submission includes an example object and script that you can run to see behavior similar to the example above.
I like this submission for several reasons:
- It increases your productivity as a MATLAB programmer.
- It makes your code more reliable by reducing a common, and difficult to find, source of bugs.
- In addition to displaying a helpful error message, it also allows users to view the universe of valid property values, thus avoiding the error message in the first place, and improving their self esteem.
- Back when I helped staff our technical support line, somebody called and requested that we add this exact feature!
- It’s a great example of how to arrange and package a MATLAB utility. It includes clear documentation in HTML format, example code, and even unit tests that can be run with Steve Eddins’s xUnit framework. The content is grouped into separate folders, keeping things organized. If you find yourself developing tools in MATLAB for others to use, this is a good illustration of how you can bundle everything up cleanly.
Let us know what you think here or leave a comment for Andrew.
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.