Skip to content

Instantly share code, notes, and snippets.

@darekmydlarz
Created January 3, 2018 14:33
Show Gist options
  • Save darekmydlarz/7e040d2a3dc68f16d814aa1213b9374a to your computer and use it in GitHub Desktop.
Save darekmydlarz/7e040d2a3dc68f16d814aa1213b9374a to your computer and use it in GitHub Desktop.
Decorator vs Imperative
Image image = new RotatedImage( // just a regular declaration
CLOCKWISE,
90,
new GrayScaledImage(
new CachedImage(
"//cdn.google.com/logos/apple.png",
new RemoteImage("//cdn.google.com/logos/apple.png")
)
)
);
return image.bytes(); // all magic happens heere
// vs imperative approach
ImageService {
RemoteImageService remoteImages;
ImageCache cache;
byte[] getImage(String uri) {
Image image = cache.get(uri)
if(image != null) {
return image;
}
image = remoteImages.getImage(uri);
if(image != null) {
return image;
}
ImageUtils.grayscale(image);
ImageUtils.rotate(image, CLOCKWISE, 90);
return image;
}
}
@darekmydlarz
Copy link
Author

darekmydlarz commented Jan 3, 2018

  1. Image is an interface
  2. We DECLARE what image is, instead of MANIPULATING it
  3. Imagine how do you order stuff in a store? Do you say "whole grain sandwich with hummus & long-ripening cheese, please" or rather: "take a sandwich, put butter on bottom, put long-ripening cheese, put hummus, close sandwich, wrap with napkin and give it to me"?
  4. each different Image implementation is easy to reuse, easy to test, easy to modify (cause is small & cohesive)
  5. each Image impl is lazy
  6. Image is closed for modifications & open for extensions easily in contrary to ImageService approach
  • it is very easy for everyone to add more modificators to image (e.g. SaturatedImage, etc.), in imperative approach it would result in ImageService becoming a god class (or ImageUtils)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment