I was reviewing code today and one of the things we discussed was if certain data should be parameters to a method or if they should be attributes of the class that held that method.

When I see a method I want every argument used in decisions or in expressions that will eventually make their way to the return value. If there’s no return value the method probably have side effects and if that’s the case I’d probably rewrite the method so for this post let’s stick to a method with return value.

The issue we had was that some of the arguments were actually used to ensure invariants but invariants not ever changing they are known at the time the object is created and should be enforced at the time of creation. If they are violated at the time of creation they are still violated at the time of execution.

The first point worth mentioning is to enforce constraints as early as possible to fail as early A’s possible. If some constraint can be enforced at compile time they should be.

The second point worth mentioning is that every argument given to a method should influence the flow of the method everytime and possibly the result as well. The only exception to influencing the result I can think of is when the result is partly based on things external to the method. E.g. if the method is returning calls to a database.

Continuation passing

Posted: June 3, 2009 in c#, ProS

While working on version 0.3 of ProS I had the following requirement:

When given a list of statements that all return a value of IProcessor (That interface defines a method called Process) call each processors process method in turn and pass the result of the execution to the next processor in the list if and only if the result is null. At the same time the sequence of calls needs to be wrapped in a new IProcessor object so that the entire sequence can be part of another sequence.

After trying a few different approaches I ended up with using continuation passing. But what is that?

given two methods:

public int GetRandomInt()

{

return new Random().GetNext();

}

public void DoSomethingWithAnInt(int i)

{

Console.WriteLine(i.ToString());

}

a main could look like this:

public int main()

{

var i = GetRandomInt();

DoSomethingWithAnInt(i);

}

if we wanted to turn that into continuation passing we would have to change the first method and make it something like

public void GetRandomInt(Action<int> doSomethingWithAnInt)

{

var i = new Random().GetNext();

doSomeThingWithAnInt(i);

}

and main would then simply be

public int main()

{

GetRandomInt(DoSomethingWithAnInt);

}

This is actually more common than what you might think at first. Think of any Async call in .NET you’ll probably remember that one of the arguments is an AsynCallback. That call back is the continuation of the Async call. So for implementing asyncromeous behaviour the continuation passing style is very straight forward, simply pass what you want executed when the first call completes.

I need to represent a tree where each node is a decision point. E.g I might need to represent the code structure

if(a())

{

DoA();

}

else if (b())

{

DoB();

}

else

{

throw new InvalioperationException(“No sensible default action”);

}

however a() and b() is not known compile time and the number of if’s is not known either.

I ended up with a class called ContinuationProcessor that looks similiar to this:

public class ContinuationProcessor<T> : Irpocessor<T>

{

public ContinuationProcessor(ContinuationProcessor<T> continuation, IProcessor<T> processor,Func<object[],bool> condition)

{

//initialize the private fields

}

//This method is defined in IProcessor

public T Process(T obj, params object[] arguments)

{

T processedObj = null;

if(condition((new object[]{processedObj}).Concat(arguments)))

{

processedObj = processor.Process(obj,arguments);

}

if(continuation != null)

{

processedObj =  continuation.Process(processedObj,arguments);

}

return processedObj;

}

}

So it ends up not being true continuation passing since I end up returning a value, but it does make it possible to represent an arbitrary number of decision points together with the code that should be executed in case the associated decision is taken.

It’s a lot of fun writing code that represent code, but it gives me a headache trying to debug it…

Things that makes me go hmm

Posted: May 30, 2009 in Uncategorized
Tags:

One of my favorit bloggers Eric Lippert wrote recently a post he called “Things that makes you go hmmm”
I’ve written a few hmms in other post bu t just stubled across another one today.
In c# it’s perfectly legal to declare a constructor protected in a sealed class!
Kind of strange. How would you instatiate that class (without using reflection)

Just finished v0.2 actually there’s not that much new to v0.2. It simple adds a property production to the language as well. The syntax is similar to the one used in c#

A long the way I had quite a few strange experiences. The one that took me the longest to find a solution for was the fact that new LanguageCompiler(new Grammar()) (languageCompiler is a Irnoy class) ment to differrent things depending on how I used my compiler. If I used it with the Grammar Explorer from the Irony project or in the VS SDK hive everything worked fine, but using it stand alone to compile to a .dll new Grammar() suddenly turn it self into instanciating the Irony GRammar class instead of the PRoS Grammar.

Never figured out why but I can only say it’s a good thing to have the source code of the Libraries you’re using when you have to hunt down the reason to why they throw a null refererance exception.

Guess that the next thing I’ll include is a propperty setter or more advanced caching than the simple property

During my development of ProS I’d had to dig into Reflection.Emit again and one thing that keeps puzzeling me is the way the class in Reflection.Emit is designed.

Take for an example Typebuilder, the corner stone of creating a new class using Reflection.Emit. It inherits from Type however most, if not all methods it inherits from Type is overriden with a version that throws an exception explaining that that particular method is not available on TypeBuilder. The same goes for MethodBuilder, PropertyBuilder and all the other builders That all inherit from xInfo.

The design decision is a hefty violation of the liskov substitution principle (LSP) and for just that reason I’d say they need a really good argument for it. It basically results in yoou having to build a framework for reflection on your newly created types and members to be able to create a compiler. It’s a trivial but time consuming process to make that reflectio possible and well since it’s trivial I can not find that really good argument for violating LSP.

Needless that Im a huge fan of designing by contract, that’s basically my driving motivation for creating ProS, and devolping ProS I hope Im not violating LSP. If I am that is going to give me even more grey hair when I get to testing the plugability. The supporting structure of the plugability is LSP.

I’ve decided to write a post for if not all the incremental versions of ProS then at least quite a few of them. My goal is to make addition to ProS and the rebuild ProS using those additions. The reasons for this approach are mainly two. I get a good idea of what’s working and what’s not and I might just get new ideas a long the way.

Reading a book written by the team who originally created SharpDeveloper (an Open Source IDE for c#) I learn the concept of “eating your own shit” as they called it. The Search and replace functionality had been lacking and at some point they realized that the developer doing that part of the IDE was him self using UltraEdit (or some other tool) when he needed to search and replace. With that in mind they decided that going forth they could only use SharpDeveloper for their development.

It’s the same thing I’m trying to do here, though my goal is not to make a Turing_complete. Actually I’m not sure it’s even Turing incomplete 😉 So writing all of ProS in ProS will not be an option.

The first version is little more than a configurable object factory. Except for things such as using, types and values there’s really only one contruct to the language: The constructor.

The cunstructor gives the option of creating what well end up being a method returning an instance of an object. The syntax is

constructor returnType Name(arguments) : objectType

{

statements

}

The constructor is a keyword say: “next is the definition of a constructor. arguments hav the c like syntaks: type name and multiple arguments a seperated by a comma.

Statements can in this version only be used for setting ctor (which is the term I’ll use for class constructors to not confuse them with ProS constrcutor and by the way the term class is intentional) arguments. A stament could look like

number = 10;

That would tell the ProS compiler that each time this constructor is call the value passed for the arument number to the ctor must be 10. The argument names must match ctor argument names as well, and there must be a ctor with a list of arguments that matches the total of arguments and statements.

A complete example could look like the below:


using
Irony.Compiler;
using
Motologi.ProSLanguageService;
using
Motologi.ProSLanguageService.Compilers;
alias
tokenCompiler = ITokenCompiler;


class
Compilers{
constructor
tokenCompiler Alias(AstNode node) : AliasCompiler {

}
constructor
tokenCompiler Using(AstNode node) : UsingCompiler{

}
constructor
tokenCompiler Argument(AstNode node, TypeEmitter typeEmitter) : ArgumentCompiler{

}
constructor
tokenCompiler ArgumentValue(int position, bool isForStaticMethod):ArgumentValueCompiler{
}


constructor
tokenCompiler Class(AstNode node, TypeEmitter typeEmitter):ClassCompiler{

}
constructor
tokenCompiler Configuration(AstNode node, TypeEmitter typeEmitter):ConfigurationCompiler{

}
constructor
tokenCompiler Constructor(AstNode node, TypeEmitter typeEmitter):ConstructorCompiler{
}


constructor
tokenCompiler Identifier(AstNode node, TypeEmitter typeEmitter):IdentifierCompiler{

}
constructor
tokenCompiler Int(AstNode node, TypeEmitter typeEmitter):IntCompiler{
}


constructor
tokenCompiler Statement(AstNode node, TypeEmitter typeEmitter):StatementCompiler{

}
constructor
tokenCompiler String(AstNode node, TypeEmitter typeEmitter):StringCompiler{
}


constructor
tokenCompiler Type(AstNode node, TypeEmitter typeEmitter):TypeCompiler{
}
}

That class declaration is the inner workings of the ProS compiler ver 0.2. The result is two classes. One is called Injector and the other is called Compilers. The class Compilers is what is directly defined in the above code. For each of the construct there’ll be one static method on the class Compilers. The method will take the arguments listen in the argumentslist for the constructor and will return an instance of the type specified after ‘:’ I.e TypeCompiler for the last constructor.

The Injector class is nothing more than a container. For all the constructs defined in all classes there’ll be an over over of a method called Get. In essence it’s a large factory that given an ID and a set of arguments will return an object.

In contrast with say Windsor’s ServiceContainer or similar in other reflection based frameworks the list of arguments is type checked compile type.

The approach of compiling the dependency configuration does impose some other (sometimes strange) issues. So the gain in type safety and performance is not for free. But some of those issues can be resolved with delayed compilation. So that the types mentioned above wont be created until runtime. I have a plan of adressing just that in a later version of ProS. For now I’ll dig into ProS ver 0.2 using the above configuration

Well as I mentioned in Creating dynamic types in net im currently working on a language compiler. The language is called ProS. Thinking of it I might blog on the language name at some other point. The short version is that my thesis in compilers at Uni was called ‘ProS’ and whe I worked on the first version of this language I realized a lot of similarities to that project.

If you wander what happen to the first version: It died. My laptop died two days after I infected my back with Vira due to me making a backup of my moms HDD. Note to self. Use seperate backup media to own data in future.

The language is YANL (Yet anothe .Net language). you can write a program using the language only certain classes. I’m using dependency injection in all my projects and I’ve been using a few different and as noted in MAB ContainerModel / Funq: a transparent container most are painstackingly slow when it comes to creating objects. To me that’s a bit weird they are all used for just that!

The problem for most of them is that they are build on reflection. To me that’s two problems in one.  The main reason they are slow is due to reflection being slow. The second problem is that reflection is not safe.

(That is not entirely true:Typed Reflection but for the way reflection is used by ObjectBuilder, Windsor and similar the satement is true)

I like the way Funq mentioned above solves the problem with Lambda expression but I decided to take another approach to it by making a domain specific language to hanlde the injection. Basically what you can do is some thing like:

class Injector

{

constructor returnType GetMyObject([arguments])

{

//Here goes your dependency arguments

//Setting an argument named arg1 to 10:

//arg1 = 10;

//Then comes property setters.

//Same syntax as above

}

}

This will compile into a class named Injector with a set of methods called GetMyObject. The number of methods created depends on the number of constructors on the class returned by GetMyObject and the arguments given to GetMyObject. The arguments given to GetMyObject will be passed on as arguments to the constructor.

The result I expect is that this approach will be basically as fast as just simply calling the constructor. The method call is trivial and in the simple form is just one extra jump instruction.

The benefits of the ProS approach to the reflection approach is, not surprisingly, speed and type safty. After all that was my two main design goals. I’m very much looking forward to performing Daniel Cazzolino’s benchmark test to Funq and ProS.

Due to the fact that Irony and the Visual Studio SDK making it trivial to get highlighting, brace macthing and similar.  ProS comes with that as well.

Next step in the development is to take my version 0.1 and turn it on it self. Using ProS 0.1 as dependency Injector for ProS 0.2

A long the way I’ll make a few other features and add them to ProS v0.2.
A few of them are standard in most Ioc’s such as making caching possible but a few Is ProS only. One of them I had a lot of fun with when building version one. Making the Compiler plugable.

I’d write a post on  making the compiler plugable. For now I’ll just stick with saying it’s fun but im affraid it’s also the option of potentially really weird coding.

Im working on a language at the moment, which i’ll blog more on later. During the development I came to a point where I needed to actually create assembly files to test the result of the compiler. I’ve writte a few compilers using Reflection.Emit before and I’ve always come to a point where everything seems to be working fine. Using reflection I can see all the methods and all the classes but when I write it to file. There’s absolutely nothing but the manifest.

I seem to forget the trick everytime. If the module name is different from the filename it just wont work. I have actually no clue to why that is. But I had the problem today and with one single change namely making the module name the same as the file name, I solved the problem. If you don’t need to save your assemblies to disk, your basically free to choose the module name.

One of my collegues had an intereseting error report from our test suit today:

Error: “Expected 3 but was 3”

At first glance it might seem that everything is as expected!! actually it’s not but finding where the error is might be a little tricky. There’s not a lot of information to start with.

The problem is a some what shaky implementation of the unit test framework we’re using. The line of code that reports the error looks like
ASSERT_EQ(++errorCount, errorHandler.Errors.Count);

I personally don’t like the ++errorCount argument but would expect it to be fine except ASSERT_EQ is a macro and the argument is used once for comparison and once for outputting and hence incremented twice

Moral: If you’re not 100% sure what a macro does and you need it to work on a value pass a value. Only pass expressions when the macro needs an expression and not a value.

Changing habits

Posted: February 13, 2009 in Uncategorized

I’ve been reading a few posts on http://www.hanselman.com/blog/ lately under the category “I suck”. A typical Scott way of putting things and very educational.

It’s so easy to just say every one else are stupid and if they would just listen it would be so much easier and I do it a LOT.

So of that is due to my job requires me to analyse every one else job and find where they can improve. It’s a lot easier to improve what people are doing badly than improving what they are already doing well so I focus a lot of my work on the first but that’s just part of the reason. It’s a lot less costly to find some one elses faults thatn your own or at least so it seems.

I used to work in a company that made different measuring devices and our tag line was “If you can’t measure it, you cant’ improve it” I used to use that a lot a few years ago when I was envolved in pro sport but after retirring from that I’ve kinda forgotten it again. Reading Scott’s post reminded me of the value of measuring yourself once in a while.

Part of my work is changing peoples habits and one of the things I need to improve is the way I communicate what they should do differently. If you take a look at some of my posts you’d see that I’m quit capable of telling people what not to do! that’s seldom a productive way to change habits.

Try saying the following to your kind one day “Don’t put your toast in the VCR” (only works if they actually knows what a VCR is and you actually have one 🙂 ). The NLP community would call that an embedded command. The visual cortex is not capable of visualizing negations so all the kind will visualize is “put your toast in the VCR” the chances of that visualization helping you reach your goal of no food in the VCR could be improven if you told your kind to eat the toast or asked “how does you toast taste”. After all they can’t answer that if the toast is already in the VCR.

The point is that Im sure I would have more success in changing peoples habits by telling them what to do instead of telling them what not to do.

I personally reacts badly to people telling me what not to do. If my girl friend tells me I spent to much time with my computer and probably end up getting made if she says that to many times. Not because I wouldn’t gladly prioritize her needs. I just hate guessing what they are. If however I got questions like “Wanna go to the movie with me/Sit in the couch and chat” or what ever she would want to do she can’t do because Im working/playing poker at my computer my reaction would probably be a smile and “sure honey”

I might be more extreme in my reactions to being told what not to do. It easily pisses me off but Im sure that Im basically no different from others.

If you want people to do things differently tell them what you want them to do, not what you want them not to do. So instead of telling my self not to tell people what they shouldn’t do I think it’s time I told my self that I should tell people what they need to do.

and as a final note never tell people the should do somthing you want them to do and never say they shouldn’t do something if you really don’t want them to. Say youi would like them to do something. Why? imagine yourself standing in front of an open fridge look at your favorite chocolate cake and a brocolli. You’d probably be thinking I should eat more brocolli that would be so good for me when you look a the brocolli while when you look at the cake you’d think I really shouldn’t have more cake. Im betting you rarely ends up in the couch enjoying a big chunck of brocolli. Usually our “shouldn’t”s are rewarded and our “should”s are followed by punishment. 

Don’tget people to  associate want you what them to do with punishment by saying they should instead use words as “need”, “wish”, “like to” and similar