Thomas Eyde | 1 Jun 2004 01:42
Picon
Picon

Re: refactoring nested ifs

If I understand this correctly, then you have two things: Navigation + Data
Transfer.

I think all controls should know where to save and retrieve the data they
need. Think of it as a database. An ArrayList or Hashtable with the proper
facade would do. Use a real database for permanent persistence.

Then you are left with the navigation. You could use the control names as
the navigation key. Then Default.aspx can use this key to load the next
control. Or you could, as already suggested use a kind of lookup.

It can be as simple as this:

Hashtable viewMappings = new Hashtable();
viewMappings.Add("FirstView.Next", "SecondView");
viewMappings.Add("SecondView.Commit", "ThirdView");
viewMappings.Add("SecondView.Cancel", "FirstView");

Thomas
----- Original Message ----- 
From: "tourne_dr" <tourne_dr <at> yahoo.co.uk>

> The code behind the default page identifies what control was last
> displayed and what the next control is going to be, and it handles
> the transfer or information between them, in a method called
> DoPageTransfer().
>
> DoPageTransfer() is a very "smelly" method that consists of a long
> sequence of nested if statements.

(Continue reading)

Oliver White | 1 Jun 2004 01:06
Picon
Picon

RE: Suggestions required for Refactoring.

I've had a similar experience, taking over a C++ codebase when starting a new job. Fowler strongly recommends refactoring only when you already have unit tests, to prove that you have preserved behavior. However, if you have no unit tests to start with, then any change is likely to introduce bugs, whether they be refactorings or just maintaining the code. Often it is necessary to refactor before you can add unit tests, and these "unsafe" steps towards a better design and testing framework have a lot of value. For instance, if you're in a situation where data access code is mingled with business logic, it can be very difficult to write unit tests. 
 
A period of unsafe refactoring can separate the business logic and data access allowing the tests then to be written. The point is you *will* introduce bugs. If you're writing safety critical software or you're risking millions of dollars on this technique, I'd take another path. Do try and peform some functional tests as you go, as you'll catch any major flaws as you go. Do use a source control tool such as CVS so if you really go down the wrong path you can recover to a working version.
-----Original Message-----
From: Ramesh R [mailto:rameshr <at> elind.com]
Sent: Monday, 31 May 2004 5:12 PM
To: refactoring <at> yahoogroups.com
Subject: [refactoring] Suggestions required for Refactoring.

Hi,
 
    I am entrusted a task of refactoring a not so well written OO code (Java). Also the exisiting code does not have Junit test cases.
 
    Please help me with links, suggestions on how to start and go about.
   
    a. Do i need to first write the unit test cases and go futher and refactor?
    b. Are there any naming convention docs ( one apart from Sun's on their website), so that i can use them, when i do rename class, methods, etc...?
 
thanx in advance.
 
Ramesh
 


Yahoo! Groups Links

---------------------------------------------------------------------

This email is from Civica Pty Limited and it, together with any attachments, is confidential to the intended recipient(s) and the contents may be legally privileged or contain proprietary and private information. It is intended solely for the person to whom it is addressed. If you are not an intended recipient, you may not review, copy or distribute this email. If received in error, please notify the sender and delete the message from your system immediately.Any views or opinions expressed in this email and any files transmitted with it are those of the author only and may not necessarily reflect the views of Civica and do not create any legally binding rights or obligations whatsoever. Unless otherwise pre-agreed by exchange of hard copy documents signed by duly authorised representatives, contracts may not be concluded on behalf of Civica by email. Please n ote that neither Civica nor the sender accepts any responsibility for any viruses and it is your responsibility to scan the email and the attachments (if any). All email received and sent by Civica may be monitored to protect the business interests of Civica.

---------------------------------------------------------------------


Oliver White | 1 Jun 2004 01:28
Picon
Picon

RE: refactoring nested ifs

Before embarking on "Replace Conditional With Polymorphism" I'd have a look
at this:

http://www.refactoring.com/catalog/extractMethod.html

and this 

http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.
html

It is a much simpler refactoring, and sets the stage for future
decomposition.
For example (excuse my complete lack of knowledge of C#):

Protected override void DoPageTransfer (UserControl currentPage, 
UserControl nextPage) {
	if (nextpage is ControlA) {
		if (currentPage is ControlB) 
			printFoo();
		elseif (currentPage is ControlC) 
			printBar();
		else	
			printBoo();
	}
	elseif (nextpage is ControlB) {
		printFar();
	}
}

=========== Extract Method ======================

void DoControlANextPage() {
	if (currentPage is ControlB) 
		printFoo();
	elseif (currentPage is ControlC) 
		printBar();
	else
		printBoo();
}

void DoControlBNextPage() {
	printFar();
}

Protected override void DoPageTransfer (UserControl currentPage, 
UserControl nextPage) {
	if (nextpage is ControlA) 
		DoControlANextPage();
	elseif (nextpage is ControlB)
		DoControlBNextPage();
}

==== Replace Conditional With Guard Clause ====

void DoControlANextPage() {
	if (currentPage is ControlB)
	{ 
		printFoo();
		return;
	}
	
	if (currentPage is ControlC) 
	{
		printBar();
		return;
	}	
	
	printBoo();
}

void DoControlBNextPage() {
	printFar();
}

Protected override void DoPageTransfer (UserControl currentPage, 
UserControl nextPage) {
	if (nextpage is ControlA)
	{ 
		DoControlANextPage();
		return;
	}
	
	if (nextpage is ControlB)
	{
		DoControlBNextPage();
		return;
	}
}

=========================================================

At this point I might consider conditional->polymorphism, and hopefully at
this point we will have taken care of any temporary variables that might
screw up the process.

Cheers. :-)

-----Original Message-----
From: Jay Bazuzi [mailto:jaybaz <at> microsoft.com]
Sent: Tuesday, 1 June 2004 2:59 AM
To: refactoring <at> yahoogroups.com
Subject: RE: [refactoring] refactoring nested ifs

Check out
http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.ht
ml.

Just doing at the top level (nextpage) will go a long way to making your
code sane.

	-Jay Bazuzi	http://blogs.msdn.com/jaybaz_ms

--------------------------------------------------------------------- 
This email is from Civica Pty Limited and it, together with any attachments,
is confidential to the intended recipient(s) and the contents may be legally
privileged or contain proprietary and private information. It is intended
solely for the person to whom it is addressed. If you are not an intended
recipient, you may not review, copy or distribute this email. If received in
error, please notify the sender and delete the message from your system
immediately.Any views or opinions expressed in this email and any files
transmitted with it are those of the author only and may not necessarily
reflect the views of Civica and do not create any legally binding rights or
obligations whatsoever. Unless otherwise pre-agreed by exchange of hard copy
documents signed by duly authorised representatives, contracts may not be
concluded on behalf of Civica by email. Please note that neither Civica nor
the sender accepts any responsibility for any viruses and it is your
responsibility to scan the email and the attachments (if any). All email
received and sent by Civica may be monitored to protect the business
interests of Civica. 
--------------------------------------------------------------------- 

------------------------ Yahoo! Groups Sponsor --------------------~--> 
Make a clean sweep of pop-up ads. Yahoo! Companion Toolbar.
Now with Pop-Up Blocker. Get it for free!
http://us.click.yahoo.com/L5YrjA/eSIIAA/yQLSAA/umvwlB/TM
--------------------------------------------------------------------~-> 

 
Yahoo! Groups Links

<*> To visit your group on the web, go to:
     http://groups.yahoo.com/group/refactoring/

<*> To unsubscribe from this group, send an email to:
     refactoring-unsubscribe <at> yahoogroups.com

<*> Your use of Yahoo! Groups is subject to:
     http://docs.yahoo.com/info/terms/

Russ Freeman | 1 Jun 2004 01:55

Re: refactoring nested ifs

On Tue, 2004-06-01 at 00:42, Thomas Eyde wrote:

> It can be as simple as this:
> 
> Hashtable viewMappings = new Hashtable();
> viewMappings.Add("FirstView.Next", "SecondView");
> viewMappings.Add("SecondView.Commit", "ThirdView");
> viewMappings.Add("SecondView.Cancel", "FirstView");
> 

It's more complex usually, i.e. the next view is based on a computation
derived from the current system state, rather than a static decision. 
Often implemented as a state machine but not necessary.

------------------------ Yahoo! Groups Sponsor --------------------~--> 
Yahoo! Domains - Claim yours for only $14.70
http://us.click.yahoo.com/Z1wmxD/DREIAA/yQLSAA/umvwlB/TM
--------------------------------------------------------------------~-> 

 
Yahoo! Groups Links

<*> To visit your group on the web, go to:
     http://groups.yahoo.com/group/refactoring/

<*> To unsubscribe from this group, send an email to:
     refactoring-unsubscribe <at> yahoogroups.com

<*> Your use of Yahoo! Groups is subject to:
     http://docs.yahoo.com/info/terms/

Thomas Eyde | 1 Jun 2004 08:59
Picon
Picon

Re: refactoring nested ifs

Then a state machine is needed, I guess. But I don't understand how
navigation can be designed that way. Wouldn't that create "funny"
navigations once in a while?

But my hashtable sample is a kind of a state machine. The lookup key is
created by viewname + '.' + action. To handle more complex navigation, like
stepping over this screen if such and such, then add a condition to the key:

Hashtable viewMappings = new Hashtable();
viewMappings.Add("FirstView.Next", "SecondView");
viewMappings.Add("FirstView.Next.Skip", "ThirdView");

You need some logic to get the condition, so perhaps a state machine is the
answer after all?

----- Original Message ----- 
From: "Russ Freeman" <russ.freeman <at> ergnosis.com>
> It's more complex usually, i.e. the next view is based on a computation
> derived from the current system state, rather than a static decision.
> Often implemented as a state machine but not necessary.

------------------------ Yahoo! Groups Sponsor --------------------~--> 
Make a clean sweep of pop-up ads. Yahoo! Companion Toolbar.
Now with Pop-Up Blocker. Get it for free!
http://us.click.yahoo.com/L5YrjA/eSIIAA/yQLSAA/umvwlB/TM
--------------------------------------------------------------------~-> 

 
Yahoo! Groups Links

<*> To visit your group on the web, go to:
     http://groups.yahoo.com/group/refactoring/

<*> To unsubscribe from this group, send an email to:
     refactoring-unsubscribe <at> yahoogroups.com

<*> Your use of Yahoo! Groups is subject to:
     http://docs.yahoo.com/info/terms/

Ron Jeffries | 1 Jun 2004 10:11

Re: Suggestions required for Refactoring.

On Monday, May 31, 2004, at 7:06:20 PM, Oliver White wrote:

> A period of unsafe refactoring can separate the business logic and data
> access allowing the tests then to be written. The point is you *will*
> introduce bugs. If you're writing safety critical software or you're risking
> millions of dollars on this technique, I'd take another path.

What other techniques come to mind?

Ron Jeffries
www.XProgramming.com
Here is Edward Bear, coming downstairs now, bump, bump, bump, on the back
of his head. It is, as far as he knows, the only way of coming downstairs,
but sometimes he feels that there really is another way, if only he could
stop bumping for a moment and think of it. And then he feels that perhaps
there isn't. -- A. A. Milne

------------------------ Yahoo! Groups Sponsor --------------------~--> 
Make a clean sweep of pop-up ads. Yahoo! Companion Toolbar.
Now with Pop-Up Blocker. Get it for free!
http://us.click.yahoo.com/L5YrjA/eSIIAA/yQLSAA/umvwlB/TM
--------------------------------------------------------------------~-> 

 
Yahoo! Groups Links

<*> To visit your group on the web, go to:
     http://groups.yahoo.com/group/refactoring/

<*> To unsubscribe from this group, send an email to:
     refactoring-unsubscribe <at> yahoogroups.com

<*> Your use of Yahoo! Groups is subject to:
     http://docs.yahoo.com/info/terms/

Harald Mueller | 1 Jun 2004 10:55
Picon

Re: Suggestions required for Refactoring.

Ron Jeffries asked:
> On Monday, May 31, 2004, at 7:06:20 PM, Oliver White wrote:
[...]
> If you're writing safety critical software or you're
> risking
> > millions of dollars on this technique, I'd take another path.
> 
> What other techniques come to mind?

1. Non-JUnit unit tests (I'd say: Write these immediately!)

Possibilities:

** Driving the GUI via a GUI-testing tool - yes, also this is a unit test if
it tests a single function.

** Write your own unit test driver (which e.g. puts events on an event queue
- useful for "GUI-implemented business functions").

** Even: Partially copy-paste code out of monolithic methods or GUI
listeners into a unit test (you must of course guarantee that the copied
code and the "real code" remain in sync - thus, an "extract method" is of
course to be preferred - if you trust your refactoring tool completely, you
can do this without unit tests).

2. Adding (many, and non-trivial) assertions inside running code to ensure
behavior constancy over refactorings.

You need a way to guarantee that the assertions do not change the behavior:
I.e., they must be side-effect free. In Java, this is in general hard to do;
however, if you restrict the expressions allowed in assertions to only very
few constructs, you can guarantee this by a hard code review or even formal
methods - e.g. a simple parser that looks at assertions and gives an error
message if it does not recognize an identifier in it. Classes of expressions
you might allow:

** Only getters, casts and the following methods for Collections, Iterators
and arrays: Collection.iterator(), List.get(int), Iterator.hasNext(),
Iterator.next(), array access without assignment.
Risk: You must assure that all getters are side-effect free.

** Reading fields of objects and elements of arrays via reflection; Casts,
Collection, and Iterator methods like above. Advantages: You can also access
non-public (internal) state (if you manage to get the right permissions);
and you can assure side-effect free-ness (advice: Do not use raw reflection
in the assertions directly, but encapsulate it in a helper class which
prevents that you inadvertently use a method with side-effect like
Field.set()).

3. Fagan reviews after a step (print out CSDiff protocols if the changes are
small; or other documentation).
- Experience: I have never managed to accomplish this with refactoring; but
you may succeed.

4. Use formal proofs.
A "classic" in areas of fail-safe software (especially all software that
might endanger humans). But if you work in this area, refactoring is just a
sub-discipline of maintenance, which will follow very strict guidelines
anyway (regarding whether a code change happens at all; and what has to be
proven after a code modification).

Regards
H.M.Müller

-- 
+++ Jetzt WLAN-Router für alle DSL-Einsteiger und Wechsler +++
GMX DSL-Powertarife zudem 3 Monate gratis* http://www.gmx.net/dsl

------------------------ Yahoo! Groups Sponsor --------------------~--> 
Yahoo! Domains - Claim yours for only $14.70
http://us.click.yahoo.com/Z1wmxD/DREIAA/yQLSAA/umvwlB/TM
--------------------------------------------------------------------~-> 

 
Yahoo! Groups Links

<*> To visit your group on the web, go to:
     http://groups.yahoo.com/group/refactoring/

<*> To unsubscribe from this group, send an email to:
     refactoring-unsubscribe <at> yahoogroups.com

<*> Your use of Yahoo! Groups is subject to:
     http://docs.yahoo.com/info/terms/

Ron Jeffries | 1 Jun 2004 14:21

Re: Suggestions required for Refactoring.

On Tuesday, June 1, 2004, at 4:55:04 AM, Harald Mueller wrote:

> Ron Jeffries asked:
>> On Monday, May 31, 2004, at 7:06:20 PM, Oliver White wrote:
> [...]
>> If you're writing safety critical software or you're
>> risking
>> > millions of dollars on this technique, I'd take another path.
>> 
>> What other techniques come to mind?

Oliver referred to "another path". Some of these might fit that bill well,
some, it seems to me, not so much:

> 1. Non-JUnit unit tests (I'd say: Write these immediately!)

> Possibilities:

> ** Driving the GUI via a GUI-testing tool - yes, also this is a unit test if
> it tests a single function.

> ** Write your own unit test driver (which e.g. puts events on an event queue
> - useful for "GUI-implemented business functions").

> ** Even: Partially copy-paste code out of monolithic methods or GUI
> listeners into a unit test (you must of course guarantee that the copied
> code and the "real code" remain in sync - thus, an "extract method" is of
> course to be preferred - if you trust your refactoring tool completely, you
> can do this without unit tests).

There are many kinds of tests in the world, and they are all perfectly
legal as programmer tools. The above are certainly good ideas, yet not what
I was looking for in Oliver's "another path" comment.

> 2. Adding (many, and non-trivial) assertions inside running code to ensure
> behavior constancy over refactorings.

Yes ... though I would think that anything that can be done with assertions
can be done with tests, up until the real application blows out of the
water for failing a built-in assertion. (Which could be the right thing to
do, in which case, in my opinion, it's a story.)

[Nice list of safe assertion techniques elided for brevity and shortness.]

> 3. Fagan reviews after a step (print out CSDiff protocols if the changes are
> small; or other documentation).
> - Experience: I have never managed to accomplish this with refactoring; but
> you may succeed.

Yes. Possible but difficult to sustain. Slow feedback but surely worthwhile
if testing cannot sustain the need for quality /and confidence/.

> 4. Use formal proofs.
> A "classic" in areas of fail-safe software (especially all software that
> might endanger humans). But if you work in this area, refactoring is just a
> sub-discipline of maintenance, which will follow very strict guidelines
> anyway (regarding whether a code change happens at all; and what has to be
> proven after a code modification).

I've never been in a situation where formal proofs were of more than
academic interest, other than perhaps in a very small percentage of the
code. Is that experience atypical?

Ron Jeffries
www.XProgramming.com
I could be wrong, of course. It's just not the way to bet.

------------------------ Yahoo! Groups Sponsor --------------------~--> 
Make a clean sweep of pop-up ads. Yahoo! Companion Toolbar.
Now with Pop-Up Blocker. Get it for free!
http://us.click.yahoo.com/L5YrjA/eSIIAA/yQLSAA/umvwlB/TM
--------------------------------------------------------------------~-> 

 
Yahoo! Groups Links

<*> To visit your group on the web, go to:
     http://groups.yahoo.com/group/refactoring/

<*> To unsubscribe from this group, send an email to:
     refactoring-unsubscribe <at> yahoogroups.com

<*> Your use of Yahoo! Groups is subject to:
     http://docs.yahoo.com/info/terms/

Harald Mueller | 1 Jun 2004 15:11
Picon

Re: Suggestions required for Refactoring.

Hi Ron -

I like it that 2 of my 4 items got an unqualified "Yes" from you ;-)

Just a few small comments to clarify:

> > 1. Non-JUnit unit tests (I'd say: Write these immediately!)
[...]
> 
> There are many kinds of tests in the world, and they are all perfectly
> legal as programmer tools. The above are certainly good ideas, yet not
> what
> I was looking for in Oliver's "another path" comment.

Just to make it clear:

* There are JUnit unit tests which are a proper subset of ...
* ... unit tests (with other tools) which are a proper subset of ...
* ... tests

My impression is that when discussing tests or unit tests in the context of
Java refactoring, many people in these days automatically limit these words
to the first item.

Refactoring, as commonly(??) understood or at least defined, requires *unit*
tests - they need, of course, not be JUnit unit tests (and cannot unless
Java is used); and they should not (must not?) be
system/integration/load/functional/what-have-you tests.

My list tried to give ideas for non-JUnit unit tests, just in case someone
thought that only JUnit tests make sense; or - on the other hand - that "any
test is a test for refactoring".

[Side note: One can discuss why and whether refactoring really requires
*unit tests*; or just "tests" in general. And also, what the "unit" in "unit
test" may legally be ... I have my ideas here, but this has certainly
discussed on TDD and unit tests groups endlessly ...].

> 
> > 2. Adding (many, and non-trivial) assertions inside running code to
> ensure
> > behavior constancy over refactorings.
> 
> Yes ... though I would think that anything that can be done with
> assertions
> can be done with tests, 

First, the question is whether it really can be done with *unit* tests. This
is not clear. Extreme example: A huge monolithic main method that reads data
from a real-world share price web-service feed and computes, in some tricky
way, a small result which it writes into a database.

This (horrible) design *cannot* be unit-tested (before refactoring - but
unit tests would be necessary to be allowed to start refactoring! - a
chicken-egg problem), as it will read different data on each run.

However, sprinkling the main with assertions which are proven to be
side-effect-free (by construction) would allow refactoring to start.

[I accept that I might be nit-picking or even "lawyer-izing" here, in that
I'm talking about definitions of terms like "unit test" (at least something
which is not a functional test, load test, or some other sort of test),
"refactoring" (by definition something which requires a means to prove
behavior-consistency over its steps) - but I think this is useful to
understand what one is talking about.
Another, also acceptable way is to use all these terms loosely - any test
tests some unit (whatever it is), so every test is a unit test; every
modification which improves something can be called refactoring. But then
the original question about "another path [to ensure safe refactoring]" is
useless, as any path in "some sense" is a test ...].

Second, the question is whether anything that can be done with assertions
can be done *efficiently* with (any sort of) tests. In the extreme example
above, a much later (test) step might indeed discover errors in the stored
result; but it would certainly be better that errors are found earlier.

> 
> [Nice list of safe assertion techniques elided for brevity and shortness.]

Thx.

> 
> > 3. Fagan reviews 
[...]
> 
> > 4. Use formal proofs.
[...]
> 
> I've never been in a situation where formal proofs were of more than
> academic interest, other than perhaps in a very small percentage of the
> code. Is that experience atypical?

I'd say it is typical. I just mentioned it because it *is* a possible way.

The only place where I was near a "formal proof" environment was the
development of railway signalling software in a neighboring team; and even
there, only a small portion of basic systems was handled like that -
detailled and very formalistic Fagan reviews where the standard QA method.
The "maintenance phase" (which was - then, in the times of hard waterfall
processes - the only part in the process which would change code; and hence
had some resemblance to today's refactoring) had to use these methods - and
I think they used reviews  exclusively (i.e. even software which underwent
some proof in its first version was later QAed only by reviews).

Regards
H.M.Müller

-- 
+++ Jetzt WLAN-Router für alle DSL-Einsteiger und Wechsler +++
GMX DSL-Powertarife zudem 3 Monate gratis* http://www.gmx.net/dsl

------------------------ Yahoo! Groups Sponsor --------------------~--> 
Make a clean sweep of pop-up ads. Yahoo! Companion Toolbar.
Now with Pop-Up Blocker. Get it for free!
http://us.click.yahoo.com/L5YrjA/eSIIAA/yQLSAA/umvwlB/TM
--------------------------------------------------------------------~-> 

 
Yahoo! Groups Links

<*> To visit your group on the web, go to:
     http://groups.yahoo.com/group/refactoring/

<*> To unsubscribe from this group, send an email to:
     refactoring-unsubscribe <at> yahoogroups.com

<*> Your use of Yahoo! Groups is subject to:
     http://docs.yahoo.com/info/terms/

Michael Feathers | 1 Jun 2004 15:41
Picon

Re[2]: Suggestions required for Refactoring.


OW> I've had a similar experience, taking over a C++ codebase when starting a
OW> new job. Fowler strongly recommends refactoring only when you already have
OW> unit tests, to prove that you have preserved behavior. However, if you have
OW> no unit tests to start with, then any change is likely to introduce bugs,
OW> whether they be refactorings or just maintaining the code. Often it is
OW> necessary to refactor before you can add unit tests, and these "unsafe"
OW> steps towards a better design and testing framework have a lot of value. For
OW> instance, if you're in a situation where data access code is mingled with
OW> business logic, it can be very difficult to write unit tests. 

OW> A period of unsafe refactoring can separate the business logic and data
OW> access allowing the tests then to be written. The point is you *will*
OW> introduce bugs. If you're writing safety critical software or you're risking
OW> millions of dollars on this technique, I'd take another path. Do try and
OW> peform some functional tests as you go, as you'll catch any major flaws as
OW> you go. Do use a source control tool such as CVS so if you really go down
OW> the wrong path you can recover to a working version.

The thing to recognize is that different projects have different risk
profiles.  Not all projects are safety critical or have large amounts
of money in play.

I advocate higher level tests when you can get a sense of what they
cover, but in general the further tests are from what they test, the
harder it is to determine that and you may think that they are
preserving the behavior you want to change when they aren't.

There are some refactorings you can do safely without tests, but you
have to be *very* conservative.   Here's one.  Try to think of all of
the things that can go wrong when you do this refactoring.  There
aren't too many.

I have a class which accesses a singleton logger in a method:

class RTYDispatcher : public Dispatcher
{
public:
     void dispatch(COMPacket *packet) {
        ...
        Logger::getInstance()->logMessage(INFORMATIONAL, "packet sent");
        ...
    }
};

I want to see that the packet was sent in a test, but without
instantiating and checking a logger.

Here's what I can do.

Find the declaration of the logMessage method of Logger:

    void logMessage(int severity, const string& message);

Copy it's signature into the RTYDispatcher class as a protected
method:

class RTYDispatcher : public Dispatcher
{
public:
     void dispatch(COMPacket *packet) {
        ...
        Logger::getInstance()->logMessage(INFORMATIONAL, "packet sent");
        ...
    }

private:
    virtual void logMessage(int severity, const string& message);

};

Copy the logging like from the dispatch method into a body for the new
method:

void RTYDispatcher::logMessage(int severity, const string& message)
{
    Logger::getInstance()->logMessage(INFORMATIONAL, "packet sent");
}

Adjust the parameters:

void RTYDispatcher::logMessage(int severity, const string& message)
{
    Logger::getInstance()->logMessage(severity, message);
}

Now go back to the dispatch method and remove the text
"Logger::getInstance()->":

class RTYDispatcher : public Dispatcher
{
public:
     void dispatch(COMPacket *packet) {
        ...
        logMessage(INFORMATIONAL, "packet sent");
        ...
    }

private:
    virtual void logMessage(int severity, const string& message);

};

Now you can subclass RTYDispatcher and override logMessage to sense
what is sent to it.

This refactoring required minimal editing and, critically, it
'preserved signatures' so there isn't a chance of a conversion error.

If you have a tool that does safe extract method, this refactoring is
even more direct.

The trick is, working with a partner, working small, and be very
conservative.  Most errors I've run into using these techniques are
the result of too much ambition, just do what it takes to break
dependencies that prevent testing.

Michael Feathers
www.objectmentor.com

------------------------ Yahoo! Groups Sponsor --------------------~--> 
Yahoo! Domains - Claim yours for only $14.70
http://us.click.yahoo.com/Z1wmxD/DREIAA/yQLSAA/umvwlB/TM
--------------------------------------------------------------------~-> 

 
Yahoo! Groups Links

<*> To visit your group on the web, go to:
     http://groups.yahoo.com/group/refactoring/

<*> To unsubscribe from this group, send an email to:
     refactoring-unsubscribe <at> yahoogroups.com

<*> Your use of Yahoo! Groups is subject to:
     http://docs.yahoo.com/info/terms/


Gmane