Refactoring a server side creating of JavaScript with C# verbatim literal strings (@)

Posted: July 25th, 2010 | Author: | Filed under: Refactoring | Tags: , , , | No Comments »

Today I was refactoring a code of my job colleagues and stuck in horror (coding).

Beware Coding Horror on the way….

codinghorror

In one method I found this code:

string summary = String.Empty;
int counter = 0;
int i = 0;

foreach (PoiMapData poi in listAllPoi)
{
  string name = poi.KindName.Replace(" ", "_");
  string lat = poi.Latitude.ToString().Replace(",", ".");
  string lon = poi.Longitude.ToString().Replace(",", ".");

  summary = Helper.GetLeadingHtml(poi.Summary, 150);
  summary = summary.Replace("'", "\\'");

  string title = poi.Title.Replace("'", "\\'");

  i = poi.Id;

  ScriptString += "\t" + @"var point" + i + @" = new GLatLng(" + lat + ", " + lon + ");\n" + "\t" +
                       @"var marker" + i + @" = createMarker(point" + i + ", '" +
                       @"<span class=""title"">" + @"<a href=""PoiDetail.aspx?poiID=" + poi.Id + @""">" + title + @"</span><br />" +
                       "', '" + @"<br /><span class=""summary"">" + summary + @"</span>" + "', " +
                       "icon" + poi.KindId + ", " + "'" + name + "');\n " + "\t" +
                       "map.addOverlay(marker" + i + ");\n" + "\t" +
                       "listaPOI[" + counter + "] = marker" + i + ";\n\n ";
  counter++;
}

Holy Hejlsberg! If I may say :) I think this screaming Concatenation explains how very, very, and super very wrong this code is, and this is not all, because this piece of code is in foreach loop so it would continue over and over and over again. Horror!

…And this is still not all! Forget about speed and benchmarking, and for a second think what is most important in code: maintainability and readability, woohooo, can you even read above code. It is totally cluttered with “+”, “\n”, \t”, “@”!

But all that code doing is script (JavaScript) with GoogleMaps markers of all Points of interest, so it can be represent on map. But problem is that this JavaScript building is done on sever-side, using database for getting all Points of interest (there is also a grouping by kind of points of interest, but never mind that, back to refactoring).

So what is the best way to format and build formated JavaScript in C# language? For me it is by using, so called, verbatim literal string. In C#, is used @ sign (“monkey” as many would say, but actually is “at” sign) to indicate the verbatim literal string.

So what a hella heck is verbatim literal string. According to MSDN:

By prefixing a string literal with “@”, you can insert line breaks and other special characters into a string, and the C# compiler will interpret everything between the open and closing quotation marks as the contents of that string. Note that quotation marks within the string need to be doubled, or else the compiler will assume it has hit the end of the string literal.

So now is easy to refactor above shown horror. First why there is variable i, i is very popular in for loops, indicating index, but here uses point of interest Id. Why?!!. Actually, I would rename counter to index, or maybe use a for loop here better and some naming of variables are totally wrong, but let it be, that can pass, we want to refactor this concatenation coding horror…

Stop!
Refactoring time!

string summary;
ScriptString = String.Empty;
int counter = 0;

foreach (PoiMapData poi in listAllPoi)
{
  summary = Helper.GetLeadingHtml(poi.Summary, 150);
  summary = summary.Replace("'", "\\'");

  string script =
    @"{0}
      var point{1} = new GLatLng({2}, {3});
      var marker{1} = createMarker(point{1},
                                   '<span class=""title""><a href=""PoiDetail.aspx?poiID={1}"">{4}</span><br />',
                                   '<br /><span class=""summary"">{5}</span>',
                                   icon{6},
                                   '{7}');
       map.addOverlay(marker{1});
       listaPOI[{8}] = marker{1};";

  ScriptString = String.Format(script,
                               ScriptString,                               // {0}
                               poi.Id,                                     // {1}
                               poi.Latitude.ToString().Replace(",", "."),  // {2}
                               poi.Longitude.ToString().Replace(",", "."), // {3}
                               poi.Title.Replace("'", "\\'"),              // {4}
                               summary,                                    // {5}
                               poi.KindId,                                 // {6}
                               poi.KindName.Replace(" ", "_"),             // {7}
                               counter);                                   // {8}

  counter++;
}
  • I’ve removed many local variables, I just don’t see no purpose for their existence, especially famous (i)?!!.
  • Create a string that will hold formatting in a placeholders ({0},…).
  • In String.Format, first is ScriptString which is simulating “ScriptString +=” concatenation.
  • Rest are those needed for GoogleMaps marker(s).
  • String.Format could be in one line of code but I put comments of what number placeholder has, only for easier reading.
  • Verbatim literal strings keep all formatting so there is no need for tabs, newlines, etc..

Even though this will produce “fat” (full of white-spaces) script, this code should be only used for development, and for deployment I would rather crate one flat script probably. Done preferably with StringBuilder.

Here are some nice blog post of prominent bloggers I’ve found while refactoring this coding horror:

Happy coding and refactor your ugly code every now and then.

It’s good for the soul!


The Clash of MVC Frameworks!

Posted: August 6th, 2009 | Author: | Filed under: The Clash of MVC Frameworks | Tags: , , , , , , , , , , , , , | 3 Comments »

MVC Architecture

Today, I have been bumped by an wild idea to make a comparison between “most popular”  MVC frameworks. Idea is to create simple web application but it will have at least one many-to-many relationship in it . The application will be something that I got on my job to make, and because of  its OS architecture (Linux)  we decide to be a PHP application. It is fairly simple and tomorrow when I got my mind set it on more for this application I’ll make an data model.

Initially I wanted to be done with Zend Framework but we have an Debian machine for this application, and even after upgrade it had a PHP version 5.2.0 (first he had 4.4.4?!!!), but for Zend Framework prerequisite is PHP version 5.2.4+.

So, today I started coding with CakePHP, and I didn’t try to copy/paste code. I write all, and had a lots, lots and lots of errors. Uh, this PHP (for me) is so unnatural to write. Funny, I had most of errors on forgetting to add semicolon on the end (but almost never have this problem in C#), and else I had problems with OOP syntax in PHP (which I totally dislike), uh, so many errors. Probably because I’ve been coding with PHP but very rarely OOP related, most of , was as with all others so called ‘spaghetti code’. And by all means I really didn’t mean to spit and tell that PHP is bad language, because it is highly used and it can be learned very fast, and it is also very powerful especially since PHP 5, but it is missing some language elegance. And for sure CakePHP is a great MVC Framework…

Ok, enough about PHP and me, back to MVC frameworks. Idea is to make this little application in this MVC frameworks:

As you can see there will be no true Java MVC like Spring because all of this frameworks mentioned up are (for me) clones of Ruby on Rails and they are RAD frameworks or ones for quick development of web application. Driven by Convention over Configuration (CoC) paradigm which Java MVC frameworks very lacks!  But believe me I have nothing against Java frameworks, they prove themselves through years and I would really like to do something in Spring or Spring.NET! And maybe I shall one day…

If I forget some good framework, please tell it or you would rather see some other framework instead of this. Write them then, don’t be shy?


C# learning roadmap

Posted: May 10th, 2009 | Author: | Filed under: Learnaholism | Tags: , | 1 Comment »

Mainly I deicide to blog knowledge which I read/learn from programming books that I bought. But there will be blogging about setting an Agile Software Development environment or some doubts on the best suited environment for my needs. Especially for making some kind of real-world application.

In First Phase of learning I’ll start to sharp my knowledge of C#. My main idea is to write all the things I’ve learned from reading and experimenting with C# language features and/or .NET base class libraries.

There are three books I bought and respect them a lot and I want absorb their knowledge and blog them as a reference:

  1. Jeffrey Richter – CLR via C#, Second Edition : Great internals on C# and CLR
  2. Joseph & Ben Albahari – C# 3.0 In a Nutshell : Great quick reference on C# 3.0
  3. Jon Skeet – C# In Depth : Brilliant book about the heart of C# language and my primarily roadmap for learning C# in Depth

The Second Phase of learning is setting up an environment for Agile Software Development mainly:

  • Source Control – now I’m in doubt on using Git or Subversion as client or some variant of this source controls repositories available on Internet like GitHub or XP-Dev
  • Continuous IntegrationJetBrains TeamCity or maybe CruiseControl.NET but CI will have build tool NAnt, code coverge tool NCover and if NDepend is have some free or community version.
  • Agile Project Management – Set up TargetProcess or maybe Rails based Redmine or something else?!

The Third Phase of learning will be building a real-world applications with modern programming principles in mind (DDD, TDD, S.O.L.I.D, BDD, ORM), but also the goal is the not to postpone the UX, and all project documentation from planning to designing the application. For this phase I should blog in near future about all my thoughts on what real-world applications will be, and all technologies that will be a part of application. For now my goal is MVC like web application, but would be also nice to make WPF application.

The idea for all written code will be to be in spirit with great book Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries (2nd Edition)  by Krysztof Cwalina and Brad Abrams and tools like fxCop and StyleCop.

The Forth Phase is for now SF, but I always wanted be a part of some OpenSource project, now primarily I want to be a part of some .NET project. Even though super SF would be to do start new and useful OpenSource  project by myself!

Even I break learning in phases this doesn’t mean that I’ll blog only one phase and when that phase is over then go to another phase. And I really think that Second Phase will be over far before than First Phase!