问:
How you return to a code when you don't remember what you were doing?
Well, I have some problems with procrastination and whatnot, but those get infinitely worse, when I cannot remember what I should be doing.

I mean, I know my project, I wrote 100% of the code so far, and I knew more or less what I was doing, but I don't remember exactly what, I don't remember what file I was editing and why.

How I get back on track? (because right now my technique of opening the source code and staring at it is not working)

答:
I situations like these I find it helpful to take a look at the use cases and try to map them to the source-code. In other words, pretend you are one of your most important users and think what they would do when using your system. Think about the most important task they would be trying to accomplish with your software, and what steps they would take to accomplish their work. Then, think about how that would be implemented and what parts of the source-code would perform each function. Then you will start to get familiarized again with the code base.

Take your time. Don't try to know everything at once. Once you learn how a single function works, it will help you learn the next and so forth.

Best of luck.


问:
How to read thousands lines of code without any documentation?
Previously I was searching for a good TimeLine control for a WPF project. I found an answer in Here which direct me to this CodePlex project.

Now I want to change code to feed my culture needs. But there are some mismatches!

My question is:

How you interact with such thousands lines of code?

EDIT:

Any shortcut will be great!

答:
SE-Radio interviewed Dave Thomas about this very subject

This podcast episode has many tips and techniques to enter the 'culture' of the project and understand how the original inhabitants lived.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 2.5


问:
Make methods that do not depend on instance fields, static?
Recently I started programming in Groovy for a integration testing framework, for a Java project. I use Intellij IDEA with Groovy plug-in and I am surprised to see as a warning for all the methods that are non-static and do not depend on any instance fields. In Java, however, this is not an issue (at least from IDE's point of view).

Should all methods that do not depend onto any instance fields be transformed into static functions? If true, is this specific to Groovy or it is available for OOP in general? And why?

答:
It's hard to imagine that this would make any discernible effect on performance.  The only benefit that I can see to making them static is that it provides a visual indication that instance state is unaffected.  In other words, it tells the person reading the source code something... "interesting" about that method, just by virtue of it being there.  The real question is, does it clarify or confuse?  "Why is this method static?  Is it a factory method? Is the ability to call it without an object instance needed?"

In addition, some folks don't like static methods, because they claim that you cannot mock them, and therefore they are not testable, or something along those lines.   Certainly, if you are making it static for any of the usual reasons, like providing a factory method for example, then I'm all for that.  I'm just not quite sure that making methods static just because they don't touch instance state is a mandate.


答:
I assume you are not using an issue tracker for your project. Else it would be trivial to trace your previous steps.

Finding the latest changes

Finding the file you were working on before procrastinating should not be much of a problem. If you are using a source code management (SCM) tool like Git, reading the history should help. If you aren't using any SCM or version control system (VCS), you can still sort your files by modification date (here's how to do this in a UNIX shell).

Remembering your intentions

The difficult part is to remember why you were doing something. If the code is so hard to read that its intent is unclear, I perform static code analysis. I do this the same way I would do it to understand code that was written by someone else. While trying to follow the program flow, I draw UML diagrams (mostly class and activity diagrams, in really bad cases also sequence diagrams). This does not only help with getting to understand the code but also serves as a future documentation.

Avoiding the problem in the future

First of all, if your main problem is that you cannot remember you previous intents because the code is so difficult to comprehend, this is the time for refactoring. It will save you a lot of trouble in the future. If, however, the problem is that you have multiple unfinished code structures and you cannot remember what to finish first, you might want to try one or more of the following:

SCM: If you're not using SCM/VCS, start doing it. In case of tracking your previous steps, SCM helps you if you keep a clean history (remember the principle: "commit early, commit often"). It also prevents you from irrevocably deleting files (e.g., with UNIX' rm).

Issue tracker: If all this still does not help you avoiding your problems, start using an issue tracker. There are countless free and light-weight tools available to help you keep track of your changes.

Unit testing: Another method that can help you to quickly find the place to continue your work is to create unit tests. There are frameworks for all the widely used languages (e.g., Java, C, Objective-C, ...) and some languages even have a such a framework in their standard libraries (e.g., Python). If you think that unit testing might help you, also take a look at test driven development (TDD). For many developers it seems really weird not to start programming right away but to write tests for something that isn't there. However, it can lead to a whole new perspective of software development.

If all of these suggestions seem to be too much of an overhead, you could just write TODO comments in your code. This is not the cleanest and safest solution but the easiest and fastest.

Title: How you return to a code when you don't remember what you were doing?

Body:
Well, I have some problems with procrastination and whatnot, but those get infinitely worse, when I cannot remember what I should be doing.

I mean, I know my project, I wrote 100% of the code so far, and I knew more or less what I was doing, but I don't remember exactly what, I don't remember what file I was editing and why.

How I get back on track? (because right now my technique of opening the source code and staring at it is not working)


问:
Getting the relational table data into XML recursively
I have levels of tables (Level1, Level2, Level3, ...) For simplicity, we'll say I have 3 levels.

The rows in the higher level tables are parents of lower level table rows. The relationship does not skip levels however. E.g. Row1Level1 is parent of Row3Level2, Row2Level2 is parent of Row4Level3. Level(n-1)'s parent is always be in Level(n).

Given these tables with data, I need to come up with a recursive function that generates an XML file to represent the relationship and the data. E.g.

<data>
  <level levelid = 1 rowid=1>
    <level levelid = 2 rowid=3 />
  </level>
  <level levelid = 2 rowid=2>
    <level levelid = 3 rowid=4 />
  </level>
</data>
```

<p>I would like help with coming up with a pseudo-code for this setup. This is what I have so far:  </p>

<p>Edited/Updated code:</p>

```XElement GetXML(ArrayList list, XElement xml)
        {
            XElement xElement = xml;
            // Get the rows of the current list into xmlData format
            ArrayList childList = GetChildList(list);

            if (childList != null)
            {
                foreach (Row r in list)
                {
                    // Convert the rows to xml
                    xElement = new XElement(xml);
                    xElement.AddFirst(new XElement("Row"));
                    xElement.Add(new XAttribute("RowId", r.RowId));

                    // Get the children as xml
                    if (childList != null)
                    {
                        ArrayList childRows = GetChildRows(list);
                        XElement childXml = GetXML(childRows, xElement);
                        if (childXml != null)
                        {
                            xElement.Add(childXml);
                        }
                    }
                }
            }
            return xElement;
       }
```

<p>This is the main function. I can add the rest of the test program if needed. Thank you.</p>

```static void Main(string[] args)
        {
            Program p = new Program();

            // Initialize datasets
            p.InitializeLists();

            // Create xml map of the datasets
            XElement x = p.GetXML(p.level1, new XElement("Row"));

            Console.WriteLine(x.ToString());
            Console.ReadLine();
        }
```

答:
Here is the whole solution. This worked. Thanks for looking :)</p>

```<code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Xml.Linq;

namespace RecursiveExcursion
{
    class Program
    {
        ArrayList level1 = new ArrayList();
        ArrayList level2 = new ArrayList();
        ArrayList level3 = new ArrayList();

        static void Main(string[] args)
        {
            Program p = new Program();

            // Initialize datasets
            p.InitializeLists();

            // Create xml map of the datasets
            XElement x = p.GetXML(p.level1, new XElement("Rows"));

            Console.WriteLine(x.ToString());
            Console.ReadLine();
        }

        void InitializeLists()
        {
            // Add rows to the first list
            level1.Add(new Row(1, 1, 0));
            level1.Add(new Row(1, 2, 0));
            level1.Add(new Row(1, 3, 0));

            // Add rows to the second list
            level2.Add(new Row(2, 1, 1));
            level2.Add(new Row(2, 2, 2));
            level2.Add(new Row(2, 3, 2));
            level2.Add(new Row(2, 4, 3));
            level2.Add(new Row(2, 5, 1));
            level2.Add(new Row(2, 6, 1));

            // Add rows to the third list
            level3.Add(new Row(3, 1, 3));
            level3.Add(new Row(3, 2, 3));
            level3.Add(new Row(3, 3, 4));
            level3.Add(new Row(3, 4, 6));
            level3.Add(new Row(3, 5, 6));
            level3.Add(new Row(3, 6, 6));
        }

        XElement GetXML(ArrayList list, XElement xml)
        {
            XElement xElement = xml;

            // Get the rows of the current list into xmlData format
            ArrayList childList = GetChildList(list);

            if (childList != null)
            {
                foreach (Row r in list)
                {
                    // Convert the rows to xml
                    XElement xElementRow = new XElement("Row");
                    xElementRow.Add(new XAttribute("RowId", r.RowId));

                    // Get the children as xml
                    ArrayList childRows = GetChildRows(list, r);
                    xElement.Add(GetXML(childRows, xElementRow));
                }
            }
            else
            {
                foreach (Row r in list)
                {
                    XElement xElementRow = new XElement("Row");
                    xElementRow.Add(new XAttribute("RowId", r.RowId));
                    xElement.Add(xElementRow);
                }
            }
            return xElement;
        }

        private ArrayList GetChildRows(ArrayList list, Row r)
        {
            ArrayList childList = GetChildList(list);
            ArrayList childRows = new ArrayList();

            if (childList != null)
            {
                foreach (Row childRow in childList)
                {
                    if (childRow.ParentRowId == r.RowId)
                    {
                        childRows.Add(childRow);
                    }
                }
                return childRows;
            }
            else
            {
                return null;
            }
        }

        private ArrayList GetChildList(ArrayList list)
        {
            if (list.Count > 0)
            {
                int listName = 0;

                Row firstRow = (Row)list[0];
                listName = firstRow.ListId;

                switch (listName)
                {
                    case 1:
                        {
                            return this.level2;
                        }
                    case 2:
                        {
                            return this.level3;
                        }
                    case 3:

                    default:
                        {
                            return null;
                        }
                }

            }
            return null;

        }

        bool IsLastLevel(int listId)
        {
            return listId == 3;
        }
    }

    class Row
    {
        public int ListId { get; set; }
        public int RowId { get; set; }
        public int ParentRowId { get; set; }

        public Row()
        {
        }

        public Row(int listId, int rowId, int parentRowId)
        {
            ListId = listId;
            RowId = rowId;
            ParentRowId = parentRowId;
        }
    }
}
</code>```

Body:
Here is the whole solution. This worked. Thanks for looking :)

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Xml.Linq;

namespace RecursiveExcursion
{
    class Program
    {
        ArrayList level1 = new ArrayList();
        ArrayList level2 = new ArrayList();
        ArrayList level3 = new ArrayList();

        static void Main(string[] args)
        {
            Program p = new Program();

            // Initialize datasets
            p.InitializeLists();

            // Create xml map of the datasets
            XElement x = p.GetXML(p.level1, new XElement("Rows"));

            Console.WriteLine(x.ToString());
            Console.ReadLine();
        }

        void InitializeLists()
        {
            // Add rows to the first list
            level1.Add(new Row(1, 1, 0));
            level1.Add(new Row(1, 2, 0));
            level1.Add(new Row(1, 3, 0));

            // Add rows to the second list
            level2.Add(new Row(2, 1, 1));
            level2.Add(new Row(2, 2, 2));
            level2.Add(new Row(2, 3, 2));
            level2.Add(new Row(2, 4, 3));
            level2.Add(new Row(2, 5, 1));
            level2.Add(new Row(2, 6, 1));

            // Add rows to the third list
            level3.Add(new Row(3, 1, 3));
            level3.Add(new Row(3, 2, 3));
            level3.Add(new Row(3, 3, 4));
            level3.Add(new Row(3, 4, 6));
            level3.Add(new Row(3, 5, 6));
            level3.Add(new Row(3, 6, 6));
        }

        XElement GetXML(ArrayList list, XElement xml)
        {
            XElement xElement = xml;

            // Get the rows of the current list into xmlData format
            ArrayList childList = GetChildList(list);

            if (childList != null)
            {
                foreach (Row r in list)
                {
                    // Convert the rows to xml
                    XElement xElementRow = new XElement("Row");
                    xElementRow.Add(new XAttribute("RowId", r.RowId));

                    // Get the children as xml
                    ArrayList childRows = GetChildRows(list, r);
                    xElement.Add(GetXML(childRows, xElementRow));
                }
            }
            else
            {
                foreach (Row r in list)
                {
                    XElement xElementRow = new XElement("Row");
                    xElementRow.Add(new XAttribute("RowId", r.RowId));
                    xElement.Add(xElementRow);
                }
            }
            return xElement;
        }

        private ArrayList GetChildRows(ArrayList list, Row r)
        {
            ArrayList childList = GetChildList(list);
            ArrayList childRows = new ArrayList();

            if (childList != null)
            {
                foreach (Row childRow in childList)
                {
                    if (childRow.ParentRowId == r.RowId)
                    {
                        childRows.Add(childRow);
                    }
                }
                return childRows;
            }
            else
            {
                return null;
            }
        }

        private ArrayList GetChildList(ArrayList list)
        {
            if (list.Count > 0)
            {
                int listName = 0;

                Row firstRow = (Row)list[0];
                listName = firstRow.ListId;

                switch (listName)
                {
                    case 1:
                        {
                            return this.level2;
                        }
                    case 2:
                        {
                            return this.level3;
                        }
                    case 3:

                    default:
                        {
                            return null;
                        }
                }

            }
            return null;

        }

        bool IsLastLevel(int listId)
        {
            return listId == 3;
        }
    }

    class Row
    {
        public int ListId { get; set; }
        public int RowId { get; set; }
        public int ParentRowId { get; set; }

        public Row()
        {
        }

        public Row(int listId, int rowId, int parentRowId)
        {
            ListId = listId;
            RowId = rowId;
            ParentRowId = parentRowId;
        }
    }
}


问:
How do you cope with ugly code that you wrote?
So your client asks you to write some code, so you do. He then changes the specs on you, as expected, and you diligently implement his new features like a good little lad. Except... the new features kind of conflict with the old features, so now your code is a mess. You really want to go back and fix it, but he keeps requesting new things and every time you finish cleaning something, it winds up a mess again.

What do you do? Stop being an OCD maniac and just accept that your code is going to wind up a mess no matter what you do, and just keep tacking on features to this monstrosity? Save the cleaning for version 2?

答:
Deliberately overestimate the time needed for your next features. Use that extra time to clean up.

You'll never be able to justify maintenance, and the client needs it regardless, so give them the bitter medicine (slightly increased costs for the next features) so they can get better.


问:
Can I rightfully claim this as my own project if I recieved help online?
Basically I'm new to network programming in Python, so I went on a tutorial online to find out about it. Using what was taught in the tutorial (creating a socket, connecting to ports, etc), I modified the code so that I made a program where two computers can send messages to one another.

If I were to apply for a job and show this to my interviewers, would the code for it technically be mine? It is fair to say that I didn't modify the code by that much; However, what if for example I modified it into something like a tic-tac-toe game, where two users play each other from different PCs, would the code then be mine? I just don't want to look like a plagiarizer hence why I ask.

答:
I'd go with the classic line "it depends".

As you already say that you didn't modify it much, i'm fully on Roberts side. It's not your project.

But on the other side: We developers all like to discuss, research and sometimes copy-paste for our projects. Fiddeling around with other peoples code is pretty common. If you modify it a lot, put some effort in it, providing new features or a different approach on the problem, then it's your code.

Just stick to the truth about the amount of work you did truly by yourself and i'm sure no one will call you a plagiarizer.


答:
Run the tests.  If I have failing tests then that is probably what I was working on.

Diff working copy against revision control. Seeing all the edits I have made recently but not committed usually reminds me of what I was doing.

Read commit history. Start looking through version control history at what has been happening recently.  That usually points me back at the road map and the next task on the list.


答:
First and foremost, this should probably be moved to the Code Review site.

I would prefer to come at the problem from a different angle, using objects to handle the behavior rather than a recursive method which knows how to traverse everything.  Doing so seems to map your domain better, with a bonus that it eliminates the need for a ListID value stored on each row, making it scale better.

```<code>public class Row
{
   public ICollection<Row> ChildRows { get; private set; }
   public int RowId { get; private set; }
   public int ParentRowId { get; private set; }

   public Row(int rowId, int parentRowId)
   {
      RowId = rowId;
      ParentRowId = parentRowId;
      ChildRows = new List<Row> ();
   }

   public XElement BuildXML(int level)
   {
      var element = new XElement("level",
                                 new XAttribute("levelid", level),
                                 new XAttribute("rowid", RowId));
      if (ChildRows.Any())
         element.Add(ChildRows.Select(r => r.BuildXML(level + 1)));

      return element;
   }
}
</code>```

I would then build my object hierarchy as a tree structure.  To do so easily, I would initialize with two collections - one a list of the top-level items, and the other a dictionary of all items:

```<code>void InitializeLists()
{
   var allRows = new List<Row>
                 {
                    new Row(1, 0),
                    new Row(2, 0),
                    new Row(3, 0),
                    new Row(1, 1),
                    new Row(2, 2),
                    new Row(3, 2),
                    new Row(4, 3),
                    new Row(5, 1),
                    new Row(6, 1),
                    new Row(1, 3),
                    new Row(2, 3),
                    new Row(3, 4),
                    new Row(4, 6),
                    new Row(5, 6),
                    new Row(6, 6),
                 };
   var rowTable = allRows.ToDictionary(r => r.RowId);

   var rootRows = new List<Row>();
   foreach(var row in allRows)
   {
      if(row.RowId == 0)
         rootRows.Add(row);
      else
      {
         Row parentRow;

         if(rowTable.TryGetValue(row.ParentRowId, out parentRow))
         {
            parentRow.ChildRows.Add(row);
         }
         else
         {
            // throw or log an appropriate error
         }
      }
   }

   _rootRows = rootRows;
}
</code>```

With that done, your XML building becomes rather trivial:

```<code>public static void Main(string[] args)
{
   var p = new Program();

   // Initialize datasets
   p.InitializeLists();

   // Create xml map of the datasets
   XElement x = p.GetXML();

   Console.WriteLine(x.ToString());
   Console.ReadLine();
}

public XElement GetXML()
{
   var xElement = new XElement("Rows");
   foreach(var row in _rootRows)
      xElement.Add(row.BuildXML(1));

   return xElement;
}
</code>```

Update

I failed to notice on my first attempt that the row IDs were non-unique.  There are two basic options to address this:

Make the IDs unique

Make a composite key for lookup which will be unique.  The easiest option here is to re-introduce the list IDs and build a key as a combination of ID and list ID.

Since the above examples handle cases with unique row IDs, I will add some tweaks for the second option.  First, we re-introduce ListId to the Row.  This lets us remove the parameter from BuildXML:

```<code>public class Row
{
   public ICollection<Row> ChildRows { get; private set; }
   public int RowId { get; private set; }
   public int ListId { get; private set; }
   public int ParentRowId { get; private set; }

   public Row(int rowId, int listId, int parentRowId)
   {
      RowId = rowId;
      ListId = listId;
      ParentRowId = parentRowId;
      ChildRows = new List<Row> ();
   }

   public XElement BuildXML()
   {
      var element = new XElement("level",
                                 new XAttribute("levelid", ListId),
                                 new XAttribute("rowid", RowId));
      if (ChildRows.Any())
         element.Add(ChildRows.Select(r => r.BuildXML()));

      return element;
   }
}
</code>```

Then, we re-do how we initialize:

```<code>void InitializeLists()
{
   var allRows = new List<Row>
                 {
                    new Row(1, 1, 0),
                    new Row(2, 1, 0),
                    new Row(3, 1, 0),
                    new Row(1, 2, 1),
                    new Row(2, 2, 2),
                    new Row(3, 2, 2),
                    new Row(4, 2, 3),
                    new Row(5, 2, 1),
                    new Row(6, 2, 1),
                    new Row(1, 3, 3),
                    new Row(2, 3, 3),
                    new Row(3, 3, 4),
                    new Row(4, 3, 6),
                    new Row(5, 3, 6),
                    new Row(6, 3, 6),
                 };

   const string FMT = "{0}:{1}";

   var rowTable = allRows.ToDictionary(r => string.Format(FMT, r.ListId, r.RowId));

   var rootRows = new List<Row>();
   foreach(var row in allRows)
   {
      if(row.ListId == 1)
         rootRows.Add(row);
      else
      {
         Row parentRow;

         var parentKey = string.Format(FMT, row.ListId-1, row.ParentRowId);

         if(rowTable.TryGetValue(parentKey, out parentRow))
         {
            parentRow.ChildRows.Add(row);
         }
      }
   }

   _rootRows = rootRows;
}
</code>```

Finally, we fix the GetXML function so it does not pass in a starting level:

```<code>XElement GetXML()
{
   XElement xElement = new XElement("Rows");
   foreach(var row in _rootRows)
      xElement.Add(row.BuildXML());

   return xElement;
}
</code>```

Title: Getting the relational table data into XML recursively

Body:
I have levels of tables (Level1, Level2, Level3, ...) For simplicity, we'll say I have 3 levels.

The rows in the higher level tables are parents of lower level table rows. The relationship does not skip levels however. E.g. Row1Level1 is parent of Row3Level2, Row2Level2 is parent of Row4Level3. Level(n-1)'s parent is always be in Level(n).

Given these tables with data, I need to come up with a recursive function that generates an XML file to represent the relationship and the data. E.g.

<data>
  <level levelid = 1 rowid=1>
    <level levelid = 2 rowid=3 />
  </level>
  <level levelid = 2 rowid=2>
    <level levelid = 3 rowid=4 />
  </level>
</data>
```

<p>I would like help with coming up with a pseudo-code for this setup. This is what I have so far:  </p>

<p>Edited/Updated code:</p>

```XElement GetXML(ArrayList list, XElement xml)
        {
            XElement xElement = xml;
            // Get the rows of the current list into xmlData format
            ArrayList childList = GetChildList(list);

            if (childList != null)
            {
                foreach (Row r in list)
                {
                    // Convert the rows to xml
                    xElement = new XElement(xml);
                    xElement.AddFirst(new XElement("Row"));
                    xElement.Add(new XAttribute("RowId", r.RowId));

                    // Get the children as xml
                    if (childList != null)
                    {
                        ArrayList childRows = GetChildRows(list);
                        XElement childXml = GetXML(childRows, xElement);
                        if (childXml != null)
                        {
                            xElement.Add(childXml);
                        }
                    }
                }
            }
            return xElement;
       }
```

<p>This is the main function. I can add the rest of the test program if needed. Thank you.</p>

```static void Main(string[] args)
        {
            Program p = new Program();

            // Initialize datasets
            p.InitializeLists();

            // Create xml map of the datasets
            XElement x = p.GetXML(p.level1, new XElement("Row"));

            Console.WriteLine(x.ToString());
            Console.ReadLine();
        }
```

Body:
First and foremost, this should probably be moved to the Code Review site.

I would prefer to come at the problem from a different angle, using objects to handle the behavior rather than a recursive method which knows how to traverse everything.  Doing so seems to map your domain better, with a bonus that it eliminates the need for a ListID value stored on each row, making it scale better.

public class Row
{
   public ICollection<Row> ChildRows { get; private set; }
   public int RowId { get; private set; }
   public int ParentRowId { get; private set; }

   public Row(int rowId, int parentRowId)
   {
      RowId = rowId;
      ParentRowId = parentRowId;
      ChildRows = new List<Row> ();
   }

   public XElement BuildXML(int level)
   {
      var element = new XElement("level",
                                 new XAttribute("levelid", level),
                                 new XAttribute("rowid", RowId));
      if (ChildRows.Any())
         element.Add(ChildRows.Select(r => r.BuildXML(level + 1)));

      return element;
   }
}

I would then build my object hierarchy as a tree structure.  To do so easily, I would initialize with two collections - one a list of the top-level items, and the other a dictionary of all items:

void InitializeLists()
{
   var allRows = new List<Row>
                 {
                    new Row(1, 0),
                    new Row(2, 0),
                    new Row(3, 0),
                    new Row(1, 1),
                    new Row(2, 2),
                    new Row(3, 2),
                    new Row(4, 3),
                    new Row(5, 1),
                    new Row(6, 1),
                    new Row(1, 3),
                    new Row(2, 3),
                    new Row(3, 4),
                    new Row(4, 6),
                    new Row(5, 6),
                    new Row(6, 6),
                 };
   var rowTable = allRows.ToDictionary(r => r.RowId);

   var rootRows = new List<Row>();
   foreach(var row in allRows)
   {
      if(row.RowId == 0)
         rootRows.Add(row);
      else
      {
         Row parentRow;

         if(rowTable.TryGetValue(row.ParentRowId, out parentRow))
         {
            parentRow.ChildRows.Add(row);
         }
         else
         {
            // throw or log an appropriate error
         }
      }
   }

   _rootRows = rootRows;
}

With that done, your XML building becomes rather trivial:

public static void Main(string[] args)
{
   var p = new Program();

   // Initialize datasets
   p.InitializeLists();

   // Create xml map of the datasets
   XElement x = p.GetXML();

   Console.WriteLine(x.ToString());
   Console.ReadLine();
}

public XElement GetXML()
{
   var xElement = new XElement("Rows");
   foreach(var row in _rootRows)
      xElement.Add(row.BuildXML(1));

   return xElement;
}

Update

I failed to notice on my first attempt that the row IDs were non-unique.  There are two basic options to address this:

Make the IDs unique

Make a composite key for lookup which will be unique.  The easiest option here is to re-introduce the list IDs and build a key as a combination of ID and list ID.

Since the above examples handle cases with unique row IDs, I will add some tweaks for the second option.  First, we re-introduce ListId to the Row.  This lets us remove the parameter from BuildXML:

public class Row
{
   public ICollection<Row> ChildRows { get; private set; }
   public int RowId { get; private set; }
   public int ListId { get; private set; }
   public int ParentRowId { get; private set; }

   public Row(int rowId, int listId, int parentRowId)
   {
      RowId = rowId;
      ListId = listId;
      ParentRowId = parentRowId;
      ChildRows = new List<Row> ();
   }

   public XElement BuildXML()
   {
      var element = new XElement("level",
                                 new XAttribute("levelid", ListId),
                                 new XAttribute("rowid", RowId));
      if (ChildRows.Any())
         element.Add(ChildRows.Select(r => r.BuildXML()));

      return element;
   }
}

Then, we re-do how we initialize:

void InitializeLists()
{
   var allRows = new List<Row>
                 {
                    new Row(1, 1, 0),
                    new Row(2, 1, 0),
                    new Row(3, 1, 0),
                    new Row(1, 2, 1),
                    new Row(2, 2, 2),
                    new Row(3, 2, 2),
                    new Row(4, 2, 3),
                    new Row(5, 2, 1),
                    new Row(6, 2, 1),
                    new Row(1, 3, 3),
                    new Row(2, 3, 3),
                    new Row(3, 3, 4),
                    new Row(4, 3, 6),
                    new Row(5, 3, 6),
                    new Row(6, 3, 6),
                 };

   const string FMT = "{0}:{1}";

   var rowTable = allRows.ToDictionary(r => string.Format(FMT, r.ListId, r.RowId));

   var rootRows = new List<Row>();
   foreach(var row in allRows)
   {
      if(row.ListId == 1)
         rootRows.Add(row);
      else
      {
         Row parentRow;

         var parentKey = string.Format(FMT, row.ListId-1, row.ParentRowId);

         if(rowTable.TryGetValue(parentKey, out parentRow))
         {
            parentRow.ChildRows.Add(row);
         }
      }
   }

   _rootRows = rootRows;
}

Finally, we fix the GetXML function so it does not pass in a starting level:

XElement GetXML()
{
   XElement xElement = new XElement("Rows");
   foreach(var row in _rootRows)
      xElement.Add(row.BuildXML());

   return xElement;
}


问:
Is there an established or defined best practice for source control branching between development and production builds?
I struggled in how to phrase my question, so let me give an example in hopes of making more clear what I am after:

I currently work on a dev team responsible for maintaining and adding features to a web application.  We have a development server and we use source control (TFS).  Each day everyone checks in their code and when the code (running on the dev server) passes our QA/QC program, it goes to production.

Recently, however, we had a bug in production which required an immediate production fix.  The problem was that several of us developers had code checked in that was not ready for production so we had to either quickly complete and QA the code, or roll back everything, undo pending changes, etc.  In other words, it was a mess.

This made me wonder: Is there an established design pattern that prevents this type of scenario.  It seems like there must be some "textbook" answer to this, but I am unsure what that would be.  Perhaps a development branch of the code and a "release-ready" or production branch of the code?

答:
In my organization, we always tag each production deployment in the repository. Since we use SVN, this tag can become a branch if required, by just committing changes to it. That's exactly what we do if there is a bug in production that needs an immediate fix. In that situation, we check-out a clean copy of that particular revision (the production version) to one of the developers workstation, make the fix, run all the tests and, if all is ok, we deploy the application. Then we commit the changes back to the repository turning the production tag into a branch. That commit becomes the latest production tag.

Once the emergency is solved, we merge the fix back into the mainline and kill that production branch. The production branch becomes a regular production tag again. It can only become a branch if such an emergency happens again.

I'm not sure how easy would be to the same using TFS, but the important lesson here is that you need a stable revision to deploy to production. The current production revision are stable by definition, so you just need to tag them so you can work on them when an emergency comes up. It is also important that you are able to easily set up clean working copies from any revisions in your source repository.

What's important to highlight is that you should never deploy code that isn't ready for production. In the case you described, you should work off of the version currently in production to fix only the particular issue that created the emergency, and not use whatever code is in your developer's current working copies.

Finally, to answer your question, the main software configuration pattern that I think you should follow, which is the base for the method I described above, is called Release Line, following Stephen Berczuk's great book titled Software Configuration Management Patterns.

Edit: I should also give proper credit to Marjan Venema who mentioned a similar approach in a comment that I had not read until now.


问:
Is it okay to just add a page or two PHP page to add some functionality to a Drupal site?
I'm not familiar with Drupal, really.  I can dig around the admin interface and navigate the directories and find the files that I need to just fine as well.

What I'm really not familiar with is adding modules or extending modules.  The site currently takes an order and sets up recurring payments through Ubercart and uses Authorize.net as a gateway.  Right now, when a payment fails, a single e-mail gets sent out to the admin.  We'd like to extend it to send an e-mail to the user and let them change their payment information through another page on the site.

Authorize has a service called Silent Post URL that basically just posts a carbon copy in XML to whatever URL you give it.  We'd like to accept that XML, deserialize it, parse the data, send a notice to the user and give them the page for updating their information.

So, I guess it'll be two PHP pages.  One for the XML API call from Authorize.net, and then one for the page for the users' to update their payment information.

Could I just create two simple pages each handling their own tasks, or should I check out properly extending a module?  If it's appropriate for me to write up the pages and not have to hook them into the module, what would be the best way to handle setting up what needs to get done?

(The most experience I've had with extending a PHP site has been hacking away at someone else' poorly constructed, custom framework, so if anyone has any good resources perhaps on PHP best practices that they could share through a PM or a comment, I'd appreciate It)

(Also, I'm still getting the hang of Stack Exchange, so if this isn't appropriate please let me know.  I'll delete it.)

答:
If the new page doesn't use users from Drupal site, doesn't rely on any pages in your Drupal site, doesn't use the theme of your Drupal site and doesn't otherwise have any interaction with the site, you might want to do it that way.

I still wouldn't.

Part of using any platform is learning to work within it so you can use all the parts of it to your advantage.  You're already using Drupal users and messaging which means you're using the database.  You can either figure out how to use Drupal to access them or you can go build your own page with its own database settings, it's own security, figure out how to manually tie into Drupal users and messaging and hope that you don't break anything while you're in there.


答:
I used to suffer from the same problem once. Not because my code was so messy, but simply because sometimes one is interrupted for longer than originally planned and thus simply forgets things you didn't plan to forget initially. A todo list may help, but usually it is not fine-grained enough.

I then developed the habit to leave some small notes to myself within the code, near the place where I planned to continue work. This is not checked into the VCS, it's only for me. Maybe two/three lines is completely enough to capture the latest thoughs when you leave work.

When you come back later, you simply hit "compile" and the Compiler will bring up the (uncompileable) place in the code, where you left the notes. And that's the starting point.

It may not work in all cases one can think of, but for me it does.


答:
If what you did was modify someone's code to do something you wanted then it would be dishonest to claim that you code was "yours". Rather, it is a program you created based on existing code.

Now you may have noticed that many programmers use other peoples code. All the time. Libraries and APIs are essentially a formalized way to use code that someone created in your own project. While what you did was not the same as using a library or API, it has the same effect.

In the case of the simple P2P program you can claim that you wrote a messaging application that utilizes another programmers implementation of simple web protocols. You can go ahead and call it your program, you should just give credit to whoever wrote the borrowed parts. And it would be best to add comments to the code citing the source, so other can find it if need be.

And in the case of the game, you wrote a game. You can claim this as your code. This game then utilizes a set of functions that you got from another source to enable multiplayer functionality. Again, you should probably site the source of that code at least in comments in your code. However in this situation you can probably get away with not explicitly telling this to others outside of the code, as you really did write the game.

Many developers rely on libraries to deal with some of the more complex problems they face. Things like network protocols, graphics, and advanced math are used by many people, so there are libraries that do all those things vary well. Utilizing this kind of code is not only completely acceptable, but also normal.

If you say "this is a IM client" or "this is a video game" nobody is going to be surprised if the network code is from a third party. Just don't claim that you are the sole author of all parts of the code, and you should be fine.

However you should look into another possibility: Is the code in question protected by any terms of use? To this point I have been talking about code that is made available either with no terms, or very open terms. However if the author has some more specific terms follow them. If they only intended the code o be for educational purposes, than using it in any capacity beyond that is not okay. There are all  kinds of limitations they may place on that code, so be careful about how you use it.

Title: Can I rightfully claim this as my own project if I recieved help online?

Body:
Basically I'm new to network programming in Python, so I went on a tutorial online to find out about it. Using what was taught in the tutorial (creating a socket, connecting to ports, etc), I modified the code so that I made a program where two computers can send messages to one another.

If I were to apply for a job and show this to my interviewers, would the code for it technically be mine? It is fair to say that I didn't modify the code by that much; However, what if for example I modified it into something like a tic-tac-toe game, where two users play each other from different PCs, would the code then be mine? I just don't want to look like a plagiarizer hence why I ask.


问:
Does anyone use Ceiling and *not* immediately cast it to an integer?
I think every single time I've used Math.Ceiling or its language variant, I've always had to cast it to an integer. I mean... that's the whole point, isn't it? To get a whole number. So why doesn't it just return an int?

答:
Smalltalk's does.

```<code>100000000000000000000.5 ceiling => 100000000000000000000
</code>```

100000000000000000000 is a LargePositiveInteger, meaning an integer that uses more than 32 bits in its representation.

As Michael points out, the above answer is wrong. I didn't notice that while the answer was an integer the answer was wrong because the float loses precision. So instead here's another, CORRECT, version, which works because we don't use floats:

```<code>(100000000000000000000 + (1 / 2)) ceiling => 100000000000000000001
</code>```

Body:
Smalltalk's does.

100000000000000000000.5 ceiling => 100000000000000000000

100000000000000000000 is a LargePositiveInteger, meaning an integer that uses more than 32 bits in its representation.

As Michael points out, the above answer is wrong. I didn't notice that while the answer was an integer the answer was wrong because the float loses precision. So instead here's another, CORRECT, version, which works because we don't use floats:

(100000000000000000000 + (1 / 2)) ceiling => 100000000000000000001


答:
The problem is always the maintenance. Are you willing to patch the page every time Drupal gets patched? Are you willing to re-integrate it every time something changes?

It's a better plan to find a module that does what you need, that's still under active development. Anything else, and you're making a commitment to maintenance that will last as long as the site.

Title: Is it okay to just add a page or two PHP page to add some functionality to a Drupal site?

Body:
I'm not familiar with Drupal, really.  I can dig around the admin interface and navigate the directories and find the files that I need to just fine as well.

What I'm really not familiar with is adding modules or extending modules.  The site currently takes an order and sets up recurring payments through Ubercart and uses Authorize.net as a gateway.  Right now, when a payment fails, a single e-mail gets sent out to the admin.  We'd like to extend it to send an e-mail to the user and let them change their payment information through another page on the site.

Authorize has a service called Silent Post URL that basically just posts a carbon copy in XML to whatever URL you give it.  We'd like to accept that XML, deserialize it, parse the data, send a notice to the user and give them the page for updating their information.

So, I guess it'll be two PHP pages.  One for the XML API call from Authorize.net, and then one for the page for the users' to update their payment information.

Could I just create two simple pages each handling their own tasks, or should I check out properly extending a module?  If it's appropriate for me to write up the pages and not have to hook them into the module, what would be the best way to handle setting up what needs to get done?

(The most experience I've had with extending a PHP site has been hacking away at someone else' poorly constructed, custom framework, so if anyone has any good resources perhaps on PHP best practices that they could share through a PM or a comment, I'd appreciate It)

(Also, I'm still getting the hang of Stack Exchange, so if this isn't appropriate please let me know.  I'll delete it.)


问:
How to collaborate on features using github
github encourages 1 fork per user, so that that user can work independently on a feature and then request that feature to be accepted into the main repository via pull request.

However, what if 2 developers need to collaborate on that feature? What is the ideal workflow for this? I could see a number of options:

Both developers fork the original repository. Each developer pulls/pushes changes between each other's repository. This seems like a lot of work (tiny micro operations) and also creates a delay between changes, so increases the window for conflicts.

Developer 1 forks from the main repository, developer 2 forks from developer 1. Same as #1 mainly but hopefully simplifies Developer 2's life a little?

Developer 1 gives Developer 2 permissions to his own fork, so they both work out of the same central repository. Not sure if this is ideal.

I'm also curious where branches come into this. Obviously there would be a branch for the feature itself but that branch can't exist in a single place, it would have to exist on multiple forks and be synchronized.

Basically just really confused about this workflow, would like an approach for how this can be best accomplished.

答:
Create a feature branch for the functionality that you'd like to implement.

Both developers will pull a local copy of the feature branch. They can push incremental progress to the feature branch, and conflicts will be resolved via merging, should they arise.

EDIT

The way I would approach this problem:

From the main, up to date repository, create a branch git checkout -b FeatureBranch

Both users checkout this branch git fetch and git checkout FeatureBranch

Now each user has a local copy of FeatureBranch on their machine

Each user is able to progress individually on their local branch, committing changes as they please. When enough progress is made, they can each push their changes to the remote branch git push origin FeatureBranch. Git will handle merging automatically, unless a conflict arises that cannot be automatically resolved. In this event, the pusher will have to manually resolve it.

When the feature branch is ready to be merged back into master, issue a pull request, or git merge

FYI I think you have your terminology mixed up in your post. Users should create a branch from the master branch, and upon completion of their work, they issue a pull request and the admins can decide to merge it in or not. Forking, at least in my mind, is reserved for taking a project at a certain point, and heading in a different direction with development. If a feature branch is intended to enhance the current code base, and fits the ideology and paradigm of the project, I would recommend branching.

Perhaps some more background information about your use case would be helpful.


问:
Does the method of adjustment matter, or just the final calibration?
A company produces software (and hardware) that is used to both perform automatic adjustments on electronic test equipment as well as perform calibrations of the same equipment. The results of the calibrations are put onto a certificate of calibration that is sent to the customer along with the equipment.

This calibration certificate states various conditions of the calibration, such as what hardware (models/serial numbers) and software (version) was used to perform the calibration, as well as things like environmental conditions, etc.

Making the assumption that the software used to produce the data (and listed on the calibration certificate) used on the certificate of calibration must have gone through a "test/release" process and must be considered "released" software - does this also mean that the software used for adjustment must also be released?

I believe that the method (software/environmental conditions/etc) used or present during adjustment doesn't matter, all that really matters is the end result of the calibration, the conditions present during the calibration, and whether or not the equipment was within the specifications.

The real question I'm hoping to get answered: Is there a reputable source (e.g. NIST or somewhere similar) that addresses this question? (I have searched...)

The thinking is that during high volume production runs, the "unreleased" system can be used to perform adjustments, as long as a released system is used to perform the calibrations, since the time required to perform the adjustments is much longer than the calibration. This unreleased system will eventually become released for use, but currently is not.

Also, please not that there is a distinction between "adjustment" and "calibration". The definition from BIPM International vocabulary of metrology, 2.39:

Operation that, under specified conditions, in a first step,
  establishes a relation between the quantity values with measurement
  uncertainties provided by measurement standards and corresponding
  indications with associated measurement uncertainties (of the
  calibrated instrument or secondary standard) and, in a second step,
  uses this information to establish a relation for obtaining a
  measurement result from an indication.

Followed by NOTE 2 (emphasis in original text):

Calibration should not be confused with adjustment of a measuring
  system, often mistakenly called "self-calibration", nor with
  verification of calibration

As a side note, I'm not sure why this got down voted. It's regarding software and it's use before and after release for use. I believe there is a best practice that can be applied and this is (hopefully) not primarily opinion based.

答:
It sounds like you are leaning solely on the results of equipment calibrations to serve as Verification and Validation for a piece of unreleased software.

If the only requirement in the software design specification for the unreleased software is that it must be capable of making adjustments to a piece of equipment under calibration, then that may be a valid approach.  But seldom does software have only a single such requirement.  If there are other software requirements, then I would say that this approach is not valid.

It is these kinds of rationalizations that eventually lead to problems like the Ariane 5 explosion, or the Therac-25 accidents, or sudden acceleration in Toyota vehicles.


答:
Note that IDEA has this inspection for Java as well, it is called Method may be 'static',

This inspection reports any methods which may safely be made static. A method may be static if it doesn't reference any of its class' non static methods and non static fields and isn't overridden in a sub class...

Thing is though that for Java code, this inspection is turned off by default (programmer can turn it on at their discretion). The reason for this is most likely that validity / usefulness of such an inspection could be challenged, based on a couple of quite authoritative sources.

To start with, official Java tutorial is rather restrictive on when methods should be static:

A common use for static methods is to access static fields.

Given above, one could argue that turning on by default mentioned inspection doesn't comply with recommended use of static modifier in Java.

Besides, there is a couple other sources that go as far as suggesting a judicious approach on using ideas that lie behind this inspection or even discouraging it.

See for example Java World article - Mr. Happy Object teaches static methods:

Any method that is independent of instance state is a candidate for being declared as static.

Note that I say "candidate for being declared as static." Even in the previous example nothing forces you to declare instances() as static. Declaring it as static just makes it more convenient to call since you do not need an instance to call the method. Sometimes you will have methods that don't seem to rely on instance state. You might not want to make these methods static. In fact you'll probably only want to declare them as static if you need to access them without an instance.

Moreover, even though you can declare such a method as static, you might not want to because of the inheritance issues that it interjects into your design. Take a look at "Effective Object-Oriented Design" to see some of the issues that you will face...

An article at Google testing blog even goes as far as claiming Static Methods are Death to Testability:

Lets do a mental exercise. Suppose your application has nothing but static methods. (Yes, code like that is possible to write, it is called procedural programming.) Now imagine the call graph of that application. If you try to execute a leaf method, you will have no issue setting up its state, and asserting all of the corner cases. The reason is that a leaf method makes no further calls. As you move further away from the leaves and closer to the root main() method it will be harder and harder to set up the state in your test and harder to assert things. Many things will become impossible to assert. Your tests will get progressively larger. Once you reach the main() method you no longer have a unit-test (as your unit is the whole application) you now have a scenario test. Imagine that the application you are trying to test is a word processor. There is not much you can assert from the main method...

Sometimes a static methods is a factory for other objects. This further exuberates the testing problem. In tests we rely on the fact that we can wire objects differently replacing important dependencies with mocks. Once a new operator is called we can not override the method with a sub-class. A caller of such a static factory is permanently bound to the concrete classes which the static factory method produced. In other words the damage of the static method is far beyond the static method itself. Butting object graph wiring and construction code into static method is extra bad, since object graph wiring is how we isolate things for testing...

You see, given above it looks only natural that mentioned inspection is turned off by default for Java.

IDE developers would have a really hard time explaining why they think it is so important as to set it on by default, against widely recognized recommendations and best practices.

For Groovy, things are quite different. None of arguments listed above apply, particularly the one about testability, as explained eg in Mocking Static Methods in Groovy article at Javalobby:

If the Groovy class you're testing makes calls a static method on another Groovy class, then you could use the ExpandoMetaClass which allows you to dynamically add methods, constructors, properties and static methods...

This difference is likely why default setting for mentioned inspection is opposite in Groovy. While in Java default "on" would be source of users confusion, in Groovy, an opposite setting could confuse IDE users.

"Hey the method doesn't use instance fields, why didn't you warn me about it?" That question would be easy to answer for Java (as explained above), but for Groovy, there is just no compelling explanation.

Title: Make methods that do not depend on instance fields, static?

Body:
Recently I started programming in Groovy for a integration testing framework, for a Java project. I use Intellij IDEA with Groovy plug-in and I am surprised to see as a warning for all the methods that are non-static and do not depend on any instance fields. In Java, however, this is not an issue (at least from IDE's point of view).

Should all methods that do not depend onto any instance fields be transformed into static functions? If true, is this specific to Groovy or it is available for OOP in general? And why?


答:
Adjustment is the process of re calibration. Calibration is the state of the systems accuracy and errors. From a regulatory framework, it is rare to worry how the adjustment was done, and common to worry about the calibration. Hence the need for calibration certificates. (It is common to worry that adjustment cannot be done after calibration, I will ignore that for now....)

A simple example might be the calibration of a fuel pump at your local service station. You care that is is calibrated correctly, as does the law. Typically its done by filling  test bucket, but maybe its done putting a flow meter on the pump nozzle while filling a car. In both cases, the test equipment must also be calibrated (usually to a higher standard).  However, if the pump is reading wrong and needs adjustment, it does not matter if this is done by a setting in software, turning a trim pot or replacing a sensor.

In a production environment it is not normally required (within a regulatory framework) that the adjustment process be rigorous, i.e. you can use whatever means you want in production to adjust, including unreleased automated software, provided the system is calibrated to the regulatory/commercial requirements. However, in my experience, the commercial risk and cost of unreleased software in high volume production lines means it just does not happen, as therefore the two tasks are often performed by the same system.

Note: Some frameworks with strict control (life critical systems etc) will have regulatory oversight of adjustment and calibration. In this case the answer does not stand.

Title: Does the method of adjustment matter, or just the final calibration?

Body:
A company produces software (and hardware) that is used to both perform automatic adjustments on electronic test equipment as well as perform calibrations of the same equipment. The results of the calibrations are put onto a certificate of calibration that is sent to the customer along with the equipment.

This calibration certificate states various conditions of the calibration, such as what hardware (models/serial numbers) and software (version) was used to perform the calibration, as well as things like environmental conditions, etc.

Making the assumption that the software used to produce the data (and listed on the calibration certificate) used on the certificate of calibration must have gone through a "test/release" process and must be considered "released" software - does this also mean that the software used for adjustment must also be released?

I believe that the method (software/environmental conditions/etc) used or present during adjustment doesn't matter, all that really matters is the end result of the calibration, the conditions present during the calibration, and whether or not the equipment was within the specifications.

The real question I'm hoping to get answered: Is there a reputable source (e.g. NIST or somewhere similar) that addresses this question? (I have searched...)

The thinking is that during high volume production runs, the "unreleased" system can be used to perform adjustments, as long as a released system is used to perform the calibrations, since the time required to perform the adjustments is much longer than the calibration. This unreleased system will eventually become released for use, but currently is not.

Also, please not that there is a distinction between "adjustment" and "calibration". The definition from BIPM International vocabulary of metrology, 2.39:

Operation that, under specified conditions, in a first step,
  establishes a relation between the quantity values with measurement
  uncertainties provided by measurement standards and corresponding
  indications with associated measurement uncertainties (of the
  calibrated instrument or secondary standard) and, in a second step,
  uses this information to establish a relation for obtaining a
  measurement result from an indication.

Followed by NOTE 2 (emphasis in original text):

Calibration should not be confused with adjustment of a measuring
  system, often mistakenly called "self-calibration", nor with
  verification of calibration

As a side note, I'm not sure why this got down voted. It's regarding software and it's use before and after release for use. I believe there is a best practice that can be applied and this is (hopefully) not primarily opinion based.


答:
Get another job and let other people deal with it. Muahahahhahahaa.

.....

Just joking. :)

But in all seriousness: estimation padding is your friend. I generally do a decent realistic estimate, then double it. This might sound excessive, and sometimes it is, but it's better to overestimate a bit and even look a tad slow sometimes - than to leave bad impressions by turning out buggy code and always blowing your estimates. And of course, you incur technical debt by letting the codebase get hacky.

Another (related) tip: Always estimate seemingly tiny, no brainer tasks to a decent sized block. Say, for example - an item which you are almost sure will just be a simple one line 30 second change - give it 1 hour (or maybe whatever the lowest time block is on your timesheet or CR system, eg 15 mins/0.25 hour). And give half-day or 1 day blocks for the slightly bigger but still relatively trivial items.

The reason for this is mainly psychological: I find that if you get in the habit of quickly hacking up small changes, the work feels rushed, and you never end up sitting back, taking stock, and refactoring stuff that needs to be refactored. Also, on a practical level: small-but-non-trivial changes sometimes blow out, and you don't want to be constantly feeling like you're behind schedule and putting out bug fires. It's part and parcel of why code bases get hacky over time.

Finally, always remember that people don't have to know that you are padding your estimates somewhat. As long as you're a competent developer and you're cranking out work at a decent pace, this padding won't be noticeable. ie Don't tell the PHB "My initial estimate is that it'll take two hours, but give me half a day". Just tell him "I think it'll take about half a day." and leave it there.

Title: How do you cope with ugly code that you wrote?

Body:
So your client asks you to write some code, so you do. He then changes the specs on you, as expected, and you diligently implement his new features like a good little lad. Except... the new features kind of conflict with the old features, so now your code is a mess. You really want to go back and fix it, but he keeps requesting new things and every time you finish cleaning something, it winds up a mess again.

What do you do? Stop being an OCD maniac and just accept that your code is going to wind up a mess no matter what you do, and just keep tacking on features to this monstrosity? Save the cleaning for version 2?


答:
Note that you may have stateless classes that implement some interface (e.g. java.lang.Runnable - you can't make their methods static. Some patterns (e.g. Strategy) also can produce stateless objects that may even have several methods.

Statics are first cousins of the singletons. It will be really hard to move from statics to non-statics at a later point - so when you will need to add state you will be tempted to start introducing static variables.


问:
How to charge in agile iterative approach?
I have a doubt about budgeting when working with agile iterative approach. If I understood well, in agile at the end of each iteration we have usable product, so we have some of the requirements met and then some part of the software will be already working.

How do we charge for our work in this methodology? Do we charge per iteration, i.e. charge per major requirements being met, or just charge the customer when the software is indeed finished and then receive for everything at once?

答:
Usually the project approach doesn't matter.  Most likely one will present a daily rate per consultant/resource.  Then take the rate times the days for the cost estimate.

For example (numbers for ease of multiplication):

Daily rate=100

Agile = 10 iterations.  Each iteration will last 10 days = 100 days

100x100 = $10000 per consultant/resource

Different rates will apply depending on the resource (Dev, QA, Arch, PM, etc.).  Some resources may not be allocated 100%.


问:
What is the right level of site blocking for you as a developer?
Almost all developers who work for a large corporation find themselves on the wrong side of site blocking software. It can be both frustrating ("Just let me read that damn blog!") and helpful ("Woah! Dodged a bullet with that site").

In your opinion, what is the right level of blocking to apply to developers and why?

答:
Zero.

If you have a developer who doesn't produce, blocking websites won't help that.

The quantity and quality of code produced by a developer is a not linearly scalable with time spent staring into an IDE.

Being productive in creative and challenging work requires "contiguous time" and "flexible time." Contigious time is a block of time where a developer knows he won't be interrupted by anyone, flexible time is time where a developer knows he is allowed to take breaks on his own schedule and rest his mind when he needs it.

Over management is a problem for contigious time, site blocking is a problem for flexible time.

As Jason Fried points out in this tedTalk, ten years ago no one had a problem with employees taking breaks to smoke. Facebook and the like are just modern day version of the smoke-break - they're necessary, useful and should be embraced by management.


答:
iteration rates based on labor, or for clients that like flat-bids, price each feature based on estimates, and add up for each iteration

the 'true' answer for you will end up being 'whatever both you and the client are comfortable with'

Title: How to charge in agile iterative approach?

Body:
I have a doubt about budgeting when working with agile iterative approach. If I understood well, in agile at the end of each iteration we have usable product, so we have some of the requirements met and then some part of the software will be already working.

How do we charge for our work in this methodology? Do we charge per iteration, i.e. charge per major requirements being met, or just charge the customer when the software is indeed finished and then receive for everything at once?


问:
How to educate business managers on the complexity of adding new features?
We maintain a web application for a client who demands that new features be added at a breakneck pace. We've done our best to keep up with their demands, and as a result the code base has grown exponentially. There are now so many modules, subsystems, controllers, class libraries, unit tests, APIs, etc. that it's starting to take more time to work through all of the complexity each time we add a new feature. We've also had to pull additional people in on the project to take over things like QA and staging, so the lead developers can focus on developing.

Unfortunately, the client is becoming angry that the cost for each new feature is going up. They seem to expect that we can add new features ad infinitum and the cost of each feature will remain linear.

I have repeatedly tried to explain to them that it doesn't work that way - that the code base expands in a fractal manner as all these features are added. I've explained that the best way to keep the cost down is to be judicious about which new features are really needed. But, they either don't understand, or they think I'm bullshitting them. They just sort of roll their eyes and get angry. They're all completely non-technical, and have no idea what does into writing software.

Is there a way that I can explain this using business language, that might help them understand better? Are there any visualizations out there, that illustrate the growth of a code base over time? Any other suggestions on dealing with this client?

答: I have been in your shoes before. And its a little more simple than you think. Put yourself in their shoes. Which means you need to stop using words like fractal and code base... they have no idea what that means. I am not trying to be mean here. However, you need to address your audience in a way that they will understand. In my case I fully involved them in the development process and made sure they knew what each resource was doing and how adding a new feature would impact that resource. You may even have to reveal cost to them by letting them know that, this engineer who is working on the feature you asked for last week is getting paid x per hour. You now need him to split his time to work on these two other features you are wanting next week. He is the only engineer on the team with that skill. The business managers need to know a lot more detail but in a less techy way. Does that make sense?</p>

OwnerDisplayName: Donald Harris


答:
I am using simple way to manage requests for adding new functionality.
Each new functionality that out of initial scope should be estimated.

So when customer asks to add some feature, I and my team think what should be done, and how
it could be done. When we have all necessary information we prepare estimations and
describe what parts of the system should be updated to have requested feature done.

Without many technical words. And when customer see ETA he can calculate final price.
Then he decide, do he want this feature or not.

Do not agree on each customer request without any word.
Each feature should be discussed, agreed and estimated.

Title: How to educate business managers on the complexity of adding new features?

Body:
We maintain a web application for a client who demands that new features be added at a breakneck pace. We've done our best to keep up with their demands, and as a result the code base has grown exponentially. There are now so many modules, subsystems, controllers, class libraries, unit tests, APIs, etc. that it's starting to take more time to work through all of the complexity each time we add a new feature. We've also had to pull additional people in on the project to take over things like QA and staging, so the lead developers can focus on developing.

Unfortunately, the client is becoming angry that the cost for each new feature is going up. They seem to expect that we can add new features ad infinitum and the cost of each feature will remain linear.

I have repeatedly tried to explain to them that it doesn't work that way - that the code base expands in a fractal manner as all these features are added. I've explained that the best way to keep the cost down is to be judicious about which new features are really needed. But, they either don't understand, or they think I'm bullshitting them. They just sort of roll their eyes and get angry. They're all completely non-technical, and have no idea what does into writing software.

Is there a way that I can explain this using business language, that might help them understand better? Are there any visualizations out there, that illustrate the growth of a code base over time? Any other suggestions on dealing with this client?


问:
Participants in Agile retrospective
Who should be the participants in retrospective? Will it be only the team members OR should the Product manager, all the stakeholders and dependent teams also participate.

I am of the opinion that only the team should meet to discuss in retrospectives, else all team members will not open up. But one of the managers insist that all the stake holders should also be included.

答:
The stakeholders have their say at the end of the Sprint Review, which is their point of time to voice concerns, influence the possible forecast the upcoming sprints and give feedback.

The Sprint Retrospective is for the Scrum Team. In some cases only the Development Team and the Scrum Master are present at this meeting. The product owner should join, often the relationship with the product owner is part of what can be improved, so inviting him/her should make that process easier. Also, any changes to the DoD (that can be made as outcome of the Retrospective) need to be taken past the Product Owner, maybe the team missed an important reason (like legislation) for the things to be as they are. In the end the Product Owner is end-accountable for the product and it's quality, so he should have a say.

In the Professional Scrum Developer course we also include a remark that you might get a more open communication going by asking the Product Owner to leave the meeting at some point. If that is the case, the lack of transparency and trust should be addressed at some point in a retrospective in the future, I'd say...

Stakeholders have no place at the retrospective. If they want changes to how things are going they will need to go through the Product Owner. If there are issues between stakeholders and the team, it might be a good idea to do a separate meeting (not a retrospective) with the whole scrum team present (incl SM and PO) to put the cards face up on the table and work out the issues.

Have you asked the manager why he thinks these stakeholders need to be included? What does he want to get out of that meeting? Figure out which meeting would be the right place for that concern to be addressed and who should be the one addressing it. There might be a need to plan something that's outside of the standard scrum meeetings, which of course is allowed.

Relevant passage from the scrum guide:

The Sprint Retrospective is an opportunity for the Scrum Team to inspect itself and create a plan
  for improvements to be enacted during the next Sprint.

OwnerDisplayName: Sushma R

Title: Participants in Agile retrospective

OwnerDisplayName: jessehouwing


答:
Who should be the participants in retrospective? Will it be only the
  team members OR should the Product manager, all the stake holders,
  dependent teams also participate.

The purpose of the retrospective is for the scrum team to evaluate their performance during the sprint. In this meeting they can discuss:

What went well during the sprint?

What went wrong during the sprint?

What the team could do differently to improve?

The project stakeholders and product manager should not be involved as they were not part of the Scrum team on a day to day basis. The retrospective is for the scrum participants.

In my experience, I have found that stakeholders and product managers are not concerned about technical matters, development practices, hardware issues etc. which the development team encountered during the sprint. Their main concern is that the Scrum teams are producing the correct product, and they find this out during the product demos.

As for other dependent teams, they too should not participate in the retrospective either as they did not directly participate. However, a member/members of the Scrum team should, along with the Scrum master, definitely regularly participate in Scrum of Scrums with other dependent development teams to ensure that other teams are aware of progress, and so that knowledge can be shared.

Title: Participants in Agile retrospective

Body:
Who should be the participants in retrospective? Will it be only the team members OR should the Product manager, all the stakeholders and dependent teams also participate.

I am of the opinion that only the team should meet to discuss in retrospectives, else all team members will not open up. But one of the managers insist that all the stake holders should also be included.

OwnerDisplayName: Fresh


答:
I would use the classic answer.... "it depends". Your work culture (how open people are) and your relationship with the PO influence this decision.

Ultimately, the goal of retrospective session is to look for an improvement. You may want to ask yourself (and team) whether having PO in your session will yield better result or worse.

I used to work in the team that PO is involved in the session and he really contributes a lot to our meetings from different perspective. Still, this is because he has a very good relationship with the team and everyone can speak openly.

Another option is to divide your session into "non-technical" and "technical" issues. After the non-technical issues are discussed, the PO can leave and enjoy his freedom. (Usually they should be happy about this). However, the Scrum master should be cautious on how are you going to prioritize the action items later as the team may value the team's items more than the PO's.

Title: Participants in Agile retrospective

OwnerDisplayName: ijemmy


答:
If there are issues related to for instance planning, collaboration and communication between the PO and the team members, then I suggest to invite the PO to the retrospective.

When you are doing planned product releases, it might be useful to organize a retrospective directly after the release, where the team and stakeholder can discuss the sprints that have lead to the release and come up with ideas to improve the way of working for the upcoming delivery.

Title: Participants in Agile retrospective

OwnerDisplayName: BenLinders


问:
Creating deterministic key pairs in javascript for use in encrypting/decrypting/signing messages
So I have been searching everywhere and havn't been able to find anything with the sufficient information I need.. so Im a bit stumped on this one at the moment

What I am trying to do is create a public/private key pair (like PGP) upon a users account creation, based on their passphrase and a random seed. The public key would be saved on the server, and ideally the private key would never be seen by the server whatsoever. The user could then sign in, and send a message to another user. Before the message is sent, the senders key pair would be re-generated on the fly based on their credentials (and maybe a password prompt) and used to encrypt the message. The receiver would then use their own re-generated private key to decrypt said message.

The server itself should never see any plaintext passwords, private keys or readable messages.

Bit unsure how on how I could go about implementing this. Iv been looking into PGP, specifically openPGP.js. The main trouble I am having is being able to regenerate the key-pair based off a specific seed. PGP seems to have a random output even if the inputs are the same. Storing the private key in a cookie or in HTML5 storage or something also isnt really an option, too unreliable.

Can anyone point me in the right direction?

答:
What you are looking for is a variant of a zero-knowledge proof where you can stash some data on a set of servers and use them to recreate your credentials.  Here is a pretty good paper that describes how that would work:

Password authentication using multiple servers

Also, there is a company that does something really similar to this for you (full disclosure, I work there) and makes it available via a library:

Adrenaline Mobility

OwnerDisplayName: SlickTheNick

OwnerDisplayName: Sam King


问:
Either I'm not confident I just don't know anything
My name is Sael and I'm 14 years old. Since I was 12 and I got my first computer I instantly go interested in making games. So of course like any other I googled it, got discouraged and forgot about it for a few months. When I was 13 I decided to continue programming, and decided that java would best suit me. Now after a year, I have a basic understanding of java and how it works (it just clicked instantly one day). Anyways, my problem is that I know how I'm going to make a simple game in my head, but as soon as I click that "New Project" button on eclipse, I'm instantly lost and can't figure out where to start. I can't do much without a tutorial beside me since my mind is so dependent on it. So here's the question : what can I do to get past this problem of mine, and have any of you felt like this before?

sorry if my English is a bit incorrect, Spanish is my main language*

I've made Minecraft mods before

答: Just keep coding dude! We've all been there. Nothing wrong with following tutorials to learn - I'm doing the same thing myself, after having programmed for 20 years I'm following an objective-c tutorial right now. It's not a problem. Starting from an empty project is really hard and something you only need to do much later on. Just sit back and enjoy learning to code.


答:
Get a book. I started learning Java with "Thinking in Java", there might be other better books available by now. Main problem I see with Java is that it's object-oriented - I believe it adds unnecessary complexity for new developers.

You may also consider other languages - I see that Python is considered more approachable. I would still very much recommend starting with a book.

You did Minecraft mods - good. Did you consider experimenting with something like Unity3d? Those game engines have scripting support that will force and motivate you to start coding.

Title: Either I'm not confident I just don't know anything

Body:
My name is Sael and I'm 14 years old. Since I was 12 and I got my first computer I instantly go interested in making games. So of course like any other I googled it, got discouraged and forgot about it for a few months. When I was 13 I decided to continue programming, and decided that java would best suit me. Now after a year, I have a basic understanding of java and how it works (it just clicked instantly one day). Anyways, my problem is that I know how I'm going to make a simple game in my head, but as soon as I click that "New Project" button on eclipse, I'm instantly lost and can't figure out where to start. I can't do much without a tutorial beside me since my mind is so dependent on it. So here's the question : what can I do to get past this problem of mine, and have any of you felt like this before?

sorry if my English is a bit incorrect, Spanish is my main language*

I've made Minecraft mods before


答:
ah the blank page hurdle the most hated and under appreciated of all obstacles to creativity.

in my experience there are 2 places you can start,

develop the background logic of the game first using unit tests for verification

start with the interface and showing the pretty stuff first even if the backing logic is lacking

in both cases having a basic idea of what the logic should do before you start will be an essential guiding line.

I'm going to burst a bubble here and say you are probably not going to make the next minecraft here. You will make mistakes, either in logic or implementation. Don't be afraid to make them and learn from them, ask yourself: why did you choose this and why was it a bad idea. You could even deliberately try some anti-patterns and find out why they are anti-patterns.


答:
It helps to have a basic understanding of the essence of programming.  At its core, programming is creating instructions for a computer.  A computer is essentially a box with an IQ of 5, so programming consists of figuring out how to explain yourself so clearly that a box with an IQ of 5 can understand you.

The main part of this is breaking down large issues into smaller ones.  For example, you have a large issue to solve: "build a simple game."  So, what are the sub-issues here?  (Let's say it's a Tetris game, just to have a concrete example to go by.)

Create a main screen

Create the gameplay itself

Create a leaderboard to store high scores

Now let's break those down further:

Create a main screen

Get a background image

Create a menu

Respond to player input for starting a new game, quitting the game, and displaying the leaderboard

Create the gameplay itself

Devise a way to represent the well

Define the different types of pieces, and how they rotate

Figure out how to draw the well and the pieces to the screen

Figure out how to make the pieces fall, one square at a time, on a fixed time step.

Figure out how to make the piece stop falling when it can't move down further.

Devise a way to get input from the player to move and rotate the pieces.

Extend the code where the piece stops falling to check for newly filled lines, and clear them.

Implement a game-over condition when the well fills up

Implement scoring.

Create a leaderboard to store high scores

Figure out how to store data to a file

Choose/devise a file format

Write code that loads the high score file into memory when the game starts

At the end of each match, check the current score against the high score data and update it as appropriate

Implement a screen that displays the leaderboard.  Make sure it has a way to get back to the main menu.

...and so on.  The trick to not getting overwhelmed by large, complex projects is by breaking them down into smaller pieces, and breaking them down into smaller pieces still, until you end up with problems small enough that you know how to solve them.  That's really half of what learning programming is: learning how to break down problems into smaller ones.  (The other half is expanding your repertoire of solutions to small problems!)


答:
You are young. Don't worry about that. I struggled much more when I was your age.

If you want to learn programming properly though, Java is a horrible language to start with. It's full of accedental complexities, and you'll find yourself doing lots of boilerplates. It is widely used because it has been well marketed in the past, but unless you're only into money-oriented programming, it's not what you want to start with.

You want to learn programming, not Java. I suggest you have a look at this book freely available online How to Design Programs. The second edition of the book is still in draft but very readable. The language these books use is (simplified) Racket, which is simple, fun to learn yet very powerful. And these books teach you real programming concepts, not syntax fiddling.

Another book you can look at is Realm of Racket, which teaches you programming by writing up a game throughout the chapters, dealing with stuff like graphics and networkings along the way.

You are young, so take your time and enjoy the joy of understanding new things. And when you have questions, don't hesititate to ask on StackOverflow :)


问:
Initiating processing in a RESTful manner
Let's say you have a resource that you can do normal PUT/POST/GET operations on.  It represents a BLOB of data and the methods retrieve representations of the data, be they metadata about the BLOB or the BLOB itself.

The resource is something that can be processed by the server on request.  In this instance a file that can be parsed multiple times.

How do I initiate that processing?  It's a bit RPC like.  Is there best practice around this?

I've read this: RESTFul: state changing actions but it doesn't really answer the question.

(First time on programmers. This is the right place for this sort of question, right?)

答:
The HTTP protocol has built-in support for the concept of background or batch operations in the form of status code 202:

10.2.3 202 Accepted

The request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. There is no facility for re-sending a status code from an asynchronous operation such as this.

The 202 response is intentionally non-committal. Its purpose is to allow a server to accept a request for some other process (perhaps a batch-oriented process that is only run once per day) without requiring that the user agent's connection to the server persist until the process is completed. The entity returned with this response SHOULD include an indication of the request's current status and either a pointer to a status monitor or some estimate of when the user can expect the request to be fulfilled.

Clients will appreciate if your 202 response also includes a Location header where they may check the status. This is especially important for any automated end-to-end tests.

I'm not sure if this is really your question, because a large chunk of it actually seems to be referring to Content Negotiation, which is how you store or retrieve "different representations" of something. Of course you can just have different URLs, such as /widgets/1/info and widgets/1/blob, but the preferred way of doing this is through conneg. There are two headers that are relevant here:

Accept, which specifies what the client wants to receive;

Content-Type, which specifies what the client is actually sending.

So, for example, let's say you have a widgets API that is supposed to be able to support widgets in either the "ACME" or "OMNI" format. The client can send in either format via the Content-Type header:

PUT /widgets/123

  Content-Type: application/vnd.foo.acme-widget+json

PUT /widgets/456

  Content-Type: application/vnd.foo.omni-widget+json

The server should understand both of these requests and choose the correct parsing method based on the Content-Type header. On the receiving end, the client specifies with Accept:

GET /widgets/123

  Accept: application/vnd.foo.acme-widget+json

GET /widgets/123

  Accept: application/vnd.foo.omni-widget+json

Both requests are for the same resource, and they use the same method (GET), but when the server sees the first one, it should provide the data using the ACME scheme, and when it sees the second one, it should provide the same data in OMNI scheme.

One considerable benefit of this approach is that every resource still has a canonical URI which you can use in Location headers and so on. It's not required, but generally ideal in REST for each resource to "live" at exactly one URI and no more.

If the difference is truly between data and metadata then you probably should have an actual metadata resource, like /widgets/123/info, but if you are dealing with different representations of the same data then you should use Accept and Content-Type.

I think that covers all aspects of your question, but if you think something is missing - please clarify.


问:
Web Services and code lists
Our team heavily discuss the issues how to handle code list in a web service definition. The design goal is to describe a provider API to query a system using various values. Some of them are catalogs resp. code lists. A catalog or code list is a set of key value pairs. There are different systems (at least 3) maintaining possibly different code lists. Each system should implement the provider API, whereas each system might have different code list for the same business entity eg. think of colors. One system know [(1,'red'),(2,'green')] and another one knows [(1,'lightgreen'),(2,'darkgreen'),(3,'red')] etc.

The access to the different provider API implementations will be encapsulated by a query service, but there is already one candidate which might use at least one provider API directly.

The current options to design the API discussed are:

use an abstract code list in the interface definition: the web service interface defines a well known set of code list which are expected to be used for querying and returning data. Each API provider implementation has to mapped the request and response values from those abstract codelist to the system specific one.

let the query component handle the code list: the encapsulating query service knows the code list set of each provider API implementation and takes care of mapping the input and output to the system specific code lists of the queried system.

do not use code lists in the query definition at all: Just query code lists by a plain string and let the provider API implementation figure out the right value. This might lead to a loose of information and possibly many false positives, due to the fact that the input string could not be canonical mapped to a code list value (eg. green -> lightgreen or green -> darkgreen or both)

What are your experiences resp. solutions to such a problem? Could you give any recommendation?

答:
I've gone with option 2 in the past, it's least painful for the clients and for adding new consumers: you can componentize codes and meanings, so as to make another client's addition painless, and in that sense this is the most useful way.

You'll need every client to provide a dictionary, and maybe someone from each side to figure out equivalences whenever there's fuzziness (which, to my experience, can be very often).

Title: Web Services and code lists


问:
If an entity is composed, is it still a god object?
I am working on a system to configure hardware. Unfortunately, there is tons of variety in the hardware, which means there's a wide variety of capabilities and configurations depending on what specific hardware the software connects to.

To deal with this, we're using a Component Based Entity design where the "hardware" class itself is a very thin container for components that are composed at runtime based on what capabilities/configuration are available. This works great, and the design itself has worked well elsewhere (particularly in games).

The problem is that all this software does is configure the hardware. As such, almost all of the code is a component of the hardware instance. While the consumer only ever works against the strongly typed interfaces for the components, it could be argued that the class that represents an instance of the hardware is a God Object.

If you want to do anything to/with the hardware, you query an interface and work with it.

So, even if the components of an object are modular and decoupled well, is their container a God Object and the downsides associated with the anti-pattern?

答:
Where does the logic and complexity live? If the outermost Hardware instance is mainly a facade or adapter, while the sub-components have most of the logic and behavior, then I'd say "No".

There may be other criticisms you could level at it, but to me a "God Object" is more often a class with way "too many" lines of code doing "too many" different kinds of things.


问:
Why is it not standard to implement abstraction layers for the file system?
I have been taught to access databases through abstraction layers. I was wondering why it is not also standard practice to access the file system through an abstraction layer? It seems to me unit testing would become much simpler, since mocking the filesystem is often a pain and poorly supported by some languages.</p>

答:
In the vast majority of languages and frameworks, the stream is an abstract concept, and methods can be designed to accept generic streams (which can be substituted for in-memory data) instead of concrete file system objects.

I personally have not found much benefit to unit-testing file operations beyond that level, because there are so many things that can go wrong in practice that the unit tests prove almost nothing at all about the application's ability to perform its function.

It's actually a lot like database abstractions; typically you don't try to abstract something like the database connection or an ORM session/context/whatever, you just create a "repository" or "query" abstraction to encapsulate all the data access and mock that. So file I/O isn't that much different; you don't generally want to abstract the file system itself, just the operation being performed on the file system expressed in terms of the problem domain, and that needs to be done in user code.

If you're finding that you need to mock the file system, I'd say your system-under-test is getting a little too intimate with it. Just delegate those file operations to a handful of higher-level abstractions and exclude their implementations from code coverage, like you would normally do with SQL queries.