Alex Baranosky
Alex Baranosky

Reputation: 50094

Refactoring Derived Classes' Methods to Common Base Class' Method? (C#)

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?

Upvotes: 1

Views: 1101

Answers (3)

dahlbyk
dahlbyk

Reputation: 77580

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()
    {
        ...
    }
}

Upvotes: 4

Will Eddins
Will Eddins

Reputation: 13907

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.

Upvotes: 0

Adrian Godong
Adrian Godong

Reputation: 8921

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.

Upvotes: 0

Related Questions