HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

Create a stack implementation that handles the multi thread scenario

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thehandlesstackcreatemultithatthreadscenarioimplementation

Problem

MyStack.h

@interface MyStack : NSObject

- (id)pop;
- (void)pushObject:(id)object;

@end


MyStack.m

@interface MyStack ()

@property (atomic) NSMutableArray *stackArray;

@end

@implementation MyStack

- (instancetype)init {
    self = [super init];
    if (self != nil)
    {
        _stackArray = [NSMutableArray new];
    }
    return self;
}

- (id)pop {
    id obj = nil; // can return statements be part of critical sections themselves?
    @synchronized(self) {
        if ([self.stackArray count] != 0) {
            obj = [self.stackArray lastObject];
            self.stackArray = [[self.stackArray mutableCopy] removeLastObject];
        }
    }
    return obj;
}

- (void)pushObject:(id)object {
    @synchronized(self) {
        [self.stackArray addObject:object];
    }
}

@end

Solution

This is very easy to read and well written. As far as I can tell, it accomplishes your goal in a very straightforward way, and should be very easy to maintain going forward.
Does It Do Enough?

Overall, it's a very simple class. Are you sure there aren't any additional things it should do? I know in the past, I've needed to check the size of a stack (see how many items are on it). So a -count method might be in order. And maybe an -isEmpty method (though a caller could just check if count is 0.) Also, sometimes it is desirable to get the top object without popping it off. Many stack implementations have a -top method to do that.

You might also want to offer some additional initializers similar to the other Cocoa containers. Maybe things like -initWithCapacity:, -initWithStack:, and if you're feeling ambitious, -initWithObjects:.
Error Handling

In the -pop method you check to see if there are any items on the stack, and if so, return the top item after removing it from the stack. In general a caller should be informed if they are trying to pop a stack with no items on it. While you do return nil it might be better to raise an exception in that case, similar to how an NSArray will raise an exception if you try to get an object at an index that does not exist.

Context

StackExchange Code Review Q#152066, answer score: 2

Revisions (0)

No revisions yet.