【发布时间】:2011-03-11 11:45:08
【问题描述】:
我正在使用 tinyxml 来解析 xml 文件,我发现这里的错误处理适用于箭头代码。我们的错误处理只是向文件报告一条消息。
这是一个例子:
const TiXmlElement *objectType = dataRoot->FirstChildElement( "game_object" );
if ( objectType ) {
do {
const char *path = objectType->Attribute( "path" );
if ( path ) {
const TiXmlElement *instance = objectType->FirstChildElement( "instance" );
if ( instance ) {
do {
int x, y = 0;
instance->QueryIntAttribute( "x", &x );
instance->QueryIntAttribute( "y", &y );
if ( x >= 0 && y >= 0 ) {
AddGameObject( new GameObject( path, x, y ));
} else {
LogErr( "Tile location negative for GameObject in state file." );
return false;
}
} while ( instance = instance->NextSiblingElement( "instance" ));
} else {
LogErr( "No instances specified for GameObject in state file." );
return false;
}
} else {
LogErr( "No path specified for GameObject in state file." );
return false;
}
} while ( objectType = objectType->NextSiblingElement( "game_object" ));
} else {
LogErr( "No game_object specified in <game_objects>. Thus, not necessary." );
return false;
}
return true;
我不是对此大发雷霆,但如果有人能想出一种更清洁的方法来实现这一点,我将不胜感激。
附:例外不是一种选择。
编辑:
这样的东西会更好吗?
if ( !path ) {
// Handle error, return false
}
// Continue
这消除了箭头代码,但箭头代码类型将所有错误日志记录在一个地方。
【问题讨论】:
标签: c++ refactoring error-handling xml-parsing