Design Patterns Part 2

Design Patterns Part 2

Repository

This one clicked for me. You create a repository interface that defines what you need (add, find, update), then a concrete class implements it. Your service takes the interface via DI so the details are hidden away. I think the big win is you can swap implementations later (different DBs, in-memory for tests, etc.) without rewriting the service.

Strategy

This was interesting. You inject a behavior into a class instead of hard-coding it. The example I saw was a payment service that needs to handle different payment types. You define an interface like Pay(), then create implementations (PayPal, Apple Pay, etc.). When you construct the service, you pass in the strategy you want. If you find yourself writing lots of if or switch branches to vary behavior, a strategy might be cleaner.

KATA Learnings

StringBuilder

This is a faster way to build strings because concatenation creates a new string each time. I had seen StringBuilder before but never really used it. I like how you can Append() and keep going (and there are other methods like Clear() and Replace()). For short strings I still just use +, but for loops or larger builds this feels better.

Char vs String

I never really thought about the difference: 'A' is a char and "A" is a string. In Python and JavaScript there's no difference between single and double quotes, so this tripped me up in C#. I am trying to be more deliberate about it now.

Comments

No comments yet.

Add a comment