假设你有一个基类:
class base
{
public:
virtual void OnConnect() = 0;
virtual void OnDisonnect() = 0;
// Other functions ...
};
有几个类继承自base,其中大部分对这两个功能有不同的实现。但是,其中一个派生类具有相同的内容,我想知道以下哪种样式更好,为什么:
(A) 在两个函数中保留重复的代码
void derived::OnConnect(const char* err)
{
/*
* 3~5 lines of code in this function with a block of comment.
*/
}
void derived::OnDisconnect(const char* err)
{
/*
* 3~5 lines of code in this function with a block of comment.
*/
}
(B) 将一个委托(delegate)给另一个
void derived::OnConnect(const char* err)
{
/*
* 3~5 lines of code in this function with a block of comment.
*/
}
void derived::OnDisconnect(const char* err)
{
// Same as OnConnect()
OnConnect(err);
}
(C) 定义另一个函数并在 OnConnect/OnDisconnect 中调用该函数
static func(const char* err)
{
/*
* 3~5 lines of code in this function with a block of comment.
*/
}
void derived::OnConnect(const char* err)
{
func(err);
}
void derived::OnDisconnect(const char* err)
{
func(err);
}
哪个更好?
最佳答案
由于两个函数接口(interface)中没有任何内容表明一个应该与另一个有任何关系,我认为我们可以安全地排除选项 B。
就我个人而言,我会选择选项 C。
关于c++ - c/c++中两个函数内容相同时,哪种风格更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22144858/