Slides and Code Samples from my Talk at LIDNUG - What?!? C# Could Do That???

On Thursday I had the honor to do a virtual talk at LIDNUG – the LinkedIn .NET User Group. A stage where lots of .NET celebs like Scott Gu, Jeffery Richter, Jeff Prosise and others have talked in the past.

I’d like to thank all the attendees and the LIDNUG crew who made this possible – Inbar, Peter and Brian – you guys rock!

About the talk – I focused on the dynamic capabilities of C#. Started with some black magic done using the dynamic keyword, then moved on to practice witchcraft with the combination of IronRuby and C#, and ended with the new and shiny .NET spell-book also known as project “Roslyn”.

The talk was recorded and it can be found on YouTube:

The code samples from the talk are also available – click here to download them [2.47Mb].

I had a blast, hope you did as a well.
All the best,
Shay.




My Leading Candidate for Worst C# Feature – Method Hiding

I love C#, I really do. Of course is has its little annoying quirks here and there, but in general it is, IMHO, one of the best static programming languages out there. Having said that, one thing that makes me wonder “WHAT THE HELL WERE THEY THINKNING?!?$?!?” every single time is the feature known as “Method Hiding”.

What is Method Hiding?

Method hiding, in short, is the crippled, mentally-ill brother of method overriding. For example, look at the next code:

class A
{
  public string GetName()
  {
    return "A"; 
  }
}

class B : A
{
  public new string GetName()
  {
    return "B";
  }
}

Class A has a GetName method; class B inherits from class A and implements the GetName method as well. 
Look carefully at the GetName method signature in class B – do you see the new keyword there? this means that the method doesn’t override the implementation in class A, it just hides it. What does that mean? read on.

So What’s the Big Deal? Hide, Override… Who Cares?

There is a huge difference in the behavior of method hiding and overriding. Look at the next two samples:

Method hiding vs. Method overriding

The left part is a method hiding example, and the right part is a method overriding example. Now let’s go through the use cases.

First – using the father classes:

FatherHidden fh = new FatherHidden();
fh.GetName(); // = "A"

FatherVirtual fv = new FatherVirtual();
fv.GetName(); // = "A"

Both are available and return the same result. Good.

Second – using the son classes:

SonHiding sh = new SonHiding();
sh.GetName(); // = "B"

SonOverriding so = new SonOverriding();
so.GetName(); // = "B"

Again, both methods return the expected result. Swell!

Third – using polymorphism – storing an instance of the son classes in a father class variable and calling the GetName method:

FatherHidden fh = new SonHiding();
fh.GetName(); // = "A"

FatherVirtual fv = new SonOverriding();
fv.GetName(); // = "B"

See that? the hidden method (FatherHidden.GetName) had suddenly woken up, took over and returned “A” instead of the expected “B”! kicking polymorphism out the door while doing it!

Is It a Problem?

Yes, it is. I’ve never found any reason to use method hiding and I can’t think of a good reason start using it in the future. OOP is great and I can’t understand why we need ways to screw it up. In my opinion, if you get to a situation where you need to use method hiding, re-think your design and start over.

This is not just a cute code smell. It can lead to nasty bugs along the way. For instance, I came across something like the next piece of code when doing a code-review lately:

class Base
{
  public bool IsAuthenticated { get { return false; } }
}
class SomeAuthClass : Base
{
  public new bool IsAuthenticated { get { return CheckAuthentication(); } }
}

Now, as long as they use SomeAuthClass variable types on their system, everything will work fine. But once a developer comes and wants to use some OOP magic, all users will immediately become unauthenticated. And this is no fun. No fun at all.

One of my major problems with method hiding is that it is C#’s default behavior – you don’t even need to write the new keyword. And even if the method on the base class is marked as virtual, and you forget to mark the method on the inheriting class with override – you fall back to method hiding…

#sadpanda

What I Am Suggesting

I know this feature isn’t going to disappear. Ever. I’m sure some people have found a reason to use it like there’s no tomorrow and Microsoft is one of the best in keeping their products backwards-compatible.

However, I would like:

  • To get a compilation error if a method is going to hide another method and is not marked with the new keyword.
  • To make the method hiding feature obsolete (yes, obsolete!) and get a compilation warning when using this feature in future versions of the framework.
  • You to stop using method hiding.
  • Everyone to recycle more and save the planet!

All the best,
Shay.

kick it on DotNetKicks.com Shout it




Please Use TryParse and Avoid Parse+Try/Catch

Recently I’ve run into a piece of class which was operating as the central place for type conversions in the system. While the idea of having such a class doesn’t sound like a problem, the way it’s been implemented definitely is.

Most of the conversion methods looked something like that:

public int ToInt(string value)
{
  try
  {
    return Int32.Parse(value);
  }
  catch
  {
    return DefaultValue;				
  }
}

I took this method for a test drive – I executed it within a loop and put a stopwatch before and after. The next chart demonstrates the results (X=number of loop iterations, Y = execution time in milliseconds):

Parse with try/catch execution time chart

100,000 calls to this ToInt method takes about 10 seconds!

This implementation would have been acceptable if there were no other solution for doing this stuff. But there is ALWAYS another way! and this time this way has a name – TryParse.

TryParse will achieve the same result like Parse but with one major difference – it will not raise an exception once the conversion is unsuccessful but instead it will return false. Changing the ToInt method implementation is quite easy:

public int ToInt2(string value)
{
  int result;
  if (!Int32.TryParse(value, out result))
  {
    return DefaultValue;
  }
  return result;
}

And now, when I re-run the test drive code I got blown away by the results – look at that chart:

TryParse execution time chart

The time for 100,000 conversions dropped from ~10 seconds to ~20 milliseconds! that is about 500% faster!!!

This is the joined chart, which makes the results crystal clear:

Joined results: TryParse vs Parse+try/catch

Conclusion

There is a single conclusion to this post: avoid using Parse+try/catch and start using TryParse. As simple as that.

All the best,
Shay.

kick it on DotNetKicks.com Shout it




Forget 42, –1 is My New Answer to Life

I’ve just stumbled upon the next code statement – Thread.Sleep(-1). It left me wondering what was happening there since MSDN tells you nothing about a –1 value for the milliseconds parameter:

“The number of milliseconds for which the thread is blocked. Specify zero (0) to indicate that this thread should be suspended to allow other waiting threads to execute. Specify Infinite to block the thread indefinitely.“ – System.Threading.Thread.Sleep, MSDN

To check that out, I opened the IronRuby interactive console and filled in System::Threading::Thread.Sleep(-1) and hit Enter just to find out that this call blocks the thread indefinitely. Could it be? –1 is Infinite?

Reflector to our aid! oh wait, RedGate now charges money for it and had planted a time bomb inside the free version which made it stop working. grrrr
ILSpy to our aid! (I highly recommend ILSpy as a Reflector alternative… very similar, free, oss… great community effort!)

Anyway, ILSpy proved my concerns:

System.Threading.Timeout.Infinite Value

So… –1 actually represents Infinity (when it comes to threading in .NET). And Infinity is much cooler than 42, hence –1 is the new answer to life.
Q.E.D.

All the best,
Shay.




LINQ Tip: Chain Ordering

Assuming you have the next code:

public class Person
{
  public string Name { get; set; }
  public int Age { get; set; }
}

public class Whatever
{
  public void Do()
  {
    var people = new List<Person>
                  {
                     new Person {Name = "Shay Friedman", Age = 27},
                     new Person {Name = "Shawn Doe", Age = 51},
                     new Person {Name = "Elvis Presley", Age = 76}
                  };            
  }
}

And now you want to order it first by name and then by age using LINQ. If you were to do that:

var orderedPeople = people.OrderBy(p => p.Name).OrderBy(p => p.Age);

You would get incorrect results:

LINQ Tip: Results when using OrderBy after an OrderBy call.

That’s because the second OrderBy call just overrides the first call results. To fix that, use the ThenBy LINQ method:

var orderedPeople = people.OrderBy(p => p.Name).ThenBy(p => p.Age);

And now everything works as expected:

LINQ Tip: Using ThenBy after an OrderBy call.

All the best,
Shay.




return a = “hello”; What will Happen?

I came across an interesting piece of code the other day, something I didn’t even know possible in C#.

Consider the next code (which doesn’t make lots of sense, but it gets the point across):

public string Test()
{
  string a;
  return a = "hello";
}

What do you think will happen? what will be returned from this method?


……
………….
………………

So?


……
………….
………………

The answer is that this method will return “hello”.

Why did it happen?

When thinking more about it, this behavior is expected. It becomes very clear when reading about the assignment (=) operator on MSDN:

"The assignment operator (=) stores the value of its right-hand operand in the storage location, property, or indexer denoted by its left-hand operand and returns the value as its result."

To make things even simpler, think about the syntax of multiple assignments in one line – b = a = “hello”; – this is exactly the same. In the sample above I just return the value instead of assigning it to the variable b.

All the best,
Shay.

kick it on DotNetKicks.com Shout it



A Mini-Review-Benchmark of Ruby’s Different Testing Frameworks

On of the most shining features of the Ruby language for .NET developers is, in my opinion, its testing frameworks. Ruby has got such amazing testing frameworks that it is such a shame that people still use other languages to test code.

The goal of this post is simple – to show you how to test a given code in various different frameworks, so you can choose the one for you. In the meanwhile I will also take the amount of time taken for each framework to run the tests and compare the times at the end.

For that I’m using my Ruby implementation of choice – IronRuby RC4 (1.8.6 compatible) and my powerful computer (running Windows 7 64-bit). Each testing framework will contain the same 7 tests of the tested code and be executed from the command line.

Note: The testing frameworks I bring in this post are my own random picks. I tried to bring the popular ones and some other small but interesting ones. There are more testing frameworks in Ruby and if you think I should add another ones, let me know and I’ll add them to the list too.

The Tested Code

The code I’m going to test is a C# code (IronRuby FTW!) which resides in an assembly named WaterHelper.dll. The code is as follows:

namespace Demo
{
    public class WaterHelper
    {                
        public bool IsWaterBoiled(decimal celsius)
        {
            return celsius >= 100;
        }

        public bool IsWaterFrozen(decimal celsius)
        {
            return celsius <= 0;
        }

        public string GetWaterStatus(decimal celsius)
        {
            if (IsWaterBoiled(celsius))
            {
                return "Steam";
            }
            else if (IsWaterFrozen(celsius))
            {
                return "Ice";
            }
            return "Liquid";
        }
    }
}

Not much of complication here – three methods that do some water temperature related calculation.

Test::Unit

Official site: http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/classes/Test/Unit.html

The first testing framework I’m using is Ruby’s built-in one – Test::Unit. It is very similar to NUnit (in .NET) or JUnit (in Java).

The Test::Unit test code which tests the WaterHelper class is as follows:

require 'test/unit'
require "WaterHelper.dll"

class TC_WaterHelper < Test::Unit::TestCase
  def setup
    @instance = Demo::WaterHelper.new
  end
  
  def test_water_boiling_point
    result = @instance.is_water_boiled(100)
    assert_equal true, result
  end
  def test_water_is_boiled
    result = @instance.is_water_boiled(150)
    assert_equal true, result
  end
  
  def test_water_freezing_point
    result = @instance.is_water_frozen(0)
    assert_equal true, result
  end
  def test_water_frozen
    result = @instance.is_water_frozen(-50)
    assert_equal true, result
  end
  
  def test_water_status_steam
    result = @instance.get_water_status(300)
    assert_equal "Steam", result
  end  
  def test_water_status_liquid
    result = @instance.get_water_status(70)
    assert_equal "Liquid", result
  end
  def test_water_status_Ice
    result = @instance.get_water_status(-5)
    assert_equal "Ice", result
  end
end

Execution time: 0.082005 seconds.

RSpec

Official site: http://rspec.info/
Version: 1.3.0

By following BDD principles and providing a clean and elegant DSL (Domain Specific language), RSpec has gained a lot of fans. It is maybe the most popular testing framework in the Ruby world currently.

The code to test the WaterHelper.dll with RSpec is as follows:

require "rubygems"
require "spec"
require "spec/autorun"
require "WaterHelper.dll"

describe "Testing WaterHelper class" do
  before(:each) do
    @instance = Demo::WaterHelper.new
  end
  
  it "should be boiling water when it is 100 degrees" do
    result = @instance.is_water_boiled(100)
    result.should be_true
  end  
  it "should be boiling water when it is 150 degrees" do
    result = @instance.is_water_boiled(150)
    result.should be_true
  end
  
  it "should be frozen water when it is 0 degrees" do
    result = @instance.is_water_frozen(0)
    result.should be_true
  end
  it "should be frozen water when it is -50 degrees" do
    result = @instance.is_water_frozen(-50)
    result.should be_true
  end
  
  it "returns Steam for 300 degress" do
    result = @instance.get_water_status(300)
    result.should == "Steam"
  end
  it "returns Liquid for 70 degress" do
    result = @instance.get_water_status(70)
    result.should == "Liquid"
  end
  it "returns Ice for -5 degress" do
    result = @instance.get_water_status(-5)
    result.should == "Ice"
  end
end

Execution time: 0.201012 seconds.

Cucumber

Official site: http://cukes.info/
Version: 0.6.4

Cucumber is one of the most innovative frameworks out there. It took BDD one step further by providing a simple way to write requirement documents in a language called Gherkin (which is plain English with a few rules) and interpret them via code.

The next Gherkin code contains the requirements for the WaterHelper class:

Feature: WaterHelper
  As all users
  I want to know the status of the water
  To know how to treat it
  
  Scenario: Water are boiled at 100 degrees
    Given the temperature is 100 degrees
    When I check whether the water is boiled
    Then I should find out that it is
    
  Scenario: Water are boiled at 150 degrees
    Given the temperature is 150 degrees
    When I check whether the water is boiled
    Then I should find out that it is
    
  Scenario: Water are frozen at 0 degrees
    Given the temperature is 0 degrees
    When I check whether the water is frozen
    Then I should find out that it is
    
  Scenario: Water are frozen at -50 degrees
    Given the temperature is -50 degrees
    When I check whether the water is frozen
    Then I should find out that it is
    
  Scenario Outline: Water status
    Given the temperature is <temperature> degrees
    When I check the water status
    Then I should find out it is "<status>"
    
    Examples:
      | temperature | status |
      |     300     | Steam  |
      |     70      | Liquid |
      |     -5      |  Ice   |

And this is the Ruby code file to interpret the requirements:

require "WaterHelper.dll"

Before do
  @instance = Demo::WaterHelper.new
end

Given /the temperature is (.*) degrees/ do |temperature|
  @temperature = temperature.to_f
end

When /I check whether the water is boiled/ do
  @result = @instance.is_water_boiled(@temperature)
end
When /I check whether the water is frozen/ do
  @result = @instance.is_water_frozen(@temperature)
end
When /I check the water status/ do
  @result = @instance.get_water_status(@temperature)
end

Then /I should find out that it is/ do
  @result.should == true
end
Then /I should find out it is "(.*)"/ do |status|
  @result.should == status
end

Execution time: 0.883 seconds.

Shoulda

Official site: http://github.com/thoughtbot/shoulda
Version: 2.10.3
Modification: there is currently a bug in IronRuby which prevents Shoulda from running. I altered the IronRuby code to make it work and I’m in contact with the IronRuby team about the problem.

Shoulda is another popular testing framework. It is built on top of the Test::Unit testing framework and it makes it more developer-friendly.

The test code is as follows:

require 'rubygems'
require 'shoulda'
require "WaterHelper.dll"

class WaterHelperTest < Test::Unit::TestCase
  context "WaterHelper" do
    setup do
      @instance = Demo::WaterHelper.new
    end
    
    should "be boiling water when it is 100 degrees" do
      result = @instance.is_water_boiled(100)
      assert_equal true, result
    end
    should "be boiling water when it is 150 degrees" do
      result = @instance.is_water_boiled(150)
      assert_equal true, result
    end
    should "be frozen water when it is 0 degrees" do
      result = @instance.is_water_frozen(0)
      assert_equal true, result
    end
    should "be frozen water when it is -50 degrees" do
      result = @instance.is_water_frozen(-50)
      assert_equal true, result
    end
    should "return Steam for 300 degress" do
      result = @instance.get_water_status(300)
      assert_equal "Steam", result
    end
    should "return Liquid for 70 degress" do
      result = @instance.get_water_status(70)
      assert_equal "Liquid", result
    end
    should "return Ice for -5 degress" do
      result = @instance.get_water_status(-5)
      assert_equal "Ice", result
    end
  end
end

Execution time: 0.096005

riot

Official site: http://github.com/thumblemonks/riot
Version: 0.10.13
Modification: changed code to use iron-term-ansicolor (IronRuby’s equivalent to term/ansicolor)

The riot testing framework is a cute little thing. Its main goal is to make it quicker to write tests and to execute them. The code turns out very minimalistic, which makes this framework a good choice when you need to write some quick unit tests.

The next code contains the unit tests for the WaterHelper class written with the riot framework:

require "rubygems"
require "riot"
require "WaterHelper.dll"

context "Tests WaterHelper class" do
  setup {  Demo::WaterHelper.new }  
  
  asserts("the water is boiling when it is 100 degrees") {  topic.is_water_boiled(100) }    
  asserts("the water is boiling when it is 150 degrees") {  topic.is_water_boiled(150) }    
  asserts("the water is frozen when it is 0 degrees") {  topic.is_water_frozen(0) }    
  asserts("the water is frozen when it is -50 degrees") {  topic.is_water_frozen(-50) }
  asserts("you get steam when it is 300 degress") { topic.get_water_status(300) == "Steam" }
  asserts("you get liquid when it is 70 degress") { topic.get_water_status(70) == "Liquid" }
  asserts("you get ice when it is -5 degress") { topic.get_water_status(-5) == "Ice" }
end

Execution time: 0.083005 seconds.

Protest

Official site: http://rubyprotest.org/
Version: 0.3

Protest is another small and fun testing framework. It is described as a “small, simple and easy-to-extend testing framework” on its web site. It keeps it promise, I tell ya!

The next code tests the WaterHelper class using the Protest framework:

require "rubygems"
require "protest"
require "WaterHelper.dll"

Protest.context "WaterHelper class" do
  setup do
    @instance = Demo::WaterHelper.new
  end
  
  test "should be boiling water when it is 100 degrees" do
    result = @instance.is_water_boiled(100)
    assert result == true
  end
  test "should be boiling water when it is 150 degrees" do
    result = @instance.is_water_boiled(150)
    assert result == true
  end
  test "should be frozen water when it is 0 degrees" do
    result = @instance.is_water_frozen(0)
    assert result == true
  end
  test "should be frozen water when it is -50 degrees" do
    result = @instance.is_water_frozen(-50)
    assert result == true
  end
  test "returns Steam for 300 degress" do
    result = @instance.get_water_status(300)
    assert result == "Steam"
  end
  test "returns Liquid for 70 degress" do
    result = @instance.get_water_status(70)
    assert result == "Liquid"
  end
  test "returns Ice for -5 degress" do
    result = @instance.get_water_status(-5)
    assert result == "Ice"
  end
end

Execution time: 0.164009 seconds.

Stories

Official site: http://github.com/citrusbyte/stories
Version: 0.1.3

The Stories testing framework is built on top of Test::Unit and provides an entire different syntax for it. It has a convenient DSL for writing tests as “stories”.

The next code tests the WaterHelper class using the Stories framework:

require "rubygems"
require "stories"
require "WaterHelper.dll"

class WaterHelperClass < Test::Unit::TestCase
  story "As a user I want to know the status of the water" do
    setup do
      @instance = Demo::WaterHelper.new
    end
    scenario "Given 100 degrees, the water should be boiled" do
      result = @instance.is_water_boiled(100)
      assert_equal true, result
    end
    scenario "Given 150 degress, the water should be boiled" do
      result = @instance.is_water_boiled(150)
      assert_equal true, result
    end
    scenario "Given 0 degress, the water should be frozen" do
      result = @instance.is_water_frozen(0)
      assert_equal true, result
    end
    scenario "Given -50 degress, the water should be frozen" do
      result = @instance.is_water_frozen(-50)
      assert_equal true, result
    end
    scenario "On 300 degrees, water status should be steam" do
      result = @instance.get_water_status(300)
      assert_equal "Steam", result
    end
    scenario "On 70 degrees, water status should be liquid" do
      result = @instance.get_water_status(70)
      assert_equal "Liquid", result
    end
    scenario "On -5 degrees, water status should be ice" do
      result = @instance.get_water_status(-5)
      assert_equal "Ice", result
    end
  end
end

Execution time: 0.118007 seconds.

Lemon

Official site: http://proutils.github.com/lemon/
Version: 10.03.06

Lemon is an interesting unit testing framework. It provides a DSL which makes it very clear to identify which class and method you are testing. Moreover, it has code coverage capabilities which can report you which methods are not covered by your code. It is dependant on a bunch of other gems which makes it a bit slower than other frameworks.

The next code tests the WaterHelper class using the Lemon framework:

require "WaterHelper.dll"

TestCase Demo::WaterHelper do
  Concern "Water statuses are returned as expected."

  Before { @instance = Demo::WaterHelper.new }

  Unit :is_water_boiled => "returns true for 100 degress" do
    result = @instance.is_water_boiled(100)
    result.assert == true
  end
  Unit :is_water_boiled => "returns true for 150 degress" do
    result = @instance.is_water_boiled(150)
    result.assert == true
  end
  
  Unit :is_water_frozen => "returns true for 0 degress" do
    result = @instance.is_water_frozen(0)
    result.assert == true
  end
  Unit :is_water_frozen => "returns true for -50 degress" do
    result = @instance.is_water_frozen(-50)
    result.assert == true
  end
  
  Unit :get_water_status => "returns Steam for 300 degress" do
    result = @instance.get_water_status(300)
    result.assert == "Steam"
  end
  Unit :get_water_status => "returns Liquid for 70 degress" do
    result = @instance.get_water_status(70)
    result.assert == "Liquid"
  end
  Unit :get_water_status => "returns Ice for -5 degress" do
    result = @instance.get_water_status(-5)
    result.assert == "Ice"
  end
end

Execution time: 1.204097 seconds.

bacon

Official site: http://rubyforge.org/projects/test-spec
Version: 1.1

bacon is a small RSpec clone which is written in 300 lines of code. Its syntax is very similar to RSpec with a small difference on the expectation method (should).

The next code tests the WaterHelper class with the bacon framework:

require "rubygems"
require "bacon"
require "WaterHelper.dll"

describe "Testing WaterHelper class" do
  before do
    @instance = Demo::WaterHelper.new
  end
  
  it "should be boiling water when it is 100 degrees" do
    result = @instance.is_water_boiled(100)
    result.should.be.true
  end
  it "should be boiling water when it is 150 degrees" do
    result = @instance.is_water_boiled(150)
    result.should.be.true
  end  
  it "should be frozen water when it is 0 degrees" do
    result = @instance.is_water_frozen(0)
    result.should.be.true
  end
  it "should be frozen water when it is -50 degrees" do
    result = @instance.is_water_frozen(-50)
    result.should.be.true
  end
  
  it "returns Steam for 300 degress" do
    result = @instance.get_water_status(300)
    result.should.equal "Steam"
  end
  it "returns Liquid for 70 degress" do
    result = @instance.get_water_status(70)
    result.should.equal "Liquid"
  end
  it "returns Ice for -5 degress" do
    result = @instance.get_water_status(-5)
    result.should.equal "Ice"
  end  
end

Execution time: 0.120007 seconds.

Contest

Official site: http://rdoc.info/projects/citrusbyte/contest and http://github.com/citrusbyte/contest
Version: 0.1.2

Contest’s target is to bring contexts to Test::Unit. Its syntax is similar to Shoulda’s just with a different test method name (named test).

The code:

require 'rubygems'
require 'contest'
require "WaterHelper.dll"

class WaterHelperTest < Test::Unit::TestCase
  context "WaterHelper" do
    setup do
      @instance = Demo::WaterHelper.new
    end
    
    test "be boiling water when it is 100 degrees" do
      result = @instance.is_water_boiled(100)
      assert_equal true, result
    end
    test "be boiling water when it is 150 degrees" do
      result = @instance.is_water_boiled(150)
      assert_equal true, result
    end
    test "be frozen water when it is 0 degrees" do
      result = @instance.is_water_frozen(0)
      assert_equal true, result
    end
    test "be frozen water when it is -50 degrees" do
      result = @instance.is_water_frozen(-50)
      assert_equal true, result
    end
    test "return Steam for 300 degress" do
      result = @instance.get_water_status(300)
      assert_equal "Steam", result
    end
    test "return Liquid for 70 degress" do
      result = @instance.get_water_status(70)
      assert_equal "Liquid", result
    end
    test "return Ice for -5 degress" do
      result = @instance.get_water_status(-5)
      assert_equal "Ice", result
    end
  end
end

Execution time: 0.077004

Custom Testing Framework

This is a custom testing framework built in one line of code. I found it in a blog post by Paul Berry. It is not really for production purposes but it works well, it’s cool and it shows you how powerful Ruby is.

This next piece of code contains both the tests and the testing framework implementation. I surrounded everything with the Benchmark library to get the amount of time it takes to execute the tests:

require "benchmark"
require "WaterHelper.dll"

total_time = Benchmark.measure do
  tests = {
    "is_water_boiled(100)" => true,
    "is_water_boiled(150)" => true,
    "is_water_frozen(0)" => true,
    "is_water_frozen(-50)" => true,
    "get_water_status(300)" => "Steam",
    "get_water_status(70)" => "Liquid",
    "get_water_status(-5)" => "Ice"
  }

  instance = Demo::WaterHelper.new
  
  # The next line goes over all tests and executes them
  tests.each{|e,v| puts((r=eval("instance." + e))==v ? ". #{e}" : "! #{e} was '#{r}', expected '#{v}'")}
end

puts total_time

Execution time: 0.156001 seconds.

Benchmark Conclusion

Benchmarking testing frameworks is not such a good idea. Performance is not something you should care about when you write tests. It is much more important to have a maintainable set of tests instead of fast running ones that need a week of work when a requirement changes.

But, it’s cool and interesting to have charts in blog posts! so, here it is… the comparison between the execution time of all testing frameworks in this post:

Ruby's testing framework execution time comparison

It turned out that Contest is the quickest one but except Cucumber and Lemon, the rest of the frameworks are behind only by a small difference.

Interesting facts:

  • All frameworks finished the tests under 1 second.
  • Test::Unit is more than 2 times faster than RSpec.
  • Contest, which is build on top of Test::Unit, actually runs a bit faster (I tried that multiple times!)
  • The custom testing framework got a real nice spot in the middle.
  • Cucumber is not the quickest one at all but it is still the coolest one :-)

Conclusion

IronRuby opens a whole new world of opportunities for .NET developers and Rubyists. In this post I focused on testing code but of course there is much more to it than just that. However, this showcase gets my point through – this post includes a variety of 11 (!!!) different testing frameworks. Each frameworks has its own uniqueness, making it very easy for you to choose the framework that works best for you.

And just for you to know - I had so much fun writing this post! Ruby is just awesome. Period.

All the best,
Shay.

Share: DZone | RubyFlow | Reddit

Shout it kick it on DotNetKicks.com




Use .NET Built-in Methods to Save Time and Headaches

During our everyday programming tasks we run into several repetitive code blocks that after the 20th time you implement them become really annoying. The worst case is to re-implement these code blocks every time, and the better case is to create a central class library with helper classes and methods. However, a large amount of these tasks can be achieved easily with built-in .NET methods.

In this post I will go through several repetitive code blocks and show you how to implement them using built-in .NET method. If you want to add your suggestions, comment! I’ll add your suggestions to the post periodically.

Disclaimer: I’m sure some of the code blocks I use in the NOT Recommended sections can be written much better. These code blocks are here just for demonstration purposes.

Code Block #1 – Check string for nullity or emptiness

NOT Recommended

str = "something"
if (str == null || str == String.Empty)
{
	// Oh no! the string isn't valid!
}

Recommended

str = "something"
if (String.IsNullOrEmpty(str))
{
	// Oh no! the string isn't valid!
}

Code Block #2 – Check string for nullity or emptiness (spaces only string is invalid too)

NOT Recommended

str = "something"
if (str == null || str.Trim() == String.Empty)
{
	// Oh no! the string isn't valid!
}

Recommended (C# 4.0 Only)

str = "something"
if (String.IsNullOrWhiteSpace(str))
{
	// Oh no! the string isn't valid!
}

Code Block #3 – Copy an Array

NOT Recommended

string[] source = new string[] { "a", "b", "c" };
string[] dest = new string[3];
for (int i=0; i < source.Length; i++)
{
	dest[i] = source[i];
}

Recommended

string[] source = new string[] { "a", "b", "c" };
string[] dest = new string[3];
Array.Copy(surce, dest, source.Length);

Code Block #4 – Check if a char is a digit

NOT Recommended

char c = '1';
if (c == '1' || c == '2' || c == '3' ||
	c == '4' || c == '5' || c == '6' ||
	c == '7' || c == '8' || c == '9' ||
	c == '0')
{
	// It's a digit!
}

Recommended

char c = '1';
if (Char.IsDigit(c))
{
	// It's a digit!
}

Code Block #5 – Combine Paths

NOT Recommended

string folder = @"C:\MyDir";
string file = "MyFile.docx";
// Combine to make a path
string path = folder + @"\" + file;

Recommended

string folder = @"C:\MyDir";
string file = "MyFile.docx";
// Combine
string path = System.IO.Path.Combine(folder, file);

Code Block #6 – Get file extension out of a file path

NOT Recommended

string path = @"C:\MyDir\MyFile.docx";
string extension = path.Substring(path.LastIndexOf("."));

Recommended

string path = @"C:\MyDir\MyFile.docx";
string extension = System.IO.Path.GetExtension(path);

Code Block #7 – Get MyDocuments Path

NOT Recommended

// Probably some nasty stuff here

Recommended

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

Code Block #8 – Check if object is of a specific type

NOT Recommended

object obj = "str";
if (obj.GetType() == typeof(String))
{
	// It's a string!
}

Recommended

object obj = "str";
if (obj is String)
{
	// It's a string!
}

As Adrian Aisemberg has pointed out, these samples are not entirely the same. The is keyword will return true also if obj is of a derivative type of String (in this sample).

Code Block #9 – Set default enum value

NOT Recommended

public class MyClass
{
	private enum Sample 
	{
		A,
		B,
		C
	}
	static Sample s = Sample.B; // Set default value explicitly
	public static void Run()
	{	
		Console.WriteLine(s); // Prints B
	}
}

Recommended

public class MyClass
{
	private enum Sample 
	{
		A,
		B = 0, // Make B the default value
		C
	}
	static Sample s; // Default value will be used
	public static void Run()
	{	
		Console.WriteLine(s); // Prints B
	}
}

Code Block #10 – Check if a string starts with another string

NOT Recommended

string str = "Hello World";
if (str.Substring(0, 5) == "Hello")
{
	// String starts with Hello!			
}

Recommended

string str = "Hello World";
if (str.StartsWith("Hello"))
{
	// String starts with Hello!		
}

Code Block #11 – Convert list of items of one type to a list of items of a different type

NOT Recommended

List<int> list = new List<int>(new[] { 1, 2, 3, 4, 5 });
List<string> convertedList = new List<string>();
foreach (int item in list)
{
	convertedList.Add(item.ToString());
}

Recommended

List<int> list = new List<int>(new[] { 1, 2, 3, 4, 5 });
List<string> convertedList = list.ConvertAll<string>(Convert.ToString);

Code Block #12 – Check if a string contains a number and get the number

NOT Recommended

string str = "4";

int num = 0;
bool success = false;
try 
{
	num = Convert.ToInt32(str);
	success = true;
}
catch
{
	success = false;
}

if (success)
{
	// Do something with the number
}

Recommended

string str = "4";

int num = 0;
if (Int32.TryParse(str, out num))
{
	// Do something with the number
}

Code Block #13 – Writing a string to a file (courtesy of Yaron Naveh)

NOT Recommended

const string str = "put me in a file";
const string file = @"c:\logs\file.txt";

var fs = new FileStream(file, FileMode.Create);          
var sw = new StreamWriter(fs);
sw.Write(str);

sw.Close();
fs.Close();

Recommended

const string str = "put me in a file";
const string file = @"c:\logs\file.txt";

File.WriteAllText(file, str);

Code Block #14 – Pick value if not null and a different on if it is (courtesy of Abhishek)

NOT Recommended

string input = "sdfds";
string result = null;
if (input == null)
{
	result = "Input is null!";
}
else
{
	result = input;
}

Recommended

string input = "sdfds";
string result = input ?? "Input is null!";

 

This is it for now. If you have more, comment and I’ll add your suggestions to the list (with credits).

All the best,
Shay.

kick it on DotNetKicks.com Shout it



Is String.IsNullOrEmpty Good or Bad?

I started to wonder about that when I was looking for an equivalent method in Ruby. Apparently, Ruby doesn’t come with such a method built-in, but you can add it very easily by using Ruyb’s monkey patching abilities.

This is odd, because Ruby is the greatest language and has everything you possibly need (and IronRuby is even better! :) ). So why isn’t there an IsNullOrEmpty-like method? Well, they might just didn’t think it was important enough. And there might be a different answer, maybe the decision has other reasons below the surface.

Several developers have discussed the String.IsNullOrEmpty issue over the years. Some say it’s good, some say it’s bad and some even say it’s hazardous to your code (because of a bug it has).

For me, I go with Ruby’s approach (unless they didn’t add it because of time constraints). Most of the time there will be a big difference between a null string object and an empty string object. Therefore, I think that String.IsNullOrEmpty() should be avoided as much as possible and the application should have a convention of how uninitialized strings should look like – nulls or String.Empty

For example, say you need to validate some input and String.Empty is sent to you. How do you know if the string is an uninitialized string or a real input? saying that null is the convention would have solved this confusion.

I know there are cases where you have to use IsNullOrEmpty. For example, when using 3rd party components that you are not aware of their uninitialized string convention (if such exists…). This is why I don’t rule out IsNullOrEmpty entirely. I do say that wherever you can, do not use it and prefer str == null to spot uninitialized strings.

By the way, deciding that only null is the convention for uninitialized strings can also improve your application performance since str == null is faster than String.IsNullOrEmpty(str) in about 35%. However, you’ll notice an improvement only if you’re doing billions of String.IsNullOrEmpty calls, so don’t panic right away.

In conclusion, String.IsNullOrEmpty is there for convenience reasons.  Sometimes with convenience comes tranquility, so make use of it wisely!

Just a final addition, Ruby on Rails adds a blank? method to Ruby which provides the equivalent to String.IsNullOrEmpty method in C#. So, if Ruby does not contain everything you need, Ruby on Rails surely does! :)

So what do you think, IsNullOrEmpty is good or bad for your application?

All the best,
Shay.

kick it on DotNetKicks.com Shout it



 


C# Recorder using IronRuby

[This post is the second in my series of IronRuby samples. Read the first one here]

The release of Visual Studio 2010 Beta 2 and IronRuby .Net 4.0 Beta 2 CTP has brought some AMAZING abilities to the .Net world like the dynamic keyword. This keyword is a revolutionary little thing. It takes everything you know about C# and throws it away – explicit types, locating syntax errors in compilation time, compiled code…

Sounds bad? well, it is just AWESOME!!! The dynamic keyword brings so much goodness to our beloved C# language, that if it was possible I would have hugged it and asked it to join my family.

Well, enough with the nonsense, let’s get down to business. IronRuby is Microsoft’s implementation of the Ruby language. It runs on top of the DLR and provides a seamless integration with .Net code. In short, it ROCKZZZZZ. This post is about IronRuby’s seamless integration with .Net and the ability to use the great power of Ruby inside C#.

The Ruby language has some very powerful metaprogramming abilities. One of those is the method_missing method. When you declare it in your class, every call to a method that doesn’t exist will be routed to it. You can then do whatever you want with the call – execute a different method, raise an exception, interpret the call somehow or just do whatever you want (jump in the air? do your little Irish dance thing?).

Another nice metaprogramming feature is the ability to send requests to objects by using the send method. The concept is very similar to C#’s reflection method – Invoke.

Now if we combine method_missing and send, we can create a class that saves calls and playbacks them upon request. I will call it… tam tam tam… Recorder:

 

class Recorder
  # Initialize an array that will save the calls
  def initialize
    @calls = []
  end
   
  # Save the calls to method_missing	
  def method_missing(name, *args, &block)
    @calls << [name, args, block]
  end

  # Playback the calls on a given object	
  def playback(obj)
    @calls.each do |name, args, block|
      obj.send name, *args, &block
    end
  end
end

 

I think this code is pretty straight forward, no special things here. With this class defined, we can record Ruby calls and playback them on Ruby objects:

 

# Record calls
rec = Recorder.new
rec.reverse!
rec.insert 2, "ABAB"
rec.delete! "A"

# Playback them on a real object
str = "Hello World"
rec.playback(str)
puts str # Prints "dlBBroW olleH" 

 

 

It is AWESOME, but the great thing about it is that with .Net 4.0 and the dynamic keyword, it is available in C# too!

To try the next code by yourself, first open Visual Studio 2010 Beta 2, create a new C# console application and add references to IronRuby.dll, IronRuby.Libraries.dll, Microsoft.Scripting.dll and Microsoft.Dynamic.dll (remember to use the CTP assemblies and not the regular IronRuby assemblies).

The following code loads the Ruby recorder class file (recorder.rb) to the C# environment, creates an instance of the Recorder class, records a few operations and playbacks them on .Net objects:

 

static void Main(string[] args) 
{      
  // Load the recorder IronRuby file
  var engine = IronRuby.Ruby.CreateEngine();
  engine.ExecuteFile("../../recorder.rb");
  dynamic ruby = engine.Runtime.Globals;

  // Initialize IronRuby's recorder class
  dynamic recorder = ruby.Recorder.@new();

  // Record
  recorder.Add(1);
  recorder.Add(2);

  // Playback on CLR's List object
  List<int> list = new List<int>();
  recorder.playback(list);

  // Print the results!
  foreach (var item in list)
  {
    Console.WriteLine(item);
  }

  // Record console printing
  recorder = ruby.Recorder.@new();
  recorder.Write("IronRuby");
  recorder.WriteLine(" and .Net 4.0");
  recorder.WriteLine("Rock!!!!!!!!!!");

  // Playback on console
  recorder.playback(Console.Out);
}


The output to the console will be:
1
2
IronRuby and .Net 4.0
Rock!!!!!!!!!!

Try it out and see the magic happens right in front of your very own eyes!

In my opinion, this joint venture is incredibly helpful and useful. I predict that as time goes by we will see more and more dynamic language code make its way to the conservative .Net world, enhancing it and adding it powerful abilities that it never has had before.

All the best,
Shay.

Share it: kick it on DotNetKicks.com Shout it




Subscribe Subscribe

That's Me!

Hi! I'm Shay Friedman
I'm Shay Friedman - a Visual C#/IronRuby MVP, a consultant and instructor of .NET technologies, author, speaker and new technologies freak
More about me

Contact Me

> Contact page
> Twitter: @ironshay
> LinkedIn profile

Search

Hosted By

I'm hosting this site on Arvixe and I'm very happy with it.
If you're looking for ASP.NET hosting, I highly recommend it
(and if you order from this link I also get some beer money!)
Web Hosting