Successfully reported this slideshow.
Upcoming SlideShare
×

# Conditionals and Polymorphism

587 views

Published on

Replacing Conditionals with Polymorphism

Published in: Technology
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

• Be the first to like this

### Conditionals and Polymorphism

1. 1. Tell me and I'll forget. Show me and I might remember. But involve me and I will understand. 1
2. 2. A misconception 2
3. 3. A misconception 3
4. 4. Puzzle Imagine arranging 6 glasses in a row and filling three of them with water like this…. Every time you pick up a glass it counts as a move. What is the smallest number of moves that needs to be made in order to leave the glasses alternating full and empty? -– Explain your answer. 4
5. 5. Conditionals and Polymorphism Presented by Ashok Guduru Technical Architect Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 5
6. 6. Inheritance & Polymorphism Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 6
7. 7. Premise Most ifs can be replaced with polymorphism Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 7
8. 8. Introduction - Not all ifs but most of them cab be replaced by polymorphism - It is kind of fun to write code without ifs (e.g. Smalltalk ) Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 8
9. 9. Conditionals and Polymorphism • Why?: Why we need to avoid ifs - Functions without ifs are easier to read - Functions without ifs are easier to test - Functions without ifs are easier to maintain and extend Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 9
10. 10. Conditionals and Polymorphism NOTE: One of the grandest sounding words in object jargon is polymorphism. • Polymorphism: What it is?: - - You dispatch into a method who’s binding not known at compile time (a good old polymorphism) E.g. a Class and a bunch of sub-classes inheriting from for printing You say print and its not known it is printing to printer, screen or to a PDF Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 10
11. 11. Conditionals and Polymorphism • How do we get rid of ifs? • Use Polymorphism - If an object should behave differently based on its state If you have to check the same condition in multiple places Usually happens using flags and your code is sprinkled with a bunch of ifs all over the codebase - Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 11
12. 12. Conditionals and Polymorphism • But… Use Conditionals - - Mainly to do comparisons of primitive objects: >, <, >=, <=, ==, != etc. There are other uses but today we focus only on avoiding ifs Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 12
13. 13. Conditionals and Polymorphism We’re going to focus on business logic that should behave differently based on conditionals Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 13
14. 14. Conditionals and Polymorphism • To be if free… - Never return a null, instead return NullObject (Typically an object that doesn’t do anything) - e.g. An empty list, A null logger - Nulls are your friends inside of a development test but enemies in production code - When you return a null from a method you can’t dispatch on null. You get a null pointer exception - Don’t return error codes, instead throw an exception (Java RunTime Exception only.) Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 14
15. 15. Conditionals and Polymorphism • What is a subclass? - aka Base Class, Super Class, Parent Class etc. Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 15
16. 16. Conditionals and Polymorphism • Polymorphism uses subclassing WARNING: - Be careful about runaway subclassing - Not to go and crazy on using more subclassing - Deep inheritance hierarchies creates problems on testability, understandability and couple of other abilities as well. Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 16
17. 17. Conditionals and Polymorphism State Based Behavior Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 17
18. 18. Replace Conditionals with Polymorphism Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 18
19. 19. Replace Conditionals with Polymorphism • You have a conditional that chooses different behavior depending on the type of an object - Move each leg of the conditional to an overriding method in a subclass. Make the original method abstract. - The common logic stays in base class (super class) Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 19
20. 20. Replace Conditionals with Polymorphism public double GetSpeed() { switch(_type) { case EUROPEAN: return getBaseSpeed(); case AFRICAN: return getBaseSpeed() – getLoadFactor() * _numberOfCoconuts; case NORWEGIAN_BLUE: return isNailed ? 0 : getBaseSpeed(_voltage) default: throw new ArgumentException(“Should be unreachable”); // Java RuntimeException(“Should be unreachable”); } } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 20
21. 21. Replace Conditionals with Polymorphism Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 21
22. 22. Replace Conditionals with Polymorphism public abstract class Bird { public abstract double GetSpeed(); protected double getBaseSpeed(); } public class EuropeanBird : Bird { public double GetSpeed() { return getBaseSpeed() } } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 22
23. 23. Replace Conditionals with Polymorphism public class AfricanBird : Bird { public double GetSpeed() { return getBaseSpeed() – getLoadFactor() * _numberOfCoconuts; } } public class NorwegianBlueBird : Bird { public double GetSpeed() { return isNailed ? 0 : getBaseSpeed(_voltage) } } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 23
24. 24. Replace Conditionals with Polymorphism public class BirdFactory { public double createInstance(_type) { switch (_type) case EUROPEAN return new EuropeanBird(); case AFRICAN: return new AfricanBird() case NORWEGIAN_BLUE: return new NorwegianBlueBird(); default: throw new ArgumentException(“Should be unreachable”); //Java RuntimeException(“Should be unreachable”); } } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 24
25. 25. Replace Conditionals with Polymorphism public static main() { Bird bird = BirdFactory.createInstance(BirdType.EUROPEAN); SpeedCalculator sc = new SpeedCalculator(bird); sc.Calculate(); } public class SpeedCalculator { private Bird _bird; void SpeedCalculator(Bird bird) { _bird = bird; } public void Calculate() { return _bird.GetSpeed(); } } Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 25
26. 26. Summary • A Polymorphic solution is often better because - New behavior can be added without having the original source code, and - Each operation/concern is separated in a separate file which makes it easy to test/understand and maintain Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 26
27. 27. Summary • Prefer polymorphic over conditionals: - Switch almost always means you should use polymorphism - Sometimes if…elseif… means same as switch - In both of above cases the code is begging for polymorphism. It is almost a rule… I can say! - if is more subtle… sometimes an if is just and if Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 27
28. 28. Simple things should be simple and complex things should be possible. - Alan Kay 28
29. 29. Puzzle Imagine arranging 6 glasses in a row and filling three of them with water like this…. Every time you pick up a glass it counts as a move. What is the smallest number of moves that needs to be made in order to leave the glasses alternating full and empty? -– Explain your answer. 29
30. 30. Puzzle Imagine arranging 6 glasses in a row and filling three of them with water like this…. Every time you pick up a glass it counts as a move. What is the smallest number of moves that needs to be made in order to leave the glasses alternating full and empty? -– Explain your answer. 30
31. 31. Puzzle … and the answer is ONE 31
32. 32. Books: 1. Agile Software Development Principles, Patterns, and Practices by Robert C. Martin (aka Bob Martin or Uncle Bob) 2. Effective Java by Joshua Bloch 3. Code Complete (2nd Edition) by Steve McConnell Code Complete: A Practical Handbook of Software Construction Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 32
33. 33. 33
34. 34. The amateur software engineer is always in search of magic. -- Grady Booch Thank you! Ashok Guduru Blog: http://www.ashokg.com Twitter: @AshokGudur Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 34