Naveen's Weblog

Bridge to future

Sensible code Part II – What is software quality??

Posted by codingsense on March 31, 2014


Before getting to software quality, lets spend time to see how a software degrades?

Software degrade doesn’t happen in a day or a week, it takes couple of months or even years for us to realize that the software quality is degraded. And it takes even more time after that to bring it back on track. It just starts to happen from the day when we start rushing the code into it, without giving enough time for ourselves to think before implementing features or fixing defects, we always tend to think the code that we write is good.

And if we are not concentrating on quality on every step we take in developing we end up as I had mentioned in my last post here.

Imagine how it would be if we could track the degrade at the moment when we insert a bad code. It really needs good observation and practices to achieve it, but in real world since we are so busy in writing new code and delivering quickly we least bother on looking back on what we have done wrong. And we are always proud of our code, how can we check if we are at the best.

There are few good practices that will really help us to avoid sidelining with your product quality path. And using these practices in every step will ensure us that we get early warnings and keep our product lively.

Let’s see what are the quality parameters that really matters in product health.

  1. Cyclic Dependencies: This is the most important of all, this parameter targets the types and namespaces. If there is any cyclic dependencies then it shows most of the principles are broken. and once we introduce cyclic dependencies, its really really hard to maintain that piece of code. To describe a cyclic dependency lets taken an example. If a type/namespace A is using a type/namespace B and B in-turn is using A, then we call such dependency as cyclic dependency. In this case both A and B are tightly coupled and any changes in A or B will result in an impact in both of them. Writing UT for such dependent types is also hard to mock or stub.
  2. Afferent coupling (Ca): This parameter helps us to monitor single responsibility principle (SRP). This parameter is applicable for method, type (class), namespace (package) and even assemblies. For eg: if 3 other types are dependent on a type t1, then afferent couple of t1 is 3. If there are more types referring a type then it shows that it is taking more responsibility and it should be broken down into multiple types.
  3. Cyclomatic complexity (CC): This parameter is the count of number of path of execution. For eg: If there is no condition in your method then the CC of that method would be 1. If there is one if condition it would be 2. So any condition in your method will increase the CC by 1. All the following keywords increases CC by 1. If, while, for, foreach, case, default, continue, goto, ||, &&, catch, ?:,?? etc..
  4. Interfaces: Following dependency inversion principle (DIP) and interface segregation principle (ISP) gives us very much flexibility for future modification.
  5. DIP says no classes should be accessed directly but should be used thorough an interface.. For eg imaging if a type A wants to use B, instead of referring B directly in A, create IB interface and use IB in A, now A is dependent on the signature not the behavior, if new type of B1 comes we don’t have to change anything in A, and simple pass the instance of B1 instead of B.

    ISP says dont clutter your interface with all the methods but segregate it using SRP. For eg: if we are writing some class for Person and create an interface IPerson with methods, walk, run, stop, sit, stand, eat, sleep, meditate, exercise etc. Instead separate IPerson with behavioral interface, like IMove can have walk, run, stop methods, instead of having them in IPerson directly. and then inherit IPerson or better Person class from IMove.

  6. New keyword: For creating any object, we have to use a new keyword, but why is it called bad to use new keyword? new keyword is good if its in right places, it should not be scattered though out the code, the less new keyword is used the better. We can decrease the usage of new keyword using factory method, dependency injection or MEF. But how does it help us?? imaging a logger class, and as of now we have a requirement that logger should log only in a text file and we implemented it and used new keyword across our code wherever we need logging. Later if the requirement says we should provide also option to log in event logger then we start writing if-else inside our logger class. Instead its a new responsibility and should be taken care by a new class. So if we had the creation of logger in a factory, we can just write a new implementation and return it.
  7. Comment and names: Comments as suggested by uncle bob in his book “Clean Code” is ugly. He suggests that if the variable, methods, types, namespaces and assemblies are named in a descriptive way, then there is no need for a comment. Reading a line should feel like reading an English sentence. Always make a class noun and a method verb, Eg a class Cycle can have methods like Ride(), Start(), Stop()
  8. Number of lines: This parameter depends on programming language that is used, for .Net and Java for a method 15 is an ideal count, and for a type its 200. There are many cases that is observed when you cannot write a logical flow within 15 lines in a method. But ideally it’s good to method and type as short as possible.

There are many many more quality parameters that needs to be considered. But lets focus on these above parameters since they are really important to be taken care of. In next post lets see how to get early warnings on the above parameters as soon as we break the law.

Let me know if there are any important parameters that I have missed to mention.

Happy Learning :)

Posted in Codingsense | Tagged: , | Leave a Comment »

Sensible coding part I – Howz your product???

Posted by codingsense on March 26, 2014

After few years of experiencing development in various projects and technologies, I started to think of reflecting my past on what went right and what went wrong in terms of development for self appraisal.

While analyzing I found couple of common things that happens in a life time of a product and people working on it.

Kick off a project – Happy birthday to our new project (Year 0):
Product is getting born, very much in versatile state. Lets name it Mr Perfect. Management bless Mr Perfect to be built with world class code and can sustain any changes in the requirement and will live long and long with good health and bring a very good name to the company.
Best competent people are selected for the team. Everyone in the team are excited about the new deliverable that are planned, we can see the excitement and energy in the team. All are busy in learning a new technology or new version of technology, people come up with different approaches for any given problem. Working with such team seems wonderful.

First release of Mr Perfect (Year 1):
Product has survived the first release and any changes or bug fixes have not effected it. People start working on new requirements and changes that comes from the filed users very positively.

Second release of Mr Perfect (Year 2):
Lots of changes and bug fixes were done, new and new features are getting pushed into the product. Deadlines are short, managers ask for quicker deliveries, customer asks for quicker fixes. People start to doing hard work and ignore smart work to achieve the goals.

Third release of Mr Perfect (Year 3):
The product has grown big with more than half million lines of code. People have created a mindset on which feature is good and which feature is bad ( few techies call it legacy code :) ). The feature that are labelled legacy, is creating panic in the people who are associated with it. If there is any bug raised in it, they start to panic and get frustrated sometimes.

Fourth release of Mr Perfect (Year 4):
Our marketing and requirement guys go to customer to check how do they feel about the product and what else they need. They come up with a big list of new features, scrap some features and list of customer complaints on improper support.
Development team is unable to digest the changes, they start looking for workarounds, hiding some features, implementing new features.

BOOOOMMMMMMMM!!!!

What are the probable outcomes?? any guesses??
Check which all of the below listed would be true.

  • A bug fix in one module, starts creating impact on some other module.
  • The code is hard to understand, very fragile and not versatile.
  • Duplicate code is introduced everywhere, any fixes at one place should be fixed everywhere.
  • Performance of the product is very low.
  • Loads of memory leaks results in slow performance and crashes the tool often.
  • Removing a feature is not easy since some of its classes is used by many of them.
  • Development team asks for much higher estimations to achieve even a small change.
  • Bugs reported in critical features (Legacy code) are ignored and delayed as much as possible.
  • Quality team raises non compliance on some features with more bugs.
  • Managers are worried about their competent team.
  • Development team suggests lets refactor the features or build a new product.

Blah Blah Blah..

Guess what would happen to such Mr Perfect product or the customers who rely on them?

Has anyone seen these problems in the product?? What went wrong suddenly just last year everything was fine?? Is there any solution for this??

Let me know your comments if you have seen such issues or are living with it or overcame it.
hmm I bet there has to be some solution for such :)

Next >> Sensible Code part-ii What is software quality?

Happy Learning :)

Posted in C#, Codingsense, Solutions | Tagged: , | Leave a Comment »

2012 in review

Posted by codingsense on December 31, 2012

The WordPress.com stats helper monkeys prepared a 2012 annual report for this blog.

Here’s an excerpt:

19,000 people fit into the new Barclays Center to see Jay-Z perform. This blog was viewed about 110,000 times in 2012. If it were a concert at the Barclays Center, it would take about 6 sold-out performances for that many people to see it.

Click here to see the complete report.

Posted in Uncategorized | Leave a Comment »

HTML 5 Canvas – Line

Posted by codingsense on September 9, 2012


In the previous post we have drawn all the available objects on the canvas.
Lets look into the drawLine method.

<!DOCTYPE html>
<html>
<head>
<title>HTML5</title>
<script type="text/javascript">

    function load() {
        // Get a reference to the element.
        var elem = document.getElementById('myCanvas');

        // Always check this for non supported browsers
        if (elem.getContext('2d')) {
            // Get the 2d context.
            var context = elem.getContext('2d');
            //Set color for filling
			context.fillStyle = "#62ADE3";
			//Apply the rectangle with set color
            context.fillRect(0, 0, 500, 500);
			
			drawLine(10, 10, 100, 100);
		}
	}
	
	function drawLine(sourceX, sourceY, destinationX, destinationY) {
        var elem = document.getElementById('myCanvas');
        var context = elem.getContext('2d');
        context.strokeStyle = "rgb(0, 0, 0)";
        context.lineWidth = 3;
        context.moveTo(sourceX, sourceY);
        context.lineTo(destinationX, destinationY); // Black line
        context.stroke();
    }

</script> 

</head>
<body onload = load();>
	<canvas id="myCanvas" width="500" height="250">
		Hi I am Mr.Canvas and your browser doesn't support me :(
	</canvas>
</body>
</html>
  1. First we get the canvas element and the context.
  2. Next we set the stroke style, that is what color brush has to be used to draw the line.
  3. Set the line width
  4. Move the starting point to sourceX and sourceY pixels.
  5. From there we draw line to the given destinationX and destinationY pixels.
  6. And we stoke the element, this is actully where the line is drawn on the canvas.

So only moveTo and lineTo methods are enough to draw a line on a canvas. But in many other tutorials you have seen beginPath and closePath methods also used. Lets see why they are used and when its useful to use them.

<!DOCTYPE html>
<html>
<head>
<title>HTML5</title>
<script type="text/javascript">

	var context;
    function load() {
        // Get a reference to the element.
        var elem = document.getElementById('myCanvas');
		
        // Always check this for non supported browsers
        if (elem.getContext('2d')) {
            // Get the 2d context.
            context = elem.getContext('2d');
            //Set color for filling
			context.fillStyle = "#62ADE3";
			//Apply the rectangle with set color
            context.fillRect(0, 0, 500, 500);
			drawPath();
			
		}
	}
	
	function drawPath() {
		context.strokeStyle = "rgb(0, 0, 0)";
        context.lineWidth = 3;
		context.beginPath();
		context.moveTo(10,10);
		context.lineTo(100, 100);//1
		context.lineTo( 70, 180);//2
		context.lineTo(30, 200);//3
		//context.closePath();
        context.stroke();
    }

</script> 

</head>
<body onload = load();>
	<canvas id="myCanvas" width="500" height="250">
		Hi I am Mr.Canvas and your browser doesn't support me :(
	</canvas>
</body>
</html>

Copy the above code and run it. You will see 3 lines drawn on the canvas. Now uncomment the context.closePath() in the drawPath method and see what happens.
Consider you want to draw a path on the canvas and then you need to join the last point drawn with the starting point, then the beingPath and closePath methods are handy.

Note that when drawing path you can use moveTo method only once between beginPath and closePath methods. If there is another moveTo then it will start up a new path and the closePath will not close the path as desired.


Happy Learning :)
Codingsense

Posted in HTML 5 | Tagged: , | Leave a Comment »

Peep into HTML5 Canvas

Posted by codingsense on September 9, 2012


Canvas is a wonderful gift in HTML 5. You can draw any kinds of shape and do loads of animations using it. First lets get clear understanding on what all can be drawn on canvas.

Lets make our hands dirty by going step by step to see how easy we can create Canvas elements.
Lets work on the get the below canvas element and to cover most of the available canvas elements.

canvas_basics
Lets start first creating the canvas with all necessary html headers.
Create an empty file with extension .htm or .html and add the below lines in it. Make sure you open it the browser that supports HTML5 (Chrome, Safari, Firefox).

<!DOCTYPE html>
<html>
<head>
<title>HTML5</title>
<script type="text/javascript">

    function load() {
        // Get a reference to the element.
        var elem = document.getElementById('myCanvas');

        // Always check for properties and methods, to make sure your code doesn't break 
        // in other browsers.
        if (elem.getContext('2d')) {
            // Get the 2d context.
            var context = elem.getContext('2d');

            context.fillStyle = "#62ADE3";
            context.fillRect(0, 0, 500, 500);
			
            drawLine(10, 10, 100, 100);
			drawCircle(150, 60, 50);
			drawCurve(150, 150, 200, 100, 250, 150);
			writeText("Welcome to HTML 5",250,40);
			drawRect(300, 60, 150,100);
			drawArc(100, 200, 25, 1* Math.PI, 2* Math.PI, false);
			drawArc(200, 200, 25, 1/2 * Math.PI, 2* Math.PI, false);
			drawArc(300, 200, 25, 1/3 * Math.PI, 2* Math.PI, false);
			drawArc(400, 200, 25, 0 * Math.PI, 2* Math.PI, false);
        }
	}

	function drawArc(pointX, pointY, radius, startAngle, endAngle, clockwise)
	{
		var canvas = document.getElementById("myCanvas");
        var context = canvas.getContext("2d");
        context.beginPath();
        context.arc(pointX, pointY, radius, startAngle, endAngle, clockwise);
        context.lineWidth = 15;
        context.strokeStyle = "black";
        context.stroke();
	}
	
	function drawRect(pointX, pointY, width, height)
	{
		var elem = document.getElementById('myCanvas');
        var context = elem.getContext('2d');
		context.rect(pointX, pointY, width, height);
        context.fillStyle = '#8ED6FF';
        context.fill();
        context.lineWidth = 5;
        context.strokeStyle = 'black';
        context.stroke();
	}
	
	function writeText(text,pointX, pointY)
	{
		var elem = document.getElementById('myCanvas');
        var context = elem.getContext('2d');
		context.font = "20px tahoma";
		context.fillText(text, pointX, pointY);
	}
	
	function drawCircle(centerX, centerY, radius)
	{
		var elem = document.getElementById('myCanvas');
        var context = elem.getContext('2d');
		context.beginPath();
        context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
        context.fillStyle = "#8ED6FF";
        context.fill();
        context.lineWidth = 5;
        context.strokeStyle = "black";
        context.stroke();
	}
  
  function drawCurve(point1X, point1Y, point2X, point2Y, point3X, point3Y)
	{
		var elem = document.getElementById('myCanvas');
        var context = elem.getContext('2d');
		context.beginPath();
        context.bezierCurveTo(point1X, point1Y, point2X, point2Y, point3X, point3Y);
        context.lineWidth = 5;
        context.strokeStyle = "black";
        context.stroke();
	}
  
    function drawLine(sourceX, sourceY, destinationX, destinationY) {
        var elem = document.getElementById('myCanvas');
        var context = elem.getContext('2d');
        context.strokeStyle = "rgb(0, 0, 0)";
        context.moveTo(sourceX, sourceY);
        context.lineTo(destinationX, destinationY); // Black line
		context.lineWidth = 3;
        context.stroke();
    }
    
</script> 
</head>
<body onload = load();>
	<canvas id="myCanvas" width="500" height="250">
		Hi I am Mr.Canvas and your browser doesn't support me :(
	</canvas>
</body>
</html>



Ok double click the file and check how your cavas is painted.
Whenver playing around with canvas you will do all the stuffs in javascript, so the below body part is untouched.
From next post lets look into each of the elements in depth.

Happy Learning :)
Codingsense

Posted in HTML 5 | Tagged: , | 1 Comment »

What is HTML 5?

Posted by codingsense on August 25, 2012


As per Wikipedia,
HTML5 is a markup language for structuring and presenting content for the World Wide Web, and is a core technology of the Internet originally proposed by Opera Software. It is the fifth revision of the HTML standard (created in 1990 and standardized as HTML4 as of 1997) and, as of August 2012, is still under development. Its core aims have been to improve the language with support for the latest multimedia while keeping it easily readable by humans and consistently understood by computers and devices (web browsers, parsers, etc.). HTML5 is intended to subsume not only HTML 4, but XHTML 1 and DOM Level 2 HTML as well.


Basically, HTML 5 is the latest version of HTML released which has added many functionalities, giving us a good set of features with which we can develop very rich and iteractive web applications without depending much on any other tools.


For HTML5 references,
What’s New in HTML 5?
HTML 5 and Visual Studio


Browser limitations:
None of the available browsers support all features of HTML 5 specifications. I found a website http://html5test.com/ which gives points on how much support the browser provides for HTML 5. I checked with most of the browsers and found google chrome to take the highest points of 437. In future all browsers should support all features provided by HTML 5, but to play around now I am currently using google chrome browser.

From next post lets dive deep into some of the new elements provided in HTML 5.

Happy learning :)
Codingsense

Posted in HTML 5 | Tagged: | Leave a Comment »

Sincere Apologies

Posted by codingsense on August 25, 2012

Guys I am back after quite a long time. Please accept my sincere apologies if I have made you wait for my replies or if you didnt get it on time.

I was busy with my project work for sometime and skipped blogging and it became an habit :( . I got enough questions from my well wishers on why I stopped blogging.

BTW what did I do for so long?????
I was focusing on some non functional areas as

And while in these work I came to know why the above non functional areas are as equally important and the functional areas. Our team even got design excellence award in our company for these work :).

Then one day recently my eyes catched up with HTML 5 and on some of the experiments people are doing with it, its truly amazing. Check out few HTML5 experiments here. I have started doing few samples to get a proper hands on HTML 5 and to know how to use HTML 5 to build next generation web applications.

I will soon try to come up with some posts to explain on each of the above items.

Happy learning :)
Codingsense

Posted in Uncategorized | Leave a Comment »

2010 in review

Posted by codingsense on January 2, 2011

The stats helper monkeys at WordPress.com mulled over how this blog did in 2010, and here’s a high level summary of its overall blog health:

Healthy blog!

The Blog-Health-o-Meter™ reads Wow.

Crunchy numbers

Featured image

About 3 million people visit the Taj Mahal every year. This blog was viewed about 52,000 times in 2010. If it were the Taj Mahal, it would take about 6 days for that many people to see it.

 

In 2010, there were 15 new posts, growing the total archive of this blog to 63 posts. There were 10 pictures uploaded, taking up a total of 166kb. That’s about a picture per month.

The busiest day of the year was December 14th with 282 views. The most popular post that day was Left Join, Right Join Using LINQ.

 

Where did they come from?

The top referring sites in 2010 were google.com, google.co.in, codeproject.com, yandex.ru, and social.msdn.microsoft.com.

Some visitors came searching, mostly for linq left join, left join linq, linq join, left join in linq, and linq join example.

Attractions in 2010

These are the posts and pages that got the most views in 2010.

1

Left Join, Right Join Using LINQ March 2009
16 comments

2

Customize a slider in WPF, Step by Step Tutorial February 2010
1 comment

3

Difference between Select and SelectMany in LINQ September 2008
7 comments

4

MSSQL Output in XML using For XML December 2008

5

Bulk Insert and Update MSSQL December 2008
14 comments

Posted in Uncategorized | 1 Comment »

The designer cannot process the code at line

Posted by codingsense on December 5, 2010

From somedays back I was getting a weird problem while opening the design of windows form. The error message looked like the below one

The designer cannot process the code at line 37: this.comboBox1.Items.AddRange(new []{ “one”, “two”, “three”, “four”}); The code within the method ‘InitializeComponent’ is generated by the designer and should not be manually modified. Please remove any changes and try opening the designer again.

If I commented the AddRange line it was working fine or It was pointing at the next line those had AddRange method. I quickly googled for the solution and found many but none of the fix was useful. By careful observation I found that something was missing the line. See if you can observe what’s missing the below line ;)

 this.comboBox1.Items.AddRange(new []{
“one”,
“two”,
“three”,
“four”});

Just adding the type of the array that I was creating solved my problem, for above problem I added new object[] and then all worked fine.

this.comboBox1.Items.AddRange(new object[]{
“one”,
“two”,
“three”,
“four”});

After fixing the issue I started searching for the person who had removed it, I wanted to show him the issue so that he will not do the same next time. After searching for hours I found that it was Mr. ReSharper who had removed the type. From then I started carefully using Resharper instead of just clicking on what it suggests.

Happy coding :)
Codingsense

Posted in Uncategorized | 2 Comments »

Zip/Unzip using System.IO.Package in .Net

Posted by codingsense on December 5, 2010

I was working on a project where it was required to zip and unzip files, these days we were using Cabarc.exe and all was working fine. Now we planned to give unicode support and booom!! cabarc.exe failed to zip the folder, since it does not support unicode characters. I found that there are many open source projects like SharpZipLib, DotNetZip etc. But we did not wanted to use the available open source projects to implement it. So I decided to search for some other option and what I found is System.IO.Package in WindowsBase.dll. It exposes a class called Package which will help to pack and unpack files and folders.

Download Source code (13 Kb)

I have made a separate dll (CustomPackage.dll) that you can use for zipping and unzipping of folders. I have also created a dummy project PackageWrapper to help you understand how to make calls to the dll.

Features:

  • The project supports Unicode characters in folder or files (Limitation with Cabarc.exe)
  • Zipping is done also for all sub directories . While unzipping the same directory structure will be maintained.

Improvements for you to do:
I have used Mime Type as MediaTypeNames.Application.Octet to make it generic and support all kind of files and have used the compression option CompressionOption.NotCompressed since the mime type will not compress. If you know that you will have only similar type of files to zip or unzip then you can select proper Mime type and compression option as CompressionOption.Maximum to compress the files to maximum extent.

For any kind of improvements or clarifications please feel free to comment.

Happy Coding :)
Codingsense

Posted in C# | Tagged: | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.