2

I have a mutable array which I have exposed in interface. I have also exposed the array accessors to modify the array. If any modification happens within the array, I would have to reset and re-calculate some data using KVO. To support KVO, I am using array accessors as shown below:

Array property + Array accessors + Wrapper for array accessors:

Mutable Array:
@property (nonatomic, strong) NSMutableArray *portfolioItemArray;

Array Accessors:
-(void)insertObject:(Service*)object inPortfolioItemArrayAtIndex:(NSUInteger)index;
-(void)removeObjectFromPortfolioItemArrayAtIndex:(NSUInteger)index;
-(void)insertPortfolioItemArray:(NSArray *)array atIndexes:(NSIndexSet *)indexes;
-(void)removePortfolioItemArrayAtIndexes:(NSIndexSet *)indexes;

Wrappers for Array Accessors:
-(void)addObjectToPortfolioItemArray:(Service*)inObject;
-(void)removeObjectFromPortfolioItemArray:(Service*)inObject;
-(void)addObjectsToPortfolioItemArray:(NSArray*)inPortfolioItemsArray;
-(void)removeObjectsFromPortfolioItemArray:(NSArray*)inPortfolioItemsArray;

All fine, the KVOs are triggered provided only array accessors or its wrappers are called by other programmers too.

Problem: Some other developers may choose to perform:

[portfolioObject.portfolioItemArray addObject:xxxxx];

Instead of:

[portofolioObject addObjectToPortfolioItemArray:xxxxx];

This would screw the whole setup and it does not trigger the KVO. Is there a better mechanism of handling this? How to avoid programmers from opting direct insertion into the mutable array without using the array accessors?

Edit: Forgot to mention, I would have to expose the array because it can be set from outside (part of requirement). I am updating my KVO observation by overriding the setter for -portfolioItemArray.

Raj Pawan Gumdal
  • 7,390
  • 10
  • 60
  • 92

1 Answers1

2

Don’t expose the mutable array. Expose an immutable array and a few methods to mutate the portfolio.

zoul
  • 102,279
  • 44
  • 260
  • 354
  • Forgot to mention, I would have to expose the array because it can be set from outside (part of requirement). I am updating my KVO observation by overriding the setter for -portfolioItemArray. – Raj Pawan Gumdal Sep 12 '14 at 07:32
  • What exactly does it mean for the array “to be set from outside”? You already expose mutating methods to change the array from the outside. This would work even if the array was immutable. Exposing a mutable array is simply bad encapsulation, bad design. Working around it is guaranteed to be painful. – zoul Sep 13 '14 at 06:36
  • By setting the array from outside, I mean, usage of the API in the following fashion: [aPortfolio setPortfolioItemArray:newPortfolioArray] – Raj Pawan Gumdal Sep 14 '14 at 04:24
  • You can do that with an immutable array (`NSArray`) just fine. – zoul Sep 14 '14 at 06:17