Author: Pete

Errors

Rails Install Issue

So, I am making a serious go of learning Rails. I have installed it on my Vista machine before, but never really given it a go. So, now that I’ve got a Mac, I decided to try to learn Rails on it. I downloaded the Ruby One-Click Installer and installed it. Per its suggestion, I ran

sudo gem install rails

Then, I got this error

Bulk updating Gem source index for: 
http://gems.rubyforge.org ERROR:  
While executing gem ... (Gem::GemNotFoundException)     
Could not find rails (> 0) in any repository

I did some Googling and found out that I had to just run this code

sudo gem update

and select the correct packages to include. Then, I just reran

sudo gem install rails

and I was money in the bank.

I hope this helps anyone else who encounters the same issue. Now, on to working through some tutorials.

Code Tips

Liskov Substitution Principle

I was listening to Hanselminutes a few weeks back and Scott Hanselman had Uncle Bob Martin on to talk about the SOLID principles of object-oriented design. SOLID stands for

  • Single responsibility principle
  • Open closed principle
  • Liskov substitution principle
  • Interface segregation principle
  • Dependency inversion principle

Obviously, each one of those could warrant its own blog post and Robert Martin himself has written and spoken about them extensively. Uncle Bob did bring up a classic problem on Hanselminutes, though, that I wanted to take some time to talk about.

We who design object-oriented systems have a problem. We’ve been taught that the whole world is made of objects and that we are supposed to model our software after the real world. However, as I’ll cover in this post, sometimes that is a mistake.

The Liskov Substitution Principle says that “Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it” (Uncle Bob’s paraphrase). I have found this one somewhat confusing in the past, but I think that this Rectangle-Square problem explains the problem very well.

In math, the definition of a rectangle is “a parallelogram with four right angles”. One Webster’s definition of a square is “a rectangle with all four sides equal”. Right in the definition from the real world, a square is a rectangle. “Is a” is often a key phrase in object-oriented design used to denote an inheritance relationship.

So, let’s pretend we have the following code:

public class Rectangle
    {
        public virtual int Width { get; set; }
        public virtual int Height { get; set; }

        public virtual int ComputeArea()
        {
            return Width * Height;
        }
    }

    public class Square : Rectangle
    {
        private int _height;
        public override int Width 
        {
            get { return _height; }
            set
            {
                _height = value;
            }
        }

        public override int Height
        {
            get { return _height; }
            set
            {
                _height = value;
            }
        }
        
        public override int ComputeArea()
        {
            return base.ComputeArea();
        }
    }

Okay, that works. You can run code against it and at first blush it behaves like it should. However, the Liskov Substitution Principle says that you should be able to have

Rectangle r = new Square();

and have no problems.

While you can do that and can then operate on r as if it were a rectangle, there is a problem. A person who only knows about rectangles might do this to our r.

Rectangle r = someMethodThatWillReturnASquareSometimes();
r.Width = 10;
r.Height = 15;

They would then get entirely unpredictable results when they computed the area or even went back in to retrieve the properties (finding one had changed without their knowledge). A person who would want to operate in a safe way would have to eventually do the following:

Rectangle r = someMethodThatWillReturnASquareSometimes();

if (r is Square)
{
  // Special Square Processing
}
else
{
  // Normal Rectangle Stuff
}

That now pretty much defeats the purpose of using base classes and interfaces. If you have to know about derived classes and their implementation, you’ve lost the battle. I think that this is a great reminder to model objects logically how they affect the program, not how they reflect “real life”.

NMock

Intro to NMock

If you do Test Driven Development (TDD) for any amount of time and with any amount of serious effort you are going to run across a problem. Sometimes you can’t test one object without other objects being involved. Since you can’t properly test one object without isolating it, you need to fake or mock the others that you aren’t testing. The Wikipedia entry on Mock Objects discusses it in some more detail.

A good candidate for a mock are objects that return current information (and as such are hard to properly test) or objects that will make permanent changes to databases, for instance, and as such are also poor candidates for repeatable testing.

The first (and only) mocking framework that I’ve used is NMock. I chose it because my rule is “when in doubt, choose the product that is named ‘n’ and then what you are doing” (remember my NLog and NUnit posts?).

Examine the code below and my comments about what each section is doing.

using System;
using NMock2;

namespace PeteOnSoftware
{
    public interface IBlogEntry
    {
        string PostName { get; set; }
        DateTime PostingDate { get; set; }
        string PostBody { get; set; }
        bool SavePost();
    }

    public class NMock
    {
        public static void MakeMocks()
        {
            // Create the Mock Object "factory"
            var mockery = new Mockery();

            // Create our mock object based on the interface defined above
            IBlogEntry mockBlogEntry = (IBlogEntry) mockery.NewMock(typeof (IBlogEntry));

            // Here is the awesome part.  Here is where we define our Mock behavior.  Not only will 
            // our object now return true when the SavePost() method is called and "Intro to NMock" 
            // when the PostName property is called, but it will only do it one time - as we have
            // defined here.
            Expect.Once.On(mockBlogEntry).Method("SavePost").WithNoArguments().Will(Return.Value(true));
            Expect.Once.On(mockBlogEntry).GetProperty("PostName").Will(Return.Value("Intro to NMock"));

            // Output the results to the screen to see if it is behaving as we expect.
            Console.WriteLine(mockBlogEntry.SavePost());
            Console.WriteLine(mockBlogEntry.PostName);
        }
    }
}

This outputs the following to the output window:

True
Intro to NMock

However, check out the following code:

using System;
using NMock2;

namespace PeteOnSoftware
{
    public interface IBlogEntry
    {
        string PostName { get; set; }
        DateTime PostingDate { get; set; }
        string PostBody { get; set; }
        bool SavePost();
    }

    public class NMock
    {
        public static void MakeMocks()
        {
            var mockery = new Mockery();

            IBlogEntry mockBlogEntry = (IBlogEntry) mockery.NewMock(typeof (IBlogEntry));

            Expect.Once.On(mockBlogEntry).Method("SavePost").WithNoArguments().Will(Return.Value(true));

            // Output the results to the screen to see if it is behaving as we expect.
            Console.WriteLine(mockBlogEntry.SavePost());
            Console.WriteLine(mockBlogEntry.PostName);

            // We told the mock earlier that we would only call SavePost() once.  Let's see what 
            // happens if we call it again.
            Console.WriteLine(mockBlogEntry.SavePost());
        }
    }
}

This returns the following exception:

Unhandled Exception: NMock2.Internal.ExpectationException: 
     unexpected invocation  of blogEntry.SavePost()

One application of how that could be useful would be if you are testing your business tier to make sure that it does not call Save() on an object or into the DataTier more than one time per invocation. There are other options, as well. You can say Expect.AtLeastOnce or Expect.AtLeast(some int) or Expect.AtMost or Expect.Between or Expect.Never. The framework is so flexible. You can define how you want the mock object to behave depending on its inputs.

Examine the following code that makes the SavePost method return true if passed 1 and false if passed -1.

using System;
using NMock2;

namespace PeteOnSoftware
{
    public interface IBlogEntry
    {
        string PostName { get; set; }
        DateTime PostingDate { get; set; }
        string PostBody { get; set; }
        bool SavePost(int id);
    }

    public class NMock
    {
        public static void MakeMocks()
        {
            var mockery = new Mockery();

            IBlogEntry mockBlogEntry = (IBlogEntry) mockery.NewMock(typeof (IBlogEntry));

            Expect.AtLeastOnce.On(mockBlogEntry).Method("SavePost").With(1).Will(Return.Value(true));
            Expect.AtLeastOnce.On(mockBlogEntry).Method("SavePost").With(-1).Will(Return.Value(false));
            
            Console.WriteLine(mockBlogEntry.SavePost(1));
            Console.WriteLine(mockBlogEntry.SavePost(-1));
        }
    }
}

As you can see, NMock is flexible and can be very useful to a programmer who is doing unit tests. Next time, I’d like to take a look at Dependency Injection / Inversion of Control and how it can be used with Mocking to not only make your code flexible, but very testable.

Linq

Project Euler Problem Two

Last time, I began working on the Project Euler problems and I set out guidelines for myself that I would attempt the problem first in C# (that I’m most comfortable with) and then try to solve the problem in some new way. Last time, I used some of the LINQ extension methods that I hadn’t previously used before. Some solutions might be in F#, Ruby, Python, etc, and I might use each “new way” more than once (since 10 lines of code doesn’t make me an expert!).

I present Project Euler Problem Two. Here is the code for the C# solution using LINQ.

    /// <summary>
    /// Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
    /// 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
    /// By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
    /// Credit to Bill Wagner for the solution.
    /// http://tinyurl.com/4846a5
    /// I knew LINQ had to have a cool answer and I learned a lot 
    /// about what LINQ can do from this little snippet of code.
    /// I blogged this originally at https://www.peteonsoftware.com/index.php/2008/12/07/project-euler-problem-two/
    /// </summary>
    public class ProblemTwo
    {
        private static Dictionary<int, long> cachedFibonacci = new Dictionary<int, long>();
            
        public static long Solve()
        {
            var evens = (from n in Enumerable.Range(0, 4000000)
                            let value = ComputeFibonacci(n)
                            where (value%2) == 0
                            select ComputeFibonacci(n)).TakeWhile(n => n <= 4000000);
     
            return evens.Sum();
        }
     
        public static long ComputeFibonacci(int term)
        {
            long answer;
     
            if (cachedFibonacci.TryGetValue(term, out answer))
            {
                return answer;
            }
     
            if (term < 2)
            {
                answer = term;
            }
            else
            {
                answer = ComputeFibonacci(term - 1) + ComputeFibonacci(term - 2);
            }
     
            cachedFibonacci.Add(term, answer);
     
            return answer;
        }
    }

As I note in the comments, this is basically Bill Wagner’s solution to this problem. His solution was so ingenious and taught me some things about LINQ that I just had to work it in here. The compute Fibonacci method was created because other Project Euler problems in the future are going to use the Fibonacci sequence, so we should have a reproducible way to create the series. I like his use of the dictionary to be able to ask for any point in the series at any time and you will only have to compute as terms that you have not yet calculated. Caching is a good thing.

The thing that was new to me was the let keyword in the LINQ query. What Bill does is store the value of the current n into value and then says that we only want it if it is even. This allows only the even values to be used. The rest of the problem is very simple, but I just wanted to point out those two points of interest.

I also tried this problem in Ruby. You can go to an interactive ruby session in your web browser here. If you type in the following code, you can see that it also works as well.

def computeFibonacci(firstTerm, secondTerm)
	return firstTerm + secondTerm
end

firstTerm = 0
secondTerm = 1
answer = 0

while secondTerm < 4000000
	newTerm = computeFibonacci(firstTerm, secondTerm)
	if secondTerm % 2 == 0
		answer += secondTerm
	end
	firstTerm = secondTerm
	secondTerm = newTerm
end

print "Answer is ", answer

There is nothing special about this code. No whiz-bang code maneuvers. Just straight forward Ruby code. I found it very helpful to test it out at the link above and see that it worked. What is funny to me (and will likely get me in trouble) is how similar the basics of Ruby are to VB (or just BASIC) in general. It is easy to pick up because it is familiar to so many people. It was a good introductory exercise into Ruby, however, so I thought that I would share it with you.

If you have any comments or questions, please feel free to leave me a comment here.

Fluff

A Dearth of Mid-Level Developers

My company is having a very difficult time finding mid-level developers. Our development team isn’t that large, so the number of junior people we can support isn’t that large. In terms of .Net experience, we have 3 relatively junior developers and myself. I’ve done a fair amount of architect work, senior development / team lead stuff, and been doing .Net for about as long as it has been out. That leaves us with a gaping “talent hole” that could be filled by a mid-level developer or two.

The problem, however, is that every resume we see is someone who is definitely very junior or someone claiming to be an architect (who often techs out at lower mid-level). My boss (and I can’t say I blame him) is against hiring someone who thinks too highly of himself and seems unteachable. A certain amount of ego does come with the territory and everyone is trying to get the best job for the most money possible, but people really need to be honest with themselves.

I’ve done a lot of thinking about this and I think that I’ve come to a conclusion on this problem. The reason that we are having such a hard time finding solid mid-level developers is because they are actually very scarce (in relation to the rest of the populace). Hear me out.

Junior developers are – of course – the most plentiful. Every developer who will ever be anything starts out in this rank. However, I believe that the people who will actually become great in this profession move out of this group rather quickly. In talent level, they are my coveted mid-level developers; by experience, they can easily be overlooked as still junior.

Almost two years ago, Jeff Atwood wrote a post on Coding Horror in which he quoted Bill Gates on this subject. I’ll leave you to read the post, but basically someone asked Bill Gates if accumulating experience made programming easier and he said, “No. I think after the first three or four years, it’s pretty cast in concrete whether you’re a good programmer or not”. He goes on from there, but that hits my point.

People who “get it” and have a lot of experience – the “rock stars” that Joel Spolsky writes about – are hard to find. Spolsky claims that you don’t find them easily at all because they are rarely on the market for any amount of time and in essence “hand pick” their jobs.

People who “get it” and don’t have a lot of experience – probably most likely the people I am looking for – are very hard to find because their resumes hide the fact that they are good and are going to be awesome some day.

People who don’t “get it” can have any number of years of experience and they are still not attractive candidates. In the Columbus, Ohio market (where I’m located) there is a relative shortage of developers, so seemingly everyone can find a job. What I’m speculating is that these individuals end up with 7-8 years of experience and think that they should then be able to land a senior job. In my opinion, however, they fall into the category of “poor developer” and shouldn’t be hired into those positions by any reputable company. What may happen is that some consulting firm will pick them up and bill them out at $150.00 an hour as “experts”, but it is really the consulting company’s system that gets them through projects.

(A quick note: I am not saying that anyone who consults is no good. I’ve met several consultants who are of the utmost quality and deserve every penny they make (often they are independent and actually get to keep much of what they bill). However, I’ve also met quite a few consultants who I’d mark as falling into the broad categorization of this post.)

I don’t know what to do about this problem, actually. If you are a good, solid developer who “gets it” and wants to work with the latest and greatest coming out of Redmond, leave me a comment and if we still have positions open at the time, I will personally make sure that your resume gets looked at and unless it is god-awful, I can pretty much guarantee you a phone tech-screening. From there its all you, hotshot.