SlideShare a Scribd company logo
1 of 53
Dependency Breaking Techniques
            Working Effectively with LegacyCode
                                             Ver 1.0




               아키텍트를 꿈꾸는 사람들 cafe.naver.com/architect1
                            현수명 soomong.net
                                                #soomong
before           after




24   dependency breaking techniques
1. Adapt Parameter



                                        Interface A’

   Method (   A   ){
     ...
   }



                         Concrete A’                   Concrete A’
                       for production                    for test
When to use?
 - parameter is difficult to test.
 - can’t use Extract Interface on a parameter’s class.
2. Break Out Method Object


  Class


     longMethod A() {
       …
       …
       …                New Class A
     }

                          longMethod () {
                            …
                            …
                            …
                          }
When to use?
- method is too large

- use instance data and methods
3. Definition Completion


                       Definition for
       Definition          Test




     Concrete Class    Concrete Class
When to use?
 - language supplies that can declare a type in on place and
define it another.

- to break dependencies in procedural language like C.
4. Encapsulate Global References



    Class               New Class A


     Global reference      Global reference
When to use?
- to separate dependencies on global references.
5. Expose Static Method


                          Class


    Class
                             Static Method () {
                               …
        Method () {          }
          …
        }
When to use?
- trying to test code that can’t be instantiated.
6. Extract and Override Call

Class               Class               Class for test


   Method ( ) {        Method ( ) {
    …                   …

            logic           call A();
        …                   …
   }                   }
                                         @Override

                       Method A ( ) {      Method A( ) {
                         logic               test logic
                       }                   }
When to use?
- trying to test only single method call.
7. Extract and Override Factory Method


Class                Class                   Class for test


constructor( ) {      constructor( ) {
  …                     …
  object = new A()      object = call A();
  …                     …
}                     }

                                             @Override

                      Factory method A(){    Factory method A(){
                        return new A()         …
                      }                      }
When to use?
- trying to test code that creates objects in constructor.
8. Extract and Override Getter

Class                Class                     Class for test


constructor( ) {      constructor( ) {
  …                     …
  object = New A()      object = null;
  …                     …
}                     }

                                                @Override
object
                      Getter Method getA(){     Getter Method getA(){
                        if A is null              …
           object           return new A();     }
                        return A;
                      }


                      getA()
                                   getA()




                                              Lazy initialize
When to use?
  - trying to test code that creates objects in constructor
  - language doesn’t support virtual function call in a derived class
from base class’s constructor
9. Extract Implementer


                Duplicated Class

                 Method A() {      Interface
Class              …
                 }                  virtual Method A()
 Method A() {
   …             Method B() {       virtual Method B()
 }                 …
                 }
 Method B() {
   …
 }
When to use?
- hard to naming the interface
10. Extract Interface


                Interface

                 virtual Method A()   Concrete Class
Class
                                       Method A() {
                 virtual Method B()
 Method A() {                            …
   …                                   }
 }

                                       Method A() {
 Method B() {                            …
   …                                   }
 }
When to use?
- trying to test code that break dependency
11. Introduce Instance Delegator

Class                    Class                     Class for test

Static Method A( ) {      Static Method A( ) {
  …                         …
}                         }

                                                    @Override
                           Method A’(){              Method A’(){
 Class.A()
                             A();                      …
                           }                         }
             Class.A()


                         instance.A’()


                                   instance.A’()
When to use?
- static method has logic that hard to test

- it’s weird

- 더 큰 리팩토링의 시작
12. Introduce Static Setter

Class                           Class                           Class for test

Static instance                 Static instance

private constructor( ) {        protected constructor( ) {
}                               }




Static Method getInst(){        Static Method getInst(){
  if instance is null             if instance is null
      instance = new Class();         instance = new Class();
  return instance;                return instance;
}                               }

                                                                @Override

                                Method setInstance(…) {         Method setInstance(…) {
                                  instance = …                    test logic
                                                                }
                                }
When to use?
 - Singleton test

 - Protected constructor = can subclassing = 구리다

 - singleton을 코드로 강제하는 것보다는 팀원들이
모두 이해하는게 더 중요하다?
13. Link Substitution


                        Global reference for test
                          Call history
                          Value history



    Method A() {
      …
    }
                        Method A() {
                          record call history
                          record value history
                          …
                        }
When to use?
- to break dependencies in procedural language like C.
14. Parameterize Constructor

Class                 Class                Class for test


constructor( ) {      constructor( ) {
  …                     this( new A() );
  object = new A();   }
  …
}




                      constructor( A ) {   constructor( A ) {
                        …                    …
                        object = A;          object = test;
                        …                    …
                      }                    }
When to use?
- to separate the object that created in constructor.

has dependencies on parameter’s class.
but it’s a small concern.
15. Parameterize Method


    Class                 Class


    Method( ) {           Method( A ) {
      …                     …
      object = new A();     object = A;
      …                     …
    }                     }
When to use?
 -to separate the object that created in method.

dependency issue?
Extract and Override Factory Method is alternative way.
16. Primitivize Parameter

Class          Class                     TestClass


Method ( ) {   Method ( ) {              TEST( ) {
 …               …                         …
    logic        call free function();     call free function();
    …            …                       }
}              }




                free function( ) {
                    logic

                }
When to use?
- work to get a class under test is too large.

- what the…
17. Pull Up Feature
                                  New Abstract Class

                                        Method A( ) {
                                          …
                                        }

                                        abstract Method B
                                        abstract Method C




  Class
     Method A( ) {
       …             Class                              Class for test
     }
                        Method B( ) {                       TEST( ) {
     Method B( ) {        …                                   CHECK(A());
       …                }                                   }
     }
                       Method C( ) {
     Method C( ) {       …
       …               }
     }
When to use?
- to test just one method that clustered with other methods.
18. Push Down Dependency

                     Abstract Class
Class
                       Method A( ) {
 Method A( ) {           …
   …                   }
 }

                       Method B( ) {
 Method B( ) {           …
   …                   }
 }
                      abstract drawUI()

Method drawUI( ) {
  …
}
                     New Concrete Class    Concrete Class for test




                      Method drawUI( ) {    Method drawUI( ) {
                        …                     // do nothing
                      }                     }
When to use?
 - dependencies are pervasive like drawing UI.
19. Replace Function with Function Pointer



   Method main( ) {   Method main( ) {
     …                  …
     A();               *pointer
     …                  …
   }                  }
                                         *Method testA( ) {
                                           test logic
                                         }
   Method A( ) {
     …
   }                  *Method A( ) {
                        …
                      }
When to use?
- to break dependencies in procedural language like C.

Different points of view
- horribly unsafe VS useful tool
20. Replace Global Reference with Getter



Class                  Class                    Class for test

 Global references A     Global references A



A                       getA

                A                     getA
                                                @Override
                       Getter Method getA() {   Getter Method getA() {
                         return A;                …
                       }                        }
When to use?
- separate dependencies on global references
21. Subclass and Override Method

  Class                 Class



  private Method A(){   protected Method A(){
    …                     …
  }                     }




                                            subClass for test


                                                @Override

                                                protected Method A(){
                                                  …
                                                }
When to use?
 - break dependencies in object-oriented language.

Many of the other dependency-breaking techniques
are variations on it.
22. Supersede Instance Variable

 Class              Class                    Class for test

 variable           variable

 constructor( ) {   constructor( ) {
   variable;          variable;
 }                  }


                                             @Override
                    supersedeVariable(A) {   supersedeVariable(A) {
                      variable = A;            …
                    }                        }
When to use?
 - separate objects that created in constructor.
 - language disallows overrides of virtual function calls
in constructors.


Use uncommon prefix : supersede

개발자들이 잘못 사용할지도 모르니
잘 모르는 uncommon 한 단어를 prefix 로 사용하자??
23. Template Redefinition


                                        generics
   Method (   A   ){
     ...
   }



                       Concrete type           Concrete type
                       for production             for test
When to use?
 - language supplies generics and a way of aliasing types.
24. Text Redefinition

                        TestClass


      Class                Class

                           def Method A()
      def Method A()       end
        …
        logic
        …
      end




                        TEST( ) {
                          …
                          test Class
                        }
When to use?
- break dependencies in interpreted language like Ruby.
전체 정리하면서 느낀 점

- 억지스러운 면이 자주 보인다.

- dependency 는 깨질지 몰라도 Readability는 더 낮아진다.

- 코드가 잘못 사용될 수 있으니 개발자가 더 주의 깊게 살펴봐야 한다.

- 아무래도 LegacyCode 와의 싸움이 힘겹긴 한가보다. 이해하자.

- 억지스럽고 지저분한 방법일지라도 대안이 없다면
  그게 바로 최선의 방법이다.

- 원문이 훨씬 보기 쉽다. (번역 X)
Reference



            레거시코드 활용 전략
            http://www.yes24.com/24/goods/3092523
감사합니다

More Related Content

What's hot

Juniper Srx quickstart-12.1r3
Juniper Srx quickstart-12.1r3Juniper Srx quickstart-12.1r3
Juniper Srx quickstart-12.1r3
Mohamed Al-Natour
 
Access control list 2
Access control list 2Access control list 2
Access control list 2
Kishore Kumar
 
Object-Oriented Programming with C#
Object-Oriented Programming with C#Object-Oriented Programming with C#
Object-Oriented Programming with C#
Svetlin Nakov
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
Doncho Minkov
 
Tratamento de exceções
Tratamento de exceçõesTratamento de exceções
Tratamento de exceções
Alvaro Oliveira
 

What's hot (20)

Juniper Srx quickstart-12.1r3
Juniper Srx quickstart-12.1r3Juniper Srx quickstart-12.1r3
Juniper Srx quickstart-12.1r3
 
Real Life Clean Architecture
Real Life Clean ArchitectureReal Life Clean Architecture
Real Life Clean Architecture
 
Java 8 Default Methods
Java 8 Default MethodsJava 8 Default Methods
Java 8 Default Methods
 
Inheritance
InheritanceInheritance
Inheritance
 
Hacking Lab con ProxMox e Metasploitable
Hacking Lab con ProxMox e MetasploitableHacking Lab con ProxMox e Metasploitable
Hacking Lab con ProxMox e Metasploitable
 
Linux Tutorial For Beginners | Linux Administration Tutorial | Linux Commands...
Linux Tutorial For Beginners | Linux Administration Tutorial | Linux Commands...Linux Tutorial For Beginners | Linux Administration Tutorial | Linux Commands...
Linux Tutorial For Beginners | Linux Administration Tutorial | Linux Commands...
 
Access control list 2
Access control list 2Access control list 2
Access control list 2
 
Guaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in RustGuaranteeing Memory Safety in Rust
Guaranteeing Memory Safety in Rust
 
Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism Java
 
Router commands
Router commandsRouter commands
Router commands
 
Inheritance and its types In Java
Inheritance and its types In JavaInheritance and its types In Java
Inheritance and its types In Java
 
VMware Disaster Recovery Solution Presentation EN (1).pptx
VMware Disaster Recovery Solution Presentation EN (1).pptxVMware Disaster Recovery Solution Presentation EN (1).pptx
VMware Disaster Recovery Solution Presentation EN (1).pptx
 
Object-Oriented Programming with C#
Object-Oriented Programming with C#Object-Oriented Programming with C#
Object-Oriented Programming with C#
 
Object-oriented Programming-with C#
Object-oriented Programming-with C#Object-oriented Programming-with C#
Object-oriented Programming-with C#
 
Java 8 - interfaces
Java 8 - interfacesJava 8 - interfaces
Java 8 - interfaces
 
Clean Architecture
Clean ArchitectureClean Architecture
Clean Architecture
 
Tratamento de exceções
Tratamento de exceçõesTratamento de exceções
Tratamento de exceções
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 
Java: Encapsulamento e modificadores de acesso
Java: Encapsulamento e modificadores de acessoJava: Encapsulamento e modificadores de acesso
Java: Encapsulamento e modificadores de acesso
 
Java Interview Questions and Answers | Spring and Hibernate Interview Questio...
Java Interview Questions and Answers | Spring and Hibernate Interview Questio...Java Interview Questions and Answers | Spring and Hibernate Interview Questio...
Java Interview Questions and Answers | Spring and Hibernate Interview Questio...
 

Viewers also liked

연결자가 필요해!
연결자가 필요해!연결자가 필요해!
연결자가 필요해!
Nasol Kim
 
Erlang을 이용한 swap 서버
Erlang을 이용한 swap 서버Erlang을 이용한 swap 서버
Erlang을 이용한 swap 서버
Jaejin Yun
 
나는 버그를 잡는다.
나는 버그를 잡는다.나는 버그를 잡는다.
나는 버그를 잡는다.
Nasol Kim
 

Viewers also liked (20)

Scalable Web Architecture and Distributed Systems
Scalable Web Architecture and Distributed SystemsScalable Web Architecture and Distributed Systems
Scalable Web Architecture and Distributed Systems
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
 
Erlang
ErlangErlang
Erlang
 
연결자가 필요해!
연결자가 필요해!연결자가 필요해!
연결자가 필요해!
 
Erlang을 이용한 swap 서버
Erlang을 이용한 swap 서버Erlang을 이용한 swap 서버
Erlang을 이용한 swap 서버
 
이산수학 Ch.5
이산수학 Ch.5이산수학 Ch.5
이산수학 Ch.5
 
HTML5 & CSS3 - Video,Audio
HTML5 & CSS3 - Video,AudioHTML5 & CSS3 - Video,Audio
HTML5 & CSS3 - Video,Audio
 
MapReduce
MapReduceMapReduce
MapReduce
 
Hybrid app
Hybrid appHybrid app
Hybrid app
 
The Art of Computer Programming 1.2.5
The Art of Computer Programming 1.2.5The Art of Computer Programming 1.2.5
The Art of Computer Programming 1.2.5
 
[페차쿠차] 배움의 기술
[페차쿠차] 배움의 기술[페차쿠차] 배움의 기술
[페차쿠차] 배움의 기술
 
The Art of Computer Programming 2.3.2 Tree
The Art of Computer Programming 2.3.2 TreeThe Art of Computer Programming 2.3.2 Tree
The Art of Computer Programming 2.3.2 Tree
 
Clojure Chapter.6
Clojure Chapter.6Clojure Chapter.6
Clojure Chapter.6
 
xUnitTestPattern/chapter8
xUnitTestPattern/chapter8xUnitTestPattern/chapter8
xUnitTestPattern/chapter8
 
The Art of Computer Programming 2.4 다중연결구조
The Art of Computer Programming 2.4 다중연결구조The Art of Computer Programming 2.4 다중연결구조
The Art of Computer Programming 2.4 다중연결구조
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
프로그램은 왜 실패하는가?
프로그램은 왜 실패하는가?프로그램은 왜 실패하는가?
프로그램은 왜 실패하는가?
 
나는 버그를 잡는다.
나는 버그를 잡는다.나는 버그를 잡는다.
나는 버그를 잡는다.
 
실전 윈도우 디버깅. Ch3. 디버거 해부
실전 윈도우 디버깅. Ch3. 디버거 해부실전 윈도우 디버깅. Ch3. 디버거 해부
실전 윈도우 디버깅. Ch3. 디버거 해부
 
프로그래머의 길,멘토에게 묻다 2장
프로그래머의 길,멘토에게 묻다 2장프로그래머의 길,멘토에게 묻다 2장
프로그래머의 길,멘토에게 묻다 2장
 

Similar to Dependency Breaking Techniques

Automating Interaction Testing with UML Sequence Diagrams: Where TDD and UML ...
Automating Interaction Testing with UML Sequence Diagrams: Where TDD and UML ...Automating Interaction Testing with UML Sequence Diagrams: Where TDD and UML ...
Automating Interaction Testing with UML Sequence Diagrams: Where TDD and UML ...
João Pascoal Faria
 
Metaprogramming Techniques In Groovy And Grails
Metaprogramming Techniques In Groovy And GrailsMetaprogramming Techniques In Groovy And Grails
Metaprogramming Techniques In Groovy And Grails
zenMonkey
 
Java concepts and questions
Java concepts and questionsJava concepts and questions
Java concepts and questions
Farag Zakaria
 

Similar to Dependency Breaking Techniques (20)

Java OO Revisited
Java OO RevisitedJava OO Revisited
Java OO Revisited
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java Reflection Concept and Working
Java Reflection Concept and WorkingJava Reflection Concept and Working
Java Reflection Concept and Working
 
8 polymorphism
8 polymorphism8 polymorphism
8 polymorphism
 
Automating Interaction Testing with UML Sequence Diagrams: Where TDD and UML ...
Automating Interaction Testing with UML Sequence Diagrams: Where TDD and UML ...Automating Interaction Testing with UML Sequence Diagrams: Where TDD and UML ...
Automating Interaction Testing with UML Sequence Diagrams: Where TDD and UML ...
 
CHAPTER 3 part2.pdf
CHAPTER 3 part2.pdfCHAPTER 3 part2.pdf
CHAPTER 3 part2.pdf
 
11slide.ppt
11slide.ppt11slide.ppt
11slide.ppt
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Metaprogramming Techniques In Groovy And Grails
Metaprogramming Techniques In Groovy And GrailsMetaprogramming Techniques In Groovy And Grails
Metaprogramming Techniques In Groovy And Grails
 
A (too) Short Introduction to Scala
A (too) Short Introduction to ScalaA (too) Short Introduction to Scala
A (too) Short Introduction to Scala
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
 
Java concepts and questions
Java concepts and questionsJava concepts and questions
Java concepts and questions
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Interface
InterfaceInterface
Interface
 
Java Concepts
Java ConceptsJava Concepts
Java Concepts
 
Test Engine
Test EngineTest Engine
Test Engine
 
Refactoring Chapter11
Refactoring Chapter11Refactoring Chapter11
Refactoring Chapter11
 
Oops
OopsOops
Oops
 

More from hyun soomyung (7)

아꿈사 매니저소개
아꿈사 매니저소개아꿈사 매니저소개
아꿈사 매니저소개
 
MongoDB
MongoDBMongoDB
MongoDB
 
Design Pattern - Multithread Ch10
Design Pattern - Multithread Ch10Design Pattern - Multithread Ch10
Design Pattern - Multithread Ch10
 
The Art of Computer Programming 1.3.2 MIXAL
The Art of Computer Programming 1.3.2 MIXALThe Art of Computer Programming 1.3.2 MIXAL
The Art of Computer Programming 1.3.2 MIXAL
 
스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)
스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)
스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)
 
예제로 보는 Pattern 연상법
예제로 보는 Pattern 연상법예제로 보는 Pattern 연상법
예제로 보는 Pattern 연상법
 
5장 그래프의 비밀 (Programming Game AI by Example)
5장 그래프의 비밀 (Programming Game AI by Example)5장 그래프의 비밀 (Programming Game AI by Example)
5장 그래프의 비밀 (Programming Game AI by Example)
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

Dependency Breaking Techniques

  • 1. Dependency Breaking Techniques Working Effectively with LegacyCode Ver 1.0 아키텍트를 꿈꾸는 사람들 cafe.naver.com/architect1 현수명 soomong.net #soomong
  • 2. before after 24 dependency breaking techniques
  • 3. 1. Adapt Parameter Interface A’ Method ( A ){ ... } Concrete A’ Concrete A’ for production for test
  • 4. When to use? - parameter is difficult to test. - can’t use Extract Interface on a parameter’s class.
  • 5. 2. Break Out Method Object Class longMethod A() { … … … New Class A } longMethod () { … … … }
  • 6. When to use? - method is too large - use instance data and methods
  • 7. 3. Definition Completion Definition for Definition Test Concrete Class Concrete Class
  • 8. When to use? - language supplies that can declare a type in on place and define it another. - to break dependencies in procedural language like C.
  • 9. 4. Encapsulate Global References Class New Class A Global reference Global reference
  • 10. When to use? - to separate dependencies on global references.
  • 11. 5. Expose Static Method Class Class Static Method () { … Method () { } … }
  • 12. When to use? - trying to test code that can’t be instantiated.
  • 13. 6. Extract and Override Call Class Class Class for test Method ( ) { Method ( ) { … … logic call A(); … … } } @Override Method A ( ) { Method A( ) { logic test logic } }
  • 14. When to use? - trying to test only single method call.
  • 15. 7. Extract and Override Factory Method Class Class Class for test constructor( ) { constructor( ) { … … object = new A() object = call A(); … … } } @Override Factory method A(){ Factory method A(){ return new A() … } }
  • 16. When to use? - trying to test code that creates objects in constructor.
  • 17. 8. Extract and Override Getter Class Class Class for test constructor( ) { constructor( ) { … … object = New A() object = null; … … } } @Override object Getter Method getA(){ Getter Method getA(){ if A is null … object return new A(); } return A; } getA() getA() Lazy initialize
  • 18. When to use? - trying to test code that creates objects in constructor - language doesn’t support virtual function call in a derived class from base class’s constructor
  • 19. 9. Extract Implementer Duplicated Class Method A() { Interface Class … } virtual Method A() Method A() { … Method B() { virtual Method B() } … } Method B() { … }
  • 20. When to use? - hard to naming the interface
  • 21. 10. Extract Interface Interface virtual Method A() Concrete Class Class Method A() { virtual Method B() Method A() { … … } } Method A() { Method B() { … … } }
  • 22. When to use? - trying to test code that break dependency
  • 23. 11. Introduce Instance Delegator Class Class Class for test Static Method A( ) { Static Method A( ) { … … } } @Override Method A’(){ Method A’(){ Class.A() A(); … } } Class.A() instance.A’() instance.A’()
  • 24. When to use? - static method has logic that hard to test - it’s weird - 더 큰 리팩토링의 시작
  • 25. 12. Introduce Static Setter Class Class Class for test Static instance Static instance private constructor( ) { protected constructor( ) { } } Static Method getInst(){ Static Method getInst(){ if instance is null if instance is null instance = new Class(); instance = new Class(); return instance; return instance; } } @Override Method setInstance(…) { Method setInstance(…) { instance = … test logic } }
  • 26. When to use? - Singleton test - Protected constructor = can subclassing = 구리다 - singleton을 코드로 강제하는 것보다는 팀원들이 모두 이해하는게 더 중요하다?
  • 27. 13. Link Substitution Global reference for test Call history Value history Method A() { … } Method A() { record call history record value history … }
  • 28. When to use? - to break dependencies in procedural language like C.
  • 29. 14. Parameterize Constructor Class Class Class for test constructor( ) { constructor( ) { … this( new A() ); object = new A(); } … } constructor( A ) { constructor( A ) { … … object = A; object = test; … … } }
  • 30. When to use? - to separate the object that created in constructor. has dependencies on parameter’s class. but it’s a small concern.
  • 31. 15. Parameterize Method Class Class Method( ) { Method( A ) { … … object = new A(); object = A; … … } }
  • 32. When to use? -to separate the object that created in method. dependency issue? Extract and Override Factory Method is alternative way.
  • 33. 16. Primitivize Parameter Class Class TestClass Method ( ) { Method ( ) { TEST( ) { … … … logic call free function(); call free function(); … … } } } free function( ) { logic }
  • 34. When to use? - work to get a class under test is too large. - what the…
  • 35. 17. Pull Up Feature New Abstract Class Method A( ) { … } abstract Method B abstract Method C Class Method A( ) { … Class Class for test } Method B( ) { TEST( ) { Method B( ) { … CHECK(A()); … } } } Method C( ) { Method C( ) { … … } }
  • 36. When to use? - to test just one method that clustered with other methods.
  • 37. 18. Push Down Dependency Abstract Class Class Method A( ) { Method A( ) { … … } } Method B( ) { Method B( ) { … … } } abstract drawUI() Method drawUI( ) { … } New Concrete Class Concrete Class for test Method drawUI( ) { Method drawUI( ) { … // do nothing } }
  • 38. When to use? - dependencies are pervasive like drawing UI.
  • 39. 19. Replace Function with Function Pointer Method main( ) { Method main( ) { … … A(); *pointer … … } } *Method testA( ) { test logic } Method A( ) { … } *Method A( ) { … }
  • 40. When to use? - to break dependencies in procedural language like C. Different points of view - horribly unsafe VS useful tool
  • 41. 20. Replace Global Reference with Getter Class Class Class for test Global references A Global references A A getA A getA @Override Getter Method getA() { Getter Method getA() { return A; … } }
  • 42. When to use? - separate dependencies on global references
  • 43. 21. Subclass and Override Method Class Class private Method A(){ protected Method A(){ … … } } subClass for test @Override protected Method A(){ … }
  • 44. When to use? - break dependencies in object-oriented language. Many of the other dependency-breaking techniques are variations on it.
  • 45. 22. Supersede Instance Variable Class Class Class for test variable variable constructor( ) { constructor( ) { variable; variable; } } @Override supersedeVariable(A) { supersedeVariable(A) { variable = A; … } }
  • 46. When to use? - separate objects that created in constructor. - language disallows overrides of virtual function calls in constructors. Use uncommon prefix : supersede 개발자들이 잘못 사용할지도 모르니 잘 모르는 uncommon 한 단어를 prefix 로 사용하자??
  • 47. 23. Template Redefinition generics Method ( A ){ ... } Concrete type Concrete type for production for test
  • 48. When to use? - language supplies generics and a way of aliasing types.
  • 49. 24. Text Redefinition TestClass Class Class def Method A() def Method A() end … logic … end TEST( ) { … test Class }
  • 50. When to use? - break dependencies in interpreted language like Ruby.
  • 51. 전체 정리하면서 느낀 점 - 억지스러운 면이 자주 보인다. - dependency 는 깨질지 몰라도 Readability는 더 낮아진다. - 코드가 잘못 사용될 수 있으니 개발자가 더 주의 깊게 살펴봐야 한다. - 아무래도 LegacyCode 와의 싸움이 힘겹긴 한가보다. 이해하자. - 억지스럽고 지저분한 방법일지라도 대안이 없다면 그게 바로 최선의 방법이다. - 원문이 훨씬 보기 쉽다. (번역 X)
  • 52. Reference 레거시코드 활용 전략 http://www.yes24.com/24/goods/3092523