The Inquisitive Coder – Davy Brion's Blog

Trying to walk that thin line between intelligence and ignorance

Think Twice Before You Map Entities To DTOs

Posted by Davy Brion on September 1st, 2010

One thing that i see a lot, and that i have largely started to avoid, is that people fetch entities with NHibernate, only to transform them to DTO’s so you can send them back to the client so they can be displayed in a a grid or some kind of list or whatever. This is usually pretty easy to do, especially if you already have a DTO mapper or are using something like Automapper. But this comes with a bit of overhead (both performance and memory) that you can often avoid quite easily.

Suppose i have a screen where i need to display entries based on the following DTO class:

    public class AuthorizationDto
    {
        public long Id { get; set; }
        public Guid ApplicationId { get; set; }
        public string ApplicationName { get; set; }
        public Guid? UserGroupId { get; set; }
        public string UserGroupName { get; set; }
        public Guid? UserId { get; set; }
        public string Username { get; set; }
        public Guid PermissionId { get; set; }
        public string PermissionName { get; set; }
        public string PermissionDescription { get; set; }
    }

This DTO basically contains data from 4 entities: Application, UserGroup, User and Permission. I could easily do something like this with NHibernate:

        	var items = Session.CreateCriteria<Authorization>()
        		.CreateAlias("Application", "a", JoinType.InnerJoin)
        		.CreateAlias("User", "u", JoinType.LeftOuterJoin)
        		.CreateAlias("UserGroup", "g", JoinType.LeftOuterJoin)
        		.CreateAlias("Permission", "p", JoinType.InnerJoin)
        		.Future<Authorization>();

        	var dtos = new AuthorizationDtoMapper().ToDtos(items);

As you can see, that’s very easy to do. Unfortunately, this code really does a lot of stuff that you might not realize. For starters, it retrieves all of the Authorization instances with its related Application, User, UserGroup and Permission instances. It also fetches those entities in their entirety, which means it’s retrieving all of their properties while i only need their Id and Name properties really. And finally, NHibernate will set up all of the things that enable its magic for all of these entity instances. That takes a few more CPU cycles and uses more memory than you truly need for the scenario of fetching entities merely to return DTO’s. This extra cost obviously becomes worse depending on the size of the resultset that you’re fetching.

A better way to do this, is to simply let NHibernate fetch only the data (columns) that you need, and to let it populate the DTO’s itself. You can easily do this using projections and the AliasToBeanResultTransformer class. The code would look like this:

			var dtos = Session.CreateCriteria<Authorization>()
				.CreateAlias("Application", "a", JoinType.InnerJoin)
				.CreateAlias("User", "u", JoinType.LeftOuterJoin)
				.CreateAlias("UserGroup", "g", JoinType.LeftOuterJoin)
				.CreateAlias("Permission", "p", JoinType.InnerJoin)
				.SetProjection(Projections.ProjectionList()
					.Add(Projections.Id(), "Id")
					.Add(Projections.Property("a.Id"), "ApplicationId")
					.Add(Projections.Property("a.Name"), "ApplicationName")
					.Add(Projections.Property("u.Id"), "UserId")
					.Add(Projections.Property("u.UserName"), "Username")
					.Add(Projections.Property("g.Id"), "UserGroupId")
					.Add(Projections.Property("g.Name"), "UserGroupName")
					.Add(Projections.Property("p.Id"), "PermissionId")
					.Add(Projections.Property("p.Name"), "PermissionName")
					.Add(Projections.Property("p.Description"), "PermissionDescription"))
				.SetResultTransformer(new AliasToBeanResultTransformer(typeof(AuthorizationDto)))
				.Future<AuthorizationDto>();

Granted, you need to write a bit more code. But that code will do far less than the first version.

Posted in NHibernate, Performance | 13 Comments »

First Impressions Of The Ruby Community

Posted by Davy Brion on August 31st, 2010

It’s been about 3 weeks since i’ve started my Ruby journey. Obviously, i still have a lot to learn. And in order to keep learning, i’m subscribing to more Ruby-related blogs and i’m starting to follow more Ruby-related folks on Twitter. At the same time, i’m gradually unsubscribing from a lot of .NET blogs and have even un-followed some people on Twitter that i only followed for .NET related stuff.

The biggest difference that i’ve noticed so far is that the Ruby community is pretty much a lot like what the ALT.NET community always wanted to be. As far as i can tell so far, knowledge is being shared all the time. And this is generally done in good spirits without negativity or flamewars (save a few exceptions obviously). People genuinely seem to care about helping other people out and making sure that everyone improves. I privately contacted a few Ruby people out of the blue. They don’t know me, and i didn’t know them. I just happened to stumble upon their blogs or twitter profiles and i figured “what the hell… i’ll just bother them with some questions”. And you know what? Every single one of them has responded in a remarkably friendly way.

When i asked them about interesting resources to follow as a newbie Rubyist, they all gladly shared their suggestions. When i thanked them for it, they all replied stating that i should feel free to contact them if i had any more questions about whatever Ruby related. Seriously, can you imagine the few .NET heroes that we have responding to questions through email from people they don’t even know like that? I can’t. Hell, i know most of them don’t respond like that. The few that do are still trying to earn their MVP award or are too worried about renewing their MVP status.

Now, i’m not saying that all is well in the Ruby/Rails world and that there are no arguments or that there isn’t any negativity or anything like that. Because the negativity and the arguments are definitely there. The thing is, it just seems to happen at a much lower frequency than it does in the .NET world. Granted, the .NET world is probably one of the most unfriendliest of all but still, the difference is striking IMO.

A part of me hopes that i’m wrong about this and that in the end, there isn’t really a substantial difference between the ruby community and the (previously ALT).NET community. Then again, another part of me hopes that what i’m seeing so far is indeed true and real. If only because that would mean that what i consider to be the ideal developer community indeed exists somewhere.

To summarize the difference: i’m sure some of you remember the infamous “Rails Is A Ghetto”-rant. Well, from what i can tell so far… if Ruby/Rails is a ghetto, then .NET is the trailer park.

Posted in Opinions, Ruby | 46 Comments »

Book Review: The Ruby Way, Second Edition

Posted by Davy Brion on August 31st, 2010

The second book i read in my ongoing Ruby journey is the second edition of The Ruby Way. While i don’t think it’s as essential as The Ruby Programming Language (you can read my review of it here), it is a very useful resource to the beginning Ruby programmer. As good as it is, it certainly has a lot of flaws as well.

At over 800 pages, this book is obviously big and heavy. That in itself is not necessarily a problem, but i wasn’t happy with the actual binding of the pages. Flipping through them just doesn’t feel right and i often felt that i had to be somewhat careful with a page if i didn’t want it to be torn out of the book by accident. And it really wouldn’t take that much effort for that to happen. If there is one book that’s an ideal test case to make you seriously consider switching to an iPad/Kindle for your reading, then this is probably it.

Luckily, the content of the book does make up for the shoddy physical reading experience. This book covers a lot of topics, which is not only a great way to introduce the beginning Ruby programmer to a variety of possibilities, but also a welcome reference to keep on your desk if you quickly need to look up how to do something. It starts off with a short review of the Ruby language, and then works its way through a variety of topics, most of which are covered very thoroughly. You really will learn everything there is to know about strings, regular expressions, numeric types, symbols, ranges, dates and times and enumerable types (arrays, hashes, sets, …). At this point, you’re about 320 pages into the book with another 450 or so to go. Those first 9 chapters are probably also the only part of the book that will at one point be read by everyone who bought this book, either while reading cover-to-cover or when you’re looking for something specific later on.

The next topic that is covered is that of IO and Data Storage. Again, this is covered pretty extensively because you’ll learn all about typical file management operations, as well as how to do marshaling of objects. There’s also a brief part on dealing with databases but it’s so short that it really would’ve been better left out altogether. You’ll see how to connect and interact with a few of the well known databases in a pretty low-level manner, but really though, hardly anyone still deals with databases in that way. It probably would’ve been better to point to some higher-level data access frameworks, since the people who are going to deal with a database in such a low-level manner are probably more than capable of figuring out how to do so without referring to a book that only briefly lists a few things that you can do for basic stuff, but nothing important.

The next chapter covers Ruby’s OOP and Dynamic features/capabilities and it’s a good 80 pages long. It goes through some of the topics a bit too quickly for my taste, but that’s alright since the next book on my reading list is Metaprogramming Ruby which is sure to whet my appetite for dynamic goodness. It does again cover quite a lot, but if you’ve read The Ruby Programming Language already, you won’t really find anything new here.

Next up is an overview of some of the graphical toolkits that you can use with Ruby. This is a chapter that ultimately doesn’t bring any value since coverage of a single toolkit is probably enough to fill an entire book already. The examples shown for each of the toolkits in this chapter are obviously short and offer no more than a quick look at how you’d interact with a certain toolkit. Well, in my case it inspired me to come up with a decent event syntax for Ruby, but that’s about it. It probably would’ve been better to leave this chapter out, and just refer to these toolkits in an appendix or something.

The book then switches to a topic that i’d been looking forward to: Threading. While Ruby does offer some constructs to deal with threading, it’s a far cry from what you might be used to in .NET. I was also surprised with the lack of attention paid to asynchronous operations, but then again, there just might not be that much interest in asynchronous programming in the Ruby world. This is definitely something i need to look into more as i continue on my Ruby journey :) . Another downside to this chapter is that some of the examples are a bit simplistic, and in some cases, aren’t quite thread-safe. If you read this chapter, focus on the discussion of what you can do with Ruby from a threading point of view, but please don’t reuse any of the code in your own code because you will end up chasing race conditions because of it.

The next 2 chapters deal with scripting, system administration and working with certain data formats (xml, rss, images, pdf). Depending on what you need or what you’re working on, this could be pretty interesting to you. The book then switches to the topics of testing and debugging. This isn’t really covered in-depth and as such, this too would’ve been better suited for an appendix with some links to online resources or dedicated books on these subjects. After that it gives another quick overview of packaging and distributing your code. This chapter also would’ve been better off being dropped since i had to package and distribute some Ruby code today and i found more useful and relevant information online than i did here.

The book then starts focusing on writing code again, but this time in the online world. First you’ll learn about low-level network programming in a chapter that is dedicated to the topic. After that, there’s a chapter about Ruby and webdevelopment and it kinda suffers from the same problems as the GUI toolkits chapter did. It lists a few of the options, of which at this point only Rails still seems to be popular but it can’t really tell you anything in-depth about it. Once again, a summarized version of this chapter would’ve been better fit for an appendix. Finally, you’ll learn about Distributed Ruby which is illustrated with an example.

The book then closes with 2 more chapters, one covering some Ruby development tools, and finally, some words on the Ruby community.

This is by far the longest book review i’ve ever written, but then again, this book is huge and i did have a lot to say about it. Its biggest flaw (apart from the shoddy physical reading experience) is that it tries to cover too much, and because of that, a lot of the stuff that is covered is basically pointless. Ideally, this book would’ve been limited to the first 11 chapters, followed by the chapters on threading and networking. The stuff about databases, web frameworks, GUI toolkits, etc… should’ve been covered in succinct appendices which should just point the reader in the right direction since there’s no way one single book can cover all of it anyway.

I know this review might come over as hard on the author and the content, but i really did like half of the book a lot. The other half however prevents me from starting this post with ‘Recommended Book’ or ‘Highly Recommended Book’ instead of ‘Book Review’. Hopefully, the upcoming 3rd edition (which should be out sometime next year) fixes some of these flaws so this book can reach the potential that it certainly does have. In the meantime, i will keep this book on my desk as a reference. About 500 of these 800 pages do contain a lot of great stuff that’s gonna save me a lot of time after all.

Posted in Books | 8 Comments »

Why Agile In The Enterprise Generally Doesn’t Work

Posted by Davy Brion on August 29th, 2010

I just came across the Manifesto for Half-Arsed Agile Software Development thanks to the wonderful world of Twitter. I’m gonna shamefully copy the text of the manifesto from the original website:

Manifesto for Half-Arsed Agile Software Development

We have heard about new ways of developing software by
paying consultants and reading Gartner reports. Through
this we have been told to value:

Individuals and interactions over processes and tools
and we have mandatory processes and tools to control how those
individuals (we prefer the term ‘resources’) interact

Working software over comprehensive documentation
as long as that software is comprehensively documented

Customer collaboration over contract negotiation
within the boundaries of strict contracts, of course, and subject to rigorous change control

Responding to change over following a plan
provided a detailed plan is in place to respond to the change, and it is followed precisely

That is, while the items on the left sound nice
in theory, we’re an enterprise company, and there’s
no way we’re letting go of the items on the right.

As funny as this is, it’s really quite sad as well. I don’t think i’m going out on a limb here if i say that the large majority of us have seen and experienced this with a striking similarity. And i think i know why. I’ve only spent time in two ‘enterprise’ companies but from what i’ve heard from a variety of people, it’s pretty much the same deal in most of them. Simply put: the typical enterprise culture leads to widespread incompetence, the majority of which is hidden from higher levels of management which eventually results in an environment where it is virtually impossible to work in an efficient manner. Whoa, i kinda dropped a bomb there didn’t i? Allow me to explain why i believe the above statement to be true.

I believe the root cause of all of the typical problems in the enterprise world to be the Peter Principle. In the enterprise world, a large group of employees is typically interested in climbing the corporate ladder. Some of them will get promoted because they did a great job. If they do a great job in their new position, they might be promoted again. Eventually, most people will end up in positions at which they perform at a level that is no longer good enough to ever be promoted again. Quite (very?) frequently, those people produced more overall value for the company in their previous position than they do in their current position. Unfortunately, none of them (save the occasional exception) will ever go back to that previous position. As good as those people were in their previous positions, they are simply incompetent for the job they’re currently doing.

Not only is it bad enough that you’ve got a lot of people who are too incompetent to do their job to a satisfactory level, you have to keep their superiors in mind as well. After all, they are the ones who promoted them. And they have superiors too. And you can safely assume that very few of them will be willing to own up their mistake in judgment to their superiors. That is, if they even realize that they made a mistake. Either way, either the incompetence is not noticed (which only points to more incompetence one level up) or it is actively hidden. Brushed under the carpet for nobody to notice. Obviously, that can’t be good for the quality of the work that is supposed to be done at every level of the hierarchy below this one. Problems will show up in pretty much everything that gets done by the lower levels. Rules, policies and guidelines are put in place to combat these problems and to try to keep the situation under control.

This in turn leads to decreased motivation, which is especially deadly for those who do have the skills and talent to right a lot of wrongs. You’re either losing time and efficiency because of people who no longer care, or because of people who simply can’t do what they’re supposed to do. Some will persevere, only to be promoted until they too are part of the problem. And the others will leave and prefer to work for smaller companies where everything seems to go “a lot smoother and easier”.

With that in mind, go over the manifesto again and ask yourself the following question: how could it possibly work in such an environment?

Posted in Opinions | 10 Comments »

‘eventpublisher’ Gem Now Available

Posted by Davy Brion on August 28th, 2010

For those of you liked the EventPublisher module that i’ve been talking about recently, it’s now available as a gem. The code is hosted on github under the MIT license and you can download/install it with the following command:

gem install eventpublisher

After that, you just need to add the following to your ruby files in order to use it:

require ‘eventpublisher’

Posted in Ruby | No Comments »

Compiler|Interpreter Warnings Are Important Learning Opportunities

Posted by Davy Brion on August 28th, 2010

When i first started to write C# code, i payed a lot of attention to compiler warnings. I wanted to avoid them at all costs. And with that i don’t mean suppressing them, but preventing them from being issued in the first place. I learned quite a few things from actually trying to understand why a certain compiler warning was issued, instead of just ignoring it like so many other developers do. In fact, when it comes to C#, i’d recommend turning on the Treat Warnings As Errors option on each project since i’ve never come across a C# compiler warning that you couldn’t avoid. And in practically every single case, avoiding the warning led to better code. When writing C#, i’ve never seen a single warning that was pointless. There might be a few esoteric ones that aren’t worth fixing, but the vast majority of us will never run into those. So do yourself a favor: if you get a compiler warning, make sure you understand why the warning was issued, and fix your code based on what you just learned while researching the warning. There simply is no reason not to do so, unless you happen to bump into the few cases where it really doesn’t matter but those cases will be far and between. In fact, i’d bet that only people like Ayende will run into them while us mortals never will.

So, how do i feel about warnings in the context of my ongoing Ruby journey? I have so little experience with Ruby that i can’t state that every single warning should be avoided. But i am of the opinion that you should at least be aware of every warning, and investigate whether or not you should modify your code to avoid it. Today i wrote my first Rakefile which automatically runs all of my RSpec tests for my EventPublisher module and one of the options of the SpecTask was to enable warnings from the Ruby interpreter. I was actually surprised that i hadn’t yet ran my Ruby code with warnings turned on. Maybe i was just too busy being impressed with the whole Ruby + TextMate package. Anyways, i turned on the warnings, ran ‘rake’ and watched a few warnings show up, much to my disappointment. Well, i was disappointed at first because i thought the code was in good shape but then i figured “ok, this is no big deal… i just gotta fix my code and i’ll learn from it”. And i did learn from it. The first one was a simple RSpec assertion that i wrote which looked like this:

	it "should know about the subscribed method for the correct event" do
		@publisher.subscribe :first_event, method(:first_event_handler)
		subscribed = @publisher.subscribed? :first_event, method(:first_event_handler)
		subscribed.should == true
	end

This generated the following warning:
warning: useless use of == in void context

I looked into it, and learned that when using RSpec, the last line should’ve been written like this:

		subscribed.should be_true

You’re probably thinking “now that’s a tiny difference and not really worth it”. And you’d be wrong. While the resulting modification in code is indeed minor, i learned about RSpec’s Matchers and how they work. And that knowledge is gonna help me in future code.

I also had the following piece of a code:

			define_method getter do
				event = instance_variable_get variable

				if event == nil
					event = Event.new(symbol.to_s)
					instance_variable_set variable, event
				end

				event
			end

When i wrote it and saw that it worked, i was pretty happy. But it turns out that this code causes the interpreter to issue the following warning:

warning: instance variable @first_event not initialized

In this case, @first_event was the value of the ‘variable’ variable, which is why the warning looks like that when the code is actually executed. So again, i looked into it, and learned that i should’ve written that code like this:

			define_method getter do
				if !instance_variable_defined? variable
					event = Event.new(symbol.to_s)
					instance_variable_set variable, event
				end

				instance_variable_get variable
			end

Moral of the story? Do not ignore compiler/interpreter warnings. They are there to help you improve not only your current code, but also your future code. That is, if you’re willing to pay attention to them.

Note: if you have experience with a variety of C/C++ compilers from back in the day, i can imagine that your opinion differs greatly from mine. However, i’m not talking about C/C++, so please keep the context (not to mention the decade…) in mind before you start typing a reply about how warnings in C/C++ could easily be justified depending on the compiler you were using ;)

Posted in Code Quality | 4 Comments »

First Experiences With RSpec/BDD

Posted by Davy Brion on August 27th, 2010

I wanted to write some tests for the EventPublisher Ruby module i’ve been playing around with, so i figured i’d just use RSpec for it since that appears to be the most popular testing library in the Ruby world. Now, in the .NET world i never really got into the whole BDD thing and i stuck with TDD because i was quite happy with the coverage that it gave me. In Ruby however, due to the whole dynamic environment i think it’s more important to test functionality as completely as possible with as little knowledge as possible of implementation details while mocking/stubbing/faking as little as possible. That doesn’t mean i wouldn’t mock anything in Ruby tests… it just means that i would try to follow my own rules on the subject as much as possible, whereas in the .NET world many of us (myself included) probably go a little overboard with the whole mocking/stubbing/faking thing.

Something to keep in mind for the rest of this post: i did not write my tests first for this thing. I know, i know, test-first is better. I generally prefer to write my tests before my real code as well, but in this case, the EventPublisher code was the result of just some first time Ruby experiments, and since i’m pretty happy with the code i don’t want to get rid of it just so i could do it “right” by re-writing it test-first. So these tests were not meant to drive the design, only to verify the correctness of the code. Also note that the tests are not complete yet. More should be added, but i thought i had enough to post here and hopefully collect some feedback from you guys/gals.

When i started with these tests for the EventPublisher module, i instinctively wanted to test on a too technical level, like i often do in .NET. For instance, i wrote a test that proved that when you called the subscribe method, that the passed in method was actually added to the Event instance that the EventPublisher uses. The thing is: if you use the EventPublisher, you never directly use Event instances. So why on earth should i even know about them in my tests, right? After all, they are an implementation detail. I had to switch my reasoning from “is the code doing what i, a software developer, think it should do?” to something along the lines of “what needs to happen when i trigger an event?”. For instance, if i trigger an event, all i should care about is that the subscribed methods are called correctly and that they receive their arguments correctly. How that actually happens is something that i probably shouldn’t care about at all in these tests.

I eventually ended up with the following:

class Publisher
	include EventPublisher
	event :my_first_event
	event :my_second_event

	def trigger_first_event(args)
		trigger :my_first_event, args
	end

	def trigger_second_event(arg1, arg2)
		trigger :my_second_event, arg1, arg2
	end
end

describe EventPublisher, ": triggering event" do
	before(:each) do
	  @publisher = Publisher.new
	end

	it "should not fail without any subscribers" do
	  @publisher.trigger_first_event "testing"
	end

	it "should pass single event arg correctly to subscribed method with one argument" do
		@args = nil
	  def my_first_event_handler(args);
			@args = args
		end

		@publisher.subscribe :my_first_event, method(:my_first_event_handler)
		@publisher.trigger_first_event "testing!"
		@args.should == "testing!"
	end

	it "should pass multiple event args correctly to subscribed method with multiple arguments" do
		@args2_1, @args2_2 = nil, nil
		def my_second_event_handler(arg1, arg2)
			@args2_1, @args2_2 = arg1, arg2
		end

		@publisher.subscribe :my_second_event, method(:my_second_event_handler)
		@publisher.trigger_second_event "second", "event"
		@args2_1.should == "second"
		@args2_2.should == "event"
	end

	it "should pass single event arg correctly to subscribed block with one argument" do
		event_args = nil
		@publisher.subscribe(:my_first_event) { |args| event_args = args }
		@publisher.trigger_first_event "test"
	  event_args.should == "test"
	end

	it "should pass multiple event args correctly to subscribed block with two arguments" do
	  first_arg, second_arg = nil, nil
		@publisher.subscribe(:my_second_event) { |arg1,arg2| first_arg, second_arg = arg1, arg2 }
		@publisher.trigger_second_event "first", "second"
		first_arg.should == "first"
		second_arg.should == "second"
	end

	it "should call subscribed method once for each time it was subscribed" do
	  @counter1 = 0
		def my_first_event_handler(args)
			@counter1 += 1
		end

		2.times { @publisher.subscribe :my_first_event, method(:my_first_event_handler) }
		@publisher.trigger_first_event "test"
		@counter1.should == 2
	end

	it "should call all subscribed methods" do
		@counter1, @counter2 = 0, 0
		def handler1(args)
			@counter1 += 1
		end

		def handler2(args)
			@counter2 += 1
		end

		@publisher.subscribe :my_first_event, method(:handler1)
		@publisher.subscribe :my_first_event, method(:handler2)
		@publisher.trigger_first_event "first_event"
		@counter1.should == 1
		@counter2.should == 1
	end

end

There are a couple of things i like about this. For starters, the output of running this code looks like this:

EventPublisher: triggering event
should not fail without any subscribers
should pass single event arg correctly to subscribed method with one argument
should pass multiple event args correctly to subscribed method with multiple arguments
should pass single event arg correctly to subscribed block with one argument
should pass multiple event args correctly to subscribed block with two arguments
should call subscribed method once for each time it was subscribed
should call all subscribed methods

Anyone can read that and understand what kind of functionality is supported.

Another big benefit of these tests is that they contain zero knowledge of the actual implementation of the EventPublisher module. They merely initiate its functionality, and verify whether the expected behavior in the given functional context occurred. I could seriously refactor (or even rewrite) the actual EventPublisher code and i wouldn’t have to change my tests as long as i don’t change the name and arguments of the subscribe and trigger methods.

For now, i’m pretty happy with this style and organization of tests and will probably stick with it for a while in my Ruby coding. Unless one (or some) of you tell me how i can improve it :)

Posted in Ruby, Test Driven Development | 2 Comments »

The Downside Of Providing An API Through Extension Methods

Posted by Davy Brion on August 26th, 2010

I recently used the excellent Moq mocking library for the first time, and i noticed a difference between Moq and Rhino Mocks (what i usually use) that i found interesting.

Consider the following useless and contrived example code:

    public interface ISomeComponent

    {

        void DoSomething();

    }

 

    public class SomeClass

    {

        private ISomeComponent someComponent;

 

        public SomeClass(ISomeComponent someComponent)

        {

            this.someComponent = someComponent;

        }

 

        public void DoSomethingReallyImportant()

        {

            someComponent.DoSomething();

        }

    }

 

Now suppose that we want to verify in a test that the DoSomethingReallyImportant method of SomeClass actually calls the DoSomething method of its ISomeComponent dependency.

With Moq, we could do that like this:

    [TestFixture]

    public class TestWithMoq

    {

        [Test]

        public void CallsDoSomethingOnSomeComponent()

        {

            var mock = new Mock<ISomeComponent>();

            var someObject = new SomeClass(mock.Object);

 

            someObject.DoSomethingReallyImportant();

 

            mock.Verify(m => m.DoSomething());

        }

    }

 

And with Rhino Mocks, it would look like this:

    [TestFixture]

    public class TestWithRhinoMocks

    {

        [Test]

        public void CallsDoSomethingOnSomeComponent()

        {

            var mock = MockRepository.GenerateMock<ISomeComponent>();

            var someObject = new SomeClass(mock);

 

            someObject.DoSomethingReallyImportant();

 

            mock.AssertWasCalled(m => m.DoSomething());

        }

    }

 

Not much of a difference, right? Except that Rhino Mocks provides you with a proxy that implements the ISomeComponent interface and Moq provides you with a generic Mock object, which contains a proxy that implements the ISomeComponent interface and is exposed through the Object property. Other than that, the tests are very similar.

The key difference is what you experience when you write the tests, as the 2 pictures below will illustrate:

Since Moq’s API is not fully based on Extension Methods, you get a normal and clean IntelliSense experience. Rhino Mocks on the other hand provides its API (at least the non-legacy stuff) solely through extension methods, which leads to all of them being included in your IntelliSense, even when they don’t make any sense at all.

It’s obviously not a major issue, but i was suprised with how much i liked not seeing all of the extension methods all the time while writing tests.

Posted in Code Quality, Test Driven Development | 7 Comments »

Auto-Wiring Ruby Events

Posted by Davy Brion on August 26th, 2010

My Rubyesq events received some nice comments in the Ruby Show #130 (fast forward to the 15 minute mark in the audio stream, or the 14 minute mark in the video stream if you wanna see or hear the part about the events), so i figured: why not make them even better?

Alex Simkin had suggested to implement some kind of auto-wiring of events. I thought it would be fun to implement, so i did. Suppose we have the following class:

class Publisher
	include EventPublisher
	event :first_event
	event :second_event

	def trigger_events
		trigger :first_event, "first event"
		trigger :second_event, "second event"
	end
end

If we want to subscribe to both events, we’d need to write code like this:

		@publisher.subscribe :first_event, method(:first_event_handler)
		@publisher.subscribe :second_event, method(:second_event_handler)

But it obviously would be much nicer if we could just do something like this:

		@publisher.subscribe_all self

The subscribe_all method could then just look at all the methods that the passed-in instance contains, and it could automatically subscribe each suitable handler (based on a simple convention) to the correct event.

That means we could just have a Subscriber class like this:

class Subscriber
	def initialize(publisher)
		@publisher = publisher
		@publisher.subscribe_all self
	end

	def stop_listening
		@publisher.unsubscribe_all self
	end

	def first_event_handler(args)
		puts args
	end

	def second_event_handler(args)
		puts args
	end
end

This was pretty easy to do actually. Our Event class remains the same, but our EventPublisher module does get a few new methods:

	def each_suitable_handler(subscriber)
		possible_handlers = subscriber.class.instance_methods.select { |name| name =~ /\w_handler/ }
		possible_handlers.each do |method_name|
			event_name = /(?<event_name>.*)_handler/.match(method_name)[:event_name]
			if EVENTS.include? event_name.to_sym
				yield event_name.to_sym, method_name.to_sym
			end
		end
	end

	def subscribe_all(subscriber)
		each_suitable_handler(subscriber) do |event_symbol, method_symbol|
			subscribe event_symbol, subscriber.method(method_symbol)
		end
	end

	def unsubscribe_all(subscriber)
		each_suitable_handler(subscriber) do |event_symbol, method_symbol|
			unsubscribe event_symbol, subscriber.method(method_symbol)
		end
	end

And the method to define an event was slightly modified, so it now looks like this:

	self.class.class_eval do
		EVENTS = []

		def event(symbol)
			getter = symbol
			variable = :"@#{symbol}"
			EVENTS << symbol

			define_method getter do
				event = instance_variable_get variable

				if event == nil
					event = Event.new(symbol.to_s)
					instance_variable_set variable, event
				end

				event
			end
		end
	end

The only difference here is that we define an EVENTS array constant, and every time an event is defined, we add the symbol of the event to the EVENTS array. I’m not very happy with using an array constant to do this, but it was the only way i found to store the symbol name of each event when it’s defined while also being able to access those symbols from within the each_suitable_handler method. Again, i’m new at Ruby so i’m probably missing an easier alternative here.

But with these changes in place, we can now run the following code:

publisher = Publisher.new
subscriber = Subscriber.new(publisher)
publisher.trigger_events
subscriber.stop_listening
publisher.trigger_events

Which produces the expected output:

first event
second event

For the 5 people who are going to want to use this: i’m going to create a gem for this soon, and the code will be hosted on GitHub. I just need to learn how to create a gem and learn how Git works first though :)

Posted in Ruby | 5 Comments »

Using More Rubyesq Events In Ruby

Posted by Davy Brion on August 23rd, 2010

In my previous post i showed a way to use events in Ruby in a way that is very similar to how it is in C#. Somebody left a comment saying that i should take off my C# hat, and do it in a more typical Ruby way. I agree with that so i wanted to create an implementation based on his comment. I also wanted to avoid opening up the Object class and requiring you to mix-in a module in order to use the events.

The goal is basically to declare an event like this:

class Something
	include EventPublisher
	event :some_event
end

And subscribing to the event would be done like this:

	something.subscribe :some_event, method(:some_handler)

or

	something.subscribe(:some_event) { |args| puts "something happened!" }

and if you subscribed with a method, you should be able to unsubscribe like this:

	something.unsubscribe :some_event, method(:some_handler)

This was again pretty simple to implement, though this implementation is not a robust as it could be (so keep that in mind if you ever decide to use this approach). First of all, we again start off with the Event class, which now looks like this:

class Event
	attr_reader :name

	def initialize(name)
		@name = name
		@handlers = []
	end

	def add(method=nil, &block)
		@handlers << method if method
		@handlers << block if block
	end

	def remove(method)
		@handlers.delete method
	end

	def trigger(*args)
		@handlers.each { |handler| handler.call *args }
	end
end

Nothing special here, except that the add method can accept a Method instance, a block, or both. The default value of the method parameter is nil so you can skip it if you only want to hook a block to the event.

And then we have the EventPublisher module that you can mix-in (more on this in a bit) to your class:

module EventPublisher
	def subscribe(symbol, method=nil, &block)
		event = send(symbol)
		event.add method if method
		event.add block if block
	end

	def unsubscribe(symbol, method)
		event = send(symbol)
		event.remove method
	end

	private

	def trigger(symbol, *args)
		event = send(symbol)
		event.trigger *args
	end

	self.class.class_eval do
		def event(symbol)
			getter = symbol
			variable = :"@#{symbol}"

			define_method getter do
				event = instance_variable_get variable

				if event == nil
					event = Event.new(symbol.to_s)
					instance_variable_set variable, event
				end

				event
			end
		end
	end
end

You might be wondering what the following line does:

		event = send(symbol)

This dynamically calls the method with the given symbol. In our case, that would be the getter method to access the event, which we only create during the registration of an event, so we can’t call this method like we’d normally do.

Also note that there is no way to unsubscribe a block from the event. Well, there might be a way but i simply don’t know how to do it, since a block is not an object and it has no identity. AFAIK (and again, i’m a ruby n00b) there is no good way to compare blocks, so we can’t unsubscribe them from events either. So you really only want to subscribe blocks to an event if you’re sure that the event will not be published at a time when you don’t want the block to be executed. Also, keep in mind that any variables that the block closes on will be kept in memory, so if your block closes on object references, their instances will be kept in memory until the publisher of the event is garbage collected.

If you need to be sure that you can remove the behavior you’ve added to an event, subscribe with a Method instance and unsubscribe when you need the added behavior removed again!

Now we can define our Publisher from the previous post like this:

class Publisher
	include EventPublisher
	event :notify

	def trigger_notify
		trigger :notify, "hello world!"
	end
end

The EventPublisher module is used as a mixin in the Publisher class. Simply put, that means that the methods defined in EventPublisher are now a part of the Publisher class as well (including their definition), and the nice thing about it is that we didn’t have to inherit from a base class to inherit this extra functionality.

We also have the following two classes:

class SubscriberWithMethod
	def start_listening_to(publisher)
		@publisher = publisher
		@publisher.subscribe :notify, method(:notify_handler)
	end

	def stop_listening
		@publisher.unsubscribe :notify, method(:notify_handler)
	end

	def notify_handler(args)
		puts "#{self.class.to_s} received: #{args}"
	end
end

class SubscriberWithBlock
	def start_listening_to(publisher)
		@publisher = publisher
		@publisher.subscribe(:notify) { |args| puts "block received: #{args}" }
	end
end

The first class subscribes to the event through a Method instance, the second simply assigns a block. As you can see, the first class can unsubscribe from the event by passing the Method instance to the unsubscribe method for that given event.

And if we run the following code:

publisher = Publisher.new
subscriber1 = SubscriberWithMethod.new
subscriber2 = SubscriberWithBlock.new
subscriber1.start_listening_to publisher
subscriber2.start_listening_to publisher
publisher.trigger_notify
subscriber1.stop_listening
publisher.trigger_notify

We get the following output:

SubscriberWithMethod received: hello world!
block received: hello world!
block received: hello world!

Posted in Ruby | 13 Comments »