MATLAB: OOP in Matlab: Why can’t methods access properties directly

by referenceby valueMATLABobject oriented programmingoop

I have a fundamental problem with Matlab. I just want to make sure that I understand the problem correctly.
Fact 1:Matlab sends arguments to functions BY-VALUE by default. Fact 2:Matlab class methods, don't have direct access to the class properties, and the object is sent as the first argument to the method.
Fact 1 + Fact 2: methods can't change the properties! They can return a copy of the object with the property changed. But the original object remains unchanged!!
What I'm trying to accomplished and can't is the following:
I have a class which is a set of points. I want to implement a method called "add" and I want to run it as: SetOfPoints1.add(Point1);
not as SetOfPoints1 = SetOfPoints1.add(point1);
why? because adding a point to the matrix of points demands extending the size of the matrix and getting a copy etc. I don't wanna get a copy twice!! It slows everything down specially when I have too many points in my set.
I know about handle/reference classes. But I'm reluctant to use it since I don't know what happens under the hood. But if it's the only way to go I'm gonna give it a try.
One more thing, in OOP , aren't methods supposed to work on the properties directly? I mean, isn't that a fundamental assumption about OOP? doesn't returning a copy violate encapsulation ? .. I don't want a copy of my object to be returned every time I run a method!!
Thanks, Aidin

Best Answer

If I understand your problem correctly, you could make SetOfPoints into an object array, where each element ( e.g., SetOfPoints(1)) is a point (see Creating Object Arrays). Then, if you want a method add, you could implement it by using a hidden property that keeps track of the current number of points (there are a lot of other ways to do it).
As for slowing down the program, your problem is really no different than growing any other array. To avoid slowdown, pre-allocate the elements of the array.
EDIT: in your example below, MATLAB is not necessarily copying all those matrices because it has a lot of internal optimization (see Can MATLAB pass by reference?) However, if you want to be sure this is not happening, you will need to use handle classes.
As for why any particular feature is designed that way, the people on MATLAB Answers are just users - we didn't write the software.