RSS
Facebook
Twitter

Wednesday, May 27, 2009

How to find a bug in an application you didn’t write

I want to share with you an experience I had today – I solved a bug…

Although I solve bugs each day as part of my work this bug was different:

On my way back from work today I called a friend to see how he is doing. He is on the way to earning his PhD and has a presentation tomorrow, unfortunately he had a problem – part of his research was an “application” he inherited and that didn’t work as he expected, I didn’t think I could do anything to help solve a bug in an application I knew nothing about but I couldn’t refuse his request so I went to his home to try and help him.

Software Bugs - FastJack

I had a few things going against me:

The Bad

First I don’t understand the application domain (underwater mining simulation), second the application was written badly like only C++ can be abused - it uses global variables, spaghetti code and variables with cryptic short names and finally I do not have the sufficient mathematic background to understand the equations used throughout the code.

The Good

What I did have was a solid understanding of C++ and visual studio 6 (we couldn’t make newer version compile and run the application).

The solution

After glancing the code I understood something – there is no way I can make sense of this code I need to reduce the problem space, so I’ve asked my friend what is the problem he’s having with the application (other then the god awful code), he told me that the form that shows a certain list doesn’t show the correct information.

The form was written using C++/MFC so we found the function that populate the list and debugged the code that provides it with data and we found  an array that had “invalid” data (invalid being –2000 – the number the author of the code decided to use).

Them we’ve looked to where the data was supposed to be inserted into the array (two functions up the stack) and discovered that the array will only be filled with valid data if a certain string was found in the input file. And so after an hour of work we were able to declare that the data was invalid (at least as far as I can tell) and all that was left to do is to request a new input file – this time with the correct information.

Conclusion

The moral of the story is simple – when encountering a difficult bug don’t try to understand all of the application at once divide it to small pieces and find a good starting place (anchor) that you can learn the code from.

and for god sake refactor your code!

Thursday, May 21, 2009

Getting started with IronPython – Part 3: unit testing

Welcome to the 3rd part of my quest to learn IronPython. In this part I’ll show how I’ve unit tested my application.

Previous parts of this series:

  1. Where to start – resources, environment and how I’ve started learning IronPython
  2. Let’s write some code – the project I’m writing along with my impressions of how things done

 

Being a TDD’er (Test Driven Developer) one of the first things I’ve searched from when I’ve started learning IronPython is unit testing framework, luckily for me I didn’t need to search too long.

magnifying glass - Dr. Pat

PyUnit – Python unit testing framework

IronPython has a good unit testing framework inherited from Python called PyUnit.

Writing unit tests using PyUnit is simple:

  1. import unittest class
  2. Create a class that inherits unittest.TestCase (test fixture)
  3. Write test methods using assertions methods

The following example is my first test in IronPython – check that the newly created board has two stores:

image

Because we’re using an open source dynamic language we have the source code for everything! Browsing the unittest.py file I found something interesting about the way assertEqual was implemented:

image

It seems the actual implementation is at the failUnlessEqual method:

image 

Likewise most of the asserts actual implementation is not the assert method but the failUnless method, in fact I could have written the test above this way:

image

Like other unit testing frameworks there is setUp and tearDown methods as well:

image

I especially like the way asserting exception was thrown is done. IronPython has an assertRaises/failUnlessRaises method to check that if a specific code snippets throws exception.

Running unit tests

Writing unit tests is only half of the fun - we need to be able to run them as well.

If all of the tests are located in the same file just add this code snippet at end of the file:

image

When passing the test file as argument to ipy.exe all of the tests inside that file will be run:

image

A successful run will look like this:

image

If your unit tests are divided between several files you can use test suites. Read more about it in Python unit testing framework documentation.

Unit testing alternatives

While learning about PyUnit I came across other alternatives for IronPython test automation:

  1. Alex Henderson (Bitter Coder) has written a framework that enables writing unit tests in IronPython and running them using NUnit. you can read about it in his blog.
  2. python-nose - nose provides an alternate test discovery and running process for unittest. Should make writing and running unit tests easier.

 

What’s next?

My unit tests are available for download here, as always I would appreciate feedback (either comments or email).

 

We’re almost there - in the post in this series I plan to explain the Minimax algorithm and its implementation.

Tuesday, May 19, 2009

Book Review - Head First Design Patterns

I always believed OO design patterns to be necessary to know and understand by all software developers, I didn’t like the fact that sometimes design was forced into a known design pattern just because a pattern existed (and wrote about it). After seen patterns abused time after time I lost faith and I was frustrated by the fact that the simplified examples of the design patterns didn’t seem to solve the problems I’ve tried to solve.

After a co-worker recommended Head First Design Patterns I read it – and became a true believer.

image

The book teaches several well known (and well used) design patterns by using easy to understand use cases in a way I found both easy to understand and remember. The book is co-authored by kathy sierra (the creator of the Creating Passionate Users blog) that has a very good understanding of the human mind and how we learn and her touch is felt throughout the book.

Each chapter teaches a new design pattern by first telling a story of a problem and walks the reader through the solution as the “customers” changer requirements or ask for additional functionality for the proposed solution until a pattern emerges.

Each chapter has a summery page of the new pattern learnt and of the new object oriented design principles learnt at that chapter.

One of the things that I liked about the book is that it doesn’t try to teach all of the design patterns that were introduced by the gang of four. In fact the book’s authors write that one of their objectives was to  create a book that weight less then the reader.

Although I read a few books and tutorials on the subject I never found one that explained the who and why of design patterns in such clarity.  Even chapters about design patterns I already known thought me someting.

 

So if you what to learn (or improve you understanding of) design pattern you can’t go wrong with this book.

Free Typemock licenses

If you're a blogger and you're interested in ASP.NET development - this is for you.

Typemock is giving free ASP.NET unit testing bundle licenses to bloggers. You can read all about it in our latest blog post.

image

Saturday, May 16, 2009

SharpDevelop 3.1 Beta released – with some IronPython goodness

When I’ve started learning IronPython I choose #Develop as my IDE. Because it had IronPython intellisense and debugging support it seemed like a good fit for my simple project. When my project needed basic UI I rolled up my sleeves and wrote a winform control line by line. It seems that the good people of #Develop had heard my cries of pain and decided to improve IronPython support of their product.

The newest version (Beta) release today comes with an IronPython winform editor – like the one I’m used to from C#/VB (and even managed C++). It’s still has a few glitches but hopefully by the time the final version (3.1) will be released all of the little bugs will be fixed.

image image

I use from #Develop to convert C# files to VB.net (and back again) now #Develop conversion tool can convert C#/VB to IronPython as well. #Develop can convert single file or whole projects to IronPython, I know I will use it to learn how code I know C# looks in IronPython.

image image

As for non IronPythons tools – #Develop now has a new profiler tool as well!

 

Although the release is a beta version if you’re into IronPython I urge you to download it and give it a try.

Thursday, May 14, 2009

Unit tests vs. Integration tests

There's a hot discussion going on between myself and Ayende (Oren Eini) about the different between unit tests and integration tests specifically on how much harder writing unit test is.

It all started when I commented on a post Oren wrote: Unit tests vs. Integration tests in a post of my own (at my company's blog). Oren then commented about my observations in another post - Don’t mock my integration tests which I replied to here.

image

I especially enjoyed reading the comments of these posts - they are idea rich, written by developers with a good understanding of TDD, unit testing and mocking frameworks.

If you want to know how you can make writing unit test easier, think that I'm wrong (or right) or just want to offer your point of view - join the conversation by commenting one of these posts.

Tuesday, May 12, 2009

Getting started with IronPython – Part 2: Let’s write some code

In the previous part I wrote on how I’ve leant the basics of IronPython programming. In this post I will show the first lines I wrote as part of the project I decided to write in order to learn IronPython.

Before I div into the code I’d like to take a moment to explain about the project I’m coding.

The Project

I’ve wanted to refresh some of the materials I’ve learnt at university in “Introduction to AI” course and for my IronPython project I choose to use Minimax algorithm. In case you’ve never heard of Minimax before - don’t worry, basically it’s an algorithm to choose the preferred move in a zero sum game of two players.

I’ll dedicate a post about it in the future but for now I’d like to cover the “prerequisite” for the algorithm – a working board game implementation.

Because I needed a simple board game with clear rules I choose to implement Mancala.

What is Mancala?

Mancala is a board game played by two players. This is what my Mancala board looks like:

 P1020979

Playing Mancala is easy:

  • The board has two stores (also called Mancala) one for each player and the goal of the game is to collect as many stones as possible.
    remark – if you don’t see the stores in the board above don’t worry my board doesn’t have any. instead I keep the seeds/stones won at the sides of the board.
  • Each player has six pots he can play from (the ones closer to his side) in the board above my side is the six lower pots.
  • Players alternate turns, in his turn a player choose one of his pots, takes all of the stones from that pot and places them one by one on every pot he passes in counter clockwise order. When the player passes his store (Mancala) he places a stone there as well.

If the last stone placed in the player’s store he gets another turn.

If the last stone is placed in an empty pot he captures the stones on the opposite pot and places them in his store along with the capturing stone.

And finally the game continues until one of the players clears all of his side (and cannot “move”).

Classes of the game

I have four classes in my Mancala  implementation: Vietnamese children playing - by ô ăn quan

  1. Board – has most of the game logic along with the board representation
  2. Store – represent the player’s stores and has a counter for the number of seeds in store
  3. Pot – represent a simple pot along with the amount of seeds in it
  4. MancalaException – game specific exception

Implementing MancalaException is simple, just define a new type that inherits from the Exception class:

image

This how I would have implemented a similar class in C#:

image

No big difference between there - both the implementations are short and to the point. Notice that I’ve use pass after the class definition tells IronPython not to expect anything more from the class.

Both Store and Pot classes are similarly implemented:

image 

In both classes the “cost” of creating a simple class is notably less then what we’ve used to from C#/VB.

Both classes has a simple “constructor” -  Python’s __init__, __init__ is one of Python’s special methods - For a full list of other special method used in Python (and IronPython) see Python Magic Methods Reference courtesy of Michael Foord.

Notice how we pass self to the class methods. Python uses the 1st parameter to access the current instance. In this example I’ve used self to set the initial number of seeds (4 in each pot and 0 in each store).

Because IronPython is a dynamic language I do not need to declare the “seeds” field before using it, in fact if I would have declared it in the class definition it would have been a static field which would have been the same for all instances for the class – this took some getting used to.  

The Board class

Board is the main class of our game. This class represents the game’s board and has the (very simple) game logic.

The Board class has one major method, and several small “helper” methods.

Let’s start with the constructor:

image

Because Python does not declare class fields before they’re used I’ve used the this method to create the board’s fields:

  • a list that contains two stores (line 3). No new needed to create a new class just write it down
  • a list that has two lists of 6 pots each (4-10)
  • set the current player turn to 0.

Python does not have the same for loops I’ve been used to have in other languages, in fact Python’s for is more similar to the foreach loop of C#/VB so in order to create a list of N pots I’ve used a trick:

  1. Create a list of N objects using the range keyword.
  2. Iterate on each object and do something.

The added bonus is the list created have N elements 0 to N-1 so I can implement a proper for loop this way

In this example I use for and range to iterate of a list of 6 elements and create a new pot class and add it to a list (line 9/10).

Board.Play method

The play method drives the game. It contains the main game logic and is responsible to act a single player turn:

image

Like all other the other methods it has the self parameter that represent the current instance (similar to this/me) and it also receives the pot that the player choose to move.

In line 4-5 I wrote simple check to make sure the player choose a valid pot (one that has seeds in it). Raising exception in Python is very similar to what I’m used to although passing is message was a bit different. In fact it seems that in Python I choose an exception type and a message and not create a new class with the message and an argument.

Lines 11 and 12 has the actual game play using the method __playSingleMove, this method marked by two underscores that tells Python that its a “private” method. this method cannot be called outside for the class and is used here to make play more readable.

I’ve used a PlayContext class to pass several arguments into this method, I needed to pass several arguments to the method that change each move. Instead of using this OO way I could have written the following:

image

Python can return multiple values but it seemed just wrong writing a line like that.

After all of the seeds have been distributed I have several more actions to do:

If the last seed has not been placed in the player store (14)

  1. Check if the last pot was empty and capture the opposite pot’s seeds (15-16)
  2. Change the current player to the next player (18)

If the current player cannot move – the game ends (20-21).

The code is readable I especially liked using indentation instead of curly brackets although it can be confusing at the beginning.

 

the full code of the Mancala classes is available here for download. This is the first time I’m writing Python/IronPython code so if I’ve missed anything or if you know of a better way to do something I did – please let me know either by email or by writing a comment.

 

That’s it for now – stay tuned for the next post where I’ll write about how I’ve unit tested my application.

image

[Mancala – by sinsofthedove]

Friday, May 08, 2009

15 Resharper keyboard shortcuts you need to know

image

I use Resharper daily and it help me to write better code faster. The only downside is that the developer needs to learn many keyboard shortcuts in order to properly use its functionality.
While I'm still learning new shortcuts every day I've found that I keep using several shortcuts most of the time.
The list below is an incomplete list of the keyboard shortcuts I've found useful in no particular order:

  1. Ctrl+Shift+Space - Smart code completion
    The ace of the pack, since I've started using it I do not need to write trivial code anymore.
    Using this shortcut tell Resharper to fill the obvious code: it can write the method's arguments in a method call, finish the initialization of a method and more.
  2. Alt+Enter - Show available quick fixes and context actions
    When there's an error in the code or Resharper has suggestion on how to improve a certain line it marks it with a red, yellow or blue underline, using this shortcut will open a context menu with the suggestions on how to repair, improve or change the code. Need to change the accessibility of you method from private to internal? want to change a delegate to lambda? this shortcut is your one (two) click solution for these problems.
  3. Ctrl+ L Mouse - Go to declaration
    I use this shortcut a lot. Clicking a method call, variable or type while holding the control key will take you to the definition of the clicked object. It's easy to find where an object was declared and find it's implementation.
  4. Ctrl+W and Ctrl+Shift+W- Extend/Shrink selection
    a class, method or for loop it's amazing how many times I need to copy or cut a certain scope. this shortcut tells Resharper to select the current scope, pressing it again will select the overall scope and so on. for example if the cursor is inside an if call the first (sometime second) selection will select the entire if, the next will select the method and the last will select the whole class.
  5. Alt+Insert - Generate code
    Depending on the cursor location using this keyboard shortcut will create a piece of needed code.
    When used in a class context it can create properties, constructor (along with variables initialization), implement or override members.
    When called inside the solution explorer it can create a new file from a predefined template.
  6. F2 - Rename this
    This rename is smarter and more powerful version of the simple quick rename visual studio has. It renames the method, variable or class along with all of the places its been used and it even renames related comments.
  7. Ctrl+Shift + R - Refactor this
    Opens a context menu with all of the refactor options available according the where the cursor is. Extract to method, introduce variable and more. Although each refactor option has its own shortcut it's easier for me to learn just this one and choose the refactor I want from the context menu.
  8. Ctrl+F6 - Change signature
    Ever needed to add or remove a method call parameter? what about changing the order of the parameters after the method has been written and being called from somewhere else in your code?
    Using this key shortcut you can add, remove or move the method parameters. Resharper automatically adds the needed code on the method calls as well where possible.
  9. Alt+F7 and Alt+Shift+F7- Find/Goto usages
    Need to find where a method or class is used in the code? just use this simple shortcuts and either get a list or just go to the caller.
  10. Ctrl + Alt + B - Goto inheritor
    When I need to go to the classes that inherit (or implement) another class or interface I use this shortcut to quickly jump to them. 
  11. Ctrl + E - Goto previously opened file
    Most of the time when I work on fixing bugs or implementing a new feature I keep jumping between a small subset of the project's files. This handy shortcut opens a searchable list of all of the last files opened sorted according to the last updated file. When choosing a file from the list it opens in the last place I've been when I've worked on it.
  12. Ctrl + N - Goto class
    I use this shortcut to open classes without going thought the solution explorer. Using it is simple start writing the class name and choose the one you need from the list. It can even handle wild cards (*handler).
  13. Alt+Shift+L - Locate in solution explorer
    From time to time I need to find the actual file I'm working on in the solution explorer. If you didn't set the auto follow option in visual studio (like me) this shortcut is a real time saver. instead of searching for the file in a big project structure just use control and L.
  14. Ctrl + J - Surround with template
    Ever finished writing a block of code and decided it should be inside a try..catch block? using Ctrl+W (see above) you can select that code and using this shortcut you can automatically surround it with one of the template provided including try..catch, for, if and so on.
  15. Ctrl + Q - Quick documentation
    Gives you a very quick, but thorough overview of the method or variable that you have your cursor on.
    You can even use it to check you own XML documentation while working on it.

 

I know there are many more useful shortcuts - if you know one feel free to write a comment about it.

Tuesday, May 05, 2009

Visual Studio windows mania

This happened today while I was debugging a failing test using visual studio

crap!

Weird...

Friday, May 01, 2009

Getting started with IronPython – Part 1 where to start

It seems to me that there is a lot of talk about the new .NET Dynamic Languages lately. Because I wanted to see what the DLR was all about I will learn IronPython as part of my quest to learn new programming languages.
image

Learning new language

When I learn a new programming language I look up three “ingredients”: a Book, tutorials/code examples and a project. It also helps if to have a “programmer friendly” IDE that helps writing and debugging.
Learning from examples scattered around the internet is possible, but I found that I learn new technology quicker when these ingredients are available. Luckily with IronPython there was not shortage of resources.
I’ve also received help from friends who showed me where to start my journey (thanks Ohad & Shay).

The Book

Nowadays with all of the blogs and other resources on the internet it seems that developers no longer bother to read books. I think that a book could supply a solid foundation and broad understanding that is hard to find when using a search engine as your primary knowledge base.
There are a few IronPython books available (such as IronPython in Action) , because I needed to learn Python as well I choose Dive Into Python as my beginner book of choice. Instead of walking you though the Python language it teaches by example - each chapter begins with a code example that shows an example of the chapter’s topic that is explained throughout  the chapter. I found this way of teaching programming great, I didn’t get bored with trivial information and by the end of each chapter I could understand a complete code example written in Python.
Dive Into Python is freely available along with the source code of its examples so if you’re interested in learning Python you can read it online or download it PDF from the comfort of your own computer.

Tutorials and Source code

There is no shortage of examples featuring IronPython (and CPython) on the internet. I’ve found a few:

Project

Hands on experience is crucial to learn a new programming language. Usually I choose a project and try to code it using that technology.
In this case I’ve decide to write a simple board game (with simple computer opponent) using IronPython.
I’ll write more about the project in related blog posts soon.

IDE (Integrated Development Environment)

After downloading IronPython from its CodePlex site I needed to set my development environment. Currently I’m using #Develop as my main IDE for C#/VB.NET home development and it seems like a good fit for IronPython as well. Although I’m still on the lookup for other tools, currently #Develop is good enough for me.
There is a project called IronPython studio I’ve considered using but it currently only supports IronPython v1 so I’ve decided against it.

That's it for now in the next blog post I’ll describe the project and my initial experience with IronPython.

Related Posts:

Server Fault enters private Beta

The maker of StackOverflow have created an IT centric site where IT professionals can ask and answer questions.

image

Although I don’t consider myself an IT professional I need to do some server & network administration at work and home and I find myself constantly wishing for a site just like this.

Server Fault is similar to its sister site – a community to ask questions I could not find an answer to searching the internet.

 

The private beta is open for current StackOverflow users as well – you can read the announcement on the StackOverflow blog.

Related Posts Plugin for WordPress, Blogger...