Refactoring. Refactoring. Refactoring. Refactoring. Refactoring. Refactoring. Lesson Five: Conditionals

Size: px
Start display at page:

Download "Refactoring. Refactoring. Refactoring. Refactoring. Refactoring. Refactoring. Lesson Five: Conditionals"

Transcription

1 Lesson Five: should not be too complex. If they are complex, refactor them to make simple methods making readability and understandability better. Learning objective have simple conditionals which are self documenting with meaningful names In our program with explaining variable names, there are still some conditionals which are difficult to understand. We find them in mainly in bestmove(). FOR EXAMPLE int bestmove(int computerstatus, int userstatus) { if (((computerstatus & (1 << potentialcomputermove)) == 0) && ((userstatus & (1 << potentialcomputermove)) == 0)) if (((potentialcomputerstatus & (1 << j)) == 0) && ((userstatus & (1 << j)) == 0)) if (((computerstatus & (1 <<firstavailablecomputermove)) == 0) && ((userstatus & (1 <firstavailablecomputermove)) == 0)) { REFACTORINGS Decomposing Conditional Consolidating Conditional Statements Consolidate Duplicate Conditional Fragments Replace Nested Conditional with Guard Clauses Remove Control Flag 1

2 Decompose Conditional You have a complicated conditional (if-then-else) statement. Extract methods from the condition, then part, and else parts. Complexity exist in a heavy if then else structure and you want to make the code more readable and understandable. You extract methods and name them where the code is readable and make small boolean methods to make the logic more understandable. if (date.before (SUMMER_START) date.after(summer_end)) charge qualitity * _winterrate + _winterservicecharge; Consider the following initial if statement. else charge quantity * _summerrate; GOES TO if (notsummer_date)) if (date.before (SUMMER)START) date.after(summer_end)) charge qualitity * _winterrate + _winterservicecharge; else charge quantity * _summerrate; charge = wintercharge(quantity); else charge = summercharge (quantity); Extract the conditional and each leg as follows. If(notSummer(date) charge = wintercharge(quantity); else charge = summercharge (quantity); private boolean notsummer (Date date) { return date.before (SUMMER_START) date.after (SUMMER_END); } // end not summer private double summercharge (int quantity) { Extract the condition into its own method Extract the then part then the else part Compile and test return quantity * _summerrate; } // end summercharge private double wintercharge (int quantity) { return quantity * _winterrate + )winterservicecharge; } 2

3 Consolidate Conditional Expressions You have a sequence of conditional tests with the same result. Sometimes you have a series of conditional checks in which the conditional statements are different but the effects are the same. Combine them into a single conditional expression and extract it. double disabilityamount() { if (_seniority < 2) return 0; if (_monthsdisabled > 12) return 0; if (_isparttime) return 0; // compute the disability amount GOES TO. Double diabilityamount () { if (isnoteligablefordisability ()) return 0; // computer the disability amount Assume the following. double disabilityamount() { if (_seniority < 2) return 0; if (_monthsdisabled > 12) return 0; if (_isparttime) return 0; // compute the disability amount These statements may be equivalent of a complex or statement double diabilityamount () { if (_seniority < 2) (_monthsdisabled > 12) (_isparttime)) return 0; // computer the disability amount Look at the condition and use extract method to communicate what the condition is looking for. double disabilityamount() { if (iseligiblefordiability()) return 0; // computer the disability amount This can be done with ands. if (onvacation()) if (lengthofservice*( > 10 ) return 1; return 0.5; Boolean iseligiblefordisability() { return ((_seniority < 2) (_monthsdisabled > 12) (_isparttime)); } // end is ElibibleFor Disability if (onvacation () && lengthofservice () > 10) return 1; else return 0.5; 3

4 Given the following if (onvacation() && lengthofservice*( > 10 ) return 1; return 0.5; Test only the condition and returns a value turn the routine into a single return statements using the ternary operator. if (onvacation () && lengthofservice () > 10)? 1; 0.5; Check that none of the conditional has side effects. Replace the string of conditionals with a single conditional statement using logical operators. Compile and test. Consider using Extract Method on the condition. Consolidate Duplicate Conditional Fragments The same fragment of code is in all branches of a conditional expression. Consolidate Duplicate Conditional Fragments: Sometime you find the same code executed in all legs of a conditional. This requires you move the code outside the conditional to make it more clear what remains constant. Move it outside of the expression. Consolidate Duplicate Conditional Fragments: You begin with the following if (isspecialdeal() ) { total = price * 0.95; send (); } // end if else { total price * 0.98; send(); Move the send method out since it is used by both if (isspecialdeal() ) total = price * 0.95; else total =price * 0.98; send(); Consolidate Duplicate Conditional Fragments: Identify code that is executed. If common code is at the beginning, do it before conditional. If the code is at the end, move it after the conditional If the common code is in the middle, see if you can move it forward or backward. If there is more than one line of code extract method. 4

5 Remove Control Flag You have a variable that is acting as a control flag for a series of boolean expressions. You have a control flag that allows exit from the conditional statements. These control flags add complexity. Get rid of the control flag. Use a break or return instead. Function checks a people list for suspicious characters void checksecurity (String [ ] people) { boolean found = false; for (int i = 0; i < people.length; i++) { if (!found) { // this is the flag if (people[i].equals ( Don )) { sendalert(); found = true; } if (people[i].equals ( John )) { sendalert(); found = true; } } // end if } // end for } // end checksecurity The control flag is the piece that sets the found variable. Step 1: Set breaks in one at a time. Leave in flag. void checksecurity (String [ ] people) { boolean found = false; for (int i = 0; i < people.length; i++) { if (!found) { if (people[i].equals ( Don )) { sendalert(); found = true; break; } if (people[i].equals ( John )) { sendalert(); found = true; break; } } // end if } // end for } // end checksecurity Step 2: Remove control flag references. You can use the return statement with function returning a String. void checksecurity (String [ ] people) { for (int i = 0; i < people.length; i++) { if (people[i].equals ( Don )) { sendalert(); break; } if (people[i].equals ( John )) { sendalert(); break; } } // end for } // end checksecurity String checksecurity (String [ ] people) { for (int i = 0; i < people.length; i++) { if (people[i].equals ( Don )) { sendalert(); return Don ; } if (people[i].equals ( John )) { sendalert(); return John ; } } // end for return ; // returns null if neither } // end checksecurity 5

6 Find the value of the control flag that gets you out of the logic statement. Replace assignments of the break-out value with a break or continue statement. Compile and test after each replacement. 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: Expressional statement may be of two forms, One form is whether either course is part of the normal behavior And the second form is a situation in which one answer from the conditional indicates normal behavior and the other indicates an unusual condition. Replace Nested Conditional with Guard Clauses: (con t) Each type of conditions have different intensions. If both are part of normal behavior, use a condition with an if and an else leg. If the condition is a unusual condition, check the condition and return if the condition is true. This is called a guard clause. Replace Nested Conditional with Guard Clauses: Given double getpayamount() { double result; if (_isdead) result = deathamount(); // this is NOT a normal course else { if (_isseparated) result = separatedamount(); // this is a normal course else { if (_isretired) result = retiredamount(); // this is a normal course else result = normalpayamount(); // this is the normal course return result } // end getpayamount Replace Nested Conditional with Guard Clauses: GOES TO separating out the behaviors. double getpayamount() { if (_isdead) return deadamount(); if (_isseparated) return separatedamount(); if (_isretired) return retiredamount(); return normalpayamount(); } // end getpayamount 6

7 Replace Nested Conditional with Guard Clauses: Given this initial code as shown before -- this is not unlikely code double getpayamount() { double result; if (_isdead) result = deadamount(); else { if (_isseparated) result = separatedamount(); else { if (_isretired) result = retiredamount(); else result = normalpayamount(); return result } // end getpayamount Replace Nested Conditional with Guard Clauses: Checking masking the normal course of action behind the checking. So we use a guard clause one at a time. double getpayamount() { double result; if (_isdead) return deadamount(); // this is masking of normals else { if (_isseparated) result = separatedamount(); else { if (_isretired) result = retiredamount(); else result = normalpayamount(); return result } // end getpayamount Replace Nested Conditional with Guard Clauses: For each check put in the guard clause. Compile and test after each check is replaced with a guard clause. 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. Avoid writing explicit conditional statements when you have objects whose behavior varies depending on the type of object you are dealing with. Polymorphism gives you the advantage. Given the following speeds for different types of birds double getspeed() { switch ()type) { case EUROPEAN: return getbasespeed(); case AFRICAN: return getbasespeed() getloadfactor() * _numberofcoconuts; case NORWEGIAN_BLUE: return (_isnailed)? 0 ; getbasespeed (_voltage); } // end switch throw new RuntimeException ( Should be unreachable ); } // end getspeed 7

8 GOES TO Bird getspeed Method: 1. Use Extract Method to take apart the conditional. 2. Use either Replace Type Code with SubClasses OR Bird getspeed Bird getspeed Bird getspeed Use Replace Type Code with State/Strategy 3. Use Move Method to place condition in an isa structure. 4. Create sub-classes with overriding methods. Suppose you have the following inheritance structure Employee Employee Type ENGINEER SALESMAN MANAGER With the following code class Employee.. int payamount() { switch (gettype)() { case EmployeeType.ENGINEER: return _monthlysalary; case EmployeeType.SALESMAN: return _monthlysalary + commission; case EmployeeType.MANAGER: return _monthlysalary + bonus; default; throw new RuntimeException ( Incorrect Employee ); } // end switch } // end Employee With the following code int gettype () { return _type.gettypecode(); } // returns type of object private EmployeeType _type; // an instance of employee type in the program abstract class EmployeeType. // is the abstract class of employee type abstract int gettypecode(); class Engineer extends EmployeeType // defines the subclass int gettypecode() { return Employee.ENGINEER; } // this returns the type The case statement is extracted so I move it into employee type. class EmployeeType // this code used to be in Employee int payamount (Employee emp) { switch (gettypecode ()) { case ENGINEER: return emp.getmonthlysalary (); case SALESMAN: return emp.getmonthlysalary () + emp.getcommission(); case MANAGER: return emp.getmonthlysalary() + emp.getbonus(); default: throw new RuntimeException ( Incorrect Employee ); 8

9 Change the payamount method to delegate to the new class. class Employee int payamount () { return _type.payamount (this)) Work on Case statement copy engineer leg to engineer class class Engineer int payamount (Employee emp) { return emp.getmonthlysalary(); } The new method overrides the case statement for engineers I can place a trap here to make sure I made no mistakes class EmployeeType int payamount (Employee emp) { switch (gettypecode ()) { case ENGINEER: throw new RuntimeException ( Should be being overridden ); case SALESMAN: return emp.getmonthlysalary () + emp.getcommission(); case MANAGER: return emp.getmonthlysalary() + emp.getbonus(); default: throw new RuntimeException ( Incorrect Employee ); I can then replace this switch statement entirely With a polymorphic call. class Employee int payamount () { return _type.payamount (this)) class Engineer int payamount (Employee emp) { return emp.getmonthlysalary(); } If the conditional statement is one part of a larger method, take apart the conditional statement and use Extract Method. If necessary use Move method to place the conditional at the top of the inheritance structure. Pick one of the subclasses. Remove the copied leg of the conditional statement. Compile and test. if (((computerstatus & (1 << firstavailablecomputermove)) == 0) && ((userstatus & (1 << firstavailablecomputermove)) == 0)) BECOMES public boolean cellempty (int computerstatus,int potentialcomputermove,int userstatus) { return ((computerstatus & (1 << potentialcomputermove)) == 0) && ((userstatus & (1 << potentialcomputermove)) == 0); } // end cellempty if ((getcomputerstatus() & (1 << i))!= 0) BECOMES public boolean squareoccupied (int i, int playerstatus) { return ((playerstatus & (1 << i))!= 0); } // end squareoccupied REUSED WITH 3 times if (squareoccupied (i, getcomputerstatus())) 9

Chapter 7: Simplifying Conditional Expressions

Chapter 7: Simplifying Conditional Expressions Chapter 7: Simplifying Conditional Expressions Conditional logic has a way of getting tricky, so here are a number of refactorings you can use to simplify it. The core refactoring here is Decompose Conditional

More information

Refactoring. Thierry Sans. with slides from Anya Tafliovich

Refactoring. Thierry Sans. with slides from Anya Tafliovich Refactoring Thierry Sans with slides from Anya Tafliovich Composing Methods Extract Method void printowing() { printbanner(); //print details System.out.println("name: " + name); System.out.println("amount:

More information

void printowing(double amount) { printbanner(); printdetails(); void printdetails(double amount) {

void printowing(double amount) { printbanner(); printdetails(); void printdetails(double amount) { Refactoring References: Martin Fowler, Refactoring: Improving the Design of Existing Code; ; Bruce Wampler, The Essence of Object-Oriented Oriented Programming with Java and UML A recent OO technique that

More information

Badge#8: Geek Refactoring

Badge#8: Geek Refactoring Badge#8: Geek Refactoring Nuno Pombo, Qualidade de Software, 2018/19 1 When To Refactor? Rule of Three When adding a feature When fixing a bug During a code review 2 How To Refactor? The code should become

More information

Composing Methods. Extract Method - Code that can be grouped - Meaningful name for method

Composing Methods. Extract Method - Code that can be grouped - Meaningful name for method Composing Methods Extract Method - Code that can be grouped - Meaningful name for method Inline Method - inverse of Extract Method - Method body is more obvious Extract Variable - Expression: hard to understand

More information

Refactoring. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 27 11/29/11. University of Colorado, 2011

Refactoring. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 27 11/29/11. University of Colorado, 2011 Refactoring Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 27 11/29/11 University of Colorado, 2011 Credit where Credit is Due Some of the material for this lecture is taken

More information

Credit where Credit is Due. Lecture 25: Refactoring. Goals for this lecture. Last Lecture

Credit where Credit is Due. Lecture 25: Refactoring. Goals for this lecture. Last Lecture Credit where Credit is Due Lecture 25: Refactoring Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 6448 - Spring Semester, 2002 Some of the material for this lecture and lecture 26 is taken

More information

CLEAN CODE, CODE SMELLS, REFACTORING

CLEAN CODE, CODE SMELLS, REFACTORING CLEAN CODE, CODE SMELLS, REFACTORING AND RELATED PRINCIPLES Barbora Bühnová buhnova@fi.muni.cz LAB OF SOFTWARE ARCHITECTURES AND INFORMATION SYSTEMS FACULTY OF INFORMATICS MASARYK UNIVERSITY, BRNO Outline

More information

Refactoring. Joseph W. Yoder. The Refactory, Inc. The Refactory Principals.

Refactoring. Joseph W. Yoder. The Refactory, Inc.  The Refactory Principals. Refactoring Joseph W. Yoder The Refactory, Inc. joe@refactory.com http://www.refactory.com The Refactory Principals John Brant Don Roberts Brian Foote Joe Yoder Ralph Johnson Refactory Affiliates Joseph

More information

Refactoring. Refactoring Techniques

Refactoring. Refactoring Techniques Refactoring Refactoring Techniques Code Quality is Important! Refactoring is... A disciplined technique for restructuring an existing body of code, altering its internal structure without changing its

More information

Refactoring Maintenance Evolution 10/31/2014. MTAT Software Engineering. Assessment Slide from Lecture 1

Refactoring Maintenance Evolution 10/31/2014. MTAT Software Engineering. Assessment Slide from Lecture 1 MTAT.03.094 Software Engineering Lecture 08: Refactoring Fall 2014 Dietmar Pfahl email: dietmar.pfahl@ut.ee Assessment Slide from Lecture 1 Next Labs Week: 70% of total grade Evaluation Exam 30% of total

More information

Refactoring. So#ware Quality Quality Audit and Cer4fica4on. Master in Computer Engineering. Roberto García

Refactoring. So#ware Quality Quality Audit and Cer4fica4on. Master in Computer Engineering. Roberto García Refactoring So#ware Quality Quality Audit and Cer4fica4on Master in Computer Engineering Roberto García (rgarcia@diei.udl.cat) Introduc4on When considering soaware evolu4on, the key dis4nc4on is: Program's

More information

Refactoring. Section (JIA s) OTHER SOURCES

Refactoring. Section (JIA s) OTHER SOURCES Refactoring Section 7.2.1 (JIA s) OTHER SOURCES Code Evolution Programs evolve and code is NOT STATIC Code duplication Outdated knowledge (now you know more) Rethink earlier decisions and rework portions

More information

Evolving Software. CMSC 433 Programming Language Technologies and Paradigms Spring Example. Some Motivations for This Refactoring

Evolving Software. CMSC 433 Programming Language Technologies and Paradigms Spring Example. Some Motivations for This Refactoring CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Refactoring April 24, 2007 Lots of material taken from Fowler, Refactoring: Improving the Design of Existing Code 1 Evolving Software

More information

Administrivia. Programming Language Fall Example. Evolving Software. Project 3 coming out Midterm October 28. Refactoring October 14, 2004

Administrivia. Programming Language Fall Example. Evolving Software. Project 3 coming out Midterm October 28. Refactoring October 14, 2004 CMSC 433 Programming Language Fall 2004 Project 3 coming out Midterm October 28 Administrivia Refactoring October 14, 2004 Lots of material taken from Fowler, Refactoring: Improving the Design of Existing

More information

Refactoring. Paul Jackson. School of Informatics University of Edinburgh

Refactoring. Paul Jackson. School of Informatics University of Edinburgh Refactoring Paul Jackson School of Informatics University of Edinburgh Refactoring definition Refactoring (noun) is a change made to the internal structure of software to make it easier to understand,

More information

bright code, dull code by fox \

bright code, dull code by fox \ bright code, dull code by fox peterson @a_fox_box \ Can you think of a time you ve been here? You come across a piece of code, you are expected to be able to work with it, and you re thinking I DIDN T

More information

Recap: Class Diagrams

Recap: Class Diagrams Com S 362: Object-Oriented Analysis and Design Recap: Class Diagrams Class diagrams represent design structure Three parts: name, attribute, operations Visibility, attribute type, multiplicity Association,

More information

CSCD01 Engineering Large Software Systems. Refactoring. Joe Bettridge. Winter With thanks to Anya Tafliovich (Based on Refactoring by M.

CSCD01 Engineering Large Software Systems. Refactoring. Joe Bettridge. Winter With thanks to Anya Tafliovich (Based on Refactoring by M. CSCD01 Engineering Large Software Systems Refactoring Joe Bettridge Winter 2018 With thanks to Anya Tafliovich (Based on Refactoring by M. Fowler) What is Refactoring? Process of changing a software system

More information

COURSE 11 DESIGN PATTERNS

COURSE 11 DESIGN PATTERNS COURSE 11 DESIGN PATTERNS PREVIOUS COURSE J2EE Design Patterns CURRENT COURSE Refactoring Way refactoring Some refactoring examples SOFTWARE EVOLUTION Problem: You need to modify existing code extend/adapt/correct/

More information

CISC327 - Software Quality Assurance

CISC327 - Software Quality Assurance CISC327 - Software Quality Assurance Lecture 19 0 (23 in 2017) Code Inspection in XP CISC327-2003 2018 J.R. Cordy, S. Grant, J.S. Bradbury, J. Dunfield 19 0 say what My next surgery is scheduled for Nov.

More information

Programming Logic and Design Sixth Edition

Programming Logic and Design Sixth Edition Objectives Programming Logic and Design Sixth Edition Chapter 4 Making Decisions In this chapter, you will learn about: Evaluating Boolean expressions to make comparisons The relational comparison operators

More information

Refactoring. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 27 04/19/11. University of Colorado, 2011

Refactoring. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 27 04/19/11. University of Colorado, 2011 Refactoring Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 27 04/19/11 University of Colorado, 2011 Credit where Credit is Due Some of the material for this lecture is taken

More information

EECS 4314 Advanced Software Engineering. Topic 10: Software Refactoring Zhen Ming (Jack) Jiang

EECS 4314 Advanced Software Engineering. Topic 10: Software Refactoring Zhen Ming (Jack) Jiang EECS 4314 Advanced Software Engineering Topic 10: Software Refactoring Zhen Ming (Jack) Jiang Acknowledgement Some slides are adapted from Professor Marty Stepp, Professor Oscar Nierstrasz Relevant Readings

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

JUnit 3.8.1, 64. keep it simple stupid (KISS), 48

JUnit 3.8.1, 64. keep it simple stupid (KISS), 48 Index A accessor methods, 11, 152 add parameter technique, 189 190 add() method, 286 287, 291 algorithm, substituting, 104 105 AND logical operator, 172 architectural design patterns, 277 278 architecture,

More information

Lecture Notes. Polymorphism. Polymorphism. If Polymorphism is Not Available. To be placed at:

Lecture Notes. Polymorphism. Polymorphism. If Polymorphism is Not Available. To be placed at: To be placed at: Lecture Notes www.cs.umb.edu/~jxs/courses/cs40 Polymorphism Polymorphism If Polymorphism is Not Available Customer gettotaltax():float * Account accounts # balance: float getbalance():

More information

Software Engineering. Top-Down Design. Bottom-Up Design. Software Process. Top-Down vs. Bottom-Up 15/06/2011

Software Engineering. Top-Down Design. Bottom-Up Design. Software Process. Top-Down vs. Bottom-Up 15/06/2011 CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2011 Thorsten Joachims Lecture 7: Software Design Software Engineering The art by which we start with a problem statement and gradually

More information

Fundamentals of Object Oriented Programming

Fundamentals of Object Oriented Programming INDIAN INSTITUTE OF TECHNOLOGY ROORKEE Fundamentals of Object Oriented Programming CSN- 103 Dr. R. Balasubramanian Associate Professor Department of Computer Science and Engineering Indian Institute of

More information

Where did the word refactoring come from?

Where did the word refactoring come from? Where did the word refactoring come from? This question struck my mind a few times when writing the refactoring book. I knew the term was used within a fairly small community, so in order to discover the

More information

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception Ariel Shamir 1 Run-time Errors Sometimes when the computer

More information

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception 22 November 2007 Ariel Shamir 1 Run-time Errors Sometimes

More information

So#ware Engineering I. Based on materials by Ken Birman, Cornell

So#ware Engineering I. Based on materials by Ken Birman, Cornell So#ware Engineering I Based on materials by Ken Birman, Cornell 1 So#ware Engineering The art by which we start with a problem statement and gradually evolve a solu@on There are whole books on this topic

More information

Chapter 15: A Longer Example

Chapter 15: A Longer Example Chapter 15: A Longer Example Reading individual refactorings is important, because you have to know the moves in order to play the game. Yet reading about refactorings one at a time can also miss the point,

More information

CFG (Control flow graph)

CFG (Control flow graph) CFG (Control flow graph) Class B T12 오지은 200814189 신승우 201011340 이종선 200811448 Introduction to CFG Algorithm to construct Control Flow Graph Statement of Purpose Q & A Introduction to CFG Algorithm to

More information

Declarations and Access Control SCJP tips

Declarations and Access Control  SCJP tips Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for

More information

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan Lecture 08-1 Programming in C++ PART 1 By Assistant Professor Dr. Ali Kattan 1 The Conditional Operator The conditional operator is similar to the if..else statement but has a shorter format. This is useful

More information

Object-Oriented Software Design and Software Processes

Object-Oriented Software Design and Software Processes Object-Oriented Software Design (COMP 304) Object-Oriented Software Design and Software Processes Hans Vangheluwe Modelling, Simulation and Design Lab (MSDL) School of Computer Science, McGill University,

More information

Assertions & Design-by-Contract using JML Erik Poll University of Nijmegen

Assertions & Design-by-Contract using JML Erik Poll University of Nijmegen Assertions & Design-by-Contract using JML Erik Poll University of Nijmegen Erik Poll - JML p.1/39 Overview Assertions Design-by-Contract for Java using JML Contracts and Inheritance Tools for JML Demo

More information

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass? 1. Overriding Methods A subclass can modify behavior inherited from a parent class. A subclass can create a method with different functionality than the parent s method but with the same: Name Return type

More information

CS 3 Introduction to Software Engineering. 3: Exceptions

CS 3 Introduction to Software Engineering. 3: Exceptions CS 3 Introduction to Software Engineering 3: Exceptions Questions? 2 Objectives Last Time: Procedural Abstraction This Time: Procedural Abstraction II Focus on Exceptions. Starting Next Time: Data Abstraction

More information

SOFTWARE ENGINEERING SOFTWARE EVOLUTION. Saulius Ragaišis.

SOFTWARE ENGINEERING SOFTWARE EVOLUTION. Saulius Ragaišis. SOFTWARE ENGINEERING SOFTWARE EVOLUTION Saulius Ragaišis saulius.ragaisis@mif.vu.lt CSC2008 SE Software Evolution Learning Objectives: Identify the principal issues associated with software evolution and

More information

Note that if both p1 and p2 are null, equals returns true.

Note that if both p1 and p2 are null, equals returns true. 258 students took the exam. The average was 26.4 out of 36; the median was 27.5; scores ranged from 3 to 35.5. 133 students scored between 27.5 and 36, 99 between 18.5 and 27, 24 between 9.5 and 18, and

More information

SELECTION. (Chapter 2)

SELECTION. (Chapter 2) SELECTION (Chapter 2) Selection Very often you will want your programs to make choices among different groups of instructions For example, a program processing requests for airline tickets could have the

More information

Refactoring: Improving the Design of Existing Code

Refactoring: Improving the Design of Existing Code Refactoring: Improving the Design of Existing Code Martin Fowler fowler@acm.org www.martinfowler.com www.thoughtworks.com What is Refactoring A series of small steps, each of which changes the program

More information

Refactoring, Part 2. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 27 12/01/09. University of Colorado, 2009

Refactoring, Part 2. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 27 12/01/09. University of Colorado, 2009 Refactoring, Part 2 Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/5448 Lecture 27 12/01/09 University of Colorado, 2009 1 Introduction Credit where Credit is Due Some of the material for

More information

CPSC 3740 Programming Languages University of Lethbridge. Control Structures

CPSC 3740 Programming Languages University of Lethbridge. Control Structures Control Structures A control structure is a control statement and the collection of statements whose execution it controls. Common controls: selection iteration branching Control Structures 1 15 Howard

More information

Refactoring Exercise

Refactoring Exercise Refactoring Exercise Maria Grazia Pia INFN Genova, Italy Maria.Grazia.Pia@cern.ch http://www.ge.infn.it/geant4/training/apc2017/ Exercise: The Video Store Grab basic concepts Get into the habit of refactoring

More information

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17 List of Programs xxv List of Figures xxix List of Tables xxxiii Preface to second version xxxv PART 1 Structured Programming 1 1 Getting started 3 1.1 Programming 3 1.2 Editing source code 5 Source code

More information

How We Refactor, and How We Know It

How We Refactor, and How We Know It Emerson Murphy-Hill, Chris Parnin, Andrew P. Black How We Refactor, and How We Know It Urs Fässler 30.03.2010 Urs Fässler () How We Refactor, and How We Know It 30.03.2010 1 / 14 Refactoring Definition

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

INHERITANCE. Spring 2019

INHERITANCE. Spring 2019 INHERITANCE Spring 2019 INHERITANCE BASICS Inheritance is a technique that allows one class to be derived from another A derived class inherits all of the data and methods from the original class Suppose

More information

Program Correctness and Efficiency. Chapter 2

Program Correctness and Efficiency. Chapter 2 Program Correctness and Efficiency Chapter 2 Chapter Objectives To understand the differences between the three categories of program errors To understand the effect of an uncaught exception and why you

More information

PROCEDURAL DATABASE PROGRAMMING ( PL/SQL AND T-SQL)

PROCEDURAL DATABASE PROGRAMMING ( PL/SQL AND T-SQL) Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 3 Database Programming PROCEDURAL DATABASE PROGRAMMING ( PL/SQL AND T-SQL) AGENDA 3. Declaring Variables/Constants 4. Flow Control

More information

CSE 452: Programming Languages. Outline of Today s Lecture. Expressions. Expressions and Control Flow

CSE 452: Programming Languages. Outline of Today s Lecture. Expressions. Expressions and Control Flow CSE 452: Programming Languages Expressions and Control Flow Outline of Today s Lecture Expressions and Assignment Statements Arithmetic Expressions Overloaded Operators Type Conversions Relational and

More information

Course December Adrian Iftene

Course December Adrian Iftene Course 10 12 December 2016 Adrian Iftene adiftene@info.uaic.ro Recapitulation QoS Functional Testing Non-Functional Testing Rotting Design Refactoring 2 QoS = ability to provide different priority to different

More information

Small changes to code to improve it

Small changes to code to improve it Small changes to code to improve it 1 Refactoring Defined A change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior

More information

Building Java Programs

Building Java Programs Building Java Programs Chapter 9 Inheritance, Polymorphism; reading: 9.2 2 The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs.

More information

CS61BL Summer 2013 Midterm 2

CS61BL Summer 2013 Midterm 2 CS61BL Summer 2013 Midterm 2 Sample Solutions + Common Mistakes Question 0: Each of the following cost you.5 on this problem: you earned some credit on a problem and did not put your five digit on the

More information

Principles of Testing and Analysis. COMP 4004 Fall Notes Adapted from Dr. A. Williams

Principles of Testing and Analysis. COMP 4004 Fall Notes Adapted from Dr. A. Williams Principles of Testing and Analysis COMP 4004 Fall 2008 Notes Adapted from Dr. A. Williams Software Quality Assurance Lec 3 1 Principles of Testing and Analysis Sensitivity Redundancy Restriction Partition

More information

Text Input and Conditionals

Text Input and Conditionals Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()

More information

Decision Making in C

Decision Making in C Decision Making in C Decision making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed

More information

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java

Objectives. Problem Solving. Introduction. An overview of object-oriented concepts. Programming and programming languages An introduction to Java Introduction Objectives An overview of object-oriented concepts. Programming and programming languages An introduction to Java 1-2 Problem Solving The purpose of writing a program is to solve a problem

More information

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application Last Time v We created our first Java application v What are the components of a basic Java application? v What GUI component did we use in the examples? v How do we write to the standard output? v An

More information

COMP 401 Spring 2013 Midterm 2

COMP 401 Spring 2013 Midterm 2 COMP 401 Spring 2013 Midterm 2 I have not received nor given any unauthorized assistance in completing this exam. Signature: Name: PID: Please be sure to put your PID at the top of each page. This page

More information

Code Refactoring. CS356 Object-Oriented Design and Programming November 21, 2014

Code Refactoring. CS356 Object-Oriented Design and Programming   November 21, 2014 Code Refactoring CS356 Object-Oriented Design and Programming http://cs356.yusun.io November 21, 2014 Yu Sun, Ph.D. http://yusun.io yusun@csupomona.edu The Problem: Software Drift Over many phases of maintenance,

More information

5. Control Statements

5. Control Statements 5. Control Statements This section of the course will introduce you to the major control statements in C++. These control statements are used to specify the branching in an algorithm/recipe. Control statements

More information

Designing Robust Classes

Designing Robust Classes Designing Robust Classes Learning Goals You must be able to:! specify a robust data abstraction! implement a robust class! design robust software! use Java exceptions Specifications and Implementations

More information

Class, Variable, Constructor, Object, Method Questions

Class, Variable, Constructor, Object, Method Questions Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx

More information

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class. Name: Covers Chapters 1-3 50 mins CSCI 1301 Introduction to Programming Armstrong Atlantic State University Instructor: Dr. Y. Daniel Liang I pledge by honor that I will not discuss this exam with anyone

More information

CT 229 Object-Oriented Programming Continued

CT 229 Object-Oriented Programming Continued CT 229 Object-Oriented Programming Continued 24/11/2006 CT229 Summary - Inheritance Inheritance is the ability of a class to use the attributes and methods of another class while adding its own functionality

More information

Code Reuse: Inheritance

Code Reuse: Inheritance Object-Oriented Design Lecture 14 CSU 370 Fall 2008 (Pucella) Tuesday, Nov 4, 2008 Code Reuse: Inheritance Recall the Point ADT we talked about in Lecture 8: The Point ADT: public static Point make (int,

More information

SOFTWARE ENGINEERING. Lecture 4 CS2110 Spring 2013

SOFTWARE ENGINEERING. Lecture 4 CS2110 Spring 2013 1 SOFTWARE ENGINEERING Lecture 4 CS2110 Spring 2013 ... picking up where we stopped 2 We were discussing the class hierarchy We had been focused on extending a class by creating a new child class We looked

More information

... picking up where we stopped SOFTWARE ENGINEERING. Interfaces 28/01/2013. Example: Overriding tostring. Example: Overriding tostring

... picking up where we stopped SOFTWARE ENGINEERING. Interfaces 28/01/2013. Example: Overriding tostring. Example: Overriding tostring 1 picking up where we stopped 2 We were discussing the class hierarchy SOFTWARE ENGINEERING Lecture 4 CS2110 Spring 2013 We had been focused on extending a class by creating a new child class We looked

More information

CLASS DESIGN. Objectives MODULE 4

CLASS DESIGN. Objectives MODULE 4 MODULE 4 CLASS DESIGN Objectives > After completing this lesson, you should be able to do the following: Use access levels: private, protected, default, and public. Override methods Overload constructors

More information

Loops. CSE 114, Computer Science 1 Stony Brook University

Loops. CSE 114, Computer Science 1 Stony Brook University Loops CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Suppose that you need to print a string (e.g., "Welcome to Java!") a user-defined times N: N?

More information

MSO Refactoring. Hans Philippi. October 2, Refactoring 1 / 49

MSO Refactoring. Hans Philippi. October 2, Refactoring 1 / 49 MSO Refactoring Hans Philippi October 2, 2018 Refactoring 1 / 49 This lecture What is refactoring?... or how to deal with the horrible code your colleagues have created... or how to deal with the horrible

More information

CS 61B Discussion 5: Inheritance II Fall 2014

CS 61B Discussion 5: Inheritance II Fall 2014 CS 61B Discussion 5: Inheritance II Fall 2014 1 WeirdList Below is a partial solution to the WeirdList problem from homework 3 showing only the most important lines. Part A. Complete the implementation

More information

Abstract Classes, Exceptions

Abstract Classes, Exceptions CISC 370: Inheritance, Abstract Classes, Exceptions June 15, 1 2006 1 Review Quizzes Grades on CPM Conventions Class names are capitalized Object names/variables are lower case String.doStuff dostuff();

More information

CS 61B Data Structures and Programming Methodology. July 3, 2008 David Sun

CS 61B Data Structures and Programming Methodology. July 3, 2008 David Sun CS 61B Data Structures and Programming Methodology July 3, 2008 David Sun Announcements Project 1 is out! Due July 15 th. Check the course website. Reminder: the class newsgroup ucb.class.cs61b should

More information

Super-Classes and sub-classes

Super-Classes and sub-classes Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an

More information

Control Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur

Control Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur Control Structures Code can be purely arithmetic assignments At some point we will need some kind of control or decision making process to occur C uses the if keyword as part of it s control structure

More information

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are built on top of that. CMSC131 Inheritance Object When we talked about Object, I mentioned that all Java classes are "built" on top of that. This came up when talking about the Java standard equals operator: boolean equals(object

More information

CS 162, Lecture 25: Exam II Review. 30 May 2018

CS 162, Lecture 25: Exam II Review. 30 May 2018 CS 162, Lecture 25: Exam II Review 30 May 2018 True or False Pointers to a base class may be assigned the address of a derived class object. In C++ polymorphism is very difficult to achieve unless you

More information

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA DECISION STRUCTURES: USING IF STATEMENTS IN JAVA S o far all the programs we have created run straight through from start to finish, without making any decisions along the way. Many times, however, you

More information

CS 370 Statements D R. M I C H A E L J. R E A L E F A L L

CS 370 Statements D R. M I C H A E L J. R E A L E F A L L CS 370 Statements D R. M I C H A E L J. R E A L E F A L L 2 0 1 5 Overview In these slides, we ll talk about good practices related to programming statements: Organizing straight-line code Using conditionals

More information

CS100J, Fall 2003 Preparing for Prelim 1: Monday, 29 Sept., 7:30 9:00PM

CS100J, Fall 2003 Preparing for Prelim 1: Monday, 29 Sept., 7:30 9:00PM CS100J, Fall 2003 Preparing for Prelim 1: Monday, 29 Sept., 7:30 9:00PM This handout explains what you have to know for the first prelim. Terms and their meaning Below, we summarize the terms you should

More information

Lecture 5: Implementing Lists, Version 1

Lecture 5: Implementing Lists, Version 1 CS18 Integrated Introduction to Computer Science Fisler, Nelson Lecture 5: Implementing Lists, Version 1 Contents 1 Implementing Lists 1 2 Methods 2 2.1 isempty...........................................

More information

University of Utah School of Computing

University of Utah School of Computing University of Utah School of Computing CS 1410 / CS 2000 Study Notes December 10, 2011 This study guide is designed to help you prepare and study the appropriate material for the final exam. For the multiple

More information

Modern Programming Languages. Lecture LISP Programming Language An Introduction

Modern Programming Languages. Lecture LISP Programming Language An Introduction Modern Programming Languages Lecture 18-21 LISP Programming Language An Introduction 72 Functional Programming Paradigm and LISP Functional programming is a style of programming that emphasizes the evaluation

More information

Definition of DJ (Diminished Java)

Definition of DJ (Diminished Java) Definition of DJ (Diminished Java) version 0.5 Jay Ligatti 1 Introduction DJ is a small programming language similar to Java. DJ has been designed to try to satisfy two opposing goals: 1. DJ is a complete

More information

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual

More information

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE Abstract Base Classes POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors class B { // base class virtual void m( ) =0; // pure virtual function class D1 : public

More information

ESC/Java2 Warnings David Cok, Joe Kiniry, and Erik Poll Eastman Kodak Company, University College Dublin, and Radboud University Nijmegen

ESC/Java2 Warnings David Cok, Joe Kiniry, and Erik Poll Eastman Kodak Company, University College Dublin, and Radboud University Nijmegen ESC/Java2 Warnings David Cok, Joe Kiniry, and Erik Poll Eastman Kodak Company, University College Dublin, and Radboud University Nijmegen David Cok, Joe Kiniry & Erik Poll - ESC/Java2 & JML Tutorial p.1/??

More information

COMP 401 Spring 2013 Midterm 2

COMP 401 Spring 2013 Midterm 2 COMP 401 Spring 2013 Midterm 2 I have not received nor given any unauthorized assistance in completing this exam. Signature: Name: PID: Please be sure to put your PID at the top of each page. This page

More information

Lecture 2: Java & Javadoc

Lecture 2: Java & Javadoc Lecture 2: Java & Javadoc CS 62 Fall 2018 Alexandra Papoutsaki & William Devanny 1 Instance Variables or member variables or fields Declared in a class, but outside of any method, constructor or block

More information

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Third Look At Java Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Little Demo public class Test { public static void main(string[] args) { int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]);

More information

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs. Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract Classes

More information