Tag Archives: oop

More Effective .NET via Effective Java: Static Factories

December 14, 2010 | Jason Kozemczak

Yesterday, I talked briefly about one of my favorite takeaways from Joshua Bloch’s Effective Java: the typesafe enum pattern.  Today I’d like to discuss another one of 57 points Bloch discusses in his book and how it can be understood and implemented from a .NET standpoint; the first point he makes in the book is to consider implementing static factory methods in your classes.

When developers start coding a class, we often start with what seems quite innocent:

Now, this is inherently bad, but we lose a certain amount of control over the use of our class when we allow public constructors.  For one, we no longer have control over how many instances of a class we will allow.  This might be important in a situation where we’re managing a pool of database connections, for instance.

Furthermore, if we have enough constructors, we might run into a signature collision, where the only alternative is to rearrange the parameter types of one or more constructors.  This will almost always be a compromise, and probably one that comes with the cost of confusing the consumer of the class.  In short, we’re limited by the fact that classes can only have 1 constructor for any given signature:

But alas, we won’t let the compiler get the best of us!  We can turn our constructors into public static factory methods:

A few things to note about the above example.  One, it doesn’t really make any sense; I haven’t done a good job at making a sensical class, and I apologize for that.  I’ve basically hodge-podged a few static factory methods into a class to point out the advantages vs. traditional object constructors.

Static Factories Over Constructors?

By using static factory methods, we can better manage instances of our class (if we’re concerned about such things), this is highlighted in the top static method.  The beauty of this implementation is that you can adjust the number of allowed instances without the user having to worry about it.  You could even transform the class into a singleton by making adjustments inside the factory method!

The last two static methods are used to highlight the more descriptive nature of static factory methods vs. constructors; it also serves the purpose of showing how signature collissions become essentially a non-issue with static factory methods.  Note that both static factory method’s names help to inform the user certain characteristics of the objects they return.  Additionally, they share the same signature, which would not be possible if constructors had been used in their place.

Another advantage that Bloch points out that I haven’t demonstrated is that using static factory methods allows you the ability to return instances of subclasses in your static factory methods.  I once wrote a small set of classes that calculated the driving distance between two locations using Google Maps and Bing Maps.  I essentially subclassed the interaction between either group and created a static factory method that returned an instance of one or the other.  Generally, it returned only instances of the Bing Maps-based calculator, but could have been easily “switched” out with the Google Maps-based calculator should Bing’s mapping services ever went down.

The Grass is Always Greener

To close, don’t let this post misguide you into thinking that factory methods are always superior to constructors.  One of the major limitations is that without public constructors, you are essentially making your class sealed.  This might potentially be bad if you explicitly want your class to be able to be subclassed.  However, note that this implementation doesn’t stop users from utilizing your class through composition (in contrast to inheritance), which can sometimes be a “cleaner” way of leveraging a class’s behavior.

In addition to the “sealed” byproduct, you also fight the fact that static factory methods don’t “look” any different than other static methods in a class (i.e. they aren’t differentiated from other methods like constructors are).  This could frustrate users of your classes if you aren’t descriptive in your class’s public contract.  Again, use judgement and pragmatism when deciding on implemeting constructors of static factory methods (or maybe use both!).

Effective .NET via Effective Java: Typesafe Enums

December 13, 2010 | Jason Kozemczak

A few weeks ago I bore through Joshua Bloch’s Effective Java.  I’d heard a number of good things about the text, and even though I code professionally in .NET these days, good OO practice is good OO practice regardless of the language.

Bloch’s book is laid out in the same fashion as the classic Effective C++ (Scott Meyers); Bloch lays out 57 suggestions to writing “better” Java code.  One of the ones that gave me an “A ha” moment was Item #21, which presents the “typesafe enum” pattern.  Bloch’s examples are of course in Java, but the pattern can be utilized in .NET (and probably a number of other languages, though I’ll focus on .NET in this post).

Bloch proposes that more often than not, Enums can (and should) be replaced by class behavior.  I’ll present an example to illustrate the advantages to this methodology.

Let’s assume we’re implementing a card game in .NET.  We’d quickly find the need to enumerate the various suits of cards.  It’d probably look something like this

This would probably work well enough, but this doesn’t really get us very far.  Enums can’t implement methods, inherit interfaces, etc.  They’re a little bit more than named integer constants  We can pretty easily get this sort of functionality plus a quite a bit more with just a bit more work.  Now, consider the following class:

What we do by making the constructor private is limit the instantiated instances to only the 4 public facing static instances, which each represent the four suits.  We can now access those instances in a similar fashion to how we access Enum values: Suit.CLUBS, Suit.DIAMONDS, etc.

Now, the above example is somewhat trivial, but where the power lies is that we are now working with dyed-in-the wool classes, so we can add all the instance methods and properties we can dream up.  One of the great bonuses is that since we know there will only be four instances of this class, object equality “just works” since we know that all references to instances of the Suit class will relate back to one of the public-facing four.

We can go even further: since our Suits are now just instances of a class, we can make the Suit class implement any interface we choose, and we can gain the benefits to that implementation (IComparable comes to mind).

One of the other issues Bloch delves in on is the issues around Serialization.  If you are de-serializing instances of the Suit class, this will introduce additional instances of the Suit class; though I’m not going to dive into the details, it’s possible to also overcome issues revolving around that.

I can imagine a number of applications where a typesafe enum class makes more sense than the traditional Enum.  That said, each situation is different, and certainly there are situations where this pattern doesn’t offer any sizable advantages.  Can you think of a time when you used an Enum where the typesafe enum pattern made more sense?  Maybe I haven’t done enough to convince you of the power behind this pattern?  Let me know in the comments!  I might follow up with a more “real world” example where this pattern can be leveraged!

There are numerous conditions such as cancer which have no cure. It isn’t hard for immigrants to buy medicines online. How it is possible? You can purchase medicament to treat chronic treatment of the symptoms of osteoarthritis or muscle rigidity. There are different other medicaments. What about levitra cost and how much does levitra cost? What do you already know about http://cialis-vs-viagra.biz/why-order-viagra-online-the-perks-of-internet-shopping-for-meds.html? (Read more cost of levitra). Currently ten percent of men aged 40 to 70 were have trouble keeping an erection during sex. It affects men in all parts of the world. Generally, having trouble getting an erection can be knotty. All kinds of drugs, from those that are elaborate “all natural” to those that are chemically produced in a laboratory, carry some kind of aftereffects. Along with them useful effects, most drugs, notwithstanding, can cause dangerous side effects although usually not everyone experiences them. Online physician services are the only safe variation if you are going to purchase drugs, like Levitra, online.