Reputation: 18895
Assuming you start out with these two classes:
public class Foo{
public virtual Baz Bar(){
return GetStandardBaz();
}
}
public class Qux: Foo{
public virtual Baz Bar(){
return GetQuxBaz();
}
}
Now lets say a requirement comes up to do something with Baz
before returning it when Bar
gets called. I would create a virtual protected
method, and remove the virtual
from the public method like so:
public class Foo{
public Baz Bar(){
var value = BarInternal();
DoSomethingFirst(value);
return value;
}
protected virtual Baz BarInternal(){
return GetStandardBaz();
}
}
public class Qux: Foo{
protected override Baz BarInternal(){
return GetQuxBaz();
}
}
This ensures that whenever Bar
get's called, the resultant Baz
is passed into DoSomethingFirst
before being returned. Yes this is a breaking change for all child classes, but it doesn't require any updates to any call sites of Bar
.
Is this a standard design pattern? Is there a better way that I'm missing? Also wondering if there is a better post-fix name than Internal
.
Upvotes: 3
Views: 163
Reputation: 3370
If you slightly change Foo
class as follows you will get Template Method pattern.
public class Foo{
public Baz Bar(){
var value = BarInternal();
DoSomethingFirst(value);
return value;
}
protected virtual Baz BarInternal(){
return GetStandardBaz();
}
}
You can achieve something similar with Decorator pattern as well. Decision will depend on details of what your classes are intended to do.
Upvotes: 2
Reputation: 171178
This is a good thing because you can filter the inputs and outputs in a standard way. You can do validation and additional processing.
You can also validate inputs so that the inner/virtual method can rely on certain conditions to be true.
I usually use the suffix "Core" (GetBarCore
).
Upvotes: 1