Matlab OOP, dependent class properties, correct coding techiques
Show older comments
Hi,
I have a conceptual problem I'm struggling with and was wondering if anyone could give some insight into this.
Essentially, I have a class with three (or more) properties. Watered down Pseudo code below:
classdef obj
Properties
A
B
C
end
Methods
constructor etc
function set.A
C = f(obj.A,obj.B) % C is dependent on A and B (MLINT warns on this line)
A = inputValue % Set A's value
end
end
end
Now herein lies the problem as I'm sure you have already noticed. I'm setting one properties value while changing another property's value. MLINT warns immediately that this is bad and correctly states that one should make C a dependent property.
This is fine unless speed is an issue. C is going to be called "lots of times". And having Matlab calculate it every time
*get.C*
is called is expensive. A and B will be updated through out the life of the object and hence I want C recalc'ed on the fly when they do.
Should I disregard MLINT (and probably good coding practice)?
Is there a better but still fast way to achieve what I want?
Regards, Phil
Accepted Answer
More Answers (1)
The usual solution to that is to make A dependent, not C. It is a less common usage of dependent properties to make use of the set function as well as the get function, but in this case that is one of the simplest solutions.
The set function for a dependent property is allowed to set other class properties (without giving any warning - i.e. in a robust way).
e.g. (code isn't perfect, but I left in some pseudo-code of yours rather than compilable Matlab code)
classdef obj
Properties
A
B
C
end
Properties( Access = private )
A_
end
Methods
function set.A
C = f(obj.A,obj.B)
A_ = inputValue;
end
function A = get.A( obj )
A = obj.A_;
end
end
end
C remains exactly as it is, though I would assume from this that you want C to have private set access.
3 Comments
Adam Wyatt
on 31 Mar 2015
You can also set A_ to be Hidden so that it is not displayed when debugging.
Adam
on 31 Mar 2015
In response to the Phillip's comment about further dependencies...
If I have two properties that want to be validated against each other or for some other reason basically need to be assigned both at the same time I just make their set property private and create my own function which takes both of them as arguments so you can only set them together.
Such a function also has no limitations on what other properties it is allowed to set or access.
Phillip
on 1 Apr 2015
Categories
Find more on Function Creation in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!