Tuesday, February 21, 2012

Use typedef to make your code easier to read.

I want to talk about the C++ keyword "typedef" in this post and how it can make your life easier.

I assume that you often work with hard to read template classes (like 90% of the STL).
Consider this code given the above assumption:

 void foo(){  
   std::list<Class> myList;  
   //...  
   for(std::list<Class>::iterator iter = myList.begin();iter !+ myList.end()iter++){  
    //..  
   }  
  std::tr1::smart_ptr<Class> myInstance(new Class());  
 }  

This type of code layout can get very confusing very fast.
If you just add 3 typedef's at the beginning of this code, you'll make the code much easier to read.

 typedef std::list<Class> MyClassList;  
 typedef std::list<Class>::iterator MyClassIterator;  
 typedef std::tr1::shared_ptr<Class> MyClassPtr;  

Using these typedefs, I'll show you what that code sample above will look like:

 void foo(){  
   MyClassList myList;  
   //...  
   for(MyClassIterator iter = myList.begin();iter !+ myList.end()iter++){  
    //..  
   }  
  MyClassPtr myInstance(new Class());  
 }  

That's much better, isn't it?

No comments:

Post a Comment