فهرست منبع

More blog post exports

Steffen Cole Blake 4 سال پیش
والد
کامیت
15a3ca8c9a

+ 224 - 0
content/post/dependency-injection/dependency-injection-part-0.md

@@ -0,0 +1,224 @@
++++
+author = "Steffen Blake"
+title = "Dependency Injection Part 0"
+date = "2021-08-28"
+description = "Whats the Deal?"
+tags = [
+    "csharp",
+    "dotnet",
+    "DependencyInjection"
+]
+categories = [
+    "DependencyInjection"
+]
+series = ["DependencyInjection"]
+aliases = ["DI-Part-0"]
++++
+
+Part 0: What's the deal? <-- (You are here!)
+
+[Part 1: Bootstrapping](/post/dependency-injection/dependency-injection-part-1)
+
+[Part 2: Extensions](/post/dependency-injection/dependency-injection-part-2)
+
+So, you’ve heard your coworkers, peers, or anonymous internet friends mention Dependency Injection. Sometimes off the cuff as part of a sentence filled with other magic tech mumbo jumbo.
+
+It sound’s pretty cool though, right? ’Dependency Injection', you’re veritable key to the programmer’s castle. It must be important to your code, right?
+
+Well, not really. In fact, for a large quantity of code architecures, especially Functional Programming, Dependency Injection is out of the question since it goes against the very principle of your language.
+
+But if you’re using an Object Oriented Architecture like C# or Java, well, now we are talking.
+
+Let’s start by seeing what the internet has to say about DI (what we will refer to Dependency Injection by from now on because, well, we programmers love our Achronyms.
+
+> “In software engineering, dependency injection is a technique whereby one object (or static method) supplies the dependencies of another object. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it.” - Wikipedia
+
+Well alright thats pretty straightforward. Except probably not, right? So what does all of that mean?
+
+Well, to start, hopefully if you’re here reading this you’re at least familiar with things like classes, constructors, 'new’ing up something, instantiation, etc.
+
+If not, go learn all those things first and come back please.
+
+So I’ll assume you’ve got the basics and you’re ready for taking on some real programming architectures.
+
+To start, consider you’re making a videogame, and you have the following `Character` class representing a character, and a static class called `AttackService` you use for, stuff or whatever:
+
+```csharp {linenos=table}
+public class Character {
+    ...
+     public int PerformAttack(Enemy enemy) {
+        var damage = AttackService.CalculateDamage(this, enemy);
+        return damage;
+     }
+     ...
+}
+```
+
+Well, an experienced programmer will quickly alert you to the fact that simply using Static classes with Static methods is cumborsome, hard to maintain, requires loading things up front even if you don’t need it, hard to unit test properly… It’s a headache. Ok so you move to having `AttackService` as a non static class, your `Character` class probably looks like this now…
+
+```csharp {linenos=table}
+public class Character {
+    private AttackService AttackService { get; } = new AttackService();
+    ...
+     public int PerformAttack(Enemy enemy) {
+        var damage = AttackService.CalculateDamage(this, enemy);
+        return damage;
+     }
+     ...
+}
+```
+
+Better, right? Well sure maybe, if you’re okay with the fact that if someone accidently breaks `AttackService`.`CalculateDamage`, any unit tests for methods that call `AttackService.CalculateDamage` will also false flag as broken too, making it hard for you to zero in on where the real problem was.
+
+Ok, so how do you get around this? How could you possibly have a class use another class, without breaking when that class breaks? Enter dependency injection (and hand in hand with it, Mocking Unit Test architecture!)
+
+# How To Inject
+So step one is, chances are your Object Oriented language of choice has something along the line of interfaces, which are effectively contracts you sign your classes up for that say “My class will have these publically exposed things at minimum”
+
+So lets start by making the `IAttackService` interface, which has that public method on it, and bind it to our `AttackService` implimentation.
+
+```csharp {linenos=table}
+public interface IAttackService {
+    int CalculateDamage(Enemy enemy, Character character);
+}
+
+public class AttackService : IAttackService {
+    public int CalculateDamage(Enemy enemy, Character character) {
+        // Magic logic goes here or whatever, not important!
+    }
+}
+```
+
+Ok cool, that doesn’t look like it changed anything, right? Wrong! See the thing about `IAttackService`, is it has no idea what `CalculateDamage` actually does, nor does it care what `CalculateDamage` does. Which might start giving you the hint about what we are going to do next… One little tweak to our `Character` class and…
+
+```csharp {linenos=table}
+public class Character {
+    private IAttackService AttackService { get; }
+    public Character(IAttackService attackService) {
+        // Always do null checks with DI!
+        if (attackService = null) throw new NullReferenceException(nameof(attackService));
+        
+        AttackService = attackService;
+    }
+    
+    ...
+     public int PerformAttack(Enemy enemy) {
+        var damage = AttackService.CalculateDamage(this, enemy);
+        return damage;
+     }
+     ...
+}
+```
+
+Now you’ll probably notice, when you need to ‘new’ up a Character you’ll have to do it like this now:
+
+```csharp {linenos=table}
+    var steve = new Character(new AttackService());
+```
+
+And that, my dear reader, is `Dependency Injection`. Character class is Dependant on `IAttackService`, but you have `Injected` it through the `Constructor`
+
+This type of Dependency Injection is called `Constructor` Dependency Injection.
+
+If you wanted the Dependency to be optional, perhaps with a default, you also could do Property Injection like so:
+
+```csharp {linenos=table}
+public class Character {
+    private IAttackService AttackService { get; private set; }
+    ...
+     public int PerformAttack(Enemy enemy) {
+        if (AttackService == null) throw new NullReferenceException(nameof(AttackService));
+        var damage = AttackService.CalculateDamage(this, enemy);
+        return damage;
+     }
+     ...
+}
+...
+    var steve = new Character { AttackService = new AttackService() };
+...
+```
+
+Which also works fine. But we’ll just stick with Constructor Injection for now because, in my opinion, it’s cleaner and easier to maintain.
+
+Congratulations, you now understand the basic of DI!
+
+#But why?
+Ok fair question, so consider now you want to unit test `Character` class without fear that your unit tests will fail. Well, rather than just injecting the usual `AttackService`, what if you constructed a dummy ‘fake’ one that just did everything in a simple, predictable way? And that fake service only existed inside of your unit test scope, so no one outside of it could accidently use it?
+
+Welcome dear reader, to the wonderful world of Mocking! You would do it in our example as simple as this:
+
+```csharp {linenos=table}
+[TestFixture]
+public class CharacterTests {
+
+    internal class MockAttackService : IAttackService {
+        public int CalculateDamage(Enemy enemy) { return 42; }
+    }
+
+    [Test]
+    public void PerformAttackTests() {
+        var mockAttackService = new MockAttackService();
+        
+        var testSteve = new Character(mockAttackService);
+        var enemy = new Enemy();
+        
+        Assert.That(testSteve.PerformAttack(enemy), Is.EqualTo(42));
+    }
+}
+```
+
+Boom, easy as that! You could even do something fancy like, perhaps add the following to your MockAttackService…
+
+```csharp {linenos=table}
+internal class MockAttackService : IAttackService {
+    public int CalculateDamageCalls { get; set; } = 0;
+
+    public int CalculateDamage(Enemy enemy) { 
+        CalculateDamageCalls++;
+        return 42; 
+    }
+}
+```
+
+And take your Unit test to the next level by validating your Dependency usage!
+
+```csharp {linenos=table}
+public void PerformAttackTests() {
+    var mockAttackService = new MockAttackService();
+        
+    var testSteve = new Character(mockAttackService);
+    var enemy = new Enemy();
+        
+    Assert.That(testSteve.PerformAttack(enemy), Is.EqualTo(42));
+    
+    // Dependency Usage Validation whoo!
+    Assert.That(mockAttackService.CalculateDamageCalls, Is.EqualTo(1));
+}
+```
+
+# Muh News!
+Ok so this all seems pretty awesome so far, but now let me show you the big ugly truth to dependency injection, and how modern programming has solved it. Imagine you have a rather large program with many many lines of code, hundreds of classes, and lots of nested dependencies.
+
+Suddenly, simply naively 'new’ing up a new class with deep nested dependencies could look as nasty as this:
+
+```csharp {linenos=table}
+var myFooService = new FooService(new barService(new phiService(), new phiLogger()), new derpService(new herpService()));
+```
+
+Oh geez! This is really starting to get out of hand now. But you probably are noticing that, hey, all of this dependency injection just looks the same all the way down. What if there was an easy way to just automatically construct all these things? Like some kind of magical `Service Container` that had everything we could ever use setup in it, and when we asked for one it automatically injected everything for us all the way down the chain…
+
+Maybe our magical code then would just become:
+
+```csharp {linenos=table}
+var myFooService = ServiceContainer.Get<IFooService>();
+```
+
+Well, this exists, in many different versions. `Autofac`, `Ninject`, `ServiceCollection`, the list goes on and on.
+
+This is called a Dependency Injection `Container`, and you generally set it up by first registering all the classes it should know about at the start of your program, and once those are ‘logged’ into it, you can just summon them back out at will later.
+
+Pretty neat, huh?
+
+Lets make one.
+
+Which will lead us on to [Part 1!](/post/dependency-injection/dependency-injection-part-1)

+ 226 - 0
content/post/dependency-injection/dependency-injection-part-1.md

@@ -0,0 +1,226 @@
++++
+author = "Steffen Blake"
+title = "Dependency Injection Part 1"
+date = "2021-09-04"
+description = "Bootstrapping"
+tags = [
+    "csharp",
+    "dotnet",
+    "DependencyInjection"
+]
+categories = [
+    "DependencyInjection"
+]
+series = ["DependencyInjection"]
+aliases = ["DI-Part-1"]
++++
+
+[Part 0: What's the deal?](/post/dependency-injection/dependency-injection-part-0)
+
+Part 1: Bootstrapping <-- (You are here!)
+
+[Part 2: Extensions](/post/dependency-injection/dependency-injection-part-2)
+
+### Note: This project will be done entirely in C#, if you want to follow alone in your own language like Java, you will probably need to do some googling on how to perform specific parts where I reference .Net specific libraries. Ill try to only do this when absolutely necessary.
+
+To start, ensure you have Visual Studio 2017 installed, you can get a free copy of the Community Edition [here](https://www.visualstudio.com/).
+
+Next, use whatever your preferred Git tool is and download a copy of the starter repo.
+
+[Github](https://github.com/SteffenBlake/TStore/tree/Dependency-Injection-Part-1)
+
+[Direct Link](https://github.com/SteffenBlake/TStore.git)
+
+You should be able to follow along with my Commits to the repo as we go, just take a look at the commits to master to get an idea for it. It should be noted you *will not be able to push anything to these branches, of course. If you want to use source control you will of course need to fork the repo in order to actually commit.
+
+This, of course, won’t be necessary, but I am still expecting to see dozens of forks of the project without any commits anyways because such is GitHub. Anyways.
+
+# Step 1: Organization
+
+I like to use the following organization for my projects, my main project just has the usual name and houses all the standard logic, classes, etc. The ‘Tests’ project will have all of our Unit tests (we’ll get to that later) and the Example project is for people to look at to get a feel for how to use the project.
+
+To begin, lets make some folders in the main ‘TStore’ project to start out organized. It should look something like this
+
+![Organization](/images/dependency-injection-part-1/organization.jpg)
+
+* Extensions: This will be the folder we put any static class extensions of interfaces/classes
+* Implementations: We will put our classes in here
+* Interfaces: As the name implies, all interfaces go in here
+* Utilities: This last folder will just hold the various other stuff that doesnt fit anywhere particular. Constants, Enums, etc.
+
+This is how I like to organize myself in C# but you are more than welcome to do it your own way, whatever works for you!
+
+So to start let’s start by breaking down the usual DI Container flow.
+
+Step 1: Instantiate a new DI Container with some form of Configure class system, which is used to start setting everything up.
+Step 2: Call some form of `Get` method on the container, passing in a type, and it will try and find something registered to that type based on prexisting config
+
+And that’s really all there is to it! It’s really simple actually, so let’s start by defining our interfaces and implementing them. We probably also want a means to check if something is registered already and the ability to unregister an object from a type as well!
+
+```csharp {linenos=table}
+public interface ITStore
+{
+    bool IsRegistered(Type type);
+    void Register(Type key, Type value);
+    void UnRegister(Type type);
+    object Fetch(Type type);
+}
+```
+
+```csharp {linenos=table}
+public class TStore : ITStore
+{
+    public virtual void Register(Type type, object entity)
+    {
+        throw new NotImplementedException();
+    }
+    
+    public virtual void UnRegister(Type type, object entity)
+    {
+        throw new NotImplementedException();
+    }
+
+    public virtual bool IsRegistered(Type type, object entity)
+    {
+        throw new NotImplementedException();
+    }
+
+    public virtual object Fetch(Type type)
+    {
+        throw new NotImplementedException();
+    }
+}
+```
+
+Easy enough. The `Register` methods for the `Store` are all pretty straightforward. We want to use a dictionary which holds a list of mapped types really, and thats about it.
+
+```csharp {linenos=table}
+private readonly Dictionary<Type, Type> Entities = new Dictionary<Type, Type>();
+
+public virtual void Register(Type key, Type value)
+{
+    Entities[key] = value;
+}
+
+public virtual void UnRegister(Type type)
+{
+    Entities.Remove(type);
+}
+
+public virtual bool IsRegistered(Type type)
+{
+    return Entities.ContainsKey(type);
+}
+```
+
+Now for the tricky part, the `Fetch` method. The key to this will be two .Net system methods (This part in particular you will have to look up how to do in other languages since they will probably be very different from C#)
+
+First, `Type.GetConstructors`, which gets us a list of `ConstructorInfo` objects, which contains a list of `ParameterInfo` objects, which we can fetch those types from, and recursively call Fetch on those ones once we find the best match.
+
+Second, `System.Activator`, which is the global machine that builds instances of all objects in your program, we’re going very low level here and calling it directly. You can pass in a list of params you know and it will find the best constructor matching those params, but we’ll do a bit of pre-caching here to help that speed up.
+
+It sounds like a bit much but this is basically the entire DI container and after this step, our DI system will be completely functional already!
+
+```csharp {linenos=table}
+// Our Cache of pre-compiled Entities
+private readonly Dictionary<Type, object> CompiledEntities = new Dictionary<Type, object>();
+public virtual object Fetch(Type type)
+{
+    // Short circuit out if we've already cached this type
+    if (CompiledEntities.ContainsKey(type))
+        return CompiledEntities[type];
+
+    if (!Entities.ContainsKey(type))
+        throw new KeyNotFoundException($"No Registered key for {type.Name} found.");
+
+    // Actual type we mapped to that we will now construct
+    var targetType = Entities[type];
+
+    // Type[][] Matrix
+    var constructors = targetType
+        .GetConstructors()
+        .Select(c => 
+            c.GetParameters()
+            .Select(p => 
+                p.ParameterType
+            ).ToArray()
+        ).ToArray();
+
+    // Our best match Type[] Array
+    var bestConstructor = constructors
+        // Grab constructors we have every param known in our Entities
+        .Where(c => c.All(p => Entities.ContainsKey(p)))
+        // Grab the first one with the biggest constructor
+        .OrderByDescending(c => c.Length).FirstOrDefault();
+
+    if (bestConstructor == null)
+        throw new KeyNotFoundException($"No valid constructor found for {type.Name}");
+
+    // Fetch all the entities for those params Recursively
+    // Compiling Type[] into object[]
+    var constructorParams = bestConstructor.Select(Fetch).ToArray();
+
+    // Use System to build an instance of our type(s) from scratch
+    var entity = Activator.CreateInstance(targetType, constructorParams);
+
+    // Cache this for later ease of access
+    CompiledEntities[type] = entity;
+
+    return entity;
+}
+```
+
+Step 2: Try it out!
+At this point we have a functional DI Container, you can test this out by creating the following services Implementations + Interfaces in your Example project (Make sure you’re Example project has a reference to the Core Project!):
+
+```csharp {linenos=table}
+public interface IConsoleService
+{
+    void PrintHelloWorld();
+}
+
+public interface IHelloWorldService
+{
+    string GetHelloWorld();
+}
+
+public class ConsoleService : IConsoleService
+{
+    private IHelloWorldService HelloWorldService { get; }
+    public ConsoleService(IHelloWorldService helloWorldService)
+    {
+        HelloWorldService = helloWorldService;
+    }
+
+    public void PrintHelloWorld()
+    {
+        var message = HelloWorldService.GetHelloWorld();
+
+        Console.WriteLine(message);
+    }
+}
+
+public class HelloWorldService : IHelloWorldService
+{
+    public string GetHelloWorld() => "Hello World!";
+}
+```
+
+And finally we will `Register` these two services in our Main method and use them, and if all worked well we should see ‘Hello World!’ on our console!
+
+```csharp {linenos=table}
+static void Main(string[] args)
+{
+    var store = new TStore.Implementations.TStore();
+    store.Register(typeof(IConsoleService), typeof(ConsoleService));
+    store.Register(typeof(IHelloWorldService), typeof(HelloWorldService));
+
+    var consoleService = (IConsoleService) store.Fetch(typeof(IConsoleService));
+
+    consoleService.PrintHelloWorld();
+
+    Console.ReadKey();
+}
+```
+
+Thanks for reading and check out [Part 2](/post/dependency-injection/dependency-injection-part-2) where we build a bunch of handy extension methods for our interface to make life a lot easier (and make our example look a lot less messy!)

+ 172 - 0
content/post/dependency-injection/dependency-injection-part-2.md

@@ -0,0 +1,172 @@
++++
+author = "Steffen Blake"
+title = "Dependency Injection Part 2"
+date = "2021-09-10"
+description = "Extensions"
+tags = [
+    "csharp",
+    "dotnet",
+    "DependencyInjection"
+]
+categories = [
+    "DependencyInjection"
+]
+series = ["DependencyInjection"]
+aliases = ["DI-Part-2"]
++++
+
+[Part 0: What's the deal?](/post/dependency-injection/dependency-injection-part-0)
+
+[Part 1: Bootstrapping](/post/dependency-injection/dependency-injection-part-1)
+
+Part 2: Extensions <-- (You are here!)
+
+If you would like to catch up to where we are at now, you can checkout the git and start on the branch ‘Dependency-Injection-Part-2’, which is where we left off on the end of Part 1
+
+[Github](https://github.com/SteffenBlake/TStore/tree/Dependency-Injection-Part-2)
+
+[Direct Link](https://github.com/SteffenBlake/TStore.git)
+
+# Interface Extension Practices
+Before we begin, I’ll go into the basics of why we are about to do the following coding choices below. What our end goal is is to have the following methods on our `ITStore` object that make life much easier for us, since the current methods are very low level and granular. Also a pain to use.
+
+```csharp {linenos=table}
+void Register(Type type);
+void Register<TKey, TValue>();
+void Register<T>();
+
+T Fetch<T>();
+```
+
+Now, you’re first instinct will be to add these directly to your `ITStore` interface and implement them on your `TStore` class, and albiet its not a necessarily bad approach, if we want anyone to ever be able to extend or make their own versions of our logic, we can do much better.
+
+To start, take a look at probably what happens when you logically work through these new methods what you end up with, based on our original function on `TStore(Register(Type, Type))`
+
+```csharp {linenos=table}
+public void Register(Type type) => Register(type, type);
+public void Register<TKey, TValue>() => Register(typeof(TKey), typeof(TValue));
+public void Register<T>() => Register<T,T>();
+
+public T Fetch<T>() => (T)Fetch(typeof(T));
+```
+
+Notice how all these new methods just do a tiny bit of work and delegate the real work back off to our original methods? Anytime you see this pattern emerge you can pretty safely go with the Extension Pattern instead.
+
+Then, when someone else wants to extend functionality of `TStore`, or make their own version of it as a middleware, instead of having 5 methods to fill out, they just need to fill out the original 2 and the Static Extensions we make will keep working for them.
+
+# Step 1: Simple Extensions
+So to start, we basically just want to apply the same code we had above, except as a static class with static extension methods, which is easy. Make sure you refer to the `ITStore` interface when extending, and not the `TStore` class!
+
+```csharp {linenos=table}
+public static class ITStoreExtensions {
+    public static void Register(this ITStore store, Type type) => store.Register(type, type);
+    public static void Register<TKey, TValue>(this ITStore store) => store.Register(typeof(TKey), typeof(TValue));
+    public static void Register<T>(this ITStore store) => store.Register<T,T>();
+    
+    public static T Fetch<T>(this ITStore store) => (T)store.Fetch(typeof(T));
+}
+```
+
+# Step 2: Update the Example code
+Now you should be able to modify your code in the example to be much cleaner looking!
+
+```csharp {linenos=table}
+var store = new TStore.Implementations.TStore();
+store.Register<IConsoleService, ConsoleService>();
+store.Register<IHelloWorldService, HelloWorldService>();
+var consoleService = store.Fetch<IConsoleService>();
+consoleService.PrintHelloWorld();
+Console.ReadKey();
+```
+
+And running it should still produce your expected output!
+
+# Step 3: Fixing your type checking
+You may notice however one minor glitch in existing code due to our generics, which we can readily fix however. The following code will, in our architecture’s current state, compile and not warn us we did something wrong:
+
+```csharp {linenos=table}
+store.Register<IConsoleService, HelloWorldService>(); // This should warn us we did something wrong!
+```
+
+Using Generics, we can handle this pretty easily, we just need some minor typechecking validation for our generic methods!
+
+```csharp {linenos=table}
+public static void Register<TKey, TValue>(this ITStore store)
+    where TValue : class, TKey
+    => store.Register(typeof(TKey), typeof(TValue));
+    
+public static void Register<T>(this ITStore store) 
+    where T: class
+    => store.Register<T, T>();
+```
+
+This code addition is pretty straightforward and has 2 parts really.
+
+First off, the class modifer asserts that this generic must be a class, not an interface. You shouldn’t be able to map an interface to an interface, only an interface to a class or a class to a class.
+
+Second, the TKey constraint basically just says ‘Our value must inherit from our key’
+
+Now if you try and do that same broken code from before, the compiler will error and inform you your types don’t match, ~viola`!
+
+# Step 4: Fancy Namespace Registering
+A fancy method lots of DI containers use is registering by namespace. This portion of the work has been easy so far, so I think it’s time for a challenge. Let’s try it out!
+
+This will take some reflection, so our first method we need to use is `GetCallingAssembly().ExportedTypes`, as well as the `IsClass` and `Namespace` property on those types.
+
+`GetCallingAssembly` will load up everything in the assembly of wherever the method was called from, and `ExportedTypes` will whittle us down to only public types. `IsClass` will whittle that further down to specifically, well, classes, and finally we can do pattern matching on the `Namespace` to get the ones we care about.
+
+We also are going to need a way to wildcard match strings, and unfortunately somehow `C#` still doesn’t have such a tool so we’ll need to convert to Regex and use that, so we’ll need the following extension to start (Can be found in multiple varients on StackOverflow from multiple authors):
+
+```csharp {linenos=table}
+public static class StringExtensions
+{
+    public static string WildCardToRegex(this string value)
+    {
+        return "^" + Regex.Escape(value).Replace("\\*", ".*") + "$";
+    }
+}
+```
+
+And we can then use these pieces of the puzzle together to automatically register everything in a namespace with wildcard and regex support:
+
+```csharp {linenos=table}
+public static void RegisterNamespace(this ITStore store, string namespacePattern)
+{
+    // Create our RegexMatch function
+    var regexPattern = namespacePattern.WildCardToRegex();
+    bool NamespaceMatch(string nSpace) => Regex.IsMatch(nSpace, regexPattern);
+
+    // Get all public non-abstract classes that match namespace
+    var targetClasses = Assembly.GetCallingAssembly().ExportedTypes
+        .Where(type => type.IsClass && !type.IsAbstract && NamespaceMatch(type.Namespace))
+        .ToArray();
+
+    // Iterate over each class in these namespaces
+    foreach (var target in targetClasses)
+    {
+        // Direct register
+        store.Register(target);
+
+        // Also register any inheritted public interfaces on that class to it
+        foreach (var interfaceType in target.GetInterfaces().Where(i => i.IsPublic))
+        {
+            store.Register(interfaceType, target);
+        }
+    }
+}
+```
+
+If all went according to plan, we can further simplify the example code now as well.
+
+```csharp {linenos=table}
+var store = new TStore.Implementations.TStore();
+store.RegisterNamespace("TStore.Example.Implementations*");
+
+var consoleService = store.Fetch<IConsoleService>();
+
+consoleService.PrintHelloWorld();
+
+Console.ReadKey();
+```
+
+And that concludes this section for today! Stay tuned for the next part where we delve into multi-registering and injecting arrays and enumerables!

+ 2 - 2
content/post/Async-Event-Stream-for-IoT-Devices-in-.Net-Core.md → content/post/iot/async-event-stream-for-iot-devices-in-net-core.md

@@ -7,10 +7,10 @@ tags = [
     "csharp",
     "dotnet",
     "IoT",
+    "guides"
 ]
 categories = [
-    "Coding",
-    "Guides"
+    "IoT"
 ]
 series = ["IoT"]
 aliases = ["async-events-IoT"]

+ 111 - 0
content/post/neato-burritos/covariance-vs-contravariance.md

@@ -0,0 +1,111 @@
++++
+author = "Steffen Blake"
+title = "Covariance vs Contravariance within Function Scopes"
+date = "2021-08-11"
+description = "A fancy little trick..."
+tags = [
+    "Coding",
+    "dotnet",
+    "csharp"
+]
+categories = [
+    "NeatoBurritos"
+]
+series = ["NeatoBurritos"]
+aliases = ["covariance-vs-contravariance"]
++++
+
+This is a topic I find a lot of C(ish) developers mention offhand. They know it has to do with Generics, inheritance in some way, and In vs Out variables.
+
+But to really dig deep into this topic, we will first need to step into the land of Math. To begin, let’s define two different functions:
+
+```csharp {linenos=table}
+string MakeString<T>(T obj) {
+    ...
+}
+
+T2 MakeT2<T1, T2>(T1 obj) {
+    ...
+}
+```
+
+The first function, `MakeString` displays `Contravariance` in its Generic `T` variable. The reason for this is it has a `T` defined as one of its parameters.
+
+If you were to call it like so in a function:
+
+```csharp {linenos=table}
+var myStringExcplicit = MakeString<int>(5);
+var myStringImplicit = MakeString(5);
+```
+
+Both calls would compile, and if you are using a linting tool, it may even suggest to remove that `<int>` call on the first explicit generic. This is because, implicitly speaking, 5 is an integer by default, so the compiler is smart enough to discern that `T` is actually int specifically here.
+
+Now, lets try and do the same thing but with the second function, MakeT2
+
+```csharp {linenos=table}
+var myStringExcplicit = MakeT2<int, string>(5);
+var myStringImplicit = MakeT2(5);    // This won't compile
+string myStringImplicit = MakeT2(5); // Not even this will either!
+```
+
+In this function, we have the `T2` variable declared as `Covarient`, which means modifying the parameters passed into the function has no implicit effect on its return value.
+
+This can further be demonstrated with our `MakeString` function simply by the following code:
+
+```csharp {linenos=table}
+MakeString(5);
+```
+
+This will even compile, because of the inherent contract all Functions have in C(ish) languages (and pretty much all other languages too), and that is that a `Function` cannot see outside of its own scope. Now I know, in C# you can use `Reflection` and a few tricks to enable seeing outside of a `Function`, (like if, for example, you wanted to get the name of the class or method the function was called within, you can indeed. But such things should be avoided unless its for logging or whatnot.)
+
+This means `Function`s have no concept of whether their return was assigned to anything, what it was assigned to, how it was used, etc. This would require knowledge outside the scope of the function, which breaks a core paradigm of logical coding.
+
+However, this has a very annoying side effect, consider the following function:
+
+```csharp {linenos=table}
+TOut DoTheThing<TIn1, TIn2, TIn3, TIn4, TIn5, TIn6, TOut>
+    (TIn1 in1, TIn2 in2, TIn3 in3, TIn4 in4, TIn5 in5, TIn6 in6) { .... }
+```
+
+Okay first I will say, please avoid making functions like this in the first place, put all those variables in a single class. But lets say that’s not possible here for some crazy reason.
+
+Well the thing about C# (and many other generic based languages) is as soon as you have even one `Covarient` variable in the scope of your function, you have to declare all of the generics of your function explicitly, even all your Contravarient ones!
+
+In other words, you’d have to call it like this:
+
+```csharp {linenos=table}
+int myThing = DoTheThing<int, int, int, int, int, int, int>(1, 2, 3, 4, 5, 6);
+Console.WriteLine($"{myThing}"");
+```
+
+Even though in this case the compiler should know that `T1` through `T6` are ints, because its not sure about that seventh `Covarient` return variable, you have to declare them all.
+
+But fear not, for in times like these, we have one Hail Mary to call upon in many of these same languages, the powerful `out` variable!
+
+If we were to declare the signature of our function like so instead:
+
+```csharp {linenos=table}
+void DoTheThing<TIn1, TIn2, TIn3, TIn4, TIn5, TIn6, TOut>
+    (TIn1 in1, TIn2 in2, TIn3 in3, TIn4 in4, TIn5 in5, TIn6 in6, out TOut out1) { .... }
+```
+
+Then we will in fact be able to safely call it like so, both ways assuming you are post C#7:
+
+```csharp {linenos=table}
+// Pre C#7 inline out vars:
+int out1;
+DoTheThing(1, 2, 3, 4, 5, 6, out out1);
+Console.WriteLine($"{out1}"");
+
+// Post C#7 shortcut (very handy here)
+DoTheThing(1, 2, 3, 4, 5, 6, out int out2);
+Console.WriteLine($"{out2}"");
+```
+
+This is because unlike the return value of the function, `out` vars are explicitly `Contravarient`, in fact if you have used them before, the compiler requires you to assign something to the variable (thus initializing it explicitly as the type defined, even if generic) before the function exits.
+
+Notice above that these out var functions don’t have their generics explicitly defined anymore
+
+This is because they no longer have any `Covarient` variables, which allows this.
+
+A very powerful and handy tool, if you ask me, especially when combined with guard cases.

+ 105 - 0
content/post/opinions/inheritance-vs-composition.md

@@ -0,0 +1,105 @@
++++
+author = "Steffen Blake"
+title = "Inheritance vs Composition"
+date = "2021-08-20"
+description = "Which to use?"
+tags = [
+    "ButThatsJustMyOpinionMan",
+    "Coding"
+]
+categories = [
+    "Opinions",
+]
+series = ["Thoughts"]
+aliases = ["inheritance-vs-composition"]
++++
+
+#### "Composition over Inheritance"
+
+This is a phrase you will eventually hear at your workplace while coding away. Perhaps during lunch break or maybe in the comments of your code review. What exactly does this mean?
+
+Well, in Object Oriented Programming, there really are two ways to relate two types to each other. ‘Is a’ vs ‘Has a’ is often the colloquial.
+
+‘Is a’ implies inheritance. For example:
+
+```csharp {linenos=table}
+public class Warrior : Player {
+```
+
+Implies `Warrior` ‘Is a’ `Player`. Which is fine and all. But lets say now that we want to have rigorous unit testing, and our `Player` Class has a lot of stuff going on already, perhaps a multitude of overridable methods and properties, and Warrior overrides a few.
+
+Well, that is fine, but we will run into a problem. Take this for example:
+
+```csharp {linenos=table}
+public class Warrior : Player {
+    public override void Attack(Target target) {
+        var attack = CalculateAttack();
+        var fMod = CalculateFMod(target.Defense, attack);
+        target.TakeDamage(attack * Constants.A_MOD + fMod * Constants.F2);
+    }
+    ...
+}
+```
+
+At first glance, this method looks fine enough, perhaps it could be structured a bit better, but nothing seems to be terribly wrong with it. But we run our unit tests and, oh no! `WarriorTests_AttackUndead` is failing after our changes earlier today!
+
+Actually wait hold on, so is `RogueTests_AttackUndead`, `PriestTests_AttackLizard` and `BarbarianTests_AttackFlying`, but other similar tests aren’t breaking on other character types, it seems kind of random and sporadic. What happened?
+
+Well turns out it was this line of code: 
+
+```csharp {linenos=table}
+var attack = CalculateAttack();
+``` 
+
+See, `CalculateAttack` is a method inherited from the `Player` base class, and it had a weird bug in it.
+
+But you were not able to instantly tell the source of the bug, because instead of a `PlayerTests_Attack` test, you had a dozen various implementations with their own logic. Owch! Because you ended up making `Player` an abstract class to be inherited from, you couldn’t easily unit test it, not without doing some extra boilerplate. Which is sub optimal…
+
+So, what if instead, your `Character` classes did this instead?
+
+```csharp {linenos=table}
+public class Warrior {
+    
+    private ICharacter Character { get; }
+    
+    public Warrior(ICharacter character) {
+        Character = character;
+    }
+
+    public override void Attack(Target target) {
+        var attack = Character.CalculateAttack();
+        var fMod = Character.CalculateFMod(target.Defense, attack);
+        target.TakeDamage(attack * Constants.A_MOD + fMod * Constants.F2);
+    }
+}
+```
+
+This is Composition vs Inheritance. And now what you have done is made `Character` a normal class, and much easier to unit test.
+
+And furthermore, now you can Mock an `ICharacter` in your `WarriorTests`, so even if `Character` methods break, your `WarriorTests` (and all others for that matter) will not throw up extra flags.
+
+Instead only `CharacterTests` will start breaking, making it very clear and concise exactly what broke and where, significantly decreasing debugging time.
+
+# Inheritance Isn’t all Bad Though
+
+Because as it turns out, there is a clear cut time when you definitely want to inherit. The primary use case is `Serialization`. Whether you have a RESTful interface serializing from JSON, Protobuff handling packets over sockets, or an ORM connected to a SQL DB manipulating entities, Inheritance is probably the right call for any `Data` classes you are handling on these systems when needed.
+
+Let’s consider the following class:
+
+```csharp {linenos=table}
+public class Packet {
+    IPayload Payload { get; }
+    public Packet(IPayload payload) {
+        Payload = payload;
+    }
+    ...
+}
+```
+
+Sure, at first glance, this looks like an easy to unit test class that is loosely coupled to its `Payload`. That’s all fine and dandy, until you try and `Serialize` the darn thing! Since your trying to handle things via `Injection`, many serializing libraries will scoff at your class and inform you it must have a parameterless constructor before they will even entertain the thought of working with the class. Doh!
+
+In this case here, I would just use `Inheritance`.
+
+There are other examples of course, but realistically speaking this is the most common one I see. Too many people are far too willing to go all the way one direction or the other, claiming Inheritance vs Composition always does and will have a better choice.
+
+But I disagree. There are times when one shines over the other and, like most things in programming, its all about using the right tool for the job.

+ 2 - 2
content/post/why-you-dont-need-a-bootcamp.md → content/post/opinions/why-you-dont-need-a-bootcamp.md

@@ -5,11 +5,11 @@ date = "2021-09-18"
 description = "I keep seeing people jump to recommending code bootcamps..."
 tags = [
     "ButThatsJustMyOpinionMan",
+    "StoryTime",
     "Coding"
 ]
 categories = [
-    "Opinions",
-    "Coding"
+    "Opinions"
 ]
 series = ["Thoughts"]
 aliases = ["async-events-IoT"]

BIN
static/images/dependency-injection-part-1/organization.jpg