2011年2月21日 星期一

C++ Coding Standards - Prefer composition to inheritance.

Herb Sutter and Andrei Alexandrescu 的理由是:Avoid inheritance taxes: Inheritance is the second-tightest coupling relationship in C++, second only to friendship. 除了 tight-coupling 外,一個重要的原因是 OO-modeling 哲學:兒子不能超過爸爸。兒子指的是 derived class,爸爸當然是 base class.

之前寫的 BubbleBall Level One 是錯誤示範,兒子超過爸爸了。改寫後如下:
class Box2dLevelOne {
public:
Box2dLevelOne() {
physics_.initWorld();
physics_.setEdgeBackground(...);
physics_.setPlayer(...);
physics_.setGoal(...);
}
~Box2dLevelOne() {
physics_.deinitWorld();
}

void setTriangle(...) {
physics_.setTriangle(...);
}

bool isGoaledAfter(int seconds) {
float time_step = 1.0f/60.0f;
for (int i = 0; i < seconds; ++i) {
physics_.simulate(time_step);
if (physics_.isGoaled()) {
return true;
}
}
return false;
}

private:
Box2dPhysics physics_;
};

TEST(Box2dLevelOne, StressTest) {
const TestItem item[] = { ... };

const int size = arraysize(item);
for (int i = 0; i != size; ++i) {
Box2dLevelOne level;
level.setTriangle(...);
EXPECT_EQ(item[i].is_goaled, level.isGoaledAfter(60 * 10));
}
}

以上。當然我還犯其他錯誤 (過早最佳化,沒有利用 assert 來說明內部假設與不變性),接下來會修掉這些錯誤。繼續加油吧!

2 則留言:

  1. Yes.

    In the old design, BaseLevel class has two responsibilities: level and physics. So I want to make BaseLevel class simpler.

    回覆刪除