Ordering of Include Statements to Reduce Hidden Dependencies

23 July, 2009 § 2 Comments

The Google C++ Style Guide says that #include statements should be ordered in the following way (if you are writing foo2.cc):

  1. dir2/foo2.h (preferred location — see details below).
  2. C system files.
  3. C++ system files.
  4. Other libraries’ .h files.
  5. Your project’s.h files.

The goal of this is to reduce hidden dependencies within header files. My question is, shouldn’t system files be included after library/project files? I would think that there is a guarantee that the system files aren’t going to include other library/project files, so wouldn’t the following order make more sense to find hidden dependencies?

  1. dir2/foo2.h (preferred location — see details below).
  2. Your project’s.h files.
  3. Other libraries’ .h files.
  4. C system files.
  5. C++ system files.

Non-member non-friend functions vs private functions

28 June, 2009 § 5 Comments

Herb Sutter has said that the most object oriented way to write methods in C++ is using non-member non-friend functions. Should that mean that I should take private methods and turn them into non-member non-friend functions? Any member variables that these methods may need can be passed in as parameters.

Example (before):

class Number {
 public:
  Number( int nNumber ) : m_nNumber( nNumber ) {}
  int CalculateDifference( int nNumber ) { return minus( nNumber ); }
 private:
  int minus( int nNumber ) { return m_nNumber - nNumber; }
  int m_nNumber;
};

Example (after):

int minus( int nLhsNumber, int nRhsNumber ) { return nLhsNumber - nRhsNumber; }
class Number {
 public:
  Number( int nNumber ) : m_nNumber( nNumber ) {}
  int CalculateDifference( int nNumber ) { return minus( nNumber ); }
 private:
  int m_nNumber;
};

Am I on the right track? Should all private methods be moved to non-member non-friend functions? What should be rules that would tell you otherwise?

I’ve asked the question on Stack Overflow. Feel free to leave a response there so I can better track responses and award credit.

Update to a previous post

22 June, 2009 § 1 Comment

I’ve updated the post titled, “C++ Trick: Removing the need for Forward Declarations“. Further reading of The C++ Programming Language by  Bjarne Stroustrup has pointed me to a partial explanation [1]:

For reasons that reach into the pre-history of C, it is possible to declare a struct and a non-structure with the same name in the same scope. For example:

struct stat {  /* ... */  };
int stat( char* name, struct stat* buf);

In that case, the plain name (stat) is the name of the non-structure, and the structure must be referred to with the prefix struct. Similarly, the keywords class, union (§C.8.2), and enum (§4.8) can be used as prefixes for disambiguation. However, it is best not to overload names to make that necessary.

That explains part of it. My assumption stands that because you are declaring that this name refers to a typename, then you will not need to forward declare it. I haven’t tried it yet, but I assume you can interchange `class` with `typename` just as well to declare that this is a type you are referring to.

[1] B. Stroustrup. The C++ Programming Language: 3rd Edition. Page 104.

C++ Trick: Removing the need for Forward Declarations

18 June, 2009 § 3 Comments

C++ is known to have lots of tricks. This is seen by some as a powerful asset and by others as a reason to stray away. I’m always fascinated by learning new features of C++ and have fun finding out more all the time.

During a recent code review, I noticed the  following code:

foo.h

#ifndef FOO_H
#define FOO_H

class foo {
};

#endif

bar.h

#ifdef BAR_H
#define BAR_H

class bar  {
 class foo* m_pFoo;
 bar();
};

#endif

bar.cpp

#include "bar.h"
#include "foo.h"

bar::bar() : m_pFoo( new foo )
{
} 

Notice anything  odd? How about line 5 in bar.h?

It turns out that there is no forward declaration needed in bar.h for the foo type if you write your declaration like so. The reason that this works is by prepending the typename with ‘class’, you are explicitly telling the compiler that foo is a type, and you are declaring a pointer to this type. If you did not prepend the declaration with class, then the compiler would have no way to know if you meant to multiply a variable named foo by another variable named m_pFoo.

You may have seen this idiom more with structs, like so:

struct POINT { 
int x;
int y;
};

struct POINT topLeft;

And so it turns out there is more! You can even replace that same line 5 with:

struct foo* m_pFoo;

This is because the C++ Standard says that a class can be declared as a struct and it is still a class. There is no difference when declaring a class or struct in C++. The only difference comes when the type is defined, in which struct causes bases and members to be public by default. [1]

I don’t recommend that you use this trick in production code, as it is likely to confuse other members of your team, and there is no performance savings by not typing the class name one more time and another semicolon, but you can definitely use this to stump one of your friends about your inner-knowledge of C++.

Update (June 22, 2009): The ability to do this comes from the pre-history of C. Within C and C++, you can create a struct/class and a non-struct/class with the same name, such as:

 struct stat { /* ... */ };
int stat( char* name, struct stat* buf ); 

When you use the struct/class, you have to prefix it with the keyword struct/class to disambiguate between the names. [2]

[1] D. Abrahams, A. Gurtovoy. C++ Template Metaprogramming: Concepts, Tools, and Techniques from Boost and Beyond. Page 25.
[2] B. Stroustrup. The C++ Programming Language: 3rd Edition. Page 104.

Strategies for refactoring to the Law of Demeter

29 May, 2009 § Leave a comment

From Wikipedia:

The Law of Demetre (LoD), or Principle of Least Knowledge, is a design guideline for developing software, particularly object-oriented programs. The guideline was invented at Northeastern University towards the end of 1987, and can be succinctly summarized as “Only talk to your immediate friends.” The fundamental notion is that a given object should assume as little as possible about the structure or properties of anything else (including its subcomponents).

Some code that I have ran across breaks the Law of Demeter. It just didn’t break it, it had complete disregard for the law. In working on some refactorings to open up unit test coverage, I worked through several different design alternatives before coming up with the final choice.

Example problem: There are quite a few lines of the codebase that look like this,

CString strUserName = theApp.GetSomeObject().GetOwner().strUserName;

In this case, there is only one instance of the SomeObject class during the execution of  the program. It is referenced using the global CWinApp-derived instance, theApp.

First idea: Use the singleton pattern. This pattern is considered an anti pattern by some, and is known to make unit testing harder since it can make the process of mocking out the object non-trivial. I quickly moved away from this decision.

Second and final idea: Use dependency injection. When the SomeObject is created within the constructor for the CWinApp-derived instance, any object that needs a reference to the object gets a reference. I was then able to make SomeObject implement an interface that the mocks can use. The references are then passed down to all parties that need this. This makes methods and classes easy to unit test and reduces some coupling, since now the code can look like this:

CString strUserName = m_pSomeObject->GetOwner().strUserName;

So we’ve gotten rid of the call to theApp, but how do we get rid of the call to the strUserName property? In this case, we can define a method within SomeObject’s interface to get the username of the owner.

CString strUserName = m_pSomeObject->GetUserNameOfOwner();

If you find yourself writing a lot of simple one line methods to access properties of an object like the Owner, then this last solution probably isn’t the best route for you to take, but it might give you an idea.

Thanks, and let me know your thoughts.

Unit testing MFC with MSTest

6 May, 2009 § 20 Comments

Visual Studio 2008 offers the built in ability to write unit tests in C# by creating a Test Project. This same feature applies to managed C++, otherwise known as C++/CLI. If you are working on a project in MFC and would like to get the same unit test integration that is built directly in to Visual Studio, there is a way. Here are the steps you will have to follow:

  1. Create a C++ Test project within your solution.
  2. Open up the Properties of the project and change the Common Language Runtime support from /clr:safe to /clr. This will allow you to execute code from both C++/CLI and simple C++.
  3. Set the project to link to MFC using a shared DLL. You cannot compile with both /clr and statically linking to MFC.
  4. Edit the test project’s dependencies and add a dependency on the MFC project that you would like to unit test.

You should be all good here, except for one large gotcha. The unit test project will have its own instance of CWinApp declared. If the MFC project that you would like to test against also has its own instance of CWinApp, then everything will get confused and the tests won’t start. To solve this, you will have to create a separate MFC DLL project and move your code to this project. Your test project should now have a dependency on this new MFC DLL project, and not your previous one. If you would still like your application to produce a single executable, just make sure that the previous project statically links against the MFC DLL that you have just created.

Let me know if you have any questions. I’ve spent the last couple days getting this scenario to work.

(I’m using GoogleMock with my unit tests, and I think that the combination of MSTest and GoogleMock is perfect. The integration with Visual Studio that MSTest provides, and the ease to make mocks with GoogleMock makes writing C++ unit tests a walk in the park. I should be putting up a simple tutorial on using GoogleMock in the future.)

More notes on “Effective C++”

23 April, 2009 § 1 Comment

This is the fourth post in a series of posts that I started after I finished reading Effective C++ by Scott Meyers. Previously covered were parts three, two, and one.

Item 31: Minimize compilation dependencies between files.
Using the pimpl idiom (“pointer to implementation”) you can truly separate the implementation from the interface. Omaha, aka Google Update, uses the pimpl idiom within the CUP implementation. This allows any client of CupRequest to have a lightweight object and be divorced from implementation details of CupRequest. If CupRequestImpl ever changes, any clients of CupRequest won’t have to recompile, allowing build times to be shorter.

Item 34: Differentiate between inheritance of interface and inheritance of implementation.
The easiest way to differentiate between interfaces and implementations is to declare your interfaces with a naming convention like IInterface. For example, this way you can clearly see that a class is enumerable because it implements IEnumerable, yet if the class inherits SortedArray, then you know that it extends an implementation of a SortedArray.

Item 39: Use private inheritance judiciously.
Sometimes classes have virtual functions that need to be overridden, this should be the only case for using private inheritance. Private inheritance is not the same as public inheritance. Public inheritance is usually referred to as an ‘is-a’ relationship, where you can say that the derived is an extension of the base class. Private inheritance simply tells implementation details, similar to a ‘has-a’ relationship.

Item 48: Be aware of template metaprogramming.
I had never heard of template metaprogramming (TMP) before this Item. This looks to be really interesting, and I’m looking forward to reading C++ Template Metaprogramming written by the Boost organization.

After reading Effective C++, I’m looking forward to using more of the STL, and getting my feet wet with TR1, Boost, and TMP. I would highly recommend reading Effective C++ for an experienced developer that is working in C++. This book is also good for students just getting in to C++, as it can help them watch out for many mistakes that novices and intermediate level developers may make.

Where Am I?

You are currently browsing entries tagged with c-plus-plus at JAWS.

Follow

Get every new post delivered to your Inbox.

Join 1,013 other followers