Search
Tuesday, February 27, 2001 ..:: Home ::.. Register  Login
   Calendar  
     
  
   Search  
     
  
   Disclosure  
     
  
   TechTidBits (Blog)  

Coding Challenge: Can you spot the coding error?

Feb 25

Written by:
Wednesday, February 25, 2009 9:44 PM  RssIcon

SB had a great coding question today which he thought enough of me to see if I could help out.  As an aside, ever notice how you can ask some people questions but not others?  Why is that?  Fodder for another blog.  Anyways, read on to see if you can solve this coding challenge.

This challenge starts off innocently enough, here's a Film class.  Nothing extravegant, just a title and year released properties with an overridden ToString

public class Film
  {
    private string title;
    public string Title
    {
      get;
      set;
    }

    private int yearReleased;
    public int YearReleased
    {
      get;
      set;
    }

    public Film( string title )
    {
      new Film( title, 0 );
    }

    public Film( string Title, int YearReleased )
    {
      title = Title;
      yearReleased = YearReleased;
    }

    public override string ToString()
    {
      string yearReleaseMessage = string.Empty;

      if(yearReleased > 0){
        yearReleaseMessage = " (Rel: " + yearReleased + ")";
      }

      return "Title: " + title + yearReleaseMessage;
    }
  }


Next is the mainline code, my gut told me SB whipped this up correctly but the problem was manifesting itself here.

class Program
    {
        static void Main(string[] args)
        {
          List computerFilms = new List();
          //prob with this code formatting tool to work with Generics
          //it should look like a List of Film objects

          Film sneakers = new Film( "Sneakers", 1992 );
          computerFilms.Add( sneakers );

          Film warGames = new Film("WarGames");
          computerFilms.Add( warGames);

          Film hackers = new Film( "Hackers", 1995 );
          computerFilms.Add( hackers );

          Film tron = new Film( "Tron");
          computerFilms.Add( tron );

          foreach( Film film in computerFilms )
          {
            Console.WriteLine( film.ToString() );
          }

          Console.ReadLine();
        }
    }


The output looked similar to this.

Computer Films Output 

But why are two of the entries empty? Why are their titles and years released empty?

The individual files being created in the mainline are all basically the same, so I went looking at the Film object.  Getting warmer!  My first hunch had to do with mixing up the local properties and setting them in the constructors. Ooooh getting warmer. But the title = Title is correct and so is the yearReleased = YearReleased. aaaahhhhh getting colder.  We called over the C++ guru (SG) and he started at the same place (static void Main.....), all good, then he went to Film.......took one look at the other constructor (hey there's two, there's a 50-50 shot of hitting the right prob source right off the bat) and BINGO!  HOT HOT HOT!!!!!!!!!!!!  Can you spot what SG did?

If you can't spot it yet, here's some hints.  Check out the constructor that takes the title string only.  Check the output, that's the one that's causing the problem.  Can you see something that just looks left out?  Any ideas that get blown away? 

If you spotted the creating of a new Film object buuuuuuuut then not doing anything with it, and you'd be right!  BINGO! 

So what's going on?  WTF?  In that one string parameter constructor, a new Film object is being created on the heap, BUT it's not being assigned to anything (note the missing leading "Film newFilmBeingCreatedHere = "), therefore, after the closing '}' of the constructor, the Garbage Collector (GC) turns around and says, "uh, nobody in here anymore, I'm going to clean this heaping mess up." 

Two things.  For the most part the GC is nondeterministic meaning you can "ask" the GC to run but you cannot "tell" it when to run (it runs when it bloody well wants to, DOH!), and second, when it does run, it's going to clean up reference objects that are out of scope (like our newly created but not assigned Film object) on the heap (all reference objects are created and removed from the heap).  Yes, there are other things the GC does and A LOT more logic behind the "objects that are out of scope" statement, but I'm trying to make sure you can read this in an hour lunch time slot. :>

After a small bit of tweaking we made it look like an oscar winner! :>  What did we do?  The easiest thing we did was remove the new Film code and replaced it with the constructor chaining call (forward constructor chaining).

Film Constructor Change

As you can see, with that one small change, everything works as expected.

Grab a coffee and get coding!

Tags:
Categories:
Location: Blogs Parent Separator TechTidBits

4 comment(s) so far...


Re: Coding Challenge: Can you spot the coding error?

>> As an aside, ever notice how you can ask some people questions but not others? Why is that? Fodder for another blog.

Can't wait to read this new blog :)

By Shane on   Friday, February 27, 2009 9:28 AM

Re: Coding Challenge: Can you spot the coding error?

HAHA! :> Coming soon to an LCD near you! :>

By phenry on   Friday, February 27, 2009 9:29 AM

Re: Coding Challenge: Can you spot the coding error?

spotted it before reading further...hehehe

By souheil on   Wednesday, March 04, 2009 9:30 AM

Re: Coding Challenge: Can you spot the coding error?

Haha I figured you'd be the other C++ guru to figure it out quickly! :>

By phenry on   Wednesday, March 04, 2009 9:31 AM

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Add Comment   Cancel 
     
  
Copyright 1999-2012 by PCHenry.com   Terms Of Use  Privacy Statement