Clean way of writing a setter that can set nested private properties
Afficher commentaires plus anciens
Is there a clean way to write a setter for private properties/members that can accept nested properties?
Something with an API like:
function set(obj, property, value)
that can be called like:
obj.set('property_name.subproperty_name', value)
I can think of an easy but verbose way:
props = split(char(property), '.')
if numel(props) == 1
if obj.(props{1}) == value, return; end
obj.(props{1}) = value;
...
else if numel(props) == 2
...
end
or a way using setfield (but then all properties need to be public):
props = split(char(property), '.')
if getfield(obj, props{:}) == value, return; end
obj = setfield(obj, props{:}, value);
...
I am asking in case anyone knows a solution to this.
I want to have this in a custom setter because it checks if the variable has changed and it updates stuff if it has.
Thanks!
2 commentaires
obj.set('property_name.subproperty_name', value)
Which property in the chain is supposed to be private, here? Do we assume subproperty_name is private to property_name? It shouldn't matter if property_name is private to class(obj). The set() method of class(obj) can access its private properties.
ErikJ GiesenLoo
le 15 Fév 2023
Modifié(e) : ErikJ GiesenLoo
le 15 Fév 2023
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!