Search And Destroy

Look out honey, ’cause I’m using technology!

Archive for August, 2011

On Having Fun

Posted by kilfour on August 27, 2011

As mentioned (often) before, a while ago I took a break from professional programming.
During which I started honing my functional programming skills.
I reckon’ I was, and still am, quite proficient in OCaml.

After that I got really interested in Haskell, so I experimented.
But the unforgiving nature of the type system was really hard to deal with and I had a lot of trouble implementing anything usefull.
I managed to pull some things off, but really didn’t get why.

Recently I have picked it up again, and it’s all starting to make sense.

Still having trouble making stuff compile and getting things to work.
The fact that I’m using a different setup/IDE/OS than before, probably isn’t helping.
But I’m really, _really_ having fun with this.

Currently looking into Happstack/HStringTemplate/et-all in order to deliver a simple web app, and I was quite proud of myself that I got a ‘hello world’ working with minimal code, and that I actually understood all of what is going on ;-) .

Another thing that I’m currently investigating is Parsec, Haskell’s built in parser.
Delivering the power of regular expressions _without_ sacrificing readability.
It is not that much more verbose than that horrendous regex stuff, but I can actually program it without having to resort to some kind of tool that translates it for me.

Here’s a small (unrelated to all of the above) thing I cooked up :

module FileCompare (
    fileDiff
) where


import System.IO (readFile)

failure :: Int -> Int -> String
failure lineIndex colIndex  =
    "Files differ at line : " ++ (show lineIndex) ++ ", column : " ++ (show colIndex) ++ ".";

compareLine :: Int -> Int -> String -> String -> String
compareLine lineIndex colIndex [] [] = 				    ""
compareLine lineIndex colIndex (x:xs) [] = 			    failure lineIndex colIndex
compareLine lineIndex colIndex [] (y:ys) = 			    failure lineIndex colIndex
compareLine lineIndex colIndex (x:xs) (y:ys) | x /= y = failure lineIndex colIndex
compareLine lineIndex colIndex (x:xs) (y:ys) | x == y =	compareLine lineIndex (colIndex + 1)  xs ys

compareLines :: Int -> [String] -> [String] -> String
compareLines lineIndex (x:xs) (y:ys) = 	(compareLine lineIndex 0 x y) ++ (compareLines (lineIndex +1) xs ys)
compareLines lineIndex [] (y:ys) = 	"File two contains more lines then file one."
compareLines lineIndex (x:xs) [] = 	"File one contains more lines then file two."
compareLines lineIndex [] [] = 		"Files are identical."

diff :: String -> String -> String
diff a b = compareLines 0 (lines a) (lines b)

fileDiff :: FilePath -> FilePath -> IO String
fileDiff f1 f2 = do
  fileOne <- readFile f1
  fileTwo <- readFile f2
  return $ diff fileOne fileTwo

Performance equals a C++ version and it can easily handle huge files.

Tell me what you think.

For the imperative minded : start reading at the bottom and then move up ;-) .

Posted in Haskell, Rants | Leave a Comment »

One of Those Nights

Posted by kilfour on August 24, 2011

QuickGenerate suits my needs for the moment.

QuickDotNetCheck still isn’t working the way I want to, but I’m going to let it rest for a little while.
I’ll probably iron out a couple of bugs I have recently introduced, so that I can start using it full-time at work.
But after that I’m going to let the idea ripe in my head a little.

So what to do for fun at home.

And then there’s Haskell…

Particulary interested in getting some web-related stuff working.

Posted in Haskell, Rants | Leave a Comment »

On Scientific Arrogance

Posted by kilfour on August 23, 2011

It is not a new thing.

There’s a reason I prefer Alan Kaye’s publications over Edgar Dijkstra’s, f.i.

I think it has to do with pragmatism versus arrogance.

When I was in my teens I read about relativity theory.
For fun.
And because I wanted to be the smartest kid on the block.
In those days, it wasn’t exactly common knowledge, and I did have a lot of fun hassling my science teachers with questions they couldn’t answer.

Recently, I’ve noticed, relativity is far more widely understood, and most people coming out of university have a much better grasp of it than I do.

After reading all that, I took some things as axioms :
– nothing travels faster than the speed of light.
– there is no such thing as action at a distance.
– nothing, not even light, can escape a black hole’s gravitational field.
– the conservation laws (notably the second law of thermodynamics, and conservation of baryon number)
– etc…

Most of these things have been proven wrong by observation in recent years.

So theories were adapted, or thrown out completely, as they should be.
Although the latter option does happen less and less.

The one thing that annoys me up to a point of boiling anger, is that some ‘scientists’ seem reluctant to accept an alternative view and even ridicule it, until a ‘peer’ higher up on the pecking order tells them that’s it’s actually a viable idea.

Just visit some of the physics forums for some ‘discussions’ that make some of the net storms in the software blogosphere seem like a friendly exchange of ideas.

The holographic universe theory (and even more so the holographic mind theory) was regarded as fringe theory for a while until some respected scientists got behind it.

Just to make things clear, I have serious apprehensions to above mentioned hypothesis’s (see my previous post), but I would never have to arrogance to debunk it, because I realize I’m not qualified to do so.

Yet, people who have studied longer than I have and should understand the math, seem to have no problem in doing so (debunking it I mean) on just first glance.
And they often employ the same unscientific methods that they accuse the other party of using.

Being just an interested laymen, I’m looking for an objective, scientific approach to the theories/models I’m interested in, and this is really hard to find.

Engelbarts dream seems further off than ever.

And here’s one thing that _really_ ticks me off.

The Crackpot Index, by John C Baez.

The next phrase should be read whilst imagining mr brando in ‘Apocalypse Now’.

‘The Arrogance, The Arrogance, …’.

Posted in Rants | 1 Comment »

My Favourite Scientific Principle : Occam’s Razor

Posted by kilfour on August 23, 2011

One should not increase, beyond what is necessary, the number of entities required to explain anything.

So please, science dudes, get a grip.

Posted in My Favourite, Rants | Leave a Comment »

Test That Mapping, … Once and For All

Posted by kilfour on August 10, 2011

I’m sure you’re all aware of how mapping business entities to DTO’s is quite a menial task and that there are several strategies to deal with that.

I employ more than one of those strategies.

But one that I use quite a bit, mainly because of speed of development, is the nhibernate/automapper combo.

Once the handler, repositories, queryobjects et all (or whatever infrastructure you use to get the data to your view) is in place, all one needs to do is, add a rightly named property to the dto and magically it gets populated with the desired value.

You don’t even have to adapt any test thanks to the AssertConfigurationIsValid method of AutoMapper.

However, ever since I first started using this way of working, two things about it all have been bothering me :
1. The need for a ‘Registry’ type class (or a static method, or whatever), where one registers all the mappings.
F.i. :

public static class Boot
{
	public static void Strap()
	{
		CreateMap<GetBetalingsAanvraagByIdentificatieResponse.BetalingsAanvraagDto, BetalingsaanvraagErelonenViewModel>()
			.ForMember(dest => dest.TotaalBedrag, options => options.Ignore());
		CreateMap<GetBetalingsAanvraagByIdentificatieResponse.BetalingsAanvraagLijnDto, BetalingsaanvraagLijnViewModel>()
			.ForMember(dest => dest.Totaal, options => options.Ignore());
		CreateMap<GetBetalingsAanvraagByIdentificatieResponse.StavingsDocumentDto, BetalingsaanvraagDocumentViewModel>();

		CreateMap<GetBetalingsAanvraagByIdentificatieResponse.BetalingsAanvraagDto, BetalingsaanvraagGrondenViewModel>()
			.ForMember(dest => dest.TotaalBedrag, options => options.Ignore());
		CreateMap<GetBetalingsAanvraagByIdentificatieResponse.BetalingsAanvraagLijnDto, BetalingsaanvraagLijnViewModel>()
			.ForMember(dest => dest.Totaal, options => options.Ignore());
		CreateMap<GetBetalingsAanvraagByIdentificatieResponse.StavingsDocumentDto, BetalingsaanvraagDocumentViewModel>();

		CreateMap<GetBetalingsAanvraagByIdentificatieResponse.BetalingsAanvraagDto, BetalingsaanvraagVorderingsstatenViewModel>()
					.ForMember(ba => ba.TotaalBedrag, options => options.Ignore());
		CreateMap<GetBetalingsAanvraagByIdentificatieResponse.BetalingsAanvraagLijnDto, BetalingsaanvraagLijnViewModel>()
					.ForMember(ba => ba.Totaal, options => options.Ignore());
		CreateMap<GetBetalingsAanvraagByIdentificatieResponse.StavingsDocumentDto, BetalingsaanvraagDocumentViewModel>();

		CreateMap<BetalingsaanvraagLijnViewModel, UpdateBetalingsLijnBedragRequest>();	
		
		...
	}
}

2. The fact that the AssertConfigurationIsValid test just isn’t enough to avoid run-time errors.

The first issue can be avoided by putting the container to work.
Let’s just wrap the static automapper stuff into some objects :

public interface IMapper
{
	void Configure();

	//for testing only, curse you C# generics 
	object Map(object target);
}

public interface IMapper<in TFrom, out TTo> : IMapper
{
	TTo Map(TFrom from);
	IEnumerable<TTo> Map(IEnumerable<TFrom> fromList);
}

public class Mapper<TFrom, TTo> : IMapper<TFrom, TTo>
{
	public virtual void Configure()
	{
		AutoMapper.Mapper.CreateMap<TFrom, TTo>();
	}

	public object Map(object @from)
	{
		return Map((TFrom)@from);
	}

	public virtual TTo Map(TFrom @from)
	{
		return AutoMapper.Mapper.Map<TFrom, TTo>(@from);
	}

	public virtual IEnumerable<TTo> Map(IEnumerable<TFrom> fromList)
	{
		return fromList.Select(Map);
	}
}

Create some mappers, f.i. :
public class ProjectDetailMapper : Mapper<Project, ProjectDetailDto> { }

public class GetProjectDetailHandler : IGetProjectDetailHandler
{
	private readonly IGetProjectQuery query;
	private readonly IMapper<Project, ProjectDetailDto> mapper;

	public GetDetailBetalingsAanvraagHandler(
		IGetProjectQuery query,
		IMapper<Project, ProjectDetailDto> mapper)
	{
		this.query = query;
		this.mapper = mapper;
	}

	public ProjectDetailDto Handle(string id)
	{
		return mapper.Map(query.UniqueResult(id));
	}
}

And register them in the container :
public class MyRegistry : Registry
{
	public MyRegistry()
	{
		Scan(cfg =>
		{
			cfg.TheCallingAssembly();
			cfg.WithDefaultConventions();
			cfg.ConnectImplementationsToTypesClosing(typeof(IMapper<,>))
				.OnAddedPluginTypes(ex => ex.Singleton().OnCreation(map => ((IMapper)map).Configure()));
		});
	}
}

Above example assumes you’re using structuremap, but I’ve done the same with both windsor and unity.
Registering the mappers as singletons and calling their Configure method effectively does the same thing as the Boot.Strap() method above.
Except now this bookkeeping code is handled by the container.

The advantage of the method above, I find, is the fact that the mapping can be put right next to the feature, where I feel it belongs.
Mapping is not a cross-cutting concern.

The second issue, however is far more serious.
Look again at the Boot.Strap() example.
If I forget to add a mapping to the initialize method, there is no way I will find out until I actually try to map this in the app. Either through automated acceptance testing or through manual ‘labor’.

So how can we test this better ?

The refactoring described above will help us a lot.

Maintaining the same level :
Using the Boot.Strap() method we can easily test configuration by simple executing the method and then calling : ‘AutoMapper.Mapper.AssertConfigurationIsValid()’.
The same thing can be achieved by retrieving all Mapper derived types, instantiating one of each, call the configure methods and then call AssertConfigurationIsValid, like so :

[Test]
public void ConfigurationIsValid()
{
	var mappers = ScanAssemblyForMappers(); 
	mappers.ForEach(m => m.Configure());
	AutoMapper.Mapper.AssertConfigurationIsValid();
}

Upping the level :
Using the same reflection technique and with the help of quickgenerate we can test that everything we want to map, can actually be mapped.

[Test]
public void CanMap()
{
    var mappers = ScanAssemblyForMappers();
    mappers.ForEach(m => m.Configure());
    mappers.ForEach(m => m.Map(new AutoMapperTestBuilder().One(GetSourceType(m))));
}

The AutoMapperTestBuilder class is derived from quickgenerate’s DomainGenerator and sets up some stuff in the constructor.

public class AutoMapperTestBuilder : DomainGenerator
{
    public AutoMapperTestBuilder()
    {
        With<Mededeling>(
            opt => opt.StartingValue(() =>
                new[]
                {
                    new Mededeling(new StringGenerator(1, 34).GetRandomValue()),
                    new Mededeling(
                        new IntGenerator(100, 999).GetRandomValue(),
                        new IntGenerator(1000, 9999).GetRandomValue(),
                        new IntGenerator(10000, 99999).GetRandomValue())
                }
                .PickOne()));

        OneToOne<Project, Location>((p, g) => p.Location = l);
        ...
    }
}

Now the only that can go wrong is that I declare a dependency on a IMapper and I forget to actually implement this.

Fortunately, in that case, the unit test that verifies the Container configuration fails ;-) .

Posted in C# Musings | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.