Don’t Make the Recipe Static

DSCF0719_20_21.jpg

Today it was time to talk about static class members in the first year programming course. I always have problems with static. If you are not careful you start thinking that static means “doesn’t change much”. This is reasonable in real life, but not in C# programming. In C# programming static means “always present, part of a class and not of an instance”. At this point I thought an example would serve well, so we started talking about contexts where static would make sense.

Consider that you are implementing a system for a fast food store. You have a class called “Dish” and the system stores an instance of Dish for each of the items in the menu. A Dish instance holds the list of ingredients for the dish, the sale price, and the name of the dish. For example, there might be a dish called “Chicken and Chips” which held two ingredients (chicken and chips) and a price value (perhaps four pounds 50 pence). I asked everyone for some suggestions for static class members for the Dish class. Someone suggested that recipe would be a good candidate for a static member.

Not so. The idea of a static member is one that exists as part of the class. Which means that recipe could only be static if every dish was cooked in the same way (i.e. the recipe exists once for the entire class). Each dish needs its own recipe, so this must be a non-static member of the Dish class. However some things, for example the maximum and minimum price of dishes, the maximum number of ingredients that a dish can have all make sense as static members of the Dish class.

Simon has a sign on his office wall, “Consider the context”. When trying to work out what makes sense as static and what doesn’t, this is very good advice. And a good starting point is that “a recipe should not be static”.