Gestern fand das erste .NET Coding Dojo in Hamburg statt und es war aus meiner Sicht ein voller Erfolg. Als erstes möchte ich mich an dieser Stelle bei der Firma masters of arts für die Räumlichkeit und natürlich bei allen Teilnehmer für die aktive Mitarbeit bedanken.
Durchgeführt haben wir das Dojo im Randori-Stil, d.h. es gab einen Entwickler, einen “Co-Piloten” und das Publikum. Nach jeweils 5 Minuten bzw. jedem neuen Testfall wurden die Positionen mit neuen Teilnehmer aus dem Publikum getauscht.
Nach einer kurzen allgemeinen Einführung in das Thema “Coding Dojo” habe ich die Aufgabenstellungen der Kata.FizzBuzz und Kata.DictionaryReplacer vorgestellt. Durch kurze Abstimmung haben wir dann (vermutlich durch meine Wortwahl beeinflusst) die Kata.DictionaryReplacer gewählt.
Mit der Wahl dieser Kata war ich nicht ganz unglücklich, da wir DictionaryReplacer schon im Online Dojo durchgenommen haben und ich deshalb die Fallstricke schon etwas einschätzen konnte.
Kata.DictionaryReplacer
Create a method that takes a string and a dictionary, and replaces every key in the dictionary pre and suffixed with a dollar sign, with the corresponding value from the Dictionary.
Nach kurzer Einführung in die Vorgehensweise des Test-Driven Developments (TDD) und Diskussion über sinnvolles Naming ging es dann auch richtig in die Entwicklung. Die Kata eignet sich in dieser Form auch sehr schön um tatsächlich “Test first” zu arbeiten. Die Implementierung folgt quasi als logische Konsequenz.
Interessant und ungleich komplizierter wurde es dann als wir eine zusätzliche Anforderung eingebaut haben. Da es sich bei der Kata um eine Art Templatesystem handelt liegt es nahe auch in den Values des Wörterbuchs neue Keys zu erlauben und somit eine beliebige Ersetzungstiefe zu erreichen. Diese Anforderung ist ein wunderbares Beispiel dafür wie sehr man mit Aufwandsabschätzungen daneben liegen kann. 😉
Die rekursive Ersetzung wurde noch sehr schnell gelöst, aber richtig schwer haben wir uns dann mit der Erkennung von zyklischen Ersetzungen und der daraus folgenden Endlosschleife getan. Nach und nach wurden immer kompliziertere Lösungsmöglichkeiten genannt, die aber in der gegebenen Zeit nicht fehlerfrei umgesetzt werden konnten. Als Folge haben wir immer noch einen Test “rot”. Wer Lust hat kann sich also die Quellen vom github Repository ziehen und als Hausaufgabe den verbleibenden Test “grün” machen.
In der Nachbetrachtung haben wir noch einige Sachen festgestellt:
Was lief gut?
Die Rotation der Teilnehmer klappte problemlos
Lösungsideen sprudelten förmlich aus dem Publikum
Interessante Edge-Cases wurden gefunden
Viele kleine Tipps (z.B. Resharper Shortcuts) wurden ausgetauscht
TDD wurde als erfolgreich für die Kata angesehen
Die Randori-Form sorgt für Aktivität
Ganz wichtig: Es hat Spaß gemacht!
Was wollen wir besser machen?
Schneller den ersten Test schreiben
Intensivere Diskussion des Interfaces
Noch mehr Wert auf das Naming legen
Versuchen die einfachste Lösung zu wählen
Mehr Wert auf Refactoring legen
wurde etwas vernachlässigt, da wir viel Zeit an der Endlosschleife verbraucht haben
Die Rollen Driver, Co-Pilot und Publikum klarer trennen
Nach jedem implementierten Testcase bzw. jeder Rotation der Teilnehmer in das git Repository einchecken
Von Anfang an externe Tastatur und Maus für den Laptop bereit stellen
Internetverbindung um Syntaxfrage schneller klären zu können
Als möglichen Termin für das Dojo haben wir jetzt grob jeweils den 3. Mittwoch im Monat vorgeschlagen. Über die Xing-Gruppe der .NET User Group Hamburg werden wir natürlich auch wieder entsprechende Einladungen verschicken.
Bei einem Coding Dojo treffen sich Software-Entwickler um ihre Fähigkeiten beim gemeinsamen Lösen einer Programmieraufgabe (der sogenannten Code-Kata) zu verbessern. Dabei soll vor allem der Spaß im Vordergrund stehen. Folgende Grundsätze gelten:
Das Dojo ist nicht konkurrenzbetont sondern gemeinschafts- und spaßorientiert.
Vom Einsteiger bis zum erfahrenen Softwareentwickler ist jeder willkommen.
Lösungen werden im Team erarbeitet, gemeinsam umgesetzt und gemeinsam präsentiert.
Zur Lösung müssen Tests geschrieben werden.
Es gibt keine Musterlösung! Die Lösungsmöglichkeiten sind bewusst offen und geben Raum für unterschiedlichste Entscheidungen. Interessant ist insbesondere das gegenseitige Anleiten und Lehren.
Es gibt verschiedene Möglichkeiten ein Coding Dojo abzuhalten. Für unser erstes Treffen wollen wir die sogenannte RandoriKata-Version probieren. Dabei wird die Problemstellung wird von einem Entwickler-Duo gelöst (Driver und Copilot). Alle anderen Personen sind jedoch eingeladen sich aktiv an der Lösung zu beteiligen und dem Entwickler-Duo Hilfestellungen und Hinweise zu geben. Nach einer gewissen Zeit (ca. 7 Minuten) wird das Duo ausgetauscht und die nächsten Entwickler haben die Chance die Lösung voranzutreiben.
Am Mittwoch, den 17.03.2010 werde ich in Hamburg-Altona einen Vortrag zu “Funktionaler Programmierung mit F#” halten.
“Funktionale Programmiersprachen nehmen seit geraumer Zeit einen hohen Stellenwert in der Wissenschaft ein. Demnächst könnte es eine dieser Sprachen sogar aus dem Forschungsbereich direkt in den Mainstream schaffen. Visual Studio 2010 wird neben C# und VB.NET die funktionale Programmiersprache F# als dritte Hauptsprache anbieten. Der Vortrag soll einen Einblick in funktionale Konzepte und deren Umsetzung in F# geben. Insbesondere soll auf “Funktionen höherer Ordnung”, Typinferenz, Currying, Pattern Matching, “Unveränderlichkeit” und parallele Programmierung eingegangen werden.”
“In object-oriented programming, the open/closed principle states "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification"; that is, such an entity can allow its behaviour to be modified without altering its source code.”
If we follow this principle we get lot’s of small and testable classes. I want to demonstrate this with a simple spam checker for mails.
Let’s say our mail class has only a sender, a recipient, a subject and the mail body:
publicclassEMail
{
publicstring Sender { get; set; }
publicstring Recipient { get; set; }
publicstring Subject { get; set; }
publicstring Body { get; set; }
public EMail(string sender, string recipient,
string subject, string body)
{
Sender = sender;
Recipient = recipient;
Subject = subject;
Body = body;
}
}
publicenumSpamResult
{
Spam,
Ok,
Unknown
}
Now we want to know if a mail is spam or not. Of course we need some rules and some kind of “rule checker” to decide this. Here is a very naïve implementation for this:
publicclassRuleChecker
{
publicSpamResult CheckMail(EMail mail)
{
var result = TestRule1(mail);
if(result != SpamResult.Unknown)
return result;
result = TestRule2(mail);
if (result != SpamResult.Unknown)
return result;
// …
returnSpamResult.Unknown;
}
privateSpamResult TestRule1(EMail mail)
{
// I don’t care about the concrete rules
}
privateSpamResult TestRule2(EMail mail)
{
// I don’t care about the concrete rules
}
}
It is obvious that this implementation breaks the Open/Closed Principle. Every time someone comes up with a new anti-spam rule or the rule priorities change I have to modify the code in CheckMail(). Another problem here is that I can’t test CheckMail() isolated from the concrete rules.
With the help of the Open/Closed Principle our implementation could look like this:
publicinterfaceISpamRule
{
SpamResult CheckMail(EMail mail);
}
publicclassRuleChecker
{
privatereadonlyIEnumerable<ISpamRule> _rules;
public RuleChecker(IEnumerable<ISpamRule> rules)
{
_rules = rules;
}
publicSpamResult CheckMail(EMail mail)
{
foreach (var rule in _rules)
{
var result = rule.CheckMail(mail);
if (result != SpamResult.Unknown)
return result;
}
returnSpamResult.Unknown;
}
}
Now you could easily write isolated UnitTests for RuleChecker.CheckMail() and for every new rule.
You get the your concrete RuleChecker by calling the constructor with a list of rules:
classMyFirstRule : ISpamRule
{
publicSpamResult CheckMail(EMail mail)
{
// I don’t care about this
}
}
classMySecondRule : ISpamRule
{
publicSpamResult CheckMail(EMail mail)
{
// I don’t care about this
}
}
// …
var ruleChecker =
newRuleChecker(
newList<ISpamRule>
{
newMyFirstRule(),
newMySecondRule(),
// …
});
Alex please correct me if I’m wrong, but I think this is what you had in mind Friday.
As stated before, we end up writing lot’s of very small classes – mostly with only one (public) method. I think this is some kind of functional approach, the only question is how we glue our code entities together. Let’s look at the corresponding F# implementation:
type EMail =
{ Sender: string;
Recipient: string;
Subject: string;
Body: string}
type SpamResult =
| Spam
| OK
| Unknown
let checkMail rules (mail:EMail) =
letrec checkRule rules =
match rules with
| rule::rest ->
match rule mail with
| Unknown -> checkRule rest
| _ as other -> other
| [] –> Unknown
checkRule rules
The signature of checkMail is (EMail -> SpamResult) list -> EMail –> SpamResult, which means it takes a list of rules (as above the order is important) and a EMail and returns the SpamResult. In addition I exchanged the explicit foreach loop with a tail recursion to make it look more functional.
As you can see the F# implementation is nearly the same as the C# implementation, just without explicitly wrapping our public method in classes. If we would use Reflector we would see that the F# compiler is building the classes around our functions. One could say if we follow the Open/Closed Principle we come to functional code or the other way around if we write functional code we automatically apply the Open/Closed Principle. I think that’s why I really didn’t care about this before.
Appendix
After thinking about this implementation and the extra type hint (see mail:EMail) I came up with a slightly more generic implementation:
type SpamResult =
| Spam
| OK
let checkRules rules element =
letrec checkRule rules =
match rules with
| rule::rest ->
match rule element with
| None -> checkRule rest
| _ as other -> other
| [] –> None
checkRule rules
Here I deleted the enum value for SpamResult.Unknown and used the standard None option. As a consequence the signature changed to: val checkRules : (‘a -> ‘b option) list -> ‘a -> ‘b option. The function still takes a list of rules and a element and returns a option value. Now the checkRules function works with every kind of rule result and takes arbitrary elements.
Yesterday I was talking about F# at the .NET Developer Group Braunschweig. It was my first talk completely without PowerPoint (just Live-Coding and FlipChart) and I have to admit this is not that easy. But the event was really a big fun and we covered a lot of topics like FP fundamentals, concurrency and domain specific languages (of course I showed “FAKE – F# Make”).
Now I have a bit time before I go to the next BootCamp in Leipzig. Today Christian Weyer will show us exciting new stuff about WCF and Azure.
Question 4 – Try to explain “Currying” and “Partial Application”. Hint: Please show a sample and use the pipe operator |>.
Obviously this was a tricky question for FP beginners. There are a lot of websites, which give a formal mathematical definition but don’t show the practical application.
“Currying … is the technique of transforming a function that takes multiple arguments (or more accurately an n-tuple as argument) in such a way that it can be called as a chain of functions each with a single argument”
I want to show how my pragmatic view of the terms here, so let’s consider this small C# function:
public int Add(int x, int y)
{
return x + y;
}
Of course the corresponding F# version looks nearly the same:
let add(x,y) = x + y
But let’s look at the signature: val add : int * int –> int. The F# compiler is telling us add wants a tuple of ints and returns an int. We could rewrite the function with one blank to understand this better:
let add (x,y) = x + y
As you can see the add function actually needs only one argument – a tuple:
let t = (3,4) // val t : int * int
printfn "%d" (add t) // prints 7 – like add(3,4)
Now we want to curry this function. If you’d ask a mathematician this a complex operation, but from a pragmatic view it couldn’t be easier. Just remove the brackets and the comma – that’s all:
let add x y = x + y
Now the signature looks different: val add : int -> int –> int
But what’s the meaning of this new arrow? Basically we can say if we give one int parameter to our add function we will get a function back that will take only one int parameter and returns an int.
let increment = add 1 // val increment : (int -> int)
printfn "%d" (increment 2) // prints 3
Here “increment” is a new function that uses partial application of the curryied add function. This means we are fixing one of the parameters of add to get a new function with one parameter less.
But why are doing something like this? Wouldn’t it be enough to use the following increment function?
let add(x,y) = x + y // val add : int * int -> int
let increment x = add(x,1) // val increment : int -> int
printfn "%d" (increment 2) // prints 3
Of course we are getting (nearly) the same signature for increment. But the difference is that we can not use the forward pipe operator |> here. The pipe operator will help us to express things in the way we are thinking about it.
Let’s say we want to filter all even elements in a list, then calculate the sum and finally square this sum and print it to the console. The C# code would look like this:
var list = new List<int> {4,2,6,5,9,3,8,1,3,0};
Console.WriteLine(Square(CalculateSum(FilterEven(list))));
If we don’t want to store intermediate results we have to write our algorithm in reverse order and with heavily use of brackets. The function we want to apply last has to be written first. This is not the way we think about it.
With the help of curried functions, partial application and the pipe operator we can write the same thing in F#:
let list = [4; 2; 6; 5; 9; 3; 8; 1; 3; 0]
let square x = x * x
list
|> List.filter (fun x -> x % 2 = 0) // partial application
|> List.sum
|> square
|> printfn "%A" // partial application
We describe the data flow in exactly the same order we talked about it. Basically the pipe operator take the result of a function and puts it as the last parameter into the next function.
What should we learn from this sample?
Currying has nothing to do with spicy chicken.
The |> operator makes life easier and code better to understand.
If we want to use |> we need curryied functions.
Defining curryied functions is easy – just remove brackets and comma.
We don’t need the complete mathematical theory to use currying.
Be careful with the order of the parameter in a curryied function. Don’t forget the pipe operator puts the parameter from the right hand side into your function – all other parameters have to be fixed with partial application.
Last Friday we had a fantastic LearningByTeaching F# BootCamp in Leipzig. Each attendee got homework and had to solve one theoretical question and one programming task. For this two questions they had to present their results to the rest of us and after this I gave my solution in addition.
It was very interesting to see the different strategies and solutions. In this post series I will discuss the questions and some of the possible solutions.
Question 1 – What is “Functional Programming” in contrast to “Imperative Programming”?
This seems to be an easy question but in fact, the attendees had some problems to give a short definition of both functional and imperative Programming.
I didn’t find a formal definition of the terms so my intention was to clarify things with an informal description like the one from Wikipedia:
“In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state. Functional programming has its roots in the lambda calculus, a formal system developed in the 1930s to investigate function definition, function application, and recursion.”
I think the main aspect here is: avoiding state and mutable data. Maybe the words “side-effect”, recursion and “higher-order functions” could also be used, but they will be discussed in later questions.
On my slides I covered the following aspects:
Functional programming is a paradigm
FP tries to avoid shared state
Functions are first class citizens, enabling higher-order functions
Pure functions
no side-effects
Results calculated only on the basis of input values
Question 2 – Explain the keyword “let”. In F# we are talking about “let-bindings” and not “variables”. Why?
Basically you use the let keyword to bind a name to a value or function. It won’t change any more, so a binding is immutable at default and not “variable”.
I was glad to see the presenter showing the problem with an imperative assignment like x = x + 1, which from a mathematical view is paradoxical. There is no x which equals x plus one. I think choice of the F# assignment operator is better than equality sign. The statement x <- x + 1 shows the real intention. I want to put the old value of x plus one into the memory cell where x was before. So we discussed some basic terms like scope and mutability here and I showed how we can explicitly tell the compiler to use mutable data using reference cells or mutable variables.
Maybe it wasn’t that good idea to discuss “Imperative F#” at such an early point (without knowing any functional concepts), but it showed the contrast to immutable let-Bindings.
Question 3 – What is a recursion? Try to explain why we often want recursions to be tail-recursive. Hint: Look at the following C# program. What is the problem and how could you solve it?
public static Int64 Factorial(Int64 x)
{
if (x == 0) return 1;
return x*Factorial(x - 1);
}
…
Factorial(10000);
It was interesting to see that nearly nobody expected a real problem in such a short code snippet. Some attendees thought this program might have an integer overflow – but only the presenters (they tested the program) gave the right answer (stack overflow). In fact they gave a very good and deep explanation about recursion and the problem on the stack.
As the question hinted, a possible solution was adding a accumulator variable and using tail-recursion:
public static BigInt FactorialTailRecursive(BigInt x, BigInt acc)
{
if (x == BigInt.Zero) return acc;
return FactorialTailRecursive(x - BigInt.One, x*acc);
}
Unfortunately this "trick" doesn’t work in C# (the compiler doesn’t use tail calls), but it leads to the correct idea – converting it to a while-loop. Of course I would prefer the tail-recursive F# solution:
/// Tail recursive version
let factorial x =
let rec tailRecursiveFactorial x acc =
match x with
| y when y = 0I -> acc
| _ -> tailRecursiveFactorial (x-1I) (acc*x)
tailRecursiveFactorial x 1I
We didn’t cover continuation passing here. I think this could be something for an advanced session.
Next time I will discuss the rest of the introduction and show some of the first programming tasks.
Eben bin ich beim Lernen für die Datenbankenprüfung auf einen Wettbewerb mit dem merkwürdigen Namen “wettbehalle” gestoßen. Dabei soll für einen Vortrag meines Professors bei der Langen Nacht der Wissenschaften 2009 in Halle eine Seite möglichst gut für diesen Begriff bei Google gelistet sein.
Ich habe auch schon interessante / riskante Versuche im Netz dazu gesehen, allerdings glaube ich, dass diese konsequent abgestraft werden dürften.
Bei besonders umkämpften Suchbegriffen (die ich hier aus gutem Grund nicht aufzähle), wird jede Form der Manipulation erfahrungsgemäß von den Suchmaschinen-Betreibern schnell entdeckt. Bei einem so seltenen Wort wie wettbehalle, nach dem vermutlich nur zur Langen Nacht der Wissenschaften gesucht wird, bin ich mir jedoch nicht so sicher.
Möglicherweise (bzw. sehr wahrscheinlich) wird da auch etwas automatisiert unternommen. Fakt ist aber, dass der Wettbewerb nicht unter echten Marktbedingungen ausgetragen wird.
Obwohl es um Optimierung geht, werde ich für den Wettbewerb nur diesen einen Artikel hier und einen Tweet “einreichen”. Es wird zwar schwierig damit gegen eine Parteienseite und die Uni Halle zu bestehen, aber vielleicht wird ja zu starke Optimierung auch auf diesem Level schon abgestraft.
PS: Ok, das ging erstaunlich schnell – schon 9 Minuten nach dem Posten des Artikels hat Google ihn ganz oben gelistest. Wer will kann den Artikel aber trotzdem gerne verlinken.
PS 2: Vielleicht sollte ich noch etwas flamen – das hilft in der Regel immer um Links zu bekommen. Also bald findet ja das BootCamp zu “Funktionaler Programmierung mit F#” in Leipzig statt – in diesem Sinne: “Objektorientierte Programmierung wird völlig überschätzt.” 😉
Filed under: TechTalk — Steffen Forkmann at 11:08 Uhr
Seit Herbst 2008 bietet Microsoft TechNet eine neue Veranstaltungsreihe an: den sogenannten Microsoft TechDay. Im Mai wird sich diese Reihe um das Thema „Administrieren mit PowerShell“ drehen.
“Die Windows PowerShell, zeitweise auch bekannt unter den CodenamenMonad und Microsoft Command Shell (MSH), ist eine von Microsoft entwickelte Alternative zum Windows-Kommandozeilenprogramm cmd.exe und zum Windows Script Host.
Die auf dem .NET-Framework in der Version 2.0 basierende Windows PowerShell verbindet die aus Unix-Shells bekannte Philosophie von Pipes und Filtern mit dem Paradigma der objektorientierten Programmierung. Der Benutzer kann wie bisher einfache Befehle an einer Kommandozeile ausführen und miteinander verknüpfen oder aber auch komplexe Skript-Programme mit der eigens dafür entwickelten PowerShell Scripting Language schreiben.”
“Funktionale Programmiersprachen nehmen seit geraumer Zeit einen hohen Stellenwert in der Wissenschaft ein. Demnächst könnte es eine dieser Sprachen sogar aus dem Forschungsbereich direkt in den Mainstream schaffen. Visual Studio 2010 wird neben C# und VB.NET die funktionale Programmiersprache F# als dritte Hauptsprache anbieten. Der Vortrag soll einen Einblick in funktionale Konzepte und deren Umsetzung in F# geben. Insbesondere soll auf “Funktionen höherer Ordnung”, Typinferenz, Currying, Pattern Matching, “Unveränderlichkeit” und parallele Programmierung eingegangen werden.”
[Abstract]
Warning: Creating default object from empty value in /www/htdocs/w007928a/blog/wp-content/plugins/wp-referencesmap/GoogleMapsWrapper.php on line 55