Skip to content

Instantly share code, notes, and snippets.

@imack
Last active August 29, 2015 14:16
Show Gist options
  • Save imack/a0cd24e91e19c3750bcc to your computer and use it in GitHub Desktop.
Save imack/a0cd24e91e19c3750bcc to your computer and use it in GitHub Desktop.
ShapeArea
#import <Foundation/Foundation.h>
@interface AreaCalculator : NSObject
+(float) calculateArea:(NSArray*)shapes;
@end
@implementation AreaCalculator
+(float) calculateArea:(NSMutableArray*)shapes{
float totalArea = 0.0;
for (Shape *shape in shapes){
totalArea += [shape getArea];
}
return totalArea;
}
@end
/* This is the way that breaks open/closed
+(float) calculateArea:(NSMutableArray*)shapes{
float totalArea = 0.0;
for (Shape *shape in shapes){
if ([shape isKindOfClass:[Rectangle class]]){
Rectangle *rect = (Rectangle*)shape;
totalArea += rect.width * rect.height;
} else {
Circle *circle = (Circle*)shape;
totalArea += circle.radius * 2 * 3.1415926;
}
}
return totalArea;
}
*/
@interface Circle : Shape
@property(nonatomic, assign) int radius;
@end
@implementation Circle
-(float) getArea{
return self.radius * 2 * 3.1415926;
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
Rectangle *rectangle1 = [[Rectangle alloc] init];
rectangle1.width = 2;
rectangle1.height = 3;
Rectangle *rectangle2 = [[Rectangle alloc] init];
rectangle2.width = 4;
rectangle2.height = 6;
Circle *circle = [[Circle alloc] init];
circle.radius = 7;
Square *square = [[Square alloc] init];
square.width = 4;
square.height = 3; //This is what breaks Liskov's
NSArray *rectArray = @[rectangle1, rectangle2, circle, square];
NSLog(@"total area: %.2f", [AreaCalculator calculateArea:rectArray] );
}
return 0;
}
@interface Rectangle : Shape
@property(nonatomic,assign) int width;
@property(nonatomic,assign) int height;
@end
@interface Shape : NSObject
-(float) getArea;
@end
@implementation Shape
-(float) getArea{
[NSException raise:@"getArea called on Shape, asshole" format:@"invliad", nil];
return 0.0;
}
@end
@interface Square : Rectangle
@end
@implementation Square
-(float)getArea{
return pow(self.width, 2);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment