The Principle of the Procrustean Bed in Programming

The software world of today has evolved to the point where the number and variations of programming languages are so large that it's impossible for someone to know even their names, let alone their features. I've recently found a site, www.99-bottles-of-beer.net, that provides solution to a program that prints a song about bottles of beer in 721 programming languages and variations. And that's a quite big number. What happens with the large majority of programmers is that they know, more or less, several programming languages and try to adapt all the rest to fit their programming customs and routines, even by breaking the conventions of a language or creating the false impression of something that isn't there. It's a Procrustean bed of programming.

So who was this man, Procrustes? He was a bandit named Damastes who lived near Eleusis in Attica, the territory of Athens in ancient Greece, and was later called Procrustes, which in old Greek means "the stretcher." He kept a house by the side of a road and offered hospitality to people traveling the roads, inviting them to dinner and to rest over the night in a special bed of iron, which, he said, had the special property of fitting the exact length of whoever lay down upon it. But there was a catch, because as soon as the person lay down on the bed, Procrustes began to stretch the person if he/she was too short to fit the bed, until he/she died, or cut off his/her legs if he/she was too tall.

Something similar happens today with many programmers. Object-oriented techniques are the ones most used today, so I will focus on object-oriented languages and examples. Many programmers know several largely used object-oriented languages, such as C++, Java, or C#. Many things can be done by using each of these languages in different ways; sometimes these tasks are easier with one language abd harder with another. Some things can only be achieved by using a particular programming language. The problem appears when people, instead of trying to adapt to one language, are working on altering that language to meet their preferences. Languages, like people, are different. Forcing a little bit the comparison, I would say that each programming language has its own personality and that should be respected. The power of software developing lies in the variety of programming languages.

One example I would like to tackle is provided in an article called Using Interfaces in C++ by Jose Lamas Rios. In this article, Mr. Rios proposes a way of using interfaces in C++. With all due respect, I strongly disagree with the approach. There is a catch in this title, because though interfaces are supported by Java, C#, and VB.NET (just to name a few languages), they are not supported by C++. In C++, there is no such thing as interfaces. However, there is an equivalent: abstract classes. Interfaces and abstract classes are used to achieve the same goals as different language-specific approaches. What the author proposes is creating several macros later to be used to apparently implement interfaces. Besides the fact of disguising the C++ keywords class and public as interface and implements, which has the purpose of turning the C++ syntax to the Java-side, the use of those macros is by no means error-proof and does not create a Java-like interface. All they do is create a C++ abstract class. The only good point is enforcing the declaration of a virtual destructor for the class, but that's the only point in it, and it's not a strong one. The method is tautological, it doesn't bring anything new to C++. Moreover, the programmer still has to follow standard C++ rules.

#define Interface class

#define DeclareInterface(name) Interface name { \
          public: \
          virtual ~name() {}

#define DeclareBasedInterface(name, base) class name : public base { \
          public: \
          virtual ~name() {}

#define EndInterface };

#define implements public

DeclareInterface(IFoo)
   virtual int FooSomething() const = 0;
   virtual void FooAction() = 0;
EndInterface

class Foo: Implements IFoo
{
   virtual int FooSomething() const {...}
   virtual void FooAction() {...}
};

In using such a construction, the programmer must:

  • Make sure all methods are declared virtual; moreover, they all should be declared as pure virtual methods (=0);
  • Make sure no data is declared for the interface because they are supposed to be just a contract that expresses behavior, but does not provide functionality of any kind;
  • Not derive interfaces from anything else but another interfaces.

So, C++ programmers still have to play by the standard C++ rules. Why do this if it doesn't bring something new? Using macros in this way reduces readability. Software needs to be maintained, new features added, old bugs fixed, Often, the members of the team that developed the software make the changes, sometimes a totally different team is given the task of maintaining some piece of software. When someone sees such a construction, like the one listed above (DeclareInterface \ EndInterface, implements IFoo), he/she may have some problems understanding what it's all about. Using non-standard methods in any commercial software has an important impact on the maintainability, and should be carefully avoided. Then, on the other hand, one rebel member of a team may dislike something, and decide to #undef and re-#define them in several files, creating even more confusion to the maintenance team.

So why go to so much trouble to create the false impression of interfaces in C++? I frankly see no good point in it. Because macros are expanded at pre-compile, we would just end up with a class. So, using the standard way of declaring would be much better.

Another example that I will consider comes from the C++ (or Java) programmers who start writing .NET applications, whether it is C# or VB.NET, and I have to admit that I was doing it too in the beginning. C++ programmers who follow the heuristic that says all class member data should be private and have Get/Set accessors use the same style in .NET. The problem is that .NET promotes the use of properties that allow clients to access class state as if they were accessing member fields directly, while actually implementing that access through a class method. Properties appear to be member variables even though they are implemented as methods. In C#, get and set properties are compiled into get_XXX and set_XXX methods, which is their representation in MSIL. However, simple properties are inlined by the JIT compiler, which means there is no difference in performance between accessing a property and a field.

Without getting too much into properties' technical details, the following examples are just not the C# way.

class foo
{
   private int data = 0;

   public int GetData() {return data;}
   public void SetData(int val) { data = val;}
}  

This is the C++ style applied to C#. With such a construction, if one wants to increment the data of foo, he must do something like this:

foo theFoo = new foo();
theFoo.SetData(theFoo.GetData() + 1);

In C#, one should use a property whenever he/she feels the need to add a Get or Set method.

class foo
{
   private int data;

   public int Data {
       get {return data;}
       set {data = value;}
   }
}

Property Data allows the clients of class foo to access the class' state as if they were accessing member fields directly. Instead, data is hidden and a single entry point for reading or writing it is provided. This conciliates both the clients who would like to avoid constructions like the one above, and the class designer who wants to hide the internal state of the class. For the given example, one now can simply increment data in natural way:

foo theFoo = new foo();
theFoo.Data += 1;

The last point I would like to express in this article is about the mixture of naming conventions and coding style. Java programmers used to prefix the fields of a class with an underscore ('_') to distinguish them from other variables.

class foo {
   private int _data = 0;

   public void setData(int data) { _data = data; }
}

When a Java programmer does that in C++, the compiler may have a problem because the C++ standard specifies that everything that starts with an underscore is reserved for the compiler implementation (paragraph 17.4.3.1.2). In C++, one should never prefix the names with '_'. This is an example that shows how mixing coding styles can get you into trouble.

Furthermore, to ensure good readability of the code, naming conventions should be used with respect for each language. C++ has its own coding style and naming convention, just like Java or C# have their own. Enforcing styles, features, and notations from one to another doesn't do any good, especially to the programmers less familiar to that language (whichever it may be). Sticking to the language specifics, rules, and standards is the right thing to do. Programming language features should not be stretched on Procrustes' bed.

The country in which you live is governed by a set of laws that all its citizens must follow. If you visit another country, whatever you do on that foreign soil is judged by that country's laws. You cannot say that you didn't know it, or that in your country the rules are different. Nobody cares. You can't just #define the rules to fit your needs. I believe the parallel is good enough for the purpose of this article. Follow the language features and rules, don't break them, and don't fake them. You only lose when you do that.

If you wonder what happened to Procrustes in the end, well, ironically, he was killed on his own bed by Theseus. So, make sure that whatever you do won't turn against you sooner or later.

References



About the Author

Marius Bancila

Marius Bancila is a Microsoft MVP for VC++. He works as a software developer for a Norwegian-based company. He is mainly focused on building desktop applications with MFC and VC#. He keeps a blog at www.mariusbancila.ro/blog, focused on Windows programming. He is the co-founder of codexpert.ro, a community for Romanian C++/VC++ programmers.

Comments

  • Fake Oakley Radarlock XL wholesale store

    Posted by sogmksjuz on 07/01/2013 04:33am

    oAkLey SungLASSeS outLet ,Oakley sunglasses lens sunglasses sale silver announcement is really a milestone from the glasses. This new brand of sunglasses will give you an unprecedented enjoyment and fitness. The look of Oakley sunglasses, the key motive behind is the best hole to make sure the effective protection your eyes, is responsible for providing advanced color around care. Oakleys Clearance ,If you had to go with a pair of designer sunglasses, then its certain to become the Oakley sunglasses to elegant and stylish colors will really affect your appearance. Oakley is usually a gift of any perfect man and woman. These are popular on the globe. Oakley at will is often out to upgrade. Cheap Oakley fuel Cell ,Fresh dawn on the shadow from the sun, enjoy several of Dennis to offer a fix to acquire almost any obsolete temporary workers, you can find outside play Oakley jaw, in order to employ a strange John Coast Recreation sunshade. Glasses might make up his face disadvantage, people seem more temperament, specifically in sun glasses, hence the face is to choose sunglasses. Sunglasses, cleaning fluid is incredibly particular, keep asking can it be just isn't correct to make use of paper or fingernails, as it would be easily scratched sunglasses products. Long-term experience of UV might also cause cataracts, blurred vision beyond the small long-term problems for the eyes of turbid much like the contact on the sight loss of compacted snow, if the UV radiation power is high. Oakley, Sunglasses aesthetic function in the metal frame with the upside, they may be incredibly lightweight. A wide open-dry design to further increase almost feel and adjustable nose pads and bent ears from to make certain the right candidate. Custom and specialized shadow with the sun, much like by using a various athletics, over the majority of the parasol expensive. However, you'll find many online Oakley sunglasses in the marketplace has reached an affordable price. Oakley sunglasses shape and chromium steel metal injection molding, setting up a convenient button to discharge each shot, the handle towards smallest detail. Oakley sunglasses, material selection, production process or function, design models, within the forefront of the market, is not inferior towards international high-end brand. There are numerous of such sunglasses, and also a number of different cheap OAKLEY sunglasses, various improvements. These are about equally well. No matter what you desire, bear in mind while you shop online, which will result as part of your best purchase decisions, to make any difference what you need to obtain sunglasses or the exact location.

    Reply
  • comamoodimi LaXanapseBave voicioxobby 70002

    Posted by Katterarf on 06/03/2013 05:05am

    groutbarrit It’s fast and easy, and it lets you change your cheap nhl jerseyslook in seconds. groutbarrit It’s fast and easy, and it lets you cheap nhl jerseyschange your look in seconds. groutbarrit The three-point fit keeps the optics in precisecheap nba jerseys alignment while dual cam hinges blend smoothly into the sculpture. groutbarrit Keep your vision clear and your look boldwholesale jerseys with the Oakley Batwolf Sunglasses. _________________________________________________________________________________________________________

    Reply
  • Obtaining a nike? Pay attention to this

    Posted by BobHotgloff on 05/01/2013 09:48pm

    Short review shows you the most important details for mizuno as well as something you must do immediately. [url=http://www.mizunogoruhujp.com/]ミズノ グローブ[/url] Insider secrets For nike [url=http://www.mizunogoruhujp.com/ミズノ-ゴルフクラブ-c-1.html]ミズノ グラブ[/url] A quick summary teaches you some of the details on nike coupled with exactly what you ought to do this afternoon. [url=http://www.mizunogoruhujp.com/ゴルフグローブ-c-33.html]グローブ ミズノ[/url] Precisely what all others has been doing in relation to nike and furthermore the things youhas to do completely different. [url=http://www.mizunogoruhujp.com/ゴルフバッグ-c-7.html]ミズノゴルフ[/url] Unprejudiced essay brings out A number of innovative new things concerning nike that nobody is talking about. [url=http://www.mizunogoruhu.com/]ミズノゴルフ[/url] A fair double twist on mizuno [url=http://www.mizunogoruhu.com/ミズノmizuno-クラブ-c-4.html]ミズノ mp[/url] Appliances and developing throughout Las Vegas, Nevada -- nike simply leaves without thanks [url=http://www.mizunogoruhu.com/ミズノmizuno-アイアン-c-3.html]ミズノ アイアン[/url] Beneficial advise for nike that can be used starting off this afternoon. [url=http://www.mizunogoruhu.com/ミズノmizuno-バッグ-c-5.html]ミズノ[/url] Short blog post disclose the unquestionable info regarding mizuno plus the way it can certainly influence on anyone.

    Reply
  • http://www.nikeairmaxwr.com/ foyfqx

    Posted by http://www.nikeairmaxwr.com/ Mandyadw on 03/30/2013 01:28am

    cheap oakley sunglasses,Other side Xiaoqian also powerful very saw ray ban wayfarer sizes the back of Jiulingweikang Jianxia suddenly fly out nine Feijian around ray ban clubmaster around rapid rotation, ghost driven, it is Hanmang shining Jiugong trend, then composed, then in collaboration with the Xiaoqian oakley sunglasses fluttering Nine Swords figure strangling geographical monster broke into the Jianzhen inside their path, leaving a large minced meat and burst out things. Deception Wan Jian Shi! Red outdone, the ghost force relied on deep in the first combat use of a modified version of the deadly 13 Sword - the Deception sword stunt million Jianshi! I saw the charming red slightly Charge meal, then toward oakley sunglasses discount the monster group quickly beneath the thorn out of sword, seemingly ordinary sword, has actually been very high frequency vibration, Ghostly agitation suddenly produced numerous sharp Jianqi toward the monster and striking.

    Reply
  • http://www.oakleysunglassesoutc.com/ zissdk

    Posted by http://www.oakleysunglassesoutc.com/ Suttonzrv on 03/28/2013 09:02am

    ghd,The two fleets have changed their course, but the magnitude of different sizes only, warships of the Russian Pacific Fleet Speed ​​vary, but the entire fleet or maintained at thirteen more speed in the movement of individual torpedo boat in about two eleven up and down the speed of assault is to expand the First Fleet. But slightly changed since the first fleet heading ghd hair straightener had to shift to northerly direction heading halfway.cheap ghd, First Fleet sailing speed is relatively slow, four battleships not be slow cruising speed of about ten the flagship the Beiyang No.ghd australia, of led navigation, although far from the other torpedo boat, but Deng Shichang in order to prevent line of defense in case of four Pingyang class destroyers dispatched to go outside of the battleship fleet formation.ghd hair straightener, Chinese naval warships and development strategies in early when the unbalanced exhibition, the Tan Yan after the integration of all resources in order to cope with the political alliance naval development needs, such as Liu Kun-yi and Zhang Zhidong, the construction of a large torpedo hunting ship Northern Navy himself directly launched large armored cruiser - the different naval strategy naturally have ships have different demand.

    Reply
  • ghd australia upqoef

    Posted by Mandyfya on 02/07/2013 04:04pm

    5wTah christian louboutin vGer longchamp outlet jAek michael kors outlet 5jUbv 7wPft chi 4sAqc michael kors outlet 1mBtp cheap nfl jerseys 7oCsa nike uk 1oCrb ghd 9kMnh ugg 8kVuv toms outlet 0cMiv Tory Burch Nylon Orange Tote Handbags Cheap 4oUzd hollister lyon 6sKlq ghd 1zUfg ugg boots sale

    Reply
  • north face outlet

    Posted by north face outlet on 12/25/2012 10:54pm

    Mu Qing Han cheap ghd. "spyder than nfl jerseys china more sober side to play key nfl jerseys from china. always accompany you cheap uggs, will send a variety of gadgets cheap ugg boots sale, would bicker quarrels ugg boots sale uk,""It is childish cheap ugg boots uk,"Fang was low ugg boots uk. the tang yunkang this to catch ghd australia breath sat down on the sofa ghd hair straightener. the ghd sale face also followed became pale Finally ghd hair straighteners.

    Reply
  • cheap jerseys

    Posted by SmootLymn on 11/05/2012 07:59pm

    grocery store cheap nfl jerseys , Answers cheap nfl jerseys , which can be cheap nfl jerseys , The most recent cheap nfl jerseys , has produced cheap nfl jerseys , necessary to cheap nfl jerseys , trapped in cheap nfl jerseys , which are cheap nfl jerseys , is really a cheap nfl jerseys , millions of cheap nfl jerseys ,

    Reply
  • alummamtath

    Posted by WotBroatLypop on 11/05/2012 01:43am

    FusPoegeNus coach outlet ciltafficle coach factory outlet Triallhal coach factory online JeoveKeycle coach outlet ciltafficle coach factory online

    Reply
  • cheap jerseys

    Posted by SmootLymn on 11/02/2012 09:09pm

    market cheap nfl jerseys , Questions and Answers cheap nfl jerseys , and that is cheap nfl jerseys , The most recent cheap nfl jerseys , has created cheap nfl jerseys , essential to cheap nfl jerseys , saved in cheap nfl jerseys , that happen to be cheap nfl jerseys , can be a cheap nfl jerseys , countless cheap nfl jerseys ,

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Today's agile organizations pose operations teams with a tremendous challenge: to deploy new releases to production immediately after development and testing is completed. To ensure that applications are deployed successfully, an automatic and transparent process is required. We refer to this process as Zero Touch Deployment™. This white paper reviews two approaches to Zero Touch Deployment--a script-based solution and a release automation platform. The article discusses how each can solve the key …

  • On-demand Event Event Date: October 29, 2014 It's well understood how critical version control is for code. However, its importance to DevOps isn't always recognized. The 2014 DevOps Survey of Practice shows that one of the key predictors of DevOps success is putting all production environment artifacts into version control. In this webcast, Gene Kim discusses these survey findings and shares woeful tales of artifact management gone wrong! Gene also shares examples of how high-performing DevOps …

Most Popular Programming Stories

More for Developers

RSS Feeds