2011年2月13日 星期日

Do The Simplest Thing That Could Possibly Work

今天加 SphereStack test,果然爛掉。為什麼?這是因為個人奉行:
Do the simplest thing that could possibly work.

這就是 test-driven 的精神,除非測試失敗,否則不要寫多餘的程式碼,即使下個測試會用到。因此原先系統不支援圓形物體,這就是為什麼會爛掉的原因。

在這當下,才是真正寫程式碼的時機。
  if (config.shape_config->type == ShapeConfig::Polygon) {
...
b2PolygonShape shape_impl;
...

b2FixtureDef config_impl;
config_impl.shape = &shape_impl;
config_impl.friction = config.friction;
config_impl.restitution = config.restitution;
config_impl.density = config.density;

itself_->CreateFixture(&config_impl);
}
else if (config.shape_config->type == ShapeConfig::Circle) {
...
b2CircleShape shape_impl;
...

b2FixtureDef config_impl;
config_impl.shape = &shape_impl;
config_impl.friction = config.friction;
config_impl.restitution = config.restitution;
config_impl.density = config.density;

itself_->CreateFixture(&config_impl);
}
好多重複的程式碼,雖然可以立即 refactor,改善既有的程式碼,但目前測試都沒過,千萬別急著動,這也是 test-driven 的精神。測試過了再來 refactor,順便確保 refactored code 是對的。

跑測試,沒過。見鬼了!不是的,因為我又少支援線段物體,只好再加上去讓他過。
  if (config.shape_config->type == ShapeConfig::Polygon) { 
...
}
else if (config.shape_config->type == ShapeConfig::Circle) {
...
}
else if (config.shape_config->type == ShapeConfig::Edge) {
...
b2EdgeShape shape_impl;
...

b2FixtureDef config_impl;
config_impl.shape = &shape_impl;
config_impl.friction = config.friction;
config_impl.restitution = config.restitution;
config_impl.density = config.density;

itself_->CreateFixture(&config_impl);
}
更多重複的程式碼。這不重要,重要的是先跑測試。啊!過了。接著再來 refactor 吧!
  b2Shape* shape_wrapper;

if (config.shape_config->type == ShapeConfig::Polygon) {
...
b2PolygonShape* shape_impl = new b2PolygonShape();
shape_wrapper = shape_impl;
...
}
else if (config.shape_config->type == ShapeConfig::Circle) {
...
b2CircleShape* shape_impl = new b2CircleShape();
shape_wrapper = shape_impl;
...
}
else if (config.shape_config->type == ShapeConfig::Edge) {
...
b2EdgeShape* shape_impl = new b2EdgeShape();
shape_wrapper = shape_impl;
...
}
else {
return;
}

b2FixtureDef config_impl;
config_impl.shape = shape_wrapper;
config_impl.friction = config.friction;
config_impl.restitution = config.restitution;
config_impl.density = config.density;

itself_->CreateFixture(&config_impl);

delete shape_wrapper;
再跑測試,還是過,refactor 品質沒有問題 (可能 code 還很髒,可能還有 bug,不過至少可以過 SphereStack)。Do the simplest thing that could possibly work.

沒有留言:

張貼留言