如何组织此代码


myThread是一个每秒执行一次的函数,基本上它读取一些必须解析和执行的数据。这个函数增长了很多,它有1500多行代码,就像下面的例子一样,有很多[if-else-if-else]阻止了很多重复,比如sleep或SendToChat向控制台发送命令,而且它很难维护、更改等

我想要一些关于如何重写的建议(如果可能的话,用代码示例,这将有助于我理解布局(,我不是很有经验,所以我不太确定是否有可能将这些代码变成更好的代码,以提高可维护性和可读性?

也可以随意评论任何函数或其他任何东西,因为它可以帮助我改进其他错误的地方。

这只是代码的一部分样本,而不是整个代码。如果您觉得需要代码中的任何其他信息,请随时询问,我会尽可能发布

附言:这不是irc的事。

private void myThread()
{
    while(isRunning)
    {
        // SOME PARSED DATA HERE
        // if (parsedData matchs) do the below stuff
        Messages received = new Messages
        {
            Sent = Convert.ToDateTime(match.Groups[1].Value),
            Username = match.Groups[3].Value,
            MessageType = (match.Groups[2].Length > 0) ? MsgType.System : MsgType.Chat,
            Message = match.Groups[4].Value.Trim(),
            CommandArgs = match.Groups[4].Value.ToLower().Trim().Split(' ')
        };
        // Get the user that issued the command
        User user = usersList.Find(x => x.Name == recebe.received.ToLower());
        if (user != null)
        {
            // different greetings based on acess level
            if (received.Message == "has entered this room")
            {
                if (User == null)
                {
                    SendToChat("/w " + received.Username + " " + received.Username + " you have no registration.");
                    Thread.Sleep(1000);
                    SendToChat("/kick " + received.Username + " not registered.");
                    Thread.Sleep(1000);
                }
                else
                {
                    string cmd = (user.Access < Access.Vouch) ?
                        "/ann " + user.Access.ToString() + " <" + received.Username + "> has entered the room." :
                        "/w " + received.Username + " " + received.Username + " welcome to our room !";
                    SendToChat(cmd);
                    Thread.Sleep(1000);
                }
            }
            // Here we filter all messages that start with a . which means it is a command
            else if (received.Message.StartsWith(".") && user != null)
            {
                // here we verify if the user has Access to use the typed command and/or if the command exists 
                if (accessList.Exists(x => x.Access == user.Access && x.HasCommand(received.CommandArgs[0])))
                {
                    if (received.CommandArgs[0] == ".say")
                    {
                        SendToChat("/ann " + received.Username + " says: " + received.Message.Substring(received.CommandArgs[0].Length + 1));
                        Thread.Sleep(1000);
                    }
                    else if (received.CommandArgs[0] == ".command")
                    {
                        string allowedList = string.Empty;
                        int count = 0;
                        foreach (string cmd in listaAccesss.Find(x => x.Access == user.Access).Command)
                        {
                            if (count == 0)
                                allowedList += cmd;
                            else
                                allowedList +=  ", " + cmd;
                        }
                        SendToChat("/w " + received.Username + " " + received.Username + " you are allowed to use the followed commands: " + permite);
                        Thread.Sleep(1000);
                                    }
                    else if (received.CommandArgs[0] == ".vip")
                    {
                        if (received.Command.Count() < 2)
                        {
                            SendToChat("/w " + received.Username + " " + received.Username + ", see an example of how to use this command: .vip jonh");
                            Thread.Sleep(1000);
                        }
                        else if (received.Command.Count() == 2)
                        {
                            var target = usersList.Find(x => x.Name == received.CommandArgs[1]);
                            if (target == null)
                            {
                                User newUser = new User
                                {
                                    Name = received.CommandArgs[1].ToLower(),
                                    Access = Access.VIP,
                                    Registered = DateTime.Now,
                                    RegisteredBy = received.Username.ToLower()
                                };
                                usersList.Add(newUser);
                                SendToChat("/ann " + user.Access.ToString() + " " + user.Name + " has promoted " + received.CommandArgs[1] + " to VIP.");
                                Thread.Sleep(1000);
                            }
                            else if (target != null && target.Access == Access.VIP)
                            {
                                SendToChat("/w " + received.Username + " " + received.Username + " the user " + target.Name + " already have VIP access.");
                                Thread.Sleep(1000);
                            }
                            else if (target != null && user.Access == Access.HeadAdmin && user.Access < target.Access)
                            {
                                Access last = target.Access;
                                target.Access = Access.Vouch;
                                SendToChat("/ann " + user.Access.ToString() + " " + received.Username + " promoted/demoted the " + last.ToString() + " " + target.Name + " to VIP.");
                                Thread.Sleep(1000);
                            }
                            else if (target != null && target.Access == Access.Vouch)
                            {
                                target.Access = Access.VIP;
                                target.RegisteredBy = user.Name;
                                SendToChat("/ann " + user.Access.ToString() + " " + received.Username + " promoted the vouch of " + target.Name + " to VIP.");
                                Thread.Sleep(1000);
                            }
                            else
                            {
                                SendToChat("/w " + received.Username + " " + received.Username + " you can't register or modify the user " + received.CommandArgs[1] + ".");
                                Thread.Sleep(1000);
                            }
                        }
                    }
                }
                else
                {
                    SendToChat("/w " + received.Username + " " + received.Username + " command not found.");
                    Thread.Sleep(1000);
                }
            }
        }
        Thread.Sleep(1000);
    }
}

通常,当您看到复杂的条件逻辑(许多if/else块和嵌套条件(时,您应该考虑将代码重构为State或Strategy设计模式(取决于情况(。看看这些有什么想法。

更新:
如果你在如何重构代码方面遇到了麻烦,我最近读到一本很棒的书,它有助于分解流程(涵盖了从添加版本控制到单元测试到持续集成的所有内容……还谈到了迭代分解,直到你能够应用依赖项注入等内容(,因为每一个主题都有整本书,但这是一个很好的起点:
.Net 中Brownfield应用程序的开发

组织此代码的一个好方法是使用"责任链"设计模式。

这个想法是为每个知道该做什么的"命令"有一个类,例如:

public class NewUserCommand : ConsoleCommand
{
    public override void Process(Context context, string command)
    {
        if (context.User != null)
        {
            // different greetings based on acess level
            if (context.Received.Message == "has entered this room")
            {
                if (context.User == null)
                {
                    SendToChat("/w " + context.Received.Username + " " + context.Received.Username + " you have no registration.");
                    Thread.Sleep(1000);
                    SendToChat("/kick " + context.Received.Username + " not registered.");
                    Thread.Sleep(1000);
                    //I could process the request
                    return;
                }
            }
        }
        //I dont know what to do, continue with the next processor
        this.Successor.Process(context, command);
    }
}

每个命令都需要其中一个类。

我通常会做一个小技巧,虽然这不是一个好的重构方法,但会让代码更可读。

而不是:

if (condition1) {
    statement1;
} else if (condition2) {
    statement2;
    if (condition3) {
       statement3;
    }
}

我使用:

if (condition1) {
    statement1;
    return;
}
if (condition2) {
    statement;
    return;
}
if (condition2 && condition3) {
    statement3;
    return;
}

降低代码的复杂性是分解代码的第一步。接下来我要采取的步骤是:

  • 重构为不同的方法
  • 寻找相似的方法、重构和拥有辅助方法
  • 将不依赖于内部数据的方法移动到其他类
  • 当您似乎有两种不同的方法来处理完全不同的"事物"时,将它们作为单独的类(这是一项主要的工作,尤其是在冗长的代码上(
  • 当您将事情分离但又是过程性的时,您可能会开始应用模式来减少代码的重复。Jason Down提到了State、Strategy,但Factory、Template Method和大多数方法也可以,这取决于您的需求

它肯定需要一些重构。几件事:

  • 不要重复你自己(例如线程。睡眠(1000(;)
  • 把它分成几个方法
  • 把你的逻辑和蓄意破坏分开
  • 使用依赖项注入(Messages,isRunning应传递给方法(
  • 与其使用多个标志,不如使用多态性

首先,我认为您应该将这个庞大的代码拆分为几个方法。将您所评论的逻辑部分分开。您应该为注释的每个部分都有一个方法(这是最低限度的(。尝试开始这个:

  1. 方法://此处的某些部分数据//如果(parsedData匹配(执行以下操作试着做一个这样的方法。

  2. 方法//获取发出命令的用户

  3. 基于访问级别的方法//不同问候语

  4. 方法//在这里我们过滤所有以开头的消息。这意味着它是一个命令

等等…

你必须对重复的部分进行方法,这样你就可以总是在一个地方进行更改,而不是搜索所有代码并将每个参数更改为新值。

相关内容

  • 没有找到相关文章

最新更新