Yearly Archives: 2006

Why I Prefer C# to Java (The Language)

The first language I really learned to program in was Java. The first language I actually delivered a product with was C#. It wasn’t hard to move from one to the other, as in most aspects the language was exactly the same. There are some significant differences, though. The most striking difference in my mind is how the C# language has received so many nice little features that just make the code cleaner. You could write Java code in C# if you wanted to, but that would just be plain silly. Here’s a sample of what I’m talking about:

Java and C# both utilize a finally concept that lets the programmer clean up resources. However, C# takes this a step further with the using statement. Here’s the Java way…


Timer timer;
try{
timer = new Timer();
timer.start();
doStuffWeWantToTime();
} finally {
timer.stop();
}

…And now the C# way…


using(new Timer.start()){
doStuffWeWantToTime();
}

The using statement will implicitly call the Timer’s Dispose method once the block goes out of scope. The compiler actually generates the same code as the try/finally block, so it’s all just syntactic sugar. But sugar is so sweet.

Next up, we have the new generic Collections namespace in C#. On my current project (Java), we implemented a class called the Finder, which takes a collection and a specification. It uses the specification object(s) to filter the collection like so:


public List getProductsForSale(){
return new Finder(getProducts(),
new ProductsOnSaleSpecification()).find();
}
public class ProductsOnSaleSpecification(){
public bool isSatisfiedBy(Object obj){
Product p = (Product)obj;
return p.isOnSale();
}
}

The Finder abstracts out the looping, while the ProductsOnSaleSpecification tells the Finder which products we’re interested in. It’s pretty sweet, that is until I realized that this is actually built in to C#’s generic collection classes (the following is pseudo-code… Use of generics is implied, but I’m too lazy to html-encode the angle brackets):


public List getProductsForSale(){
return Products.FindAll(IsProductOnSale);
}
private boolean IsProductOnSale(Product p){
return p.IsOnSale;
}

It’s worth noting that the C# collection classes have more than just the FindAll concept… You can also call Exists, Find(one), ConvertAll, FindIndex, FindLast, ForEach, Remove, RemoveAll and TrueForAll in much the same way. You can also pass in an anonymous block of code, which is based on .NET’s support of delegates. I’ve written about this in more detail before.

A basic language feature that exists in C# is the notion of a Property, which allows you to present the internal state of an object in a cleaner form than the Java standard of using getters and setters. Again, this is just syntactic sugar, but it’s nice to be able to visually tell whether you’re operating directly on an object’s state. Here’s the Java code and it’s C# equivalent.


public class Dude(){
private int age;
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
}


public class Dude(){
private int age;
public int Age{
get{ return age; }
set{ age = value; }
}
}

My next C# feature isn’t really a feature, and it’s perhaps the most contentious of my points. The feature is the lack of checked exceptions in C#. My current project has very few points in the code where we actually handle exceptions (the Facades, and various points in the UI, but almost nowhere in the Domain). Yet we’re consistently forced by the Java compiler to stick throws ValidationException on almost all of our methods. It quickly just becomes unwanted noise in the code base.

That’s about it for my little comparison. I still have a few more points I could make, specifically around delegates and events in C#, and how stupid it is that the Java foreach statement equivalent only operates on generic lists without needing a cast, but I’ll save those for another post.

In Search of Stupidity

A couple choice quotes from Eric Sink’s foreward to In Search of Stupidity 2 by Rick Chapman:

The movie industry wants us to buy all our DVDs again so we can see them in “high definition”, but they can’t decide which new format they want. Either way, this comes in the nick of time, because as we all know, the central problem with DVD technology is the atrocious picture quality.

…and…

The time between the initial release of Windows XP and Windows Vista is roughly the life span of a dog, and apparently the main new feature is that it will be harder to use digital music and video content. Oh yeah, and it looks prettier.

Have Your Cake

This one’s for Ted, Joe, Vlad, Alan and anyone else who thinks functional programming is the shit.

This is neat stuff, because it means we’ll get most of the cool stuff from functional languages in a statically-typed, IDE friendly language. One of the most common complaints about Ruby that I’ve heard, both on our project and online, is that there is no good IDE support (meaning refactoring, and navigation through the code in this context). If this sort of stuff is coming to C#, you can also be damn sure that similar features will make it into Java.

When the Code Speaks

I did a little bit of refactoring the other day that I’m pretty happy with, so I thought I’d share.

We started out with a method in the SystemProfile who’s signature is specified below:


List createPriorityAllocationGroups(
ProfileGroup profileGroup,
List allAllocationChildren,
FacilityMonthlyMeasurements sourceForMeasurementPoints,
FacilityMonthlyMeasurements sourceForOwnerTypeClassification)

It is called within a loop for every ProfileGroup contained in the SystemProfile like so:


private List getProfileAllocationGroupsForProfileGroups(
List profileGroups,
List allAllocationChildren,
FacilityMonthlyMeasurements sourceForMeasurementPoints,
FacilityMonthlyMeasurements sourceForOwnerTypeClassification){
List profileAllocationGroups = new ArrayList();
for (Iterator iter = profileGroups.iterator(); iter.hasNext();) {
ProfileGroup profileGroup = (ProfileGroup) iter.next();
profileAllocationGroups.addAll(
createPriorityAllocationGroups(
profileGroup,
allAllocationChildren,
sourceForMeasurementPoints,
sourceForOwnerTypeClassification,
isCustomProfile));
}
sortProfileAllocationGroups(profileAllocationGroups);
return profileAllocationGroups;
}

Having to pass in four parameters to a method is a little smelly, but not too bad. The bad part happened within the method, which had grown quite complicated over a long period of time. The purpose of the method is to simply assemble a list of new PriorityAllocationGroup objects, so it should have looked something like this:


PriorityAllocationGroup allocationGroup = createNewPriorityAllocationGroup(group);
allocationGroup.addAllocationChildren(getPriorityAllocationChildrenForGroup(group));
allocationGroup.addMeasurementPoints(getMeasurementPointsForGroup(group));
return priorityAllocationGroup;

Instead, we had an implementation that was about 75 lines long, and so convoluted it took
me and my pair almost half a day to figure out how to implement a feature for our story.
Which sucks.

The very first refactoring I identified was to move the method into ProfileGroup. Many of the questions being asked within the method were specific to this object, so keeping it in SystemProfile no longer made sense. This involved moving a lot of other helper methods into ProfileGroup as well. Nothing actually got any simpler, but at least we were now just asking ProfileGroup to assemble it’s ProfileAllocationGroups instead of stuffing it all in SystemProfile.

So originally we had this:


class SystemProfile{
List getProfileAllocationGroupsForProfileGroups(
List profileGroups,
List allAllocationChildren,
FacilityMonthlyMeasurements sourceForMeasurementPoints,
FacilityMonthlyMeasurements sourceForOwnerTypeClassification);
List createPriorityAllocationGroups(
ProfileGroup profileGroup,
List allAllocationChildren,
FacilityMonthlyMeasurements sourceForMeasurementPoints,
FacilityMonthlyMeasurements sourceForOwnerTypeClassification);
}

Which became this:


class SystemProfile{
List getProfileAllocationGroupsForProfileGroups(
List profileGroups,
List allAllocationChildren,
FacilityMonthlyMeasurements sourceForMeasurementPoints,
FacilityMonthlyMeasurements sourceForOwnerTypeClassification);
}


class ProfileGroup{
List createPriorityAllocationGroups(
SystemProfile systemProfile,
List allAllocationChildren,
FacilityMonthlyMeasurements sourceForMeasurementPoints,
FacilityMonthlyMeasurements sourceForOwnerTypeClassification);
}

The next refactoring involved removing another smell (at least to me); passing in Lists as
parameters. Obviously there are sometimes reasons for this, but it’s usually better to be able to call a method like getAllAllocationChildren() at will instead of passing the list all over the place. As it turned out, the allAllocationChildren parameter originated from a method within SystemProfile. Since we were passing the SystemProfile in as a parameter, we could eliminate this parameter to make the method signature look like this:


class ProfileGroup{
List createPriorityAllocationGroups(
SystemProfile systemProfile,
FacilityMonthlyMeasurements sourceForMeasurementPoints,
FacilityMonthlyMeasurements sourceForOwnerTypeClassification);
}

One of the patterns I saw after this cleanup was that the 4 parameters originally passed in were in turn being passed in to other methods. Over and over again. Eventually the lightbulb goes on in my head as I realize that what we’re actually signifying by passing these parameters all over the place is that we’re operating inside a specific
context. So the next refactoring was to combine the sourceForMeasurementPoints, sourceForOwnerTypeClassification, and the SystemProfile into a
ProfileAllocationGroupContext object. Once this was done, it was a simple matter to change the signature of all the helper methods to take the context object as well.


class ProfileGroup{
List createPriorityAllocationGroups(
ProfileAllocationGroupContext context);
}

It’s now the job of the SystemProfile to create the ProfileAllocationGroupContext, which is then passed on to every ProfileGroup when we ask for its ProfileAllocationGroups. Whew!

This seemed ok, but there was still some stuff that didn’t quit fit. There were lots of calls like this in ProfileGroup.createPriorityAllocationGroups:


context.getMeasurementPointsToBeAllocated(this);

This was a fantastic example of how when you’re refactoring code it sometimes "speaks" to you. I had originally thought that putting this code in ProfileGroup was the right thing to do, but as I worked through all the above refactorings it became obvious that it wasn’t. Here’s the method that kicked everything off in SystemProfile as it stood at this point in the refactoring:


List getProfileAllocationGroupsForProfileGroups(
List profileGroups,
ProfileGroupAllocationContext context){
List profileAllocationGroups = new ArrayList();
for (Iterator iter = profileGroups.iterator(); iter.hasNext();) {
ProfileGroup profileGroup = (ProfileGroup) iter.next();
profileAllocationGroups.addAll(profileGroup.createPriorityAllocationGroups(context));
}
sortProfileAllocationGroups(profileAllocationGroups);
return profileAllocationGroups;
}

The code was telling me that instead of


profileGroup.createPriorityAllocationGroups(context)

we should actually be doing


context.createPriorityAllocationGroups(profileGroup)

This makes sense, if we say that for the given context, we want to assemble a list of
PriorityAllocationGroups. By moving the method to the context object we’re actually making it do double duty as an assembler or builder, but that can easily be factored out later. So in the end, my object model looked like this:


class SystemProfile{
List getProfileAllocationGroupsForProfileGroups(
ProfileAllocationGroupContext context);
//plus a bunch of state and other methods
}


class ProfileGroup{
//original state based stuff
}


class ProfileAllocationGroupContext{
List createPriorityAllocationGroups(ProfileGroup profileGroup);
}

Responsibilities of Objects

Here’s a quick refactoring tip.

Try to turn something like this…


public class Facility{
private boolean isGasBaseProduct(MeasurementPoint measurementPoint) {
return measurementPoint.getProduct().isGas()
|| measurementPoint.getProduct().isGasLiquid()
|| measurementPoint.getProduct().isGasByProduct();
}
}

…into this:


public class MeasurementPoint{
private boolean isGasBaseProduct() {
return getProduct().isGas()
|| getProduct().isGasLiquid()
|| getProduct().isGasByProduct();
}
}

This Just In…

Buckles is neglecting his blog again. And he’s still using recycled designs created by other people.

The funny thing is, he’s now single, so he should have all the time in the world to work on nerdly things like website designs. But for some reason, he’s reneged on his duties as a geek and reverted back to trying to be cool (which he will never be able to do as well as me anyways).

Oh, and one other thing… Vlad, Ted… You’re next.

Fun With Generics and Anonymous Methods

Here’s a little snippet of pure C# 2.0 sex that shows how to use anonymous methods and generics to create a facade into your domain layer. But first, a little background…

Layers are as follows, top down:

  • UI layer. Utilizes DTO’s assembled from the domain that directly map to a screen. All the screen does is display the values from the dto, nothing else. Testing the DTO’s gets you really close to the skin of the UI.
  • Facade. Organizes calls to the domain along functional lines. Wraps calls to the domain in a transaction, catches errors and warnings and sticks them somewhere accessible to the UI. Assembles domain objects into DTO’s for the UI. Updates the domain with info from the UI.
  • Domain. Business objects that perform the reall meat and hold all the logic pertaining to the customer’s problem.

In my case, the domain is mapped to a database using NHibernate. I’m using a Repository object to abstract that stuff away. Originally, my facade directly used the Repository in the following pattern:

public void AddBasePackageOptionsToCart(int unitId, int basePackageId, DateTime currentDate)

        {

            using (IRepository repository = DataManager.StartTransaction())

            {

                Unit unit = _FindValidUnitById(unitId);

                BasePackage basePackage = unit.Floorplan.GetBasePackage(basePackageId, currentDate);

                unit.Cart.SelectBasePackageAndAddOptions(basePackage);

                repository.VoteToCommit();

            }

        }

This is nice and clear, althought what do we do if an exception is thrown? Wrap each and every call in a try/catch? This is ugly, and creates repetition. We also have to remember to commit the transaction every time we are using a read/write transaction. I’ve spent much time debugging only to find I forgot to call VoteToCommit(). We can do better.

Enter the FacadeTransaction object. Using generics and anonymous methods, we can make sure our call to VoteToCommit is always called. We can also centralize our exception handling in one single place. Witness:

internal class FacadeTransaction<T>

    {

        public delegate T TransactionMethod();

 

        public TransactionMethod method;

 

        public FacadeTransaction(TransactionMethod o)

        {

            method = o;

        }

 

        public T Execute()

        {

            using (IRepository repo = DataManager.StartTransaction())

            {

                T returnValue = method();

                repo.VoteToCommit();

                return returnValue;

            }

        }

 

        public T ExecuteReadOnly()

        {

            using (DataManager.StartReadOnlyTransaction())

            {

                return method();

            }

        }

    }

And here’s how we utilize the FacadeTransaction:

public BasePackageListPageDto FindBasePackageListPageDto(int floorplanId, DateTime date)

        {

            return new FacadeTransaction<BasePackageListPageDto>(delegate

                {

                    Floorplan floorplan = Floorplan.FindById(floorplanId);

                    return new BasePackageListPageAssembler(floorplan, date).AssembleDto();

                }

                ).ExecuteReadOnly();

        }

 

        public BasePackageDto SaveBasePackage(BasePackageDto packageDto)

        {

            return new FacadeTransaction<BasePackageDto>(delegate

                {

                    BasePackageAssembler assembler = new BasePackageAssembler();

                    BasePackage package = assembler.Initialize(packageDto);

                    DataManager.GetCurrentRepository().Save(package);

                    return assembler.AssembleDto(package);

                }

                ).Execute();

        }

We use generics so that we can dynamically change our return type without casting. We use an anonymous method so that we can wrap each interaction with the domain in a single transaction without repeating code. We could also centralize our error handling if we wanted to. Sweet.