如何重构以下代码

时间:2015-11-10 09:53:33

标签: generics refactoring

嗨,下面的BackendHubProxy继承Hub,我还有另一个类使用GlobalHost.ConnectionManager.GetHubContext();

重构以下内容有什么好处?

    private static void OnGamesDisabled(Guid playerId)
    {
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<BackendHubProxy>();
        hubContext.Clients.User(playerId.ToString("N")).DisablePlayer();
    }

    private static void OnGamesDeauthorized(Guid playerId)
    {
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<BackendHubProxy>();
        hubContext.Clients.User(playerId.ToString("N")).DeauthorizePlayer();
    }

    private static void OnGamesChanged(string[] lobbyClientIds)
    {
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<FrontendHubProxy>();
        hubContext.Clients.Groups(lobbyClientIds).GamesChanged();
    }

1 个答案:

答案 0 :(得分:0)

您没有明确说明您的最终目标是什么,但假设您正在尝试消除重复,则可以将重复提取到一种方法。

private static Clients getClients()
{
    var hubContext = GlobalHost.ConnectionManager.GetHubContext<BackendHubProxy>();
    return hubContext.Clients;
}

private static void OnGamesDisabled(Guid playerId)
{
    getClients().User(playerId.ToString("N")).DisablePlayer();
}

private static void OnGamesDeauthorized(Guid playerId)
{
    getClients().User(playerId.ToString("N")).DeauthorizePlayer();
}

private static void OnGamesChanged(string[] lobbyClientIds)
{
    getClients().Groups(lobbyClientIds).GamesChanged();
}