תכנות מונחה עצמים - III. Topics related to OO development Refactoring Design...

50
ההההה ההההה ההההה- III

Transcript of תכנות מונחה עצמים - III. Topics related to OO development Refactoring Design...

- תכנות מונחה עצמיםIII

Topics related to OO development

Refactoring

Design patterns

Refactoring

Agenda Introductory questions

Example

Refactoring: Focus on its nature, not on techniques What is refactoring?

Why refactoring?

How refactoring?

Why refactoring hard?

Extreme Programming and refactoring

Summary

Introductory Questions

מתי אתם לא מרוצים מקוד שכתבתם? מה אתם

עושים במצבים כאלה?

.נניח שאתם עובדים בצוות פיתוח תוכנה

ראש הצוות שלכם מבקשת מכם לכתוב את הקוד כל שהוא

יהיה קריא יותר. כיצד תגיבו?

חבר לצוות מספר שמה שחשוב לו בפיתוח תוכנה הוא

שהקוד רץ. לכן, ברגע שהקוד שכתב עובר את כל הבדיקות,

הוא עוזב את הקוד ולא משפר את המבנה והעיצוב שלו.

כיצד תגיבו?

Example

A given design

Source: Martin Fowler, Kent Beck (Contributor), John Brant (Contributor), William Opdyke, don Roberts. (2002). Refactoring: Improving the Design of Existing Code, Addison-Wesley.

Example

A given design:

Is it well designed?

In what cases may it

cause problems?

Would you change it?

If yes: suggest alternative designs.

Example – Reflection

How it emerged? Deal was originally being used to display a single deal. Someone wanted a table of deals. The subclass Tabular Active Deal displays a table. Now you want tables of passive deals. Another subclass is added. Small changes in many places. The code has become complicated, time is pressing, ... Adding a new kind of deal is hard, because the deal logic is

tangled with the presentation logic.

Example – Reflection

How it emerges? – In general

“One day you are adding one little subclass to do a little

job. The next day you are adding other subclasses to do

the same job in other parts of the hierarchy. A week (or

month or year) later you are swimming in spaghetti.

Without a paddle.” (Fowler)

Example – Reflection

Problems in tangled inheritance:

It leads to code duplication.

It makes changes more difficult:

Strategies for solving a certain problem are spread around.

The resulting code is hard to understand.

Example – Reflection

How tangled inheritance can be observed? Spot for a single inheritance hierarchy that is doing 2 jobs.

“If every class at a certain level in the hierarchy has subclasses

that begin with the same adjective, you probably are doing two

jobs with one hierarchy.”

Why it can not be coded “correctly” at the first

stage?

Step-by-step refactoring (Fowler’s style)

Example – Step by Step Refactoring

First step: identify the jobs being done by the

hierarchy.

Job #1: capturing variation according to type of deal.

Job #2: capturing variation according to presentation

style.

Second step: decide which job is more

important.

The dealness of the object is far more

important than the presentation style.

Leave Deal alone and extract the

presentation style to its own hierarchy.

Example – Step by Step Refactoring

Example – Step by Step Refactoring

Third step: use Extract Class to create a

presentation style.

Extract Class You have one class doing work that should be done by

two.

Create a new class and move the relevant fields and

methods from the old class into the new class.

Example – Step by Step Refactoring

Fourth step: Create subclasses of the extracted

class and initialize the instance variable to the

appropriate subclass.

Adding subclasses of presentation style

Example – Step by Step Refactoring

Fifth step: Use Move Method and Move Field to

move the presentation-related methods and

variables of the deal subclasses to the

presentation style subclasses.

No code left in the classes Tabular Active Deal and Tabular Passive Deal. Remove them.

Example – Step by Step Refactoring

Sixth step: Separate the hierarchies: Distinguish

between single and tabular.

Example Original Refactored

Example - Reflection

What did we do?

Is there a difference between the two designs? If yes – what is it?

How is this change supposed to improve our life?

In what way may the change be useful for someone who did not write the code?

Couldn’t we write the code refactored from the beginning?

Example - Summary

Tease Apart Inheritance

You have an inheritance hierarchy that is doing

two jobs at once.

Create two hierarchies and use delegation to

invoke one from the other.

This format guides Fowler’s book.

Example - Summary

Delegation:

The ability of an object to issue a message to another

object in response to a message. Delegation can be used

as an alternative to inheritance. Contrast: inheritance.

Source: OMG Unified Modeling Language Specification.

More about inheritance vs. delegation:

http://www-inst.eecs.berkeley.edu/~cs61a-tb/week8/oop.html

Example - Summary

למהrefactoring מתאים ליישום

בפיתוח תוכנה מונחה עצמים?

Refactoring

In what follows:

What is refactoring?

Why refactoring?

When refactoring? When not?

How refactoring?

Why refactoring hard?

XP and refactoring

Refactoring

Fowler: Refactoring is the process of changing a software

system in such a way that it does not alter the external

(observable) behavior of the code yet improves its

internal structure, to make it easier to understand and

cheaper to modify.

Kent (in Fowler, p. 51): Refactoring is the process of

taking a running program and adding to its value, not by

changing its behavior but by giving it more of these

qualities that enable us to continue developing at speed.

Refactoring

What do programmers do when refactoring:

remove duplication

improve communication and program

comprehension

add simplicity

add flexibility

Refactoring – Metaphors

Metaphors for refactoring :

relationships with your program

health

Refactoring – Metaphors I

[Refactoring] is like a new kind of relationship with your

program. When you really understand refactoring, the

design of the system is as fluid and plastic and moldable

to you as the individual characters in a source code file.

You can feel the whole design at once. You can see how

it might flex and change – a little this way and this is

possible, a little that way and that is possible. (Kent, in

Fowler, p. 333)

Refactoring – Metaphors II

Refactoring as health: exercises and eating a proper diet.

The culture we live in.

We can always make excuses, but we are only fooling

ourselves if we continue to ignore good behavior.

Near-term and long-term benefits.

Refactoring

Main questions:

What is refactoring? OK

Why refactoring?

When refactoring? When not?

How refactoring?

Why refactoring hard? Why people do not do that?

XP and refactoring

Why Refactoring

Refactoring improves the design of the software

fosters the examination of the software design

removes duplicated code:

reduces the amount of code

the code says everything once and only once

Why Refactoring

Refactoring makes software easier to understand

helps make your code more readable

increases program comprehension: leads to higher

levels of understanding that otherwise may be missed

Why Refactoring

Refactoring helps you program faster

sounds counterintuitive

less bugs, no patches

helps correct bugs: errors need to be modified

only in one place

Refactoring

Main questions:

What is refactoring OK

Why refactoring? OK

When refactoring? When not?

How refactoring?

Why refactoring hard? Why people do not do that?

XP and refactoring

When refactoring

You have written some code.

How would you find what to refactor?

What clues in the code may guide you?

Fowler, chapter 3 – Bad smells in code

When refactoring Fowler, Chapter 3 – Bad smells in Code

Duplicated Code:

“If you see the same code structure in more than one

place, you can be sure that your program will be better

if you find a way to unify them”.

Extract Method: When you have the same expression

in two methods of the same class.

When refactoring Fowler, Chapter 3 – Bad smells in Code

Long Method:

“the longer the procedure is, the more difficult it is to

understand”.

Extract method: find parts of the methods that seem

to go nicely together and make a new method.

When refactoring Fowler, Chapter 3 – Bad smells in Code

Comments: “if you need a comment to explain what a block of code

does, try Extract Method. If the method is already extracted

but you still need a comment to explain what it does, use

Rename Method.”

“when you feel the need to write a comment, first try to

refactor the code so that any comment becomes

superfluous”.

“a comment is a good place to say why you did something.

This kind of information helps future modifiers”.

When shouldn't you refactor?

When the code is a mess and it would

be better to start from the beginning.

Factors that will be discussed later:

Culture

Internal resistance

Refactoring

Main questions:

What is refactoring OK

Why refactoring? OK

When refactoring? When not? OK

How refactoring?

Why refactoring hard? Why people do not do that?

XP and refactoring

How Refactoring

Most of the time it is done in small and local

places

Sometimes: a sequence of refactoring

Refactoring requires high level of awareness

All the time

Two hats: adding functions and refactoring

How refactoring Resources for specific refactoring:

Refactoring Home Page: http://www.refactoring.com

Martin Fowler, Kent Beck (Contributor), John Brant

(Contributor), William Opdyke, don Roberts (1999).

Refactoring: Improving the Design of Existing Code,

Addison-Wesley. Many of the citations in this refactoring presentation are from the

book.

Some IDEs (Integrated development environments)

offer Refactoring menu Example: Eclipse, IntelliJ

Refactoring

Main questions:

What is refactoring OK

Why refactoring? OK

When refactoring? When not? OK

How refactoring? OK

Why refactoring hard? Why people do not refactor?

Extreme Programming (XP) and refactoring

Why refactoring hard ?

Sub-questions:

Why people do not refactor naturally?

Why does refactoring raise resistance?

Why refactoring hard ?

Culture:

“refactoring is an overhead activity. I’m paid to write

new, revenue-generating features”.

“What do I tell my manager?”

Treat it as part of the profession: This is how you

develop code, it is not viewed by you as an additional

work.

Why refactoring hard ?

Internal resistance: Why are developers reluctant to

refactor? (Opdyke, in Fowler’s book, p. 313)

it should be executed when the code runs and all the

tests pass. It seems that time is wasted now.

if the benefits are long-term, why exert the effort now?

In the long term, developers might not be with the

project to reap the benefits.

developers might not understand how to refactor.

refactoring might break the existing program.

Refactoring

Main questions:

What is refactoring OK

Why refactoring? OK

When refactoring? When not? OK

How refactoring? OK

Why refactoring hard? OK

Extreme Programming and refactoring

Extreme Programming and Refactoring

Refactoring is part of eXtreme Programming:

Refactoring can be carried out without XP, but it has

additional value with XP

It has similar targets to those that XP inspires

When refactoring is part of XP:

refactoring becomes part of the routine

it stops feeling like an overhead activity

Extreme Programming and Refactoring

Mutual relationships of refactoring and other XP practices

Source: Beck, K. (2000). eXtreme Programming explained, Addison Wesley.

Refactoring

Main questions:

What is refactoring OK

Why refactoring? OK

When refactoring? When not? OK

How refactoring? OK

Why people do not refactoring? OK

XP and refactoring OK

Refactoring – Summary

Refactoring requires awareness!

Main Message:

We should not skip refactoring.

Software development is a process that all its

details cannot be envisioned in advance.

Refactoring may improve programming skills.