Common mistakes in software development

***** Rant Alert ******

<rant>

At my current client I’ve got to do mainly maintenance on existing applications. This gives me the chance to look into codebases that have been created by other people and that don’t really reflect how I would write things. That is all good though it gives me a chance to learn new ways of doing things and when I think their way is better I’ll surely adopt.

Anyway when I’m browsing these codebases I do find a lot of things that could have been done better or more correctly and that’s what I’ll be writing about a little today.

The first one is returning bools:

I’ve found this in just about every project I’ve been in:

public bool IsNull(){
  if(obj == null)
    return true;
  else
    return false;
}

The snippet above is a very long winded way of writing. IMHO this hurts readability and you’re saying the same thing twice. obj == null already returns a bool it makes no sense writing it again.

public bool IsNull() { return obj == null; }

Another thing I keep seeing is very liberal use of try..catch blocks that catch all exceptions. Admittedly try..catch is cool but it should be used at times you are actually interested in the exception that is thrown. But it shouldn’t be used as a safeguard to swallow exceptions you don’t want to fix at this moment.  I keep seeing this code in projects:

try{
  myBLObject.FindSomething(someId).SomeMethod();
}
catch(Exception){
// Nothing to be done but error stops
}

Now that can be easily written so that it won’t throw an exeption and then the try catch isn’t necessary anymore at all. Try..catch blocks most certainly have their use but throwing and catching exceptions definitely hurts performance because the system has to generate a complete stack trace etc. for every exception that is being thrown.

var result = myBLObject.FindSomething(someId);
if(result != null) result.SomeMethod();

The code becomes a lot more readable, not to mention faster. I’ve seen this being used in OnRowDataBound events etc on grids with 500+ rows, removing the try catch blocks more than doubles the speed of that page.

The next one on the list is using if,else and switch statements. They are sometimes a cause of code bloat. To put it in the words of Scott Hanselman:

I think that using only if, for and switch is the Computer Programmer equivalent of using “like” in every sentence.

Scott does a great job explaining why they can be pretty evil so I’ll just leave you with a link to his post

I have another couple of posts in the making on this subject but I had to get this out of my system. These are also very quick wins the other things I’m going to talk about are application architecture and stored procs….
</rant>

White paper on IronRuby published

Manning published my white paper — or green paper as they call it — on IronRuby.

You can find it here: http://manning.com/free/green_carrero.html

This paper tries to give you an introduction on what the ruby language is and how it could work for you. If you want to know more than what’s on those pages there is always the book: http://manning.com/carrero

Technorati Tags:

IronNails: Some progress

I thought it might be a good idea to update you guys on how IronNails is progressing.  I think I’ve got it so that you aren’t exposed to writing many of the boring boilerplate code that comes with taking this approach (M – V – VM- C). Also to execute an action on a controller asynchronously you can by just adding :mode => :asynchronous to your view_action declaration.

A lot is still left to do but this proves that it is possible to use IronRuby today to do some pretty cool stuff. From the top of my head here are some things that still need to be done:

  • The ability to load xaml from an assembly like the one that is generated when you use Blend for your design.
  • More predefined behaviors
  • Templated generators
  • Silverlight support

But the core of the framework is working. Now it’s a matter of extending the functionality. Some of the features the framework does support

  • Binding to controller actions through commands
  • Binding to controller actions through event handlers on the view proxy
  • Asynchronous execution of actions
  • Timed execution of actions
  • Binding to models

I will be developing my sample for my chapter against this framework and will add the pieces I’m missing as I get on.

Some of the things I foresee that might need to be added are:

  • support for controlling the application from an IronRuby console so that you can interact with the interface as it is running.
  • support for a console to interact with the code of the application.
  • support for plugins

So after all these lists how would an application look like when you are developing it?

The controller:

# file name: demo_controller.rb
class DemoController < IronNails::Controller::Base
  view_object :status_bar_message, "The status bar message"

  view_action :change_message

  def change_message
    @status_bar_message = "#@status_bar_message appended"
  end
end

The ViewModel:

# file name: DemoViewModel.cs
public class DemoViewModel : IronNails.View.ViewModel { }

The View:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:behaviors="clr-namespace:IronNails.Library.Behaviors;assembly=IronNails.Library"
    Title="Window1" Height="300" Width="300">
    <StackPanel>
        <TextBlock Text="{Binding Objects[StatusBarMessage].Value}" ></TextBlock>
        <Button Content="Click me" behaviors:ClickBehavior.LeftClick="{Binding Commands[ChangeMessage]}" />
    </StackPanel>
</Window>

There are currently 2 dictionaries available to the view. One that contains the models (Objects) and one that contains the commands (Commands).  The value of an entry in the Objects needs to be observable by implementing INotifyPropertyChanged and that is what’s responsible for the binding syntax Objects[ModelName].Value

At this moment there are only a couple of behaviors implemented: LeftClick, RightClick, DoubleClick and Hover.

The framework expects that you follow the basic naming conventions of the technology you’re programming in. So in ruby you underscore names but in C# and xaml you camelcase them.

By defining an object with view_object :o bject_name, default value you define it with a default value that you can change afterwards in the controller actions.  By defining an action with view_action :action_name, :mode => :asynchronous you tell that framework that you want to link a method or a block as a controller action and execute it asynchronously.

Finally found the insert key on my macbook pro keyboard

I finally managed to figure out what the insert key is on my macbook pro. I missed it a lot because in Resharper the standard command to generate code is Alt+Ins. This key combination seems to be engraved in my brain because it was really hard for me to use it with a different key combination. Anyway the winning combinations are:

Insert: fn+return

Alt+Insert: fn + alt/option + return

IronNails : Rails like development for IronRuby with WPF/Silverlight

For my book IronRuby I’m working on chapter 4. That chapter is about doing WPF development with IronRuby. I started out with a straight port of Witty to IronRuby. As I was doing that the cogs started turning and I came up with a way to bring the rails style of development to WPF.   I decided to investigate that route a little bit further and now I have a small framework that enables you to write WPF applications with the MVC paradigm. I decided to open that code up as open source and host it on github. 

At first I used the name Sails for my framework but it turns out there is java clone of rails that is called opensails. So to avoid confusion David M. Peterson proposed the name IronNails.

On Sat, 02 Aug 2008 08:00:44 -0600, Charles Oliver Nutter wrote:

    FYI, there’s already a framework named "Sails" for Java:
http://www.opensails.org/

For the sake of sticking to the "Iron" theme, why not replace the ‘S’ with an ‘N’ and go with IronNails. ;-)   Maybed it’s just me, but if given the choice, I’d much rather nail it than sail it any day of the week. :D


/M:D

M. David Peterson

You can find the project here: http://github.com/casualjim/ironnails

At this moment it’s definitely not finished at all, but it does work. The remainder of the week I’ll move my previous demo code onto this framework, update the code samples in my chapter and finish the content. I hope I will have all of this done by the end of next week.

Back to the IronNails project:

Because DLR objects cannot be used to bind to in WPF you have to define a skeleton of the ViewModel in C#, but this will change in the future. When that changes I’ll look at extending the framework to make use of some other WPF patterns like defining a DependencyObject and Behaviors. Once those are defined you get a very clean separation between design and behavior.

This is abstracted away from you but in the background the framework works with the View – ViewModel – Model – Controller pattern although I’ve tried to keep your exposure to the view model to a minimum. The framework follows naming conventions per language. So in C# and XAML you camel case stuff and in IronRuby you underscore stuff.

The very core of the framework is defined in C# but most of the code is IronRuby, depending on how hard it will be after the DLR RTM’s I may look at adding support for all the DLR languages.

IronNails
=========

IronNails is a framework inspired by the Rails and rucola frameworks. It offers a rails-like way of developing
applications with IronRuby and Windows Presentation Foundation (WPF).
This framework uses the pattern Model – ViewModel – View – Controller (M-VM-V-C). It should be able to run on both WPF
and Silverlight.
The idea is that the views can be created using a design tool like Blend for example and just save that xaml as is. The
designer should not need to use anything else than drag and drop to create a GUI design. The behaviors are then added to
the view by using predefined behaviors in the framework or by defining your own behavior.
The framework then generates a proxy for the view which will be used to transparently wire up the commands in the
behaviors to controller actions.

You are now able to write the following code for a controller:

class MyController < IronNails::Controller::Base

  view_action :show_message, :triggers => :my_button do
    MessageBox.show "This is the great message from a block"
  end

  view_action :change_color, :triggers => { :element => :my_text_block, :event => :mouse_enter }
  view_action :reset_color, :triggers => { :element => :my_text_block, :event => :mouse_leave } do |view|
    view.my_text_block.foreground = :black.to_brush
  end

  view_object :people, Person.find_all

  def change_color(view)
    view.my_text_block.foreground = :red.to_brush
  end

end

At this moment the project has 0 unit tests, it has below minimal documentation and it still needs a work like defining the behaviors. I have to move on with my book but intend to continue developing this framework after my book is finished and IronRuby RTM’s.  There are some more workarounds in the project that will all disappear as IronRuby progresses.

kick it on DotNetKicks.com

Moving back to belgium

Tonight is my last night in New Zealand. Tomorrow I will fly back to Belgium to see what has changed in the 3 years that I’ve been away. I already know that my home city Antwerp has changed a lot because they were completely redoing the place when I left. I think it might still too soon for a reflective post on my experiences in New Zealand. What I can say is that I had a great time here and I made some great friendships with some extraordinary people. Depending on who you ask this is a good or bad thing but I’ll surely be back in a couple of years :)

Read more »

How I Got Started in Software Development

Michael Eaton started a meme with the question: How did you get started in software development?

Yesterday Simone Chiaretta tagged me in his post, so it’s now my turn to answer the questions and tag other bloggers:

Read more »

Dynamic Script Control

Both Silverlight and WPF use XAML markup to describe their user interface.  As I’m currently writing my chapter on WPF for my book IronRuby In Action and I want to use some xaml that has been generated before for a different project but with an IronRuby class to load the xaml I’m in trouble. This is because you can declare assembly references in the xml namespace declarations so you can use the types in that assembly from xaml. 

The DLR based languages don’t compile into static assemblies and this means that you can’t use those xml namespace definitons to reference your assemblies.  I wrote a fairly trivial control that acts like a hook for DLR based controls in the XAML tree.

You can check it out at codeplex.
http://codeplex.com/dynamicscriptcontrol

The idea behind this control is that you can "hook" your DLR based control into the visual tree by setting some properties.  You can set properties on the DLR based control by setting the Attributes property on the DynamicScriptControl

Let’s look at a quick example:

1. The ruby file defining a custom TextBox. But you can do whatever  you want in that ruby file of course.

dynamic_script_control_rubyscript

All this textbox does is preset it’s text property to "I’m prefilled"

2. The xaml for the window

dynamic_script_control_window_xaml 

You first declare a namespace for the assembly that has the DynamicScriptControl. Next I have a StackPanel that contains 2 DynamicScriptControls. The first just contains the 2 mandatory properties. We need to know which class you want to instantiate in the file you provide by setting the ScriptFile property. This script file property is a path to your ruby file in my case prefilled_text_box.rb.
The second DynamicScriptControl is one where I want to initialize the control with my own text property. To declare those properties you have to add them to the Attributes collection of the DynamicScriptControl. At this moment it’s not smart enough to know which datatype you give it so you can specify a format string which was necessary in this case because text is a string.

3. The result

dynamic_script_control_window

Michael Foord the author of IronPython In Action will provide the python integration in this control.

There was a release of the Dynamic Silverlight SDK earlier this week which contained the necessary source code files to compile a common DLR for both IronRuby and IronPython.  That is what makes it possible to support multiple scripting languages from the start. 

I’ve hosted the source code on google and you can find that at:

http://code.google.com/p/dynamic-script-control

The IronRuby in Action book went into EAP today

It’s been a bit of journey but my IronRuby in Action book finally went into EAP today. EAP means exactly what it means in the software world, still very much subject to change. This could be seen as a public review :)   I welcome any suggestions you may have.

You can find the book at http://manning.com/carrero
There is also a forum there where you can post suggestions and/or problems you may encounter when running the code samples. I look at it as my issue tracker :)

I’m currently working on a chapter where I build a complete twitter client with IronRuby and WPF (not silverlight as indicated on the current TOC). It is based on Witty but uses IronRuby instead of C# to drive the xaml. Also some storyboards have been replaced by IronRuby instead of by xaml stuff. It’s also not a straight port of Witty because I haven’t really looked at their code apart from the xaml that is.

Happy reading :)

Update: Some people started calling it the “jugs book”

kick it on DotNetKicks.com

Technorati Tags: ,

Using the mini spec framework that comes with IronRuby

I’ve set out to build my first "real" application (still playground material) with IronRuby today and for me no application can be built without having the unit tests or specs to give me that warm fuzzy feeling that things should work. That being said the first thing on my list of things to do is figure out how to use the minispec framework that IronRuby currently uses to write my specs.

Since my application will be doing a fair bit of http requests I want to be able to mock that out so I don’t have to rely on the webservers to be up and running or being online to run the specs.

The first thing I did was copy a couple of files from the tests\IronRuby\Specs directory in the directory where you downloaded the IronRuby source code into (C:\tools\IronRuby) in my case. I copied those files in a specs subdirectory of my application directory. The files we’re going to need are:

  • mini_mock.rb
  • mini_rspec.rb
  • mspec_helper.rb
  • rspec_helper.rb
  • simple_mock.rb
  • spec_helper.rb
  • spec_runner.rb

The next thing on my to-do list is then to change some of the files so that we can run our own specs on our terms.

The first changes I made are in spec_helper.rb. I replace require ‘mini_mock’ on line 18 with require File.dirname(__FILE__) + ‘/mini_mock’

The next bit is in the spec_runner.rb file. I just removed the word core/ in that file because our specs will just live in a directory structure under the specs folder.

now to create the first spec and mock with that spec framework:

I created a folder models in my specs folder. In that folder I created a file spec_test_spec.rb with the following content

require File.dirname(__FILE__) + "/../spec_helper.rb"

describe "Specs" do

  it "should work" do
    # puts "Yay!!! It works"
  end

  it "should mock methods" do
    mock = Object.new
    mock.should_receive :mocked_method, :returning => "Yay!!! I'm mocking"
    result = mock.mocked_method
    result.should == "Yay!!! I'm mocking"
    # puts result
    Mock.verify
  end

end

This just has a test method to see if it will run the rspec syntax and the second is where I tested to see if I could mock methods on objects. In the future we’ll be able to use mocha and rspec for example and then we’ll have a nicer syntax for mocking stuff.  But this will do for now.

Then I opened up a command console and navigated to the folder that contains my application

+ C:\projects\lumpr\src\Sylvester.DesktopEdition\Sylvester.IronRuby\specs

» ir spec_runner.rb models – pass

Specs should work

Specs should mock methods

Total pass: 2 out of 2 examples

I may post an example later this week with some real tests but this shows you how to get going with the mini spec framework to test your .NET stuff today.

Technorati Tags: ,

Page 4 of 26« First...23456...1020...Last »