Pages

Tuesday, August 9, 2016

c# Dependency Injection

Dependency Injection is a way to implement the Inversion of Control (IOC) principle. 

Start of app, need to configure container. One option is to create a class to configure (register interfaces to implementations). 

Benefits of Dependency Injection.

A) Unit testing. Can now mock implementations for interfaces. So instead of actually Saving data, it mocks a successful save. Instead of reading data, it mocks returned data. In the unit test, you can Verify that each call is done. Can check logged messages. 

B) Able to change code implementations later. Without changing the "internal" code. Just change the container to register the interface to the new implementation (new class) ... existing code should work as is. This decoupling of code makes large applications very modular and flexible. It is now plug and play. 

Types of DI:

1) Constructor Injection (most popular)

public class InjectedClass
{
    private IDepInterface _iDependInterface;

    public InjectedClass(IDepInterface myInterface)
    {
        _iDependInterface = myInterface;
    }
}


2) Property Injection (applied at the property level)
 
private IDepInterface _myProp;

public IDepInterface MyDependencyProperty
{
     get { return ths._myProp;  }
    set { this.myProp = value;  }
}


3) Method Injection (when entire class doesn't need dependency, but just that one method)

public class InjectedClass
{
     readonly IDepInterface _iDependencyInterface;
  
    public MyMethod(IDepInterface myInterface)
    {
        // use myInterface
    }
}

SOLID


https://www.youtube.com/watch?v=gwIS9cZlrhk


Single Responsibility Principle - a function should only have one reason to change

OC Principle - a class should be open for extension but closed for modification. Once a class is done, it is done (unless there is a bug).

Meyer: Derives from requirements for the code. If requirements change, instead of changing the class, make a new class that inherits from the old class. Make the changes in the new class instead and leave the old class untouched. If you make the method in the old class "virtual", then you can "override" the method in the new class.

Massive question: how much of the class do you make "virtual". Very difficult to answer because once its coded, you are not supposed to go back and change from "virtual" to not "virtual" and vice versa.

Also, sometimes its hard to determine if its a bug or feature change.

Upside: if you code something and build a bunch of unit tests, if the code requirements change and you recode the logic, then the unit tests need to be redone. However, using OCP, because you don't change the original class, there is no need to redo existing tests. Instead, create a new class (which inherits from the old class) and therefore, you only need to create a new unit test of the new class.

Polymorphic: instead of Meyer method, create an abstract base class or an Interface and build new implementations as needed and plug in.

How to get it to work with abstract classes (AC) or interface? Since you are not inheriting, you have to really know what your AC or interface is supposed to be doing.

Both Meyer and Polymorphic hold that the original class should not need to be modified (unless there is a bug) to implement changes or to extend the original requirements.

BENEFIT: you don't change code once it works. Then you don't break code that is working.

Liskov Principle (about 29 min)

Tuesday, April 26, 2016

c# try and catch

DO NOT DO THIS. If an exception is thrown in CallMethod() and it gets bubbled up to this try/catch, you must use “throw;” to rethrow the exception. “throw;” will preserve the stack trace while “throw ex;” will make it look like the exception originated here. This can cause much confusion when trying to debug exception statements.

try
{
    CallMethod();                         
}
catch (Exception ex)
{
    SMXLog.LogException(ex);
    throw ex;
}



 If all that is happening in the catch block is a re-throw, then you do not need this Try/Catch at all. The try/catch is redundant and does nothing extra. In the above example, it is ok to use a try/catch with “throw;” because the catch block is Logging (doing something).

try
{
   CallMethod();                      
}
catch (Exception ex)
{
    // If the only thing being done in the Catch block is a re-throw,
    // then the entire try/catch block is redundant/not needed.
    throw;  
}


     https://stackoverflow.com/questions/881473/why-catch-and-rethrow-an-exception-in-c (good overview)

http://stackoverflow.com/questions/22623/throwing-exceptions-best-practices

using just "throw" will only bubble up a message that an exception occurred at the "throw" line rather than the actual line where exception occurred.

using "throw new exception" will preserve the stack trace with exact line of fault. but need to use parameters that allow the details to bubble up.

both examples work. first is if you want to include some extra detail but not necessary as each displays a very detailed message.



Thursday, December 17, 2015

c# extension methods

C# EXTENSION METHODS – add methods, that currently do not exist, to a class . Example, can add methods to the String class. Must be declared in a static class with static methods. This example extends the DateTime class. 


EXTENSION METHOD CREATED

Add caption






EXTENSION METHOD USAGE

Sunday, October 25, 2015

Delegates and events

A delegate in c# are variables that hold a reference to a function. It can reference more than one function (multicast). When the delegate is called, it will invoke all functions assigned. If return values are given, the return value of the delegate will be from the last function invoked.

Example:

public delegate string MyDelegate();

MyDelegate myDel = SomeFunction;   // this is short hand. Might see "new MyDelegate(SomeFunction)"

myDel += AnotherFunction;  // multicasting. Adding additional functions. 


var return = myDel();  // both functions will be invoked but return will hold "another"


public string SomeFunction()
{
    return "some";
}

public string AnotherFunction()
{
    return "another";
}


Rules can bend for delegate signature matches. It is a result of inheritance,

The delegate return value must match the return type of the function assigned to the delegate except in cases of covariance. Covariance is when the return type (Dog) of the function is derived from the return type (Animal) of the delegate. 

COVARIANCE:

delegate Animal MyCovarDelegate();     

MyCovarDelegate myCovDel = FindDog;

public Dog FindDog();  // Dog (function return type) is derived from Animal (delegate return type)

public class Animal
{
    public string type;
    public boolean mammal;
}

public class Dog : Animal
{
    public string breed;
}


The delegate parameter type must match the parameter type of the function except in cases of contravariance. Contravariance is when the param type (Dog) of the delegate is derived from the param type (Animal) of the function. It is reverse/contra of covariance. 

CONTRAVARIANCE:

delegate void MyContraDelegate(Dog d); // Dog (delegate param type) is derived from Animal (function return type)

MyContraDelegate myConDel = ViewDog;

public void ViewDog(Animal a); 


Why Delegates?

1) Is used to handle events (shown below).
2) Allows programs to run methods at run time without knowing the methods at compile time.
2a) Objects can be decoupled between publishers and subscribers. Publisher has no idea who is subscribing nor what the subscriber is doing. It simply creates an event, when the event is raised, it checks to see if there are any subscribers. If subscribers, then it runs the EventHandler (which contains a list of methods (points to methods) that are set to run).
2b) By creating a new class and simply subscribing to the existing event that is published, you can add new classes and attach to events without modifying the original code. Hence, less chance of code breakage. 
3) Achieves Inversion of Control (IOC) when a framework/library wants to call you.
4) Can pass delegates as a parameter to a function.


public class Person
{
     public delegate void MyEventHandler();
     public event MyEventHandler cashEvent;

     public void AddCash()
    {
        If (cash > 5 )    // some event occurs
                   {
                      If (cashEvet != null)   // check for subscribers
                                           {
                                                cashEvent();   // fire event
                                           }
                   }
    }
}

public class Hello
{
     Person p = new Person();
     p.cashEvent += p_cashEvent;      // subscribe to event and assign function(s) to invoke
    
    public void p_cashEvent()
    {
      // do something
    }
}


*****

Func <T> and Action <T> are .net built in delegates

Tuesday, September 15, 2015

Value vs Reference Types in c#

VALUE types are stored in one location in stack memory.

Primitive types such as int, bool, float, char are value types.

Structs are value types. Structs are cut down classes. Must use Struct keyword instead of class. Structs do not support inheritance. They reside in stack memory which can run faster than things stored in heap.

Runtime deals with the actual data so it is more efficient.


Reference types are stored in heap memory. The object is created in memory and then handled through a reference, similar to a pointer.

Classes are reference types. They are less efficient. Classes support inheritance.


Example value types:

int i = 1;
int j = i;
i++;

what is the value of j?

when you assign the value of i to j, it makes an actual copy of the value so j = 1; so when i is incremented, it doesn't affect the value of j; therefore, j = 1 and j does not = 2.


Example reference types:

class Form()
{
   string Text;
}

Form myForm = new Form();   // this creates two stores of memory: 1) ref to object  2) the object itself  

Form myForm;              // this breaks down the above to see clearer  1) reference to object is created
myForm = new Form();    // object is created in memory

Test (myForm);

void Test (Form f)
{
    f.Text = "hello";      // myForm's caption changes because myForm and f point to the same object
    f = null;   // myForm is intact because only a copy of the reference has been nullified/erased; myForm still holds its original reference to the object
}



http://www.albahari.com/valuevsreftypes.aspx

Monday, September 7, 2015

Object Oriented Programming

Object Oriented Programming (OOP) is a software development methodology that breaks up code into modules for greater reuse and maintainability. Prior to OOP, code was written in procedural format that led to large, monolithic pieces of code that was difficult to maintain (update and make changes). OOP breaks up the code into chunks for better maintainability which allows the code base to scale.

Class allows you to create custom types by grouping together variables, methods, and events. The class acts a blueprint or a template.

There are 3 pillars of OOP.

1) Inheritance - this deals with code reuse. If there are multiple classes that share the same properties, fields, methods, and events, you can create a base class that contains all of the shared members. Any child class that inherits from the base class is automatically exposed to all the members of the base class. The child class can be extended to add its own members to make it unique. If a method in the base class is defined as virtual, then the child class can override the method creating a new method implementation.

An abstract class is a base class that can contain abstract methods. Abstract methods are only defined and do not have any code implementation. Abstract classes cannot be instantiated. They can only be inherited. When a class inherits from an abstract class, it must implement all the abstract methods. An interface is a special form of an abstract class where ALL the methods are abstract. A class can only inherit from one abstract class. A class can inherit from multiple interfaces.

2) Encapsulation - this describes hiding the internal state (data) of a class. The common technique is to use private fields that can only be accessed by public properties. The advantage is that you have more control over the behavior of the data you can protect the data. For example, if you define a public field as int, it is exposed (can be changed) by all the code in the application. Also, it has a valid range of +/- 2.1 billion. By using encapsulation, you can implement code in the SET part of the public property that limits the valid values from 0 - 10.

Encapsulation helps to reduce coupling between objects and increases code maintainability.

3) Polymorphism - allows an object of one type to behave like a different type.

Example is the use of interfaces. You can have multiple classes inheriting the same interface, however, each class can implement different methods, thereby achieving different behaviors.

Another example is the use of overrides. If a base class defines a method as virtual, then child classes that inherit from the base class can override/change the virtual method implementation. The result is that multiple classes can inherit from the same base class, but because of different code implementations (overrides), they can all behave differently.

Method overloading IS NOT polymorphism.

*****

Interface - collection of properties and public methods grouped together to encapsulate functionality. The methods are abstract meaning that they are only defined. Any class that inherits from an interface must implement code for all the methods. In this sense, an interface is like a contract that guarantees the availability of all the methods defined. An interface is a special form of an abstract class whereby, all the methods are abstract. As such, it cannot be instantiated and must be inherited.

Static member - are shared between instances of a class. Think of them as global variables. Don't have to instantiate to use. Example:  Console.WriteLine() is a static method.

Struct - is like a cut down version of a class. Use Struct keyword instead of class. Structs are value types and resides in one place in memory. Classes are reference types so it holds a reference to a location in memory where the content is stored. Struct resides in the stack memory and the actual object is affected so it runs faster than classes that reside in the heap. Structs do not support inheritance.