Archive for category Best Practices/Clean Coding

My love… for Expressive Programming Languages

I started out my journey with programming as a teenager learning GW-BASIC. Soon I learnt C language followed by C++.  I was impressed with the OO syntactic constructs C++ had on offer but I felt a little uneasy with a few constructs such as the scope resolution. I started studying Java. It immediately caught my attention with the syntactic improvements and simplifications it brought over C++.

I was still in academics, so learning(precisely trying) programming languages on surface, was a fun activity. I went through PHP, Javascript. I came in interaction with C#. This was the time this language was evolving. The internet was full of text describing the fact that C# was Microsoft’s Java. This encouraged me to study C# and consequently .Net Framework in detail. This was the time LINQ was introduced and I simply loved it. I really liked the way it was elegantly added to the C#. The features added to C# for supporting LINQ namely lambda expressions, implicitly typed  variables, anonymous types, extension methods, query expressions and etc complemented the LINQ infrastructure beautifully. By the time I finished academics, I was a seasoned OO developer.

Recently, I was considering to learn a more cryptic language that aligns with jQuery’s ‘write less, do more’ tagline (although not a language, I like jQuery for the same reason). I considered Python/Ruby but did not find these exciting enough. I have just come across Scala, and decided to make it my next fun mission.

Normally when I learn a new programming, I would give very little time to learning conventional constructs(for, if, function/class definitions etc). After a very long time, I have come in connection with a language that demands paying attention to such constructs. So no liberty of skipping pages.

I am considering Programming in Scala by Martin Odersky – the man behind Scala, et al. At the time of writing this post, considerable amount of content that teaches Scala, is avaible on Google Books. If you already know Scala, you would probably know by now, what my feedback about the language is…A-W-E-S-O-M-E.

The motivation for using Expressive Languages

  • The code becomes declarative in nature. It has less noise for syntactic constructs and more concentration on the intended logic.
  • The above feature makes the developer productive in writing and making changes to the code
  • Debugging becomes super easy.
  • I personally feel, a developer has a better chance of aligning his/her code with coding best practices.

The only reason I find to keep my self from using an expressive language for a particular task is, as you might have guessed performance. Comparing LINQ to collections with loops, reveals loops are faster. You need to be able to judge if you need mission critical performance, otherwise the difference is ignorable.

Advertisements

, , , , ,

4 Comments

A NetSuite Best Practice – Client JS in Suitelets

Often we need writing Suitelets in Netsuite that have conventional HTML UI elements rather than the objects provided by Netsuite’s UI Builder API. We normally use HTML within javascript string to be sent to client side. To write code against the elements in this HTML, client side javascript also goes within a string. Problems arise when we need to update the code within a string as we are not able to use the features of the IDE to its fullest. This post is all about solving these problems, exploiting the fact that the server-side code written for Suitelets is also in javascript.

The Technique

Good news is that each javascript function object has a toString() method, and a better news is that it works as expected in Netsuite ! :).

So the idea is to write client and server-side code alike and use the toString() method of the client-side functions to aggregate the client-side script.

Example

Lets take a simple scenario. We are creating a user registration form within a Suitelet using plain old HTML form elements.

  • When the user inputs first and last name fields we would like to suggest a user name.
  • When the user inputs a password, we would like to warn if it contains the first or last name.

Here goes the script:

function main(request,response)
{
    response.writeLine(getClientSideCode());
    response.writeLine(getHtml());
}
function getHtml()
{
    var h = '';
    h += 'First Name';
    h += '<input type="text" id="txtFName" onblur="setUserIdFromNames();"/>';
    h += 'Last Name';
    h += '<input type="text" id="txtLName" onblur="setUserIdFromNames();"/>';
    h += 'User Name';
    h += '<input type="text" id="txtUserName" />';
    h += 'Password';
    h += '<input type="password" id="txtPass" onblur="performPasswordSecurityCheck();"/>';
    return h;
}
function getClientSideCode()
{
    var s = '';
    s += '<script type="text/javascript">';
    s += 'function setUserIdFromNames()';
    s += '{';
    s += '  var firstName = document.getElementById("txtFirstName").value;';
    s += '  var lastName = document.getElementById("txtLastName").value;';
    s += '  var userName = firstName.toLowerCase() + \'.\' + lastName.toLowerCase();';
    s += '  document.getElementById("txtUserName").value = userName;';
    s += '}';
    s += 'function performPasswordSecurityCheck()';
    s += '{';
    s += '  var password = document.getElementById("txtPassword").value;';
    s += '  var firstName = document.getElementById("txtFirstName").value;';
    s += '  var lastName = document.getElementById("txtLastName").value;';
    s += '  if(password.indexOf(firstName)!=-1 || password.indexOf(lastName)!=-1)';
    s += '      alert("Using names in password makes it less secure!");';
    s += '}';
    s += '</script>';
    return s;
}

The highlighted lines contain the script that is problematic. Its difficult to read,  refactor and debug.

Here is the improved version of the code:

function getClientSideCode()
{
    var arrFunctions = [setUserIdFromNames,performPasswordSecurityCheck];
    var clientScript = '<script type="text/javascript">';
    for (var i = 0; i < arrFunctions.length; i++)
        clientScript += arrFunctions[i].toString();
    clientScript += '</script>';
    return clientScript;
}

function setUserIdFromNames()
{
    var firstName = document.getElementById('txtFirstName').value;
    var lastName = document.getElementById('txtLastName').value;
    var userName = firstName.toLowerCase() + '.' + lastName.toLowerCase();
    document.getElementById('txtUserName').value = userName;
}

function performPasswordSecurityCheck()
{
    var password = document.getElementById('txtPassword').value;
    var firstName = document.getElementById('txtFirstName').value;
    var lastName = document.getElementById('txtLastName').value;
    if(password.indexOf(firstName)!=-1 || password.indexOf(lastName)!=-1)
        alert('Using names in password makes it less secure!');
}

Notice the changes from the previous version:

  • All the client-side functions now coexist with the server-side code
  • The getClientSideCode() function  has the references of all client side functions. It iterates over all of these to append each to the client-side script.

Pros and Cons

The latter code is much better than the earlier version.

  • The client-side code is easier to maintain. Its free of noisy code/characters like extra semicolons, quotes and annoying escape sequences.
  • One can use the features provided by the IDE to make change in the code such as renaming identifiers and code formatting.

However there are a few limitations to this approach that must be taken care of .

  • The IDE has no means to discriminate between server and client-side functions so the developer has to be careful using intellisense/autocompletion to avoid calling client code in server-side and viceversa.
  • Every time you create/remove a client-side function you need to update the collection of functions(arrFunctions in the code example).
function main(request,response)
{
//response.writeLine(getClientSideCode());
response.writeLine(getHtml());
}function getHtml()
{
var html = ”;
//html += getClientSideCode();
html += ‘<script type=”text/javascript”>’;
html += ‘    function setUserIdFromNames()’;
html += ‘    {‘;
html += ‘        var firstName = document.getElementById(“txtFirstName”).value;’;
html += ‘        var lastName = document.getElementById(“txtLastName”).value;’;
html += ‘        var userName = firstName.toLowerCase() + “.” + lastName.toLowerCase();’;
html += ‘        document.getElementById(“txtUserName”).value = userName;’;
html += ‘    }’;
html += ‘    function performPasswordSecurityCheck()’;
html += ‘    {‘;
html += ‘        var password = document.getElementById(“txtPassword”).value;’;
html += ‘        var firstName = document.getElementById(“txtFirstName”).value;’;
html += ‘        var lastName = document.getElementById(“txtLastName”).value;’;
html += ‘        if(password.indexOf(firstName)!=-1 || password.indexOf(lastName)!=-1)’;
html += ‘            alert(“Using names in password makes it less secure!”);’;
html += ‘    }’;
html += ‘</script>’;
html += ‘<div>’;
html += ‘    First Name<input type=”text” id=”txtFirstName” onblur=”setUserIdFromNames();”/><br />’;
html += ‘    Last Name <input type=”text” id=”txtLastName” onblur=”setUserIdFromNames();”/><br />’;
html += ‘    User Name <input type=”text” id=”txtUserName” /><br />’;
html += ‘    Password  <input type=”password” id=”txtPassword” onblur=”performPasswordSecurityCheck();”/><br />’;
html += ‘    …’;
html += ‘</div>’;
return html;
}

, , , ,

3 Comments

Multiple Inheritance with Strategy Pattern

When I was introduced to programming languages like Java and C# (coming from C++), one of the things that I really missed was Multiple Inheritance. That is, in these languages we could not say something like:

class AllRounder : Batsman, Bowler { }

These languages offer interfaces to establish polymorphism. That is we can say (in C#):

class Batsman
{
     void Bat()
     {  Console.WriteLine("Do batting.");  }
}
interface IBowler
{
     void Bowl();
}
class Bowler : IBowler
{
     public void Bowl()
     {  Console.WriteLine("Do bowling.");  }
}
class AllRounder : Batsman, IBowler
{
     public void Bowl()
     {  Console.WriteLine("Do bowling.");  }
}

Do you see a problem here…? I do.

The problem is that the Bowl() is implemented twice, although the code it contains is by definition the same. Its a shame calling this code ‘Multiple inheritance’ because actually interfaces do not inherit anything. They just ensure a contract. The only feature of inheritance that interface provide is Polymorphism. You can say:

IBowler bowler = new AllRounder();
bowler.Bowl();

But the problem with duplication is that if we need changing Bowl() in the Bowler class we will almost always require changing the Bowl() implementation in the AllRounder class. The are a few ways to get around this. The key to all solutions I can think of at the moment is to introduce a layer of abstraction i.e. wrap the code of Bowl() into code commonly accessible to both. I’ll choose using the Strategy Pattern

interface IBowlingBehavior
{
    void PerformBowling();
}
interface IBowler
{
    IBowlingBehavior BowlingBehavior { get; set; }
    void Bowl();
}
class Batsman
{
    void Bat()
    {  Console.WriteLine("Do batting.");  }
}
class Bowler : IBowler
{
    public IBowlingBehavior BowlingBehavior { get; set; }
    public void Bowl()
    {  BowlingBehavior.PerformBowling();  }
}
class AllRounder : Batsman, IBowler
{
    public IBowlingBehavior BowlingBehavior { get; set; }
    public void Bowl()
    {  BowlingBehavior.PerformBowling(); }
}
class DefaultBowlingBehavior : IBowlingBehavior
{
    public void PerformBowling()
    {  Console.WriteLine("Do bowling.");  }
}

This allows us to implement the bowling code in one place as well as select one of the many implementations of BowlingBehaviors at runtime!

class SpinBowlingBehavior : IBowlingBehavior
{
    public void PerformBowling()
    {  Console.WriteLine("Do spin bowling.");  }
}
class FastBowlingBehavior : IBowlingBehavior
{
    public void PerformBowling()
    {  Console.WriteLine("Do fast bowling.");  }
}

and later we can say…

Bowler fastBowler = new Bowler { BowlingBehavior = new FastBowlingBehavior() };
fastBowler.Bowl(); //Bowl Fast
fastBowler.Bowl(); //Bowl Fast
fastBowler.BowlingBehavior = new SpinBowlingBehavior();
fastBowler.Bowl(); //Bowl Slow, fool the batsman

, , , ,

2 Comments