Showing posts with label Tools. Show all posts
Showing posts with label Tools. Show all posts

Tuesday, September 25, 2012

Control the Complexity of Your JavaScript Functions with JSHint

New JSHint Features


Many of you are aware of the JSHint code quality tool that has been around for the past couple of years. As of recently, the following new options that have been added regarding the complexity of a function.

  • maxparams
  • maxdepth
  • maxstatements
  • maxcomplexity

Parameters, Depth, and Statements


By reducing the number of parameters, the number of nesting, and the number of statements in your function you can dramatically increate the readability and modularity of your code.

The following piece of code shows using the maxparams, maxdepth, and maxstatements to warn us of possible issue with our functions.



JSHint gives an error that too many parameters were used because we limited maxparams to 3 and the code accepted 4 parameters. An error occurred because the depth of logic is too deep because we limited it to a maxdepth of 2. We will also get an error about the number of lines in our function because we limited maxstatements to 5 and we have many more than that.

Cyclomatic Complexity


A less commonly known software metric used to evaluate functions is Cyclomatic Complexity. Like it sounds, it's purpose is to calculate the overall intricacy of a function and to give a score that reflects it's complexity.

"The cyclomatic complexity of a section of source code is the count of the number of linearly independent paths through the source code." --http://en.wikipedia.org/wiki/Cyclomatic_complexity

In addition to the above parameters, depth, and statement metrics you can now track the overall complexity using the maxcomplexity option.



As you see above, the above function has more complexity that what we set in maxcomplexity.

You might be wondering what a reasonable maxcomplexity value is for your project. In the 2nd edition of Steve McConnell's Code Complete he recommends that a cyclomatic complexity from 0 to 5 is typically fine, but you should be aware if the complexity starts to get in the 6 to 10 range. He further explains that anything over a complexity of 10 you should strongly consider refactoring your code.

Global Options


Instead of adding these options to the top of each and every JavaScript file you an instead use a .jshintrc file in your project and JSHint should pick up those settings. This is handy if your project is large and you want some consistent settings across the board.



Wednesday, November 12, 2008

New F# SyntaxHighlighter Brush

Ever since my previous blog about Code Highlighters For Your Blog, I have heard several people interested in implementing the SyntaxHighlighter on their blog. If so, there is a good article by Guogang Hu about integrating it into your Blogger blog.

One of those individuals was my friend, Daniel Mohl (via twitter... @dmohl). However, Daniel had a need to support F#, which is not one of the out-of-the-box languages that is supported by the SyntaxHighlighter. I saw this as a fun side project to support this language for him.

F.Y.I. If you like F#, his blog is definitely one you should check out!

Here is an example F# program that is only a proof of concept that Dan put together for me to exercise the F# brush sufficiently... it doesn't actually work! :) I am just starting to learn the language, so please give me some slack!

If you find any areas that I missed while supporting the language, please let me know and I'll fix it. Feel free to download and use the F# SyntaxHighlighter Brush and provide any suggestions or comments.

Note: The JavaScript file has been minimized with JSMin, so it might be a little difficult to read.

I'd like to contribute the F# Brush to the Google Code project, but I am not yet a contributor on the project. If I am able to become a contributor, then I will post the code as part of the main project.

#light
namespace testforElijah
module testModuleForElijah
open System
let multiple x = x * x
val CalculateSeqExample: seq<int> -> int
type ICustomerDao = interface
    abstract GetById: int -> ICustomer
end
type CustomerDao = class
    new: unit -> CustomerDao
    interface ICustomerDao
end
if
then
elif
else
@"c:\test\test.xml"
'c'
"xyz"B
"tes"+"t"
[for x in list -> expr]
type 'a option = 
  | None
  | Some of 'a

//This is a test
let showSomething (name, something)
  match name with
    | Some  (some, thing) -> (* do something*)
    | None
 
type node = 
  { Name : string;
    Links : list list;}
and link = 
  | Dangling
  | Link of node 

Thursday, October 30, 2008

An NDepth Look @ NDepend

Synpopsis

I've been wanting to review NDepend for quite some time, but I figured it was bad form to run it against my production code from work.

So, instead of running the tool against my work code, I thought I'd use the PetShop ASP.NET MVC project that I created for the .NET User's Group.

NDepend provides many ways to visualize the architecture of any particular project.  To create the following pictures and diagrams all I did was point NDepend to my Visual Studio solution file.

Dependency Graph

A useful way to get an understanding of how your application architecture is to generate a Dependency Graph based off your code. The following graph shows show the PetShop pieces relate to one another.

 

Dependency Matrix

For those of you who are graphically challenged, there is a Dependency Matrix that does a nice job of showing how many dependencies there are between 2 particular areas of your design.

  

Code Metrics

The next diagram has always impressed me. Even if you didn't know what it meant... it is pretty impressive to just look at :) The following diagram is actually showing the Code Metrics for your project. The following image represents the number of lines of code (LOC) in your project.  


CQL Queries

In addition to all these cool graphs, matrices, and images, there are some hard core queries that you can perform against your assemblies. NDepend has something called Code Query Language (CQL) that allows you to write custom queries to identify numerous statistics such as:
  • Which public methods have more than 30 lines of code?
  • Which classes implement System.IDisposable?
  • Which methods have been refactored recently and is not thoroughly covered by tests?
  • etc...

 

The following is an example of what a CQL query looks like. This query identifies the methods that are too big in your assembly. NDepend comes with a library of already created queries, such as this one, but you are able to add to or customize these quieres as well. 


Conclusion

There is so many more features that I haven't covered that NDepend provides, but I wanted to highlight some of the features that I thought are very useful and could help you in your current projects.

I think this tools adds some great functionality that dovetails nicely with the features of from the various Visual Studio suites.

Don't just take my word for it, I encourage you to download a trial version of NDepend and check it out for yourself.

Then if you like it, make a list of the features that are useful for your project, show it to your boss, and see if your work will pay for it :)

Thursday, September 25, 2008

IE8 Beta 2 Pros


I do like the Developer Tools that are embedded in IE 8 Beta 2. They are about equivalent to what Firebug is to Firefox, which is a great step in the right direction.

I have also noticed that the errors returned from JavaScript exceptions are much more descriptive and accurate compared to IE7 or before.

Wednesday, July 23, 2008

jQuery Flexigrid Using C# 3.0 (.NET 3.5) & LINQ

When I developed my first ASP.NET MVC application, I was a little disappointed with my options for a rich grid. I initially used the grid that is part of the MVCContrib project, but it is pretty simple and there aren’t many features out of the box.

I was very pleased with the code of my MVC application, but the presentation was so 1990's. With all of this new technology I thought the presentation deserved something snappy. That is when I found Flexigrid.

As I mentioned in my last blog entry, I started to use jQuery. To my joy, Flexigrid is a jQuery plugin! Flexigrid uses jQuery to asynchronously populate the contents of the grid using either XML or JSON input.

The following is an example of what the grid looks like. It contains features to sort, page, search, move columns, resize, etc…

flexigridExample

The User Interface portion was pretty straightforward to put together. You just need to define your columns, the data source, and some additional parameters (such as: search terms, size, etc…).

   



I wanted to use this opportunity to try out some new features of .NET 3.5, so I wanted to incorporate LINQ and JSON serialization.

To do this, I needed to setup some classes that the Flexigrid will recognize once serialized. Here is what I came up with.
   1: public class FlexigridViewData
   2: {
   3:     public int page;
   4:     public int total;
   5:     public List<FlexigridRow> rows = new List<FlexigridRow>();
   6: }
   7:  
   8: public class FlexigridRow
   9: {
  10:     public long id;
  11:     public List<string> cell;
  12: }
Now is the part where the fun begins. I had already retrieved the content I needed from the Middle Tier. I use LINQ to query the generic list to obtain the correct page subset and then use a helper extension method to serialize the contents to JSON.
   1: public void Page_Load()
   2: {
   3:     Response.Clear();
   4:     Response.ContentType = "text/x-json";
   5:     Response.Write(GetPagedContent());
   6:     Response.Flush();
   7:     Response.End();
   8: }
   9:  
  10: private string GetPagedContent()
  11: {
  12:     var pageIndex = Convert.ToInt32(Request.Params["page"]);
  13:     var itemsPerPage = Convert.ToInt32(Request.Params["rp"]);
  14:     var sortName = Request.Params["sortname"];
  15:     var sortOrder = Request.Params["sortorder"];
  16:     var query = Request.Params["query"];
  17:  
  18:     IEnumerable<Contact> pagedContacts;
  19:     if (string.IsNullOrEmpty(query))
  20:     {
  21:         pagedContacts = sortOrder.Equals("asc") ?
  22:             Contacts.OrderBy(contact => contact.GetPropertyValue<IComparable>(sortName)) :
  23:             Contacts.OrderByDescending(contact => contact.GetPropertyValue<IComparable>(sortName));                
  24:     }
  25:     else
  26:     {
  27:         Func<Contact, bool> whereClause = (contact => contact.GetPropertyValue<string>(sortName).Contains(query));
  28:         pagedContacts = sortOrder.Equals("asc", StringComparison.CurrentCultureIgnoreCase) ?
  29:             Contacts.Where(whereClause).OrderByDescending(contact => contact.GetPropertyValue<IComparable>(sortName)) :
  30:             Contacts.Where(whereClause).OrderBy(contact => contact.GetPropertyValue<IComparable>(sortName));
  31:     }
  32:     int count = pagedContacts.Count();
  33:     pagedContacts = pagedContacts.Skip((pageIndex - 1) * itemsPerPage).Take(itemsPerPage);
  34:  
  35:     const string imageLinkFormat = @"<a href=""{0}""><img src=""{1}"" border=""0"" /></a>";
  36:     const string imageFormat = @"<img src=""{0}"" border=""0"" />";
  37:     var flexigrid = new FlexigridViewData {page = pageIndex, total = count};
  38:     foreach (var contact in pagedContacts)
  39:     {
  40:         flexigrid.rows.Add(new FlexigridRow
  41:         {
  42:             id = contact.ID,
  43:             cell = new List<string> 
  44:             { 
  45:                 string.Format(imageLinkFormat, ResolveUrl("~/Contact.mvc/Detail/" + contact.ID), 
  46:                 ResolveUrl("~/Images/Detail.gif")), 
  47:                 contact.ID.ToString(), 
  48:                 contact.FirstName, 
  49:                 contact.LastName, 
  50:                 contact.DateOfBirth.ToShortDateString(), 
  51:             }
  52:         });
  53:     }
  54:  
  55:     return flexigrid.ToJson();    
  56: }
Here are some helper extension methods that I used to complete the above code snippets.
   1: public static class JsonHelper
   2: {
   3:     public static string ToJson(this object obj)
   4:     {
   5:         var serializer = new JavaScriptSerializer();
   6:  
   7:         return serializer.Serialize( obj );
   8:     }
   9:  
  10:     public static string ToJson(this object obj, int recursionDepth)
  11:     {
  12:         var serializer = new JavaScriptSerializer();
  13:  
  14:         serializer.RecursionLimit = recursionDepth;
  15:  
  16:         return serializer.Serialize( obj );
  17:     }
  18: }
   1: public static T GetPropertyValue<T>(this object component, string propertyName)
   2: {
   3:     return (T) TypeDescriptor.GetProperties(component)[propertyName].GetValue(component);
   4: }
As a side note, I did have to dive into the JavaScript and fix two issues that I came across, but other than that it works like a charm.
I would prefer if the developer of the product had a better system of tracking bugs and maintaining a forum, but in the meantime what is setup is sufficient.

Wednesday, January 17, 2007

Firebug 1.0 Beta

For those of you who use Firefox, you should check out the Firebug 1.0 beta extension! I had used the old version for quite some time, but I was blown away with the great enhancments in the 1.0 beta version.

Here are some of its features...

Here is what Rich Strahl had to say about it...
"I’ve been using Visual Studio’s JavaScript debugging most of the time, but with Firebug in this state I’ve been able to move most of my debugging – except for IE specific issues which are unfortunately quite common – into Firebug.

Highly recommended."

Thursday, January 11, 2007

IE Developer Toolbar Beta 3

There is a new version of the IE Developer Toolbar from Microsoft!

"This Beta 3 version of the toolbar contains functionality and stability enhancements over previous versions, including:

  • Style Tracer: Right mouse click on a style value for an element and select Style Tracer to find the style rule that is effecting that value.

  • CSS Selector Matches: View a report of all style rules set and how many times they are used on the current page.

  • View Source: View the formatted and syntax colored source of the original page, currently rendered page, element or element with the styles that are effecting it."


To view some screenshots of these new features check out the Microsoft IE Blog.

Wednesday, January 10, 2007

Resource Refactoring Tool

By default, Visual Studio has a way to localize the text in a ASP.NET page, but there is no tool for extracting the text from the code behind or app_code files, until now!

There is a great new program, The Resource Refactoring Tool, that helps you localize your .NET applictions.

Most recently, they have added support for localizing the code behind files in a Web Applications... which is what I have been waiting for.

I installed and tested the tool and it is has been very handy.

Tuesday, November 07, 2006

BareGrep

I recently ran across a great tool ( BareGrep ) to perform UNIX-like grep commands in Windows. The more I use the tool, the more I continue to appreciate it.

You can download and use the software for free. If you purchase it, then the nag screen goes away and I think there may be more functionaity.

Anyway, today I was asked to extract all the references to color ( embedded styles and CSS classes ) from our web application. With all the RGB and HEX values dispersed across the site it could have been a tedious daunting task, however, with the help of BareGrep it didn't take very long.

I used BareGrep with the following settings to recursively search our codebase for references to RGB values.


 Folder: C:\starteam\myhealthIQ\UserInterface\Web
 Files: .*\.(cs|aspx|html|xsl|js|css|ascx|master)
 Text: (\(\s*\d+,\s*\d+,\s*\d+\s*\))

Note: I did another search for HEX values using another regular expression.

Once I got the results from the above two searches, I exported the values and ran a BareGrep "Invert Match" search against our standard colors ( example: "(196,\s*38,\s*39)|(165,\s*176,\s*65)|etc..." ) to isolate any unapproved colors.


I actually came across the above tool while I was looking for a Tail application for Windows and found BareTail. I recommend this tool as well if you need a tool to show the end of a log file in real time.

Monday, November 06, 2006

Google Code Search

Google is at it again. This time they have come out with a new tool to search open source code... called Code Search.

Some other code search tools that I found ( not associated with Google ) are

Saturday, September 09, 2006

CSS Adapaters Beta 2

For those of you who would like more control of your HTML output from ASP.NET 2.0, then check out the newly updated CSS Adapters Beta 2.

At one point I looked into using "CSS Adapters Beta 1" because the native asp:Menu HTML output does not work well with all browsers ( mainly Safari ). However, my direction was altered in another direction that didn't need the asp:Menu control, so Safari compatibility with the menu was no longer an issue.

Anyway, I know there are some hardcore CSS gurus who will do anything they can to not use tables for non-tabular data. If that describes you, or if you'd just like a little more control of your HTML output, then check out the CSS Adapters Beta 2.