Vítejte na blog.vyvojar.cz Přihlásit | Registrovat | Pomoc

Static code analysis daily report

I have my own license of NDepend Professional (developer edition) and I would like to monitor quality of our source code during iteration. So I scheduled NDepend.Console.exe to run daily before midnight. The only prerequisites are to have updated source files and to have solution compiled when I’m leaving office. I usually have both so it’s not problem for me to fulfill both requirements and schedule the task. It took me a few minutes and now I have this report which can warn me if something goes wrong.

In the report there’s a Summary of Rules violated, which looks great, but it’s not so useful for me, because if whole team don’t care about these rules there is always any violated rule (mainly in big teams). This list was mostly same yesterday and tomorrow it will be similar.

image

I would like to monitor if our code isn’t getting worse so I use these nice Trend charts below which use history of my daily builds. Thanks to these charts I spend only few minutes per day to check code quality and I’m able to alarm team if something goes wrong.

image

image

image

Posted by ernest | 0 Comments
Vedeno pod:

How to monitor Too Big metric using NDepend

Technorati Tags: ,
imageWhen I saw Treemap View in HTML report first time I was thinking that it’s just nice visualization of some metric. You know one of funny visualizations such as Gource, but after opening the map in VisuaNDepend I found out that it’s more.

It can be used for many common scenarios and I'm going to start with Too Big, Too Complex.

It’s just visualization, but it makes me think: how important is class size?

If it works and it’s small I don’t mind if it’s alright or buggy (OK, I don’t mind because I don’t know) let the method stay there. But if the box is buggy only small ones can be replaced easily.image

For me it’s really important if it’s big, because in such case it’s mystery box.

Many lines of code will stay untouched for a long time, just it’s not possible to maintain them. How could you maintain millions lines of code? So we need visualization to quickly discover too big types/methods which are potentially source of problems.

NDepend’s Treemap View is not only visualization, but it displays additional info about the method and it allows diving directly into source code. Some alerting based on this can be useful and NDepend can warn you using Methods too big rule. But I want to avoid the warning we can use awesome Trend charts, here’s screenshot of a such chart.

image

This trend chart is visible in Dashboard panel so I can see it directly after I open VisualNDepend. On a daily basis it’s better to me to see it in report, because I can just quickly check it and go to develop.

Posted by ernest | 0 Comments

NDepend code query for static classes

I got an offer to test NDepend Professional version. I’ve accepted and installed the tool. For those who don’t know what it is, you can read a lot on their homepage. I would like to share with my first impressions about this interesting software.

Let’s dive into code analysis more deeply.

Background

In last project I found a class that has a lot of methods and all of them were static. It was impossible to write unit test and the test doesn’t exist yet.

I started thinking why it happened and it seems to me that the problem is because that there’s structured (not object oriented) code. There’s many dependencies, many conditions, high complexity. We had to put SuppressMessage on the main method, because our code analyzer reports high code complexity after I added one single condition (you know in regression we don’t bigger changes).

So I made this query which should report about all such classes (potential time bombs) in our code. I will not write how many classes I found, but here’s the query and you can try on your own (if you have NDepend of course).

Static classes code query

// <Name>State holders candidates</Name>
// Non-static types with many static methods
// which probably pass the state
// in parameters

warnif count > 0 from t in JustMyCode.Types
where t.Methods.Where(m => !m.IsStatic).Any()
&& t.Methods.Where(m => m.IsStatic).Count() > t.Methods.Where(m => m.IsStatic).Count()
&& !t.IsStatic
orderby t.Methods.Count() descending
select new { t, t.InstanceMethods, t.StaticMethods }

Posted by ernest | 0 Comments
Vedeno pod: ,

To unit test or not to unit test?

Yesterday we were discussing about some BL code and we was not able to agree if we should write fast unit tests testing the new class or if we should write integration tests testing all classes up to the database. I’ll try to sum up:

Integration tests Unit tests
can be written without refactoring requires refactoring to allow mocking of DAL (i.e. Unit-testing with Service Locator, Stubbing out ServiceLocator for unit testing)
requires a data helper for filling a database requires a data helper for returning a data (data can be generated on the fly)
tests all at once (BL, DAL, DB scripts) tests only the class
allows BL to have side effects (it stores some additional data somewhere else?) needs to know class dependencies (it’s required to mock all DAL objects)
usually positive tests only positive and negative tests too (What is positive test and negative test in unit testing)
runs long runs very fast

What I see is that integration tests are useful if you don’t worry about complexity of the tested class and don’t worry about test speed. If you write unit tests it forces you to write simple classes and you can take advantage of the tests speed.

I would like to hear your voice, to write unit tests or not to write unit tests?

Posted by ernest | 3 Comments

SolarWinds SWIS API Cheat Sheet

I’m fun of PowerShell and I use it in my new job from time to time. We use it for calling SolarWinds SWIS SDK. Because I’m not PowerShell/SWIS guru (yet) I’ve made a quick cheat sheet which allows me to quickly call what I need.

Feel free to use it if you need it

Posted by ernest | 0 Comments

New word in IT – Insight

I noticed that there’s new word in IT. We’re developing AppInsight for SQL, Microsoft has StreamInsight and right now I found out that Perforce introduces Insights too.

Posted by ernest | 0 Comments

Browser statistics in 2013 and 10 years ago

According to browser statistics on w3school.com Internet Explorer lost 70%:

2013 Internet Explorer Firefox Chrome Safari Opera
January 14.3 % 30.2 % 48.4 % 4.2 % 1.9 %

and 10 years ago

2003 Internet Explorer Mozilla Netscape Opera
January 84.6 % 4.0 % 4.0 %  

It can be seen that IE is still loosing every month. Should we still design pages for IE6 or IE7?

Posted by ernest | 0 Comments

How to check if IP address is localhost?

There’s many articles how to check local IP addresses in C#, but many of them (OK, first few links on Google) uses DNS. The problem is that DNS is in Application layer in OSI model, so the algorithm relies on DNS usage on server. I think that better is to use Network layer directly:

   1: public static bool IsLocalHost(IPAddress ipAddress)
   2: {
   3:     var allNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
   4:     return allNetworkInterfaces
   5:         .Contains(adapter => adapter.GetIPProperties().UnicastAddresses
   6:             .Where(address => address.Address.AddressFamily == AddressFamily.InterNetwork || address.Address.AddressFamily == AddressFamily.InterNetworkV6)
   7:             .Contains(address => address.Address.Equals(ipAddress)));
   8: }

I skipped some checks of the method input just to demonstrate how it can be done.

Hopefully you’ll find this useful

Posted by ernest | 0 Comments

Why should every developer take care about good class design

Few days ago I had to re-implement some piece of code. It should be easy, but I spent 20 minutes to change one line of code. Why?

Some background

Because I always try to write unit tests I had to change creation of a dependent class. The instantiation and main call was done like this:

var version = new Version(BuildInfo.Version.Major, 0, 0, BuildInfo.Version.Revision);

var manager = new LicenseManager();

var license = manager.GetLicense(appName, version);

Because the class implements ILicenseManager and we're using Service Locator, I rewrited the code to use interface instead:

var version = new Version(BuildInfo.Version.Major, 0, 0, BuildInfo.Version.Revision);

var manager = ServiceLocator.GetService<ILicenseManager>();

var license = manager.GetLicense(appName, version.ToString());

Great, now the call is testable by a unit test. But as you can notice there's a change in GetLicense() method call. It's because the interface doesn't include the overloaded method with strongly typed parameter version. It takes string instead. But I don't mind let's call ToString().

Step-by-step to solve the problem

After testing the code I found that the overloaded GetLicense() method returns null. Why? I had to do some steps to find the reason, here they are:

  1. Analyzing log files and founding the NullReferenceException - 20 seconds
  2. I checked method documentation (it was fast, ReSharper has a nice shortcut Ctrl+Shift+F1), but no documentation exists - 10 seconds
  3. I had to debug the program to be sure that parameters are correct, so I started debugging (remember It should be small change and I didn't have written unit tests yet) - it took 5 minutes to start the program (because of compilation and web site optimization)
  4. I put breakpoint to the source code and I was going to web site to test the call - 30 seconds
  5. I checked parameters using Watch - parameters were OK,expression version.ToString() returned "5.0.0.565" properly - 10 seconds
  6. I checked manager instance if it was instantiated properly (some casting problems) - 60 seconds
  7. I found out that the manager is in referenced assembly, so I cannot step into source codes directly, so I tried to find source codes - 10 minutes
  8. I found that I'm not able to find source code in our version control system, I have to treat it as third-party library, so I started ILSpy and looked at the method implementation - 30 seconds
  9. I finally got it, the method requires version.Major.ToString() – 5 seconds
  10. I had to go to coffee - 3 minutes

Final implementation

var version = new Version(BuildInfo.Version.Major, 0, 0, BuildInfo.Version.Revision);

var manager = ServiceLocator.GetService<ILicenseManager>();

var license = manager.GetLicense(appName, version.Major.ToString());

Conclusion

We all know such problem solving. It happens to us every day. Checking documentation, log analyzing, debugging code. We spend a lot of time with solving such issues. If you study the step-by-step above you can easily find out that if the method had documentation the solution would take 30 seconds instead of 20 minutes. Following takes me about 30 seconds to write:

/// <summary>

/// Returns license based on application name and major version number.

/// </summary>

But it isn't the only way how to precede errors. In first place the interface should contain the overloaded method with strongly typed version parameter.

I found some other problems with designing classes:

  1. If we publish a method on a concrete class instead on an interface, consumers will always use concrete implementation, not the interface.
  2. If we write documentation on public methods we will safe our time
  3. If we design strongly typed parameters we will avoid typo and additionally we will safe time with parsing strings

It can be seen that good class design matters. And I think that matters a lot. We have to remember that

We design classes for us

Do you have your own suggestions how to design classes or what anti-patterns we should avoid?

Posted by ernest | 1 Comments

Using WinMerge with TFS

Using WinMerge with TFS

Great, thank you Rory

Ernest

Posted by ernest | 0 Comments
Vedeno pod:

ReSharper vs CodeRush vs JustCode

This is brief comparison of code some development tools integrated in Visual Studio.NET, which I did for my new company. This post doesn't try to compare all refactorings, but it tries to compare product as a whole. The comparison targets VS.NET 2010 and C#.

JetBrains ReSharper - http://www.jetbrains.com/resharper/

DevExpress CodeRush - http://devexpress.com/Products/Visual_Studio_Add-in/Coding_Assistance/

Telerik JustCode - http://www.telerik.com/products/justcode.aspx

I used Google as an information source. If anything is wrong please write a comment, I will update the table.

UPDATE: I updated the table with some details according comments below. Thank you all for your help. 

Feature\Product

JetBrains
RerSharper C#
v7.0

DevExpress
CodeRush Refactor! Pro
v12.1.5

Telerik
JustCode
v2012.1.608.4

 

Personal Price

€142+VAT

$249.99

$249

Commercial Price

From  €237+VAT

Contact

$249.99

Free version

Trial

Xpress 11.2.12

Trial

VS.NET 2010 (.NET 4.0)

Yes

Yes

Yes

VS.NET 2012 (.NET 4.5)

Yes

Yes

Yes

Technologies/Languages

EDM

No

No                 

No

Silverlight

Yes

Yes

Yes

Windows Phone

Yes

No

Yes

Metro style apps

Yes

No

Yes

WinRT

Yes

No

Yes

XAML

Yes

Yes

Yes

Javascript

Yes

Yes

Yes

CSS

Yes

Yes

Yes

XML

Yes

Yes

Yes

Scripting

MSBuild/NAnt

No

No

Extensibility (plugins)

Yes

Yes

Yes 

Features

Code analysis

Class/Solution

Class/Solution

Class/Solution

Unit test runner

NUnit,MSTest,MbUnit,NBehave,csUnit,xUnit.Net

NUnit,MSTest,MbUnit, MSpec,xUnit

MSTest, xUnit, NUnit, MbUnit, Galio, MSpec, QUnit, Jasmine

Silverlight unit test runner

AgUnit plugin (v 0.6)

SlUnitTesting included

No

Call/Value tracking

Yes

No

No

Annotated Framework

Yes (with own annotations too)

No

No

Code coverage

JetBrains dotCover product

No

No

Duplicate Detection and Consolidation

No

Yes

No

Code metrics

No

Yes

No

Navigation

Navigation

Camel Humps

Camel Humps

Camel Humps

Type Hierarchy

Yes

No

 

File Structure

Yes

No

 

Stack Trace Explorer

Yes

No

 

Find Usages

Yes

Yes (The References Toolwindow)

Yes

Tab to next reference

No

Yes

Yes (Ctrl+Alt+Up/Down)

Code Generation/Refactoring

Create from usage

Yes

Yes

Yes

Templates

Yes

Yes

Yes

Cleanup

Yes

Yes

Yes

Move Class/Method

Yes

Smart Copy&Paste

Yes

Naming Style checker

Yes

Code Style Enforcer plug-in

Yes

Intelligent paste

No

Yes (type cast, field declaration, color reference …)

No

Context menu fixes

Yes

Yes

Yes

 

Posted by ernest | 7 Comments

Smurf Naming Convention and Megamoth rock

Probably all of you have some own programming jargon. You will probably fall in love to New programming jargon post (I did). In my last job, the favorite was Smurf Naming Convention and MEGAMOTH!


Posted by ernest | 0 Comments
Vedeno pod:

What Inversion of Control brings to us?

Inversion of Control (IoC) is a very nice concept, one of my favourite. It helps easily extend existing code without need to make change to the extended library. It is based on an idea of injecting class dependency into an object oriented code. What does it mean?

There is many posts on the Net with subject Inversion of Control (IoC). Shortly it means exactly what it says: the pattern inverses the way how objects controls other objects. The straightforward way of using other object is to create it directly with constructor. The other way (in IoC manner) is to request/gain the object from someone else.

Nice simple example can be seen here.

This concept is not new to many developers. For example about 18 years ago this concept was used in Turbo Vision to create text user interface:

TMenuBar *newMenu = new TMenuBar( r,
    *
new TSubMenu( "~\360~", kbAltSpace ) +
    *
new TMenuItem( "~A~bout", cmAbout, kbAltA, hcNoContext ) +
    newLine() +
    // this TMenuItem will bring up another menu
    *new TMenuItem( "Exit", 0, new TMenu(
    *
new TMenuItem( "Exit & ~S~ave", cmQuit, kbAltX, hcNoContext, 0,
        new TMenuItem( "Exit & ~A~bandon", cmQuit, kbAltY, hcNoContext, 0,
        new TMenuItem( "Just ~Q~uit", cmQuit, kbAltZ, hcNoContext, 0,
        new TMenuItem( "~N~ext Level", 0, new TMenu(
            *
new TMenuItem( "~O~ne", cmQuit, kbAltX, hcNoContext, 0, 
            new TMenuItem( "~T~wo", cmQuit, kbAltX )))) 
    )))), hcNoContext)
    );

However I think that in these days the concept is more important than ever. It is so important that I recommend to think about it a little. What it can bring to us today?

Every customer has different needs

First, it may solve the problem of customizations. Think that you have a software which you sell to many customers. The problem is that every customer wants the software to behave in a different manner and if you have dependencies between classes hard coded using constructors you have only 2 choices. You may tell the customer that the software doesn’t support this behavior, because the change will influence other customers when you give them upgrade. When you say this you may loose the customer.

Probably you change the software. However you need to make the change only for this customer so you create a copy of the source code and make changes in the copy. Now you have a separate copy of a software for each customer and everybody is happy. Except a developer, who must keep many programs up to date (think that every copy is independent program). Copy and paste approach raises many problems for example bug fixing.

IoC (along with good object oriented design) allows developers not to make source code copies. Instead of copying developers are able to take advantage of inheritance. With IoC concept you can inherit the class, change its behaviour and let dependent objects use instances of your inherited class. Sounds good, doesn’t?

Error free upgrades

Another problem is quality. If you have a complex software it’s very hard to keep it in a good quality (so without errors) while you add new features. Any change in the software may arise to a problem because a small change in one class may cause an error in another dependent class. How can IoC help us to solve this problem? The solution to this is not IoC itself but it’s unit testing. And in unit testing is IoC very important.

Unit test is piece of code which tests output of methods and classes. Proper unit test needs a tested class to have good object oriented design and it must use IoC. Then the unit test is able to run very fast (milliseconds) and it ensures that the class remains in a good condition after you’ve made a change in it. Unit tests must test functionality of a single class not the whole underlying framework so you need to simulate dependent objects and here is the IoC concept important, because in unit testing you usually create fake/mock objects on which tested classes depends.

Conclusion

You may see that the Inversion of Control concept becomes more and more important, because developers are pushed by customers to deliver programs in some quality and flexible enough to meet individual customer requirements. However the concept is not the only solution. The code needs to meet object oriented design mainly it must use encapsulation of its inner fields. It’s not difficult to achive this encapsulation. You can use many of refactoring methods to clean smelly code, but this is not goal of this post.

If you found my article useful you can continue to read what Martin Fowler writes about Inversion of Control.

I wish you happy coding

Posted by ernest | 0 Comments
Vedeno pod:
Více článků Další stránka »