Refactoring C-style pretty-typing in C ++ - style pretty-typing

I want to refactor multiple printf

/ sprintf

/ operators fprintf

into expressions ostream

/ sstream

/ fstream

. The code in question prints integers and floating point numbers using whitespace and fixed decimal points.

I think it would be a good candidate for writing Martin Fowler's style of safe step-by-step refactorings with important notes. The first step, of course, is to get the legacy code into the test wiring, which I did.

What slow and careful steps can I take to accomplish this refactoring?

+3


source to share


2 answers


Basic conversion mechanics:

  • Convert each printf

    -style %w.pf

    or clause %w.pe

    , where w

    is the field width and p

    is the number of digits of precision, to << setw(w) << setprecision(p) << fixed

    .
  • Convert each printf

    -style %wd

    or %wi

    , where w

    is the field width, to << setw(w)

    .
  • Convert "\n"

    to endl

    if needed.

Process for printf

:

  • Create char[]

    (call it text

    ) with sufficient overall width.
  • Convert printf(...)

    to sprintf(text, ...)

    and use cout << text

    for actual text printing.
  • Complete the general instructions.

Process for fprintf

:



  • Same as printf

    but use fstream

    instead cout

    .
    • If you already have a public C-style object FILE

      that you don't want to refactor at this time, it gets a little sticky (but can be done ).
  • Complete the general instructions.

Process for sprintf

:

  • If the string being written is only used for output to the stream in the current context, refer to one of the two refactorings above.
    • Otherwise, start by creating stringstream

      and streaming the content char[]

      you are writing to. If you're still going to learn from it char*

      , you can do std::stringstream::str().c_str()

      .
  • Complete the general instructions.

General instructions:

  • Convert each sentence one at a time to C ++ style.
  • Remove *printf

    and char[]

    ads as needed when done.
  • Use other refactorings as needed, such as Fowler, Refactoring.
+2


source


If refactoring is not an end in itself, you can avoid it altogether (well, almost) by using a formatting library such as tinyformat , which provides an interface similar printf

but type-safe and uses IOStreams internally.



+2


source







All Articles