2013-03-16 136 views
2

例如,我有两个方法CreateNewDocument和OpenDocument,它们在我的GUI代码中有两个不同的级别。一个是低级别的,只是做了方法名称的含义;另一个是高级别,它会在做所需的工作之前检查现有文档可能存在的不存在。低级别名称出现在高级别代码中,因为它们被调用来实现高级别方法。我的问题是如何区分它们以避免混淆用户和读者?请仔细阅读说明的代码。如何命名不同级别的类似方法?

class GuiClass 
{ 
public: 
    // Re-implement to tell me how to do the low-level create new document. 
    virtual void LowLevelCreateNewDocument(); 

    // Then I do the high-level version for you. 
    void HighLevelCreateNewDocument() 
    { 
     // Handle unsavings and blabla... 
     ... 
     // Then do the low-level version 
     LowLevelCreateNewDocument(); 
     // Afterward operations 
     ... 
    } 
}; 
+2

'CreateNewDocument'和'OpenDocument'对我来说似乎是两件非常不同的事情。这两个我都认为是高水平的。 – 2013-03-16 11:53:45

回答

1

我会作出这样的“低级别” CreateNewDocument()方法protectedprivate,因为它似乎,它应该只从该类中的其他类成员或派生的人分别称为。

class GuiClass 
{ 
public: 
    // Then I do the high-level version for you. 
    void CreateNewDocument() 
    { 
     // Handle unsavings and blabla... 
     ... 
     // Then do the low-level version 
     CreateNewDocumentInternal(); 
    } 

protected: 
    //pure virtual to enforce implementation within derived classes. 
    //          | 
    //          V 
    virtual void CreateNewDocumentInternal() = 0; 
}; 

class GuiClassImpl : public GuiClass 
{ 
protected: 
    /*virtual*/ void CreateNewDocumentInternal() 
    { 
     //Do the low-level stuff here 
    } 
}; 

如果这些方法真的在不同的实现水平,可以考虑把它们分成不同的类或命名空间,作为已经建议。使用必须实现纯虚拟受保护成员函数的子类,您已经具有适当的封装。