C
C#2y ago
DeaDo

Inherit from Abstract class: base.Do() vs field.Do

If im using the command Pattern, is there some rule, that says, that i should use base.Do instead of creating a field? Example:
public class Increment : CounterCommand
{

private Counter counter;

public Increment(Counter counter) : base(counter)
{
this.counter = counter;
}

public override void Execute() => counter.Increment();
public override void Undo() => counter.Decrement();
public override void Redo() => counter.Increment();
}
public class Increment : CounterCommand
{

private Counter counter;

public Increment(Counter counter) : base(counter)
{
this.counter = counter;
}

public override void Execute() => counter.Increment();
public override void Undo() => counter.Decrement();
public override void Redo() => counter.Increment();
}
or:
public class Increment : CounterCommand
{
public Increment(Counter counter) : base(counter)
{

}

public override void Execute() => base.counter.Increment();
public override void Undo() => base.counter.Decrement();
public override void Redo() => base.counter.Increment();
}
public class Increment : CounterCommand
{
public Increment(Counter counter) : base(counter)
{

}

public override void Execute() => base.counter.Increment();
public override void Undo() => base.counter.Decrement();
public override void Redo() => base.counter.Increment();
}
Why is the better approach better?
8 Replies
Anton
Anton2y ago
composition allows you to combine multiple things, inheritance only allows a single one generally prefer composition, even though it's usually more boilerplate google composition vs inheritance
DeaDo
DeaDoOP2y ago
well in this task im supposed to inherit. Its a study task otherwise I wouldn't use inheritance at all
Anton
Anton2y ago
and you don't need to override anything on the second thing in practice, you avoid inheritance if you can
DeaDo
DeaDoOP2y ago
I know. I still have to create examples for some oop design patterns i would almost never use in my personal projects
Anton
Anton2y ago
patterns can be useful at a conceptual level
DeaDo
DeaDoOP2y ago
If i don't override i get compliler issues, that tell me that im supposed to implement them. I guess u would suggest to imblement them in the base?
Anton
Anton2y ago
oh it's a base class then sure i mean those are abstract
DeaDo
DeaDoOP2y ago
yes they are... But i guess i can make Redo just execute Execute in abstract base, and there shouldn't be any rule preventing that
Want results from more Discord servers?
Add your server