Saturday, April 21, 2012

If Your Only Tool Is A Lambda, All Your Problems Will Look Like Can Be Tackled By Lambda Only

I love lambda, you love lambda, we all love lambda. When we neo-.NET kids encounters a problem that involves anything enumerable, we launch right away our lambda-fu into stratosphere, not even taking into account that there might be a simpler way to tackle the problem


For example, given a problem to sum all BigIntegers, we tend to solve it in lambda-ish way sort of way. But since a BigInteger lacks a Sum lambda/extension method, we are inclined to write it with what is available to us, i.e. we use Aggregate lambda:


using System;
using System.Linq;

using System.Numerics;

using System.Collections.Generic;


class Great 
{
 public static void Main() 
 {
  var bigInts = new List<System.Numerics.BigInteger>() {1, 2, 3, 4};

  var result = bigInts.Aggregate((currentSum, item)=> currentSum + item);
   
  Console.WriteLine(result);
 
 }
}



However, we forget that there's already a simpler alternative available to us, which is BigInteger's helper Add method. Given lambda's popularity, we tend to forget that lambdas can be fed with helper methods. If there's already a predefined helper method for a given problem, by all means use them to simplify things up. The code above could be rewritten by using predefined helper:

var bigInts = new List<System.Numerics.BigInteger>() {1, 2, 3, 4};

var result = bigInts.Aggregate(BigInteger.Add);   

Console.WriteLine(result);

Output:
10


So there we are, we can use predefined helper method, simple and has lesser noise. Lest we forgot, lambdas are just inlined delegates; so if there's already a predefined helper method that matches the lambda's delegate signature, feel free to use that helper method

Thursday, April 19, 2012

ServiceStack Walkthrough. Screenshots guide

Create an ASP.NET MVC Project:




Add ServiceStack components (ServiceStack.dll, ServiceStack.Interfaces.dll):



Get the DLLs at: https://github.com/ServiceStack/ServiceStack/downloads


Add this line to Web.config's httpHandlers section:

<add path="yourServicestack*"
 type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" />



Put this inside configuration section:


<location path="servicestack">
  <system.web>
    <httpHandlers>
      <add path="*" 
        type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" 
        verb="*" />
    </httpHandlers>
  </system.web>
</location>



Add these lines on RegisterRoutes:
routes.IgnoreRoute ("yourServicestack");
routes.IgnoreRoute ("yourServicestack/{*pathInfo}");



Add these Request,Response,Service classes in your Models directory:


class Hello  
{
 public string Name { get; set; }
   
}

class HelloResponse
{
 public string Result { get; set; }   
}

class HelloService : ServiceStack.ServiceHost.IService<Hello>
{
 public object Execute(Hello request) 
 {
  return  new HelloResponse { Result = "Good morning " + request.Name + "!" };
 }
} 









And add these other Request,Response,Service classes in Models directory too:


class Subtraction 
{ 
 public decimal Minuend { get; set; }  
 public decimal Subtrahend { get; set; }  
}


class SubtractionResponse 
{
 public decimal Difference { get; set; }
}

class SubtractionService : ServiceStack.ServiceHost.IService<Subtraction>
{
 public object Execute(Subtraction request) 
 {      
  return  new SubtractionResponse { Difference = request.Minuend - request.Subtrahend };
 }
}


Add these code in Global.asax.cs:


protected void Application_Start ()
{
 RegisterRoutes (RouteTable.Routes);
  
 new NextBillionAppHost().Init();
}



public class NextBillionAppHost : ServiceStack.WebHost.Endpoints.AppHostBase
{
 //Tell Service Stack the name of your application and where to find your web services
 public NextBillionAppHost() 
    : base("Billionaire Web Services", 
          typeof(DemoServiceStack.Models.SubtractionService).Assembly) { }

 public override void Configure(Funq.Container container)
 {       
  //register user-defined REST-ful urls
  Routes
   .Add<DemoServiceStack.Models.Hello>("/como-esta")
   .Add<DemoServiceStack.Models.Hello>("/como-esta/{Name}");
  
  Routes
   .Add<DemoServiceStack.Models.Subtraction>("/solve-subtraction")     
   .Add<DemoServiceStack.Models.Subtraction>("/solve-subtraction/{Minuend}/{Subtrahend}");
 }
}



Then run (shortcut key: command+option+enter), then type in address bar:


http://127.0.0.1:8080/yourServicestack

,then you shall see this:



Then under Operations, click the JSON tag of Subtraction operation, you shall see this:



Then type this url in the address bar:

http://127.0.0.1:8080/yourServicestack/solve-subtraction/2011/1955

You shall see this:



Then try to click the JSON, XML, etc, see the output.


You can use ServiceStack instead of WCF. REST-ful services is easier with ServiceStack. ServiceStack has a good programming model, i.e. the Request, Response and their Service has good cohesion

Monday, March 26, 2012

Advantage of explicit interface implementation

When I encountered this code in Java:

interface ISpeakerVolume
{
    void Increase();
    void ActivateHallEffect();
}

abstract class Tablet implements ISpeakerVolume
{     
}

I'm thinking why Java doesn't require the programmer to explicitly state if the methods are not supposed to be implemented in abstract class. While this same intent must be stated explicitly if you are using C#

interface ISpeakerVolume
{
    void Increase();
    void ActivateHallEffect();
}

abstract class Tablet : ISpeakerVolume
{     
    public abstract void Increase();
    public abstract void ActivateHallEffect();
}


By the way, if you are wondering why the method declaration signature is not exactly the same as its interface, actually they are not different. interface is just an abstract class with all its methods enforced to be abstract too and public. If such code can be explicitly written (not possible in C#, possible in Java), an interface shall be written like this:


abstract interface ISpeakerVolume
{
    public abstract void Increase();
    public abstract void ActivateHallEffect();
}

abstract class Tablet implements ISpeakerVolume
{
    public abstract void Increase();
    public abstract void ActivateHallEffect();
}

That will compile, interface methods are just abstract methods which doesn't require programmers to explicitly state it as such. And in Java, you can put the abstract keyword before the interface keyword; interface is just an abstract structure, with all its methods enforced to be abstracts too.


So as you can see, on an abstract class you can pass-the-buck the interface methods you don't wish to implement just by exactly repeating the interface method signature, i.e. public abstract void MethodNameHere();




Now, back to why C# didn't mimic the implicitness option of Java, why the need to repeat the interface method's signature if you don't want to implement the interface method in abstract class.


C# can't assume that you just want to pass-the-buck things up when you didn't re-declare the interface methods signature on abstract class. C# wanted you to be conscious of your decision; if you are newcomer to C#, C# allows us to provide different implementations for interface members which has same name and signature.


An example (has compilation errors: abstract class: XXX does not implement interface member YYY) :

interface ISpeakerVolume
{
    void Increase();
    void ActivateHallEffect();
}

interface ILcdBrightness
{
    void Increase();
    void ActivateSepia();
}


abstract class Tablet : ISpeakerVolume, ILcdBrightness
{
}




The abstract Tablet class implements two interfaces which has a method with same name. In C#, you can provide different behaviors for those methods(Increase) with same name, C# cannot just assume that they are the same just because they have the same name. However, if those same method name really have same implementation and you don't want to implement it right there on the abstract class, you can just pass-the-buck things up by repeating the interface signature in the abstract class.


abstract class Tablet : ISpeakerVolume, ILcdBrightness
{
    // repeat all the interface signature in the abstract class

    // repeating this method signature(and prefixing abstract) makes the two interfaces' Increase method 
    // to only have one behavior on inheriting classes of this abstract class
    public abstract void Increase(); 

    public abstract void ActivateHallEffect();
    public abstract void ActivateSepia();
}


So that's a good conscious decision, you must state your intention to the compiler, compilers can't infer your intentions; because for all we know, those Increase methods might have different behaviors and should be implemented differently. If that is the case, that can be done in C# by explicitly implementing different behaviors for each interface method, the method name is prefixed with the interface name followed by dot then followed by the interface's method name.


abstract class Tablet : ISpeakerVolume, ILcdBrightness
{
        void ISpeakerVolume.Increase()
        {
            // behavior goes here
        }

        void ILcdBrightness.Increase()
        {
            // behavior goes here
        }


        public abstract void ActivateHallEffect();
        public abstract void ActivateSepia();
}


The need for explicit interface implementation is also apparent if the method name is the same but they have different return type. An example:


interface ISpeakerVolume
{
        void Increase();
        void ActivateHallEffect();
}

interface ILcdBrightness
{
        int Increase();
        void ActivateSepia();
}


abstract class Tablet : ISpeakerVolume, ILcdBrightness
{

        // can the compiler infer which of the two Increase should it pass-the-buck?

        public abstract void ActivateHallEffect();
        public abstract void ActivateSepia();
}


ISpeakerVolume has an Increase method which has a void return type, while ILcdBrightness' Increase method has a return type of int. On that scenario, it's more readily apparent why the compiler cannot pass-the-buck the abstract methods implicitly; if the compiler allows such implicitness, what would be the return type of the overriding method on the concrete class then? Compilers can't give preferential treatment to a method based on its return type.


Since C# has explicit interface implementation; you can use it to elegantly pass-the-buck things up for methods with same name, especially if their return types are different.


interface ISpeakerVolume
{
        void Increase();
        void ActivateHallEffect();
}

interface ILcdBrightness
{
        int Increase();
        void ActivateSepia();
}


abstract class Tablet : ISpeakerVolume, ILcdBrightness
{

        void ISpeakerVolume.Increase()
        {
            IncreaseSpeakerVolume();
        }
        public abstract void IncreaseSpeakerVolume();


        int ILcdBrightness.Increase()
        {
            return IncreaseLcdBrightness();
        }
        public abstract int IncreaseLcdBrightness();




        public abstract void ActivateHallEffect();
        public abstract void ActivateSepia();
}


When a concrete class inherit the abstract class Tablet, the concrete class can then make a separate implementation for IncreaseSpeakerVolume and IncreaseLcdBrightness. Neat :-)



This post was originally intended as a bash on C# for not allowing the implementing class to pass-the-buck the interface members by not implementing the interface members, but ended up appreciating C# design choice on forcing the developers to be more explicit with their intent



Actual code:

using System;
                    
public class Program
{
    public static void Main()
    {
        var t = new Ipad();
        
        ISpeakerVolume s = t;
        ILcdBrightness l = t;
        
        s.Increase();
        l.Increase();
        
        s.TurnOn();
        l.TurnOn();
        
    }
    
    
}

interface ISpeakerVolume
{
    void Increase();
    
    void TurnOn();

}
 
interface ILcdBrightness
{
    void Increase();
    
    void TurnOn();
}
 

abstract class Tablet : ISpeakerVolume, ILcdBrightness
{
    // C# enforces us to repeat all the interface members on the implementing abstract class or concrete class

 
    public void Increase()
    {
        Console.WriteLine("Yeah");
    }
    
    void ISpeakerVolume.TurnOn()
    {
        Console.WriteLine("Speaker On");
    }
    
    void ILcdBrightness.TurnOn()
    {
        Console.WriteLine("LCD On");
    }
 
}

class Ipad : Tablet
{
    
}

Output:
Yeah
Yeah
Speaker On
LCD On

Tuesday, March 20, 2012

Possible in SQL Server, deleting any row

Given this data:

RollNo      Name
    1       Yoko
    1       Yoko
    1       Yoko


How to delete the 3rd row?

Requirement source: http://stackoverflow.com/a/6645780/11432

create table test
(
n int,
name varchar(30)
);

insert into test values(1,'yoko'),(1,'yoko'),(1,'yoko');

select ROW_NUMBER() over(order by name) as ordinal, * from test;



 ordinal | n | name 
---------+---+------
       1 | 1 | yoko
       2 | 1 | yoko
       3 | 1 | yoko
(3 rows)


Deleting the 3rd row:

with a as
(
select ROW_NUMBER() over(order by name) as ordinal, * from test
)
delete from a where a.ordinal = 3;


-- delete last row
with a as
(
select ROW_NUMBER() over(order by name) as ordinal, * from test
)
delete from a where a.ordinal = (select MAX(ordinal) from a);

That's both possible in SQL Server, it will have error on Postgresql though:

ERROR:  relation "a" does not exist
LINE 5: delete from a where a.ordinal = 3
                    ^


********** Error **********

ERROR: relation "a" does not exist
SQL state: 42P01
Character: 91

Monday, February 27, 2012

A primer on unit testing with Moq

The following code is a primer on unit testing, just get Moq from Nuget. Note: Actual unit testing should be done on a separate project, not on Main method :-) This code just demonstrates how elegant Moq is for unit testing needs.

using System;

using Moq;

namespace MoqSample
{
    class Program
    {
        static void Main(string[] args)
        {
            // ARRANGE
            
            decimal amount = 100;

            // that's why you will love unit testing, mishaps could be avoided :-)
            string errorMessage = "Could be an anomaly, passed amount is different from amount to transfer"; 

            var mockedSource = new Mock<IAccount>();
            mockedSource.Setup(x => x.Withdraw(It.Is<decimal>(a => a != amount))).Throws(new Exception(errorMessage));
            mockedSource.Setup(x => x.Deposit(It.Is<decimal>(a => a != amount))).Throws(new Exception(errorMessage));
            
            
            var mockedDest = new Mock<IAccount>();
            mockedDest.Setup(x => x.Withdraw(It.Is<decimal>(a => a != amount))).Throws(new Exception(errorMessage));
            mockedDest.Setup(x => x.Deposit(It.Is<decimal>(a => a != amount))).Throws(new Exception(errorMessage));
            



            // ACT

            int test = 0;
            /*
             * 0's error: NONE
             * 
             * 1's error:
             * Expected invocation on the mock should never have been performed, but was 1 times: source => source.Deposit(.amount)
             *  
             * 2's error:
             * Expected invocation on the mock once, but was 2 times: dest => dest.Deposit(.amount)
             * 
             * 3's error:
             * Expected invocation on the mock once, but was 0 times: dest => dest.Deposit(.amount)
             * 
             * 4's error:
             * Expected invocation on the mock once, but was 0 times: source => source.Withdraw(.amount)
             * 
             * 5's error:
             * Could be an anomaly, passed amount is different from transfer amount
             *             
             * */

            if (test == 0)
                TransactionMaker.TransferFund(mockedSource.Object, mockedDest.Object, amount);                
            else if (test == 1)
                TransactionMaker.TransferFundBuggy1(mockedSource.Object, mockedDest.Object, amount);                
            else if (test == 2)
                TransactionMaker.TransferFundBuggy2(mockedSource.Object, mockedDest.Object, amount);
            else if (test == 3)
                TransactionMaker.TransferFundBuggy3(mockedSource.Object, mockedDest.Object, amount);
            else if (test == 4)
                TransactionMaker.TransferFundBuggy4(mockedSource.Object, mockedDest.Object, amount);                
            else if (test == 5)
                TransactionMaker.TransferFundAnomalous(mockedSource.Object, mockedDest.Object, amount);                
            else
                throw new Exception("Select test case from 0 to 5");


            // ASSERT

            mockedSource.Verify(source => source.Withdraw(amount), Times.Once());
            mockedSource.Verify(source => source.Deposit(amount), Times.Never());

            mockedDest.Verify(dest => dest.Deposit(amount), Times.Once());
            mockedDest.Verify(dest => dest.Withdraw(amount), Times.Never());

        }

        
    }


    public static class TransactionMaker
    {

        public static void TransferFund(IAccount sourceAccount, IAccount destAccount, decimal amountToTransfer)
        {
            sourceAccount.Withdraw(amountToTransfer);
            destAccount.Deposit(amountToTransfer);            
        }

        public static void TransferFundBuggy1(IAccount sourceAccount, IAccount destAccount, decimal amountToTransfer)
        {
            sourceAccount.Withdraw(amountToTransfer);
            sourceAccount.Deposit(amountToTransfer);            
        }

        public static void TransferFundBuggy2(IAccount sourceAccount, IAccount destAccount, decimal amountToTransfer)
        {
            sourceAccount.Withdraw(amountToTransfer);
            destAccount.Deposit(amountToTransfer);
            destAccount.Deposit(amountToTransfer);
        }


        public static void TransferFundBuggy3(IAccount sourceAccount, IAccount destAccount, decimal amountToTransfer)
        {
            sourceAccount.Withdraw(amountToTransfer);            
        }

        public static void TransferFundBuggy4(IAccount sourceAccount, IAccount destAccount, decimal amountToTransfer)
        {
            sourceAccount.Deposit(amountToTransfer);
        }

        public static void TransferFundAnomalous(IAccount sourceAccount, IAccount destAccount, decimal amountToTransfer)
        {
            sourceAccount.Withdraw(amountToTransfer);
            destAccount.Deposit(amountToTransfer + 0.5M);
        }

        
    }



    public interface IAccount
    {
        void Withdraw(decimal v);
        void Deposit(decimal v);
    }

    public class Account : IAccount
    {
        public void Withdraw(decimal amount)
        {
        }

        public void Deposit(decimal amount)
        {
        }
    }
}