MATLAB: OOP Dynamic Properties ordering is very strange…

addpropdynamic propertiesdynamicpropsMATLABoop

I have a class defintion which makes use of OOP dynamicprops and I've noticed some odd behaivor in accessing the properties.
classdef myClass < dynamicprops
properties
x
end
methods
function this = myClass(x)
this.x = x;
end
end
end
If I add new properties to the class in a script which looks something like this
clear all
clear classes
hObj = myClass(10);
hObj.addprop('a');
hObj.addprop('b');
hObj.addprop('c');
hObj.addprop('d');
hObj.addprop('e');
fn = fieldnames(hObj)'
I was expecting the properties to be added to hObj in the same order that they are scripted in, but I find that the properties added to hObj do not get added in any consistent way. EVERY TIME I run the script, hObj is returned with a different order in the properties ?! Can anyone explain why these dynamic properties behave in such a stranage way? Is there no way to control the order in which these properties appear in the object?
It would be nice if I could control the order so that a function call like fieldnames(hObj) would return values in a predictable way. As a secondary but also irksome issue there appears to be no way to REMOVE a dynamic property once it has been added?!
… here is the output from 5 runs of the script I show above in R2010b:
fn =
'x' 'b' 'a' 'c' 'd' 'e'
fn =
'x' 'd' 'e' 'a' 'c' 'b'
fn =
'x' 'd' 'a' 'b' 'e' 'c'
fn =
'x' 'b' 'd' 'a' 'c' 'e'
fn =
'x' 'b' 'a' 'd' 'c' 'e'

Best Answer

I did come up with a workaround for this which solves the immediate issue. It involves much more sophistication than I was originally hoping for with these classes, but it appears to do the trick. For the application I am working on, it would be counter-intuitive to have the dynamic properties appear to the user in an order that did not match the order they were inserted in. In general the property names are not inserted in alphabetical order. So here is an outline of the solution:
  • add a private, hidden property "dynPropOrder" for the class.
  • restrict access to addprop() by making it private for the class.
  • add a public addDynamicProperty(propertyName) method for the class, which inserts adds the dynamic property using addprop(), but also appends the property name to the hidden dynPropOrder property in a cell string array.
  • overload the display(), properties() and fieldnames() methods to return the properties in the expected order using the hidden dynPropOrder attribute.
  • add a removeDynamicProperty(propertyName) which does reverse operations for the specified property.
Does this seem overly complicated to anyone else? Like I said it works, but I am disappointed there did not appear to be a more straightforward way. I welcome any suggestions...