Posts

Showing posts with the label C#

The Acyclic Visitor Pattern

Knock knock The visitor design pattern is a way to add new operations to a hierarchy of classes without having to change the hierarchy itself. For example, with a simple hierarchy of fruits, you can have an IFruitVisitor interface that operates on the different classes in the hierarchy (in C#): interface IFruitVisitor { void Visit(Apple apple); void Visit(Grape grape); } The hierarchy classes then accept the visitor and fulfil the double-dispatching necessary to call the right Visit method: abstract class Fruit { public abstract void Accept(IFruitVisitor visitor); } class Apple : Fruit { public override void Accept(IFruitVisitor visitor) { visitor.Visit(this); } } class Grape : Fruit { public int NumberOfGrapes { get; set; } public override void Accept(IFruitVisitor visitor) { visitor.Visit(this); } } Note how each Accept method looks the same but is actually dispatching to a different method in the visitor ( Visit(Apple) and Visit(Grape) ). ...

DCI Example with NRoles

Image
The DCI (Data, Context, Interactions) architecture is a style that proposes an interesting separation of concerns between the domain model of a system (what the system is ) and its behavior (what the system does ), normally associated with its use cases. The rationale is that, since these parts incur change at different rates, isolating them from each other results in a system that's easier to understand, evolve and maintain. In order to enact a specific use case, a specialized context instantiates the necessary data objects assigned to the needed roles to run the required "algorithm". A very common example is that of a bank transfer operation. This example has already been described in C# with the C# quasi-mixins pattern . With NRoles the code for a role lives in a single abstraction, which results in a more compelling implementation. I'll change the example a little bit, to introduce a stateful role; something that's harder to achieve with pure C#. The...

NRoles: An experiment with roles in C#

Image
In the last months, I've been developing in my spare time a proof-of-concept post-compiler with Mono.Cecil to enable roles in C# : NRoles . Roles are high level constructs that enable better code reuse through easier composition. They are very similar to traits as described in the traits paper (pdf) . Set up NRoles is hosted on google code . You can get the latest source code with this mercurial command: hg clone https://code.google.com/p/nroles/ nroles You can also download the latest binary package from the downloads page . To set up a Visual Studio project to use NRoles, unzip the binary package (or compile from source) in a folder accessible to the project. I normally have a project root folder, with folders for the project code ( src ) and for any used libraries ( lib ). For example: src\ project files ... lib\ nroles-v0.1.2-bin\ NRoles.dll nutate.exe other NRoles binaries ... In the project, add a reference to the NRoles.dll ...

C# Mixins With State

With the C# quasi-mixin pattern , one of the biggest limitations is that the mixins can't introduce state to a class. An alternative was for the mixin interface to require the composing classes to implement a property that the mixin would use as its own, as demonstrated in this example . In the .NET Framework 4.0, the ConditionalWeakTable<TKey, TValue> class can be used to associate arbitrary state to any instance. It's thread safe and it keeps a dictionary of weak references from the target instance to its associated state. If a target instance has no references outside the conditional weak table, then it can be reclaimed by the garbage collector. When that happens, its entry in the table is removed. This makes it possible for a mixin-like class to maintain state for the instances it extends. Let's look at a mixin for a message container: public enum MessageType { Error, Warning, Info } public class Message { public readonly MessageType Type;...

Interface Implementation Through Aggregation

It's very tedious, mechanical and error-prone to implement an interface where all its members just delegate the call to some field or property that also implements the interface. For these C# types: interface I { void M1(); void M2(); void M3(); } class C : I { public void M1() { /*...*/ } public void M2() { /*...*/ } public void M3() { /*...*/ } } To implement the interface I in another class that just delegates the implementation to C , all the delegating code has to be done manually: class D : I { I impl = new C(); public void M1() { impl.M1(); } public void M2() { impl.M2(); } public void M3() { impl.M3(); } } It's not a surprise, then, that a very common request to enhance C# is the ability to lean on the compiler to generate this delegating code. The idea is to have some kind of syntax like this to achieve the same result as above: // Warning: Invalid C# ahead class D : I { I impl = new C() implements I; } This has already been ...

Roles in C# Implementation

After seeing what roles in C# might look like, let's see the necessary transformations that would enable them. This is one possibility that a C# compiler could use to implement roles without having to make changes to the underlying CLR. Roles A role is transformed into a set of types: an interface (which the compositions will implement), a static class with the role code, and a class that encapsulates the role state. The interface for the role is the most important type and it will carry the role name. Because all the generated types are related, they'll be packaged together as nested types inside the role interface. Nesting types inside an interface is not supported in C#, but is supported by the underlying CIL. So we'll be looking at some invalid C# along the way; just think of it as "decompiled" CIL. Let's see these transformations for a simple role: role RPrintableWithCount { int count = 0; public void Print() { Console.WriteLine(...

Roles in C#

Traits (pdf) are described as composable units of behavior, and are a natural evolutionary path for languages like C# or Java. Microsoft must be seriously looking at them, since it's sponsored some research about Traits in C# (pdf) . I'll describe what I think is an extension to the traits idea that would make a great feature in C# (and in Java, VB.NET, ...): roles. Roles are already a reality in Perl 5, with the Moose::Roles module. They even have their own syntax in Perl 6 . They help create better organized and reusable code, are an effective and safer alternative to multiple inheritance, and have explicit semantics (which means no surprises) as opposed to mixins. What I'll describe here is based on the theoretical traits (as described in the traits paper), on Perl roles and on Scala traits , all adapted to C#. A role is, like a class, a type that holds behavior and state. It can be composed into a type (either a class, a struct or another role) to make its memb...

A more understandable IComparable

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." - Martin Fowler In the .NET framework the IComparable<T> interface is used to compare values: public interface IComparable<T> { int CompareTo(T other); } The comparison is done with the CompareTo method. It returns zero if the current object is equal to the passed in parameter; a negative number if it's less than the parameter; and a positive number if it's greater than it. That's a very non-intuitive return value, reminiscent of the C strcmp function. I know that this scheme is already ingrained in our brains, but it creates code that's not directly decipherable: static int BinarySearch<T>(IList<T> list, T target) where T : IComparable<T> { if (list == null) throw new ArgumentNullException("list"); int lower = 0; int upper = list.Count - 1; while (lower <= upper) { int midd...

C# Quasi-Mixins Example

As an example, I'll adapt one of the mixins found in the book Fundamentals of Object-Oriented Design in UML to use the C# quasi-mixins pattern . Given the following (simplified) domain classes: namespace Domain { public enum Medium { Email, SnailMail, IntergalacticMail } public class Customer { public string Name { get; set; } public string Address { get; set; } public string Email { get; set; } public Medium PreferredMedium { get; set; } } public class Invoice { public string Header { get; set; } public List<string> LineItems { get; set; } public Customer Customer { get; set; } } } We'd like to be able to send an invoice to a customer by using his preferred medium. To keep the code to send the invoice separate from the Invoice domain class, and to abstract it so that it can send any kind of document (not just invoices) that adhere to a certain format, a mixin to send documents is created: namespace ...

C# Quasi-Mixins Pattern

Extension methods are an interesting feature of C#. They allow for behavior to be added to existing classes. For example, a ToXml() method can be added to class Object , effectively making that method available everywhere: public static class XmlSerializableExtension { public static string ToXml(this Object self) { if (self == null) throw new ArgumentNullException(); var serializer = new XmlSerializer(self.GetType()); using (var writer = new StringWriter()) { serializer.Serialize(writer, self); return writer.GetStringBuilder().ToString(); } } // for completeness... public static T FromXml<T>(string xml) { var serializer = new XmlSerializer(typeof(T)); return (T)serializer.Deserialize(new StringReader(xml)); } } So, any instance can be serialized to XML simply like this: var customer = new Customer { Name = "Guybrush Threepwood", Preferred = true }; var xml = customer.ToXml(); Now, certainly all classes ...

Revisiting IDisposable

In my last post , I've introduced a better alternative to the official pattern for implementing the IDisposable interface in .NET: public class BetterDisposableClass : IDisposable { public void Dispose() { CleanUpManagedResources(); CleanUpNativeResources(); GC.SuppressFinalize(this); } protected virtual void CleanUpManagedResources() { // ... } protected virtual void CleanUpNativeResources() { // ... } ~BetterDisposableClass() { CleanUpNativeResources(); } } This pattern is easier to understand because it cleanly separates the responsibilities to implement a disposable class that releases unmanaged (native) and managed resources in different methods. Each method is highly focused on a single identifiable task. This concept can be taken one step further, where different classes are created to deal with each concern. First, each unmanaged resource must be encapsulated in its own class: public class NativeDisposable : IDisposa...

A Better IDisposable Pattern

In .NET, objects that implement the IDisposable interface are objects that need special cleanup code to run deterministically when they're not needed anymore. (Another interesting use of this interface is to delimit a scope , but I'll focus on the original cleanup use case in this post.) public interface IDisposable { // cleanup resources void Dispose(); } Most .NET languages have a special syntax to automatically call the method Dispose at the end of a scope where the object is used. In C#, this special syntax is implemented with the using statement: using (var stream = File.OpenRead("interestingFile")) { // do something interesting } The compiler expands this code to: var stream = File.OpenRead("interestingFile"); try { // do something interesting } finally { if (stream != null) { ((IDisposable)stream).Dispose(); } } Sweet sugar indeed. To implement the IDisposable interface in a non-sealed class, there's an of...

C# Static Classes are not Real Classes

In C# and in Java, there's a common idiom to provide utility functions as static methods of classes that cannot be instantiated. This stems from the limitation that these languages don't allow the definition of any function outside of a class. This can be seen as an anti-pattern, because what's missing is the ability to declare functions, not only classes; like in C++. The class has to be declared sealed (final in Java) and a private constructor must be created to prevent inadvertent instantiation. public sealed class ConversionUtils { private ConversionUtils {} public static double ConvertTemperature( double fromTemperature, TemperatureUnit fromUnit, TemperatureUnit toUnit) { ... } } In C# 2.0, static classes were introduced to the language. A static class is a special type of class that's annotated with the static modifier and that: can't be instantiated (implicitly abstract) can't be subclassed (implicitly sealed) can...

Optional Parameters and Method Overloads

The ability to declare optional parameters is another feature that will be introduced in C# 4.0. A natural complement to method overloads, it generally helps code to be more concise. Until now, method overloads have been used for the awkward responsibility of creating default values for what otherwise would be much better expressed as optional parameters. Many overloads have been created for which the sole responsibility is to call another overload with some default values for some parameters. public CreditScore CheckCredit() { return CheckCredit(false, true); } public CreditScore CheckCredit(bool useHistoricalData) { return CheckCredit(useHistoricalData, true); } public CreditScore CheckCredit( bool useHistoricalData, bool useStrongHeuristics) { // do the heavy-lifting ... } For this style of method, optional parameters let you create just one method, with default values set on its signature. public CreditScore CheckCredit( bool useHistoricalData = false, bool u...

Named Parameters Increase Readability

When reading C# code, sometimes there are method calls which aren't readily obvious. The method can have too many parameters, or a series of parameters of the same type. This can make things a little confusing. A more aggravating case is that of boolean parameters. It's hard to find out what true or false mean in some cases. var creditScore = customer.CheckCredit(false, true); Normally, we need to look at the method signature to understand how it's being called, and what each parameter represents. public CreditScore CheckCredit( bool useHistoricalData, bool useStrongHeuristics) { ... } Since code is more often read than it's written, any means to improve readability will have a direct effect on maintainability. Every line of code should clearly communicate its intent. No clever hacks or streams of unintelligible parameters. A good solution to the boolean case is to use enumerations. This way, we force the caller to use a well known name for the param...

C# Extension Methods and Null References

With extension methods in C# 3.0, you can create methods that operate as if they were instance methods of other classes. You can "add" methods to any class, even to core classes like System.String and System.Object . This example creates two string extensions: public static class StringExtensions { public static string HtmlEncode(this string input) { return AntiXss.HtmlEncode(input); } public static int ToInt32(this string s) { return Int32.Parse(s); } } (I used the HtmlEncode method implemented in the Anti-Cross Site Scripting Library .) The way to use extension methods is to call them as if they were instances of the extended class itself (given as the first parameter to the extension methods): int input = "123".ToInt32(); ... string safeString = unsafeString.HtmlEncode(); Or you can use them as normal static methods (it has the same effect as above): int input = StringExtensions.ToInt32("123"); ... string safeStri...