我该如何组织这段代码?

时间:2011-05-30 21:36:29

标签: c# winforms .net-3.5 readability maintainability

myThread是一个每秒执行一次的函数,基本上它会读取一些必须被解析和执行的数据。函数增长了很多,超过1500行代码,如下面的示例,有很多[if else if else]阻止大量重复,如sleep或SendToChat向控制台发送命令,并且很难维护对它做出改变等。

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

也可以随意评论任何功能或其他任何功能,因为它可以帮助我改进其他错误的事情。

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

PS:这不是一件好事。

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);
    }
}

5 个答案:

答案 0 :(得分:7)

通常当您看到复杂的条件逻辑(大量if / else块和嵌套条件)时,您应该考虑将代码重构为StateStrategy设计模式(取决于具体情况)。看看那些想法。

更新:
如果您在如何重构代码时遇到问题,我最近阅读的一本很棒的书有助于打破这一过程(包括从添加版本控制到单元测试再到持续集成的所有内容......还讨论了破坏事物迭代地向下,直到你能够应用依赖注入等事情。)。它没有完全涵盖任何主题,因为有完整的书籍专门针对每个主题,但它是一个很好的起点:
Brownfield Application Development in .Net

答案 1 :(得分:3)

组织此代码的一种好方法是使用“Chain of responsibility”设计模式。

这个想法是为每个知道该做什么的“命令”设置一个类,例如:

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);
    }
}

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

答案 2 :(得分:1)

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

而不是:

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提到州,战略,但工厂,模板方法,其中大多数也会根据您的需要做。

答案 3 :(得分:1)

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

答案 4 :(得分:0)

嗯,首先,我认为你应该把这个巨大的代码分成几个方法。要分隔您评论过的逻辑部分。对于评论的每个部分,您应该有一个方法(这是最小的)。试着开始这个:

  1. 方法://这里有一些分析数据        // if(parsedData匹配)执行以下操作 尝试制作一种方法。

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

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

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

  5. 依旧......

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