CSC/ECE 517 Fall 2009/wiki 2 If SJ: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
 
(4 intermediate revisions by the same user not shown)
Line 1: Line 1:
'''Refactoring If Statement with Polymorphism.'''
'''Refactoring If Statement with Polymorphism.'''


== Problem with If Statement ==
== Design Consideration: Reuse and Change ==


According to the famous book "Refactoring: Improving the Design of Existing Code " by Martin Fowler: [5], refactoring is the process of applying behavior-preserving transformations to a program with the objective of improving the program’s design. Intuitively people refer to code refactoring as "cleaning it up."
One of the most important consideration of Object-Orientation Software Design is 'Reuse' and 'Change' [2][4]. In terms of reuse, we mean to build the new software with the building block from the old software. The importance of 'change' is from the fact that the software is always changing to keep alive. So that how to effectively make change to the source code is critical for the software design.  
=== The Problem of If Statement ===


=== Idea of Polymorphism ===
Under the design consideration we have discussed, the problem of if statement is quite obvious: 1. the conditional relationship in function level prevent us to reuse each of the function separately. We can only reuse the whole application as a unit. 2. when we want to change the functionality of a certain function or add a new function we have to trace to every implementation code. Such change is expensive and violate the OO principle 'code to interface instead of implementation'.   


Refactoring is very useful for software engineer to maintain the quality of their code in different environment. In fact, no software can be guaranteed to be perfect when it is first developed. Usually when the source code is applied to different customer needs, we want to improve the inner-structure without modify the external behavior. The ability to refactor your code takes the pressure off the design phase of software development. Refactoring gives you the ability to change the design of the code at a later stage. This means that you don’t have to get the design absolutely right before you write any code. You can get a rough design worked out, code it up and then if (when) you spot a better design you can refactor your code towards the better design.
=== Example of If statement ===
<pre>
public class Operator
{
    string operation;


=== Example of Refactoring Conditional Statement with Polymorphism===
    public int Execute(int x, int y)
 
    {
In the following we list some popular refactoring to specify how refactoring transform the code. For more detail information, the reader please refer to the section 2.1.2 of the thesis of Thomas Corbat [1]. [1] provide Ruby example for each refactoring this list. 
        switch(operation)
 
        {
{|
            case "Add":
| 1. Merge Class Parts
                return x + y;
|-
            case "Subtract":
| 2. Convert Local Variable to Field
                return x - y;
|-
            case "Multiply":
| 3. Encapsulate Field
                return x * y;
|-
            case "Divide":
| 4. Extract Method
                return x / y;
|-
            default:
| 5. Inline Class
                throw new InvalidOperationException("Unsupported operation");
|-
        }
| 6. Inline Method
    }
|-
}
| 7. Move Field
|-
| 8. Move Method
|-
| 9. Rename Class
|-
| 10. Rename Field
|-
| 11. Rename Local Variable
|-
| 12. Rename Method
|-
| 13. Replace Temporary Variable with Query
|-
| 14. Split Temporary Variable
|}
 
=== Ruby Example of Refactoring ===
 
*Before Rename:
<pre>
def badRenameMethod
    puts("Hello World");
end
</pre>
</pre>


*After Rename:
In such example of conditional statement on operator, we see that: if we want to reuse function "add" operator in the other code segment, we have to reuse whole Class operator with the value "Add". And if we want to add a new operation "Power", we need to code in the implementation of Class Operator.
<pre>
def hello
    puts("Hello World");
end
</pre>


*Before Encapsulation:
== Idea of Polymorphism ==
<pre>
Facing the problem of the conditional statement, people[2] come up with refactoring method called 'Polymorphism'. The idea of Polymorphism is to replace the highly functional relationship with the subclass override procedure under abstract class. So subclass is created to encapsulate each function in the conditional statement and the conditional relation is replaced by override a common abstract class. The advantage of such idea is to separate the functionality.   
class SomeClass
    def initialize
        @field = 0;
    end
end
</pre>


*After Encapsulation:
=== Definition of Polymorphism ===
<pre>
According to [1], Subtype polymorphism, almost universally called just polymorphism in the context of object-oriented programming, is the ability of one type, A, to appear as and be used like another type, B.
class SomeClass               
    def initialize
        @field = 0;
    end
   
    def field
        @field
    end
    private :field
   
    def field= field
        @field = field
    end
    private :field=
end
</pre>


=== Java Example of Refactoring ===
The primary usage of polymorphism in industry (object-oriented programming theory) is the ability of objects belonging to different types to respond to method, field, or property calls of the same name, each one according to an appropriate type-specific behavior. The programmer (and the program) does not have to know the exact type of the object in advance, and so the exact behavior is determined at run time.


*Before Rename:
== Example of Refactoring Conditional Statement with Polymorphism ==
*Before refactoring
<pre>
<pre>
public class rename_method
public class Operator
{
{
     static void badRenameMethod()
     string operation;
 
    public int Execute(int x, int y)
     {
     {
        System.out.println("Hello, world!");
        switch(operation)
        {
            case "Add":
                return x + y;
            case "Subtract":
                return x - y;
            case "Multiply":
                return x * y;
            case "Divide":
                return x / y;
            default:
                throw new InvalidOperationException("Unsupported operation");
        }
     }
     }
}
}
</pre>
</pre>


*After Rename:
*After refactoring
<pre>
<pre>
public class rename_method
public abstract class Operator
{
    public abstract int Execute(int x, int y)
}
 
public class Add : Operator
{
{
     static void hello()
     public override int Execute(int x, int y)
     {
     {
         System.out.println("Hello, world!");
         return x + y;
     }
     }
}
}
</pre>
public class Subtract : Operator
 
*Before Encapsulation:
<pre>
public class encap_field
{
{
     public String field;
     public override int Execute(int x, int y)
    {
        return x - y;
    }
}
}
</pre>
public class Multiply: Operator
 
*After Encapsulation:
<pre>
public class encap_field
{
{
     private int field;
     public override int Execute(int x, int y)
 
    public void setField(int field)
     {
     {
         this.field = field;
         return x * y;
     }
     }
 
}
     public int getField()
public class Divide: Operator
{
     public override int Execute(int x, int y)
     {
     {
         return field;
         return x / y;
     }
     }
}
}
</pre>
</pre>
== Refactoring support for Current Ruby IDE ==
This the following table we summary the current ruby IDE and their refactoring support situation.
{|
| Current Ruby IDE || Refactoring Support (Y/N)
|-
| [http://www.activestate.com/komodo/ ActiveState Komodo] || N
|-
| [http://www.netbeans.org/ NetBeans] || N
|-
| [http://www.ruby-ide.com/ruby/ruby_ide_and_ruby_editor.php Arachno Ruby] || N
|-
| [http://freeride.rubyforge.org/wiki/wiki.pl FreeRIDE] || N
|-
| [http://www.mondrian-ide.com/ Mondrian Ruby IDE] || N
|-
| [http://www.sapphiresteel.com/ Ruby in Steel] || N
|-
| [http://www.jetbrains.com/ruby/index.html RubyMine] || Y
|-
| [http://www.eclipse.org/ Eclipse] ([http://aptana.com/ Aptana]) || Y 
|}
=== Example of Using Ruby Refactoring Tools in Eclipse ===
Here the renaming of the method "badRenameMethod" to "Hello" is illustrated for Ruby.  The source code is shown in section 1.3.
{|
| [[Image:r00.jpg|thumb|upright|The badly named method "badRenameMethod is shown with a call to this method.]]
| [[Image:r01.jpg|thumb|upright|The method is highlighted and then right clicked on.  Refactor then Rename is selected.]]
| [[Image:r02.jpg|thumb|upright|The method is renamed to "hello"]]
| [[Image:r03.jpg|thumb|upright|A preview of each call to the method.]]
| [[Image:r04.jpg|thumb|upright|The resulting code after refactoring is shown with newly renamed method.]]
|}
Here the encapsulation of the field "field" is illustrated for Ruby.  The source code is show in section 1.3.
{|
| [[Image:r05.jpg|thumb|upright|The field to be encapsulated is shown inside its class.]]
| [[Image:r06.jpg|thumb|upright|The field is highlighted and then right clicked on.  Refactor then Encapsulate Field is selected.]]
| [[Image:r07.jpg|thumb|upright|A reader and writer method is selected to be generated and labeled private.]]
| [[Image:r08.jpg|thumb|upright|A preview of the encapsulation.]]
| [[Image:r09.jpg|thumb|upright|The resulting code after refactoring is shown with encapsulated field.]]
|}
=== Example of Using Java Refactoring Tools in Eclipse ===
Here the renaming of the method "badRenameMethod" to "Hello" is illustrated for Java. The source code is show in section 1.4.
{|
| [[Image:j00.jpg|thumb|upright|The badly named method "badRenameMethod is shown.]]
| [[Image:j01.jpg|thumb|upright|The badly named method is called.]]
| [[Image:j02.jpg|thumb|upright|The method is highlighted and then right clicked on.  Refactor then Rename is selected.]]
| [[Image:j03.jpg|thumb|upright|The method is renamed to "hello" as shown and preview is selected.]]
| [[Image:j04.jpg|thumb|upright|A preview of each call to the method.]]
| [[Image:j05.jpg|thumb|upright|The resulting code after refactoring is shown with newly renamed method.  The call is shown here.]]
|}
Here the encapsulation of the field "field" is illustrated for Java. The source code is show in section 1.4.
{|
| [[Image:j06.jpg|thumb|upright|The field to be encapsulated is shown inside its class.]]
| [[Image:j07.jpg|thumb|upright|The field is highlighted and then right clicked on.  Refactor then Encapsulate Field is selected.]]
| [[Image:j08.jpg|thumb|upright|A getter(reader) and setter(writer) mehtod is selected and named.]]
| [[Image:j09.jpg|thumb|upright|The resulting code after refactoring is shown with encapsulated field.]]
|}
== Comparison of Ruby and Java Refactoring Tools ==
=== Comprehensiveness ===
These are the following refactoring options available in eclipse for Ruby and Java.
{|
|'''Refactoring Options for Java in Eclipse'''  ||||  '''Refactoring Options for Ruby in Eclipse'''
|-
|Rename  || || Rename
|-
|Move || || Move
|-
|Change Method Signature || || Merge Class Parts in File
|-
|Extract Local Variable || || Pull Up
|-
|Extract Constant || || Pull Down
|-
|Inline || || Merge With External Class Parts
|-
|Convert Anonymous Class to Nested || || Split Local Variable
|-
|Convert Member to Top Level || || Merge With External Class Parts
|-
|Convert Local Variable to Field || || Inline
|-
|Extract Super Class || || Extract Constant
|-
|Extract Interface || || Encapsulate Field
|-
|Extract Class || || Convert Local Variable to Field
|-
|Use Supertype where possible
|-
|Pull Up
|-
|Pull Down
|-
|Introduce Parameter Object
|-
|Introduce Indirection
|-
|Introduce Factory
|-
|Introduce Parameter
|-
|Encapsulate Field
|-
|Generalize Declared Type
|-
|Infer Generic Type Arguments
|}
=== Ease of Use and Integrated Develop Environment(IDE) Integration ===
The refactoring options for Ruby and Java cover all the basic refactorings.  The differences in the number of options mainly come from the difference in the two languages. Ruby is a [http://en.wikipedia.org/wiki/Type_system#Dynamic_typing dynamically typed language], has unbounded [http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming polymorphism], and all classes are open to extension or can be inherited.  On the other hand, Java is a [http://en.wikipedia.org/wiki/Type_system#Static_typing statically typed language], polymorphism is mainly implemented via [http://en.wikipedia.org/wiki/Interface_%28computer_science%29 interfaces] and [http://en.wikipedia.org/wiki/Implementation_inheritance inheritance], and classes cannot be extended at run-time.  The given examples (in section [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2009/wiki_1a_9b_SJ#Ruby_Example_of_Refactoring [1.3]], [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2009/wiki_1a_9b_SJ#Java_Example_of_Refactoring [1.4]]) illustrate the ease of use of the refactoring tools for both Ruby and Java and how well these tools are integrated into the Eclipse IDE.
== References ==
== References ==


[1] Thomas Corbat, Lukas Felber, Mirko Stocker Refactoring Support for the Eclipse Ruby Development Tools, Diploma Thesis, HSR University of Applied Sciences Rapperswil Institute for Software.
[1] Polymorphism in object-oriented programming, http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming
 
[2] Code Refactoring Wiki, http://en.wikipedia.org/wiki/Code_refactoring.


[3] The First Workshop on Refactoring, https://netfiles.uiuc.edu/dig/RefactoringWorkshop
[2] Rene Santaolaya, Olivia G. Fragoso, Joaquín Pérez, Lorenzo Zambrano, Restructuring Conditional Code Structures Using Object Oriented Design Patterns, Lecture Notes in Computer Science.  


[4] Refactoring Tutorial for Ruby on Rails, http://www.good-tutorials.com/tutorials/ruby-on-rails/refactoring
[3] Refactoring conditional statement, http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism


[5] Martin Fowler Refactoring: Improving the Design of Existing Code
[4] Object Orientation Design, http://en.wikipedia.org/wiki/Object-oriented_design

Latest revision as of 20:45, 9 October 2009

Refactoring If Statement with Polymorphism.

Design Consideration: Reuse and Change

One of the most important consideration of Object-Orientation Software Design is 'Reuse' and 'Change' [2][4]. In terms of reuse, we mean to build the new software with the building block from the old software. The importance of 'change' is from the fact that the software is always changing to keep alive. So that how to effectively make change to the source code is critical for the software design.

The Problem of If Statement

Under the design consideration we have discussed, the problem of if statement is quite obvious: 1. the conditional relationship in function level prevent us to reuse each of the function separately. We can only reuse the whole application as a unit. 2. when we want to change the functionality of a certain function or add a new function we have to trace to every implementation code. Such change is expensive and violate the OO principle 'code to interface instead of implementation'.

Example of If statement

public class Operator
{
    string operation;

    public int Execute(int x, int y)
    {
         switch(operation)
         {
             case "Add":
                 return x + y;
             case "Subtract":
                 return x - y;
             case "Multiply":
                 return x * y;
             case "Divide":
                 return x / y;
             default:
                 throw new InvalidOperationException("Unsupported operation");
         }
    }
}

In such example of conditional statement on operator, we see that: if we want to reuse function "add" operator in the other code segment, we have to reuse whole Class operator with the value "Add". And if we want to add a new operation "Power", we need to code in the implementation of Class Operator.

Idea of Polymorphism

Facing the problem of the conditional statement, people[2] come up with refactoring method called 'Polymorphism'. The idea of Polymorphism is to replace the highly functional relationship with the subclass override procedure under abstract class. So subclass is created to encapsulate each function in the conditional statement and the conditional relation is replaced by override a common abstract class. The advantage of such idea is to separate the functionality.

Definition of Polymorphism

According to [1], Subtype polymorphism, almost universally called just polymorphism in the context of object-oriented programming, is the ability of one type, A, to appear as and be used like another type, B.

The primary usage of polymorphism in industry (object-oriented programming theory) is the ability of objects belonging to different types to respond to method, field, or property calls of the same name, each one according to an appropriate type-specific behavior. The programmer (and the program) does not have to know the exact type of the object in advance, and so the exact behavior is determined at run time.

Example of Refactoring Conditional Statement with Polymorphism

  • Before refactoring
public class Operator
{
    string operation;

    public int Execute(int x, int y)
    {
         switch(operation)
         {
             case "Add":
                 return x + y;
             case "Subtract":
                 return x - y;
             case "Multiply":
                 return x * y;
             case "Divide":
                 return x / y;
             default:
                 throw new InvalidOperationException("Unsupported operation");
         }
    }
}
  • After refactoring
public abstract class Operator
{
    public abstract int Execute(int x, int y)
}

public class Add : Operator
{
    public override int Execute(int x, int y)
    {
        return x + y;
    }
}
public class Subtract : Operator
{
    public override int Execute(int x, int y)
    {
        return x - y;
    }
}
public class Multiply: Operator
{
    public override int Execute(int x, int y)
    {
        return x * y;
    }
}
public class Divide: Operator
{
    public override int Execute(int x, int y)
    {
        return x / y;
    }
}

References

[1] Polymorphism in object-oriented programming, http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming

[2] Rene Santaolaya, Olivia G. Fragoso, Joaquín Pérez, Lorenzo Zambrano, Restructuring Conditional Code Structures Using Object Oriented Design Patterns, Lecture Notes in Computer Science.

[3] Refactoring conditional statement, http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism

[4] Object Orientation Design, http://en.wikipedia.org/wiki/Object-oriented_design