Conditionals and Polymorphism

50 %
50 %
Information about Conditionals and Polymorphism
Technology

Published on February 20, 2014

Author: ashokguduru

Source: slideshare.net

Description

Replacing Conditionals with Polymorphism

Tell me and I'll forget. Show me and I might remember. But involve me and I will understand. 1

A misconception 2

A misconception 3

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

Conditionals and Polymorphism Presented by Ashok Guduru Technical Architect Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 5

Inheritance & Polymorphism Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 6

Premise Most ifs can be replaced with polymorphism Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 7

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

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

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

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

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

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

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

Conditionals and Polymorphism • What is a subclass? - aka Base Class, Super Class, Parent Class etc. Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 15

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

Conditionals and Polymorphism State Based Behavior Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 17

Replace Conditionals with Polymorphism Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 18

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

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

Replace Conditionals with Polymorphism Copyright © 2013 Coextrix Technologies Pvt. Ltd., Bangalore 21

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

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

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

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

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

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

Simple things should be simple and complex things should be possible. - Alan Kay 28

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

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 … and the answer is ONE 31

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

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

Add a comment

Related presentations

Related pages

Replace Conditional with Polymorphism - refactoring.guru

Problem: You have a conditional that performs various actions depending on object type or properties. Solution: Create subclasses matching the branches of ...
Read more

Replace Conditional with Polymorphism - Refactoring

Replace Conditional with Polymorphism. You have a conditional that chooses different behavior depending on the type of an object. Move each leg of the ...
Read more

Replace Conditional With Polymorphism - c2.com

How Far to Take it? How many of the conditionals (IF/case) should be converted to polymorphism? The opinions seem to vary widely on this. Is an application ...
Read more

c++ - Do polymorphism or conditionals promote better ...

I recently stumbled across this entry in the google testing blog about guidelines for writing more testable code. I was in agreement with the author until ...
Read more

Replace conditional with polymorphism - Stack Overflow

"Replace conditional with polymorphism" is elegant only when type of object you're doing switch/if statement for is already selected for you. As an example ...
Read more

Polymorphism vs Conditionals | Sebas on Software

Polymorphism vs conditionals is a common debate when it comes to object oriented design. Needless to say, it is widely accepted that polymorphism is the ...
Read more

Transform Conditionals to Polymorphism - hillside.net

Transform Conditionals to Polymorphism is a pattern language describing how conditionals —i.e nested tests, switch statements— are transformed into ...
Read more

1: Polymorphism vs. Conditionals | Giant Robots Smashing ...

Ben Orenstein and Joe Ferris (and the surprise special guest Seana Quental) start the series off with a very technical discussion about Polymorphism vs ...
Read more

Replace Conditional With Polymorphism - YouTube

A screencast of one of Martin Fowler's refactoring patterns from the series called Simplifying Conditional Expressions
Read more