notes

Log | Files | Refs | README

refactoring.md (2451B)


      1 # Refactoring
      2 
      3 ### Book: Refactoring: Improving the Design of Existing Code (Addison-Wesley Professional 1999)
      4 
      5 ## The First Step in Refactoring
      6 
      7 > Whenever I do refactoring, the first step is always the same. I need to build
      8 > a solid set of tests for that section of code. The tests are essential because
      9 > even though I follow refactorings structured to avoid most of the
     10 > opportunities for introducing bugs, I'm still human and still make mistakes.
     11 > Thus I need solid tests.
     12 
     13 > An important part of the tests is the way they report their results. ... The
     14 > tests are thus self-checking. It is vital to make tests self-checking. If you
     15 > don't, you end up spending time hand checking some numbers from the test
     16 > against some numbers of a desk pad, and that slows you down.
     17 
     18 > As we do the refactoring, we will lean on the tests. I'm going to be relying
     19 > on the tests to tell me whether I introduce a bug. It is essential for
     20 > refactoring that you have good tests. It's worth spending the time to build
     21 > the tests, because the tests give you the security you need to change the
     22 > program later.
     23 
     24 ### Before you start refactoring, check that you have a solid suite of tests. These tests must be self-checking.
     25 
     26 ## Decomposing and Redistributing the Statement Method
     27 
     28 1. Overly Long Statement method:
     29 
     30 > The obvious first target of my attention is the overly long statement method.
     31 > When I look at a long method like that, I am looking to decompose the method
     32 > into smaller pieces. Smaller pieces of code tend to make things more
     33 > manageable. They are easier to work with and move around.
     34 
     35 - Extraction Method
     36 
     37 > When I extract a method, as in any refactoring, I need to know what can go
     38 > wrong. If I do the extraction badly, I could introduce a bug into the program.
     39 > So before I do the refactoring I need to figure out how to do it safely.
     40 
     41 > [!info] Tip: Refactoring changes the programs in small steps. If you make a
     42 > mistake, it is easy to find the bug.
     43 
     44 > Is renaming worth the effort? Absolutely. Good code should communicate what it
     45 > is doing clearly, and variable names are a key to clear code. Never be afraid
     46 > to change the names of things to improve clarity. With good find and replace
     47 > tools, it is usually not difficult. Strong typing and testing will highlight
     48 > anything you miss. Remember
     49 
     50 > [!info] Tip: Any fool can write code that a computer can understand. Good
     51 > programmers write code that humans can understand.