C# Delegates, Anonymous Methods, and Lambda Expressions

0

Category :

C# Delegates, Anonymous Methods, and Lambda Expressions.

Delegates

Pointer to a function.
A way to pass methods the same way you pass values and objects around
 
delegate int DiscountDelegate(); 
 
Just like a class, however, it isn't very useful until we create an instance of it.

Remember that a delegate is nothing more then a reference to a method.

Even though DiscountDelegate does not have any constructors, when creating one, there is an implicit constructor that wants a method matching its signature (no params, returning int).

Type in the name in the same way you would call the method; all you do is omit the parentheses.

Another way to think of a delegate is that it defers the execution of a method.

} 

Func

Later, in 3.5, they were nice enough to give us some common delegates to use so we wouldn't have to constantly define our own. They expanded Action and added Func, and the only difference between them is that Func matches methods that return a value and Action matches ones that do not.

This means that we do not need to declare our DiscountDelegate and instead can use Func in its place.

Our delegate's signature now becomes Func. Notice the Calculate method now takes a boolean parameter and that we call discount() using a boolean.

class Program 
{ 
    static void Main(string[] args) 
    { 
        new ShoppingCart().Process(new Func(Calculator.Calculate)); 
    } 
} 
 
class Calculator 
{ 
    public static int Calculate(bool special) 
    { 
        int discount = 0; 
        if (DateTime.Now.Hour < 12) 
        { 
            discount = 5; 
        } 
        else if (DateTime.Now.Hour < 20) 
        { 
            discount = 10; 
        } 
        else if (special) 
        { 
            discount = 20; 
        } 
        else 
        { 
            discount = 15; 
        } 
        return discount; 
    } 
} 
 
class ShoppingCart 
{ 
    public void Process(Func discount) 
    { 
        int magicDiscount = discount(false); 
        int magicDiscount2 = discount(true); 
    } 
}
Type inference allows us to completely omit the explicit creation of Func as long as the method we pass has the proper signature of the expected delegate.
eliminating the need to even explicitly create a Func delegate

// works because Process expects a method that takes a bool and returns int 
new ShoppingCart().Process(Calculator.Calculate); 

Anonymous methods

Anonymous methods let you declare a method body without giving it a name.
Anonymous methods can only be created when using delegates and, in fact, they are created using the delegate keyword.

new ShoppingCart().Process( 
        new Func(delegate(bool x) { return x ? 10 : 5; } 
    )); 

You can put as much or as little logic between the curly braces as you would in any other method.

there is even more trimming we can do. Naturally, we can omit the need to explicitly declare the Func delegate; .NET takes care of that for us when we use the delegate keyword.

new ShoppingCart().Process( 
      delegate(bool x) { return x ? 10 : 5; } 
    );  

The true power of anonymous methods can be seen when using .NET methods that expect delegates as parameters and when responding to events. Previously, you had to create a method for every possible action you wanted to take. Now you can just create them inline and avoid polluting your namespace.

// creates an anonymous comparer 
custs.Sort(delegate(Customer c1, Customer c2) 
{ 
    return Comparer.Default.Compare(c1.ID, c2.ID); 
}); 
 
// creates an anonymous event handler 
button1.Click += delegate(object o, EventArgs e) 
                      { MessageBox.Show("Click!"); }; 

Lambda expressions

From MSDN: 'A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.'

lambda expressions replace anonymous methods and add many features.

Looking back at our last example, we had trimmed the code down to where we were basically creating the entire discount algorithm in a single line.
new ShoppingCart().Process( 
        new Func(delegate(bool x) { return x ? 10 : 5; } 
    )); 

Lambda expressions use the 'goes to' operator => to indicate what parameters are being passed to the expression.
The compiler takes this a step further, and allows us to omit the types and infers them for us.
If you have two or more parameters, you need to use parentheses: (x,y) =>. If you only have one, however, you don’t need them: x =>.
static void Main(string[] args) 
{ 
    Func del = x => x ? 10 : 5; 
    new ShoppingCart().Process(del); 
} 
// even shorter... 
static void Main(string[] args) 
{ 
    new ShoppingCart().Process(x => x ? 10 : 5); 
} 

Yep, that's it. The boolean type of x is inferred and so is the return type, because Process takes a Func. If we want to implement the full code block like we had before, all we need to do is add the braces.

static void Main(string[] args) 
{ 
    new ShoppingCart().Process( 
    x => { 
        int discount = 0; 
        if (DateTime.Now.Hour < 12) 
        { 
            discount = 5; 
        } 
        else if (DateTime.Now.Hour < 20) 
        { 
            discount = 10; 
        } 
        else if(x) 
        { 
            discount = 20; 
        } 
        else 
        { 
             discount = 15; 
        } 
        return discount; 
    }); 
} 

One last thing…

There is an important difference between using braces and not using them. When you use them, you are creating a 'statement lambda', otherwise it is 'expression lambda'. Statement lambdas can execute multiple statements (hence the need for braces) and can not create expression trees. You will probably only run into this problem when working with the IQueryable interface. The example below shows the problem.

Statement Lambda use curly braces and can execute multiple statements (hence the need for braces) and can not create expression trees.
List list = new List(); 
IQueryable query = list.AsQueryable(); 
list.Add("one"); 
list.Add("two"); 
list.Add("three"); 
 
string foo = list.First(x => x.EndsWith("o")); 
string bar = query.First(x => x.EndsWith("o")); 
// foo and bar are now both 'two' as expected 
foo = list.First(x => { return x.EndsWith("e"); }); //no error 
bar = query.First(x => { return x.EndsWith("e"); }); //error 
bar = query.First((Func)(x => { return x.EndsWith("e"); })); //no error 
The second assignment of bar fails at compile time. This is because IQueryable.First expects an expression as a parameter whereas the extension method List.First expects a delegate. You can force the lambda to evaluate to a delegate (and use the First's method overload) by making a cast as I did in the third assignment to bar.

It's hard to end the discussion here, but I feel I must. Lambdas are basically broken into two categories; the kind that create anonymous methods and delegates, and the kind that create expressions. Expressions are an article by themselves and are not necessarily required knowledge to be a .NET developer (although their implementation in LINQ certainly is).

Informative graphic showing different parts of LINQ query




my thanks to:
http://www.codeproject.com/Articles/47887/C-Delegates-Anonymous-Methods-and-Lambda-Expressio
http://www.codeproject.com/Articles/19154/Understanding-LINQ-C

AngularJS Basics

0

Category :

1) Angular Directive = ng-app

2) Access Angular Model through controllers

3) $scope is Angular Model

4) ng-controller directive sets js function name to use as controller for a portion of page, different portions of the page could have diff controllers.

5) Setting ng-app="nameApp" prevents polluting of the global namespace:
 
 <html ng-app="nameApp">
   <head>
     <meta charset="utf-8">
     <title>Angular.js Example</title>
     <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
     <script>
       var nameApp = angular.module('nameApp', []);
       nameApp.controller('NameCtrl', function ($scope){
         $scope.firstName = 'John';
         $scope.lastName = 'Smith';
       });
     </script>
   </head>
   <body ng-controller="NameCtrl">
     First name:<input ng-model="firstName" type="text"/>
     <br>
     Last name:<input ng-model="lastName" type="text"/>
     <br>
     Hello {{firstName}} {{lastName}}
   </body>
     </html>
    
6) Could have multiple Angular apps running on the same page.







my thanks to:
https://github.com/curran/screencasts/tree/gh-pages/introToAngular

AngularJS Intro

3

Category :

Data Binding Framework

Main usage creating single-page apps.
Based on MVC architecture

Provide solutions for:

  • Routing - handling updates to the url hash fragment
  • Templating - dynamically creating and updating HTML based on templates and models
  • Data binding - synchronise the model and user interface
  • Top data-binding frameworks:

    AngularJS
    KnockoutJS
    Ember
    JsViews

    Related libraries

    • jQuery - industry standard library for DOM manipulation and AJAX
    • AMD - for seperating JavaScrip projects across many files using modules, allowing depencies from one files on another. Require
    • Angular provides a jQuery like API jqLite - which is like jQuery minimal functionality
    • Promises - industry standard pattern for dealing with asynchronous control flow. The top Promises implementation is Q.
    • Async.js
    • Handlebars - templating engine. Angular Templates use similar syntax.

    Angular Learning Resources

    It is straightforward to teach yourself about Angular, as there are so many learning resources on the Web.

    Bird's-eye-view:

    Learn Angularjs This Weekend - Advice on which resources to use for getting up to speed on Angular.
    A Better Way to Learn AngularJS - A great collection of links to resources for learning Angular.
    AngularJS-Learning - A kitchen sink of links to Angular learning resources.

    Introductory tutorials and guides:

    Angular Developer Guide Conceptual Overview
    • Enumerates fundamental concepts
    • Provides several code examples
    Official Angular Tutorial
    • Useful to read through
    • Emphasizes testing
    • Starts with complex boilerplate project
    • Great diagrams
    Egghead.io
    • A collection of short screencasts (scroll to the bottom for intoduction content)
    AngularJS Fundamentals In 60-ish Minutes
    • A talk on YouTube that covers fundamentals of Angular
    Learn Angular.js in 30 Min
    • A screencast showing how to build an app using UI-Router
    • Does not cover basics, jumps to advanced usage
    • Great example of how development flows in practice
    An Introduction to AngularJS Forms Validation

    Design and implementation of Angular:

    Re-Imagining the Browser with AngularJS
    • Talk by Miško Hevery, creator of Angular
    • Discusses the high-level goals of Angular
    Bringing Angular Apps to Life with Animation by Miško Hevery
    Google I/O 2013 - Design Decisions in AngularJS
    "Writing Directives" talk by Misko Hevery




    my thanks to: https://www.youtube.com/watch?v=TRrL5j3MIvo
    https://github.com/curran/screencasts/tree/gh-pages/introToAngular

    High Cohesion, Loose Coupling

    0

    Category : , ,

    We are witnessing a high demand for a maintainable software, software that can change easily over time. In order to prolong the value of the software for a long period of time you have to make it respond easier to change. There are a few guidelines that you can follow that can help you out.

    Here, I try to shed some light on two of those: cohesion and coupling

    High Cohesion

    Cohesion in software engineering is the degree to which the elements of a certain module belong together. Thus, it is a measure of how strongly related each piece of functionality expressed by the source code of a software module is.

    Functional Cohesion

    Functional cohesion is when parts of a module are grouped because they all contribute to a single well-defined task of the module.

    One way of looking at cohesion in terms of OO is if the methods in the class are using any of the private attributes. Below is one example of how a high-cohesion class would look like.

    1:    class HighCohesion  
    2:    {  
    3:      private int _elementA;  
    4:      private int _elementB;  
    5:    
    6:      public int MethodA()  
    7:      {  
    8:        var returnValue = SomeOtherMethod(_elementA);  
    9:        return SomeVeryOtherMethod(_elementB);  
    10:      }  
    11:    
    12:      public void PrintValues()  
    13:      {  
    14:        Console.WriteLine(_elementA);  
    15:        Console.WriteLine(_elementB);  
    16:      }  
    17:    }  
    
    

    The point is having a the classes as small as possible in terms of elements. The less elements we have the greater the possibility for them to be used in all the methods.

    Loose Coupling

    Coupling in simple words, is how much one component knows about the inner workings or inner elements of another one, i.e. how much knowledge it has of the other component.

    Correct and clear description of what 1:1 coupling is:

    iPods are a good example of tight coupling: once the battery dies you might as well buy a new iPod because the battery is soldered fixed and won’t come loose, thus making replacing very expensive. A loosely coupled player would allow effortlessly changing the battery.


    Loose coupling is a method of interconnecting the components in a system or network so that those components, depend on each other to the least extent practically possible…

    Tight coupling is where components are so tied to one another, that you cannot possibly change the one without changing the other.

    The image above shows us a relation between two classes that is called tight coupling. Class1 above directly instantiates objects of Class2, and even goes as far as accessing member variables and so on. This makes it very dependent on Class2. What if we decided we wanted to add extra parameter in Class2’s constructor and make the default one private? Then we would have to change every usage of Class2 everywhere.
    1:    class ClassA  
    2:    {  
    3:      private bool _elementA;  
    4:        
    5:      public int MethodA()  
    6:      {  
    7:        if (_elementA)  
    8:          return new ClassB()._elementB;  
    9:          
    10:        return 0;  
    11:      }  
    12:    
    13:      public void PrintValues()  
    14:      {  
    15:        new ClassB().MethodB();  
    16:      }  
    17:    }  
    18:    
    19:    class ClassB  
    20:    {  
    21:      public int _elementB;  
    22:    
    23:      public void MethodB()  
    24:      {  
    25:        Console.WriteLine(_elementB);  
    26:      }  
    27:    }  
    

    We can solve this is by so called inverting the dependencies, by adding another layer. Example in C# would be adding an interface. That’s way Class1 will only be dependent on the interface, and not the actual implementation of Class2. Image 4 ilustrates this point.
    Instantiation of the actual implementation will take place somewhere else in the code. This is the one of the most important reasons why dependency injection frameworks are being used.
    1:  class ClassA  
    2:    {  
    3:      private readonly ISomeInterface _interfaceImpl;  
    4:    
    5:      public ClassA(ISomeInterface interfaceImpl)  
    6:      {  
    7:        _interfaceImpl = interfaceImpl;  
    8:      }  
    9:    
    10:      public int MethodA()  
    11:      {  
    12:        return _interfaceImpl.MethodB();  
    13:      }  
    14:    
    15:      public void PrintValues()  
    16:      {  
    17:        _interfaceImpl.PrintValues();  
    18:      }  
    19:    }  
    20:    
    21:    interface ISomeInterface  
    22:    {  
    23:      int MethodB();  
    24:      void PrintValues();  
    25:    }  
    26:    
    27:    class ClassB : ISomeInterface  
    28:    {  
    29:      private int _elementB = 2 + 2;  
    30:    
    31:      public int MethodB()  
    32:      {  
    33:        return _elementB;  
    34:      }  
    35:    
    36:      public void PrintValues()  
    37:      {  
    38:        Console.WriteLine(_elementB);  
    39:      }  
    40:    }  
    

    What is the reason behind this, you may ask yourselves???……..Change.

    When we have the components this separate, then we can have separate implementation of different problem areas. With separate implementation we can change as much as we want without breaking some other greater process that is using it. Furthermore, when you can change components independently, there is nothing stopping you from developing them independently and even deploy them separately.

    Law of Demeter

    The Law of Demeter (LoD) or the principle of least knowledge is a object-oriented software design principle. In its general form, the LoD is a specific case of loose coupling.

    The formal object form of the law can be summarized as:

    A method of an object may only call methods of:
    1. The object itself.
    2. An argument of the method.v
    3. Any object created within the method.
    4. Any direct properties/fields of the object.

    The conclusion can be summarized in one sentence:
    Don’t talk to strangers!
    An object A can request a service (call a method) of an object instance B, but object A should not “reach through” object B to access yet another object, C, to request its services. Doing so would mean that object A implicitly requires greater knowledge of object B’s internal structure. Instead, B’s interface should be modified if necessary so it can directly serve object A’s request, propagating it to any relevant subcomponents. Alternatively, A might have a direct reference to object C and make the request directly to that. If the law is followed, only object B knows its own internal structure.

    In particular, an object should avoid invoking methods of a member object returned by another method , like for example:
    var a = someObject.FirstMethod().SecondMethod();
    For many modern object oriented languages that use a dot as field identifier, the law can be stated simply as “use only one dot”. The above example breaks the law where for example:
    var a = someObject.Method();
    does not. As an analogy(Wikipedia), when one wants a dog to walk, one does not command the dog’s legs to walk directly; instead one commands the dog which then commands its own legs.

    The advantage of following the Law of Demeter is that the resulting software tends to be more maintainable and adaptable. Since objects are less dependent on the internal structure of other objects, object containers can be changed without reworking their callers.

    my thanks to: http://thebojan.ninja/2015/04/08/high-cohesion-loose-coupling/

    Learning TDD using Kata's

    0

    Category : ,

    Why We Need to Learn TDD?

    Think of a scenario where a developer did complete unit testing and the Quality Assurance guys did their job and marked the deliverables ready for production. What happened if the other developer’s code/changes break the first developer’s code? Now, here we can think about TDD. As it is self-explanatory, Test Driven Development means what we are writing, we are testing. In this way, if someone broke your code, then your test(s) will get failed and you can check the broken area. This is just a one aspect, TDD is a huge one.

    What is TDD?

    As per wiki, TDD is defined as:
    "Test-driven development (TDD) is a software development process that relies on the repetition of a very short development cycle: first the developer writes an (initially failing) automated test case that defines a desired improvement or new function, then produces the minimum amount of code to pass that test, and finally refactors the new code to acceptable standards"



    TDD has three stages called Red Green Refactor (RGR).

    • Red – First write test that fails.
    • Green – Modify/alter code so, test pass.
    • Refactor- Re-write the code better.

    What is TDD Kata?

    Kata is a Japanese word and means as ‘form’ and detailed choreographed pattern of body moments.
    In martial arts, what they do, they do practice and repeat the steps to hone the skills and their patterns. Similarly, in software, the idea was originally invented by Dave Thomas. The motive of this idea is the same, do practice, repeat tasks and make your skills perfect.

    The FizzBuzz Kata

    Print the numbers from 1 to 100. But for multiples of three, print "Fizz” instead of the number and for the multiples of five, print "Buzz". For numbers which are multiples of both three and five, print "FizzBuzz".

    Other Katas:

    https://github.com/garora/TDD-Katas
    http://tddkatas.codeplex.com/
    http://codingkata.net/

    My thanks to:
    http://www.codeproject.com/Articles/886492/Learning-Test-Driven-Development-with-TDD-Katas

    Decorator Design Pattern Intro

    0

    Category : , ,

    Decorator Design pattern allows developer to satisfy some SOLID rules:

    • 1) Single Responsibility Principle – Class/Function should do only one task or Class/Function should have only one reason to change.
    • 2) Open Close Principle – Class/Function is open for extension but close for modification.
    • 3) Liskov Substitution type – If type S is derived from Type T then object of Type T can be replaced by object of Type S.


    Simple Example of Design Pattern

    namespace BasicDecoratorPattern
    {
        public class Client
        {
            public Client()
            {
                IBaseService realTimeService = new BasicServiceImplementaion();
    
                IBaseService basicRealTimeServiceDecorator1 = new Decorator1OnBasic(realTimeService);
                IBaseService basicRealTimeServiceDecorator2 = new Decorator2OnBasic(realTimeService);
    
                basicRealTimeServiceDecorator1.Print();
                basicRealTimeServiceDecorator2.Print();
            }
        }
    
        public interface IBaseService
        {
            void Print();
        }
    
        public class BasicServiceImplementaion : IBaseService
        {
            public void Print()
            {
                Console.WriteLine("Basic Item");
            }
        }
    
        public class Decorator1OnBasic : IBaseService
        {
            private readonly IBaseService BasicRealTimeService;
            public Decorator1OnBasic(IBaseService service)
            {
                BasicRealTimeService = service;
            }
    
            public void Print()
            {
                BasicRealTimeService.Print();
                Console.WriteLine("Extra functionality from Decorator ONE");
            }
        }
    
        public class Decorator2OnBasic : IBaseService
        {
            private readonly IBaseService BasicRealTimeService;
            public Decorator2OnBasic(IBaseService service)
            {
                BasicRealTimeService = service;
            }
    
            public void Print()
            {
                BasicRealTimeService.Print();
                Console.WriteLine("Extra functionality from Decorator SECOND");
            }
        }
    }
    




    my thanks to: http://www.codeproject.com/Articles/872818/How-and-Where-Decorator-Design-Pattern