Re: Question about removing duplication: inheritance vs static methods

From: Aaron Perrin (aaron_perrinspam_at_yahoo.com)
Date: 10/17/03


Date: 17 Oct 2003 06:41:38 -0700

tonis <tonis22@nosp-am.starline.ee> wrote in message news:<3f8c4b09@news.infonet.ee>...
> Hi!
>
> I have realized that duplication is something to avoid but it isn't
> always easy to do so. One way is to use inheritance: if two classes have
> something common extract superclass with common code(using 'Template' or
> 'Strategy' pattern etc). But this sometimes introduces artificial
> coupling, subclasses become dependent from superclass which can change.
> And if subclass needs modifying programmer most know much about what
> superclass is doing, also code becomes hard to read/browse ....
>
> Second way is to extract static methods and put it in util classes.
> Probably more easy to do & use but not flexible and I guess not good
> design either. Also, I have noticed that following test first
> programming combined with maxim 'Do simplest thing possible' often leads
> along that way -- producing code full of static methods.
>
> Another question: I have extracted method but don't know where to attach
> it :
> 1) to the class which the method mostly uses( through args or
> functions) and make it non-static
>
> 2) make it static and move to Utils class
>
> 3) extract method object or new class which operates on parameters.
>
> Solution 1) is often logical but after some time target class will lot
> of methods attached to it... Also, often compromising with SRP.
> BTW, is there suggestions about "good codestyle" metrics about how much
> methods class "can" have or how many lines of code method "can" have?
>
> 2) is also easy but ....
>
> 3) is usally hardest thing to do (until we don't have refactoring tool
> support for that) ...
>
>
> What are your suggestions/opinions?
>
> thanks
>
> Tonis
>
> Java Developer

Well I'm far, far from an expert, but I generally keep a set of static
util functions around until I find patterns. When patterns occur, I
group them up to 1) abstract and 2) save code and 3) promote
decoupling or 4) improve readability.

For example, at first I may have a static util function that reads a
character from a disk file.

char Read(char* file);

Then, later I may need to add a new util function to write a char to a
disk file.

void Write(char c, char* file);

I may just do something like:

char File::Read();
void File::Write();

On the other hand, I may encounter a need for a new util function that
reads a character from memory. Or, later I may need a util function
that reads multiple characters from a file.

I may do something like:

IStream File::Read();
IStream Memory::Read();

Remember that OO is really a natural progression of procedural. To me
it doesn't make a lot of sense to add a ton of class structure just to
support one or two methods.

Aaron