Sergio and the sigil

Language Envy - String Interpolation

Posted by Sergio on 2009-01-17
Language Envy: This post is part of a series where I wish C# had a particular feature I came to like when working with other programming languages.

Every time I have to produce a string in C# the little groaning chimp that lives inside my head pulls his hair out. It's about time we had a better way of doing this.

We all use string.Format to make these string concatenations more readable, but it's still too easy to get the order wrong or miss one of the argument values and get an exception. JetBrain's Resharper can be helpful here, giving hints when you have too many or too few arguments in a call to string.Format.

So what am I whining about?

When you need to create a string that mixes literals with variables in PHP (or Ruby, or Boo, or Perl, etc) it's so much easier to type, read and maintain than in C#:

<?php
	$price = 12.34;
	$product = "DVD Media";
	echo "$product costs $price";
	//ouputs: DVD Media costs 12.34
?>

Although this would be enough to get a lot done, the interpolation syntax can help with more complicated expressions beyond simple variables:

<?php
	$order = $user->getLastOrder();
	echo "The first item in the order was {$order->item[0]}.";
	//ouputs: The first item in the order was DVD Media.
?>

One interesting thing to note is that this is a syntax for combining expression values and literals. The interpolation isn't evaluated in strings that already exist and are passed in (like some user input.) In other words, the interpolation happens at parsing time, where the string is declared. The parser will not look into an existing string and replace tokens that look like variables — at least not without you explicitly asking it to do so.

In PHP the interpolation goes a little further. Just for the sake of curiosity, check this out.

<?php
	$var1 = 1000;
	$name = 'var1';
	//recursive interpolation:
	echo "The value of the variable named $name is {${$name}}";
	//outputs: This is the value of the var named var1 is 1000 
?>

Wouldn't it be nice to have such syntax in C#? The string would probably need to be taken care of at compile time, so a statement like this:

//DOESN'T WORK YET. JUST A DAYDREAM
var text = "The price of a ${product.Name} is ${product.Price}.";

At compile time would be treated as if it had been written as follows.

var text = "The price of a " + product.Name + 
           " is " + product.Price + ".";
// OR ...
var text = string.Concat("The price of a ", product.Name, 
           " is ", product.Price, ".");

Done like the example above this would be a backwards compatibility problem. I'm sure it's possible to put some symbol before the opening double quote to make this compatible.

Gamers Need Not Apply

Posted by Sergio on 2009-01-08

Recently I came across this forum message where the author describes a conversation he had in Australia with a recruiter who, at some point, said that:

"employers specifically instruct him not to send them World of Warcraft players. He said there is a belief that WoW players cannot give 100% because their focus is elsewhere, their sleeping patterns are often not great, etc."
"He has been specifically asked to avoid WoW players."

This post is not about gaming. I'm not a gamer (just so you know, wink, wink) and I'm not going to attempt to get into behavioral patterns or stereotypes of gamers. I want to understand the rationale behind a request like the quoted one. Replace gamer with audiophile, or sports fanatic, or someone that is too deeply consumed with other activities (e.g. parenting, church, small business on the side, etc) and you get the same issue.

No one needs to be as passionate as you

As much as we would like everyone to be as passionate as we are for our job (I'm assuming you are,) that doesn't represent the real situation in the vast majority of the workplaces.

For many people, arguably most of them, what they do from 9 to 5 is just their job. When they get home, they shut off or, more likely, the better part of their day starts.

I have even talked about Wally before, which represents a much more deteriorated stage.

The following quote from a message posted by Charlie Poole pretty much summarizes how I try to deal with this situation and how to recognize brightness and passion even in someone that doesn't share the same thirst I have, 24h a day.

...
[Kurt]: To me the separation seems to between .net programmers of the type that wouldn't consider letting their job interfere with their leisure time by reading development books and blogs, and taking part in mailing lists and user groups, or programming at home, and those that do who are also likely to follow most alt.net principles and practices (even if they haven't heard of alt.net)
[Charlie]: I used to make that separation. Well, I still do, but without the implied value judgement. IMO, folks have a right to a life outside of the development world and the vast majority of professional programmers don't live and breathe it the way some of us do. Those folks need to be reached as well.

I did a gig a while back with a bunch of mainframe COBOL guys, helping to re-invent agile techniques for their environment. Most of them had families and wanted to go home to them at the end of the day. But during the day, they wanted to learn new things and do the best job possible. I respect their choice - maybe it makes more sense than it does for me to be typing this note in the wee hours of the morning. :-) I think there is room for folks like that - there as to be, since they seem to be the majority. We just have to figure out how to reach them.
...

But it is still your job

Everything has a healthy limit, even gaming.

At the end of the day, you're (hopefully) still earning your pay for the job you perform. If these other activities start taking their toll on your focus and stamina to get your work done, it's a sign you need to exercise some moderation or find a job that allows you keep them or, better yet, make them your job.

Everything has a healthy limit, even the passion for your job.

Moderation applies here too. I'm in a constant struggle to manage my time responsibly. Even if the activities are (somewhat) job-related, many times they are not appropriate during billable time.

Some examples of things I avoid or moderate during work hours — and leave them for before or after work:

  • Twitter - a huge attention whore. I try not to have it on during the day or at least disable the pop-up and minimize it, checking it only when I have or need a break.
  • IM - mine is usually very quiet. I use the busy status when needed
  • Reading tech blogs or news - a few before work. If they pile up I'll catch up at night
  • Writing a blog post - any blog post worth reading takes time to be written. This is my blog, so I'll have to use my time feed it.
  • Mailing lists - I don't actually spend too much time on these. I only monitor a handful of them and only one is fairly active. I check new topics once or twice a day. Only read if sounds interesting.

So, can we hire gamers?

Although I can understand the rationale behind not hiring someone that has an extreme, obsessive compulsion for playing video games, which could prevent him/her from performing the job, I could never agree with the implied blanket statement that all gamers will become bad employees and should be avoided. Again, replace gamers with...

Chicago ALT.NET Plans for 2009

Posted by Sergio on 2009-01-07
UPDATE: We had to cancel this meeting because of the heavy snowfall forecast.

Due to scheduling problems we had to delay this announcement more than we would like to. But we will still have our monthly meeting on Wednesday, January 14th.

Planning for 2009

6:00 pm
Pizza and networking time

6:30 pm
We had a guest speaker for this month's meeting but unfortunately we had to change plans at the last minute.

Instead of that we will use the opportunity to do some group housekeeping.

  • What worked well and what didn't in 2008
  • What direction should we take with our group
  • Viability of our group organizing a CodeCamp soon
  • Global ALT.NET participation: as suggested in this message

If you want to help define our meetings format and group actions, then come and help us in this discussion.

7:45 pm
We have skipped the open discussion portion of our meetings last couple of times. This time, after we cover the items in the agenda, let's make sure we reserve some time for this activity.

There's a chance we have someone from Red Point lead a discussion about Agile development.

We'll update this description if we receive confirmation or not of the Agile discussion.

Language Envy - hash literals

Posted by Sergio on 2009-01-05
Language Envy: This post is part of a series where I wish C# had a particular feature I came to like when working with other programming languages.

It's easy to let a small language feature go unnoticed. The more I spend time writing JavaScript and Ruby, the more one little detail shows itself loud and clear when I go back to my trusty C# (well, it shows itself by not being absent, if that makes any sense.)

The little language detail I'm writing about today is the literal syntax for hashes. Especially in JavaScript, because all objects are just hashes on steroids, which makes the literal object syntax become one and the same with the hash literals.

In JavaScript it's easy as 1-2-3. It's not surprising so many libraries are adopting hash parameters.

//Prototype.js sample
var elements = { success: 'myDiv', failure: 'errorDiv' };
var ajax = new Ajax.Updater(
	elements, 
	'getData.aspx', 
	{ method: 'get', onFailure: reportError }
	);
//jQuery sample (jQuery UI)
$('#fromDate').datepicker({rangeSelect: true, firstDay: 1});
$("#search").autocomplete("/product/find",
	{ autoFill: true, delay: 10, minChars: 3 }
	);

Now, I understand that part of the popularity of hashes in JavaScript and Ruby is due to the loose typing of these languages. But if the syntax wasn't light, APIs like the above ones would be much more painful to use.

C# 3 does have a hash syntax (or, more accurately, a dictionary one.) Unfortunately, dictionary initializers, although being a step forward, still leave noise to be removed.

// hypothetical search API 
var books = FindWithCriteria<Product>(
              new Dictionary<string,object>
              {
                {"Category", Category.Books},
                {"MinPrice", 33.45},
                {"MaxPrice", 50.00},
                {"Contains", "asp.net"}
              });

Hmmm, no, thanks. Maybe that's the reason we are starting to see some APIs that use (abuse?) anonymous objects and reflection to create hashes.

// hypothetical search API 
var books = FindWithCriteria<Product>(
              new { 
                Category = Category.Books,  
                MinPrice = 33.45,
                MaxPrice = 50.00, 
                Contains = "asp.net" 
              });

This last one doesn't look so bad on the surface, but we know what is going on under the covers so it's like putting lipstick on a pig. If, instead of using reflection at run-time, the compiler had support for converting the above anonymous object into a IDictionary<string,object>, then we would have a more convenient and efficient way of creating hashes. Maybe it's too late to introduce a feature like that while maintaining backwards compatibility.

I believe when you add a language feature that is elegantly designed (i.e. clean and unnoticeable,) it becomes popular more quickly — just like what is happening with lambdas . The existing alternatives for creating hashes in C# 3 are still too noisy or inefficient to be integrated in our code without reducing the readability or incurring a performance penalty.

Playing with Ruby 1.9 - named parameters (sort of)

Posted by Sergio on 2008-12-31

I just installed Ruby 1.9.1 RC1 alongside my stable 1.8.6 installation. I'm planning to experiment with the changes and new language features for both using them in new code and upgrade old code (or at least protect old code from potential breaking changes.)

In light of the upcoming changes in C# 4, more specifically the addition of named and optional parameters, one of the new Ruby 1.9 features called my attention immediately.

Ruby, even 1.9, doesn't support named parameters in method calls. Instead, a common pattern is to provide a Hash parameter and call it something like options. Any optional argument is passed as an item of this hash, normally using a Symbol for the key. It helps that Ruby has special support for hash arguments, making the call look much cleaner:

def my_method(arg1, arg2, options)
  opt1 = options[:option1] || "default value for opt1"
  opt2 = options[:option2] || "default value for opt2"
  # ... etc ...
end

#calling the method:
my_method(val1, val2, { :option2 => "opt val 2", :something => "whatever"})
# simplified syntax
my_method(val1, val2, :option2 => "opt val 2", :something => "whatever")

In a way this is the poor man's version of named parameters, but it seems to do the job.

This is a very popular Ruby idiom (you can see that a lot in JavaScript as well,) so truly popular that the syntax was further simplified in 1.9. We can now ditch the arrow thingy and write the same exact code as follows:

#calling the method:
my_method(val1, val2, { option2: "opt val 2", something: "whatever"} )
# simplified syntax
my_method(val1, val2, option2: "opt val 2", something: "whatever")

The first syntax is identical to what you'd use in JavaScript. The second one is the same of named parameters in C# 4. I thought this was a welcome coincidence. See the C# 4 version below.

//NOTE: C# 4 code
void my_method(string arg1, string arg2, 
      string option1 = "default 1", string option2 = "default 2",
      string something = "")
{
  // ... method body here ...
}

//calling the method:
my_method(val1, val2, option2: "opt val 2", something: "whatever");