Thursday, December 20, 2012

Fizz Buzz in APL

I came across the Fizz Fuzz programmers test and just couldn't help myself programming it in APL:

p←0=3 5∘.|l←i←⍳100
l[(,∧⌿p)/i]←⊂'Fizz Buzz'

And that is the way it is done (the code is self explanatory :))

Wednesday, December 19, 2012

Software inovation by law

At one point in time, some people figured out that the world was full of selfish bastards that would leech off each other and therefore smart people would not innovate because all their hard work would be stolen. The patent was invented and this allowed inventors to work on difficult problems and if succeeding  be rewarded in the end. The leechers however have discovered that they can use the patent system for their own benefit. Instead of patenting stuff that represent a great effort they patent simple every day things like rectangles, colors or human gestures.

So now the patents are no longer used to defend the innovative from the bullies. Instead the bullies uses them to keep the innovative from being innovative. By having a vast amount of patents on everyday things and by keeping them to you self until someone has violated them, you effectively keep anyone from creating anything new unless they can afford a patent war against you.

In other words, it no longer depends how good your ideas are but how much money you have. I hope someone with the power to be heard one day figures this out and requests the system to be changed. Patents should only cover things obtained through some kind of effort, and patent owners should be forced to license the use of their patents to others. Color combinations or shapes are not to be claimed by anyone as their property! That's just my opinion...

Tuesday, December 18, 2012

Happy Happy Joy Joy.. Learning a new programming language

A year ago I started a new job. The company that is now my employer has a lot of code written in an old and obscure language called APL. So I have had to sit down and learn APL.

APL is short for "A Programming Language" and being invented in 1953 it is a very old language. For me its a fresh new approach to programming. Instead of spawning from electronic engineers, APL comes from the twisted mind of a mathematician. That means that the language does not origin from abstracting processor instructions, but from what would be useful for doing math. This makes it an extremely high level language that is very powerful once you wrap you head around it. APL sees the world as vectors and matrixes (single dimensionned arrays and multi dimensioned arrays for the rest of us). Once you have your world defined in arrays, you will be amazed by the expressiveness that APL provides.

I recently listened to hanselminutes where they talked about F#. One of the key points with F# was how little code you had to write to accomplish anything.  The example given was Conway's game of life. Ruby could do it in 140 characters. F# weighed in with an impressive 127 characters. Compared to APL these languages are however very verbose. APL does the same thing in only 38 characters. To be fair, this problem is right down APL's alley as 'twodimensional array' is a native type of APL.

To begin with APL is completely unreadable. First of all, the character set used is not present in you favourite font. Secondly there is no operator prescedence in APL, Expressions are evaluated from right to left.

  • 3 + 4 = 7
    returns 3 (4 is not equal to 7 and returns 0, 3 is added)
  • 4 * 0 + 4
    returns 16 
  • etc.
Example code from wikipedia:

This code finds all the primenumbers up to R.Remember to read this from the right. ⍳R creates a vector  containing the numbers from 1 to R. 1↓ drops the first element of that vector. The new vector is assigned to R. The / in this context means a filter, it will filter the vector on the right by the binary vector(elements are boolean). 
R∘.×R produces a matrix(double sided array) containing the product of all combinations of numbers found in R. R∊ produces a binary vector of all elements in R that are also on the right. The binary vector is inverted by ~ and the filter is applied. Voila, a vector of prime numbers.

All in all it's great to learn a new language that is so different. This probably will never be language of choice but it has given me a different perspective on the other languages I use.

Thursday, August 09, 2012

Unit tests are not all black and white

And they are not all red or green either. From a management perspective it might make sense to divide unit tests into the ones that pass, and mark everything else as an error. After all, this is what is confirmed to work and what is not.

From a development's perspective this approach makes less sense. The main goal is still to get all unit tests in the green zone. It's just that some of the test that do not pass are not errors that need immediate attention. Some of the error may already be planned to be fixed in the future, configuration problems or dependencies on resources that are not available at the moment of the test run.

Take for example a test that uses a database (i known that technical it is not a unit test). You want to test that some updates are done correctly. If for some reason the database is down and you can't get an open connection to the database, would you fail the test? My suggestion is that you don't. The test is not about getting a connection to the database but about doing the update.

They way I like to use unit tests is to utilize the ignore or inconclusive state of tests. If it is some configuration,  some 3. party component missing on the test machine or some error that is scheduled in the future I like to take them out of the errors in need of immediate attention.

I have seen panicking because hundreds of tests fail just because the password of the database user had changed. This should maybe fail in a single test that verifies that the database is accessible, but not the whole test suite.

It's a good idea to prioritize your tasks, and by using levels of severity in your unit tests you can optimize your bug fixing efforts a bit and focus on the errors that are real.

Tuesday, August 07, 2012

Recursive lambdas

More and more programming languages supports a functional approach to programming. the functional approach gives a more compact syntax that for some people will be easier to read because everything can be kept together.

In C#, lambda expressions take us closer towards functional programming. An important concept of functional programming is recursitivity which in many cases can replace loops.

I pulled up my old base conversion algoritm and gave it a try. Basically it takes an integer and returns a string respresented in a base of your choice.

Integers to Text

The variable chars contains the characters used in the output. For a conversion to base 16 (hex) the first 16 are used etc..
C# doesn't let you reference something that is defined in the same line, so the signature of the lambda is defined in the previous line. The actual conversion is all written in one line of code and I'll let you decipher it yourselfes. Because of the recursion, no loop is required. It will basically calls itself for every character to be output. As C# doesn't support tail recursion (this is not completely true, but I won't count on it anyway), recursive code in C# has a limit to how many times a method can call itself.

I also did one that goes the other way.

Text to Integer
What i have now is two methods so that I can convert from any base (limited to the length of the charset used) to any other base. this is how i convert a hex number into base 3.


Thursday, July 26, 2012

Inline, nested if statements

The ?: operator was something I had to get used to when I first saw it. I allows you to define a conditional if statement on a single line with a build in assignment. This compacts a lot of code and once you get used to it it's quite readable.

var <result> = <if-condition> ? <true value> : <false value>;

This can, among other things, be used to translate values. In the following s will contain the text "Small" if i is less than 3, otherwise "Not Small"

int? i = 4;
string s = i<3 ? "Small" : "Not small";

Whatever is behind the colon, you can replace with a new inline if statement. Now its an if/else if/else statement on a single line.

string s = i<3 ? "Small" : i==3 ? "Three" : i>3 ? "Large" : "Not a Number";

Which gives the same result as.

string s;
   s = "Small";
}else if(i==3){
   s = "Three";
}else if(i>3){
   s = "Large";
   s = "Not a Number";

This is even better when used in lambda expressions as a "standard" lambda expression only allows one statement. 

   GetInts().Select(i=>i<3?"Small":i==3?"Three":i>3?"Large":"Not a Number")
            .Aggregate((x, y) => x + "\n" + y)

Wednesday, January 25, 2012

Era of the XAML user interface

I hear the term XAML user interfaces mentioned way too often these days.

XAML has in fact nothing to do with userinterfaces. XAML is just a language for instantiating an object structure. I have previously written about how I have used it as a configuration language for my applications, a sort of light weight dependency injection framework. To show that WPF and Silverligth are not the only UI frameworks that can be used with XAML I have used XAML to create a small Windows Forms form.

The root node of my XAML file will be Form. By providing "clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms" as the default namespace Visual Studio and .net will recognize the elements and validate them to match a structure that is allowed beneath a form. If you need to use other .net namespaces, you just add a prefixed xml namespace for each of those .net namespaces.

Visual Studio will pr default open a WPF/Silverlight visual presentation along with the text editor when opening the XAML file. As we are not using WPF or silverlight the visual presentation will not show anything usefull. The XAML can be distributed as a file besides you application, embedded as XAML or embedded as BAML (XAML compiled to a binary format). The BAML approach is probably the most sensible solution for a real life application.

To create an instance of the form just give the XAML stream to a XamlReader and cast the result to a Form object. Now the form can be displayed by calling Show, like you would on any other windows form.

When the form object has been created, i use two lines of code to hookup some eventhandlers before showing the form. The find method on the form is an extension method for Form that flattens that flattens the structure of the form so that LINQ can be used on it. The generic type is a filter that only returns the controls of that type and the lambda is a further filter. The find method has been implemented in the plain framework, so you can go there to se the implementation.
The Do method is just like the ForEach method on List, this however work for any type of IEnumerable<T>.

The first of the two lines finds all buttons whose name start with "Command" and hook them up to an event handler. The second line hooks an event handler to the TextChanged event of all controls whose name start with Value. In this way it is easy to use a naming convention to hook the UI up to business logic. Dependind on your architecture, you might hook it up to fire commands or whatever.

You might implement some layout manager the same way, or you might inherit panel or something other control and create a layout manager that way. By implementing you own controls you can also put metadata on the controls in your UI.

So, XAML has the potential of being used with other UI frameworkds than WPF and Silverlight.

Thursday, January 19, 2012

Suitable Business model?

I have created a prototype for an application.
  • I know there is a market for what the application does as there are existing products that have same target audience.
  • Existing products are VERY pricy.
  • The product is simpler and easier to maintain than existing products in the market.
I just have one problem. How should I put this to market?

A way could be to make it open source. This has worked for me with plain. Plain was however a theoretical experiment, a playground for thougths on how simple and easy application architecture could be made. There was never a plan for a final release because the process was more important. The no limits and no constraints meant that we could implement a search filter framework that resembled Linq a bit before we ever heard of Linq. A validation framework much like the one now found in nHibernate and ASP.Net Mvc 3 etc.. But plain intentionaly lacked one thing that I would like my new project to have. Exposure and usage.
  • Open source the product and commercialize tools and support.
  • Open sourcing everything.
  • Make everything closed source.
  • Some others I haven't thought of.

This is a more finite problem and I want to work towards a releasable codebase. Will a enterprise product ever be popular if it is cheap?
Will it be possible to have a differentiated licensing model for hobbyists and enterprises. Will this model result in a greater usage? Is it at all possible to have the kind of openness and transparency I'm looking for if the project is not open source?

Wednesday, January 18, 2012

Declarative structure initialization

I'm on the lookout for a Dependency Injection framework for .net that supports a small, compact and declarative syntax. I want it to be so easy that non programmers can figure out what is going on.

My first thoughts were on XAML as it is simple and declarative. The reason for not choosing this anyway is that it doesn't support generics in a nice way. By not in a nice way I mean very verbose and strange. On top of that XAML is not implemented on mono.

Springframework and Castle Winsor is also too verbose for my likings. Although they are very good, they still require me to define my object at one place and reference they together in a structure somewhere else. Thsi is not a bad thing, I would just, also, like the possibility to create the objects in the structure inline where they are needed.

Another solution could be to consume code and execute it. This ofcorse is also way off compared to what I want to accomplish.

Any Ideas on what path to follow?

Wednesday, January 04, 2012

Wishlist: Derived generic parameters

In .Net generics gives a nice way to make type agnostic code that are not limited to a specific type.

The following two types are taken from the plain framework.

interface IBusinessEntity<T>{
    T Id {get;set;}

interface IDao<T,TT> where T : IBusinessEntity<TT>{
    T Get(TT);
    TT Save(T);

As shown you can use gemeric types as generic parameters for other types. In the IDao interface, I have specified that T must be a IBusinessEntity interface with the TT type as a generic parameter.
In my example I will create a Article class that implements the IBusinessEntity interface and a generic Dao implementation

class Article : IBusinessEntity<int>{
    //some code

class Dao<T,TT> : IDao<T,TT>{
    //some code

Now I want to get a dao for the class you just created. As Article has int as a generic parameter, the Dao objects has to defined with the article type as well as int to be able to compile.

var dao = new Dao<Article,int>();

Once you apply "Article", the only valid type as TT is "int". If you apply anything else, the compiler will let you know that "Article" is not valid. The reason for this is that in the definition of IDao, T has a requirement for T, not TT.
It has been bugging me that the compiler complains about the type of T and not the type of TT. T is the important generic parameter, and TT could just be derived from that.

In future releases of .net I would like to be able to write the following.
interface IDao<T<TT>> where T : IBusinessEntity<TT>{
    T Get(TT);
    TT Save(T);

This way I could specify TT as part of the signature, but as TT is derived from what type T is, I would only have to specify T when using it.
When creating the dao I could then write.

var dao = new Dao<Article>();

This is a small improvement, but it would remove some strange dependency error when using multiple generic parameters.