Saturday, July 9, 2011

Simple trick to make your code more readable

Recently I read the following post by Martin Fowler: http://martinfowler.com/bliki/FlagArgument.html that advocates for making boolean parameters more readable. He gives some great advises, but some times they involve too much code refactoring or produce lots of methods that are basically the same.

What I find very useful is to pass the parameters by name where the meaning of the bool constant is not clear. To illustrate what I mean, I will use an example from his article:

Instead of:
reserveSeat(aCustomer, true);

I would rather use:
reserveSeat(aCustomer, isPremium: true);

This make much clearer what is the meaning of the bool parameter, while reading the code. This way, I try to apply the principle "write read-friendly code instead of write-friendly code" :)

Monday, May 9, 2011

Introducing yourself to ASP.NET MVC

I've been interested in this technology from the first time a heard about it and I am very excited about it. Unfortunately, I haven't got a chance to work with it professional, yet, But still I tried building some application in my spare time and feel very keen on mastering my skills.

Getting started with ASP.NET MVC can be really frustrated in the first couple of days. Especially, for developers that have years of experience with Web Forms. As I already showed in my previous post, building a simple application is really easy.

What confused me the first time was the 'Convention over Configuration' philosophy. This can give you the feeling that lots of things happen by magic. If you are a control freak, you can feel really vulnerable at first glance.

Web Forms concept is to mimic the Win Forms developing style. ASP.NET MVC on the other side is something brand new:
  • No PostBack is used
  • The web pages are no longer physical source code files.
  • Events usage is cut to minimum

When you try building a web site using some NuGet package you think that even more magic applied and things can become really messy. Well, this is the challenge that every new framework brings. A steep learning curve, but also a different angle to look at programming. Even if you not use it in your every day work - it will enrich your mindset and probably help you build better designs and cleaner code.

Usually you don't pay attention to those details until you are stuck with a problem that you have no idea where it came from. Not knowing how the things happen from inside will be you worst enemy when debugging your application and setting your environment.

What helped me is a book called Professional ASP.NET MVC 3.0. It's great, it's written by the people who invented the framework. After the first two chapters you will be able to write your own application. With the rest of the book you will gain deep understanding of the lifecycle of every MVC application. You will know what are View, Controllers and Models, how are defined, how can be extended and how can they do your job. There are lots of examples and some more sophisticated scenarios are discussed. Lots of good insights are waiting there, so ... Enjoy!

Tuesday, May 3, 2011

Building simple ASP.NET MVC Application in 10 minutes using NuGet package

I will try to illustrate a very simple ASP.NET MVC application using NuGet. My goal is to illustrate how easy and straightforward can be to create a simple application. In a few words, I will create a brand new application, which at this stage will be able only to list, create, edit and delete code snippets. I will use Visual Studio 2010, ASP.NET 4 and SQL Server Express in my example.

1. Create an empty ASP.NET MVC 3 application.


2. Create an empty class into the 'Model' folder of the MVC project.


3. Open the Package Manager Console and write the following command:
    Install-Package MvcScaffolding

The output should look like:

'T4Scaffolding (≥ 1.0.0)' not installed. Attempting to retrieve dependency from source...
Done.
'EntityFramework (≥ 4.1.10311.0)' not installed. Attempting to retrieve dependency from source...
Done.
You are downloading EntityFramework from Microsoft, the license agreement to which is available at http://go.microsoft.com/fwlink/?LinkID=211010. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'EntityFramework 4.1.10331.0'.
Successfully installed 'T4Scaffolding 1.0.0'.
Successfully installed 'MvcScaffolding 1.0.0'.
Successfully added 'EntityFramework 4.1.10331.0' to SnippIt.
Successfully added 'T4Scaffolding 1.0.0' to SnippIt.
Successfully added 'MvcScaffolding 1.0.0' to SnippIt.

Remember that this command will alter your project, add some references, etc... You should perform this step in every solution that you want to use this package.

4. Now it's time to define your model class. Open the CodeSnippet.cs file that we previously created and write its definition. Here is a sample:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace SnippIt.Models
{
    public class CodeSnippet
    {
        public int Id { get; set; }

        [Required]
        public string Title { get; set; }

        [Required]
        public string Body { get; set; }
    }
}

Note that we have marked the 'Title' and 'Body' property as required. This attribute is defined in the System.ComponentModel.DataAnnotations and you can find there some other useful attributes that will help you to validate your Model class.

5. And this is the magic step ... Open your Package Manager Console and write the following command

Scaffold Controller CodeSnippet

And the output will look like:

Scaffolding CodeSnippetsController...
Added database context 'Models\SnippItContext.cs'
Added 'CodeSnippets' to database context 'SnippIt.Models.SnippItContext'
Added controller Controllers\CodeSnippetsController.cs
Added Create view at 'Views\CodeSnippets\Create.cshtml'
Added Edit view at 'Views\CodeSnippets\Edit.cshtml'
Added Delete view at 'Views\CodeSnippets\Delete.cshtml'
Added Details view at 'Views\CodeSnippets\Details.cshtml'
Added Index view at 'Views\CodeSnippets\Index.cshtml'
Added _CreateOrEdit view at 'Views\CodeSnippets\_CreateOrEdit.cshtml'

And all is done!

Let's look what actually happened here.
  • Since, I choose Razor to be my default view engine, all the generated view are written with Razor.
  • Open your database server and you will notice that a new database is created. It probably will be named 'SnippIt.Model.SnippItContext'. Of course, you can tweak a little the Scaffolding command and change this name.
  • While we are still in the database, take a look at the 'CodeSnippets' table that is also auto-generated. As you can suppose the 'Title' and 'Body' columns are marked as not nullable. What is more interesting is that the 'Id' column is marked as primary key is set as Identity with seed=1 and increment=1. The Scaffolding package is smart enough to do this by default.
  • Now let's open the site itself. All the work here is already done for you, too. There is a 'Create new' link and 'Edit', 'Delete' and 'Details' links for every code snippet that you have added.

    While you add your first code snippet you will notice that there is validation added automatically for your required fields and the primary key column is hidden from the user interface perspective. When you try to delete an entity a nice confirmation screen is displayed. Everything is almost as I would do it, just a little more work is needed to make this application a real world web site.
  • If you are curious enough and open the CodeSnippetController.cs file in the Controllers you will again notice that your entities are retrieved and saved by the Id column. It will look similar to:

            //
            // GET: /CodeSnippets/Edit/5
     
            public ActionResult Edit(int id)
            {
                CodeSnippet codesnippet = context.CodeSnippets.Single(x => x.Id == id);
                return View(codesnippet);
            }
    
            //
            // POST: /CodeSnippets/Edit/5
    
            [HttpPost]
            public ActionResult Edit(CodeSnippet codesnippet)
            {
                if (ModelState.IsValid)
                {
                    context.Entry(codesnippet).State = EntityState.Modified;
                    context.SaveChanges();
                    return RedirectToAction("Index");
                }
                return View(codesnippet);
            }
    

    Also, the post method is strongly typed, which is great and will help you in writing more durable code.

All this was done in 5 simple steps and 15 minutes (including the time to read this post). Most of the actions can be customized to fit your specific needs. This Scaffolding package will save a lot of your precious time by doing the dummy work and leave you to deal with the business logic that you have to implement. It guarantees that the generated code is consistent in all layers - database, presentation, etc. I hope this will be useful to you.

Monday, April 25, 2011

Refactoring: Improving the Design of Existing Code

It is a great book from Martin Fowler & Co. What I found most useful are all the examples that are given for almost every refactoring that is described. The examples are simple with not much details to distract you, but still they are excellent illustrations of the topics. And don't fool yourself - they might be written in Java, but almost all of them are actually language agnostic and will apply to your favourite object oriented programming language.

In my opinion the concept of the Bad Smells in Code should be taught in the schools and universities as a separate course. Some of them are taught indeed, but this topic should be studied much more in depth and with much more attention to the details. The skill to know when the code needs refactoring is something that comes not with reading and studying, but with lots of practice and experience. It's never too early to start building this knowledge and probably this process will continue until you stop being developer. It's great that with this book you can kind of get a sense, when something is wrong with your design.

What is really interesting - the authors talk about tools that should support and help the developer in refactoring his code. Well, most of their ideas are already reality! At least Java and .NET have very advanced software development environments and what of the things that are done manually in the book are just a few keyboard clicks away.

To sum up, I think this book is a must for every developer, especially for those that work with existing and legacy code. 

What's next? After Refactoring: Improving the Design of Existing Code I think I should deepen my knowledge in design patterns.

Sunday, February 27, 2011

Data migration for dummies

For the last month I've been working on data migration between three different systems. This turned out to be quite hard task and now I learned some valuable lessons for me.


What seems to be our biggest mistake was to underestimate this task. Trying to migrate data from to distinct systems that are outside your control to a system that is just taking its first breath can be very frustrating for the all people and stakeholders involved. Plan it carefully with frequent milestones to meet. At every milestone try to communicate the progress with the future consumers of your system in order to catch possible incompatibilities as early as possible. Expect the unexpected and always keep a time buffer.


To start you need to research all the possible ways to get the data from the source database. In our case we couldn't get a dump of the source databases from our vendors, so we had to deal on our own. We had to deal with custom report functionalities in the web sites and a web services that was exposed for writing 3rd party tools. Its important to get as much data as you can, sometimes we could get some fields only through the reports and others only from the developer's API. It is always nice if you get to an unique identifier for every object in the source database. This way future fixes and data deduplication is much easier.


Before start writing your migration logic make sure that you have mapped all nomenclatures from the source system into the target system. Often, this means that a business decision should be taken. If you plan to do the migration using SQL scripts ( as we did ) - make sure to improve your skills in SQL. Some basic level might be enough when dealing with ORM and writing simple custom queries from time to time, but preparing a data migration scripts is not an easy job and you will make use of some additional knowledge for sure. 


Do not neglect the quality of the code you write. Sure it will be used only one time and probably deleted for ever after that, but writing and debugging spaghetti code for more than a month will be much easier if you follow your code policy as you do in your every day development. Do not hard code constant values if there is a business logic in them (statuses, types, etc...), use variable to review what is the meaning of the constants. Performance matters, too. It makes difference if your migration will take a minutes or a day. After all, you are dealing with live data and sometimes the business cannot be stopped for a day in order to perform a migration. Also, make sure that you have source controlled your scripts - you can freely deleted it after the migration is over.


In our case pair programming was a huge success during this month. The main reason is that the work is hard to be separated in smaller task that can be solved concurrently. Also, usually the logic of migration is harder to analyzed and debugged, so having additional pair of eyes to help you is much more productive than working separately. 


You will probably need SQL-abled tester in order to verify your work. Testing data migration without querying the database is like looking for a needle in a haystack. The tester could be another developer that was not involved in your migration process. Also, plan your scripts in order to be revertible if failure occurs in every step of the migration, as much as possible. All kind of errors are possible when merging to separate systems - data truncation errors, data cast errors etc. Use transactions and plan your script carefully in order to handle this kind of errors. What can help you here is to be proactive and test your migration script with live data both from source and the target system.


In our case when we had a fixed deadline to meet, making fixes in the last day or two turns out to be a disaster. Avoid introducing big changes in your logic in the last days. On contrary, try to plan your migration in a way that allows applying fixes later, after the migration is done.


Well, these are the tips that could saved me a lot of time and hopefully you can make use of them. And finally, prior starting your work evaluate the effort you are going to spend and consider migrating the data by hand. Some times you can spend more resources and time in writing scripts and code, than manually migrating your data. 


Furthermore, writing SQL script can be very frustrating for a .NET developer and this will of course affect the performance and quality of his work. I happened to be in this position and sometimes is critical to be able to motivate yourself and keep your spirit up. 

Sunday, January 30, 2011

Software engineering on demand

I'm just about to finish Refactoring to Patterns and it made me think about experience with applying design patterns. I have attended a few university courses regarding design patterns and every time I learned something new - I was so eager to implement it that I probably have made some mistakes.

The main idea in this book is to apply design patterns only when you have to. Design patterns are great for solving well known problems and they are tool that every software engineer should have in its toolbox. But when it comes to solving problems that are not there you can really shoot yourself in the foot using design patterns. From my experience as a professional developer I often have to maintain and extend someone else's code. And this part of the job. Whether this colleague is no longer in the company or is currently working on a different project, you can't escape it. I've noticed that over-engineering is as frequent mistake as under-engineering. And it can cause a lot of damage to every project. I have caughted myself very eager to try some new technology or pattern where it is not actually necessary. As a result - the project gets harder to maintain and extend and probably there is a severe performance penalty.

The best way to avoid this problem is to apply patterns and technologies on demand. Do not try to predict future business requirements and do not fulfil them without any need. You can always refactor your code later when it is actually needed. And this book will give you some guidelines how to perform refactoring in some common cases.

Still, we are all human - how to overcome this affinity to try and implement new stuff as soon as you meet them. Use the sandbox pattern - make yourself a place where you can try, test and evaluate your new ideas. After all not every idea that you read can and should be applied - some are worthless, some are priceless and some - it depends.

The best things are as simple as they should be. We don't kill flies with nuclear weapons. So, don't use abstract factory and strategy pattern to write a "Hello, world!"

Friday, January 14, 2011

New user group in Sofia: Web Platform

Yesterday new user group was born here in Sofia, Bulgaria. Its domain is defined pretty wide - Web Platform, which means that very wide range of topics will be covered. First meeting was about "Building web sites with new technologies" and included ASP.NET MVC3, .NET Nuggets, SQL CE, Web Deploy, IIS Express and so on.


What was new to me was the nuggets and the IIS Express. Nuggets looks like a big time saver, I always like to focus on business logic and keep the plumbing part to minimum and from this point of view .NET is far behind some other technologies. I am very eager to try the scaffoldings for MVC and to see how they work for a real life application.


I am very happy about this new user group, since its domain is very close to my current job profile and I think that it will be of great use to me. After the first meeting, my strongest recommendation is to get deeper into the topic. You cannot cover all this technologies in a session of two hours. And we have already seen a lot of light demonstrations with most of them. What we need is a deeper look, how the things actually happens. I would like to see a real world showcase of how these things work together.


I wish all the best to this new user group, I hope to meet some kindred spirits there. If you want to join, here is a facebook page. Next meeting - HTML5. Since, there is no official web page it is up to us to spread the word, so - tweet up :) !

Wednesday, January 12, 2011

Craftsmanship, What it is really all about?

I've been interested in craftsmanship for two months already. I read a couple of books, added some blogs in my rss reader and followed a bunch of twitter accounts. Now, after reading all this things I started asking myself - What we are talking about here?

By reading the Manifesto of Software Craftsmanship, one can say that it's something that only "the chosen one" can practice. By signing the Manifest you feel like entering into a secret society with sacred mission. Well, I don't feel so pathetic about it. In my eyes, people are getting too romantic here. After all, we are working in modern society with market society - we need to working for a living. And customers don't care if you are modern knight armed with wireless keyboard. They only want a working piece of software.

Still, It's up to you to be in a condition to deliver this working piece of software. How to improve your skills? How to stay in touch with latest technologies, that come up everyday? How to solve hard problems? Here craftsmanship can give you priceless advices (of course, you don't have to be an apprentice to follow this steps nor craftsman to give them). Apprenticeship should keep you in good shape and make better and better everyday. Without any arrangements to keep you on the track, you professional career is likely to end pretty soon in our dynamic and constantly changing industry.

To sum up, what craftsmanship means to me? The values that craftsmanship has are those to help me improve myself. Everything apart from my professional development, all those ego trips that people tend to follow are pointless and should be ignored.