Looping object arrays that are properties of other objects - what level to implement them?

3 views (last 30 days)
I'm a bit new to OOP. I'm having trouble deciding the best way to implement methods for object arrays.
Consider an object that is an array. I want to perform a method on each element of the array. Should I put my method call in a loop, or call the method once and put the loop inside the method of the object?
% Option A - loop outside of class (loop around method call)
for i=1:length(ObjectInst)
ObjectInst(i).Update();
end
%
% The Update method in the object does not have a loop. For example,
% consider a method that modifies a property. For option A, no
% loop is used:
%
obj.property = 1;
%
% Option B - loop inside of class
ObjectInst.Update();
%
% The Update method in this examples DOES have a loop
for iobj=1:length(obj)
obj(iobj).property = 1;
end
Is one of these preferred over the other? What are the advantages/disadvantages of putting loops around the calling of methods (option A), vs. putting loops inside every method (option B)?
So far I'm finding that option A is cleaner. Forcing every object method to work directly on arrays seems to be cumbersome.

Answers (1)

Soumya Saxena
Soumya Saxena on 22 Dec 2016
I understand that you would like to know the difference between the 2 methods of updating instances of a a class. Both methodologies are correct and can be used, depending on your use case and implementation.
In the first case, we put the for loop outside of the class and update each object instance inside the for loop.
In the second case, we update once and inside the update function, we put a for loop.
For example, if we have 3 objects, a1, a2 and a3, we can create an object array as follows:
ObjectInst=[a1 a2 a3]
Case 1: We put the "for" loop outside the class. Here"setVal" is the setter function in the class, to update the property of the object.In this case, we have the flexibility to skip objects that we do not want to update or want them to remain unchanged. For example, in the following code, we can skip, the second object a2:
for i=1:2:3
ObjectInst(i).setVal(i);
end
Case2: We update once and inside the update function, we put a for loop.In this case, we will have to define a separate "update" function in the class, which has the for loop. In this case, we will have to specify the updated values that we want to set. We will call this update function on the object array as follows:
newObj = ObjectInst.update([1 a2.getVal 6])
In this case, if we want the second object a2, to remain unchanged but a1 and a3 to change to 1 and 5 respectively, we will have to provide "a2.getVal" to make sure it remains the same.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!