The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

tempusfugit (144) [Avatar] Offline
#1
I realize that the code isn't production strength and that it needs to be simple to get the point across. However there is one aspect about the code that strikes me as inconsistent. FuncList.Cons takes advantage of the immutability of the "tail list" and simply reuses it to construct the new list. However the most common "tail list", the empty list (instance) is always duplicated whenever you start a new list.

A couple more lines of code could make "The Empty List<T>" (that is, the empty list for a particular type parameter T) reusable without getting into a separate class or using the Special Case/Null Object pattern. Granted, there is little to be gained from saving a few instances of empty list object instances. However I think a shared empty list better communicates the idea that it is safe to share any "tail list" between lists thanks to the immutability of the lists themselves.

[pre]
public class FuncList<T> {

public FuncList(T head, FuncList<T> tail) {
IsEmpty = false;
Head = head;
Tail = tail;
}

public bool IsEmpty { get; private set; }
public T Head { get; private set; }
public FuncList<T> Tail { get; private set; }

// Enforced "Just Create One"
// http://butunclebob.com/ArticleS.UncleBob.SingletonVsJustCreateOne
//
public static FuncList<T> EmptyList { get { return emptyList; } }

private static readonly FuncList<T> emptyList = new FuncList<T>();
private FuncList() { IsEmpty = true; } // For the EmptyList only
}

public static class FuncList {

public static FuncList<T> Empty<T>() {
return FuncList<T>.EmptyList;
}

public static FuncList<T> Cons<T>(T head, FuncList<T> tail) {
return new FuncList<T>(head, tail);
}
}
[/pre]