Sunday, October 9, 2016

C# Generics

C# Generics

Generics allow us to treat different types and classes similarly through the power of type parameters. For example, rather than defining the same method across multiple classes, we can define a single class that can take in multiple types in a single location. Hopefully the examples provided below can help illuminate exactly what I'm talking about.

Let's say we have a backpack that we put a bunch of stuff into. Books, pencils and notebooks, for example. We might make a class Backpack like this:
public class Books
    {
        private Collection<Book> BookCollection;
        public void Add(Book book)
        {
            this.BookCollection.Add(book);
        }
    }
    public class Pencils
    {
        private Collection<Pencil> PencilCollection;
        public void Add(Pencil pencil)
        {
            this.PencilCollection.Add(pencil);
        }
    }

Can you see something wrong here? We have 3 methods with the same exact name, and they are all adding something of some type to that type's collection. This is a serious violation of DRY. Why do we have to do this though? Because C# requires us to define what we are performing the action on - it has not idea what's going on otherwise. So how can we reduce our code footprint while simultaneously giving C# something to define? Generics.

Rather than having to create a separate, unique list for each one of our classes - we can simply make a GenericList class that creates a new list upon instantiation. We defer type specification until instantation without the cost or risk of runtime casts or boxing operations.

public class GenericList<T> : IEnumerable
    {
        private Collection<T> GenericCollection;
 
        public IEnumerator<T> GetEnumerator()
        {
            return this.GenericCollection.GetEnumerator();
        }
 
        IEnumerator IEnumerable.GetEnumerator()
        {
            throw new NotImplementedException();
        }
    }

public class TestClass
    {
        static void Main()
        {
            var bookCollection = new GenericList<Books>();
            var pencilCollection = new GenericList<Pencils>();
            bookCollection.GetEnumerator();
            pencilCollection.GetEnumerator();
        }
    }


Once we have that, we can use a GenericList where ever and whenever - this gives us more flexibility and reduces the amount of code. Generics can be seen as an instance of composition, whereby we extract some common behavior or property from classes. This is especially useful for collections of different data types, such as Dictionaries. Typically, we use generics more often than creating them - regardless, generics are a great way to reuse code and improve performance, specifically by avoiding boxing/unboxing and casting operations.

Sunday, October 2, 2016

Pillars of OOP

Pillars of OOP

Object-oriented programming is a programming paradigm of focusing code towards the construction and treatment of objects, or instances of classes. This mechanic is illustrated through features (pillars) which is important to understand and implement in order to minimize bugs, reduce complexity and create quality code!

Encapsulation:
Separate concerns. The waiter shouldn't care how the chef is making food, just that he makes it and the same holds that the chef shouldn't care how the waiter is delivering food, just that he's doing it. The implementation of a procedure should not be shared with other blocks of your code - they should remain separate and should interact minimally.

  • Prevents unintended consequences of changing code in one place.
  • Loosely coupled code for maintainability.
  • Examples: 
    • Access Modifiers (Public, Private, Protected, Internal, Protected Internal)
    • Accessors (get; set;)
Inheritance:
Code re-usability. You shouldn't have to redefine an entire set of properties and methods for classes that are similar - instead, you should structure the code so that classes inherit from other classes in order to reduce the amount of code written. Classes that have a similar relationship, either through properties or behavior, should have an explicitly defined relationship that allows one to 'inherit' from the other. Based on a "Is a" relationship.

  • Reduces code count
  • Improves structure and organization, leading to improved readability.
  • Examples:
    • The ":" operator extends a derived class (left) from a base class (right)
    • "is" and "as" keywords for casting (also upcasting and downcasting)

Polymorphism
Extract and distribute commonalities. The term derives from the ability to use the same name for what may be different actions on objects of different types. Humans can walk and so can dogs. We can abstract this commonality out from both, make a class called Walkability and extend it to classes that can walk. This explicit relationship means that humans and dogs can walk because they extend Walkability. This is typically done through interfaces or virtual methods - they act as a contract guaranteeing a specific function. The way that humans walk is different from dogs, but they still walk - same thing is applied here: while the implementation is different, we still guarantee that humans can "walk" and dogs can "walk". Based on a "has a" relationship.

  • Loosely coupled code for maintainability.
  • Flexibility to change commonalities among separate types
  • Reduce code count
For some, there is a fourth pillar (data abstraction), but I've decided to make a separate blog post on that so that I can explain why some include it and some don't, while also covering what it is.

Summary: Understand your pillars so that you can take full advantage of OOP to write better code.

Saturday, October 1, 2016

Static vs Instance C#/JS

Welcome back! I've finally found some time to myself to continue this blog. Also, I have become hopelessly overwhelmed with the subtle differences between C# and Javascript, so I will attempt to overcome that mountain, and maybe you'll learn something new (or correct me!).

Static Method vs. Class/Instance/Non-static methods

2 cent summary
So we need to first establish a key difference: classes outline the characteristics (properties) and behaviors (methods) of a construct. Functions that are defined within classes (methods) are specific to the instances of that class - they cannot be called without an instantiation of that class. Static methods are essentially type functions that can, within limits, be called at any point without the need of an object or instance, so long as the type is available.

C#
What are static methods? Basically, they are functions that are available without the instantiation of an object or instance from a class - which makes a lot more sense having been exposed to a language like C# or Java. An example of a static method is System.Diagnostics.Debug.WriteLine(). Ever notice how you can call this function without instantiating System.Diagnostics.Debug()? Probably not, because that wouldn't make sense right? Well, this is an example of a static method - it's a function attached to the type itself rather than an instantiation/object.

Javascript
However, coming from my JS roots, what does this mean? Well, Classes are not really a syntactic thing (at least not in ECMA5), but depending on your design and instantiation pattern, you can mimic this mechanic. Through a constructor function, you can call methods specific to that instance (either internally or externally) while also attaching methods to the constructor itself (static methods).

Example:
var Person = function(name, age) {
  this.name = name;
  this.age = age;
  this.introduce = function() {
    console.log("Hello, my name is " + this.name);
  }
}
Person.AnswerToUniverse = function() {
  console.log("42");
}
var Cameron = new Person("Cameron", 27);
//Static Method:
Person.Answer();

//Instantiation Method:
Cameron.yell();

Summary
Static methods are functions attached to type, instance/class methods are attached to instances/objects.

EDIT: OH GAWD, I WAS SO WRONG!!! Fixed.















Reference
https://www.youtube.com/watch?v=53LWUQVyZb8