SlideShare a Scribd company logo
1 of 40
Download to read offline
Refactoring and Reflection




  Marcus Denker
  denker@iam.unibe.ch

  Universität Bern




© Marcus Denker
Roadmap




>    First lecture: Refactoring
     — Squeak as an example



>    Second Lecture: Reflection
     — About current research




© Marcus Denker
Part I: Refactoring




  Marcus Denker
  denker@iam.unibe.ch

  Universität Bern




© Marcus Denker
Overview




> Refactoring: Basics
> Refactoring in Squeak: Browser + Tools
> Refactoring Engine: Implementation
> Discussion: Reflection?




© Marcus Denker
Roadmap




> Refactoring: Basics
> Refactoring in Squeak: Browser + Tools
> Refactoring Engine: Implementation
> Discussion: Reflection?




© Marcus Denker
What is Refactoring?




>    The process of changing a software system in such a
     way that it does not alter the external behaviour of the
     code, yet improves its internal structure.

     — Fowler, et al., Refactoring, 1999.




© Marcus Denker
Typical Refactorings

Class               Method                    Attribute
add (sub)class to   add method to class       add variable to class
hierarchy
rename class        rename method             rename variable
remove class        remove method             remove variable
                    push method down          push variable down
                    push method up            pull variable up
                    add parameter to method   create accessors
                    move method to            abstract variable
                    component
                    extract code in new
                    method

© Marcus Denker
Why Refactor?

“Grow, don’t build software”
     — Fred Brooks
>    The reality:
     —    Extremely difficult to get the design “right” the first time
     —    Hard to fully understand the problem domain
     —    Hard to understand user requirements, even if the user does!
     —    Hard to know how the system will evolve in five years
     —    Original design is often inadequate
     —    System becomes brittle over time, and more difficult to change


>    Refactoring helps you to
     — Manipulate code in a safe environment (behavior preserving)
     — Recreate a situation where evolution is possible
     — Understand existing code
© Marcus Denker
Rename Method — manual steps


>    Do it yourself approach:
     — Check that no method with the new name already exists in any
       subclass or superclass.
     — Browse all the implementers (method definitions)
     — Browse all the senders (method invocations)
     — Edit and rename all implementers
     — Edit and rename all senders
     — Remove all implementers
     — Test

>    Automated refactoring is better !

© Marcus Denker
Rename Method


> Rename Method (method, new name)
> Preconditions
     — No method with the new name already exists in any subclass or
       superclass.
     — No methods with same signature as method outside the
       inheritance hierarchy of method
>    PostConditions
     — method has new name
     — relevant methods in the inheritance hierarchy have new name
     — invocations of changed method are updated to new name
>    Other Considerations
     — Typed/Dynamically Typed Languages => Scope of the renaming


© Marcus Denker
Refactoring and Metaprograming


>    Automated Refactoring is metaprograming
     — We use a program to edit programs



>    Does not need to use Reflection
     — Pure source-to-source transformation (e.g. Java)



>    Uses reflective facilities in Smalltalk
     — But… letʼs discuss that at the end



© Marcus Denker
Roadmap




> Refactoring: Basics
> Refactoring in Squeak: Browser + Tools
> Refactoring Engine: Implementation
> Discussion: Reflection?




© Marcus Denker
Refactoring in Squeak


>    No support in standard IDE
     — Example: Try to rename a method

>    Refactoring Browser
     — First Refactoring Browser (for any language)
     — Now over 10 years old

>    Installation
     — Get Squeak 3.9 (older version for 3.8, too)
     — Install Package AST
     — Install Package Refactoring Engine


© Marcus Denker
Refactoring Browser




>    Browser with menus for e.g
     —    rename
     —    Push up/down
     —    Inlining
     —    Add parameter
     —    Extraction




© Marcus Denker
SmallLint

>   Checks for common mistakes




© Marcus Denker
SmallLint Checks

>    Possible Bugs
     — Variable read before written
     — Defines #= but not #hash
     — Modifies Collection while iterating over it

> Bugs
  — Uses True/False instead of true/false
  — Variable used but not defined
> Squeak Bugs
> Unnecessary Code
> Intention Revealing

© Marcus Denker
SmallLint



> Very useful!
> Especially valuable for beginners


>    Has been integrated with SUnit
     — Call SmallLint automatically as a test

>    Tag methods where SmallLint is wrong
     — Uses Squeak 3.9 Method Pragmas




© Marcus Denker
RewriteTool

>    Pattern driven automatic editor




© Marcus Denker
RewriteTool

>    Access to full power of Refactoring Engine

>    Custom refactorings:
     — generic rewrites that the RB does not currently provide
     — bulk transformations: your project needs to change a project-
       specific pattern to a new form
     — changing layers: e.g. build a new DB layer, find and change
       17,000 references to old layer
     — migrations: e.g. between Smalltalk dialects


> Powerful but not trivial to use
> Examples: Later

© Marcus Denker
Roadmap




> Refactoring: Basics
> Refactoring in Squeak: Browser + Tools
> Refactoring Engine: Implementation
> Discussion: Reflection?


                  [Main Source] Don Roberts, John Brant, and Ralph Johnson. A
                  Refactoring Tool for Smalltalk. Theory and Practice of Object
                  Systems, vol. 3, issue 4


© Marcus Denker
Implementation Overview



 > Goal: Transformation on the Source
 > Idea: Transform into a higher level tree
   representation




© Marcus Denker
The RB Abstract Syntax Tree



                                                    RBProgramNode
>   AST: Abstract Syntax Tree                         RBDoItNode
     — Encodes the Syntax as a Tree                   RBMethodNode
                                                      RBReturnNode
     — Features:                                      RBSequenceNode
          –       Visitors                            RBValueNode
          –       Backward pointers in ParseNodes   
      RBArrayNode
                                                    
      RBAssignmentNode
          –       Encodes formatting                
      RBBlockNode
          –       Transformation (replace/add/      
      RBCascadeNode
                  delete)                           
      RBLiteralNode
          –       Pattern-directed TreeRewriter     
      RBMessageNode
                                                    
      RBOptimizedNode
          –       PrettyPrinter                     
      RBVariableNode




© Marcus Denker
A Simple AST


RBParser parseExpression: '3+4'   explore it




© Marcus Denker
A Simple Visitor


      RBProgramNodeVisitor new visitNode: tree




                               Does nothing except
                               walk through the tree




© Marcus Denker
More Complete Visitor

RBProgramNodeVisitor subclass: #TestVisitor

 instanceVariableNames: 'literals'

 classVariableNames: ''

 poolDictionaries: ''

 category: 'Compiler-AST-Visitors'

TestVisitor>>acceptLiteralNode: aLiteralNode

 literals add: aLiteralNode value.

TestVisitor>>initialize

 literals := Set new.

TestVisitor>>literals

 ^literals

       tree := RBParser parseExpression: '3 + 4'.
       (TestVisitor new visitNode: tree) literals

                                               a Set(3 4)
 © Marcus Denker
Tree Matcher


>    Implementing all Refactorings with visitors
     — Too much work
     — Too low level

>    Needed: High level specification of transformations

>    Rewrite Engine: Core of Refactoring Engine

>    No only useful for Refactoring!


© Marcus Denker
Tree Matcher




>    Describe transformation by using patterns

>    Syntax: Smalltalk + Meta Variables

>    Example:       | `@Temps |
                    ``@.Statements.
                    ``@Boolean ifTrue: [^false].
                    ^true


© Marcus Denker
Meta Variables

     All Meta Variables begin with `
       Character        Type           Example

       `                recurse into   ``@object
                                       foo
       @                list           | `@Temps |
                                       `@.statements

       .                statement      `.Statement

       #                literal        `#literal



© Marcus Denker
Example 1



 >     Search for:       ``@object not ifTrue: ``@block


     • Replace with:      ``@object ifFalse: ``@block




     • Explanation:
         – Eliminate an unnecesary not message



© Marcus Denker
Example 2

                              | `@Temps |
                              ``@.Statements.
 >     Search for:            ``@Boolean ifTrue: [^false].
                              ^true

     • Replace with:
                               | `@Temps |
                               ``@.Statements.
                               ^``@Boolean not

     • Explanation:
         – Return the value of the boolean negated instead of using a
           conditional


© Marcus Denker
Implementation: Model and
Environment

>    Model Code transformed but not installed
     — We need to be able to see refactored code without changing the
       system.
     — RBNameSpace

>    Model Classes + Methods
     — Framework duplicates Smalltalkʻs structural Reflection
     — RBClass, RBMethod

>    Model Scope to which Refactorings apply
     — RBEnvironment


© Marcus Denker
Back to Code: Pretty Printer




> Visitor: Walks the AST
> Prints out text for each node



>    Problem: How to preserve formatting?
     — AST saves formatting (whitespace, parenthesis)
     — Pretty Printer can use saved formatting information




© Marcus Denker
Contributions needed

>    Improved UI

>    Integrated Parser with Squeak NewCompiler
     — Scanner/Parser done with tool (SmaCC)
     — Easier to change / experiment


>    Integrated RoelTyper
     — Heuristical type inference


>    Better PrettyPrinter
     — Configurability
     — Better Layout

© Marcus Denker
Roadmap




> Refactoring: Basics
> Refactoring in Squeak: Browser + Tools
> Refactoring Engine: Implementation
> Discussion: Reflection?




© Marcus Denker
Reflection?


>    We change the system using itself
     — So itʻs Reflection, on some level

>    But: Letʻs look again at the definition
     — Model of itself
     — Causally connected


>    We Build our own abstraction layer
     — AST + Environment

>    This Model is not causally connected!

© Marcus Denker
State Today




© Marcus Denker
Why not this?




© Marcus Denker
We have seen...




> Refactoring: Basics
> Refatoring in Squeak: Browser + Tools
> Refactoring Engine: Implementation
> Discussion: Reflection?




© Marcus Denker
Questions?




> Refactoring: Basics
> Refatoring in Squeak: Browser + Tools
> Refactoring Engine: Implementation
> Discussion: Reflection?


                              Questions?
© Marcus Denker
License

>    http://creativecommons.org/licenses/by-sa/2.5/



                                           Attribution-ShareAlike 2.5
     You are free:
     • to copy, distribute, display, and perform the work
     • to make derivative works
     • to make commercial use of the work

     Under the following conditions:

              Attribution. You must attribute the work in the manner specified by the author or licensor.

     
              Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting
              work only under a license identical to this one.

     • For any reuse or distribution, you must make clear to others the license terms of this work.
     • Any of these conditions can be waived if you get permission from the copyright holder.

                     Your fair use and other rights are in no way affected by the above.
© Marcus Denker

More Related Content

Viewers also liked

Some thoughts on success
Some thoughts on successSome thoughts on success
Some thoughts on successRajit Desai
 
Talk: An Instrument whose Music is Ideas
Talk: An Instrument whose Music is IdeasTalk: An Instrument whose Music is Ideas
Talk: An Instrument whose Music is IdeasMarcus Denker
 
Pharo: Syntax in a Nutshell
Pharo: Syntax in a NutshellPharo: Syntax in a Nutshell
Pharo: Syntax in a NutshellMarcus Denker
 
מצגת לשירה בציבור
מצגת לשירה בציבורמצגת לשירה בציבור
מצגת לשירה בציבורmoshfeu
 

Viewers also liked (7)

Some thoughts on success
Some thoughts on successSome thoughts on success
Some thoughts on success
 
קן לציפור
קן לציפורקן לציפור
קן לציפור
 
Talk: An Instrument whose Music is Ideas
Talk: An Instrument whose Music is IdeasTalk: An Instrument whose Music is Ideas
Talk: An Instrument whose Music is Ideas
 
Pharo3 at Fosdem
Pharo3 at FosdemPharo3 at Fosdem
Pharo3 at Fosdem
 
Pharo: Syntax in a Nutshell
Pharo: Syntax in a NutshellPharo: Syntax in a Nutshell
Pharo: Syntax in a Nutshell
 
Lecture: Reflection
Lecture: ReflectionLecture: Reflection
Lecture: Reflection
 
מצגת לשירה בציבור
מצגת לשירה בציבורמצגת לשירה בציבור
מצגת לשירה בציבור
 

Similar to Refactoring

Beyond Text - Methods as Objects
Beyond Text - Methods as ObjectsBeyond Text - Methods as Objects
Beyond Text - Methods as ObjectsMarcus Denker
 
Reflection and Context
Reflection and ContextReflection and Context
Reflection and ContextMarcus Denker
 
Unanticipated Partial Behavioral Reflection
Unanticipated Partial Behavioral ReflectionUnanticipated Partial Behavioral Reflection
Unanticipated Partial Behavioral ReflectionESUG
 
Lecture: Refactoring
Lecture: RefactoringLecture: Refactoring
Lecture: RefactoringMarcus Denker
 
Unanticipated Partial Behavioral Reflection
Unanticipated Partial Behavioral ReflectionUnanticipated Partial Behavioral Reflection
Unanticipated Partial Behavioral ReflectionMarcus Denker
 
Sub-Method Reflection
Sub-Method ReflectionSub-Method Reflection
Sub-Method ReflectionMarcus Denker
 
The Reflectivity
The ReflectivityThe Reflectivity
The ReflectivityESUG
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoringkim.mens
 
Sub-method Structural and Behavioral Reflection
Sub-method Structural and Behavioral ReflectionSub-method Structural and Behavioral Reflection
Sub-method Structural and Behavioral ReflectionMarcus Denker
 
Webinar: Migrating from RDBMS to MongoDB (June 2015)
Webinar: Migrating from RDBMS to MongoDB (June 2015)Webinar: Migrating from RDBMS to MongoDB (June 2015)
Webinar: Migrating from RDBMS to MongoDB (June 2015)MongoDB
 
Talk: Practical, Pluggable Types
Talk: Practical, Pluggable TypesTalk: Practical, Pluggable Types
Talk: Practical, Pluggable TypesMarcus Denker
 
Presentation about my Research
Presentation about my ResearchPresentation about my Research
Presentation about my ResearchMarcus Denker
 
Behavioral Reflection
Behavioral ReflectionBehavioral Reflection
Behavioral ReflectionMarcus Denker
 

Similar to Refactoring (20)

Reflection
ReflectionReflection
Reflection
 
Lecture: Reflection
Lecture: ReflectionLecture: Reflection
Lecture: Reflection
 
Beyond Text - Methods as Objects
Beyond Text - Methods as ObjectsBeyond Text - Methods as Objects
Beyond Text - Methods as Objects
 
Reflectivity Demo
Reflectivity DemoReflectivity Demo
Reflectivity Demo
 
Reflection and Context
Reflection and ContextReflection and Context
Reflection and Context
 
Unanticipated Partial Behavioral Reflection
Unanticipated Partial Behavioral ReflectionUnanticipated Partial Behavioral Reflection
Unanticipated Partial Behavioral Reflection
 
Lecture: Refactoring
Lecture: RefactoringLecture: Refactoring
Lecture: Refactoring
 
08 refactoring
08 refactoring08 refactoring
08 refactoring
 
Unanticipated Partial Behavioral Reflection
Unanticipated Partial Behavioral ReflectionUnanticipated Partial Behavioral Reflection
Unanticipated Partial Behavioral Reflection
 
Stoop 305-reflective programming5
Stoop 305-reflective programming5Stoop 305-reflective programming5
Stoop 305-reflective programming5
 
Sub-Method Reflection
Sub-Method ReflectionSub-Method Reflection
Sub-Method Reflection
 
Demo: Reflectivity
Demo: ReflectivityDemo: Reflectivity
Demo: Reflectivity
 
The Reflectivity
The ReflectivityThe Reflectivity
The Reflectivity
 
Code Refactoring
Code RefactoringCode Refactoring
Code Refactoring
 
Sub-method Structural and Behavioral Reflection
Sub-method Structural and Behavioral ReflectionSub-method Structural and Behavioral Reflection
Sub-method Structural and Behavioral Reflection
 
Webinar: Migrating from RDBMS to MongoDB (June 2015)
Webinar: Migrating from RDBMS to MongoDB (June 2015)Webinar: Migrating from RDBMS to MongoDB (June 2015)
Webinar: Migrating from RDBMS to MongoDB (June 2015)
 
Talk: Practical, Pluggable Types
Talk: Practical, Pluggable TypesTalk: Practical, Pluggable Types
Talk: Practical, Pluggable Types
 
Presentation about my Research
Presentation about my ResearchPresentation about my Research
Presentation about my Research
 
Unstuck
UnstuckUnstuck
Unstuck
 
Behavioral Reflection
Behavioral ReflectionBehavioral Reflection
Behavioral Reflection
 

More from Marcus Denker

ConstantBlocks in Pharo11
ConstantBlocks in Pharo11ConstantBlocks in Pharo11
ConstantBlocks in Pharo11Marcus Denker
 
First Class Variables as AST Annotations
First Class Variables as AST AnnotationsFirst Class Variables as AST Annotations
First Class Variables as AST AnnotationsMarcus Denker
 
Supporting Pharo / Getting Pharo Support
Supporting Pharo / Getting Pharo SupportSupporting Pharo / Getting Pharo Support
Supporting Pharo / Getting Pharo SupportMarcus Denker
 
Lecture: "Advanced Reflection: MetaLinks"
Lecture: "Advanced Reflection: MetaLinks"Lecture: "Advanced Reflection: MetaLinks"
Lecture: "Advanced Reflection: MetaLinks"Marcus Denker
 
thisContext in the Debugger
thisContext in the DebuggerthisContext in the Debugger
thisContext in the DebuggerMarcus Denker
 
Lecture. Advanced Reflection: MetaLinks
Lecture. Advanced Reflection: MetaLinksLecture. Advanced Reflection: MetaLinks
Lecture. Advanced Reflection: MetaLinksMarcus Denker
 
Improving code completion for Pharo
Improving code completion for PharoImproving code completion for Pharo
Improving code completion for PharoMarcus Denker
 
VUB Brussels Lecture 2019: Advanced Reflection: MetaLinks
VUB Brussels Lecture 2019: Advanced Reflection: MetaLinksVUB Brussels Lecture 2019: Advanced Reflection: MetaLinks
VUB Brussels Lecture 2019: Advanced Reflection: MetaLinksMarcus Denker
 
Lecture: Advanced Reflection. MetaLinks
Lecture: Advanced Reflection. MetaLinksLecture: Advanced Reflection. MetaLinks
Lecture: Advanced Reflection. MetaLinksMarcus Denker
 
Open-Source: An Infinite Game
Open-Source: An Infinite GameOpen-Source: An Infinite Game
Open-Source: An Infinite GameMarcus Denker
 
PharoTechTalk: Contributing to Pharo
PharoTechTalk: Contributing to PharoPharoTechTalk: Contributing to Pharo
PharoTechTalk: Contributing to PharoMarcus Denker
 
Feedback Loops in Practice
Feedback Loops in PracticeFeedback Loops in Practice
Feedback Loops in PracticeMarcus Denker
 

More from Marcus Denker (20)

Soil And Pharo
Soil And PharoSoil And Pharo
Soil And Pharo
 
ConstantBlocks in Pharo11
ConstantBlocks in Pharo11ConstantBlocks in Pharo11
ConstantBlocks in Pharo11
 
Demo: Improved DoIt
Demo: Improved DoItDemo: Improved DoIt
Demo: Improved DoIt
 
First Class Variables as AST Annotations
First Class Variables as AST AnnotationsFirst Class Variables as AST Annotations
First Class Variables as AST Annotations
 
Supporting Pharo / Getting Pharo Support
Supporting Pharo / Getting Pharo SupportSupporting Pharo / Getting Pharo Support
Supporting Pharo / Getting Pharo Support
 
Lecture: "Advanced Reflection: MetaLinks"
Lecture: "Advanced Reflection: MetaLinks"Lecture: "Advanced Reflection: MetaLinks"
Lecture: "Advanced Reflection: MetaLinks"
 
thisContext in the Debugger
thisContext in the DebuggerthisContext in the Debugger
thisContext in the Debugger
 
Variables in Pharo
Variables in PharoVariables in Pharo
Variables in Pharo
 
Lecture. Advanced Reflection: MetaLinks
Lecture. Advanced Reflection: MetaLinksLecture. Advanced Reflection: MetaLinks
Lecture. Advanced Reflection: MetaLinks
 
Improving code completion for Pharo
Improving code completion for PharoImproving code completion for Pharo
Improving code completion for Pharo
 
VUB Brussels Lecture 2019: Advanced Reflection: MetaLinks
VUB Brussels Lecture 2019: Advanced Reflection: MetaLinksVUB Brussels Lecture 2019: Advanced Reflection: MetaLinks
VUB Brussels Lecture 2019: Advanced Reflection: MetaLinks
 
Slot Composition
Slot CompositionSlot Composition
Slot Composition
 
Lecture: Advanced Reflection. MetaLinks
Lecture: Advanced Reflection. MetaLinksLecture: Advanced Reflection. MetaLinks
Lecture: Advanced Reflection. MetaLinks
 
PHARO IOT
PHARO IOTPHARO IOT
PHARO IOT
 
Open-Source: An Infinite Game
Open-Source: An Infinite GameOpen-Source: An Infinite Game
Open-Source: An Infinite Game
 
Lecture: MetaLinks
Lecture: MetaLinksLecture: MetaLinks
Lecture: MetaLinks
 
PharoTechTalk: Contributing to Pharo
PharoTechTalk: Contributing to PharoPharoTechTalk: Contributing to Pharo
PharoTechTalk: Contributing to Pharo
 
Feedback Loops in Practice
Feedback Loops in PracticeFeedback Loops in Practice
Feedback Loops in Practice
 
Pharo6 - ESUG17
Pharo6 - ESUG17Pharo6 - ESUG17
Pharo6 - ESUG17
 
Pharo6
Pharo6Pharo6
Pharo6
 

Recently uploaded

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 

Recently uploaded (20)

Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 

Refactoring

  • 1. Refactoring and Reflection Marcus Denker denker@iam.unibe.ch Universität Bern © Marcus Denker
  • 2. Roadmap > First lecture: Refactoring — Squeak as an example > Second Lecture: Reflection — About current research © Marcus Denker
  • 3. Part I: Refactoring Marcus Denker denker@iam.unibe.ch Universität Bern © Marcus Denker
  • 4. Overview > Refactoring: Basics > Refactoring in Squeak: Browser + Tools > Refactoring Engine: Implementation > Discussion: Reflection? © Marcus Denker
  • 5. Roadmap > Refactoring: Basics > Refactoring in Squeak: Browser + Tools > Refactoring Engine: Implementation > Discussion: Reflection? © Marcus Denker
  • 6. What is Refactoring? > The process of changing a software system in such a way that it does not alter the external behaviour of the code, yet improves its internal structure. — Fowler, et al., Refactoring, 1999. © Marcus Denker
  • 7. Typical Refactorings Class Method Attribute add (sub)class to add method to class add variable to class hierarchy rename class rename method rename variable remove class remove method remove variable push method down push variable down push method up pull variable up add parameter to method create accessors move method to abstract variable component extract code in new method © Marcus Denker
  • 8. Why Refactor? “Grow, don’t build software” — Fred Brooks > The reality: — Extremely difficult to get the design “right” the first time — Hard to fully understand the problem domain — Hard to understand user requirements, even if the user does! — Hard to know how the system will evolve in five years — Original design is often inadequate — System becomes brittle over time, and more difficult to change > Refactoring helps you to — Manipulate code in a safe environment (behavior preserving) — Recreate a situation where evolution is possible — Understand existing code © Marcus Denker
  • 9. Rename Method — manual steps > Do it yourself approach: — Check that no method with the new name already exists in any subclass or superclass. — Browse all the implementers (method definitions) — Browse all the senders (method invocations) — Edit and rename all implementers — Edit and rename all senders — Remove all implementers — Test > Automated refactoring is better ! © Marcus Denker
  • 10. Rename Method > Rename Method (method, new name) > Preconditions — No method with the new name already exists in any subclass or superclass. — No methods with same signature as method outside the inheritance hierarchy of method > PostConditions — method has new name — relevant methods in the inheritance hierarchy have new name — invocations of changed method are updated to new name > Other Considerations — Typed/Dynamically Typed Languages => Scope of the renaming © Marcus Denker
  • 11. Refactoring and Metaprograming > Automated Refactoring is metaprograming — We use a program to edit programs > Does not need to use Reflection — Pure source-to-source transformation (e.g. Java) > Uses reflective facilities in Smalltalk — But… letʼs discuss that at the end © Marcus Denker
  • 12. Roadmap > Refactoring: Basics > Refactoring in Squeak: Browser + Tools > Refactoring Engine: Implementation > Discussion: Reflection? © Marcus Denker
  • 13. Refactoring in Squeak > No support in standard IDE — Example: Try to rename a method > Refactoring Browser — First Refactoring Browser (for any language) — Now over 10 years old > Installation — Get Squeak 3.9 (older version for 3.8, too) — Install Package AST — Install Package Refactoring Engine © Marcus Denker
  • 14. Refactoring Browser > Browser with menus for e.g — rename — Push up/down — Inlining — Add parameter — Extraction © Marcus Denker
  • 15. SmallLint > Checks for common mistakes © Marcus Denker
  • 16. SmallLint Checks > Possible Bugs — Variable read before written — Defines #= but not #hash — Modifies Collection while iterating over it > Bugs — Uses True/False instead of true/false — Variable used but not defined > Squeak Bugs > Unnecessary Code > Intention Revealing © Marcus Denker
  • 17. SmallLint > Very useful! > Especially valuable for beginners > Has been integrated with SUnit — Call SmallLint automatically as a test > Tag methods where SmallLint is wrong — Uses Squeak 3.9 Method Pragmas © Marcus Denker
  • 18. RewriteTool > Pattern driven automatic editor © Marcus Denker
  • 19. RewriteTool > Access to full power of Refactoring Engine > Custom refactorings: — generic rewrites that the RB does not currently provide — bulk transformations: your project needs to change a project- specific pattern to a new form — changing layers: e.g. build a new DB layer, find and change 17,000 references to old layer — migrations: e.g. between Smalltalk dialects > Powerful but not trivial to use > Examples: Later © Marcus Denker
  • 20. Roadmap > Refactoring: Basics > Refactoring in Squeak: Browser + Tools > Refactoring Engine: Implementation > Discussion: Reflection? [Main Source] Don Roberts, John Brant, and Ralph Johnson. A Refactoring Tool for Smalltalk. Theory and Practice of Object Systems, vol. 3, issue 4 © Marcus Denker
  • 21. Implementation Overview > Goal: Transformation on the Source > Idea: Transform into a higher level tree representation © Marcus Denker
  • 22. The RB Abstract Syntax Tree RBProgramNode > AST: Abstract Syntax Tree RBDoItNode — Encodes the Syntax as a Tree RBMethodNode RBReturnNode — Features: RBSequenceNode – Visitors RBValueNode – Backward pointers in ParseNodes RBArrayNode RBAssignmentNode – Encodes formatting RBBlockNode – Transformation (replace/add/ RBCascadeNode delete) RBLiteralNode – Pattern-directed TreeRewriter RBMessageNode RBOptimizedNode – PrettyPrinter RBVariableNode © Marcus Denker
  • 23. A Simple AST RBParser parseExpression: '3+4' explore it © Marcus Denker
  • 24. A Simple Visitor RBProgramNodeVisitor new visitNode: tree Does nothing except walk through the tree © Marcus Denker
  • 25. More Complete Visitor RBProgramNodeVisitor subclass: #TestVisitor instanceVariableNames: 'literals' classVariableNames: '' poolDictionaries: '' category: 'Compiler-AST-Visitors' TestVisitor>>acceptLiteralNode: aLiteralNode literals add: aLiteralNode value. TestVisitor>>initialize literals := Set new. TestVisitor>>literals ^literals tree := RBParser parseExpression: '3 + 4'. (TestVisitor new visitNode: tree) literals a Set(3 4) © Marcus Denker
  • 26. Tree Matcher > Implementing all Refactorings with visitors — Too much work — Too low level > Needed: High level specification of transformations > Rewrite Engine: Core of Refactoring Engine > No only useful for Refactoring! © Marcus Denker
  • 27. Tree Matcher > Describe transformation by using patterns > Syntax: Smalltalk + Meta Variables > Example: | `@Temps | ``@.Statements. ``@Boolean ifTrue: [^false]. ^true © Marcus Denker
  • 28. Meta Variables All Meta Variables begin with ` Character Type Example ` recurse into ``@object foo @ list | `@Temps | `@.statements . statement `.Statement # literal `#literal © Marcus Denker
  • 29. Example 1 > Search for: ``@object not ifTrue: ``@block • Replace with: ``@object ifFalse: ``@block • Explanation: – Eliminate an unnecesary not message © Marcus Denker
  • 30. Example 2 | `@Temps | ``@.Statements. > Search for: ``@Boolean ifTrue: [^false]. ^true • Replace with: | `@Temps | ``@.Statements. ^``@Boolean not • Explanation: – Return the value of the boolean negated instead of using a conditional © Marcus Denker
  • 31. Implementation: Model and Environment > Model Code transformed but not installed — We need to be able to see refactored code without changing the system. — RBNameSpace > Model Classes + Methods — Framework duplicates Smalltalkʻs structural Reflection — RBClass, RBMethod > Model Scope to which Refactorings apply — RBEnvironment © Marcus Denker
  • 32. Back to Code: Pretty Printer > Visitor: Walks the AST > Prints out text for each node > Problem: How to preserve formatting? — AST saves formatting (whitespace, parenthesis) — Pretty Printer can use saved formatting information © Marcus Denker
  • 33. Contributions needed > Improved UI > Integrated Parser with Squeak NewCompiler — Scanner/Parser done with tool (SmaCC) — Easier to change / experiment > Integrated RoelTyper — Heuristical type inference > Better PrettyPrinter — Configurability — Better Layout © Marcus Denker
  • 34. Roadmap > Refactoring: Basics > Refactoring in Squeak: Browser + Tools > Refactoring Engine: Implementation > Discussion: Reflection? © Marcus Denker
  • 35. Reflection? > We change the system using itself — So itʻs Reflection, on some level > But: Letʻs look again at the definition — Model of itself — Causally connected > We Build our own abstraction layer — AST + Environment > This Model is not causally connected! © Marcus Denker
  • 37. Why not this? © Marcus Denker
  • 38. We have seen... > Refactoring: Basics > Refatoring in Squeak: Browser + Tools > Refactoring Engine: Implementation > Discussion: Reflection? © Marcus Denker
  • 39. Questions? > Refactoring: Basics > Refatoring in Squeak: Browser + Tools > Refactoring Engine: Implementation > Discussion: Reflection? Questions? © Marcus Denker
  • 40. License > http://creativecommons.org/licenses/by-sa/2.5/ Attribution-ShareAlike 2.5 You are free: • to copy, distribute, display, and perform the work • to make derivative works • to make commercial use of the work Under the following conditions: Attribution. You must attribute the work in the manner specified by the author or licensor. Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under a license identical to this one. • For any reuse or distribution, you must make clear to others the license terms of this work. • Any of these conditions can be waived if you get permission from the copyright holder. Your fair use and other rights are in no way affected by the above. © Marcus Denker