Module 7. Simplifying Conditional Expressions Course: Refactoring.

Slides:



Advertisements
Similar presentations
Chapter 4 Computation Bjarne Stroustrup
Advertisements

Python Programming Chapter 5: Fruitful Functions Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Selection Control Structures Chapter 5: Selection Asserting Java © Rick Mercer.
Test-Driven Development and Refactoring CPSC 315 – Programming Studio.
You want me to do what??? Refactoring legacy applications aka : fixing someone else’s “bad” code Niel Zeeman Team Foundation Consulting
Software Testing and Maintenance 1 Today’s Agenda  Course Evaluation  HW 4 Return  HW 5 Correction  Quiz 4 Next Class  Software Refactoring.
Understanding the Three Basic Structures
Refactoring and Code Smells
Introduction to Refactoring Excerpted from ‘What is Refactoring?’ by William C. Wake and Refactoring: Improving the Design of Existing Code by Martin Fowler.
George Blank University Lecturer. REFACTORING Improving the Design of Existing Code Supplement to Ian Sommerville, Software Engineering, Chapter 20 Prepared.
REFACTORING Improving the Design of Existing Code Atakan Şimşek e
Objectives You should be able to describe:
Tutorial 4 Decision Making with Control Structures and Statements Section A - Decision Making JavaScript Tutorial 4 -Decision Making with Control.
Maintenance Refactoring and Code Smells. Where are we? Over the semester we have talked about Software Engineering. The overall goal of software engineering.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Programming Logic and Design Fourth Edition, Introductory
Programming Logic and Design Sixth Edition
Refactoring – III Measured Smells. Smells Covered 1. Comments 2. Long method 3. Large Class 462.
Advanced Programing practices
Chapter 3 Making Decisions
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 6: Code Refactoring Omar Meqdadi SE 3860 Lecture 6 Department of Computer Science and Software Engineering University of Wisconsin-Platteville.
Refactoring. Mathematics: Factor ● fac·tor – One of two or more quantities that divides a given quantity without a remainder, e.g., 2 and 3 are factors.
Selection Control Structures Simple Program Design Third Edition A Step-by-Step Approach 4.
Refactoring1 Refactoring DEPARTMENT OF COMPUTER SCIENCE AND SOFTWARE ENGINEERING CONCORDIA UNIVERSITY February 6, 2009.
1 Software Maintenance and Evolution CSSE 575: Session 3, Part 1 Simplifying Conditionals Steve Chenoweth Office Phone: (812) Cell: (937)
CPS120: Introduction to Computer Science Decision Making in Programs.
PROBLEM SOLVING WITH LOOPS Chapter 7. Concept of Repetition Structure Logic It is a computer task, that is used for Repeating a series of instructions.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
Dale Roberts 1 Program Control - Algorithms Department of Computer and Information Science, School of Science, IUPUI CSCI N305.
Refactoring 2. Admin Blackboard Quiz Acknowledgements Material in this presentation was drawn from Martin Fowler, Refactoring: Improving the Design of.
REFACTORINGREFACTORING. Realities Code evolves substantially during development Requirements changes 1%-4% per month on a project Current methodologies.
I Power Higher Computing Software Development High Level Language Constructs.
NJIT 1 Test Driven Development and Refactoring Larman, Chapter 21.
Com S 362: Object-Oriented Analysis and Design Refactoring.
Refactoring Conditionals Lesson Five: Conditionals.
Programming Logic and Design, Introductory, Fourth Edition1 Understanding the Three Basic Structures Structure: a basic unit of programming logic Any program.
Refactoring Advanced Software Engineering Dr Nuha El-Khalili.
Testing CSE 160 University of Washington 1. Testing Programming to analyze data is powerful It’s useless (or worse!) if the results are not correct Correctness.
Refactoring. Mathematics: Factor ● fac·tor – One of two or more quantities that divides a given quantity without a remainder, e.g., 2 and 3 are factors.
Refactoring1 Improving the structure of existing code.
Refactoring. 2 Process of changing a software system in such a way that it does not alter the external behavior of the code, yet improves its internal.
An Object-Oriented Approach to Programming Logic and Design Chapter 5 Making Decisions.
Software Construction and Evolution - CSSE 375 Simplifying Conditionals Shawn & Steve.
Programming Logic and Design Fifth Edition, Comprehensive
CPS120: Introduction to Computer Science Decision Making in Programs.
Module 9. Dealing with Generalization Course: Refactoring.
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
Catalog of Refactoring (5) Simplifying Conditional Expressions.
Code Refactoring Milan Vukoje Soprex SkfOffice2 SkfOffice3 Big5 Quality oriented We are hiring…
Programming Logic and Design Fifth Edition, Comprehensive Chapter 4 Making Decisions.
Control Structures: Conditionals, If/Else and Loops David Millard
Programming Logic and Design Fourth Edition, Introductory Chapter 2 Understanding Structure.
ICONFINDER ICONFINDER Founded Django based web application -PostgreSQL -Elasticsearch -Amazon Elastic Compute.
IST 210: PHP Logic IST 210: Organization of Data IST2101.
Catalog of Refactoring (6) Making Method Calls Simpler.
Refactoring and Code Smells
SWEN-610 Foundations of Software Engineering
Conditions and Ifs BIS1523 – Lecture 8.
//code refactoring Rename Method Introduce Assertion
Understanding the Three Basic Structures
Refactoring and Code Smells
Control Structure Testing
Refactoring Strategies
Refactoring and Code Smells
Advanced Programing practices
Refactoring and Code Smells
Refactoring.
Refactoring and Code Smells
Presentation transcript:

Module 7. Simplifying Conditional Expressions Course: Refactoring

Overview Decompose Conditional Consolidate Conditional Expression Consolidate Duplicate Conditional Fragments Remove Control Flag Replace Nested Conditional with Guard Clauses Replace Conditional with Polymorphism Introduce Null Object Introduce Assertion

Decompose Conditional You have a complicated conditional (if-then-else) statement. Extract methods from the condition, then part, and else parts.

Decompose Conditional if (date.before (SUMMER_START) || date.after(SUMMER_END)) charge = quantity * _winterRate + _winterServiceCharge; else charge = quantity * _summerRate; if (notSummer(date)) charge = winterCharge(quantity); else charge = summerCharge (quantity);

Decompose Conditional Before:  complexity in a program lies in complex conditional logic  a pretty long method After:  make your intention clearer by decomposing  doing this for the conditional part each of the alternatives  highlight the reason for the branching

Decompose Conditional: Mechanism Extract the condition into its own method. Extract the then part and the else part into their own methods.

Consolidate Conditional Expression You have a sequence of conditional tests with the same result. Combine them into a single conditional expression and extract it.

Consolidate Conditional Expression double disabilityAmount() { if (_seniority < 2) return 0; if (_monthsDisabled > 12) return 0; if (_isPartTime) return 0; // compute the disability amount double disabilityAmount() { if ( isNotEligableForDisability()) return 0; // compute the disability amount

Consolidate Conditional Expression Before:  a series of conditional checks with the same result After:  it makes the check clearer  sets you up for Extract Method Hit:  code already communicates your intention

Consolidate Conditional Expression: Mechanism Check side effects. A single conditional statement. Compile and test. Extract Method.

Consolidate Duplicate Conditional Fragments The same fragment of code is in all branches of a conditional expression. Move it outside of the expression.

Consolidate Duplicate Conditional Fragments if (isSpecialDeal()) { total = price * 0.95; send(); } else { total = price * 0.98; send(); } if (isSpecialDeal()) total = price * 0.95; else total = price * 0.98; send();

Consolidate Duplicate Conditional Fragments Identify code. Move it to before the conditional. Move it to after the conditional. Look code in the middle. Extract that code into a method.

Remove Control Flag You have a variable that is acting as a control flag for a series of boolean expressions. Use a break or return instead. done = false while not done if (condition) do something done = true next step of loop

Remove Control Flag Before:  more trouble  rules of structured programming  “one entry and one exit point” After:  more exit point  the conditional becomes so much more clear

Remove Control Flag: Mechanism Find the value of the control flag. A break or continue statement. Compile and test. Extract the logic into a method. Find the value of the control flag. Replace with a return. Compile and test. Return is better than break and continue Control Flag vs Result value

Exercise Remove Control Flag Decompose Conditional  else statements that are a double negative are difficult to understand.

Replace Nested Conditional with Guard Clauses A method has conditional behavior that does not make clear the normal path of execution. Use guard clauses for all the special cases.

Replace Nested Conditional with Guard Clauses double getPayAmount() { double result; if (_isDead) result = deadAmount(); else { if (_isSeparated) result = separatedAmount(); else { if (_isRetired) result = retiredAmount(); else result = normalPayAmount(); }; } return result; }; double getPayAmount() { if (_isDead) return deadAmount(); if (_isSeparated) return separatedAmount(); if (_isRetired) return retiredAmount(); return normalPayAmount(); };

Replace Nested Conditional with Guard Clauses Before:  conditional expressions come in two forms two part of the normal behavior normal behavior unusual condition After:  use guard clause [Beck] and return  the key point about is one of emphasis  if-then-else construct you are giving equal weight Hint:  clarity is the key principle: if the method is clearer with one exit point, use one exit point; otherwise don't.

Replace Nested Conditional with Guard Clauses For each check put in the guard clause. Compile and test. Expressions.

Exercise Replace Nested Conditional with Guard Clauses  Reversing the Conditions

Replace Conditional 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.

double getSpeed() { switch (_type) { case EUROPEAN: return getBaseSpeed(); case AFRICAN: return getBaseSpeed() - getLoadFactor() * _numberOfCoconuts; case NORWEGIAN_BLUE: return (_isNailed) ? 0 : getBaseSpeed(_voltage); } throw new RuntimeException ("Should be unreachable"); } Replace Conditional with Polymorphism

Before:  difficult to add a new type  high coupling After:  use polymorphism  switch or if-then-else are much less common  just create a new subclass for a new condition  reduces the dependencies Replace Conditional with Polymorphism

1. Use Extract Method. 2. Use Move Method. 3. Pick one of the subclasses. 4. Compile and test. 5. Remove the copied leg. 6. Compile and test. 7. Repeat with each leg. 8. Make the superclass method abstract.

Introduce Null Object You have repeated checks for a null value. Replace the null value with a null object.

Introduce Null Object if (customer == null) plan = BillingPlan.basic(); else plan = customer.getPlan();

Introduce Null Object Before:  ask object for what type it is  invoking some behavior based on the answer  got rid of huge amounts of procedural code After:  object does the right thing Use:  the missing Gemstone session  use of null object is the missing bin  things almost never blow up  use Singleton pattern

Introduce Null Object 1. Create a subclass with isNull operation. 2. Compile. 3. Find all places and replace. 4. Change null with isNull. 5. Compile and test. 6. Look for if not null. 7. Override the operation. 8. Remove the condition check 9. Compile, and test.

Introduce Assertion A section of code assumes something about the state of the program. Make the assumption explicit with an assertion.

Introduce Assertion double getExpenseLimit() { // should have either expense limit or a primary project return (_expenseLimit != NULL_EXPENSE) ? _expenseLimit : _primaryProject.getMemberExpenseLimit(); } double getExpenseLimit() { Assert.isTrue (_expenseLimit != NULL_EXPENSE || _primaryProject != null); return (_expenseLimit != NULL_EXPENSE) ? _expenseLimit: _primaryProject.getMemberExpenseLimit(); }

Introduce Assertion Before :  assumptions can only be decoded by looking through an algorithm After:  failure of an assertion indicates error  should never be used by other  usually are removed for production code  important to signal something is an assertion  communication and debugging aids  help the reader understand the assumptions  help catch bugs closer to their origin

Introduce Assertion: Mechanism When you see that a condition is assumed to be true, add an assertion to state it.

Exercise Null Object Real Project

Review Decompose Conditional Consolidate Conditional Expression Consolidate Duplicate Conditional Fragments Remove Control Flag Replace Nested Conditional with Guard Clauses Replace Conditional with Polymorphism Introduce Null Object Introduce Assertion