tags:

views:

179

answers:

3

Hello,

In my project I have a few functions in derived classes that are the same except for one section that is different in each.

I want to pull the method up to the base class.

The functions look like this:

func(parameters)
{
//COMMON BITS

if      (someVar == "value1")  { htmlFilename = line; }
else if (someVar == "value2") { subVideoLink = line; }
else if (someVar == "value3") { linksH2HeadingWritten = true; }

//COMMON BITS
}

where the center lines of the different functions all look like above but have different values for "someVar" and different variables in the "variable = line;" format.

This is the generalized form:

if (someVar == "CommandName") { variable = line; }

The idea I had was to send the function a Dictionary<string CommandName, ref string>... however it seems I can't make a Dictionary with ref string in it...

I would then remove the boolean cases of the 'variable' by replacing them with string versions with values of "true" or "false".

Is there a better way to do this?

A: 

You should create an overridable method on the base class:

abstract func(parameters);

And implement it on the derived classes:

class CommandN {
...
func(parameters)
{  htmlfilename = line; }
}

class CommandSubVideoLinkX {
...
func(parameters)
{  subVideoLink = line; }
}

And so on.

Adrian Godong
the Command classes aren't the derived classes these functions are in... Sorry I didn't make that clear.
Alex Baranosky
+4  A: 

A better approach would be to define a virtual (or abstract) method in the base class that you call in func. Then in each of your subclasses you can override the method with the specific instructions and func will use the subclass's behavior.

public class MyBase
{
    protected virtual void DoCommand() { throw new NotImplementedException(); }

    public void Func()
    {
        ...
        DoCommand();
        ...
    }
}

public class MySubClass : MyBase
{
    protected override void DoCommand()
    {
        ...
    }
}
dahlbyk
Ahhh... I see what you're saying. Thanks, I'll try that.
Alex Baranosky
Instead of throwing in the base, why not just mark it abstract?
Steven Sudit
Abstract methods require an abstract base class. If the base class needs to be concrete for some reason, this is one possible default implementation. Empty would be another choice. Take your pick. :)
dahlbyk
A: 

If i'm understanding what you're trying to do correctly, you can reduce

if (activeCommand.GetType().Name == "CommandName") { variable = line; }

Down to:

if (activeCommand is CommandType ) { /*logic, cast if necessary*/ }

Very useful when you have a function that takes a base class, but performs a special case for a derived type. This would also handle cases where another type derives from CommandType.

Will Eddins
yeah, thanks, I had a momentary brain fart
Alex Baranosky