Fluid Code
A blog about refactoring, .Net and all things agile by Danijel Arsenovski

It’s NOT OK to cut corners, but it’s OK to cut features.

February 15th, 2010 by admin

Just had my say in a discussion on LIDNUG group on LinkedIn. The question put for discussion was “Is it ok to cut corners to meet a deadline?”. Most of answers (or at least the way I interpreted them) say that you generally shouldn’t, but that sometimes you just might have to compromise, especially if that can be justified from business point of view. I think that from agile point of view, the reply is quite obvious. Here is what I had to say:

It’s NOT OK to cut corners, but it’s OK to cut features.

I guess that sums a great deal that agile development is all about! You do very short iterations but you do them properly (no cutting corners). Once you start with new iteration, your client can invent new, eliminate old, reprioritize all features etc. (This is what I actually mean by “cutting features”.) As it happens, most of the time the client will realize that some features are not needed, that other are, and will accept that he can live without “nice to have” as long as the core features are done right and without bugs. As a matter of fact, it is difficult (no to say impossible) to know all the features you will need right at the start of the project. So, why should you cut corners to deliver a feature you are not even sure it’s needed? This doesn’t necessarily have to do with 80-20 rule, it’s more of looking at the software as the “work in progress”. You can release the first version once you have implemented the minimum set of core features that do something useful.

Once you and the client change the mentality from “features initially put into the contract” to “real business value delivered”, you will have no need to cut corners. Switching to short iterations and having users participate in planning and accepting results of each feature had a profound effect on how my team is operating and had enabled us to really uphold the quality aspect of software.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • Reddit
  • Digg
  • StumbleUpon
  • Bloglines
  • Google Bookmarks
  • Y!GG

Posted in Agile | No Comments »

SOLID design principles explained

December 28th, 2009 by admin

Take a look at this post at lostechies.com.
Good one :)

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • Reddit
  • Digg
  • StumbleUpon
  • Bloglines
  • Google Bookmarks
  • Y!GG

Posted in Uncategorized | No Comments »

Telerik announces (yet another) .NET refactoring tool

December 3rd, 2009 by admin

Does this say anything about refactoring adoption among .NET developers? Maybe. It definitely says something about Microsoft refactoring tools state of the art (thanks Jeff). Refactoring support in Visual Studio 2010 lags miles behind refactoring support in free tools like Eclipse or Netbeans. JustCode features here.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • Reddit
  • Digg
  • StumbleUpon
  • Bloglines
  • Google Bookmarks
  • Y!GG

Posted in Refactoring, Refactoring in C#, Refactoring in VB, Visual Studio 2010 | No Comments »

Visual Studio and TDD: Better late than never

September 11th, 2009 by admin

After hearing that UML is touted as a “next big thing” in Visual Studio 2010, I must admit I was less than elated. Since I am hardly a “new kid on the block”, I freely admit that I remember that quirky diagramming tool called Visual Modeler that shipped with Visual Studio 6.0. (“Ten years after” already?). Had it been 1999, I guess UML might even sound, well… intriguing.
Fortunately, I recently came across this video:
TDD with Visual Studio
Believe it or not, but 2010 version of Visual Studio should finally provide a lot less friction for TDD developers. It can generate class and member stubs based on client code. More surprisingly, there is an integrated Test Runner that does not “fall apart” (just pick your song!) if you have tests written is some 3rd party unit testing frameworks. (On the video Karen shows executing MbUnit tests with VS Test runner.)
TDD is hardly a news these days, but hardly feels as passé as UML!

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • Reddit
  • Digg
  • StumbleUpon
  • Bloglines
  • Google Bookmarks
  • Y!GG

Posted in Agile, Programming, Visual Studio 2010, tdd | No Comments »

YAGNI is not SLACKING!

June 4th, 2009 by admin

YAGNI is a clever rule. It says that by doing less your are doing yourself and everyone else a favor. In some schools of Agile Thought like Lean it has become a whole philosophy (although they are more keen on some strange sounding Japanese words, mind you).

Only a decade or so ago, general approach was quite different. You’d try to make your system as encompassing, flexible and configurable as possible. You’d design your system for tomorrow’s needs.

I will give you a quick example. Imagine you need to program a feature on your website where you export some data to an excel file. In the old days, you’d analyze the problem, design your classes let’s say in a form of hierarchy where ExcelExporter and PdfExporter inherit BaseExporter class. You do not need to export data to pdf just yet, but you think you might need it some day, so you better be ready.
These days, however, you live in the present. You just program ExcelExporter. If one day you need pdf export feature, you will reorganize your classes so that both ExcelExporter and PdfExporter inherit BaseExporter class that contains some features common to both child Exporter classes so you can avoid duplication. If you never come to need this feature, you leave your ExcelExporter alone. You will implement new features as they are needed: just-in-time.

But there is a catch. In order to be able to move just-in-time, you should have a well designed, mercilessly refactored code covered with tests. Without refactoring or automated testing you are probably better of doing things the old fashioned way.
I think YAGNI is great and I try to follow YAGNI mercilessly. However, sometimes I hear YAGNI principle invoked in a way that it is clearly misinterpreted. For example “Maybe you do not need to refactor this code just yet” or “Maybe you do not need all those unit tests”. Thing is, to be able to do YAGNI, you need to have your code refactored and covered with tests. You need continuous integration and automated builds. Without these practices, once you need to implement a new feature in JIT fashion, things will inevitably start to break. One way to avoid “Maybe you do not need good quality software” kind of dilemmas is to make practices like TDD, refactoring and continuous integration integral part of your development process. Then, there is no need to think that you might leave out unit tests; since you are doing TDD these are in place already; since you refactor all the time, then there is no way to leave it out.

Remember, YAGNI applies to features, not to quality! One way to use YAGNI properly is to think about Technical Debt. Is the decision NOT to do something resulting in Technical Debt? Technical Debt has to be payed off with interest and with software rates are extremely steep. If you are getting into debt, you are not YAGNI, you are plain’ SLACKING!

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • Reddit
  • Digg
  • StumbleUpon
  • Bloglines
  • Google Bookmarks
  • Y!GG

Posted in Agile, Programming, Refactoring | 4 Comments »

Another Free C# Refactoring Tool from Devexpress

May 26th, 2009 by admin

I just realized I have failed to mention this on time, but I think the news still deserves a post. Developer Express have released another free C# tool that includes “a fresh selection of hand-picked features taken from CodeRush and Refactor! Pro.” You can download the tool from this URL and read more about the features it offers here.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • Reddit
  • Digg
  • StumbleUpon
  • Bloglines
  • Google Bookmarks
  • Y!GG

Posted in Refactoring in C# | No Comments »

Map two classes with one-to-one relationship to a single table in LINQ to SQL.

May 19th, 2009 by admin

Some time ago I came across the following problem. After performing a refactoring on a class and extracting associated class, I had to make my classes map to a single table in database. For that purpose I used the usual  Association attribute and ended up with a code akin to this:

[Table()]
    class Customer
    {
        private Address address;

        [Column(IsPrimaryKey=true, IsDbGenerated=false)]
        public String SSN
        {
            get;
            set;
        }

        [Column]
        public String FirstName
        {
            get;
            set;
        }

        [Column]
        public String LastName
        {
            get;
            set;
        }

        [Association(ThisKey="SSN", Storage="address", OtherKey="SSN")]
        public Address Address
        {
            get
            {
                return address;
            }
            set
            {
                address = value;
            }
        }

    [Table(Name="Customer")]
    class Address
    {
        [Column(IsPrimaryKey = true, IsDbGenerated = false)]
        public String SSN
        {
            get;
            set;
        }

        [Column]
        public string Street
        {
            get;
            set;
        }
    }

        static void Main(string[] args)
        {
            DataContext context = new DataContext("Data Source=XYZ;Initial Catalog=TEST;Integrated Security=SSPI");

            Customer customer = new Customer{
                SSN = "123",
                FirstName = "First",
                LastName = "Last",
                Address = new Address{
                    Street = "My Street",
                    SSN = "123"
                }
            };

            Table customers = context.GetTable();
            customers.InsertOnSubmit(customer);
            context.SubmitChanges();
        }

//DB DDL
CREATE TABLE [DBO].[CUSTOMER](
        [SSN] [NVARCHAR](50) NOT NULL,
        [FIRSTNAME] [NVARCHAR](50) NULL,
        [LASTNAME] [NVARCHAR](50) NULL,
        [STREET] [NVARCHAR](50) NULL,
 CONSTRAINT [PK_CUSTOMER] PRIMARY KEY CLUSTERED

As you can see, a single Customer has a single Address. Customer with corresponding Address maps to a table Customer. Everything works well, until you try save new instances. You get the following error: Violation of PRIMARY KEY constraint ‘PK_Customer’. Cannot insert duplicate key in object ‘dbo.Customer’. If you try to execute the code and you should be able to reproduce the error.

Solution

In the end, it is all just about method call order.
The solution is the commit the root object first (Customer) in our example, without related object (Address). This way, the instance of related object is created also, with all properties empty.
Second step is to set the properties of related object. Here the important detail is not to create the instance of related object, since it has been already created by linq2sql. Then, you commit changes again and this time the related object is also updated and saved.
It would probably not work if you had to enforce not null constraint on some of the related object properties.

Here is the same example fixed to work without error.

class Program
    {
        static void Main(string[] args)
        {
            DataContext context = new DataContext(
                "Data Source=XYZ;Initial Catalog=TEST;Integrated Security=SSPI");
            Table customers = context.GetTable();
 

            Customer customer = new Customer
            {
               SSN = "SomeSSN",
               FirstName = "First",
               LastName = "Last"
            };
            customers.InsertOnSubmit(customer);
            //Save customer first, this will also create the Address
            context.SubmitChanges();   

            //Now Address is not null anymore, so it will be updated
            //Linq2SQL will not try to insert new row
            customer.Address.Street = "Updated";
            context.SubmitChanges();

            //get one instance for demo purposes
            Customer saved = (from all in customers
                                 select all).First();
            Console.WriteLine(saved.Address.Street);

        }
    }

    [Table()]
    class Customer
    {
        private EntityRef
address;   [Column(IsPrimaryKey=true, IsDbGenerated=false)] public String SSN { get; set; } [Column] public String FirstName { get; set; } [Column] public String LastName { get; set; } [Association(ThisKey="SSN", Storage="address")] public Address Address { get { return address.Entity; } set { address.Entity = value; } } } [Table(Name="Customer")] class Address { [Column(IsPrimaryKey = true, IsDbGenerated = false)] public String SSN { get; set; } [Column] public string Street { get; set; } } //DB DDL CREATE TABLE [dbo].[Customer]( [SSN] [nvarchar](50) NOT NULL, [FirstName] [nvarchar](50) NULL, [LastName] [nvarchar](50) NULL, [Street] [nvarchar](50) NULL, CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • Reddit
  • Digg
  • StumbleUpon
  • Bloglines
  • Google Bookmarks
  • Y!GG

Posted in Programming | No Comments »

Professional Refactoring in C# and ASP.NET published!

April 15th, 2009 by admin

While still under “Upcoming” tag on wrox.com, you can already order Professional Refactoring in C# and ASP.NET from Amazon and take a look at some excerpts from the book at wrox.com. Enjoy!

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • Reddit
  • Digg
  • StumbleUpon
  • Bloglines
  • Google Bookmarks
  • Y!GG

Posted in Refactoring in C# | No Comments »

Code, aesthetics and symmetry

March 23rd, 2009 by admin

It might sound funny to mention aesthetic qualities like symmetry when speaking about source code. It is exactly the principle that Kent Beck mentions in his book Implementation Patterns. It has to do with inner workings of our brain. These qualities are the way to communicate with fellow programmer on another level. I’d say symmetry might be put under more general “Consistency” principle that Abrams and Cwalina are so keen about. And it is definetly in the spirit of Principle of least surprise.

What got me thinking about it is a bug I investigated recently that had to do with two base java classes: java.net.URL and java.net.URLConnection. The symptom was a generation of leaking file handles, resulting in server hanging after few hours of operation.

Take a look at this java code:

           URL url = configuration.getURL();
           URLConnection connection = url.openConnection();
           long date = connection.getLastModified();

Now, I’d typically put method open on the connection object. If you take a look at URLConnection, you will see that the class does not have the close method. That’s all right, following the symmetry principle, it would be then consistent to place closeConnection method inside the URL class. Alas, neither the URL has the method that closes the connection!

This was the source of our bug. The programmer had to open the connection in order to read getLastModified. But, since neither URL nor URLConnection had the close method, he “forgot” to close the connection. The solution is to do the following after reading the date:

InputStream stream = connection.getInputStream();
stream.close();

No wonder the programmer forgot to close the connection; there was no obvious method he could call to do so. I haven’t bothered to take a look at the code of these classes, but it seems unlikely that there was no other option when designing them. Had the authors thought about symmetry when creating URL and URLConnection classes, a nasty bug could have been averted. 

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • Reddit
  • Digg
  • StumbleUpon
  • Bloglines
  • Google Bookmarks
  • Y!GG

Posted in Programming, Refactoring | No Comments »

Dealing with legacy code

February 6th, 2009 by admin

Recently someone on a group on internet asked for some ideas and suggestions on refactoring legacy code. Not your usual refactoring, but the project consisting of refactoring legacy code.  Now, I guess the first thing that you might ask at that point is “what is legacy code anyway”?
According to some TDD purist, legacy code is any code that is not covered by comprehensive set of unit tests. Generally, legacy code is some code in advanced lifecycle phase, burdened by heavy debt, sprinkled with smells like long methods and large classes and often implemented in some older technology, language or language version.
Here is what I replied:

Hi,

I’d say you are in for a ride.
Here are a few thoughts based on my experience.

First of all, do not discard rewriting application from scratch without giving it a really good consideration. In my experience, it is often much easier to develop an application from zero when compared with refactoring legacy version; it is also much more difficult to refactor the legacy code than it might look at the first site. If your team doesn’t have prior experience with refactorng of legacy code, it’s all too easy to underestimate the task. Do an experiment. Choose a component or a class and see how long does it take to refactor it. On one occasion, I performed one such experiment. I was able to reduce a 4000 LOC component to a 2000 LOC component in a period of two weeks (eliminating dead code, duplication etc). 2000 LOC that were left over were still very far from being in any decent shape. We decided to go for developing the project from zero and to discard old code altogether.

On another occasion, I had to deal with some really old java code. Project contained proprietary implementation of XML parser. Not too much open source in the days when they created the application. Honestly, not a kind of code you wish to look at when maintaining something that is a typical enterprise application. Solution to this proved to be relatively easy; while XML used was not 100% well-formed, it was possible to replace it with 3rd party XML parser.

This leads us to my next thought. Start by refactoring on architectural level. Replace whole layers of application with 3rd party solutions when possible. For example, ORM tools and frameworks are only recently hitting the mainstream. It is not very likely that your application is using it. If possible, replace the persistence layer of coded SQL with some ORM tool.

The third suggestion. Know your problem domain but don’t use your legacy code base for the purpose of understating it. Reverse-engineering legacy codebase into domain knowledge is futile task; legacy code is often littered with duplication, dead code, poorly named elements etc. Try to understand the domain by speaking to domain expert/customer. Without domain knowlege you will find yourself in complete darkness. Maybe it is a feature, maybe a bug or a dead code altogether. Take a look at this story:
Refactoring Finds Dead Code

Finally, build up some reliable testing harness. Start by creating functional/integration tests and then add unit tests wherever possible.

You might wish to take a look at this article of mine, it talk about legacy VB apps, but many points are valid for any legacy code:
Moving up the technology stack: VB6 migration reality check

Good luck!

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • Reddit
  • Digg
  • StumbleUpon
  • Bloglines
  • Google Bookmarks
  • Y!GG

Posted in Refactoring | No Comments »

« Previous Entries