如何重新设计我的代码? [英] How to redesign my code?

查看:71
本文介绍了如何重新设计我的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题

如何重新设计我的代码?



我改变了对程序结构的看法。

我想做它已经做的事情,但是用不同的方式。

现在正在做什么:当[我从列表中选择一个用户]时,它会去看看对于我点击列表中的每个用户,在线页面并对其进行解密并解决指令。

我想要的是单个时间按钮单击,它将解决现有任务,但适用于列表中的所有用户。解决所有问题后,将所有(图像,生物等)保存到我的硬盘中,然后从那里加载。



所以,这是我的结构变化。我希望我足够清楚。



在查看代码之前,我必须指明的不是代码本身。它的工作完美。此外,我可以自己添加代码结构更改时需要的任何内容。

但它关于事物的顺序。我真的希望足够明确。

我知道如何通过剪切和粘贴重新组织。这不是什么大问题。

我最后会在BIG方法中添加[所有],最明显的一个是button1_Click一个。

我很认真,这将是一个大规模的方法。我不介意,我以前做过并且工作得很好。

我向你提出的问题想法关于重组(可能更具结构性,或者更符合逻辑),而不是我自己已经习惯做的事情。办法。也许你知道我在组织和规划结构代码思维方面错过了一些东西,我想要的东西实际上对我有帮助,而不是让我困惑。

感谢您的理解。



这里是代码(部分),但实际上并不太相关(无论如何我都把它)。

为了好玩它的价值。

I have an aqward question
How to redesign my code?

I change my mind about the structure of the program.
I want to do what its doing already, but in a different way.
What is doing right now: When [I select a user from list], its going and read the Online page and decrypt it and solving the directives, for every user i click in list.
What I want is a single time button click that will resolve the existing tasks but for ALL users in list. After resolving everything, save ALL (images,bio,etc) to my hard drive, and then load it from there.

So, this is my structure change. I hope I was clear enough.

Before looking at the code, I must specify is not about the code itself. Its working perfectly. Also, I can add by myself anything is needed when the structure of the code is changed.
But its about the order of things. I really hope to be explicit enough.
I know how to reorganize with "cut and paste". Its not such a big deal.
I will in the end, add [everything] in a BIG Method, and the most obvious one will be the button1_Click one.
I am conscientious that will be a MASSIVE method. I dont mind, I did it before and worked perfectly.
What I ask from you, are ideas about reorganizing (more structural perhaps, or logical) than I am already used to do it by myself, which is working great by the way. Maybe you know something that i missed in organizing and planning my structural code thinking, I want something that will actually help me, not confuse me.
Thanks for your understanding.

And here is the code(a part), but is not actually too relevant(I put it anyway).
For the fun of it.

//Decrypt button
private void button1_Click(object sender, EventArgs e)
{
    streamx = ""; file = ""; listBox1.Items.Clear();
    //read ALL "htm" files
    DirectoryInfo di = new DirectoryInfo(Application.StartupPath);
    foreach (var item in di.GetFiles())
    {
        if (item.Extension == ".htm")
        {
            StreamReader sr = new StreamReader(item.FullName);
            file += sr.ReadToEnd();
            sr.Close();
        }
    }
    //extract usernames into listbox
    string cod = "username=\".*?\"";
    Regex rx = new Regex(cod);
    foreach (var item in rx.Matches(file)) listBox1.Items.Add(item.ToString().Replace("username=", "").Replace("\"", ""));
    label1.Text = listBox1.Items.Count.ToString();
    listBox1.SelectedIndex = 0;

    //-----------------------------------
    //Save Files
    //save usernames from your listbox, into the [0.txt]
    StreamWriter sw = new StreamWriter("Artists\\0.txt");
    foreach (var item in listBox1.Items) sw.Write(item + "\r\n");
    sw.Close();


    //Save Images and userBio
    //-----------------------------------
}


List<string> URLs;
string urlx = "", text3564 = "", codRX = "", extrpage = ""; int i7 = 0, i8972 = 0, pagesDeviants = 1;
bool nextpag = false;
public void userBio()
{
    streamx = ""; urlx = "";
    //-http://adamhughes.deviantart.com/
    urlx = "http://" + listBox1.SelectedItem.ToString().ToLower() + ".deviantart.com";
    linkLabel1.Text = urlx;

    //-------------------------------------------------------------
    //Special wepage Reading (extract info from page)
    HttpWebRequest request;
    HttpWebResponse response = null;
    Stream stream = null;
    request = (HttpWebRequest)WebRequest.Create(urlx);
    request.UserAgent = "Foo";
    request.Accept = "*/*";
    response = (HttpWebResponse)request.GetResponse();
    stream = response.GetResponseStream();


    //Request.Cookies  ?
    //Response.Cookies ?



    StreamReader sr = new StreamReader(stream, System.Text.Encoding.Default);
    streamx = sr.ReadToEnd();
    if (stream != null) stream.Close();
    if (response != null) response.Close();
    //-------------------------------------------------------------

    //C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Web.dll
    //search information:
    //extract usernames into listbox
    RichTextBox1.Text = listBox1.SelectedItem.ToString() + "  ";
    // <div id="aboutme-personal-info">Poland</div>

    text3564 = streamx;
    if (text3564.Contains("aboutme-personal-info"))
    {
        string cod01 = "aboutme-personal-info\">.*\n.*";
        text3564 = Regex.Match(streamx, cod01).ToString().Replace("aboutme-personal-info\">", "").TrimStart().Replace("</div>", "").TrimEnd();
        RichTextBox1.Text += "[" + text3564 + "]\r\n";
    }

    if (text3564.Contains("aboutme-realname"))
    {
        string cod02 = "aboutme-realname\">.*\n.*";
        text3564 = Regex.Match(streamx, cod02).ToString().Replace("aboutme-realname\">", "").TrimStart().Replace("</div>", "").TrimEnd();
        RichTextBox1.Text += "Real Name= [" + text3564 + "]\r\n";
    }


    //"aboutme-bio";
    text3564 = streamx;
    if (text3564.Contains("START BIO"))
    {
        i7 = text3564.IndexOf("START BIO"); text3564 = text3564.Remove(0, i7);
        if (text3564.Contains("END BIO"))
        {
            i7 = text3564.IndexOf("END BIO"); text3564 = "<" + text3564.Remove(i7, text3564.Length - i7) + ">";
        }

        text3564 = text3564.Replace("<br />", "\r\n").Replace(""", "\"");

        string cod03 = "<.*?>";
        text3564 = Regex.Replace(text3564, cod03, "");
        text3564 = text3564.TrimStart().TrimEnd();


        RichTextBox1.Text += "\r\n Bio= [ " + text3564 + "\r\n]\r\n";
    }

    //avatar Image
    text3564 = streamx;
    if (text3564.Contains("<img class=\"avatar float-left\" src=\""))
    {
        i7 = text3564.IndexOf("<img class=\"avatar float-left\" src=\""); text3564 = text3564.Remove(0, i7);
        string cod05 = "src=\".*?\"";
        text3564 = Regex.Match(text3564, cod05).ToString().Replace("src=", "").Replace("\"", "");
        pictureBox2.ImageLocation = text3564;
    }

    //aboutme-profile-pic
    text3564 = streamx;
    if (text3564.Contains("id=\"aboutme-profile-pic"))
    {
        i7 = text3564.IndexOf("id=\"aboutme-profile-pic"); text3564 = text3564.Remove(0, i7);
        if (text3564.Contains("<div id=\"aboutme-info\">"))
        {
            i7 = text3564.IndexOf("<div id=\"aboutme-info\">"); text3564 = text3564.Remove(i7, text3564.Length - i7);
        }
        string cod04 = "src=\".*?\"";
        text3564 = Regex.Match(text3564, cod04).ToString().Replace("src=", "").Replace("\"", "");
        //textBox1.Text = text3564;
        pictureBox1.ImageLocation = text3564;
    }
    else
    {
        pictureBox1.Image = null;
    }

}
public void userGallery()
{
    pagesDeviants = 1;
    streamx = ""; urlx = "";
    //First Page !!!
    urlx = "http://" + listBox1.SelectedItem.ToString().ToLower() + ".deviantart.com/gallery/";
    linkLabel1.Text = urlx;
    URLs = new List<string>();


start:
    //-------------------------------------------------------------
    //Special wepage Reading (extract info from page)
    HttpWebRequest request;
    HttpWebResponse response = null;
    Stream stream = null;
    request = (HttpWebRequest)WebRequest.Create(urlx);
    request.UserAgent = "Foo";
    request.Accept = "*/*";
    response = (HttpWebResponse)request.GetResponse();
    stream = response.GetResponseStream();

    StreamReader sr = new StreamReader(stream, System.Text.Encoding.Default);
    streamx = sr.ReadToEnd();
    extrpage = streamx;//Next page? >>>



    if (stream != null) stream.Close();
    if (response != null) response.Close();
    //-------------------------------------------------------------



    //-------------------------------------------------------------
    //Extract ALL images from current Page
    //First
    //cut the page at segment: [folderview-art] (to start from correct position)
    text3564 = streamx; codRX = urlx = ""; i7 = 0;
    i7 = text3564.IndexOf("<div class=\"folderview-art\">"); text3564 = text3564.Remove(0, i7);
    //Second
    //Sample Pics x6
    string st0 = "data-super-img=";
    if (text3564.Contains(st0))
    {
        while (text3564.Contains(st0))
        {
            i7 = text3564.IndexOf(st0); text3564 = text3564.Remove(0, i7);
            codRX = st0 + ".*?(\" )";
            urlx = Regex.Match(text3564, codRX).ToString().Replace(st0, "").Replace("\"", "");
            i7 = text3564.IndexOf(urlx); text3564 = text3564.Remove(0, i7 + urlx.Length);
            URLs.Add(urlx);
        }
    }
    //-------------------------------------------------------------


    //-------------------------------------------------------------
    //Next page?
    if (extrpage.Contains("<li class=\"next\">"))
    {
        //no pages left
        if (extrpage.Contains("class=\"next\"><a class=\"disabled\">")) goto end;

        i8972 = extrpage.IndexOf("<li class=\"next\">");
        extrpage = extrpage.Remove(0, i8972);
        //extracting Next page link
        i8972 = extrpage.IndexOf("offset=\"");
        extrpage = extrpage.Remove(0, i8972 + "offset=\"".Length);
        i8972 = extrpage.IndexOf("\"");
        extrpage = extrpage.Remove(i8972, extrpage.Length - i8972);

        urlx = "http://" + listBox1.SelectedItem.ToString().ToLower() + ".deviantart.com/gallery/?offset=" + extrpage;
        pagesDeviants++;
        goto start;
    }
//-------------------------------------------------------------
end: ;
}

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    label2.Text = "Loading"; listBox1.Update();
    this.Refresh();
    userBio();
    userGallery();
    AutoArrange();
    label2.Text = "Done";
}

推荐答案

我将集中讨论一般事情,而不是你的代码实际做了什么,因为你要求改进结构化代码。



- 不要构建大量的方法。是的,他们可以工作,但他们是一个维持的噩梦。他们没有任何好处。将您的代码拆分为小方法,每个方法都有一个明确定义的目的,使其更容易理解,维护和重复使用。



- 不要使用标签和goto语句。遗憾的是,这些甚至是C#语法的一部分。以某种方式编写代码,以便它可以不用;把它分解成更小的方法对那里有很大帮助。如果您有兴趣成为一名专业程序员:如果您的老板在您的代码中看到goto语句,您将无法在试用期内存活。这与结构化编程完全相反。 http://en.wikipedia.org/wiki/Considered_harmful [ ^ ]



- 不要将常量重复为文字(例如START BIO,END BIO等。在中心位置为它们定义标识符,并在需要的地方使用标识符。如果你需要改变一些东西,你只需要在一个地方改变它。



- 在一个使用块中使用实现IDisposable的每个对象(例如StreamReader ,StreamWriter,HttpWebRequest,HttpWebResponse)。不这样做有可能导致各种奇怪的问题。使用块也有助于可视化地构建代码。有关解释,请查看以下一篇或多篇文章:

https://www.google.com/search?q=idisposable+codeproject&ie=utf-8&oe=utf-8 [ ^ ]



- 如果您对结构化编程非常认真,请不要将您的业务代码放入表单(即按钮点击的事件处理程序等)。而是选择一种设计模式,将UI与业务代码分离。对于Windows Forms,您可能需要选择MVC或MVP。

https://www.google.com/search?q=windows+forms+mvp+mvc&ie=utf-8&oe=utf-8 [<一个href =https://www.google.com/search?q=windows+forms+mvp+mvc&ie=utf-8&oe=utf-8target =_ blanktitle =新窗口> ^ ]



编辑:是的,就像CHill60已经评论过的那样,为你的标识符使用有意义的名称(控件和其他变量)。如果你想在一个月或更长时间内没有看到它之后改变你的程序,你将不记得textBox5应该是什么。
I'll concentrate here on general things, not on what your code actually does, as you're asking for improvements to structurizing code.

- Do not build massive methods. Yes they can work but they're a nightmare to maintain. They have no benefits. Splitting your code into small methods that each serve a single, well defined purpose, makes it much easier to understand, maintain and re-use.

- Do not use labels and goto-statements. It's a shame that these are even part of the C# grammar. Write your code in a way so that it can do without; breaking it up into smaller methods helps a lot there. If you should be interested in becoming a professional programmer: You won't survive the trial period if your boss sees a goto statement in your code. It's the exact opposite of structured programming. http://en.wikipedia.org/wiki/Considered_harmful[^]

- Don't repeat constants as literals (e.g. "START BIO", "END BIO" etc). Define identifiers for them in a central location and use the identifiers wherever needed. If you need to change something, you'll only need to change it in one place.

- Use every object that implements IDisposable in a using-Block (e.g. StreamReader, StreamWriter, HttpWebRequest, HttpWebResponse). Not doing this has the potential to lead to all sorts of strange problems. Using-Blocks also help to visually structure your code. For an explanation, look at one or more of these articles:
https://www.google.com/search?q=idisposable+codeproject&ie=utf-8&oe=utf-8[^]

- If you're serious about structured programming, don't put your business code into the Form (that is, into event-handlers for button-clicks and so on). Instead, choose one of the design patterns for separating the UI from your business code. For Windows Forms you might want to choose MVC or MVP.
https://www.google.com/search?q=windows+forms+mvp+mvc&ie=utf-8&oe=utf-8[^]

edit: And yes, like CHill60 already commented, use meaningful names for your indentifiers (Controls and other variables). If you want to change something about your program after you haven't looked at it for a month or more, you won't remember what textBox5 is supposed to be.


这篇关于如何重新设计我的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆