Object Proxy


Consider this simplistic example, which uses a stream reader.

public class FileLoader
{
    private readonly StreamReader _streamReader;

    public FileLoader(StreamReader streamReader)
    {
        _streamReader = streamReader;
    }

    public IEnumerable<string> Read()
    {
        var output = new List<string>();
        string line;
        while (!string.IsNullOrEmpty(line = _streamReader.ReadLine()))
        {
            output.Add(line);
        }
        _streamReader.Close();
        _streamReader.Dispose();
        return output;
    }
}

The problem I have with this class is that it isn’t exactly unit testable. First of all, it uses a stream reader and it’s not straightforward to be able to mock a stream reader due to the lack of an interface. Secondly what I reckon most developers would do is pass a real stream reader into the class and write tests in that fashion, which would be more of an integration test.

Read the rest of this entry »

Posted in EdLib. Tags: . Leave a Comment »

EdLib


Over the years as a developer, I’ve come to realise that I have encountered similar problems and have had to write same kind of code. I’m sure most of us would have gone through that kind of experience, when we wished we had saved the code snippet or functions in a central area so we can re-use it.

I’ve decided to do exactly that. I’ve created a personal library where I want to store useful, reusable code that helps me in my everyday work, and hopefully will be useful to others too. Coming up with a name was hard, so I’ve decide to concatenate my name and the work “Lib” together, which becomes EdLib.

Read the rest of this entry »

Posted in EdLib. Tags: . 2 Comments »

Linqify your code.


I’m sure most programmers are familiar with Linq, and agree with me that it’s great. I personally really enjoying using Linq, mostly in the form o f Linq to SQL and Linq to Objects. It also helps with simplifying your code and makes it easier to read. Some of the most useful Linq functions I find are FirstOrDefault, Any, All and Where. However sometimes I still come across developers writing loops to do work when Linq can be utilized to simplify it. So here are some simple code samples on how to use Linq to eliminate writing foreach loops.

Read the rest of this entry »