簡體   English   中英

參數或方法重載的幻數?

[英]Magic numbers for parameters or method overloading?

我需要為C ++中的一個類實現一個接口,在該接口中,我需要詢問與兩種類型的集合相關的事件的發生,這里說人員和動作。 我需要在所有可能的組合中要求提供人員識別符和動作識別符(全部,僅指定其中一個識別符,或同時指定兩者)
選項1)

// Asks for all events occured for every combination
int getNumberofEvents(float param1)
// Asks for all events occured for idPerson AND all possible value of idAction
int getNumberofEvents(int idPerson, float param1)  
// Asks for all events occured in idAction AND all possible value of idPerson
int getNumberofEvents(int idAction, float param1)
// Asks for all events occured in idPerson AND idAction
int getNumberofEvents(int idPerson, int idAction, float param1)

該選項很容易閱讀,但是我需要為每種可能的組合實現一個不同的接口,因此,如果我包含一個新的標識符(2³),將有8種方法。

選項2)

static const int ALL_PERSONS= 0;
static const int ALL_ACTIONS= 0;
int getNumberofEvents(int idPerson, int idAction, float param1)

對於此選項,只有一個方法界面,但是我引入了一個公共魔術數字來搜索“所有可能的ID”

關於可用性和進一步的可維護性,這是我現在想到的這兩者之間的最佳選擇(當然,還有其他一些更好的選擇我沒有包括在內)。

謝謝。

您可以修改選項2以避免使用幻數,也可以避免為操作參數傳遞人id的問題,反之亦然:

struct Person
{
    explicit Person(int x) : id (x) {}
    int id;
    static Person ALL;
};

Person Person::ALL(0);

struct Action
{
    explicit Action(int x) : id (x) {}
    int id;
    static Action ALL;
};

Action Action::ALL(0);

int getNumberofEvents(const Person& person, const Action& action, float param1);

// ...

int count = getNumberOfEvents(Person(3), Action::ALL, 1.0f);

您似乎很想重新創建標准庫中C ++包含的內容: std::count_if

請注意,它允許任意復雜的條件,因為它接受可以過濾並確定哪些對象匹配的函子對象。 使用C ++ 11,lambdas使提供條件比以往更加容易。

您可以公開begin()end()迭代器,並讓用戶調用std::count_if ,或者編寫

int getNumberofEvents(std::function<bool (const descriptor&)> filter, float param1);

並讓用戶以非常自然的方式編寫其查詢表達式:

getNumberOfEvents([](const descriptor& x) { return x.Action == ACTION_RAISE; }, 5.7);

絕對使用選項2。您的代碼用戶將不必查找要調用的方法,在某些情況下,他們只能使用您定義的常量。 僅使用一個函數名稱就可以使用戶的生活變得更加輕松,這樣他們就不必不斷引用您的.h文件來找出他們想要的多個函數(命名相同)中的哪個使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM