Entries Tagged 'Opinion' ↓

Alternative to abusing using

There’s been a bit of discussion of late about using statements, and how they’re more often being used for purposes other than just releasing resources. As always, there are those people who think it’s a flagrant abuse of a feature and shouldn’t be done, then there are those that like it. I’m in between. I do like what the using statement gives us, but I also think it is a bit of an abuse.

The “traditional” usage of the using statement can be found quite often in the land of files and streams. Take the following example, which opens a file and then closes it when it drops out of the using scope.

using (var stream = File.OpenRead("myFile.txt"))
{
  // do something with the file
}

Examples of the alternative usage can be found all over the place, but Rhino Mocks is one that’s close to my heart. Here’s from the record/replay syntax, anything in the scope of the using is recorded, and once it drops out of scope it’s no longer in record mode.

using (mocks.Record())
{
  Expect.Call(customer.Address)
    .Return("123 Rester St");
}

Again, I do like what the using statement gives us outside of releasing resources (I’m not disputing it’s usefulness there). However, I think the using keyword itself adds noise and clouds intention.

With the adoption of 3.5, I’ve started using an alternative syntax instead of usings. Actions and anonymous methods to the rescue.

Scope(() =>
{
  // do something within this scope
});

It’s a little bit more noisy in the compiler satisfying department, but because you have full control over naming, you can reveal intention more. No more unclear “using”.

So how does it work? Simple really, the method takes an Action delegate, which it the executes almost immediately. I say almost, because you can execute code before and after the execution. That gives you the benefits of the using statements wrapping ability.

public void Scope(Action action)
{
  // do something before
  action();
  // do something after
}

Some more examples:

File.OpenRead("myFile.txt", file =>
{
  // do something with the file
});
mocks.Record(() =>
{
  Expect.Call(customer.Address)
    .Return("123 Rester St");
});

I prefer this syntax over the using statement. Of course, it’s only valid for 3.5 projects.

Missed out on something big

Ever get the feeling that you’ve missed out on something big? I never got to see Star Wars at the cinema*. I missed out on the start of computers, the ASM, the BASIC hacking and what-not. I discovered most of my musical taste way after the bands were gone or going, so I never got to see them in show.

None of those are my fault, of course, because they were all before my time; in fact, most were at least a decade before me. That still doesn’t stop me from ocasionally getting the feeling that I missed out on something big.

One more. One that’s pertient to our industry: Smalltalk.

Smalltalk is one of those languages, possibly the most prominent example, that has been idolised over time. It’s often touted as having an excellent programmer experience, properly object-oriented, the source of refactoring, great tools, and a solid virtual machine behind it. It’s one of those languages that people are proud to say they once worked with it. A language that people nosalgicly look back on. It’s also got an air of betamax about it (yeah, I missed that one too), people were sure it was better, but it still didn’t become mainstream.

We Smalltalkers used to think the advantages of our language were so significant that it would take over the world. We had a huge productivity advantage over C coders. Then C++ came along and gave C coders just enough to let them improve their productivity and their ability to write larger more complex systems. It still wasn’t as good as Smalltalk, but it was better than C, and much more accessible to most programmers than Smalltalk.

-Josh Susser via Raganwald

So where am I going with this? Just like I can make myself feel a bit better by watching Star Wars on a large TV, or listening to the Rolling Stones live albums. I’d like to see what all the fuss was about with Smalltalk, by giving it a go.

I’m not sure where to start on this, or how long it’s going to take, or even when I’m going to do it; however, one day in the not too distant future I’m going to do some programming with Smalltalk.

* Although I actually did get to see A New Hope when they did the re-release special edition, which made up for it.

Plugin baby steps

Making a Visual Studio 2008 plugin isn’t as hard as it sounds.

Making one that works is a bit more difficult.

Syntax highlighting is fairly straight forward, just run a tokenizer over the text and colour code each token appropriately. It’s the code sense that is causing me to go slightly mad. To determine what methods need to be listed when the intellisesne pops up, you need to parse the code that’s in the document, then resolve any classes and references in there to build up a collection of methods to display. It gets more tricky when the document isn’t valid, because you can’t compile it. That’s where I am now, I need to figure out some way of partially compiling the document, or maybe using an AST walker.

If it hasn’t already been done, you don’t need it

If you have a really good idea, and nobody has done it before, chances are there’s a reason for that. It could be that it was technically impossible last time looked at it, but more than likely it’s because you’re trying to solve something that is only present because you’re doing something wrong.

Consider alternatives always before embarking on writing something yourself. In an ever maturing software ecosystem, and the constant catch-up .Net plays with Java, if a solution to your problem was really needed, somebody should have attempted it before.

That’s not to say don’t innovate, but don’t recreate either, and certainly don’t provide solutions to non-existent problems.

All about dependencies

This article serves as an introduction to the concept of Dependency Injection, and why you’d want to use it. It is not a getting started guide for using containers. If you’re interested in those, my personal preference is Castle Windsor and you can find their getting started guide here.

What are dependencies? Also referred to as couplings, dependencies are other modules that one module requires to fulfill it’s purpose.

Are dependencies bad? No, of course they’re not, otherwise we wouldn’t be able to create anything. However, highly coupled code can cause a lot of problems for your application.

If your code requires knowledge of how a dependency works, then your code is highly coupled. If your code is tied explicitly to an implementation, then your code is also highly coupled.

Take the following example:

public class ProductUpdater
{
	public void StoreChanges(Product product)
	{
	  SqlDataStore dataStore = new SqlDataStore();

	  dataStore.CreateConnection();
	  dataStore.OpenConnection();

	  dataStore.Update(product);

	  dataStore.CloseConnection();
	}
}

The above example is highly coupled to the SqlDataStore. Firstly, it directly creates an instance, which means there’s no way for us to replace that instance if we need to (I’ll come to why you’d want to do that in a bit). Secondly, it relies on a great deal of knowledge of SqlDataStore’s implementation. In this code we can see that you need to create a connection and open it before you can update the record; that’s quite a bit of implementation knowledge. If the SqlDataStore was to change so that the OpenConnection method created a connection if one didn’t already exist, then we’d need to change every caller of that code to remove the CreateConnection call; in large system situations like that can quickly lead to a fear of change and refactoring.

I mentioned directly creating an instance stops us from replacing it if need be. Well when would you actually want to do this? For those unfamiliar with unit testing, you probably haven’t encountered test doubles; there are different types of test doubles, but for the purposes of this example they’re interchangeable.

A test double serves as a swap-in replacement for one of your dependencies. These allow you to execute a piece of code under test, without having to worry about whether things are being put in your database, or e-mails sent for example. If your code is creating instances within methods, those instances cannot be replaced by a test double. Without that ability, testing becomes considerably more difficult.

Tightly tying your code to an instance of a class reduces the flexibility and reuse of your code. Take the above example, that same code could be used to update the product in a cache instead of the database; similarly, you could use an in-memory storage instead of a database for when you’re running in a test or demo environment. If only your method wasn’t so tightly tied to the implementation.

This is solved by using Dependency Injection, which is a part of the and Inversion of Control.

[DIP] seeks to “invert” the conventional notion that high level modules in software should depend upon the lower level modules. The principle states that high level or low level modules should not depend upon each other, instead they should depend upon abstractions. — Wikipedia

Essentially, dependency injection allows you to stop instantiating your dependencies. Instead they’re “injected” into your object when it is instantiated itself. This allows the dependencies to be swapped out like we mentioned above.

So taking the original example, here’s a version of it that’s been updated to use dependency injection.

public class ProductUpdater
{
	private SqlDataStore dataStore;

	public ProductUpdater(SqlDataStore dataStore)
	{
		this.dataStore = dataStore;
	}

	public void StoreChanges(Product product)
	{
	  dataStore.CreateConnection();
	  dataStore.OpenConnection();

	  dataStore.Update(product);

	  dataStore.CloseConnection();
	}
}

The above implementation now allows us to create a test double, and replace the SqlDataStore in our tests. As I mentioned before, we could now easily push in an in-memory implementation without any changes to the code required.

We can take this further though, because we’re still tied to a concrete class. Lets make SqlDataStore implement an interface, so we can create other implementations.

public interface IDataStore
{
	void CreateConnection();
	void OpenConnection();
	void Update(Product product);
	void CloseConnection();
}

public class ProductUpdater
{
	private IDataStore dataStore;

	public ProductUpdater(IDataStore dataStore)
	{
		this.dataStore = dataStore;
	}

	public void StoreChanges(Product product)
	{
	  dataStore.CreateConnection();
	  dataStore.OpenConnection();

	  dataStore.Update(product);

	  dataStore.CloseConnection();
	}
}

Now our example is no longer specifically tied to a SqlDataStore, so we could quite easily pass it a FileSystemDataStore, or an InMemoryDataStore, or anything else that implements IDataStore. All that without having to touch a single line within the ProductUpdater.

That’s the power of dependency injection, and why you should stop hard-coding your dependencies.

Static method abuse

I dislike static methods, there I said it.

Like everything, they have their place; but as the old analogy says, when you have a hammer everything looks like a nail. Static methods are being abused.

Don’t make me instantiate

For some reason programmers seem to be allergic to instantiating objects, to the point of where half the functionality is implemented in static classes and methods. You can go for days without seeing an instance in my current project’s code-base.

It’s certainly interesting to see. As developers who program in object-oriented languages, when it comes down to it, are being paid to instantiate objects.

I think it’s symptomatic of a bigger problem. If you think creating instances is wasteful, maybe you’re creating too many. You’re most likely violating the Single Responsibility Principal (SRP) or Separation of Concerns (SoC). Too many dependencies usually means your class is trying to do too much, get it spit-up, and get it clean.

State vs. stateless

One justification for using static methods that is often touted around is that if a method doesn’t have any state, then it should be static. To me this is a fallacy, because state isn’t everything. Take the following repository example:

Using static methods
Customer customer = Repository<Customer>.FindByID(102);

customer.Name = "James";

Repository<Customer>.Save(customer);
Using an instance
IRepository<Customer> repos = new Repository<Customer>();

Customer customer = repos.FindByID(102);

customer.Name = "James";

repos.Save(customer);

Noticably the first example is one line less than the second. However, it’s compromising readability in removing that line. Instead of using the repos instance, you’re forced to fully-qualify every method call with Repository<Customer>, which is introducing more noise per-line.

Even though the methods FindByID and Save don’t have any shared state, they both form a part of the encapsulation of data-access (in this case).

If a method forms a key part of an encapsulation, then it shouldn’t be static.

When you make the decision of creating a static method due to it being stateless, you’re revealing more implementation details than necessary. A big part of encapsulation is hiding implementation details from the consumer.

While the methods are stateless, they might not always be that way; perhaps the repository could share a session between calls in the future. With an instance based design, you won’t have any problems. Try introducing state into a static method, and things either get very messy, or you end up converting everything to instances and having to rewrite any usages.

Static methods tie you in at an early stage to a specific design, making it very difficult to refactor out later.

Not all bad

So where are the good static methods? The Math class is a good example. It contains a set of functions that are only loosely related (apart from being mathematical), that are guaranteed to be stateless, and most importantly are simple. Architecturally the methods in the Math class could be applied to a wide swath of objects (int, float, double, decimal etc…) and to have them as instance methods would complicate the class hierarchy more than it would benefit it.

Static methods should be fire-and-forget, disposable, simple, and effective.

Object-orientation

Static methods aren’t associated with an object, they’re tied to a type. This is a big distinction. People are under the belief that because statics sit in the same class definition as instance methods, that it makes them object-oriented.

Two key points of object-oriented design that static methods violate are inheritance and polymorphism. The inability to substitute a method with an implementation in a derived class is pretty unforgivable, and heavily restricting.

Finally, testing

The argument that you’re most likely to encounter against using static methods is that of testing. It’s certainly one that I agree with, I just didn’t want it to seem like that’s the main reason of my argument.

Statics are bad for testing because they can’t be substituted easily. A major part of unit testing is being able to isolate what you’re testing from it’s dependencies; isolation allows you to verify one part of the system at a time. Static methods aren’t overridable in a sub-class, and so they aren’t mockable either (without the use of TypeMock).

Of the two examples used above, in the first example it would be very hard to test that code without actually going to the database, because of the ties to the static methods. The second example could be refactored so the IRepository dependency is injected, and thus replaceable at test time.

Not being able to test in isolation is the final nail in the coffin for static methods and me.

Plug-in’s and browsers

Jeff Atwood (of Coding Horror) tweeted earlier: “On Firefox: ‘add-ons aren’t a big draw for me — I just need a browser, not a circus.’”. I don’t know whether this was a quotation of himself, or someone else; but it’s something that I’ve heard mentioned before.

Just because they’re there, doesn’t mean you have to install them.

A plug-in model in your browser allows you to install as many, or as few, plug-ins as you need. A lot of them are useless, but if there’s one that can boost your productivity, isn’t that worth it? I’d rather have a browser with a plug-in model, and one really useful plug-in, than a browser without both.

A prime example is FireBug, I couldn’t live without that plug-in. I feel stranded in IE or Safari when it comes to interrogating pages.

FireBug possibly highlights a hole in the developer support from the Firefox development team itself, but with a plug-in model you can fill that hole yourself rather than relying on their team; like we’ve had to do for years with Microsoft and Internet Explorer.

/rant off

Percieved value and developer education

A comment on a post at Jeremy D. Miller’s blog caught my eye. To paraphrase, Jeff Tucker says that part of the problem of the lack of perceived value of ORM/TDD/IOC etc is down to the developers in question not having experienced the reason these tools exist.

He makes a fair point really, we use tools because they solve a problem for us, if we haven’t actually experienced what they’re solving then their value is appears to be much less than what it is. Similarly, the value of such tools and methodologies is nil when there is a lack of recognition of a problem even existing.

However, I don’t think the solution is to have developers learn “the hard way”. To discover the problem before using the solution is a problem in its-self. If we were to all learn from our own mistakes, and not from each-others, then we’re not going to make much progress as we’re all going to be solving the same problems.

Most people will have struggled with whatever problem has necessitated the creation of these tools/methodologies, so I think it’s more a case of helping the developers connect the dots; “You remember such and such a problem? Well that’s easily solved using methodology/technology x!”, rather than making them retrace the steps of every developer before them.