The reason for this post is because I am still seeing Helper, Utility and Singleton implemented code in large enterprise scale solutions today. It is almost as bad as coding in Hungarian notation. Now this is to say that practices like Hungarian notation had a place and a purpose, notably when using dynamically linked languages such as C++ for example where you did not have type safety. Things have moved on since those days so PascalCase and camelCase are now the preferred convention, certainly within the .NET space and camel case preferred in the Java space.

Microsoft has a good post on Design Guidelines for Class Library Developers.

So really Helpers or Utilities come from (in my view) procedural languages and by definition they tend to be static types that often equate to “general stuff” that doesn’t fit anywhere else which is very much a procedural mind-set as when you build software in OO languages such as C# or Java, everything has a single responsibility.

This discussion has been flogged for years especially when .NET was becoming popular. But it seems all these discussions haven’t really changed peoples mind sets. Many developers still believe that a helper is a good thing. I am not sure how these patterns are perceived in the Java space but in .NET they are generally considered anti OO and there are good reasons for this which we will go into in this post. Nick Malik from Microsoft wrote this post 6 years ago about this very topic. I have to say I agree 100% to Nick’s comments. It’s actually quite scary to the responses Nick got to that post.

I have copied a particular comment here for reference from a chap named Nate on Nick’s blog, not to pick on Nate but purely for a discussion and example perspective:

This is all good and all, but if helper classes are undesirable, where do you put miscellaneous code that you would normally put in a helper class? Where does that method go that say, helps encode a URL? Or that function that converts an array to a comma delimited list? Or in C#, that wrapper for a certain Win32 API? In all practicality, I find that I often have these piddely tasks that don’t really lend themselves to encapsulation within an object and are pretty much on their own, but are called from myriad places. If I was coding in C++, I would place it outside of a class, but languages like C# and VB.NET don’t allow me to do that. Does it violate OO principles? Of course it does. But OO principles are not meant to be a straightjacket. All that said, I do agree that if they show up in a UML diagram, your helper class is probably doing more than isolating a “piddely task” and that something is probably wrong.

Helpers

For starters I’d like to say what “miscellaneous” stuff. This is one of the biggest issues with things like Helpers actually more with Utilities, they start out being quite small, but before you know they become a dumping ground for all things to man and beast. And to make things worst they tend to be of type static so very hard to test.

In Nates response above, I’d respond to possibly putting URL encoded functions as an extension method to the String class. But then you might say two things:

  1. Extension methods were not available back in 2005 when that blog post was written
  2. Extension methods are really helper classes anyway

The answer to the above is yes and yes! With point 2 the usage is rather different. Extension methods are helper classes in that you can only write static methods. But there is one major difference; you do not actually call the helper class directly. Instead extension methods are an extensibility point in the .NET type system that extends .NET. They often should only be very short functions that normally should not have dependencies. So the developer using an extension method should be very clear what the function is doing and should be able to use those functions in his unit tests without issues.

By the way, my extension method post linked above needs updating. Extension method classes should have the name <class>Extensions. I.e. for IEnumerable extensions, it should be IEnumerableExtensions. So here it’s very clear what are extension method classes and what are not.

So where should those URL encoded functions go back in .NET 2.0 before extension methods existed? The answer, I would incorporate a new class called URL with no static methods and make it part of my framework for my application. This then gives me the power to inject dependencies in the future should I need to and makes testing very easy.

So if class URL required dependencies I.e in the future we might want to send a sample message to a given URL which has a dependency on a custom communication adapter for example, it wouldn’t be a suitable candidate for extension methods anyway.

So take above scenario, if we had a helper class that looks like the following:

public static class Helper 
{ 
    public string static EncodeUrl(Url url) 
    { 
       // call encryption 
    } 
}

That looks ok, so for now forget about testability. But for one thing the class name is not particularly useful. So we could change it, or leave it as is. Often it will get left as is. So then another developer will think, “oh there’s a helper class for library functions”. “I’ll add my FoobarAppSpecificFeature method to it”. And so it goes on and then you end up with a god class.

God Classes

God classes are classes that do or know too much. They breach the Single Responsibility Principle. They are often a result of a procedural developer trying to implement an object oriented system with a global variable mind-set. They often do not fit in well with TDD (Test Driven Development) purely because the classes are hard to test in that they rely on external dependencies which are very hard to mock out. Also, they do not model the system in any way so maintainability comes into question as if you have god classes, you will also have god unit test classes and projects too.

Are Singletons Really bad?

I personally don’t think they are when used in conjunction with an IoC container. The reason here is that a singleton when used in conjunction with an IoC container looks no different from a non-static instance type. This is one of the major benefits of using IoC in that the life cycle is controlled by the container and not the consumer consuming the class. And this configuration should be in the composition root.

There are many valid reasons you would want such a class and the fact you can piggy back on an IoC gives great power and flexibility.

Singletons when used with IoC do not prevent you from testing unlike static types which are mostly bad for reasons already mentioned and should be avoided when possible.

Singletons <> Static types

The moment you define a static type, you immediately write off any use of IoC and testability. That really is the key message here.

The other thing to remember is that, if you implement a static type via an Extension Method or other means, remember that the developer needs to understand what is actually happening and that he wouldn’t be interested in mocking out those calls in a unit test. If the consuming developer would be interested in mocking out those calls, then reconsider the use of an extension method/static type.

So I think Singletons are ok so long as they are not static types and are made singletons are part of the container configuration they are part of.

Utilities

Utility and helper classes in terms of naming are often interchangeable. A Utility class is often equal to a helper god class.

I’m interested in your views on this post, so please comment.

Sometimes you have a requirement to generate your C# class contracts from an existing WSDL document so they can be used by consumers. It might be that the customer simply wants to keep the existing service contract and in this case only the implementation needs to be developed.

The way to do this in .NET is to use the SVCUTIL.exe command-line tool that you get when you install Visual Studio. Most people will know about this tool for generating C# client proxy classes to handle the service invocations and marshalling of simple and complex data contracts from the client side. It can also handle generation of the C# service contracts – although not pretty and will need to be cleaned up afterwards.

Just to note, when I say C# above, the tool also supports VB.NET, you just need to pass in the /l:VB switch. It defaults to C#.

So to generate your concreate service contract from an existing WSDL you can use the following syntax:

svcutil /dconly myservice.wsdl

If you’re lucky you’ll get a single myservice.cs source code file that contains everything i.e. all data contracts and the service contracts that you need in order to implement your service. You’ll need to clean this up though as the tool makes a mess of creating these contracts. You’ll also get a .XML file that can be added to your web.config or app.config file as it specifies the address, bindings and contracts for your service. It takes the address from the WSDL document and applies it to the config file.

If you’re not so lucky, you might get an error similar to the following:

D:\Workspaces\Simon\Project_Foo\Trunk\Foo\Source\Artefacts\WSDL>svcutil myservice.wsdl
Microsoft (R) Service Model Metadata Tool
[Microsoft (R) Windows (R) Communication Foundation, Version 4.0.30319.1]
Copyright (c) Microsoft Corporation. All rights reserved.

Error: Cannot import wsdl:portType
Detail: An exception was thrown while running a WSDL import extension: System.ServiceModel.Description.DataContractSerializerMessageContractImporter
Error: Schema with target namespace ‘http://schemas.foo/Services/Foo/2009&#8242; could not be found.
XPath to Error Source: //wsdl:definitions[@targetNamespace='urn:com:foo:services:foo:function:2011']/wsdl:portType[@name='PortType']

Error: Cannot import wsdl:binding
Detail: There was an error importing a wsdl:portType that the wsdl:binding is dependent on.
XPath to wsdl:portType: //wsdl:definitions[@targetNamespace='urn:com:foo:services:function:feature:2011']/wsdl:portType[@name='PortType']
XPath to Error Source: //wsdl:definitions[@targetNamespace='urn:com:foo:services:function:feature:2011']/wsdl:binding[@name='EndpointBinding']

Error: Cannot import wsdl:port
Detail: There was an error importing a wsdl:binding that the wsdl:port is dependent on.
XPath to wsdl:binding: //wsdl:definitions[@targetNamespace='urn:com:foo:services:function:feature:2011']/wsdl:binding[@name='EndpointBinding']
XPath to Error Source: //wsdl:definitions[@targetNamespace='urn:com:foo:services:fucntion:feature:2011']/wsdl:service@name=’Service’]/wsdl:port@name=’EndpointPort’]

Generating files…
Warning: No code was generated.
If you were trying to generate a client, this could be because the metadata docu
ments did not contain any valid contracts or services
or because all contracts/services were discovered to exist in /reference assembl
ies. Verify that you passed all the metadata documents to the tool.

Warning: If you would like to generate data contracts from schemas make sure to
use the /dataContractOnly option.

Looking through the error, the first thing that comes to mind is it looks like the separate namespace being imported could not be found as per the following error message:

Schema with target namespace ‘http://schemas.foo/Services/Foo/2009&#8242; could not be found

This might be the case if your WSDL document looks something like the following:

<wsdl:types>
<xs:schema>
<xs:import namespace=”http://schemas.foo.com/Services/Foo/2009&#8243; schemaLocation=”Context.xsd”/>
</xs:schema>
</wsdl:types>

You look at the above WSDL snippet and think, well Context.xsd is present in the same folder as the WSDL document to which I’m trying to generate a code contract, so why can’t SVCUTIL find it.

It can’t find it because it’s not looking for it. You have to supply SVCUTIL with all the dependent XSD files on the command-line with the name and location of the WSDL document file like the following, i.e.

SVCUTIL myservice.wsdl context.xsd

Once you execute that command, you’ll notice you’ll get a single C# file with the same name as the WSDL document (in this case myservice.cs) containing all the code required to implement the WSDL. This includes correctly decorated service contracts (interface) and the correctly decorated data contracts for use with WCF (Windows Communication Foundation). I admit it makes a mess of this but it’s a starting point and saves you a great deal of time especially if your data contracts are large and complex as often seen in SOA environments.

Comments on a topic I had previously posted about on my own blog http://john-rutter.blogspot.com/2007/12/websphere-message-queue-utilities.html but worthy of some repetition here.

 If you are using WebSphere Message Queue (WMQ), then a quick checklist of utilities you may find useful:

Other IBM blogs and web pages provide plenty of other useful information on WMQ and WebSphere ESB/Process Server, such as:

http://hursleyonwmq.wordpress.com

http://mqseries.net

http://www.ibm.com/developerworks/websphere/zones/businessintegration/wmq.html

http://soatipsntricks.wordpress.com/

 http://webspherecommunity.blogspot.com/

http://www.redbooks.ibm.com/rss/websphere.xml

Thanks to Andy Piper (http://andypiper.wordpress.com/) for pointing out some of these to me before.

Follow

Get every new post delivered to your Inbox.

Join 1,084 other followers