conditionals and polymorphism
TRANSCRIPT
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.
Conditionals and Polymorphism
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 5
Presented by
Ashok GuduruTechnical Architect
Premise
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 7
Most ifs can be replaced with polymorphism
Introduction
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 8
- 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 )
Conditionals and Polymorphism
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 9
• 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
Conditionals and Polymorphism
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 10
• 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
NOTE: One of the grandest sounding words in object jargon is polymorphism.
Conditionals and Polymorphism
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 11
• 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
Conditionals and Polymorphism
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 12
• But… Use Conditionals
- Mainly to do comparisons of primitive objects: >, <, >=, <=, ==, != etc.
- There are other uses but today we focus only on avoiding ifs
Conditionals and Polymorphism
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 13
We’re going to focus on business logic that should behave differently based on
conditionals
Conditionals and Polymorphism
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 14
• 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.)
Conditionals and Polymorphism
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 15
• What is a subclass?- aka Base Class, Super Class, Parent Class etc.
Conditionals and Polymorphism
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 16
• Polymorphism uses subclassingWARNING:
- 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.
Conditionals and Polymorphism
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 17
State Based Behavior
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 18
Replace Conditionals with Polymorphism
Replace Conditionals with Polymorphism
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 19
• 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)
Replace Conditionals with Polymorphism
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 20
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”);
}
}
Replace Conditionals with Polymorphism
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 21
Replace Conditionals with Polymorphism
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 22
public abstract class Bird {
public abstract double GetSpeed();
protected double getBaseSpeed();
}
public class EuropeanBird : Bird {
public double GetSpeed() {
return getBaseSpeed()
}
}
Replace Conditionals with Polymorphism
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 23
public class AfricanBird : Bird {
public double GetSpeed() {
return getBaseSpeed() – getLoadFactor() * _numberOfCoconuts;
}
}
public class NorwegianBlueBird : Bird {
public double GetSpeed() {
return isNailed ? 0 : getBaseSpeed(_voltage)
}
}
Replace Conditionals with Polymorphism
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 24
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”);
}
}
Replace Conditionals with Polymorphism
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 25
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();
}
}
Summary
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 26
• 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
Summary
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 27
• 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
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.
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.
Books:
Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 32
1. Agile Software Development Principles, Patterns, and Practicesby Robert C. Martin (aka Bob Martin or Uncle Bob)
2. Effective Java by Joshua Bloch
3. Code Complete (2nd Edition) by Steve McConnellCode Complete: A Practical Handbook of Software Construction