I expect this is a common problem and/or pattern question for beginners to OOP. Somehow I find myself wondering again and wasn't able to find a decent answer. So at the risk of creating a dupe...
What is the best practice or pattern to follow when a class must behave slightly differently in a given context?
I am asking specifically about differences to behavior that lie within the line by line method operations and not an entire method of my class. So I'd assume implementing two classes against a common interface with different methods may cause a lot of redundancy but perhaps not.
That said here is my dummy oversimplified C# example of an approach I've seen in the wild. Assume this class could grow to 2000+ lines and have slight differences within various private methods throughout.
using System;
namespace ClassBahaveMod
{
class Program
{
static void Main(string[] args)
{
bool isAlternateContext = args.Length >= 2 && args[1] == "1" ? true : false;
var fooService = new FooService();
if (isAlternateContext)
{
fooService.IsAlternateBehavior = true;
}
fooService.DoThing();
}
}
public class FooService
{
public bool IsAlternateBehavior { get; set; }
public void DoThing()
{
Console.WriteLine("Common Action 1");
if (IsAlternateBehavior)
{
Console.WriteLine("Alternate Action");
}
else
{
Console.WriteLine("Original Action");
}
Console.WriteLine("Common Action 2");
}
}
}
So with the above approach a "global" like and public property IsAlternateBehavior
is exposed to flag how the method should flow.
Many questions come to mind for me when looking at this implementation. My initial reaction is that this is not a great way to handle this but it works. Is this a known pattern/anti-pattern or bad practice and if so what might an alternative implementation look like? Or is this public flag just fine for many cases?