A long precarious way…

TL;DR; = This post is about improving the way you write deep null checks in C#, i.e. a chain of If-not-null checks along the object hierarchy.

I am sure there have been times in your developer life when you saw something like this, 


class Person
{
public Address Address { get; set; }
}

public class Address
{
public State State { get; set; }
}

public class State
{
public int PinCode { get; set; }
}
...
...
var p = new Person();
...
...

if (p.Address != null && p.Address.State != null)
{
var pin = p.Address.State.PinCode;
}


Ugh.., yes you have… The point is you have to go through a lot of checks in between to reach the PinCode field. In this example there are just 2 checks for Address and State, but there could be more complicated scenarios. While talking about this, I do understand by the Law of Demeter we should not be having such deep checks in the first place. But for this blog post sake, consider this as some hairy legacy code. Moving on, there is a way you could do the same thing but in a much more readable way. What I want to do is in case of a null instance anywhere in the chain of objects, the final value should be a default decided by me, without any null reference error. Here is my attempt,




public static class Extension
{
public static TResult With<TSource,TResult>(this TSource source, Func<TSource,TResult> evaluator, TResult failureValue)
where TSource : class
where TResult : class
{
if (evaluator == null)
throw new InvalidOperationException("Boom!!!");
var res = source != null ? evaluator(source) : failureValue;
return res ?? failureValue;
}
}

public class Person
{
public Address Address { get; set; }
public static Person NullInstance
{
get
{
return new Person() { Address = Address.NullInstance };
}
}
}

public class Address
{
public State State { get; set; }
public static Address NullInstance
{
get { return new Address() { State = State.NullInstance }; }
}

}

public class State
{
public int PinCode { get; set; }
public static State NullInstance
{
get
{
return new State() { PinCode = -1 };
}
}
}

...
...

var pin = this.With(x => p, Person.NullInstance)
.With(x => x.Address, Address.NullInstance)
.With(x => x.State, State.NullInstance).PinCode;


Definitely more readable huh.

Abhang Rane


Temptations of Scala…

As I continue my romance with Scala language, I decided to take up the rubber duck code from Head First Design Patterns. The code already is implemented using Strategy pattern as we know. Just check the C# code juxtaposed against the Scala code, (dont ask which one is C# code)
class Program
{
static void Main(string[] args)
{
var actualDuck = new Duck(new ActualFlyBehavior(),
new ActualQuackBehavior());
actualDuck.DoFly();
actualDuck.DoQuack();
var rubberDuck = new Duck(new NoFlyBehavior(),
new NoQuackBehavior());
rubberDuck.DoFly();
rubberDuck.DoQuack();
Console.ReadLine();
}
}

public class ActualFlyBehavior : IFly
{
public void Fly()
{
Console.WriteLine("I am actually flying!!!");
}
}

public class ActualQuackBehavior : IQuack
{
public void Quack()
{
Console.WriteLine("I am actually quacking!!!");
}
}

public class NoFlyBehavior : IFly
{
public void Fly()
{
Console.WriteLine("---");
}
}

public class NoQuackBehavior : IQuack
{
public void Quack()
{
Console.WriteLine("---");
}
}

public class Duck
{
private readonly IFly fly;
private readonly IQuack quack;

public Duck(IFly fly, IQuack quack)
{
this.fly = fly;
this.quack = quack;
}

public void DoFly()
{
fly.Fly();
}

public void DoQuack()
{
quack.Quack();
}
}

public interface IFly
{
void Fly();
}

public interface IQuack
{
void Quack();
}
object Starter extends App
{
println("Hello World!!!")
val actualDuck = new ActualDuck
actualDuck.doFly()
actualDuck.doQuack()
val rubberDuck = new RubberDuck
rubberDuck.doFly()
rubberDuck.doQuack()
}

abstract class Duck
{
def doFly()
def doQuack()
}


class ActualDuck extends Duck with Fly with Quack
{

}

class RubberDuck extends Duck
{
def doFly() {println("---")}
def doQuack() {println("---")}
}

trait Fly
{
def doFly(){println("I am actually flying!!!")}
}

trait Quack
{
def doQuack(){println("I am actually quacking!!!")}
}
 
 
 
 
 

Abhang Rane


Pocket it!

Ok so I might be a little late to the party, but nonetheless I am in the party now. Since I do follow many blogs and in search of new interesting blogs all the time, I always have this situation wherein I do find something really intriguing to read but have to save it for later. The things that interest me are coding blogs for Java, C#, Scala (I mentioned them in the increasing order of coolness), lifehacker like blogs, Agile, Daily WTF of course and the list goes on. I needed something that I can use on any of my devices, iPhone, iPad, Mac, my Dell laptop. I needed something that could do the job in at the most one click. That is the best you could do really (cant think of any quicker way really). I did hear quite a bit about EverNote and it is an excellent tool. Although somehow it is not like a one click solution I was looking for.

And then this Pocket shows up. The first thing I looked was the list of devices supported, satisfied there. The second thing was how it is used. It really has a one click solution if you are already using a supported feed reader. I use Feedly (which is an excellent replacement for Google Reader). So all you do is while you have your blog post open, just click the “Pocket” icon button at the top, thats it. End of Story! May be not. I use Chrome as my browser for reading blogs when I am on a laptop or desktop. Its got a Chrome plugin that behaves pretty much the same One-Click way I just mentioned. If this explanation was too complicated for you, they even have a short video on how to use it, go check it out. This is really End of Story.

Happy Pocketing!

Abhang Rane


A polyglot “C#”er

My professional career until now (spans barely 8 years), has been mostly “C#”ish. I liked the language when I started working with it, and really enjoyed staying within the Visual Studio editor. While I was working earlier in my career, I did find interest in reading several blogs about being a better programmer as a whole. The word “polyglot” reverberated in many such well thought blogs. I did understand at the point that having exposure to many languages will equip me better in my work. But here is my honest take on it now that I have spent some reasonably sizable amount of time with a language.

You got to know a particular language well first. For me it is undoubtedly C# as it stands. Once you have that under your sleeves, when you start exploring other languages you learn them in a different way than you would have learnt if you had not mastered a language. It becomes just involuntary that you start comparing features of this new language to the language of your forte. And with this the benefits are two-fold, you learn the new language faster, and you find better ways of solving problems in your mastered language. I think the second point is really exciting for me as I venture on learning new languages and paradigms. For some limited time now, I have worked on Java professionally. I have taken a stab at Scala and Haskell during my personal time although it is not usual to find these 2 languages easily in mainstream application development. The best way to learn languages is to solve some really common problems in computer science. I like the Producer-Consumer problem as it highlights usages of collections and threads which form the biggest chunk of the stuff we use. Below are C# snippet juxtaposed to Java snippet. Spot 6 differences to win a free trip to Goa Winking smile.





public class PCQueueCharp
{
private Queue queue = new Queue();
private static readonly object SyncLock = new object();

public PCQueue(int capacity)
{
Capacity = capacity;
}

public int Capacity { get; private set; }

public void AddTask(ITask task)
{
lock(SyncLock)
{
if (queue.Count == Capacity)
Monitor.Wait(SyncLock);
queue.Enqueue(task);
Monitor.Pulse(SyncLock);
}
}

public ITask RemoveTask()
{
lock(SyncLock)
{
if (queue.Count == 0)
Monitor.Wait(SyncLock);
var task = queue.Dequeue();
Monitor.Pulse(SyncLock);
return task;
}
}
}


public class PCQueueJava
{
private int capacity;
private final Queue queue;
private static final Object SyncLock = new Object();

public PCQueue(int capacity)
{
this.capacity = capacity;
queue = new ArrayDeque(capacity);
}

public void AddTask(ITask task) throws InterruptedException
{
synchronized (SyncLock)
{
if(queue.size() == capacity)
SyncLock.wait();

queue.add(task);
SyncLock.notify();
}
}
public ITask RemoveTask() throws InterruptedException
{
synchronized (SyncLock)
{
if(queue.size() == 0)
SyncLock.wait();
ITask task = queue.remove();
SyncLock.notify();
return task;
}
}
}



And here is a beginners implementation in Scala



class PCQueue(capacity:Int)
{
val queue = new mutable.Queue[ITask]()
val syncObject = new AnyRef

def addTask(task : ITask) : Unit =
{
synchronized
{
if(queue.length == capacity)
wait()

queue += task
notify()
}
}

def removeTask() : ITask =
{
var task : ITask = null
synchronized
{
if(queue.length == 0)
wait()

task = queue.dequeue()
notify()
}
return task
}
}

The idea is to improve this class in Scala to make it more “Scala”ble in a later post.

Abhang Rane