Jeff Perrin :: Archives for the 'Programming' Category
Wednesday, June 28th, 2006
I’ve been sick the last two days (I got a cold during the hottest part of the year so far, go figure) so I had some time to play around with C# 2.0’s generics implementation. What originally got me started was having an old project lying around that had out of date subversion information. Rather than going through each and every sub-directory and deleting .svn directories, I figured I’d write a little one-off app to do it for me.
I started out by attempting to implement the specification pattern, which led to various attempts at generic implementations that were never quite right. Fortunately, while searching for information on generics I stumbled across Joe Walnes post on The power of closures in C# 2.0 which details the use of predicate generic delegates.
For those not familiar with the specification pattern, it basically just allows you to filter a list of objects while keeping your condition separate from your loop. As an example, we often see something like this:
1 public IList FindAllMaleCustomers()
2 {
3 IList matches = new ArrayList();
4 foreach(Customer customer in Customers)
5 {
6 if(customer.IsMale)
7 {
8 matches.Add(customer);
9 }
10 }
11 return matches;
12 }
The specification pattern removes that customer.IsMale check out into a specification object, so we can now write something like this instead:
42 public IList FindAllMaleCustomers()
43 {
44 return new CustomerFinder(Customers).FindAll(new MaleCustomerSpecification());
45 }
Therefore, if the definition of a “Male” ever changes (bad example, I know) we can just change our MaleCustomerSpecification object.
Fortunately for me, .NET 2.0 includes a new type of delegate called the predicate generic delegate, which
Represents the method that defines a set of criteria and determines whether the specified object meets those criteria.
Seems like it’s exactly what we need. So rather than writing a specific specification object, we can just write a generic predicate like so:
1 public class Spec
2 {
3 public static Predicate<DirectoryInfo> SubversionDirectory
4 {
5 get
6 {
7 return delegate(DirectoryInfo dirInfo)
8 {
9 return dirInfo.Name == “.svn”;
10 };
11 }
12 }
13 }
Which we then use like this:
1 new DirectoryFinder(directories).FindAll(Spec.SubversionDirectory);
Our DirectoryFinder object is a little more complex than a standard FindAll on a method like System.Collections.Generic.List would be, because we recurse all the way through the sub-directories of a given directory:
1 public class DirectoryFinder
2 {
3 private IList<DirectoryInfo> _directories;
4
5 public DirectoryFinder(IList<DirectoryInfo> directories)
6 {
7 _directories = directories;
8 }
9
10 public DirectoryFinder(DirectoryInfo directory)
11 {
12 _directories = directory.GetDirectories();
13 }
14
15 public IList<DirectoryInfo> FindAll(Predicate<DirectoryInfo> predicate)
16 {
17 return FindAll(predicate, _directories);
18 }
19
20 private IList<DirectoryInfo> FindAll(Predicate<DirectoryInfo> predicate, IList<DirectoryInfo> directories)
21 {
22 List<DirectoryInfo> matches = new List<DirectoryInfo>();
23 foreach (DirectoryInfo info in directories)
24 {
25 if (predicate(info))
26 {
27 matches.Add(info);
28 }
29 else
30 {
31 matches.AddRange(FindAll(predicate, info.GetDirectories()));
32 }
33 }
34 return matches;
35 }
36 }
I’m almost certain there’s other ways of doing this, some are probably better as well. For another use of predicates, check out Jean-Paul Boodhoo’s post on validation in the domain layer, where he uses them to flesh out business rules.
Posted in Programming | 4 Comments »
Thursday, June 22nd, 2006
I just read The Nature of Lisp on defmacro.org, which attempts to explain why Lisp is so rad. I have to say, it’s by far the best article I’ve read in a while. I actually feel smarter, which is not a common feeling for me after reading anything related to Lisp.
As it turned out, the above article was a good lead-in to Sahil Malik’s series describing some of the good new features C# 3.0 will have. C# will definitely be getting some sweet features previously only really seen in dynamic languages (to my knowledge) in the future. Can’t wait.
Posted in Programming | 2 Comments »
Saturday, May 27th, 2006
I swore to myself a while ago that I wouldn’t write anything about Ajax, but I’m about to break this promise, mostly due to writing like this, and other various bits from around the web that quite simply just don’t appear to make any sense. So here are my thoughts, which are based on theories untested and mysteries unsolved.
First off, what is Ajax? Well, despite the capitalization, it’s an acronym coined in an Adaptive Path article written over a year ago, after Google released GMail and everyone started diving into their javascript source code to figure out how they did all that fancy page refresh stuff. It stands for “Asynchronous JavaScript + XML”, which is somewhat misleading for reasons explained later.
At the core of Ajax is one simple little javascript object called XMLHttpRequest. Peruse the article from Apple in the link I just provided. It describes the history of the object, it’s methods (or messages, Vlad), properties, and has some small examples on its usage. Passing the article through Jeff’s Super Information Condenser produces the following output:
- XMLHttpRequest has been around for many years, first in Microsoft’s IE as an Active-X object.
- The object is now supported in some form by all major browsers in use today, with some quirks.
- There are two methods of interest. open(), which prepares a connection to a URL, and send(), which makes a request asynchronously (most of the time) to the URL.
- There are a few properties of interest as well, namely onreadystatechange (an event handler you pass a function to), readyState (the current state of the object), and responseText (which is the actual response returned by the request to an URL)
Passing the condensed information through Jeff’s Even Superer Information Condenser, we end up with this:
At the core of Ajax is javascript’s XMLHttpRequest object, which lets you make and manage asynchronous requests to a server.
Notice how my Information Condenser says XMLHttpRequest is “At the core of Ajax.” So what else is Ajax comprised of, you may be asking yourself? Well, to answer that question, you’ll have to go back and re-read the Adaptive Path article I linked to above. If you want my version (which I’ll assume you do, because I’m like that), here goes: No one fucking knows.
My take on Ajax is basically that Ajax means using XMLHttpRequest to get information from a remote URL without doing a full page refresh. Exhilarating, eh? Which kind of makes me wonder why we have full on “Ajax frameworks” like Atlas, replete with special updatePanels and Control Toolkits. I personally fail to see why it needs to get so damn complicated. Maybe it’s time to play around with it a little bit to see what the big deal is.
Posted in Programming | No Comments »
Saturday, May 13th, 2006
Scott Bellware is having some “fun” over on his blog trying to explain why he is a fan of, and practices, Agile development. He’s frustrated because, in his experience, many people have misconceptions about what TDD, XP, Scrum, etc actually are, and then go on to attack these processes based on these same misconceptions.
Keeping to that theme, I’ll present a few of my observations. First, some background about me.
I started my life as a developer very recently… I graduated with a Computer Technology diploma in late 2002. One of my instructors happened to be Grigori Melnik, a Russian robot without an “off” switch. He had us pair-programming on assignments, and writing simple tests before we wrote our implementation. He also spoke a lot about XP practices, so you could say that I was indoctrinated right from the beginning.
So you’d expect that when I entered the “real world” of development, I’d dive right in to using these same Agile processes, right? Well, no. I can honestly say that I was mostly convinced of all the benefits, but actually practicing them was hard for the following reasons:
- Tool support sucked. Unit testing wasn’t integrated into Visual Studio, and there was no refactoring support at all.
- I had difficulty working with others in a pair. Communicating is hard, and takes practice, especially when you’re in a new field.
- Writing tests from scratch is very hard, unless you’ve got some mentoring.
- Coding by yourself can be almost therapeutic. Pop in some headphones, crank up the Styx, and get in the groove, baby.
For these reasons, I never really rocked out to the Agile beat. I knew about it, I had been around it my entire programming life, but it never really took hold. This is where we come back to the part where I get on topic. In Scott’s post I referenced above, he states how he’s basically come to the conclusion that Agile cannot be taught or evangelized through the written word. So he started teaching courses and speaking at user groups. Walking people through it. Letting them try stuff out under an experienced watchful eye.
I think this is the only way someone can really get what an Agile practitioner is talking about. If someone like me, who came into the development world after XP and Scrum had been developed, who had instructors teaching me this stuff from the get-go can’t latch onto the concepts without help, then what are the chances experienced developers are going to latch on? They’ve been pumping out code for years, probably doing quite well for themselves, so why change? How many other “red pills” have come along in their time, only to be shat out the other end without the promised effect?
All I can say to Scott is to keep doing what he’s doing. It probably does make a difference to many people, and may even help them code better. But even with all the benefits, there will be those who just will not be Agile. We’ve offered at least a few people jobs on my current project, only to have them take one look at “The Pit” and say “This just isn’t for me, sorry.” I remember showing our workspace to some former co-workers. They stared around at our expansive setup for a while, until one of them said, “I have way more space in my cubicle.” Whoa. Touche.
Posted in Programming | No Comments »
Monday, May 1st, 2006
Paul Gielens over on the ASP.NET weblogs has recent post talking about naming patterns for unit tests. He mentions the following naming pattern:
- Context
- Stimulus
- Result
That sounds awfully familiar to what we’ve been taught to use on my current project:
- Setup
- Execute
- Verify
Each test has one method (or system) under test, which is the “execute” step noted above. We test this method once, after we’ve written our setup, and then we verify the results are as expected. Our test names always contain the execute step, and then we’ll usually have a quick little description after that to describe how a test is different from another (the setup):
public void testSearchUsersByName_NameIsNull()
I much prefer our naming to “Context, Stimulus, Result”. That sounds more like the scientific process the skinny grey aliens use when they probe us. I don’t really know that, but I’m just saying…
Posted in Programming | No Comments »
Saturday, February 25th, 2006
I’ve been in a refactoring kind of mood lately, so I guess I’ll continue with the theme in this post…
One of the major frustrations I have when it comes to working on my current project is that a lot of code has been written by a lot of different people. A constant battle we fight is to push logic down from the presentation layer back into the domain where it belongs, and can be tested. Often, I find myself weighing the benefits of refactoring a chunk of code versus just getting the required bit of functionality completed and moving a sticky to the “done” pile. Far more often than I’d like, I just sigh to myself internally and finish the feature or bugfix without taking further action (unlike Vlad, who immortalizes his resignation within the codebase).
Well, on Thursday I’d finally had enough. Right before 5:00, Vlad passed me the umpteenth bug filed on remote inventory functionality. I took a look at the bug, went to the offending JSP’s form helper class, and proceeded to sigh yet again.
For those individuals who aren’t lucky enough to be working on our project, our form helper classes are generally known as the dumping grounds for bad, untestable code. They are also unfortunately directly accessed by the JSP’s, and are untested within our system. They’ll generally be called by Struts actions like so:
public void save(){
FormHelper helper = operationsForm.getFormHelper();
helper.save();
helper.initialize();
forward("success");
}
That method looks nice. So what’s the problem? What does the helper.save() method look like?
public void save(){
Mpoint deliveryMpoint = delivery.getMpoint();
if(deliveryMpoint.hasRemoteInventory() == false){
mastersFacade.createRemoteMpoints(deliveryMpoint);
}
delivery = mastersFacade.updateMeasurement(delivery);
closingInventory.setVolume(
delivery.getVolume().subtract(
sale.getVolume().add(openingInventory.getVolume())));
closingInventory = mastersFacade.updateMeasurement(closingInventory);
sale = mastersFacade.updateMeasurement(sale);
}
Wow, no wonder we keep getting bugs on this stuff. Either this entire block of code is in every test of this feature, or (Chris was right on this one) it’s not actually tested! Our untested save method:
- Finds a measurement point
- Checks to see if it has remote measurement points. If it doesn’t, create some
- Saves the value of the delivery measurement (which can’t actually be edited on this screen anyways)
- Calculates and saves the value of the closing inventory measurement
- And finally saves the value of the sale measurement (which is the only editable field on the form)
Not so sexy. The “initialize” method looks much the same, making at least 4 separate facade calls. At this point, I actually proceeded to do something about it. Three hours and about 5 tests later, I’d managed to completely refactor the entire thing, turning the offending code from above into this:
public void save(){
mastersFacade.updateRemoteInventory(remoteInventoryMaintenanceDto);
}
All the logic has been pushed down to the domain (RemotableMeasurementPoint) where it belongs, and I actually feel like I’ve accomplished something. For the record, this was the first time I’ve really felt like I hit the “coding groove” for quite a while. It felt good.
Posted in Programming | No Comments »
Thursday, February 16th, 2006
I was re-reading some of Ted’s stuff today, and came across his post on refactoring nested if statements. It struck a cord, because I’d just teased apart a nested for loop - if statement combination recently, mainly for the reasons Ted states:
When I see multiple nested ifs in a method, it seems to indicate a problem with responsibility. Usually, you are asking one object one thing, another object another thing, then even another object a third thing and then finally you operated on that third thing.
I’ve gained the ability to see these types of situations since I started on this project, and the one thing that really stands out when we look at nested ifs and breakdowns in object responsibility is that they make things really hard to work with. When we tease out an if into a separate method, we gain additional descriptors about what the code is trying to accomplish. For example (pseudo code in a class named MeasurementPoint):
public void createDummyOverriddenAllocationResults(
OwnershipType ownershipType){
List dummyResults = new ArrayList();
List overriddenAllocResults = getAllOverriddenBacars;
List facilities = getAllProductionSourceFacilities();
foreach(Facility fac in facilities){
if(facility.canBeOverridden(ownershipType())){
List allProducers = facility.getAllProducers();
foreach(BusinessAssociate ba in allProducers){
if(ba.hasVolumeBeenOverridden(
overriddenAllocResults, ownershipType)){
dummyResults.add(createDummyAllocationResult(ba, ownershipType, etc));
}
}
}
}
return dummyResults;
}
That’s the basic gist of what I was dealing with, although the actual code was a little more “wordy”. So we can see from the name of the method that we’re attempting to create “dummy” overridden allocation results. That’s nice, but how does the method actually decide how to create these dummy records. The answer is not immediately obvious without spending a good chunk of time inspecting the code. Whenever I see something like this I’m tempted to at least break the method down into smaller methods that help document what I’m trying to do. So the above method becomes more like this:
public List createDummyOverriddenAllocationResults(
OwnershipType ownershipType){
List overriddenAllocResults = getAllOverriddenBacars;
List facilities = getAllProductionSourceFacilities();
return createZeroVolumeOverriddenResultsForProducersWithNoVolumes(
overriddenResults, facilities);
}
So all we’ve done here is move the first foreach loop into its own method, that gives us a little more insight into how we’re accomplishing our task. But now we’ve just moved the problem into another location. So let’s break it down further:
public List createZeroVolumeOverriddenResultsEtc(
List results, List facilities){
List dummyResults = new ArrayList();
foreach(Facility fac in facilities){
List producers = fac.getProducersWithoutOverrides();
dummyResults.addAll(createOverrides(producers, etc));
}
return dummyResults;
}
We keep this up until we have all the interesting pieces wrapped up in small, do-only-one-thing methods that document what they’re doing with their names and parameters. One bad smell is really long method names… if you can’t describe what your method is doing without hitting the line-break in your code editor you can probably decompose even further.
A nice side-effect of the above refactoring was that I was able to override one of the methods in a sub-class to make a story work. In essence, after the refactoring, the sum-total of the story turned out to be a one liner (at least in the domain, the gui was another beast…).
Posted in Programming | No Comments »
Monday, February 13th, 2006
I first read Sam Smoot’s stuff in the architecture forum at asp.net, where he was one of the few individuals with substantial (heh) posts. Somewhere along the line Sam found the way and has transferred his commentary from the asp.net forums to his blog at Substantiality.net (get it?). It’s a site worth checking out, in my humble opinion.
Posted in Programming | No Comments »
Sunday, November 13th, 2005
I’ve been somewhat facinated by Ruby on Rails for a while now. Initially, I’d watched the demo videos about the basics of the framework and was impressed by how nicely everything fit together (like most people, I’d imagine). The elegance of simplicity can sometimes be mind-bending, in a why didn’t I think of that sort of way. There’s nothing new there, it’s just that the way in which it’s been implemented is so damn… well… fan-fucking-tastic.
Perhaps the thing that I respect the most about Rails and it’s developers, however, is the extent to which simple common sense was applied in it’s creation. Over the many years of “enterprise” software development, certain things have become so entrenched within the mindset of developers that we’ve missed the original point of it all. For example, how many of us cringe when we see something like this?
<% foreach( Item item in LineItems ){ %>
<p> <%= item.Name %> </p>
<% } %>
Most of us do, I’d bet. Sometime in the not-to-distant past, somebody realized that embedding a whole bunch of busness logic in with your views made things hard to manage. So they decreed “Thou shall not mix business logic with view logic” and the world was good again.
But look again at the code I’ve written above. Is there any business logic in there? No, there isn’t any at all, actually. Yet we all still experience an allergic reaction at the sight of it. Why? Instead, we write things like in another language entirely, a templating language to be exact. So now, instead of the above code, we have a layer of indirection like so:
<asp:Repeater id="repeater" runat="server">
<itemtemplate>
<p><%# DataBinder.Eval(Container.DataItem, "Name") %>
</itemtemplate>
</asp:Repeater>
Perhaps this is easier to read, perhaps not. There’s certainly more to write. The fact remains that we haven’t really changed anything. We still have two examples of view code that don’t implement any business logic. Big deal, I guess.
My point, and I do have one, is that the most refreshing thing I see when I read my new book on Rails is the complete disregard the framework authors had for certain established norms. Rather that going ahead and implementing their own templating engine for views, they simply use Ruby. Pure craziness, I know. But it works, as long as you remember not to mix your view logic with your business logic. You don’t need an entire new language to accomplish this. The dude who handles the GUI where I work (which is Struts based) will attest to the fact that a templating language does not necessarily prevent business logic from bubbling upwards through the layers anyways.
The Rails book I linked to above is chock-full of stuff like this. I highly recommend it, even if you don’t ever write a line of Ruby in your life. Basic common sense is refreshing every now and then.
Posted in Programming | No Comments »
Tuesday, September 27th, 2005
One of the things that drives me nuts about the Web right now is the complete lack of understanding among designers, programmers and users in general as to what the Web could be.
Hint: You cannot control how your site appears, or is used by others. Don’t even try. Be flexible, and learn how you can make your sites work for everybody. Not everybody…
- Can see colours the way you do (think colour blindness)
- Has the same screen size you do (think PDAs and widescreen monitors)
- Can read 10px fonts (think about poor eyesight)
- Has a broadband connection (think rural)
- Has the same taste in design (think about getting consensus about a design from your clients)
The standard tips apply here. Using standards based design is a good start, as well as following some basic design guidelines. Sexiness alone might win you the contract, but you won’t be doing your customer any favours, whether they know it or not. Give this question a thought: What are the 5 sites that you visit most often? Now, why do you visit these sites? I’m willing to bet that you visit all 5 of them for the content, rather than the way they look.
So what’s the lesson? The lesson is that Content is King, and in almost any situation I can think of, a website should be constructed in such a way that its content can be delivered to as many visitors as possible. If you can do this well, and still make your site look sexy, you’ve already got the competition whipped. (This advice presumes your site actually has content people will be interested in).
There are fortunes being made on the web right now by people who understand this.
Posted in Programming, Tech | No Comments »
Friday, August 12th, 2005
Chaz gives one of the lucid explanations on why estimating software delivery times is so hard. It’s one of the most concise explanations on the subject I’ve ever read.
“Hire somebody who you can trust to give you a good estimate. Then, if they learn something new and change the estimate, trust them again.”
Posted in Programming | No Comments »