Let’s make C# code complexer !
--
Guten Tag, C# people! Ever felt that your code was too einfach (simple)? Fret not! Let’s embark on a journey to make your code a tad bit more kompliziert (complicated) than it needs to be. Why? Well, because we can.
Abstract, Abstract, and… Abstract some more!
Remember those basic integer operations? Let’s wrap each one in its own class.
interface IOperation
{
int Execute(int a, int b);
}
class Addition : IOperation
{
public int Execute(int a, int b) => a + b;
}
Now, how about that abstract factory?
abstract class OperationFactory
{
public abstract IOperation Create();
}
class AdditionFactory : OperationFactory
{
public override IOperation Create() => new Addition();
}
Throw Exceptions for Everything!
Remember the simple days when you’d just log an error or, dare I say, use a simple if-condition? Those days are überholt (outdated)! In our quest to make things unnecessarily kompliziert, we shall ensure every unforeseen circumstance is dealt with a dramatic exception.
public void CheckInput(string input)
{
if (string.IsNullOrEmpty(input))
throw new Exception("Nein! Input should not be empty.");
if (input.Length > 100)
throw new Exception("Nein! Input is too lengthy.");
if (!input.All(char.IsLetter))
throw new Exception("Nein! Input should only contain letters.");
}
Not sure if a number is zero? Let’s not check with a simple if condition.
public int Divide(int a, int b)
{
if (b == 0)
throw new Exception("Nein! Division by zero.");
return a / b;
}
Now, every time you call a function, you’ll live on the edge. It’s like walking on a tightrope over an abyss of exceptions waiting to erupt. Living on the edge… coding style!
Never Use Simple Data Types!
Replace an integer with this:
class ComplexInteger
{
public int Value { get; set; }
public string StringRepresentation => Value.ToString();
public string BinaryRepresentation => Convert.ToString(Value, 2);
public DateTime LastModified { get; private set; } = DateTime.Now;
public void UpdateValue(int newValue)
{
Value = newValue;
LastModified = DateTime.Now;
}
}
Invoke Delegates for the Sake of It!
Instead of a simple logic:
public void Print(string message)
{
Console.WriteLine(message);
}
Let’s use a delegate:
delegate void PrintDelegate(string message);
PrintDelegate printer = (msg) => Console.WriteLine(msg);
printer.Invoke("Hello, Delegate World!");
Use the Most Verbose Syntax
Instead of:
var numbers = new List<int> { 1, 2, 3 };
var squared = numbers.Select(x => x * x);
Go for:
var numbers = new List<int> { 1, 2, 3 };
var squared = numbers.Select(delegate(int x) { return x * x; });
To round it all up, if someone asks why your code resembles a twisted labyrinth from an old German castle, just flash your most confident smile and say: “Because it’s more fun that way!”
And, dear readers, after all this needless complexity, this is what we call ‘over engineering’.