Skip to content

Instantly share code, notes, and snippets.

@jamesmanning
Created July 17, 2014 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesmanning/d6fd8b83a6a6cdc5ac91 to your computer and use it in GitHub Desktop.
Save jamesmanning/d6fd8b83a6a6cdc5ac91 to your computer and use it in GitHub Desktop.
why empty list is better than null
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var data = DataFetcher.GetData();
var stringsForUser = DataExplainer.BuildStrings(data);
// TODO: handle stringsForUser being null since we don't have non-null reference types in C#
// THIS IS WHERE WE ARE SENDING OUTPUT TO THE USER, AND WHERE WE SHOULD THEREFORE HANDLE THE CASE OF EMPTY
if (stringsForUser.Any() == false)
{
Console.WriteLine("No data was found");
}
foreach (var stringForUser in stringsForUser)
{
Console.WriteLine(stringForUser);
}
}
}
public static class DataFetcher
{
public static List<int> GetData()
{
// 50/50 chance you'll actually get data back
if (new Random().Next()%2 == 0)
{
return new List<int>() { 1, 2, 3 };
}
else
{
return new List<int>();
}
}
}
public static class DataMunger
{
public static List<int> Square(List<int> input)
{
// TODO: handle input being null since we don't have non-null reference types in C#
return input.Select(x => x*x).ToList();
}
}
public static class DataExplainer
{
public static string GetExplanation(int original, int squared)
{
return String.Format("The square of {0} is {1}", original, squared);
}
public static List<string> BuildStrings(List<int> input)
{
// TODO: handle input being null since we don't have non-null reference types in C#
var squared = DataMunger.Square(input);
var explanations = input.Zip(squared, GetExplanation).ToList();
return explanations;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment