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?
source to share
Basic conversion mechanics:
- Convert each
printf
-style%w.pf
or clause%w.pe
, wherew
is the field width andp
is the number of digits of precision, to<< setw(w) << setprecision(p) << fixed
. - Convert each
printf
-style%wd
or%wi
, wherew
is the field width, to<< setw(w)
. - Convert
"\n"
toendl
if needed.
Process for printf
:
- Create
char[]
(call ittext
) with sufficient overall width. - Convert
printf(...)
tosprintf(text, ...)
and usecout << text
for actual text printing. - Complete the general instructions.
Process for fprintf
:
- Same as
printf
but usefstream
insteadcout
.- 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 ).
- If you already have a public C-style object
- 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 contentchar[]
you are writing to. If you're still going to learn from itchar*
, you can dostd::stringstream::str().c_str()
.
- Otherwise, start by creating
- Complete the general instructions.
General instructions:
- Convert each sentence one at a time to C ++ style.
- Remove
*printf
andchar[]
ads as needed when done. - Use other refactorings as needed, such as Fowler, Refactoring.
source to share
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.
source to share