MATLAB: How to hide away properties of an object

classobjectsooppcode

I have a class in Matlab, which has a number of properties. I want to make a pcode to obfuscate content of the class. But I couldn't find any way to hide properties of the class: using struct(obj) all the properties become available. Is there any workaround?

Best Answer

I don't think there's any way to hide private properties from struct.
The only workaround I could think of would be to store the private properties in another class (handle) and use a persistent containers.Map in a function to access that class. Would be a bit of a hassle, so you need to really want to hide these properties:
classdef ClassWithPropertiesToHide
properties (Access = public) %properties that are public, hence don't need hiding
something;
end
properties (Access = private)
objectID; %will be visible through struct, but useless. Used as key in the container.Maps which unfortunately can't use a class as a key
end
methods (Access = public)
function this = ClassWithPropertiesToHide()
persistent idcount; %unique id for each class instance to be used as key in the map
if isempty(idcount)
idcount = 0;
else
idcount = idcount + 1;
end
this.objectID = idcount;
privateprops = GetPrivateProperties(this); %privateprops is a handle class, so can be modified here
privateprops.someprop = somevalue;
privateprops.someotherprop = someothervalue;
end
function someotherfunction(this)
privateprops = GetPrivateProperties(this); %get private properties
%do something
end
end
methods (Access = private)
function privateprops = GetPrivateProperties(this)
persistent propcontainer;
if isempty(propcontainer)
propcontainer = containers.Map;
end
if ~isKey(propcontainer, this.objectID)
propcontainer(this.objectID) = PrivatePropertiesClass %PrivatePropertiesClass is the class to hold the private properties. Its properties have to be public
end
privateprops = propcontainer(this.objectID);
end
end
end
Edit: The main class probably needs a destructor and a slightly more sophisticated implementation of GetPrivateProperties so that when an instance of the main class is destroyed its private properties are also removed from the map. Otherwise, memory usage can only go up. Left as an exercice to the reader...