Archive for the ‘solid code’ Category

Dotnet generics constraint

June 2nd, 2010

When working with generics in dotnet (like templates in C++) there is something called “constraint” that limits the type of generic you can use.

Say you have a method

AreEqual bool<T>(T x, T y)
{
return x == y;
}

It will stop in the compiler since T isn’t necessarily comparable.  So we have to make sure T is.

AreEqual bool<T>(T x, T y) where T:IComparable
{
return x == y;
}

This example requries T to implement IComparable; i.e. int and string but not necessarily Customer.

Other constraints are “struct” constraining T to value types like int and enums, “class” for contraining to classes or “new()” for requiring a default constructor (constructor without parameter).  One can also constrain to inherit from a class and even send this class as a parameter like T.

The constraints are limited and I have often stepped into limitations I cannot recall right now.

More info here: http://msdn.microsoft.com/en-us/library/d5x73970%28VS.90%29.aspx.

>Checking events in VBNet

March 4th, 2010

>Due to some reason unknown to man the team behind VBNet decided that the developer should not be able to see if someone listened to your event or not. It is good in most cases but very bad in another.

In Csharp raising an event goes something like this:
var ev = MyEvent;
if( null != ev ){ ev( this, args ); }

Just look through the snippets (look in the context menu in the editor) and you will find the correct way to raise an event in Csharp.

VBNet on the other hand hides the if statement and the temporary variable from the developer. It is enough to write
RaiseEvent Me, args
and the event will be raise if there is someone listening – no need to check for null.

But what if you want to check if someone is listening. In my case I needed to know if the custom control was properly wired into the scaffolding of the application; the user control sometimes whished for more information and I had to know if someone was listening.
In Csharp this would have been easy with a check for null. But VBNet…

The solution is hidden. Just check the variable “MyEventEvent“. This means that your MyClick event has a hidden variable MyClickEvent that you can check for like this:
If MyClickEvent IsNot Nothing Then

I don’t like to use hidden and unoffical solutions but this is the only way I know of.

Honor those who should.

>Avoid code ownership

March 22nd, 2009

>

I heard a thing the other day I haven’t heard for a long time.  “That is not my code”

I believe no code and all code in your current project is Yours.  There is nothing like finding a bug and leaving it be.  If you can’t correct it, flag it.  Either in a bug tracking system, to the person currently working with that part or to wherever your project stores possible riscs.

This my code-your code mentality mentioned above lead to the bug being forgotten.
That is not considered good.

>List Find Delegate

January 5th, 2009

>

Here is a short example of how to use the Find method together with an anonymous delegate in C#.
(there are plenty of examples on the web but most forget to use an external variable)

var myExternalVariable = “Cool”;
List list = new List(new string[]    {“Cows”,”Are”,”Cool”});
var possibleWord =
    list.Find(delegate(string s)
        { return s == myExternalVariable; });

if you want to be even hairier, translate to lambda

var possibleWord = list.Find(s => s == myVariable);

Sort.

>Code that is easy to read

December 30th, 2008

>

An important code regarding programming is to write code that is easy to read.

I have many times written code, polished it and then rewritten it to the original text since it was easier to read.  This is considered mature and a good thing.

A month ago I wrote code like this:
    return AllControlsRecursively((Control)form
        ).FindAll( control => (null == control as IDirty) ? false : true
    ).ConvertAll( control => (IDirty)control );

I thought about it for several days and then decided to leave the code as it was.

My reasoning behind this is that once upon a time I had problem understanding Fn in BASIC.  Later * and & in C.  Then I had to learn inheritance, virtual methods and abstract.  Today it is lambda methods, WCF and WPF.

One day one has to decide to get the fingers dirty.  That day is every day.

>How to raise an event

January 24th, 2008

>It is very simple to raise events in dotnet/C#.
But there is a caveat one should be aware of; especially since it probably will show itself intermittently and be hard to track down. It is when someone finishes his listening for the event between the does-someone-listen-for-the-event and the very firing.
The good news is that it is easily solved by a temporary variable like so:

internal event NavigateDelegate OnNavigate;

internal delegate void NavigateDelegate( NavigateTypes navigateType );

private void Raise_OnNavigate(NavigateTypes navigateType)
{
    NavigateDelegate tempEvent = OnNavigate;
    if (null != tempEvent)
    {
        OnNavigate(navigateType);
    }
}

If the above is hard to remember there is a snippet
    invoke
to use.  Just write it at a line and press Tab.

>The simplest possible solution, but not simpler than that

January 22nd, 2008

>This message will be repeated in english.

När man inom Agile pratar om den enklaste metoden menar man inte den lösning man först kommer på eller den som går snabbast att implementera.
Med enklast innebär den lösning som löser uppgiften med minst extra information och avsteg från befintligt mönster.

Detta kan tarva en förklaring.
Med minst extra information menas möten, dokumentation och implicit och explicit kunnande. Om lösningen följer gängse mönster behövs antagligen ingen dokumentation, varken som explicita dokument eller inline-kommentarer. Om lösningen är “rätt” krävs mindre möten, diskussioner, dokumentation, rådfrågningar och redogörelser.

Enklast är inte nödvändigtvis den lösning som kräver minst tankearbete eller minst jobb.

För att vara ärlig talar jag inte för hela den agila rörelsen. Texten ovan är min tolkning av begreppen, metoden, livet, universum och allting.

When the agile development movement talks about the simplest solution; they do not mean the first solution that pops up in the head or is fastest to implement.
Simplest means the solution that solves the problem with least extra information and sidesteps from the chosen/optimal path.

This might demand an explanation.
With least extra information means meetings, documenation, implicit and explicit knowledge. If the solution follows the chosen path, colour and rythm of other well written parts of the solution; it probably doesn’t need documentation, neither as explicit documents nor as inline comments. The “right” solution requires less meetings, discussions, documentations, questions and answers.

The simplest solution it not neccessarily the solution that requires the least amount of thoughts or work.

To be honest I cannot say I speak for the whole agile movement. The text above is my view of the terms, the method, life, universe and everything.

>Build list classes

January 17th, 2008

>This message will be repeated in english.

(dotnet-kod)
Gör listklasser av dina klasser.
D.v.s. gör en egen klass
    class UserList : List
    {
        …
    }

För då blir anropen

    UserList userList = new UserList( “whatever parameters” );
    User user = userList.FindByName( userName );

istället för

    List userList = GetUsersByWhatever( “whatever parameters” );
    User user = FindUserByName( userList );

Lika många rader kod och ungefär lika lättläst men bättre “information hiding” i de senare exemplet.

(dotnet code)
Make list classes of you classes.
Make it like

    class UserList : List
    {
         …
    }

Then you can have calls like

    UserList userList = new UserList( “whatever parameters” );
    User user = userList.FindByName( userName );

instead of

    List userList = GetUsersByWhatever( “whatever parameters” );
    User user = FindUserByName( userList );

About as many rows of code and about as readable but better information hding in the latter example.

>Volta and Script# – type safe javascript

December 11th, 2007

>This message will be repeated in english.

Så länge jag har känt mig själv har jag klagat på den svaga typningen i Javascript.
Jag kan förstå att implementationen är olika mellan olika webbläsare och nästan, men bara nästan, förstå Microsofts egocentriska volt med IE att göra en egen händelsemodell. Men jag kan inte förstå det strategiska beslutet av Netscape att göra ett svagt typat språk.

För några år sedan ramlade jag över en lösning, Script#, som kunde omvandla typsäker C#-kod till Javascript. Den var ett experiment så jag vågade aldrig ta in den i produktion och hade inte tid att leka med den. Vad jag inte visste förrän nyligen var att Microsoft har tyckt som jag.

Så nu har de lanserat Volta.

As long as I have known myself I have been irritated on the weak type model of Javascript.
I can understand that the implementation of Javascript differs between the web browsers. And I can almost understand Microsofts egocentric trick with Javascript in the earlier IE versions. But I have never understood Netscape’s reasoning behind making a language weakly typed.

Some years ago I stumbled over a solution, Script#, to convert type save C# code to Javascript. It was an experiment so I never dared to bring it into production even though I wanted to. What I didn’t know was that obviously someone at Microsoft thought like I.

So now they have launched Volta.

[Update: Bytte mjuk mot svag.]

Nettiers

October 24th, 2007

>This message will be repeated in english.

Jag har jobbat med Codesmith i två projekt och Nettiers i ett av dem.  Jag kan rekommendera.

Jag har inte jobbat med konkurrenter och kan inte jämföra.  Någon?

Det har varit kritiskt att det är gratis i bägge fallen så sista Nettiers/Codesmith-kombinationen som är gratis är http://nettiers.googlecode.com/files/netTiers-2.2.0.zip och http://www.codesmithtools.com/freeware.aspx.

Det finns för- och nackdelar med automatgenererad kod.
Codesmith är closed source medan Nettiers-mallarna är GPL.  Märk: resultatet av Nettiers-mallarna är inte GPLade utan dina.

I have worked with Codesmith in two projects and with Nettiers in one of them.  Recommended.

I have not tried any competitors and cannot compare.  Anyone?

In both projects it was crucial the price was zero so instead of you looking around just go to the last zero-price combination.  http://nettiers.googlecode.com/files/netTiers-2.2.0.zip and http://www.codesmithtools.com/freeware.aspx.

There are pros and cons with automatically generated code.
Codesmith is closed source while Nettiers templates are GPL.  Note: the result of Nettiers is not GPLd but yours.