Don’t worry, this post isn’t about the ongoing political problems that Belgium has been suffering from for the past 3 years. It’s about something far more interesting (ahem): the way they read my blog. I was going over the blog’s stats for last month:
As you can see, the numbers for the Belgians are far different than they are for each other country in that list. The number of pages they read each visit is way above the average. The average time they spend on this site is also much higher than most countries. And the percentage of new visitors and the bounce rate is a lot lower than what we see from other countries. That means that almost 4 out of 5 Belgians that visit this site have been here before, and keeping the total number of visits in mind and the fact that it has a much smaller population than the other countries in the top 7, they seem to keep coming back as well. And this isn’t just an anomaly because the all-time stats for this blog show pretty much the same picture:
So that makes me wonder: what’s up with these Belgians? And yes, i know that some of you are probably thinking: “well duh, it’s because you’re Belgian too!”. But there are a couple of reasons why i don’t think that me being from Belgium explains it:
So, it can’t be because i’ve been pushing this blog among the Belgian developers. So what is it then? Is it because we Belgians are generally quite thorough when it comes to learning about stuff we like? Or are we just lazy and do we love to waste a lot of time online? Both are true to some degree
. Either way, it’s nice to see Belgium among the top of a list (even if it doesn’t mean shit) that isn’t related to female tennis, chocolate, beer, organized crime or fraud.
Seriously though, i do find this kind of stuff interesting so if you are Belgian (or are familiar with how Belgians are) and have some ideas on why those numbers are so different from other countries, please do share
Creating a DSL seems like a hard thing to do, right? While there are various interesting challenges that you’ll need to deal with if you want to build and use a real DSL, the initial step of getting it working is actually a lot easier than you might think it is. I’m gonna walk you through the creation of a simple DSL, suitable for a domain that all of us have experience with. The domain is quite simple: describing entities, their properties and their relationships. Forget for a second that you could obviously get the exact same information from a set of class definitions. It’s merely a technical exercise using a domain that we all know
One of the key questions that we need to ask ourselves is: what kind of concepts do we want to be able to describe with our DSL? In our case, we want to describe a model consisting of entities. Disregarding behavior for now, we can say that each entity will consist of properties. Properties could be regular properties, references to other Entities, or collections of other entities. Here’s one way (of many, obviously) to model that in Ruby (since that language makes it very easy to define a DSL):
require 'forwardable'
class Model
extend Forwardable
def initialize
@entities = []
end
def add_entity(entity)
@entities << entity
end
def entity_for(name)
@entities.detect { |entity| entity.name == name }
end
def_delegator :@entities, :each, :each_entity
end
class Entity
extend Forwardable
attr_reader :name
def initialize(name)
@name = name
@collections = []
@properties = []
@references = []
end
def add_collection(collection)
@collections << collection
end
def add_property(property)
@properties << property
end
def add_reference(reference)
@references << reference
end
def identifier
@properties.detect { |property| property.is_identifier? }
end
def_delegator :@collections, :each, :each_collection
def_delegator :@properties, :each, :each_property
def_delegator :@references, :each, :each_reference
end
class Property
attr_reader :name
attr_reader :required
attr_reader :type
def self.new_identifier(name, type)
self.new(name, type, false, true)
end
def initialize(name, type, required=false, is_identifier=false)
@name = name
@type = type
@required = required
@is_identifier = is_identifier
end
def is_identifier?
@is_identifier
end
end
class Reference
attr_reader :name
attr_reader :entity
attr_reader :is_required
def initialize(name, entity, is_required)
@name = name
@entity = entity
@is_required = is_required
end
end
class Reference
attr_reader :name
attr_reader :entity
attr_reader :is_required
def initialize(name, entity, is_required)
@name = name
@entity = entity
@is_required = is_required
end
end
class Collection
attr_reader :name
attr_reader :entity
def initialize(name, entity)
@name = name
@entity = entity
end
end
That gives us a simple, yet complete object model to describe entities, their properties and their relationships. The next question is: how do we define the DSL? Considering an Invoice entity, suppose we’d like to describe it in our DSL like this:
entity "Invoice" identified_by "Id", :guid must_reference "Customer" must_have "Date", :date can_have "Discount", :double contains "Lines", "InvoiceLine"
This really tells us anything we need to know about this entity, and we could use this data for pretty much everything we want. There is no explicit or implicit link to any specific kind of technology, like say, a relational database, a document database, or some kind of databinding technology. We could transform or extend this data to suit whichever purpose we deem fit.
So now that we know how we want to describe our entities and their relationships, we can implement the language. As mentioned in the title of this post, this is the implementation of a simple DSL. It’s just to illustrate an idea, and not an approach that is guaranteed to stand up to the real-world requirements that a DSL could face (and that depends on a case by case basis). So in this case, we’re going to go with an implementation where each entity is described in its own file, and its filename must end with ‘_def.rb’. With that limitation in mind, we can do this:
require_relative 'application.rb'
require_relative 'entity.rb'
require_relative 'collection.rb'
require_relative 'property.rb'
require_relative 'reference.rb'
@model = Model.new
def entity(name)
entity = Entity.new(name)
@model.add_entity entity
@current_entity = entity
end
def identified_by(name, type)
@current_entity.add_property Property.new_identifier(name, type)
end
def must_have(name, type)
has name, type, true
end
def can_have(name, type)
has name, type, false
end
def must_reference(entity_name, name=nil)
references entity_name, true, name
end
def can_reference(entity_name, name=nil)
references entity_name, false, name
end
def contains(name, entity_name)
referred_entity = @model.entity_for entity_name
@current_entity.add_collection Collection.new(name, referred_entity)
end
def has(name, type, required=false)
@current_entity.add_property Property.new(name, type, required)
end
def references(entity_name, is_required=false, name=nil)
referred_entity = @model.entity_for entity_name
name = entity_name if name.nil?
@current_entity.add_reference Reference.new(name, entity_name, is_required)
end
Dir.glob('*_def.rb').each do |file|
@current_entity = nil
load file
end
@model.each_entity do |entity|
puts entity.name
print_name = Proc.new { |item| puts "\t\t#{item.name}"}
puts "\t has the following properties:"
entity.each_property &print_name
puts "\t has the following references:"
entity.each_reference &print_name
puts "\t has the following collections:"
entity.each_collection &print_name
end
As you can see, we have ‘global’ method definitions (they’re actually implicitly added to the Object class) which correspond with our language ‘keywords’. Those method implementations use the model that we defined earlier to build a nice object graph based on what we describe through our DSL.
You’ll notice that after the method definitions, you can see the following code:
Dir.glob('*_def.rb').each do |file|
@current_entity = nil
load file
end
And that’s the clue to this simple DSL: it loops through each file that matches the ‘*_def.rb’ pattern, sets an instance variable named @current_entity (implicitly added to the current Object instance in this case) to nil, and then loads the current file in the loop. The load method (it might look like a keyword, but it’s a method) executes the ruby code in the given file in place, meaning that it shares the same scope. In other words, the methods that we’ve defined here are accessible to our DSL declarations since those are executed within the same scope. And since those method implementations manipulate our domain model, we just built a simple ‘language’ to describe our entities, their properties and their relations.
Suppose we’ve got the following entity definitions (each would be in a separate file, but they are just listed all at once here):
entity "Customer" identified_by "Id", :guid must_have "Name", :string can_have "Email", :string entity "Product" identified_by "Id", :guid must_have "Name", :string must_have "Price", :integer entity "InvoiceLine" identified_by "Id", :guid must_reference "Product" must_have "Count", :integer entity "Invoice" identified_by "Id", :guid must_reference "Customer" must_have "Date", :date can_have "Discount", :double contains "Lines", "InvoiceLine"
This describes a very small domain model consisting of 4 entities. In the code listed above, you may have noticed the following piece at the end:
@model.each_entity do |entity|
puts entity.name
print_name = Proc.new { |item| puts "\t\t#{item.name}"}
puts "\t has the following properties:"
entity.each_property &print_name
puts "\t has the following references:"
entity.each_reference &print_name
puts "\t has the following collections:"
entity.each_collection &print_name
end
Given the 4 described entities, running the code above results in the following output:
Customer has the following properties: Id Name Email has the following references: has the following collections: Invoice has the following properties: Id Date Discount has the following references: Customer has the following collections: Lines InvoiceLine has the following properties: Id Count has the following references: Product has the following collections: Product has the following properties: Id Name Price has the following references: has the following collections:
So there you have it, we described our entities, their properties and their relationships in a very simple manner and those descriptions were interpreted and the data has been put into an object model that we can use for a variety of purposes if we wanted to. And there really are a lot of interesting things we can do with this, especially when keeping IronRuby in mind
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.
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.
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.
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 DevelopmentWe 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?
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’
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
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
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.
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
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!
I’m still learning Ruby, and am almost through my second book about it. But i finally caved in to the urge to just start playing around with it instead of reading about it first. One of the things i noticed so far about the language, is that it doesn’t have something like C#’s events. At least not out of the box. I thought it would be fun to write something that allows me to define and use events in Ruby in a way that is very similar to how it works in C#. It actually is pretty easy to do this and i think it shows some of the power and flexibility of the Ruby language.
For those of you who already know and use Ruby: i know that this is most likely not the best way to do this, and that all of this is probably already available. But keep in mind that this is my ‘hello world’ in Ruby and that i’m just playing around with it.
First of all, we’re going to need an Event class:
class Event
attr_reader :name
def initialize(name)
@name = name
@handlers = []
end
def +(eventhandler)
raise TypeError "Method expected" unless eventhandler.is_a? Method
@handlers[@handlers.size] = eventhandler
self
end
def -(eventhandler)
@handlers.delete eventhandler
self
end
def trigger(args)
@handlers.each { |handler| handler.call args }
end
end
This code is really simple. An Event instance has a name, and an array of handlers. A handler is just a reference to a Method that we can execute whenever we want. The + method allows you to add a handler to the event, and it simply returns self, so we can sort of mimic the C# event subscription code. Our Ruby variant basically looks like this:
publisher.some_event += method(:my_event_handler)
The – method basically uses the same trick, so unsubscribing from an event looks like this:
publisher.some_event -= method(:my_event_handler)
With that in place, we need a way to define an event in a class, and to trigger it. Preferably, this has to look as natural as possible and with that i mean that it should look like it’s just supported by language keywords. We naturally can’t add language keywords, but we can fake it sort of by adding methods which you can call without parentheses so at least it’ll look like language keywords. There are multiple ways to do this, but i’ve chosen the simplest one, which is to open the Object class and add a few private methods it. Note that in Ruby, private methods can be used by derived classes so these methods are accessible by any class that inherits from it, but you’ll never be able to call them on any instance but yourself.
class Object
private
def define_event(symbol)
getter = symbol
setter = :"#{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
define_method setter do |value|
instance_variable_set variable, value
end
end
def trigger_event(symbol, args)
event = instance_variable_get :"@#{symbol}"
event.trigger *args
end
end
This piece of code probably deserves some more explanation
. We basically add two methods to the Object class: define_event and trigger_event. When define_event is called, we dynamically add 2 methods to the class: a getter and a setter for the newly created Event. The only reason we need the setter is to enable the subscription syntax:
publisher.some_event += method(:my_event_handler)
Which is basically the same as doing this:
publisher.some_event = publisher.some_event + method(:my_event_handler)
The trigger_event method is very straightforward: it just retrieves the instance variable for the event, and calls its trigger method and passes the args variable.
And that’s it… lets demonstrate this new ‘language feature’ with a simple example. First, we have the Publisher class:
class Publisher define_event :notify def trigger_notify trigger_event :notify, "hello world!" end end
It defines an event with the name ‘notify’ and it has a public method to trigger the event. We also have a Subscriber class:
class Subscriber
def start_listening_to(publisher)
raise TypeError "Publisher expected" unless publisher.is_a? Publisher
@publisher = publisher
@publisher.notify += method(:event_handler)
end
def stop_listening
@publisher.notify -= method(:event_handler)
@publiser = nil
end
def event_handler(args)
puts "#{object_id} #{Time.now} received: #{args}"
end
end
As you can see, the Subscriber subscribes and unsubscribes from the ‘notify’ event in a manner that is very similar to how it’s done in C#.
Finally, the output of the following code:
publisher = Publisher.new subscriber1 = Subscriber.new subscriber2 = Subscriber.new subscriber1.start_listening_to publisher subscriber2.start_listening_to publisher publisher.trigger_notify subscriber1.stop_listening publisher.trigger_notify
is this:
2148074920 Sun Aug 22 12:17:58 +0200 2010 received: hello world!
2148074900 Sun Aug 22 12:17:58 +0200 2010 received: hello world!
2148074900 Sun Aug 22 12:17:58 +0200 2010 received: hello world!
As you can see, subscriber1 received the event once, while subscriber2 received it twice.
Again, this is certainly not the best way to do this but i just wanted to try this because i can. And for the experienced Ruby devs among you, please go easy on me since this is just my first piece of Ruby code
A coworker of mine spent some hours yesterday hunting down memory leaks in an app that he’d already gotten ‘leak-free’ back when it was in Silverlight 3. Turns out that the leaks are caused by changes in Silverlight 4 and not in our code. As you surely know, Microsoft releases major Silverlight versions pretty frequently (there’s at least one major new version each year). That’s great and all when it comes to introducing new features and capabilities, but it truly sucks if you keep introducing new problems as well. The total amount of time (and thus, money) that we’ve lost hunting down leaks that are located in either the core Silverlight code or the Control Toolkit (also Microsoft code) is just starting to become embarrassingly high.
To give you an idea of what kind of leaks that keep popping up, be sure to check out these links:
http://forums.silverlight.net/forums/t/179177.aspx
http://forums.silverlight.net/forums/t/179358.aspx
http://forums.silverlight.net/forums/t/180702.aspx
http://forums.silverlight.net/forums/t/181257.aspx
http://forums.silverlight.net/forums/t/171739.aspx
If anyone from Microsoft reads this: please, pretty please, pretty please with sugar on top: can we get a little bit more QA from you guys? If you can put out products like WebMatrix and LightSwitch, than surely you must have enough resources available to make sure that your real development platforms do not become a cost-sink for your customers due to your own lack of quality control, no?
Update: it’s also quite telling that the search phrase “silverlight memory leak” is the number one search phrase through which people get to this site. #justsaying
I happened to come across some blog posts and tweets that once again mentioned how evil it is to use comments in code. Some people still like to advocate the “if you need comments, your code sucks!” sentiment. As is often the case with this kind of statement, the only correct (or dare i say realistic) point of view is: it depends!
I generally agree that you should strive to avoid comments in code. That is, you should write your code in a way that doesn’t require comments for the reader to easily understand and grasp what the code is doing. However… there are situations where comments are helpful (or even required), since you simply can’t write everything in such a manner that it doesn’t require any comments.
To back up my point, i’d like to point you to this challenge i posted over a year ago. That code is clean. But pretty much everyone could use some comments to understand why that certain approach was necessary since it’s just not that obvious when focusing solely on the code. That code applies a certain pattern which isn’t well known, but there is a very specific reason why the pattern is needed. And i still believe that most developers need comments to understand it properly. That’s not to say that the guy who wrote it (which happened to be me) is better than those who’re going to have to maintain it. Hell, i wrote the code, and i would certainly be glad to see some comments in that code if i had to make a change 6 months after the fact.
The key thing to remember is this: don’t blindly follow what the books and/or the ‘legends’ say. If you need to write some code in a very non-obvious way, then you could really make things easier for those who need to maintain it (which could very well be you, btw) by including some comments to explain why a certain solution/pattern was chosen. There are some details you simply can’t show through good naming practices or clean code in general… some things simply need to be explained and it’s quite possible that a WHY comment or two benefits not only you but whoever is going to read the code more than some kind of excessive and futile exercise in making it as easy to understand as possible without comments ever will be.
In short, strive to avoid the need to write comments by writing clean code. But don’t be afraid to use comments wisely either when clean code simply doesn’t cut it. There’s nothing wrong with that. After all, we don’t all have the luxury to restrict our efforts to contrived examples.
As you probably know, i’m currently learning Ruby. And as you may or may not know, Ruby is a very dynamic language. And one of the things that i found immensely interesting about it is the ability to add methods to existing classes or to existing objects, which isn’t the same as adding a method to a class in Ruby btw. And it sorta got me thinking about how the whole static vs dynamic thing can be applied to how we are often taught about objects and classes.
Chances are that when you learned about OO, you were introduced to the concept of objects using real world items. For instance, a door could be an object. It has certain attributes, and it has certain operations that can be invoked on it. But once a door has been produced, it will never gain new capabilities. It won’t learn anything new. If anything, the attributes and operations that it was created with will only deteriorate over time.
Then again, some of us will undoubtedly have heard that a person is an example of an object too. A Person is an instance of the Human class. There is a huge difference between a Person instance and a Door instance. While the Door will never change (except for possible deterioration), a Person will change during its lifetime. It will gain new capabilities depending on what the Person instance goes through during its lifetime. It will also lose capabilities. It will gain new attributes, and some of them will no longer apply to that Person instance after a while. Its relationships can vary wildly from each Person to the next. A Person instance is highly dynamic throughout its lifetime, while a Door will always be the same.
The weird thing is… a lot of us use OO to model or mimic real world behavior. But real world behavior is pretty dynamic. Not for everything, but it definitely is for some things. And all this time, a large majority of us has been trying to model or mimic that behavior with static languages. In a static language, a Person instance would never be able to grow. You could define multiple types of Persons, but hey, a lot of people generally don’t like to be put in groups based on attributes or capabilities and you’ll always run into problems when doing so.
I’m not trying to convince anyone about anything specific in this post. But i am trying to get you think about what i’m saying. I do believe that objects can ‘grow’ in some or maybe even a lot of cases. And i think a lot of us can agree that static languages aren’t exactly a great solution to dealing with this problem (though i prefer the term ‘reality’ instead). Dynamic languages on the other hand can offer better ways to deal with this, but then again you do have to keep in mind that they come with some downsides as well. In software development, there are very, very few win-win situations. Everything is a trade-off. For everything that you know and love, there will be an alternative that is more suitable in some cases, and less suitable in others.
So now i’d like to ask you the following 2 questions:
1) do you think that objects can ‘grow’?
2) can developers grow? and how does that answer correspond to your answer to the first question?
I first learned about Ruby about 8 years ago, when another programmer that i only knew from some Linux-related forum (yup, i was a die-hard linux user at the time) kept claiming that it was one of the nicest and purest OO languages available. I kept thinking “yeah right, nobody is using Ruby for real stuff so it can’t be good”. In my defense, i was only 21 at the time and at that age a lot of people can still be quite ignorant at times (or even quite frequently). But that doesn’t change the fact that i was just plain stupid.
Fast forward 8 years, and here i am: a developer who was once convinced of the virtues of static languages, but is increasingly frustrated by both the static nature of C# (regardless of the introduction of the dynamic keyword) because of the limits it places on my creativity, as well as the entire .NET world for a variety of reasons. So i figured it was time for me to learn exactly what was so good about these dynamic languages. At first, i doubted between going for Ruby and Python. I picked Ruby, mostly because it has more momentum than Python. And since i hate learning something new from some simple online tutorials, i wanted to get some good books on the subject to make sure i really learned what it was all about. The first book i ordered was The Ruby Programming Language which seems to be the definitive guide to the Ruby language. It ought to be, with that title
Books about programming languages are generally pretty boring. It’s not the fault of the writers, or the language, it’s just because so many boring details need to be covered when learning a new language. I was very happy to see that this book certainly minimizes those boring parts. The book starts off with a quick introduction to Ruby. It very quickly goes over some code with very brief explanations as to what the code is doing. Not sure if everyone will agree on this, but for me it was like the perfect appetizer. It really made me want to learn the language thoroughly.
The next 4 chapters aren’t nearly as interesting as the introduction was. The 2nd chapter deals with the structure of Ruby code. Important, but not exactly thrilling to read. The 3rd chapter discusses some of the standard data types and you’ll also learn more about how objects work in Ruby. The stuff about objects was very interesting, but the descriptions of the data types are, as they always are, pretty boring. The 4th chapter (Expressions and Operators) and the 5th one (Statements and Control Structures) are also quite boring. But then again, i can’t possibly imagine how anyone could write about these kinds of topics in a way that is truly interesting, regardless of the programming language that is used. In fact, i’d say that these topics were dealt with in a manner that is at least less boring than how they’re usually covered in programming books. And even though those parts are not the most interesting to read, it is great reference material if you quickly need to figure out something or need to refresh your memory while working with the language.
The next 3 chapters however were (IMO) immensely interesting. Chapter 6 tells you everything you need to know about Methods, Procs, Lambdas and Closures. You might be thinking “how could that possibly be immensely interesting?”, but trust me, it is. I also think that this chapter will either strongly increase your appreciation of the Ruby language, or might be a little off putting, depending on how you generally feel about the importance of static typing vs dynamic. Most developers will see the possible dangers here and you’ll either feel fear for what people can do in a method, or you’ll love the power and flexibility while still recognizing the dangers (with an increased appreciation for automated tests, hopefully).
Chapter 7 deals with everything there is to know about classes and modules, and it’s an absolute joy to read. At this point, i really started to feel stupid for not having learned about this years ago. Lots of interesting stuff here, and the ideas it planted in my head are surely gonna hurt me frequently while coding in C# at work. Chapter 8 was even worse in this regard… it discusses Ruby’s reflection capabilities and the whole metaprogramming thing. It made my head spin, in the good way. I know i can really take serious advantage of those capabilities and i can’t wait to actually experiment with it.
The 9th chapter discusses the Ruby Platform, which is basically a succinct run down of what you can do with a lot of the standard Ruby classes. I largely skipped this chapter since the next book on my reading-list (The Ruby Way) covers all of that and more, in depth. The final chapter covers the Ruby interpreter and the general Ruby environment. It’s somewhat interesting, but nothing spectacular.
I generally approach programming language books as necessary reading (at least when you’re learning a language) but a chore at the same time. While some of the chapters in this book suffer from a lot of the same problems that you’ll find with other programming language books, it at least is less boring to read. Chapter 6 through 8 however are more than worth the cost of the book and could really change the way you think and feel about OO and if i could legally get away with it, i’d force every programmer to read those. It’s certainly not going to convince everyone, but it could open a lot of people’s eyes. This book is not only ideal to learn the Ruby language, it’ll also be an invaluable reference resource to keep on your desk as you keep taking more steps in your Ruby journey.
I already know it’s gonna take a long while before this book moves from my desk to my bookshelf.
It’s been about a month since i caved and finally joined Twitter after having earlier said that i wouldn’t. When i joined Twitter, i said this:
If i like it, i’ll keep using it and i’ll gladly state that i was wrong about the whole thing.
So here it is: i was wrong about the whole thing! Overall, i actually like it a lot and i’d probably find it pretty weird if i had to go back to going without it. But it’s not all perfect though. So, this is a list of likes and dislikes that i’ve noticed after about a month of twitter.
Likes:
Dislikes:
It’s obviously quite possible that some of the dislikes i mentioned are due to my noobness so if anyone has any tips regarding those issues, i’d love to hear them
Just a little heads-up to those reading this: this post is filed in the ‘Rants’ category. I’m gonna rant about some stuff that i don’t like, so if you don’t like reading these kinds of posts, do both of us a favor and skip this one.
I haven’t been too happy with the .NET world lately. I’ve always been somewhat critical of the .NET world, but generally, i felt it was one of the better environments to work in. But there are some things that have been bothering me for a while now, and there are some recent developments that really made me think about the future of this platform. First, i want to focus on the things that have been bothering me since the beginning. After that, i’ll discuss the problems that i expect in the future.
One Ring To Rule Them AllAs we all know, Microsoft has a tremendously large influence on how software gets developed in the .NET world. For many companies, this is indeed quite convenient. You can stick to the Microsoft Path (or should i say: the One Microsoft Way?) and you’ll have all the guidance you can ask for. They provide architectural and design guidance for everything from your database to your business layer to your service layer all the way to your presentation layer. Unfortunately, a lot of that guidance is of a terribly low quality. Follow their guidance and odds are pretty high that either your database implementation details are leaking through all the way to your screens, or that a lot of your business details are taken care of in the database. Depending on how many Microsoft MVP’s you’ve listened to, you might end up with both situations simultaneously.
One of the most important goals of every piece of guidance and tooling that they provide is accessibility. Lower-end developers should be able to use their products and their guidance and be able to build software of an acceptable quality. Unfortunately, a lot of the mess that is produced on a daily basis in the .NET world is the result of that very same goal. And the only people who are (knowingly) suffering from it are the higher-end developers. They are the ones who have to deal with, and clean up the mess. Customers and companies hardly ever realize how much money they’re losing on this because this low standard for quality is apparently not only accepted in the .NET world, but also expected. A lot of people simply don’t know that the quality of software that we, the .NET community, produce on average is really low compared to other development communities. But then again, that is naturally what you get when you want to lower the bar and try to get everyone involved with developing software. You’d think that after over 50 years of history in this business, we’d have wised up to that fallacy by now, no?
The low quality of the guidance and the tools is the reason why i have started referring to the typical Microsoft recommended development practices and products as Fisher Price Development. It’s great if you’re into toys, but if you wanna get serious, it’s just not gonna cut it. It wouldn’t be so much of a problem if the vast majority of the .NET developer community wouldn’t just blindly accept everything that Microsoft tells them to do or use. Which brings me to my next point…
Developers, Developers, Developers!There is a huge difference in quality between the higher-end .NET developers, and the lower-end. The higher-end developers are generally more open-minded to what works in other development communities and want to learn from that. And they want to take what they’ve learned and apply that in their .NET work. The lower-end developers however will rarely venture beyond the approaches that Microsoft recommends. The higher-end developers generally try to share their knowledge and experience with others, but in doing so, will waste a lot of time and effort going against the backlash they’ll get from the lower-end developers. The lower-end developers frequently accuse the higher-end developers for making things more complicated than they need to be, while they fail to realize that their initially simple solutions (as recommended by Microsoft of course) only leads to severe complications later on.
If you think about it, it’s pretty similar to the Matrix. You’ve got a small minority of people who have noticed that something isn’t quite right, took the red pill and are continuously going through hardship because of it. On the other hand, you’ve got a group of people who’d choose the blue pill to go back to a world where they’re being spoon-fed a reality that isn’t quite real by a system that only wants to keep them in check so they remain in control.
It’s just not easy to be a .NET developer who values Continuous Improvement. If you’re not wasting time working with people who are quite content with Fisher Price Development, you’re likely working for people who’re telling you to use some of the Fisher Price Building Blocks because “It’s Fisher Price! You can’t go wrong with that!”. I’ve been in both situations in the past and it just drains so much energy from you. If you’re in neither situation, you are in a very small minority.
The Road AheadSo what exactly does the future of the .NET platform look like? Obviously, nobody knows. I’ll tell you what i expect to happen though. I found it extremely telling that Microsoft is capable of putting resources on products like WebMatrix and LightSwitch (both of which are targeting the very-very-lower-end developers, or even non-developers) while at the same time, they are severely cutting back the resources for projects like IronRuby, IronPython and the DLR (which drew more interest from the higher-end developers than the lower-end developers). So what exactly does that tell us? I can only consider that to be a very clear message that the lower-end developers will always be the primary target of Microsoft, and that they really care less and less about the higher-end developers. When it comes to guidance and tooling, they are continuously displaying that they either just don’t get it, or that they just don’t care.
So where does that lead us? I think we’re only going to get more and more low-quality software projects being developed in .NET due to the increased and continuous focus on the lower-end developers and the ever decreasing focus on keeping higher-end developers happy. A lot of the higher-end developers will simply move to other platforms and communities. Communities where sharing of knowledge and experience is encouraged, instead of hampered. Communities where best practices are based on real world experience instead of being concocted in a few ivory towers by people who’ve been detached from real world projects for far too long. Communities where there is less low-quality crap that needs continuous maintenance. Communities where there is no One Ring To Rule Them All.
Soon after i introduced Agatha’s server-side caching, people started asking for client-side caching as well. There are indeed quite a few scenarios where it makes sense to cache the response of a service call on the client instead of merely doing it on the server. After all, what kind of service call can be faster than one you don’t have to make? It’s finally been added to the trunk, and it will be available in the upcoming 1.2 release. So for those of you want to use it but are still on 1.1, you can safely upgrade to the current trunk.
Usage of the client-side caching is practically identical to usage of the server-side caching feature, which means you have to use the EnableClientResponseCaching attribute on your request types where you want to use caching, and they have to implement the Equals and GetHashCode methods properly (read this post for more info on this).
Here’s a small example from the Sample that is included in the Agatha source code:
[EnableServiceResponseCaching(Minutes = 5)]
[EnableClientResponseCaching(Seconds = 30)]
public class ReverseStringRequest : Request
{
public string StringToReverse { get; set; }
public bool Equals(ReverseStringRequest other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.StringToReverse, StringToReverse);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(ReverseStringRequest)) return false;
return Equals((ReverseStringRequest)obj);
}
public override int GetHashCode()
{
return (StringToReverse != null ? StringToReverse.GetHashCode() : 0);
}
}
In this case, both the EnableServiceResponseCaching and EnableClientResponseCaching attributes were used, which means that responses for this request will be cached for 5 minutes on the server, and for 30 seconds on the client. You don’t have to use both attributes simultaneously, you can use either one of them as well depending on where you want to cache the response. You can also set a region (like you can with the server-side caching) so you can explicitely clean a certain region of the cache if you need to at some point.
Everything happens transparently from your code. If you make a service call with one request, and there is a cached response available for that request, the service call is not made and you’ll get the cached response. If you send a batch of requests, and there are cached responses available for any of those requests, the call that is sent to the service will only include the requests for which no cached response was available.