Posts

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) ). ...

Self-types in NRoles

Since roles are weaved into target classes, it's sometimes necessary for them to be able to identify the type of these classes. NRoles supports self-types through the use of a type parameter with the special name S : public abstract class REquatable<S> : IEquatable<S>, Role { public abstract bool Equals(S other); public bool Differs(S other) { return !Equals(other); } } To cast this to the type parameter, just use the Cast<T> extension method: public class Identity<S> : Role { public S Self { get { return this.Cast<S>(); } } } When other roles compose roles with self-types, they must flow the self-type through, since it will ultimately be determined by the target classes that compose them: public abstract class RComparable<S> : IComparable<S>, Does<REquatable<S>>, Role { ... } The post-compiler will check all classes that compose roles with self-types and issue an error message if the typ...

Java 8 virtual extension methods are begging to be free of interfaces

To cope with API evolution and to provide new extensions for lambda-friendly methods, Java 8 will introduce a form of extension methods in interfaces (which were called public defender methods in previous iterations of the proposal). Interface methods will be allowed to have bodies (or just a reference to a static method): interface MyInterface { void method() default { System.out.println("A good idea?"); } } A class implementing MyInterface doesn't need to provide an implementation for method() . This is particularly valuable for interface evolution to maintain binary compatibility with classes already compiled with the old interface version. In general, the old binaries would work with the new defaulted interface method without recompilation; it will just use the default implementation. The default keyword is a deliberate choice not to conflict with the rule that "interfaces have no code". Now they can have default code. Conflict resolution...

Some OO Design

"The critical design tool for software development is a mind well educated in design principles. It is not the UML or any other technology." - Craig Larman I've recently found the following interview question on stackoverflow : Basic sales tax is applicable at a rate of 10% on all goods, except books, food, and medical products that are exempt. Import duty is an additional sales tax applicable on all imported goods at a rate of 5%, with no exemptions. When I purchase items I receive a receipt which lists the name of all the items and their price (including tax), finishing with the total cost of the items, and the total amounts of sales taxes paid. The rounding rules for sales tax are that for a tax rate of n%, a shelf price of p contains (np/100 rounded up to the nearest 0.05) amount of sales tax. This is a very familiar example that can be used as a really good gauge of various software development skills. There are many different ways to solve this problem. ...

Why is composition harder than inheritance?

(just some random thoughts...) Let's take this Java example: class Base { public void method() {} } class Derived extends Base {} See how easy it is for Derived to "reuse" code from Base ? Derived is a subclass of Base , and in its constructor it calls Base 's constructor, constructing a Base before constructing a Derived : class Derived extends Base { // this is what gets generated by the compiler: public Derived() { super(); } // this doesn't exist, but illustrates what happens when we call Derived.method: public void method() { super.method(); } } Also, Derived instances have a "forwarding" method, that, when called, will delegate to the corresponding base method (this is not technically what happens, but I'm looking at the "concept" here). Isn't that convenient? Why isn't the same capability available to compose classes? Composition is always a better strategy than inheritance in "reuse" ...

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 ...

More Macros in Nemerle

After a very brief introduction to Nemerle metaprogramming , what follows is some motivation and better expression macros examples. Historically in C#, the using statement has been abused (guilty!) to provide a more convenient syntax to operations that have natural wrap up code which should be executed at the end of a logical scope. To enable a class to be usable like this, it just needs to implement the System.IDisposable interface. The problem is that these elements were designed with a very specific and important goal in mind: the deterministic disposal of unmanaged resources. That's why using wraps the call to IDisposable.Dispose() in a finally block: it has to run no matter what. A finally block is a very strong statement. It runs in the presence of exceptions, and it can't be interrupted by a ThreadAbortException , what can delay a whole application domain shutdown. That's justified for releasing resources, but it is too strong a statement for simple wrap...

Metaprogramming in Nemerle

Nemerle is a generally unknown .NET language that nevertheless has many impressive features. Its syntax is close to C#, but it has many functional programming constructs, like algebraic data types and pattern matching, that are not found in the Redmond language. It also has a very powerful metaprogramming system, where special constructs can participate in the compiler's execution pipeline and generate or manipulate code in the target program. Metaprogramming can be very useful to cut on duplication, to apply consistent policies throughout a codebase and to raise the overall expressiveness of the code. It's one of the things that makes Ruby on Rails such a compelling and successful web application framework. Unlike Ruby , Nemerle is a compiled, statically typed language, where metaprogramming is possible already in the compilation step. For a very simple (and unrealistic) example, imagine that we use lots of infinite loops in our code. In some parts we use while(true) ...

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...