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

Domain Driven Design(DDD) Presentation
Domain Driven Design(DDD) PresentationDomain Driven Design(DDD) Presentation
Domain Driven Design(DDD) PresentationOğuzhan Soykan
 
Hexagonal architecture - message-oriented software design
Hexagonal architecture  - message-oriented software designHexagonal architecture  - message-oriented software design
Hexagonal architecture - message-oriented software designMatthias Noback
 
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019Paulo Clavijo
 
Hexagonal Architecture.pdf
Hexagonal Architecture.pdfHexagonal Architecture.pdf
Hexagonal Architecture.pdfVladimirRadzivil
 
Domain Driven Design: Zero to Hero
Domain Driven Design: Zero to HeroDomain Driven Design: Zero to Hero
Domain Driven Design: Zero to HeroFabrício Rissetto
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven DesignRyan Riley
 
A Practical Guide to Domain Driven Design: Presentation Slides
A Practical Guide to Domain Driven Design: Presentation SlidesA Practical Guide to Domain Driven Design: Presentation Slides
A Practical Guide to Domain Driven Design: Presentation Slidesthinkddd
 
Technical Webinar: By the (Play) Book: The Agile Practice at OutSystems
Technical Webinar: By the (Play) Book: The Agile Practice at OutSystemsTechnical Webinar: By the (Play) Book: The Agile Practice at OutSystems
Technical Webinar: By the (Play) Book: The Agile Practice at OutSystemsOutSystems
 
Training Webinars - Secret hacks for OutSystems 10
Training Webinars - Secret hacks for OutSystems 10Training Webinars - Secret hacks for OutSystems 10
Training Webinars - Secret hacks for OutSystems 10OutSystems
 
TDD (Test Driven Developement) et refactoring
TDD (Test Driven Developement) et refactoringTDD (Test Driven Developement) et refactoring
TDD (Test Driven Developement) et refactoringneuros
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionKent Huang
 
Clean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithClean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithVictor Rentea
 
Using Processes and Timers for Long-Running Asynchronous Tasks
Using Processes and Timers for Long-Running Asynchronous TasksUsing Processes and Timers for Long-Running Asynchronous Tasks
Using Processes and Timers for Long-Running Asynchronous TasksOutSystems
 

What's hot (20)

Domain Driven Design(DDD) Presentation
Domain Driven Design(DDD) PresentationDomain Driven Design(DDD) Presentation
Domain Driven Design(DDD) Presentation
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Hexagonal architecture - message-oriented software design
Hexagonal architecture  - message-oriented software designHexagonal architecture  - message-oriented software design
Hexagonal architecture - message-oriented software design
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019Breaking Dependencies Legacy Code -  Cork Software Crafters - September 2019
Breaking Dependencies Legacy Code - Cork Software Crafters - September 2019
 
Hexagonal Architecture.pdf
Hexagonal Architecture.pdfHexagonal Architecture.pdf
Hexagonal Architecture.pdf
 
Clean coding-practices
Clean coding-practicesClean coding-practices
Clean coding-practices
 
Domain Driven Design: Zero to Hero
Domain Driven Design: Zero to HeroDomain Driven Design: Zero to Hero
Domain Driven Design: Zero to Hero
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
A Practical Guide to Domain Driven Design: Presentation Slides
A Practical Guide to Domain Driven Design: Presentation SlidesA Practical Guide to Domain Driven Design: Presentation Slides
A Practical Guide to Domain Driven Design: Presentation Slides
 
Technical Webinar: By the (Play) Book: The Agile Practice at OutSystems
Technical Webinar: By the (Play) Book: The Agile Practice at OutSystemsTechnical Webinar: By the (Play) Book: The Agile Practice at OutSystems
Technical Webinar: By the (Play) Book: The Agile Practice at OutSystems
 
Training Webinars - Secret hacks for OutSystems 10
Training Webinars - Secret hacks for OutSystems 10Training Webinars - Secret hacks for OutSystems 10
Training Webinars - Secret hacks for OutSystems 10
 
Sql Antipatterns Strike Back
Sql Antipatterns Strike BackSql Antipatterns Strike Back
Sql Antipatterns Strike Back
 
Rich domain model
Rich domain modelRich domain model
Rich domain model
 
TDD (Test Driven Developement) et refactoring
TDD (Test Driven Developement) et refactoringTDD (Test Driven Developement) et refactoring
TDD (Test Driven Developement) et refactoring
 
Clean code
Clean codeClean code
Clean code
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
 
Clean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithClean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a Monolith
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Design
 
Using Processes and Timers for Long-Running Asynchronous Tasks
Using Processes and Timers for Long-Running Asynchronous TasksUsing Processes and Timers for Long-Running Asynchronous Tasks
Using Processes and Timers for Long-Running Asynchronous Tasks
 

Viewers also liked

Scalable Web Architecture and Distributed Systems
Scalable Web Architecture and Distributed SystemsScalable Web Architecture and Distributed Systems
Scalable Web Architecture and Distributed Systemshyun soomyung
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJSKyung Yeol Kim
 
연결자가 필요해!
연결자가 필요해!연결자가 필요해!
연결자가 필요해!Nasol Kim
 
Erlang을 이용한 swap 서버
Erlang을 이용한 swap 서버Erlang을 이용한 swap 서버
Erlang을 이용한 swap 서버Jaejin Yun
 
HTML5 & CSS3 - Video,Audio
HTML5 & CSS3 - Video,AudioHTML5 & CSS3 - Video,Audio
HTML5 & CSS3 - Video,Audiohyun soomyung
 
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.5hyun soomyung
 
[페차쿠차] 배움의 기술
[페차쿠차] 배움의 기술[페차쿠차] 배움의 기술
[페차쿠차] 배움의 기술hyun soomyung
 
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 Treehyun soomyung
 
xUnitTestPattern/chapter8
xUnitTestPattern/chapter8xUnitTestPattern/chapter8
xUnitTestPattern/chapter8hyun soomyung
 
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 다중연결구조hyun soomyung
 
Domain Driven Design
Domain Driven DesignDomain Driven Design
Domain Driven Designhyun soomyung
 
프로그램은 왜 실패하는가?
프로그램은 왜 실패하는가?프로그램은 왜 실패하는가?
프로그램은 왜 실패하는가?hyun soomyung
 
나는 버그를 잡는다.
나는 버그를 잡는다.나는 버그를 잡는다.
나는 버그를 잡는다.Nasol Kim
 
실전 윈도우 디버깅. Ch3. 디버거 해부
실전 윈도우 디버깅. Ch3. 디버거 해부실전 윈도우 디버깅. Ch3. 디버거 해부
실전 윈도우 디버깅. Ch3. 디버거 해부hyun soomyung
 
프로그래머의 길,멘토에게 묻다 2장
프로그래머의 길,멘토에게 묻다 2장프로그래머의 길,멘토에게 묻다 2장
프로그래머의 길,멘토에게 묻다 2장hyun soomyung
 

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 for Legacy Code

Similar to Dependency Breaking Techniques for Legacy Code (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

아꿈사 매니저소개
아꿈사 매니저소개아꿈사 매니저소개
아꿈사 매니저소개hyun soomyung
 
Design Pattern - Multithread Ch10
Design Pattern - Multithread Ch10Design Pattern - Multithread Ch10
Design Pattern - Multithread Ch10hyun soomyung
 
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 MIXALhyun soomyung
 
스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)
스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)
스터디그룹 패턴 (A PATTERN LANGUAGE FOR STUDY GROUPS)hyun soomyung
 
예제로 보는 Pattern 연상법
예제로 보는 Pattern 연상법예제로 보는 Pattern 연상법
예제로 보는 Pattern 연상법hyun soomyung
 
5장 그래프의 비밀 (Programming Game AI by Example)
5장 그래프의 비밀 (Programming Game AI by Example)5장 그래프의 비밀 (Programming Game AI by Example)
5장 그래프의 비밀 (Programming Game AI by Example)hyun soomyung
 

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

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
 
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
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
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
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
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
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
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
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
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
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
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
 
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
 
"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
 

Recently uploaded (20)

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
 
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
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
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
 
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
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
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
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
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
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
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
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
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)
 
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
 
"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
 

Dependency Breaking Techniques for Legacy Code

  • 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