“Refactoring” Notes

I’m not going to bother with a review of Martin Fowler‘s Refactoring: Improving the Design of Existing Code. It’s good enough that its catalog, available in expanded form online, now provides the definitive vocabulary shared by dozens of refactoring tools across nearly every major development platform. Though I was already familiar with the majority of the catalog, I thought it would be worth reading the other chapters, the notes from which you will find below with my additions indicated with emphasis. I’ve also included thoughts on various entries in the catalog.

Principles in Refactoring

  • 58: You don’t decide to refactor, you refactor because you want to do something else, and refactoring helps you do that other thing.
  • 62: Beck – Maintaining the current behavior of the system, how can you make your system more valuable, either by increasing its quality, or by reducing its cost. … Now you have a more valuable program because it has qualities that we will appreciate tomorrow. … There is a second, rarer refactoring game. Identify indirection that isn’t paying for itself and take it out.
  • 62: Problems with Refactoring
    • Don’t know limitations
    • Is refactoring because a tool tells you to a bad reason?
  • 65: Modify your code ownership policies to smooth refactoring.
  • 66: Code has to work before you refactor.
  • Ward Cunningham: Unfinished refactoring = technical debt.
  • 68: You still think about potential changes, you still consider flexible solutions. But instead of implementing these flexible solutions, you ask yours, “How difficult is it going to be to refactor a simple solution into the flexible solution?” If, as happens most of the time, the answer is “pretty easy,” then you just implement the simple solution.
  • 70: Changes that improve performance usually make the program harder to work with.
  • If you optimize all code equally, you end up with 90 percent of the optimizations wasted, because you are optimizing code that isn’t run much.

Bad Smells in Code

An expanded catalog of code smells is available online.

  1. Duplicate Code
  2. Long Method
  3. Large Class
  4. Long Parameter List
  5. Divergent Change
    • One class that suffers many kinds of changes
  6. Shotgun Surgery
    • One change that alters many classes
  7. Feature Envy
  8. Data Clumps
  9. Primitive Obsession
  10. Switch Statements
  11. Parallel Inheritance Hierarchies
  12. Lazy Class
  13. Speculative Generality
  14. Temporary Field
  15. Message Chains
    • a.k.a. Law of Demeter
  16. Middle Man
  17. Inappropriate Intimacy
    • Circular Reference => Change Bidirectional Association to Unidirectional
  18. Alternative Classes with Different Interfaces
  19. Incomplete Library Class
    • Introduce Foreign Method => Extension Methods
  20. Data Class
    • Favor setters and encapsulated collections
    • Very OO-centric – FP would argue that immutable data classes are preferred
    • Hide Method => Immutability
    • 87: “Data classes are like children. They are okay as a starting point, but to participate as a grownup object, they need to take some responsibility.”
  21. Refused Bequest
    • Smell is stronger if the subclass is reusing behavior but does not want to support the interface of the superclass. (NotSupportedException)
    • Apply Replace Inheritance with Delegation
  22. Comments
    • 88: When you feel the need to write a comment, first try to refactor the code so that any comment becomes superfluous.

Building Tests

  • Tests should be fully automatic and self-checking.
  • Interesting that a distinction is drawn between unit and functional tests, but there’s no mention of integration tests as middle ground
  • 97: “When you gget a bug report, start by writing a unit test that exposes the bug.”
    • This is my #1 use case for test-first
  • 98: “The key is to test the areas that you are most worried about going wrong.”
  • 101: “Don’t let the fear that testing can’t catch all bugs stop you from writing the tests that will catch most bugs.”

If this is the first you’ve read of unit testing, check out a book dedicated to the subject like Pragmatic Unit Testing.

Catalog Notes

  • Composing Methods
    • Replace Method with Method Object
      local variables => method object fields to facilitate extracting methods
  • Moving Features Between Objects
    • Introduce Foreign Method = Extension Methods
    • Introduce Local Extension = Subclass or Proxy
  • Organizing Data
    • Replace Data Value with Object
      replace primitive with a type that means something (decimal => Money)
    • Replace Type Code with State/Strategy
      inheritance is often abused, but this is one of its best use cases
  • Simplifying Conditional Expressions
    • Introduce Null Object
      OO approach to avoiding null checks, also not to be abused
  • Making Method Calls Simpler
    • Separate Query from Modifier
      mutation and query operations don’t mix
    • Replace Parameter with Method
      this rarely applies to new code, but rather is found in methods that have evolved over time
    • Hide Method
      • Related: Remove from Interface — useful to let a method “hide in public” for easier testing without cluttering up its expected usage as implementer of an interface
    • Replace Error Code with Exception
      if a circumstance is truly exceptional, exceptions are often better than error codes…
    • Replace Exception with Test
      …but if it’s not exceptional, don’t incur the overhead; for example, return a Null Object
  • Dealing with Generalization
    • Extract Subclass, Superclass and Interface
    • Collapse Hierarchy
    • Form Template Method
    • Replace Inheritance with Delegation
    • Replace Delegation with Inheritance

Big Refactorings

  • 359: “Do as much as you need to achieve your real task. You can always come back tomorrow.”
  • 360: “You refactor not because it is fun but because there are things you expect to be able to do with your programs if you refactor that you can’t do if you don’t refactor.”
    • I need to remember this!!

These are hard to identify, but provide the biggest return on investment. Think of them as high-level goals accomplished through low-level changes from the above catalog.

  • Tease Apart Inheritance
  • Convert Procedural Design to Objects
    • Also, Convert to Functions
  • Separate Domain from Presentation
    • MVP, MVC, MVVM…use something!
  • Extract Hierarchy
Advertisements
Posted in Books, General. Tags: . Comments Off on “Refactoring” Notes

Review: Pragmatic Unit Testing In C# with NUnit (2nd Edition)

I’ve written hundreds of tests, read dozens of articles and listened to several presentations on unit testing, but until recently had never actually read a book dedicated to the subject. In reviewing my options, I was told repeatedly that I should start with Pragmatic Unit Testing (In C# with NUnit) from The Pragmatic Programmers, part of the three-volume Pragmatic Starter Kit. In the context of that starter kit, I found the book to be an excellent introduction to unit testing; however, a developer with sufficient experience could probably get by with a quick glance over the summary provided as Appendix C (which is available online).

But before I get into the book, let me start by applauding the idea of the Pragmatic Starter Kit. As I entered industry after receiving my degrees in Computer Engineering and Computer Science, it became clear that I was terribly unprepared for building quality software. Academia provided a solid foundation of theory and some (basic) techniques to structure code (OO, FP, etc), but provided precious little guidance for scaling projects beyond a few thousands lines of code. Version control was given one lecture and a trivial assignment (in CVS), the unit testing lecture did little to convince me that it actually had value, and automated testing was never even mentioned (in fact, build processes in general were scarcely discussed). These are the gaps that the Pragmatic Starter Kit aims to fill with practical advice from the field, and if Pragmatic Unit Testing is any indication the entire series should be required reading for new graduates (or even sophomores, really).

As one would expect from an introductory volume, the book begins with an excellent overview (PDF) of what unit testing is and why it matters. There are also several pages dedicated to rebuttals to common objections like “It takes too much time to write the tests”, “It’s not my job to test my code”, and my personal favorite “I’m being paid to write code, not to write tests”, which is answered brilliantly:

By that same logic, we’re not being paid to spend all day in the debugger either. Presumably we are being paid to write working code, and unit tests are merely a tool toward that end, in the same fashion as an editor, an IDE, or the compiler.

Developers are a proud lot, so the emphasis on testing as a powerful tool rather than a crutch is crucial.

Chapters 2 and 3 follow up with an introduction to testing with NUnit, first with a simple example and then with a closer look at structured testing with the framework. All the usual suspects are covered, including classic and constraint-based asserts, setup and teardown guidance, [Category], [ExpectedException], [Ignore] and more.

The most valuable chapters to a new tester will be chapters 4 and 5. The former provides the “Right BICEP” mnemonic to suggest what to test; the latter takes a closer look at the “CORRECT” boundary conditions (the B in BICEP) to test. The expanded acronyms are included in the aforementioned summary card (PDF). Even after you have a good handle on what to test, the mnemonics can still serve as a handy reminder, and starting out the overviews of each bullet are spot on. I also liked chapters 7–9, which give good guidance on qualities of good tests and how testing can be applied effectively to projects and to improve code, though the refactoring example was a bit longer than it probably needed to be.

In my opinion, the weakest parts of the book were chapters 6 and 10, on mocking and UI testing, respectively. The former starts out strong, but gets bogged down once it starts talking about tools. The reader would be better off skipping section 6.3 altogether in favor of a good Rhino Mocks or Moq introduction. The discussion of UI testing, on the other hand, covers too little on a number of topics to be of much value other than to raise awareness that you should test all parts of the application.

Overall I was quite pleased with the quantity and quality of material covered for an introductory volume, awarding four out of five donkeys. The authors make a good argument for testing and offer sound guidance for how to do it. However, if you’re already familiar with unit testing you may be better off reading The Art of Unit Testing or finding more specific material online.

Posted in .NET, Books. Tags: . 1 Comment »