Have I Mentioned the Tea?

Fuzi Miao 001

While in China, I had a short list of things I wanted to do, some of which I was able to accomplish and some of which I was not. 

I wanted to see Sun Yat Sen’s tomb (check). 

I wanted to go to the Mid-Lake Pavilion Teahouse in Shanghai because it shows up in both Neal Stephenson’s Diamond Age — in which it is one of the two main hangouts for the mysterious Dr. X along with KFC — as well as Qiu Xiaolong’s Death of a Red Heroine (unchecked). 

I wanted to track down the location of the old Russian Saint Nicholas Cathedral, which I believe was the cathedral where St. John of Shanghai and San Francisco –- a Serbian monk who eventually became a bishop and a saint venerated in America by the Russian émigré community – served (unchecked).

I wanted to try certain Chinese delicacies including fermented (through burial) duck eggs and shark fin soup (check).  The latter particularly impressed my nine-year-old son, a fan of the Japanese show Iron Chef.  

Finally, I wanted to taste and ideally purchase some Dragon Well Tea.  I had first heard of Dragon Well a few years ago when I came across a long article about it in the New Yorker – or it might just as easily been The Economist, Harper’s, since I cannot find any reference to the article on the Internet.  As I remember the article – or perhaps as I remember remembering it – it involved the obscure history of the tea, the peculiar manner in which it is harvested – once a year in spring, under a new moon, handpicked by virgins – and the devotion it has acquired among tea connoisseurs, with some sacrificing a year’s salary in order to purchase a few grams of the highest grade of the long jing leaf.  And so I’ve carried this story around in my head for many years, wondering if I would ever have a chance to taste this particular brew.

Fuzi Miao 009

I should point out that I am not any sort of tea connoisseur, myself.  I suspect I may even be a philistine when it comes to teas, my palate already distorted and ruined by years of coffee drinking.  Nevertheless, I knew that I wanted to try this tea, purported to be the greatest tea of China.

When the moment finally came, it was not anything revelatory.  The tea is, quite frankly, nice.  It has a beautiful grassy aroma and a pleasant, gentle flavor with very little bitterness.  I’d drink it again.  I could certainly see why the tea is considered to be special, but the experience was not like my first encounter with a $300 bottle of red wine in the south of France or my first mug of cold Czech beer in Prague.  Of course, I was not tasting the highest grade of long jing, which needed to be acquired back in spring – and in truth have no guarantee that the tea is even from Zhejiang Province, much less the West Lake region – though the package is marked with the official state PGI label. 

Fuzi Miao 010

In any case, drinking it at home, long jing cha has grown on me.  The smell of it immediately soothes me and the experience of drinking it requires a suitable and respectful ambience – a quiet and clean space with, ideally, a view.  The tea has not given up its secrets to me yet, but I intend to be persistent.

Ah!  But I forgot to tell you about the buying of the tea!

My Chinese colleague and I were passing a Ten Fu Teashop – one of a chain of over a thousand in China – in the Fuzi Miao and heard several young ladies, none older than 17, singing out to us and beckoning us in.

Fuzi Miao 008  Fuzi Miao 002

Upon entering Ten Fu, one of the ladies took us to a special tasting table.  The table had a smaller special wooden table on top of it with slots to catch and drain away any spilled tea.  Here the hostess went to work intricately preparing the tea for us.  I had trouble following all of her hand motions as water was brewed, then poured into receptacles, then disposed of, then poured from one receptacle to another until the hot water finally touched tea leaves. 

Fuzi Miao 003  Fuzi Miao 004   

All the while the hostess described the particular qualities of the teas she was preparing while also suggesting how they should be drunk, at what time of day, and what sort of meals they would go with.

Fuzi Miao 015  Fuzi Miao 007

When the water was poured into the cup that contained the tea, the hostess began brushing it with the lip of the cup, guiding the tea leaves this way and that along the surface of the water as she told us the history of each tea we would be tasting.  This lasted for perhaps thirty seconds and then the tea was strained into yet another receptacle.

Fuzi Miao 012  Fuzi Miao 006

From here it was finally poured into our tiny tea cups.  She then picked up my tasting cup and dumped the contents out.  The first pour was to warm the cup, only.  A second pour and I was finally allowed to taste.  By this time, the whole experience of watching the tea preparation had already overshadowed the actual tea itself.  Did I mention that the hostess was flirting with us the whole time?  We sipped our tea and asked for more.  When the hostess asked us if we would like to try another tea, we could not bring ourselves to leave for dinner as we had originally planned.  And so the whole intricate process started all over again.  The graceful hands of the hostess flitted over the various appurtenances of the tea ceremony as she smiled, laughed, scolded, cajoled, and mocked us in a fluid delivery that had us hanging on her every word – none of which I actually understood.

Fuzi Miao 017

At last we had tried three different teas — which I could barely tell apart until the oolong with osmanthus came along — and when it was clear that we would be purchasing nothing beyond my bag of Dragon Well Tea, we sadly parted ways with our hostess.  When we asked her for her name, she laughed at us and said she couldn’t possibly tell us since we had only just met her, and that we would have to come back to her many more times before she would reveal it.

Have I Mentioned the Food?

Nanjing Skyline

Have I mention the food in China?  I have been spending most evenings wandering the streets of Nanjing looking for interesting street food vendors.  Most of the afternoons, however, the corporate hosts take me to try the different regional dishes and traditional favorites. 

Today, for instance, I finally had a chance to try fermented duck eggs at lunch.  These eggs (according to my host) were only buried for a few months before being dug up and served.

Fermented Duck Eggs

I had eel yesterday (by pointing to something swimming in a tank and insisting that I wanted it) but have no picture of it.  I do have pictures of the Beijing Duck we ate for dinner a few days ago.  The bones left over from the preparation are served either fried or in a soup.  Since we had two ducks, we had the remainders served both ways.

Beijing Duck    Beijing Duck

I was surprised to find out that Sweet and Sour Chicken is an authentic Chinese dish.

Sweet and Sour Chicken    Soup

As is Kung Pao Pork and Sesame Chicken.  We also had Mo Po Tofu several times for lunch and dinner.

Mo Po Tofu    Grilled pork backs

A fish dish or two was present at almost every meal.

Sezhuan Catfish    Nanjing and Shanghai 049

And, of course, we had veggies.

Beans    Cabbage and Mushrooms

As I mentioned, following my nose through the streets of Shanghai and Nanjing has also been extremely fun.  There are lots of variations on the dumpling to be found as well as various ways to cook a noodle and deep-fry dough.

Street dumplings    Street Crepe

 

The most interesting meal, however, was the one I had tonight with Lu Bing.  The rest of the team from America has returned to Shanghai, so Bing and I went to the Fuzi Miao – the Old Confucius Temple – to do some shopping.  Bing suggested, tentatively, that we go for a traditional Nanjing meal and I jumped at the chance.  We went back and forth trying to find the right term for a meal that involves offal, duck blood soup, funky tofu, an egg cooked in tea, pickled vegetables and periwinkles.  I think we call it “country” cooking in America, though that is not quite appropriate in this case since the dishes are notably old-school “city” cuisine.

Nanjing Traditional    Fuzi Miao 023

Exile and the Celestial Kingdom

Street Caligraphy (Shanghai)

For the past week I have been working in Shanghai and Nanjing for my company.  The flight from Atlanta to Shanghai involved two legs: first three hours to Detroit and then another fourteen to Shanghai.  Most of the flight from Detroit to Shanghai was over icy tundra, so the view over the right wing of the plane was mostly of frozen rivers and crevasses.  Shanghai is a sprawling and quickly growing city on the south eastern coast of China.  Unlike other cities in which high rises are concentrated in the center, Shanghai has buildings everywhere reaching upward into the sky, the only space it can grow into since the Yangtze River does not deposit dirt quickly enough onto the coast to provide land for the Chinese perpetually migrating to this industrious city in order to fulfill their dreams of prosperity.

Misunderstanding the nature of travelling for work, I made the mistake of bringing eight large books with me to fill up the many hours I thought I would have to myself.  Instead, of course, the time has been filled up with presentations, meetings, long commutes, and exhausted evenings – not unlike Atlanta.

And so I find myself going through my regular routines in a thoroughly exotic environment.  Perhaps this is why, unlike Albert Camus’ famous description of his two weeks in a foreign city, I feel comfortable in China rather than — well — existential.

Each night the employees of the Chinese company for whom I am consulting take me out to remarkable meals.  On the nights when I am left to my own devices I have the opportunity to walk the avenues of Shanghai and Nanjing sampling street food.  Nanjing is particularly well known for its beef dumplings – which I believe I tired last night at a literal hole in the wall advertised in English as “Wu’s Famous Meat Buns”.

Nanjing is sometimes called Duck City (at least according to a website I visited) because of the quantity of duck consumed here.  Lu Bing, one of the managers of the local Nanjing branch, took me and my colleagues to a restaurant that specializes in Beijing cuisine which included, of course, Beijing Duck.

Beijing Duck

Here is a picture of our host, Bing, ladling duck soup for us:

Bing Lu 

I could talk about what a wonderful tourist destination Shanghai and Nanjing are.  Hotels and restaurants are relatively inexpensive.  The people are friendly without being fawning.  Neither city is overrun with tourists, and so one has the illusion that one sees the city an-sich rather than fur-uns.

There is another side, too, however.  The economic reforms of the past twenty years or so have brought prosperity to China — especially in areas like Shanghai and Nanjing — but have also accelerated the deracination experienced in America since the 1950’s as people increasingly move about and change jobs.  Two income households, separation from one’s home town and ancestral graves, the constant task of reinventing oneself and forming meaningful but short-lived relationships – all the symptoms described in America as “bowling alone” – are quickly manifesting themselves in China.

Nanjing streets

I wish I could say where it all leads, but I’m not even sure where this all leads in the West.  Perhaps to existential angst, after all – and perhaps it is this aspect of the modern China that I find so familiar.

Cod Chowder

moby-dick

Early in Melville’s Moby Dick, Peter Coffin, proprietor of the Spouter Inn, recommends the Try Pots, an inn known for its chowders and run by Peter Coffin’s cousin Hosea Hussey, as a good place for a meal.

Fishiest of all fishy places was the Try Pots, which well deserved its name; for the pots there were always boiling chowders. Chowder for breakfast, and chowder for dinner, and chowder for supper, till you began to look for fish-bones coming through your clothes. The area before the house was paved with clam-shells. Mrs. Hussey wore a polished necklace of codfish vertebra; and Hosea Hussey had his account books bound in superior old shark-skin. There was a fishy flavor to the milk, too, which I could not at all account for, till one morning happening to take a stroll along the beach among some fishermen’s boats, I saw Hosea’s brindled cow feeding on fish remnants, and marching along the sand with each foot in a cod’s decapitated head, looking very slip-shod, I assure ye.

The description of the cod chowder at the Try Pots has always captivated me.  I’m a fan of canned clam chowder and have occasionally had the pleasure of a bowl of clam chowder at Legal Sea Foods next to the Georgia Aquarium – but cod chowder has never made its way to my table.

"Come on, Queequeg," said I, "all right. There’s Mrs. Hussey."

And so it turned out; Mr. Hosea Hussey being from home, but leaving Mrs. Hussey entirely competent to attend to all his affairs. Upon making known our desires for a supper and a bed, Mrs. Hussey, postponing further scolding for the present, ushered us into a little room, and seating us at a table spread with the relics of a recently concluded repast, turned round to us and said—"Clam or Cod?"

"What’s that about Cods, ma’am?" said I, with much politeness.

"Clam or Cod?" she repeated.

"A clam for supper? a cold clam; is THAT what you mean, Mrs. Hussey?" says I, "but that’s a rather cold and clammy reception in the winter time, ain’t it, Mrs. Hussey?"

But being in a great hurry to resume scolding the man in the purple Shirt, who was waiting for it in the entry, and seeming to hear nothing but the word "clam," Mrs. Hussey hurried towards an open door leading to the kitchen, and bawling out "clam for two," disappeared.

"Queequeg," said I, "do you think that we can make out a supper for us both on one clam?"

However, a warm savory steam from the kitchen served to belie the apparently cheerless prospect before us. But when that smoking chowder came in, the mystery was delightfully explained. Oh, sweet friends! hearken to me. It was made of small juicy clams, scarcely bigger than hazel nuts, mixed with pounded ship biscuit, and salted pork cut up into little flakes; the whole enriched with butter, and plentifully seasoned with pepper and salt. Our appetites being sharpened by the frosty voyage, and in particular, Queequeg seeing his favourite fishing food before him, and the chowder being surpassingly excellent, we despatched it with great expedition: when leaning back a moment and bethinking me of Mrs. Hussey’s clam and cod announcement, I thought I would try a little experiment. Stepping to the kitchen door, I uttered the word "cod" with great emphasis, and resumed my seat. In a few moments the savoury steam came forth again, but with a different flavor, and in good time a fine cod-chowder was placed before us.

We resumed business; and while plying our spoons in the bowl, thinks I to myself, I wonder now if this here has any effect on the head? What’s that stultifying saying about chowder-headed people? "But look, Queequeg, ain’t that a live eel in your bowl? Where’s your harpoon?"

We have a crock pot in our kitchen – a repackaged gift from Christmases past – and I decided to put it to good use this past weekend.  The recipe itself was quite simple:

    • 1 cup finely chopped onion
    • 1 stick butter
    • 4 cups diced potato
    • 1 can creamed corn
    • 1 1/2 lb Cod
    • 1 1/2 cup water
    • 1 pint half-and-half
    • salt, pepper and thyme to taste
    • 1 bay leaf

Cook the onion in the butter until it is transparent.  Throw chopped onion and liquid butter in the crock-pot along with potatoes, creamed corn, water, cod and spices.  Cook on low for 4 1/2 to 5 hours and then add the half-and-half.  Cook for another hour.

I served it with some hushpuppies and an upside-down cake for dessert.  I have heard that crumbled bacon on top is also tasty.  The cod was a bit pricey at around $9 a pound at Kroger, and I imagine that tilapia would make a good replacement – though it wouldn’t fill my literary hunger quite so well.

 

Covariance and Contravariance In 5 Minutes

C# 4.0 will introduce new language features to help manage covariance and contravariance.  While this is a a wonderful capability, it forces us to come to terms with these (to me) somewhat unfamiliar terms.

As I have been working through Eric Lippert’s excellent series of posts on this topic as well as the wikipedia entry, it has occurred to me that the best way to come to grips with these concepts is to examine gradually more complex examples of covariance and contravariance as it currently exists in C# 3.  If this appears to be a rehash of Eric Lippert’s work, this is probably because it is.  Consequently, any mistakes are purely mine, while any virtues in this explanation are clearly his.

First, however, it is necessary to learn some vocabulary.

Take the following class hierarchy:

        public class Animal{}
        public class Mammal : Animal { }
        public class Tiger : Mammal { }

We would typically say that Mammal is more derived than Animal.  Mammal, conversely, is less derived than Tiger in this inheritance chain.

To understand covariance and contravariance, we need to replace more derived and less derived with the metaphorical terms smaller and bigger.

We do this because more derived and less derived are not adequate to describe the relation between objects such as arrays of types.

        Animal[] A;
        Mammal[] M;
        Tiger[] T;

An array of Mammal does not derive from an array of Animal.  Both Mammal[] and Animal[] are derived from System.Array. There is no inheritance relation, however, between Mammal[] and Animal[] themselves.  Nevertheless there is obviously some sort of relation present.  By convention, we call this relation a smaller than \ greater than relation.  Mammal[] is smaller than Animal[] because Mammal is more derived than Animal.  It is bigger than Tiger[] because Mammal is less derived than the type Tiger.

It is worth repeating that smaller and bigger are not the same thing as the relation between classes in an inheritance hierarchy.  They also do not have anything directly to do with memory management.  They are pure metaphors.

The C# classes above model concepts.  When we talk about concepts such as animal, mammal and tiger, we talk about these concepts falling under each other.  Socrates falls under the concept of man.  Man falls under the concept of an animal (traditionally, man is defined as a bipedal, hairless animal that laughs; see Haecceity).

Metaphorically, we can think of animal as a bigger concept than mammal because many more things fall under animal than under mammal.  Tiger, in turn, is a smaller concept than mammal because so few things fall under it.

Once we have smaller than and bigger than under our belts, we can start talking about covariance and contravariance.  Covariance and contravariance, at the most basic level, concerns the assignment of types to variables.

An assignment is covariant if we can assign a smaller type to a bigger type:

covariance

If we can assign a bigger type to a smaller type, the assignment is said to be contravariant:

contravariance

1. Covariance with simple reference types

An example will help to illustrate this. 

    Mammal m = new Tiger();
    Animal a = m;
    //Tiger t = a;  -- will not compile

We can assign a smaller type, Tiger to a variable allocated as a Mammal.  Similarly we can assign our Mammal instance to a variable allocated as an Animal.  In other words, in the assignment of simple reference types, we can assign smaller things to bigger things.  This is a covariant relation.

We cannot, however, assign an Animal instance to a Tiger.  The C# compiler just won’t let us do it, because it will not let us assign something bigger to something smaller in this case.  The assignment of simple reference types is therefore not covariant.

2. Covariance with arrays

The C# compiler also happens to allow covariant array assignments.  For instance:

    Mammal[] M = new Tiger[0];
    Animal[] A = M;
    //Tiger[] t = A;  -- will not compile

The compiler doesn’t need to allow this.  It just happens to.  What’s interesting is that the compiler will not allow us to do the same thing with generic collections. 

3. Invariance with generics

Assignment of generics is invariant in C# 3.

    // List<Mammal> mammals = new List<Tiger>(); -- will not compile
    // List<Animal> animals = mammals; -- will not compile
    // List<Tiger> tigers = animals;  -- will not compile
    //

4. Covariance with method parameters

Parameter assignment also happens to be covariant in C#.  To prove it to yourself, take the following static method:

     public static void TakeMammal(Mammal m){}

Which of the following operations is permissible in C# and which is not?

    TakeMammal(new Tiger());

    TakeMammal(new Animal());

    TakeMammal(new Mammal());

(Note, however, that ref and out parameters are invariant: http://blogs.msdn.com/ericlippert/archive/2009/09/21/why-do-ref-and-out-parameters-not-allow-type-variation.aspx .)

5. Delegate contravariance with respect to inputs

Understanding this characteristic of parameter assignments is important in order to demonstrate how contravariance occurs in C#.  In C#, delegate assignments are contravariant with respect to inputs.  Consider this code:

 public static void TakeAnimal(Animal a) {}
 public static void TakeMammal(Mammal m){}
 public static void TakeTiger(Tiger t) {}

public delegate void MammalHandler(Mammal m);

MammalHandler funcA = TakeAnimal; //OK
MammalHandler funcM = TakeMammal; //OK
MammalHandler funcT = TakeTiger;  //No!

            funcA(new Mammal()); //OK
            funcM(new Mammal()); //OK
            funcT(new Mammal()); //No!

The delegate method MammalHandler is designed to only take the Mammal type as input.  Any delegate instance – funcA, funcM, funcT – in turn may be passed Mammal objects.  If we pass a Mammal to delegate instance funcA, it ultimately gets passed to our TakeAnimal method.  Since parameter assignments – as we showed above – are covariant, passing a Mammal to TakeAnimal is permissible.  Obviously passing a Mammal to TakeMammal is also permissible.

We cannot, however, pass a Mammal to TakeTiger.  The C# compiler does not allow this.

Consequently, we also cannot assign TakeTiger to our MammalHandler delegate.  Assigning TakeTiger to funcT is illegal.

But in this impermissible delegate assignment, which thing is bigger: MammalHandler or TakeTiger?  MammalHandler, right?  With regard to delegate assignments, then, we are saying that assigning something smaller to something bigger is not allowed.  Assigning something bigger to something smaller, however, is permissible.

Delegate assignments like those above are therefore contravariant.

6. Delegate covariance with respect to return types

I say “like those above” because this is actually true only with respect to delegate inputs.  Delegates can also, of course, return objects – and when they do, this is a covariant relation.  Delegate assignments are said to be contravariant with respect to inputs, but covariant with respect to return types.  You can prove this to yourself by looking through the following code in which the delegate signature has a return value but no parameters.

 

public static Animal GetAnimal() {} public static Mammal GetMammal(){} public static Tiger GetTiger() {} public delegate Mammal GetMammalDelegate(); GetMammalDelegate funcA = GetAnimal; // No! GetMammalDelegate funcM = GetMammal; // OK GetMammalDelegate funcT = GetTiger; // OK

 

 

 

So why is this important for understanding C# 4.0?  As we briefly covered above, C# 3 has this peculiar characteristic in that the compiler treats array assignments as covariant operations, but treats the generic assignment of List<T> as an invariant operation. This is obviously a little weird.  In C# 4.0, there will be support for covariance and contravariance in generic interfaces which will allow us to specify how we want our generics to behave – for instance, a special kind of covariant IEnumerable<out T> could be implemented that would provide the sort of covariance now supported for arrays.

A Lazier Singleton with .NET 4.0

This post examines how the new Lazy<T> type can improve standard implementations of the Singleton pattern in C#.

I will ignore for the moment the common jeremiads against the Singleton pattern and the reports made by some latter-day design pattern nihilists that the Singleton is dead.   I do not mean to imply that they are wrong – it’s just that it galls me that the Singleton pattern should be the object of such scorn and ridicule when the Flyweight is allowed to go along its merry way.

Besides which, the Singleton and the Facade are the only patterns I can write from memory and without a lot of research, so I love ‘em.

The best source for design patterns in C# is probably Judith Bishop’s C# 3.0 Design Patterns published by O’Reilly Press, which provides C# versions of all 23 patterns from the Gang of Four’s Elements of Reusable Object-Oriented Software.  The elegant implementation of the Singleton pattern she recommends looks like this:

 

public sealed class Singleton {
   // Private Constructor
   Singleton( ) { }

   // Private object instantiated with private constructor
   static readonly Singleton instance = new Singleton( );

   // Public static property to get the object
   public static Singleton Instance {
          get { return instance;}
       }
}

There is a problem with this, however.  Because of the way classes with static methods work in C# (or in this case, a static property), type instantiation of the private Singleton field instance happens at an unexpected point.  For an interesting if somewhat dense read on the effect of the beforeFieldInit flag, go here.

I will simply demonstrate the problem by adding some tracking code to Judith Bishop’s recommended implementation:

    public sealed class Singleton
    {
        private static readonly Singleton instance = new Singleton();
        private Singleton()
        {
            // no default constructor
            Console.WriteLine(" >> singleton initialized");
        }

        public static Singleton Instance
        {
            get
            {
                Console.WriteLine("before singleton retrieval");
                return instance;

            }
        }
    }

I will retrieve an instance of this Singleton class from a console application like so:

    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("Calling Singleton instance");
            var s = Singleton.Instance;
            Console.WriteLine("Finished calling Singleton instance");
            Console.ReadLine();
        }
    }

When will the private type be initialized? When will the private constructor be called?  In w

hat order do you think the Console.WriteLines will be invoked?

Ideally the static members of this class would be initialized only when we needed them, and the output would be:

  1. Calling Singleton instance
  2. before singleton retrieval
  3. >> singleton initialized
  4. Finished calling Singleton instance

In actuality, however, this is the result:

singlton_results_1

This is not so bad, you may be thinking.  If our singleton is a large object this creates some additional strain to the system – but as long as the Singleton instance gets used fairly soon after it is instantiated it’s no big deal.

However, what if I come in after you have coded the singleton and decide to add another static method to your class — not understanding the intricate details of beforeFieldInit – like this:

        public static void Test()
        {
            Console.WriteLine("testing singleton");
        }

 

and rewrote the calling code like this:

            Console.WriteLine("Calling Singleton test method");
            Singleton.Test();
            Console.WriteLine("Calling Singleton instance");
            var s = Singleton.Instance;
            Console.WriteLine("Finished calling Singleton instance");
            Console.ReadLine();

 

It may not be immediately obvious but I have seriously messed up your code.  Here is the output:

singlton_results_2

Even if we never retrieve the Singleton instance, it will still be initialized when any other static method on our type is called – this is commonly known as a language runtime bummer.

.NET 4.0 introduces a new generic type called Lazy<T> which helps us out of this dilemma.  Lazy<T> is a wrapper class that facilitates thread safe, lazy instantiation of objects.  We can use it to create a new Singleton implementation that replaces the private static Singleton instance with a private static Lazy<Singleton>  instance.  The Instance property will also require a small rewrite to pull our Singleton out of the Lazy wrapper.

The full implementation of the lazy version of the singleton looks like this:

    public sealed class LazySingleton
    {
        // Private object with lazy instantiation
        private static readonly Lazy<LazySingleton> instance = 
            new Lazy<LazySingleton>(
                delegate { 
                    return new LazySingleton(); 
                }
                //thread safety first
                ,LazyExecutionMode.EnsureSingleThreadSafeExecution);

        private LazySingleton()
        {
           // no public default constructor
        }

        // static instance property
        public static LazySingleton Instance
        {
            get{ return instance.Value; }
        }
    }

Some things of note:

1. I pass a delegate as the first parameter to the Lazy constructor. There is a no parameter constructor for the generic Lazy<T> class, but it requires that type T have a public default constructor – which I obviously do not want to provide.  The delegate parameter allows me to indicate that I want to use a different constructor – in order to pass a constructor parameter to Type T, for instance, or to invoke a private constructor, in this case – than the default. 

2. The second parameter, also optional, tells the Lazy instance that I want the lazy instantiation of type T to be thread safe.

3. I retrieve the wrapped type T by asking for the Lazy type’s Value property.

Now it’s time for a contest. I add some Console.WriteLine statements as in the original and I append the malicious static Test() method as in the original.  I rewrite my Console app code to call my original Singleton code and then the new and improved — .NET 4.0 enhanced — Lazy Singleton code:

    Console.WriteLine("Calling Singleton test method");
    Singleton.Test();
    Console.WriteLine("Calling Singleton instance");
    var s = Singleton.Instance;
    Console.WriteLine("Finished calling Singleton instance");
    Console.WriteLine();

    Console.WriteLine("Calling Lazy Singleton test method");
    LazySingleton.Test();
    Console.WriteLine("Calling Lazy Singleton instance");
    var lazyS = LazySingleton.Instance;
    Console.WriteLine("Finished calling Lazy Singleton instance");
    Console.ReadLine();

and get the following, very pleasing, results:

singlton_results_3

Now that’s lazy!

What can one do with Silverlight: Part deux

Corey Schuman, Roger Peters and Mason Brown – whom many of you met at the Atlanta Silverlight Firestarter – have been under wraps for several months working on a project for IQ Interactive they repeatedly insisted they couldn’t tell me about.

Now that the beta of My Health Info on MSN has been published, not only do I finally get to see what they have been working on but I also get to share it with you.

My Health Info is an aggregator of sorts for personal medical information – a tool to help the user keep track of her personal medical history.  Unlike other portals that support widgets, however, this one is built using Silverlight.

My Health Info is an interesting alternative to the Ajax-based web portal solutions we typically see and serves as a good starting point for anyone looking to combine the “portal” concept with Silverlight technology.  The Silverlight animations as one navigates through the application are especially nice; they strike the appropriate balance between the attractive and the distracting – between cool and cloying.

Do computers think?

sheep

The online Stanford Encyclopedia of Philosophy has just published David Cole’s update to the entry on The Chinese Room Argument.

The thought problem was posed by John Searle almost 30 years ago and has been a lightening rod for discussions about theories of consciousness and AI ever since.

For those unfamiliar with it, the argument is not against the notion that machines in general can think – Searle believes that minds are built on biological machines, after all – but rather against certain projects in AI that attempt to use computational theories to try to explain consciousness.  Searle’s argument is that computational models are a dead end and that thinking machines must be investigated in a different (apparently “biological”) way.

Of course, if biology can be reduced to the computational model (for instance) then Searle’s argument may be applicable to all machines and we will have to search for consciousness elsewhere.

Here’s the crux of the argument, from the SEP entry:

“The heart of the argument is an imagined human simulation of a computer, similar to Turing’s Paper Machine. The human in the Chinese Room follows English instructions for manipulating Chinese symbols, where a computer “follows” a program written in a computing language. The human produces the appearance of understanding Chinese by following the symbol manipulating instructions, but does not thereby come to understand Chinese. Since a computer just does what the human does—manipulate symbols on the basis of their syntax alone—no computer, merely by following a program, comes to genuinely understand Chinese.”

If this sort of problem excites you, as it does me, then you may want to examine some of the articles about and around consciousness collected on David Chalmers’ website: http://consc.net/online .

What can one do with Silverlight?

rubens

The ComponentArt Summer Silverlight Coding competition is about to wrap up in a few hours.  It has managed to garner approximately 80 entries – all with publicly accessible Silverlight sites.

In the process of hosting this contest, Miljan Braticevic has achieved a wonderful thing – almost as a side-effect.  He has gathered a fantastic gallery of Silverlight applications which answer the often unvoiced question: What can one actually do with Silverlight?

If you are simply looking for ideas or, more to the point, trying to find a way to explain to your boss what Silverlight is, go here: http://www.componentart.com/community/competition2009/contestants.aspx .

The contest entries run the full gamut of mapping tools, social networking, dashboards, standard web site alternatives and games.

I do not envy the judges the task of bequeathing their golden apples.

Craft and Exposure

derek_jacobi

With Silverlight 3, Silverlight seems to have reached a critical stage – that is, people are starting to criticize it.  This is a good thing since it means we can now talk about the reality of Silverlight rather than the promise of Silverlight as a technology.

Some recent comparisons have been made between Silverlight and Flash by Michael Lankton as well as Silverlight and HTML + JQuery by Dave Ward, a truly great developer.

One topic that hasn’t been broached, I believe, is the comparison of Silverlight and WPF.  For some die-hard WPF developers I know, Silverlight just seems like a crippled version of the technology they love.  This is somewhat unfair.  Silverlight has definite limitations when compared to WPF; it also, however, is able to reach a much broader audience because it is browser-based and platform neutral.  Until a mono version of WPF is implemented, Silverlight is going to be the main way for .NET developers to get their state-of-the-art applications onto their Mac using friends’ computers.

This reminds me of a comment I heard Derek Jacobi, the great Shakespearean actor, once make to the effect of:

“I do movies for the money.  I do television for the exposure.  But I do theater for love of the craft.”

As much as I have always enjoyed windows development and have cursed the many tricks and hacks one must know to do web development, web development was still always fun because people had a greater appreciation for what one did.  In part this is because web applications simply reach a wider audience.  It is also due, I think, to the fact that users are much more savvy about the web and the way they feel it should look than consumers of desktop applications.

And so those lessons might be applied to how we look at the relationship between Silverlight and WPF.  WPF allows one to practice one’s craft – which is an enjoyable but mostly solitary affair.  Silverlight, on the other hand, provides the developer with exposure for his work – and this is no bad thing.