Showing posts with label Code Review. Show all posts
Showing posts with label Code Review. Show all posts

17 March 2018

remedy to recurring code review comments

Recently in one the interview, I was asked: "how would you handle a situation wherein which your junior developer is often making the same coding mistakes and getting same code review comments?".

I without thinking much answered it and I think the interviewer liked it.

The way I answered it.

If a developer is a making same coding mistake often, it’s more likely that he/she doesn’t know why it’s a mistake. Will sit with the colleague and explain him/her why it’s a NOT a best coding practice. After we understand why that is not a GOOD code, then it less likely that we do the same mistake again!!! (at least anytime soon!)

Thanks Ranga

06 November 2017

partial class practical use case with web service proxy regeneration

Problem statement

Recently one of my friends has to regenerate the proxy classes added via Visual Studio Add Service Reference option to an ASMX WEB service. After regeneration of the proxy classes, he started getting "HTTP Error 401 - Unauthorized" error.

Temporary solution

He called out for a help. After looking carefully into the proxy file, we found that the manually added code in the reference.cs file was got overwritten with proxy class regeneration.

The error "HTTP Error 401 - Unauthorized" indicated that authentication details are perhaps missing while making a request to web service. But we couldn't find any authentication details passing code in the latest reference.cs file. Later we checked into File History, there was a difference. The authentication related methods were not present in the latest proxy class reference.cs file.

After we added the method to include the missing authentication details, the call to web service method started working.

Auto generated web service proxy with manually edited code

It overrides the GetWebRequest() method in the same auto generated proxy class.

protected override WebRequest GetWebRequest(Uri uri)
 {
     string authInfo = "authenticaiton";
  HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(uri);
  request.Headers.Add(HttpRequestHeader.Authorization, authInfo);

  return request;
}

Permanent solution

Proxy generation happens all the time when the corresponding web service undergoes change. So, the proxy generation was recurring process and whenever proxy generation we would be sitting and fixing the same errors caused by manual changes overwriting issue.

We ought to find out a permanent solution so that all the issues with web service proxy regeneration can be put to rest.

Here partial classes in C# came to our rescue. Added a new partial class and in that partial class, included all the code we were manually adding to proxy class after it got regenerated.

New code looked like below:

namespace SameNamespaceAsThatOfProxyClass
{
  public partial class SameClassNameAsThatOfProxyClass
  {
   protected override WebRequest GetWebRequest(Uri uri)
   {
  string authInfo = = "authenticaiton";            
  HttpWebRequest request= (HttpWebRequest)base.GetWebRequest(uri);
  request.Headers.Add(HttpRequestHeader.Authorization, authInfo);
  return request;
    }
  }
}

From that point onwards, whenever web reference proxy classes were regenerated, we never faced the problem of manual code being overwritten issue. As the classes were being different, the manually added was never overwritten when the web reference proxy classes regenerated.

02 November 2017

what is defensive programming

When writing code usually we will cover ALL positive cases covered because that is what testers will test for. And also depending upon the clarity in requirements you will also code for negative test cases like non admin users should not have access to settlement reports or order reports, etc.

But we need to improve our coding skills beyond just meeting the stated functionality in terms of security, invalid inputs, unexpected errors etc.

Defensive programming example # 1

For example if some application is sending you the XML as input and says, XML they send is always going to valid as per the XSD document, then it’s better to check whether given XML is per the shared XSD or not when input is received. If not we should throw an error back to application saying the input XML doesn’t match the XSD definitions.

If you assume input is always be valid, then your application is prone for unexpected error like null reference exceptions or "object reference not set to an instance of an object", etc. Such unexpected errors are time consuming to DEBUG and fix them. So it’s always better to think what can go wrong and write the code to handle such scenarios.

Defensive programming example # 2

Let's assume you are going to build a web application to view business critical reports. Probably you show a link to a user from the business heads group to view the list of such reports in a page. When a user click on a report to your app will displays the report in detail. While your app, rendering such detail report, you need to again validate whether the user is having the enough privilege to view the report. If not, you should throw HTTP 403 Forbidden error.

While displaying the detailed report, if you don't check for the required privilege then your business critical information is easily accessible to any other application user as long as they have a valid URL to view such a report.

As a defensive programming practitioner you will add a explicit check before you start processing the request to show the detailed report.

Conclusion

This kind of programming which anticipates what can go wrong and writes the logic to handle that errors gracefully is called defensive programming. You need to become defensive programming practitioner to avoid unexpected errors and security breaches.

16 July 2017

Disable connection pooling when not used frequently

By default SQL connection pooling in enabled. That make sense given the below facts.

  • Opening and closing SQL connection is costly.
  • Usually established connections to database will be used frequently in most of the apps.

If a pooled connection is not used frequently, then you need to consider to disabling the connection pooling for that connection string alone.

When SQL connections are not used for a long time, the connection will be marked INACTIVE in database server and also there is connection IDLE TIME setting, post expiry the connection will be closed in database. So pooling logic has to open a new connection to the database when you try to open a new connection to that particular connection string. This essentially defeats the purpose of the SQL Connection pooling.

So consider disabling the connection pool for a given SQL connection string, if such connection is not used frequently.

You can refer stackoverflow post on how to disable connection pooling.

01 July 2017

StringBuilder over string concatenation

Recently I was going through a code in my personal project written long back. The legacy code was using string concatenation to build a text in a loop which ran 75 iterations on average. In each loop, there were 4 string concatenations. So totally it was doing 300 string concatenations on one run. Long back I learned its better to use StringBuilder when 5 or move string concatenation is involved. So I wanted to see how StringBuilder helps with performance over string concatenation.

Code Performance is not just about execution time, it is just one metric among many important ones!

I did code execution time comparison using Stopwatch timer to build a same text using string concatenation and also by using StringBuilder class and I found NO time difference between the them at times. Even when there is an execution time difference it was negligible. Milliseconds difference over many iterations was not exciting!"

Then I realized "the time it took to complete a task, is just one metric to measure the performance of the code among many important other metrics, hence we also need to consider other metrics around .NET Memory Management i.e, Number of Generation 0 Collection, etc. So started to track the .NET CLR Memory Performance counters.

String concatenation and measuring .NET CLR Memory Performance counters

Let's consider below C# code sample. The code is building a text using string concatenation approach.

static void Main(string[] args)
      {
        for (int i = 0; i < 10000; i++)
        {
        string text = null;
        for (int j = 0; j < 600; j++)
        {
          text += string.Format("Name{0}{1}", Guid.NewGuid().ToString(), i.ToString());
        }
        Console.WriteLine(i.ToString());
        }
        Console.ReadLine();
     }

When above code completes all looping iterations and waiting for you to key in ENTER to exit, have a look the .NET memory counters for the underlying windows process. For this blog post, I used Process Explorer tool as it serves the purpose by providing All counters I am interested and also it is easy to use plus free.






















StringBuilder to build text and measuring .NET CLR Memory Performance counters

Let's consider the below C# code to build the text using StringBuilder.

static void Main(string[] args)
      {
        for (int i = 0; i < 10000; i++)
        {
         StringBuilder text = new StringBuilder();
        for (int j = 0; j < 600; j++)
        {
         text.AppendFormat("Name{0}{1}", Guid.NewGuid().ToString(), i.ToString());
        }
        Console.WriteLine(i.ToString());
        }
        Console.ReadLine();
     }

When the above code completes all looping iterations and waiting for you to key in ENTER key to exit, have a look at the .NET memory counters for the underlying windows process. For this blog post, I used Process Explorer tool as it serves the purpose by providing All counters I am interested, also it is easy to use and free!






















Test conclusion

If you look the at .NET CLR Memory Management metrics for the two cases, we can see there is a huge difference in 'Gen 0 Collection', 'Promoted memory from Gen 0' and '% time in GC' measurements.

The code which is using string concatenation to combine strings is resulting in 75809 Gen 0 Garbage collection compared to the code which is using StringBuilder just resulting in 730 Gen 0 Garbage collection. So there is roughly 99% gain of garbage collection performance by employing StringBuilder over String concatenation.

Test results indicate, the code which is using string concatenation is witnessing more memory allocation and Garbage collection compared to the code which is using StringBuilder to do the same unit of work.

With this post I would like to drive a point. Whenever you sit for design discussion, coding and code review, just don't consider the speed of execution as the single metric to lean towards an approach. Also consider other metrics like garbage collection, CPU utilization etc to arrive at a solution.

Important notes

  • The tests were ran on INTEL i7 dual core processor, 8 GB RAM and WINDOWS 10 Operating system machine which is light on resource consumption. Not many programs running.
  • Depending on the load, the performance counters value differs. So for any performance tests, you will always need to consider the NFRs to be supported. Consider benchmarking the performance considering the Non Functional Requirements(NFRs).

12 November 2016

Effect of exceptions while initializing the static members

Recently I encountered an error saying The type initializer for class threw an exception from a .NET windows service. The error was thrown while accessing any members/methods of a class. The error kept happening until the .NET Windows service was restarted.

After digging deeper into application error logs and analyzing the code in depth, I learnt the below:

  1. The offending class had static variables. One of the static variables was getting initialized by invoking DB repository method to get configured value.

    private static decimal minInsurancePremuimAmount = InsuranceConfigRepository.GetMinPremuimAmount();
  2. The database repository method was throwing exception when failed to fetch the data from Database Server in case of any transient error,etc.

    try
    {
    }
    catch(Exception ex)
    {
      // Log and throw the exception
      throw ex;
    }
  3. When the offending class was first accessed, .NET framework tried to initialize the static variables. When it tried to initialize the minInsurancePremuimAmount, it resulted in a SQLException because Database server was not accessible at that time.
  4. So .NET framework could not complete the class initialization logic. Hence application was giving the error until it restarted.

    The type initializer threw an exception.

What was the fix?

  1. So taking clue from the issue, code changed to ensure static members initialization logic will never throw the exception up the call stack. In case of any errors happened during the static members initialization, such Exceptions just eaten and logged for DEBUG purposes.
  2. In the offending class, the internal logic was modified.

    Before accessing such static members, the members were NULL checked. If they were still NULL, the code was added to initialize the variable.

    This way even if there is an exception, only the current method invocation would fail, but not any future method invocations will result in the error "type initializer threw an exception".

25 June 2016

use DateTime.UtcNow instead of DateTime.Now.ToUniversalTime()

Often times juniors developers in the team use DateTime.Now.ToUniversalTime() to get the UTC time instead of using the direct approach DateTime.UtcNow.

Let’s go though the below points to understand the difference between the two.

  • It looks like .NET maintains the DateTime value internally in UTC time zone.
  • When you call DateTime.Now. ToUniversalTime (), actually the .NET code does two things.
    1. First, with “DateTime.Now”, converts the UTCTime to machine’s local time zone.
    2. Then on calling on the ToUniversalTime (), it converts the local time to UTC time zone again.

Obviously there is a overhead associated with using DateTime.Now.ToUniversalTime() instead of DateTime.UtcNow when you just want UTC time.

This slight run-time overhead might doesn't matter always; but while processing huge volume of operation involving code using DateTime.Now.ToUniversalTime (), can incur more CPU cost.

Apart of the cost associated, the construct “DateTime.UtcNow” looks more readable than DateTime.Now.GetUniveralTime().

So if you are using ToUniversalTime() method to get the UTC time, consider to use DateTime.UtcNow. Do this change as early, otherwise you might run the risk of this “not so good” practice getting repeated in your code base by developers adding the new code into the project.

Benchmarking

Executed the code using “DateTime.UtcNow” and “DateTime.Now. ToUniversalTime()” to get the UTC time million times in a loop like below:

Stopwatch watcher = new Stopwatch();
watcher.Start();
for (int i = 0; i < 1000000; i++)
{
  DateTime dateTime = DateTime.UtcNow;
   // DateTime dateTime = DateTime.Now.ToUniversalTime();
}
 
watcher.Stop();
Console.WriteLine(watcher.ElapsedMilliseconds.ToString());

Benchmarking results:

  • The code using “DateTime.UtcNow” took 13 millisecond to complete the for-loop execution.
  • The code using “DateTime.Now.ToUniversalTime()” took 400 millisecond to complete the for-loop execution.

11 June 2016

Calculating difference between start and end time

When you want know measure how long it takes to a web service method to return response in test/production environment, what you will do?

The easiest way is to keep calculate the difference between current date time before calling the method and after calling the method. Some thing like below:

DateTime start = DateTime.Now;
 
// Call web service
            
DateTime end = DateTime.Now;
TimeSpan difference = end.Subtract(start);

But there is a better way available in the form of Stopwatch class present in System.Diagnostics namespace starting from .NET Framework 2.0 version.

Stopwatch watcher = new Stopwatch();
watcher.Start();

// Call web service

watcher.Stop();

The Stopwatch object gives Elapsed TimeSpan property, which gives the time difference between starting and stopping the watcher. Also there is more handy property named "ElapsedMiliseconds" which gives Elapsed time in millisecond.

TimeSpan difference = watcher.Elapsed;

long durationInMillisecond = watcher.ElapsedMilliseconds;

22 December 2014

how in-memory cache can get inadvertently affected

Recently I was doing a code review for one my teammate and found an issue. The in-memory cache items were getting inadvertently affected.

Let's see what was the issue by looking into the below sample cache creation and retrieval code.

Building the object need to be cached

public class GeneralData {
        public string Id { get; set; }
        public string Text {get;set;}
        // ...some other properties
    }
Dictionary<string, GeneralData> staticData = 
         new Dictionary<string, GeneralData>();
 staticData.Add("1", new GeneralData());
 staticData.Add("2", new GeneralData());
 staticData.Add("3", new GeneralData());

System.Runtime.Caching.MemoryCache cache = 
                          MemoryCache.Default;

Add item into cache and set the cache expiration policy

cache.Add("CacheKey", staticData, 
      new DateTimeOffset(DateTime.Now.AddHours(2)));

Retrieve the cache item and perform processing

Dictionary<string, GeneralData> staticDataObject = 
              Dictionary<string, GeneralData>)
              MemoryCache.Default.Get("CacheKey");

// As part of some processing logic
// the staticDataObject was modified
staticDataObject.Remove("3");

In the above C# code sample at line 3, the GeneralData instance was removed from the local instance holding the reference to the in-memory cache object. This means the object is also removed from Cache object as well.

So pay extra attention while working with objects holding the reference to the in-memory objects, otherwise such problems will lead to inconsistent software application behavior.