Code Elegance

Avoid DataGrid*

A lot of software houses are migrating their application to the (new) WPF framework to take advantage of all the new stuff (layout models, controls, templates, styles,…)

WPF leave to the developers the freedom to realize appealing user interfaces that support an alternative interaction model not tied to the old windows controls. The benefits for the end user are countless, more productivity, easier interaction, information “find-ability”, and so on…

But what happens most of the times?

As soon as a new developer opens Visual Studio he asks: “Where’s the DataGrid?”

Why?? Is it possible that the only way that a developer knows to show some data on the screen is to put it in a grid?

I developed a bunch of WPF applications and only in one case I used the DataGrid, I always used ListBoxes, ItemControls, StackPanles….using a template to customize their appearance to show the most important information and to give the user the ability to drill down into the details when needed.

So, please, please, with WPF we have the power in our keyboard don’t use datagrids to show your data, think about your user!

The web is full of examples that don’t use the DataGrid (Google and Amazon for example) so don’t be lazy, take time to design a better user interface!

 

* No datagrid was used to write this post

No comments

Are we sure that goto is dead?

Last week, during a code review I found this code (I cut some lines to keep the post short)

 

// [Cut]
case USER_AGENT:
     // [Cut]...various code....
     goto default; //we want it to be added to serverVariables
case CONTENT_TYPE:
     // [Cut]...more code (with some "if")
     goto default; //we want it to be added to serverVariables
 case USER_LANGUAGE:
     ParseUserLanguage(variableValue);
     break;
 default:
     ServerVariables.Add(variableName, variableValue);
     break;
// [Cut]...continue...

No words.

 

Technorati Tags: ,,
3 comments

Working with Legacy Code

I give special attention to code readability and good design when I write programs, these are two metrics that I care about. I like the idea that the team members can read code and understand what the code does.

Today I spent two hours to find a silly bug. I dig with the debugger until the code near the bug, and in that code I have this instruction: 

collection.Add(currentKey, newValue);
 
The name of the method talk for it, the parameter are clear and so I didn’t step into the method to view what happens thinking that the error was in another location. Then after 1,5 hour of search without result I decided to step into the Add method and this is what I found: 
public void Add(String key, MyObject value)
{
  if (value == null)
  {
    Remove(key);
  }
  else
  {
    if (ContainsKey(key))
    {
      this[key] = value;
    }
    else
    {
      _base.Add(key, value);
    }
  }
}
The big problem here is that Remove that live in an Add method!
This paradoxical situation create a big headhake, why an Add method should remove one element from the collection? If you decide to call it Add there will be a reason, why?
 
It is one of most important things to  remember when you write code: the name of a method must meet it’s implementation! It’s simple but very valuable!
 
 
No comments

The smell of Copy&Paste

I often read phrases like these “adding a new module to our application is very simple, just copy&paste some code” or “to create a new class you have to copy&paste from an old class”. In my opinion this there is something wrong about this. Copy&Paste is a smell. If you need the Copy&Paste to add some functionality to your application means that you are duplicating your code and then you will be in trouble when you need to  maintain it.

What could you do? When the second Copy&Paste happens, stop, read your code, extract a class and “encapsulate what varies“.

No comments

Random thoughts on TDD

Here it is a flow of random thoughts about Test Driven Development. Naturally IMHO.

  • TDD is not about testing application is about design application, and have a (nice) side effect that creates a suite of tests
  • The Test obtained with TDD does not cover all the cases, but you can write more test when you need new cases or find a new bug
  • The code written in TDD is less and it focused on the needs
  • The code written in TDD is more orthogonal and simpler to maintain
  • The first red bar is the signal that the test is testing something (and it is very important)
  • The tests cannot contains if, switch, etc…so they need to be simple
  • Learning TDD is difficult: the impact is the same that you have when passing from structured programming to Object Oriented Programming
  • Learning TDD requires times and perseverance
  • You cannot learn TDD reading articles and books, you must try it
  • Every piece of code is testable
  • Testing that the tone of red is that the user likes is not a task of TDD
  • With the right use of Mock Objects you can test that the gradient is correctly set
  • The test cases comes from the User Stories written with the customer and then they responds to requirements
  • The Team that use TDD must be skilled enough…and Pair Programming helps a lot
  • The Test code is bigger than the tested code
  • TDD force you to think about what you’re writing
  • TDD force you to declare what you need before writing something
  • TDD put the developer to the client side of his code and so help him to write better interfaces
  • TDD helps you to write cleaner and decoupled code
  • The Integration Tests helps you to understand how your class interacts with others
  • When you need to refactoring your code you can start from tests
  • Tests are documentation: read a test is a great help to understand how to use your class
  • TDD does not guarantee that you code doesn’t contains bugs
  • TDD guarantee that old bug doesn’t come to life again
  • The start up cost of TDD is write off during the life of the project
  • The TDD reduce a lot the time needed for manual testing
  • With TDD the debugger is used like a surgery tool
  • TDD helps you to simplify the problem dividing it in small part and every solved part is a small step to the final solution
  • Every test case is a single functionality: if one test fail you have only one problem
  • If  you have two red test you have two distinct problems
  • Every test add a new functionality to the code
  • Is difficult to test multi threading applications
  • It’s expensive testing the UI, but there are patterns that decrease the UI code (MVP/MVC)
  • The integrations test against database help you to know if the database and the queries are ok
  • TDD force you to written less encapsulated code to  make it testable
  • TDD force you to write independent object and to inject all the dependencies
  • Write test after code is not always possible
  • TDD is not a silver bullet (but it’s help a lot!)
No comments

TDD as a metodology

TDD is often considered a practice for writing test. It isn’t: TDD is a design practice.

Time ago, while developing an application, it happens that I need to write a resource schedule algorithm. I’m not an expert in schedule algorithms, I read some paper, I know that exists various methods more or less complicated, but the one that I need was quite simple and so I preferred to write it by myself using small steps and TDD that helps me a lot.

I collected the specification from customer, wrote some stories and ordered the stories by complexity, then I begin to write the first test.

The first test try to schedule a single resource always free on a unlimited and free time lap. When this was green I wrote another one with 2 resources, then 3, then N.
Then I wrote other tests that reduced the available time, others that introduce overlapping schedules, to arrive to a test that reproduce real world cases with N resources on N projects with small time available.

What I did is to add a little complexity on every new test and having all the previous green test help me to stay on track and to keep the algorithm right. On every green test I did some refactoring to keep the design clean.

After 2 dozens tests I had the full algorithm ready to use with a suite of test that proved it. I don’t know if this is the best algorithm, I know that it is not the fastest one but I know that it satisfy the customer requirements.

Naturally after the deployment the customer begin to use it and she asked for some modification. If in general this kind on modification on this complicated algorithm is very difficult and dangerous to implement, if you have a suite of test that in a bunch of seconds verify that everything is going right you can write the new requirements quite relaxed adding new tests.

Here the TDD has a double value: first it helped me to resolve a complex problem step-by-step keeping always under control the status of the project, second it helped the introduction of new requirements requested by the customers.

2 comments

On writing good tests

When you start with Unit Testing it’s difficult to write good test. My first test were very ugly, a lot of code to setup the mock objects and a lot of asserts in the same test. Test written in this way are difficult to maintain and every little change that break the test leave in the developer a bad feeling and a diffidence in the Test Practice. He need a lot of time to find  out what’s break and why it is red.

Take a look at the following example:

[Test] public voidConstructor_ShouldDoSomeThingOnViewAndModel()
{ IDtoMapper mapper =MockRepository.CreateMock<IDtoMapper>(); IMyView view =MockRepository.CreateMock<IMyView>(); IMyModel model =MockRepository.CreateMock<IMyModel>(); IList<DomainModelData>dummyData = new List<DomainModelData>(); IList<DtoData>dummyDto = new List<DtoData>(); view.Expect(v => v.Save += null).IgnoreArguments(); model.Expect(m =>m.GetData()).Return(dummyData); mapper.Expect(m =>m.ToDto(dummyData)).Return(dummyDto); view.Expect(v =>v.SetDataContext(dummyDto);
  new MyPresenter(view, model, mapper);
  view.VerifyAllExpectation();
  model.VerifyAllExpectation();
  mapper.VerifyAllExpectation();
} 

It smell, isn’t it? What are the problems?

This test is testing too things, then is not readable and it depends on too many objects. That means that if in the next weeks I need to change it, it take too much to understand what it does and if it become red I can figure out why.

The direction in which I’m going is in where I have a lot of simple test in which every test use only one mock object and verify only one functionality.

So that test become four tests:

1) One that verify that the presenter is correctly subscribed to Save event from the view
2) One that verify that the presenter use the model to get the data to visualize
3) One that verify that the presenter calls the method ToDto on the mapper to convert the Domain Model Object in a Data Transfer Object to pass at the user interface
4) One that verify that the presener pass to the view the DTO with data to visualize

It seems hard? Not really:

- The new tests are more readable
- The new tests documents much better the functionality
- If a test fails I know exactly what doesn’t work
- Write 4 tests instead fo the one like the above one is not so hard ;-)

The result can be like this:

[Test] public void Constructor_ShouldSubscribeToViewEvents() { IDtoMapper mapper = MockRepository.CreateStub<IDtoMapper>(); IMyView view = MockRepository.CreateMock<IMyView>(); IMyModel model = MockRepository.CreateStub<IMyModel>(); view.Expect(v => v.Save += null).IgnoreArguments(); MyPresenter presenter = new MyPresenter(view, model, mapper); view.VerifyAllExpectation(); } [Test] public void Constructor_ShouldGetDataFromModel() { IDtoMapper mapper = MockRepository.CreateStub<IDtoMapper>(); IMyView view = MockRepository.CreateStub<IMyView>(); IMyModel model = MockRepository.CreateMock<IMyModel>(); IList<DomainModelData> dummyData = new List<DomainModelData>(); model.Expect(m => m.GetData()).Return(dummyData); MyPresenter presenter = new MyPresenter(view, model, mapper); model.VerifyAllExpectation(); } [Test] public void Constructor_ShouldGetDtoUsingMapper() { IDtoMapper mapper = MockRepository.CreateMock<IDtoMapper>(); IMyView view = MockRepository.CreateStub<IMyView>(); IMyModel model = MockRepository.CreateStub<IMyModel>(); IList<DomainModelData> dummyData = new List<DomainModelData>(); IList<DtoData> dummyDto = new List<DtoData>(); mapper.Expect(m => m.ToDto(dummyData)).Return(dummyDto); MyPresenter presenter = new MyPresenter(view, model, mapper); mapper.VerifyAllExpectation(); } [Test] public void Constructor_ShouldSetDataContextOnView() { IDtoMapper mapper = MockRepository.CreateStub<IDtoMapper>(); IMyView view = MockRepository.CreateMock<IMyView>(); IMyModel model = MockRepository.CreateStub<IMyModel>(); IList<DtoData> dummyDto = new List<DtoData>(); view.Expect(v => v.SetDataContext(dummyDto); MyPresenter presenter = new MyPresenter(view, model, mapper); view.VerifyAllExpectation(); }
No comments

The enviromentalist code: Reduce, Reuse, Recycle

The famous three R of the Reduce Reuse Recycle motto are very much used in the enviroment field, but they can also be applied to the programming world.
A good programmer takes care of the ecology of his own application, since the code of the application is the enviroment where he spends a lot of his working time. If the application is developed respecting the enviroment where it runs, it is surely an advantage for the whole virtual ecosystem.

Reduce: reducing the code. It seems strange, but it is often more difficult cancelling some code than adding some new one. Adding too much code is often due to overengineering, by implementing functions that are not stricly necessay, and that do not give an additional value to the final customer. It just contribute to pollute the application, making it difficult to maintain. Therefore reduce the code dimension brings to remarkable results: simplification of codebase, ease of maintainance, and in general an improvement of performance.

Reuse: do not invent the WHEEL every time. Writing classes that can be used again or using library of third parts that already do the requested task, is a good habit. Using a class, that was already writtne, brings advantages boths in terms of realization time than in terms of debugging time (hoping that the class you are reusing is bug free…)

Recycle: it may sometime happen that a class could be reused, but it is not exactly as we need. So, sometimes by using CTRL-C, CTRL-V you just introduce duplications and polluted code. If you do some refactoring you could reuse a part of the code already written adapting it to the new application. Also in this case the advantages are a lot: the quantity of the code we are adding is lower, we avoid to create classes that are too alike (or even identical) and of course we spare time and we do not pollute.

I like this idea of the enviromentalist code, as in general all the enviromentalist attitude.

What do you think about it? Do you feel code enviromentalist?

No comments

From Database to UI and back

Which approach do you use in developing applications?

Years ago, for me, was a must that the develop of new application begin from the database and over there I design the DAL and up till the user interface. For this reason the firsts days was dedicated to the design of the database. What I got was an application based on “Transaction Script” or “Table Data Gateway” with their pros and cons.
At that time the database was the most important thing in my applications.

The problem with bottom-up approach is that it takes you to create a myriad of “micro-methods” that makes very tedious developing other layers above DAL. The classic “error” is to create all the CRUD operation for every tables in database, discovering later that a lot of them are useless or that they force the other layers to know the database structure (for example they need to know the right insert order to not break the foreign constraints).
The other smell was that the design of my application was not very Object Oriented, the only thing that I used was a little bit of inheritance in the DAL to reuse some code dedicated to manage the database connection.

In 2003 i read a book that change the life to a lot of developer “patterns of enterprise architecture”.

After having read it I understand that something in my approach to  design application should be improved: I discovered the Domain Model.
Then I begin to think at my applications starting from Domain Model and once the DM was ready I start with Database and User Interface at the same time.

Now I’m in a transition period and I feel to start my applications from User Interface. I know that the UI is for the final user the most important thing of the application (stated that it works), not from a aesthetics point of view rather from an interaction and usability point of view and the way the data is displayed on the forms.
The first thing I do is to design (on paper) the mockup of the UI thinking about the interaction work-flow and the data that should be displayed. From the interface I go down to the Domain Model and then the Database.

The problem with starting from Domain Model is that your User Interface design is often binded to it and is not free to achieve the user’s needs. So starting from UI is a natural way to obtain what the customer really want, maximizing the usability and the fruibility of information.

This is not a proofed methodology for me, I’m trying this way in these months. For now I can certainly say that the mockup on paper likes a lot because the user can easily try to imaging how the interaction with the software will be and he can modify the stories of writes a new one. The Domain model grow in a more natural way guided from the functionality to implement.

Does this state that the DM and DM are less important? Absolutely not, but the user don’t bother them. 

No comments