问:
How should I build the data structure for a dynamic, unlimited-size "maze"?
I'm not actually sure that "maze" is the correct term. Basically users start in a single Room that has 4 doors (N, S, E, and W). They can go in any direction, and each subsequent room is contains another room with anywhere from 1 to 4 doorways that go to other rooms.

The "maze" is supposed to be unlimited in size, and to grow as you move rooms. There is a limited number of Rooms available, however the available number is dynamic and can change.

My problem is, I'm not sure of the best data structure for this type of pattern

I first thought about just using a [X][X] array of Room objects, but I'd really rather avoid that since the thing is supposed to grow in any direction, and only rooms that are "visited" should be built.

The other thought was to have each Room class contain 4 linked Room properties for N, S, E, and W, and just link to the previous Room, but the problem with that I don't know how to identify if a user goes into a room that has an adjacent room already "built"

For example,

```
---    ---            ----------
|        |            |        |
   Start        5          4
|        |            |        |
---    ---            ---    ---
---    --- ---------- ---    ---
|        | |        | |        |
|    1          2          3
|        | |        | |        |
---    --- ---    --- ----------

```

If the user moves from Start > 1 > 2 > 3 > 4 > 5, then Room #5 needs to know that W contains the starting room, S is room #2 and in this case should not be available, and N can be either a new Room or a wall (nothing).

Perhaps I need a mix of the array and the linked rooms, or maybe I'm just looking at this the wrong way.

Is there a better way of building the data structure for this type of "maze"? Or am I on the right track with my current thought process, and am just missing a few pieces of information?

(In case you're interested, the project is a game very similar to Munchkin Quest)

答:
I learned to do this via the book "Creating Adventure Games On Your Computer".  If you are willing to dig through BASIC code (the book is that old) go read here:

http://www.atariarchives.org/adventure/chapter1.php

For the shortcut, what they do is have an array of rooms, with an element in each array being a pointer to another room that you can go to, with 0 (I would use -1 these days) to indicate that you can't go that way.  For example, you'd make a room structure (or class or what-have-you)

```<code>room {
 int north_dir;
 int south_dir;
 int west_dir;
 int east_dir;
 // All other variables and code you care about being attached to the rooms here
}
</code>```

Then you could have an array or linked list structure or however else you want to manage your rooms.  For array-style (or C++ vectors) I'd use that code and the directions would hold the index of the room they link to; for a linked list, you could use pointers to the next room.

As others have said, if you need to dynamically generate new rooms when people enter them, you can also do that.

Body:
I learned to do this via the book "Creating Adventure Games On Your Computer".  If you are willing to dig through BASIC code (the book is that old) go read here:

http://www.atariarchives.org/adventure/chapter1.php

For the shortcut, what they do is have an array of rooms, with an element in each array being a pointer to another room that you can go to, with 0 (I would use -1 these days) to indicate that you can't go that way.  For example, you'd make a room structure (or class or what-have-you)

room {
 int north_dir;
 int south_dir;
 int west_dir;
 int east_dir;
 // All other variables and code you care about being attached to the rooms here
}

Then you could have an array or linked list structure or however else you want to manage your rooms.  For array-style (or C++ vectors) I'd use that code and the directions would hold the index of the room they link to; for a linked list, you could use pointers to the next room.

As others have said, if you need to dynamically generate new rooms when people enter them, you can also do that.


问:
Should these concerns be separated into separate objects?
I have objects which implement the interface BroadcastInterface, which represents a message that is to be broadcast to all users of a particular group. It has a setter and getter method for the Subject and Body properties, and an addRecipientRole() method, which takes a given role and finds the contact token (e.g., an email address) for each user in the role and stores it. It then has a getContactTokens() method.

BroadcastInterface objects are passed to an object that implements BroadcasterInterface. These objects are responsible for broadcasting a passed BroadcastInterface object. For example, an EmailBroadcaster implementation of the BroadcasterInterface will take EmailBroadcast objects and use the mailer services to email them out.

Now, depending on what BroadcasterInterface implementation is used to broadcast, a different implementation of BroadcastInterface is used by client code. The Single Responsibility Principle seems to suggest that I should have a separate BroadcastFactory object, for creating BroadcastInterface objects, depending on what BroadcasterInterface implementation is used, as creating the BroadcastInterface object is a different responsibility to broadcasting them.

But the class used for creating BroadcastInterface objects depends on what implementation of BroadcasterInterface is used to broadcast them. I think, because the knowledge of what method is used to send the broadcasts should only be configured once, the BroadcasterInterface object should be responsible for providing new BroadcastInterface objects.

Does the responsibility of “creating and broadcasting objects that implement the BroadcastInterface interface” violate the Single Responsibility Principle?

(Because the contact token for sending the broadcast out to the users will differ depending on the way it is broadcasted, I need different broadcast classes—though client code will not be able to tell the difference.)

答:
If you have no code that works against a BroadcastInterface directly there is no point in having it. Even if you have multiple implementations of it, you use it more as a sort of template then as an abstraction.

So an EmailBroadcaster should able to work with any implementation of BroadcastInterface.

In this case I would consider merging BroadcasterInterface with BroadcastInterface. Put behavior with the data.

ContentLicense: CC BY-SA 3.0


问:
Solutions for software using many calls to a server
I am developing software that uses many calls to a server. On a client side it's a Silverlight application. Almost every time a user clicks on a button in it, it sends 1-5 WCF calls to a server. There can be up to dozen or so users at a time. The server is a database server that serves data to a client. I am an intermediate level developer and am thinking about caching some data and syncing my changes from time to time. Are there any official solutions or technologies for it, like, patterns and such?</p>

答:
Reduce the number of calls. Caching brings a whole new slew of problems.

One button click resulting in 5 requests suggests maybe the client is too much in control, perhaps implementing business rules and such.
Let the server do the processing/thinking. Tell don't ask.


问:
Finding an A* heuristic for a directed graph
In a previous question, I asked about finding a route (or path if you will) in a city. That is all dandy. The solution I chose was with the A* algorithm, which really seems to suit my needs. What I find puzzling is heuristic. How do I find one in an environment without constant distance between 2 nodes? Meaning, not every 2 nodes have the same distance between them.

What I have is nodes (junctures), streets with weight (which may also be one-way), a start/finish node (since the start and end is always in the same place) and a goal node. In an ordinary case, I would just use the same way I got to goal to go back, but since one of the streets could have been a one-way, that may not be possible.

The main question

How do I find a heuristic in a directed graph?

答:
The heuristic is based on the direct bird's flight cost of travelling to your goal with the lowest possible weight (e..g running into a super highway without speed limits, if those exist in your context).

It has not much to do with your graph apart from the minimal weight per distance unit it could contain.


答: The heuristic doesn't have to be perfect. Whilst A* would run in ridiculously short time if h(node) was equal to the optimum path from that node to the goal, that's obviously unrealistic. However, for reasonable heuristics, they only have to be the minimum possible distance- that is, there can be no path which reaches the goal from x of less weight than h(x), but it can most assuredly be greater. Common heuristics are Euclidean distance, and Manhattan distance. Neither of these is perfect, but they both fit the requirements of A*.

Title: Finding an A* heuristic for a directed graph

Body:
In a previous question, I asked about finding a route (or path if you will) in a city. That is all dandy. The solution I chose was with the A* algorithm, which really seems to suit my needs. What I find puzzling is heuristic. How do I find one in an environment without constant distance between 2 nodes? Meaning, not every 2 nodes have the same distance between them.

What I have is nodes (junctures), streets with weight (which may also be one-way), a start/finish node (since the start and end is always in the same place) and a goal node. In an ordinary case, I would just use the same way I got to goal to go back, but since one of the streets could have been a one-way, that may not be possible.

The main question

How do I find a heuristic in a directed graph?


答:
Let h(x) be your heuristic for node x and h*(x) the perfect heuristic (where you know the EXACT distance to your goal from x), if 0 < h(x) <= h*(x) for every node of the graph then the heuristic is admissible.

If h(x) = 0 you have no information and A* degenerates into
Dijkstra's algorithm.

If h(x) = h*(x) you do know the answer
and therefore there is no problem to solve.

The closer h(x) is to h*(x), the shorter A* will take to find the shortest path.

If h(x) > h*(x) then your solution is not guaranteed to be optimal (i.e. found path might not be the least cost path.)

Some well known heuristics that meet this criteria are Euclidean distance and Manhattan distance.

If h(x) <= d(x,y) + h(y) for every edge x, y of the graph, where d(x,y) is the actual distance between the nodes, the heuristic is said to be monotone (or consistent) and no nodes need to be processed more than once.

Said that, any heuristic that doesn't overestimate the distance will do fine. It doesn't matter if your nodes have different weights, that's part of d(x) (the actual distance of your walked path), not h(x) which is just a roughly estimate to favor some paths before others. As long as h(x) (remember, it's just an estimate) is < h*(x) you'll get the optimal route.

In an ordinary case, I would just use the same way I got to goal to go back, but since one of the streets could have been a one-way, that may not be possible.

It doesn't really matter if you have one-way streets. Your graph can be directed and you just don't let your algorithm generate that route. You don't need to go back while executing A*, because it would become a longer route that if you didn't take that path in the first place. If you want to go back from GOAL to NODE that's just a new search in your search space, not a single problem.

Regarding MSalters' notice, I don't think you can derive a heuristic in a graph with just weights. You need a problem that meets some kind of criteria that offers extra information to guess from. If you only have weights, then you can't to it better than Dijkstra's because you lack any more information. It depends entirely on the problem domain, so a broad answer that fits any graph can't be given.


问:
Why did memory-managed languages like Java, Javascript, and C# retain the `new` keyword?
The new keyword in languages like Java, Javascript, and C# creates a new instance of a class.

This syntax seems to have been inherited from C++, where new is used specifically to allocate a new instance of a class on the heap, and return a pointer to the new instance.  In C++, this is not the only way to construct an object. You can also construct an object on the stack, without using new - and in fact, this way of constructing objects is much more common in C++.

So, coming from a C++ background, the new keyword in languages like Java, Javascript, and C# seemed natural and obvious to me.  Then I started to learn Python, which doesn't have the new keyword.  In Python, an instance is constructed simply by calling the constructor, like:

```<code>f = Foo()
</code>```

At first, this seemed a bit off to me, until it occurred to me that there's no reason for Python to have new, because everything is an object so there's no need to disambiguate between various constructor syntaxes.

But then I thought - what's really the point of new in Java?  Why should we say Object o = new Object();?  Why not just Object o = Object();?  In C++ there's definitely a need for new, since we need to distinguish between allocating on the heap and allocating on the stack, but in Java all objects are constructed on the heap, so why even have the new keyword?  The same question could be asked for Javascript.  In C#, which I'm much less familiar with, I think new may have some purpose in terms of distinguishing between object types and value types, but I'm not sure.

Regardless, it seems to me that many languages which came after C++ simply "inherited" the new keyword - without really needing it.  It's almost like a vestigial keyword.  We don't seem to need it for any reason, and yet it's there.

Question: Am I correct about this?  Or is there some compelling reason that new needs to be in C++-inspired memory-managed languages like Java, Javascript and C# but not Python?

答:
In C# it allows types visible in contexts where they might otherwise be obscured by a member. The allows you to have a property with same name as a its type. Consider the following,

```<code>class Address {
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
}

class Person {
    public string Name { get; set; }
    public Address Address { get; set; }

    public void ChangeStreet(string newStreet) {
        Address = new Address {
            Street = newStreet,
            City = Address.City,
            State = Address.State,
            Zip = Address.Zip
        };
    }
}
</code>```

Note the use of new allows it to be clear that Address is the Address type not the Address member. This allows a member to have the same name as its type. Without this you would need to prefix the name of the type to avoid the name collision, such as CAddress. This was very intentional as Anders never liked hungarian notation or anything similar and wanted to C# to be usable without it. The fact it was also familiar was a double bonus.

Body:
In C# it allows types visible in contexts where they might otherwise be obscured by a member. The allows you to have a property with same name as a its type. Consider the following,

class Address {
    public string Street { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Zip { get; set; }
}

class Person {
    public string Name { get; set; }
    public Address Address { get; set; }

    public void ChangeStreet(string newStreet) {
        Address = new Address {
            Street = newStreet,
            City = Address.City,
            State = Address.State,
            Zip = Address.Zip
        };
    }
}

Note the use of new allows it to be clear that Address is the Address type not the Address member. This allows a member to have the same name as its type. Without this you would need to prefix the name of the type to avoid the name collision, such as CAddress. This was very intentional as Anders never liked hungarian notation or anything similar and wanted to C# to be usable without it. The fact it was also familiar was a double bonus.


问:
What should I consider when deciding if I should use a web service backend instead of traditional MVC?
We're trying to decide what architecture to use for an upcoming web application that will eventually have a mobile portion as well. The core of the project is a social networking web application, and the mobile portion will most likely have a limited subset of the web functionality.

The two options we are looking at is either a complete web service back end, or using a traditional MVC framework for the web application and then developing web services on the side for the mobile application later.

Some arguments for web-service-only route is that it would be "simpler", as we would just have to create 1 web service as opposed to creating both a web service for the mobile portion, and additional database functions/calls for the web application. Using this method, the web application will fetch data from the web services using javascript, which would then generate the html page (sounds kind of like what a traditional MVC framework does, but this way would require everything to be done in javascript).

I'm not feeling good about the idea of using web services only because it doesn't make sense to me, but I am having trouble clarifying my issues with it.

So what should I consider when trying to determine if we should use a complete web-service backend for our project instead of traditional MVC with web services only available when needed for the mobile portion of the app?

I'm looking for a comprehensive answer to this question, not many answers each containing one piece of the answer.

答:
When implemented properly you may be able to have both worlds. When you go the web service route you may be sending the json version of the models you would be using to render your MVC views with otherwise.

For the web version you would need to build your html somewhere. I think you can do this mostly server side or do it using some form of javascript client side templating. The data/model either requires is going to be the same.

If the web service route means SOAP I would disagree also.

Why not make the web application mobile capable? You may end up not needing a native mobile app at all...


问:
What is the most space efficient way to implement a graph data structure?
I typically implement graphs as doubly linked lists but this is fairly space inefficient in my experience as I need k pointers/references for k neighbors so for an undirected graph I'd have ~2k neighbor links within the lists if my math is right. Is there a better way of saving space? I know that some of the links can be made singular if the graph is directed but is there a way to do a better job of this?</p>

答:
Well if space efficiency is all you care about then a compressed data structure would be best - but of course this isn't very efficient for access or update.....

If your graph has a relatively small number of nodes and is fairly dense (lets say at least 5% of all possible connections exist) then you may find it is more space efficient to create an adjacency matrix rather than using edge lists. This would require just one bit per possible (directed) connection, and n*n bits total where you have n nodes.

Otherwise if you need to use neighbour links then you can't easily do better than one reference per link since this is the minimum information content you need to store. If you want back-links you will need twice as many links.

There are some tricks you could try on top of this. For example, you could try sharing subsets of links ( if A and B refer to each of C, D, E then only store the list of links C,D,E once.....). However this will get complex pretty quickly and I doubt it will be worth the effort in most cases.

One other trick - assuming your graph has a reasonable number of nodes, you will certainly save space by indexing - e.g. using a 16-bit node index number rather than a full pointer / reference.


问:
What do I need to do to NOT steal "Hello World" code with a GPL license?
In the project, I found a file, math.c, with a big GPL header and ...

```<code>//------------------------------------------------------------------------------
/// Returns the minimum value between two integers.
/// \param a  First integer to compare.
/// \param b  Second integer to compare.
//------------------------------------------------------------------------------
unsigned int min(unsigned int a, unsigned int b)
{
    if (a < b) {
        return a;
    }
    else {
        return b;
    }
}
</code>```

OK, cool so I need to get min value and ... this file!? So I need to open the whole project because of it? Or do I need to reinvent mathematics?

I don't believe it's just insane, so the question is: when we can just remove the GPL header?

Must I be a weirdo and do it?:

```<code>unsigned int min(             unsigned int
JEIOfuihFHIYEFHyigHUEFGEGEJEIOFJOIGHE,
unsigned int hyrthrtRERG            ) {  if
(JEIOfuihFHIYEFHyigHUEFGEGEJEIOFJOIGHE
< hyrthrtRERG            ) {  return JEIOfuihFHIYEFHyigHUEFGEGEJEIOFJOIGHE;  }
else {return hyrthrtRERG            ;    } }
</code>```

Seriously, do they want me to write code like the above?

答:
It doesn't directly answer your question, but try this:

#define min(a,b) ((a) < (b) ? (a) : (b))
```

<p>I hereby release this glorious, complex macro to the public domain. Though I may have to  publish a paper on this technique.</p>

<p>If you're macro-phobic, try this inline version (really, unless you're coding on a SPARC, you'll save lots of CPU cycles by not wrapping a function as ubiquitous as <code>min</code> in enter/exit code):</p>

<pre class="lang-c prettyprint-override"><code>inline int min(int a, int b)
{
    return a < b ? a : b;
}
</code>```

The issue of code licensing for trivial snippets is a bit of a nuisance, really. Check with a lawyer, but I'm tempted to assume that they can't really be licensed and/or the licensing can't be enforced in practice. Same as you can't copyright or trademark the word ‘word’, then lean on people who use it. (oops)

Body:
It doesn't directly answer your question, but try this:

#define min(a,b) ((a) < (b) ? (a) : (b))

I hereby release this glorious, complex macro to the public domain. Though I may have to  publish a paper on this technique.

If you're macro-phobic, try this inline version (really, unless you're coding on a SPARC, you'll save lots of CPU cycles by not wrapping a function as ubiquitous as min in enter/exit code):

inline int min(int a, int b)
{
    return a < b ? a : b;
}

The issue of code licensing for trivial snippets is a bit of a nuisance, really. Check with a lawyer, but I'm tempted to assume that they can't really be licensed and/or the licensing can't be enforced in practice. Same as you can't copyright or trademark the word ‘word’, then lean on people who use it. (oops)


答:
Answer: Only with explicit permission of the author.

That's copyrighted code.  You cannot copy it without permission of the author.

You will have to write your own version of min, or copy a variant of min that uses a different license.

Remember, with copyright, it's the code that is protected, not the algorithm.  Copyright law comes from text.  Even if "math.c" was nothing but comments and had no executable code at all, it'd still be protected under copyright.

Title: What do I need to do to NOT steal "Hello World" code with a GPL license?

Body:
In the project, I found a file, math.c, with a big GPL header and ...

```<code>//------------------------------------------------------------------------------
/// Returns the minimum value between two integers.
/// \param a  First integer to compare.
/// \param b  Second integer to compare.
//------------------------------------------------------------------------------
unsigned int min(unsigned int a, unsigned int b)
{
    if (a < b) {
        return a;
    }
    else {
        return b;
    }
}
</code>```

OK, cool so I need to get min value and ... this file!? So I need to open the whole project because of it? Or do I need to reinvent mathematics?

I don't believe it's just insane, so the question is: when we can just remove the GPL header?

Must I be a weirdo and do it?:

```<code>unsigned int min(             unsigned int
JEIOfuihFHIYEFHyigHUEFGEGEJEIOFJOIGHE,
unsigned int hyrthrtRERG            ) {  if
(JEIOfuihFHIYEFHyigHUEFGEGEJEIOFJOIGHE
< hyrthrtRERG            ) {  return JEIOfuihFHIYEFHyigHUEFGEGEJEIOFJOIGHE;  }
else {return hyrthrtRERG            ;    } }
</code>```

Seriously, do they want me to write code like the above?


答:
It's going to depend on the structure your data.

For a dense graph with undirected edges, you can't really beat a list of bit arrays representing a triangular matrix. A List<BitArray> for example. Logically, it would look like this:

```<code> 0123
0
11
211
3001
41010
</code>```

From there, you can use the index of the root BitArray to index into a list that stores your node data.

For example, getting all of the neighbours of a node would go like:

```<code>// C#
List<Node> Nodes = /* populated elsewhere */
List<BitArray> bits = /* populated elsewhere */
public static IEnumerable<Node> GetNeighbours(int x)
{
    for (int i = 0; i < bits[idx].Count; i++)
    {
        if (this.bits[idx][i])
            yield return this.Nodes[i];
    }

    for (int i = 0; i < this.Nodes.Count; i++)
    {
        if (idx < this.bits[i].Count && this.bits[i][idx])
            yield return this.Nodes[i];
    }
}
</code>```

(note that you can also choose the index type, depending on the amount of data, to be a byte or ushort or something along those lines as all indexes will be positive. I don't consider this a micro-optimization as it's trivial)

For a directed graph, you would go the route of a n*n array of bits to store the connectivity... unless it's very sparse compared to the number of nodes, where you can go to an adjacency list of indices.

Title: What is the most space efficient way to implement a graph data structure?

Body: I typically implement graphs as doubly linked lists but this is fairly space inefficient in my experience as I need k pointers/references for k neighbors so for an undirected graph I'd have ~2k neighbor links within the lists if my math is right. Is there a better way of saving space? I know that some of the links can be made singular if the graph is directed but is there a way to do a better job of this?</p>

Body:
It's going to depend on the structure your data.

For a dense graph with undirected edges, you can't really beat a list of bit arrays representing a triangular matrix. A List<BitArray> for example. Logically, it would look like this:

 0123
0
11
211
3001
41010

From there, you can use the index of the root BitArray to index into a list that stores your node data.

For example, getting all of the neighbours of a node would go like:

// C#
List<Node> Nodes = /* populated elsewhere */
List<BitArray> bits = /* populated elsewhere */
public static IEnumerable<Node> GetNeighbours(int x)
{
    for (int i = 0; i < bits[idx].Count; i++)
    {
        if (this.bits[idx][i])
            yield return this.Nodes[i];
    }

    for (int i = 0; i < this.Nodes.Count; i++)
    {
        if (idx < this.bits[i].Count && this.bits[i][idx])
            yield return this.Nodes[i];
    }
}

(note that you can also choose the index type, depending on the amount of data, to be a byte or ushort or something along those lines as all indexes will be positive. I don't consider this a micro-optimization as it's trivial)

For a directed graph, you would go the route of a n*n array of bits to store the connectivity... unless it's very sparse compared to the number of nodes, where you can go to an adjacency list of indices.


问:
Can/Should I put my Git repository on a non-dev machine and keep it synced with the non-version control server?
I volunteer for a website, and well, basically, we don't have version control. We're working to change that, but because of several things, including the fact that I haven't worked with source control before, that's not happening for some time.

In the meantime, I'd like to move my working files into source control (probably Git) for the obvious benefits. Here's the thing: there are hundreds of thousands of files on the web server that are user-generated that I don't really want on my dev machine because, well, I pay for my own equipment (it is volunteer after all, so it's not like I can expense a new hard drive) and my dev machine is also my everyday computer and I'd rather not clog it up with a lot of stuff that doesn't need to be here.

I do, however, have an empty system sitting around that is perfectly willing to store all of that data. In all likelihood, that system is probably going to host an entire local copy of the site anyway as a backup. So, and I hope this isn't an entirely crazy idea, I'm thinking about putting the Git repository on that machine. I'm not intending to develop on that machine, however.

So,

Is putting your Git repository on a different computer than your dev machine a really bad idea? It should be technically feasible as it's on the same network, and I don't think my IDE will have any problem connecting to it, but that doesn't mean it's a terrible idea. Putting the repository on my dev machine isn't out of the question, but it'd be preferable to put it on the empty one.

(And I hope that this is related enough to keep in the same question) Because there are other people working on the site, changes are going to happen to the remote site that aren't going to go through source control. Since I'd prefer the two to stay synced, could I create a Git repository on the server, pull and merge changes into my local, and then just upload the changes through FTP? Doing any real version control on the server isn't feasible at the moment (as I said, it's being worked on), but a repository that we don't touch is a different matter. Would this be a feasible plan at all?

答:
Yes, it is possible as you described it, but very, very inconvenient and error-prone. If your repo is on another machine, you would have to copy the current state (HEAD) to your dev machine to work on the files, then copy them back to even commit something. That completely destroys one of the best features of DVCS's: cheap and fast local commits. Also, you don't only use version control as a dumb backup storage: it has history, bisect, branches, merging etc. You want that on your fingertips, without a round-trip to the other machine. Another possibility, if you are using *nix based OS on both machines is if you set up an SSH connection and work through that. That's not terribly hard, but still not optimal.

Now, I think that your repo (minus the user-generated contents) is not going to be terribly huge even with all history (I might be wrong, but unless you store and modify lots of binary data in the repo, git tends to be fairly compact). Usually, people don't store content in the repo, only code (well maybe some minor test data). So what you should do is write a suitable .gitignore file that filters out the things you don't want. The user-generated content, especially if the items are not only added but changed over time, is not something you want to version. You can still put a clone of the repo on that other machine and even on the production server. That way, deploying your changes would be a git push.


答:
I suggest you study the 'real need' to change your current situation. It is not nice to have all those calls but does it affect your system performance in a noticeable way? If you have the resources to change the current situation, then you may consider one of the options here.

As every one says, reduce the number of calls. You need to examine why you are doing all those calls to the server. Unless the calls to the server are dependent on each other result, then you probably have a generic service interface that needs to be changed. I don't know your database but assuming that it is like Customers, Order Header, Orders, you could return all this data in 1 call. This can be done in different ways, for example you could use LINQ INCLUDE (Eager Loading) or you could write a stored procedure which supports multiple result sets (MARS). The trick here is to balance between the number of calls required and the size of the result returned. You don't want to make a call that returns too much data. Here, the insightful GUI design plays a big role. If your GUI is designed without considering this, you need to tame it. For example, instead of returning 1000 orders in the above scenario, return 10 and allow for paging. Or ask the user if he/she wants to see order details (can have that as a separate button). Of course, this depends on your business needs. If most of the data your are always reading is data that does not change often, say lookup tables, then cashing those makes sense. However, you'll need a mechanism to update this cache. In many businesses, changes to lookups don't happen in an ad-hoc way and can be made at end-of-day or such. However, you need to define and implement how the cache will be refreshed.

Title: Solutions for software using many calls to a server

Body: I am developing software that uses many calls to a server. On a client side it's a Silverlight application. Almost every time a user clicks on a button in it, it sends 1-5 WCF calls to a server. There can be up to dozen or so users at a time. The server is a database server that serves data to a client. I am an intermediate level developer and am thinking about caching some data and syncing my changes from time to time. Are there any official solutions or technologies for it, like, patterns and such?</p>


答:
Don't try and solve all problems with one structure.

Define your room object to store things about the room, not its relations to other rooms. Then a 1D array, list etc can grow as you like.

A separate structure can hold "reachability" - which rooms are accessible from the room I'm in. Then decide if transitive reachability needs to be a quick calculation or not. You might want a brute force calculation and a cache.

Avoid early optimisation. Use really simple structures and dumb easily understood algorithms then optimise the ones that get used.

Title: How should I build the data structure for a dynamic, unlimited-size "maze"?

Body:
I'm not actually sure that "maze" is the correct term. Basically users start in a single Room that has 4 doors (N, S, E, and W). They can go in any direction, and each subsequent room is contains another room with anywhere from 1 to 4 doorways that go to other rooms.

The "maze" is supposed to be unlimited in size, and to grow as you move rooms. There is a limited number of Rooms available, however the available number is dynamic and can change.

My problem is, I'm not sure of the best data structure for this type of pattern

I first thought about just using a [X][X] array of Room objects, but I'd really rather avoid that since the thing is supposed to grow in any direction, and only rooms that are "visited" should be built.

The other thought was to have each Room class contain 4 linked Room properties for N, S, E, and W, and just link to the previous Room, but the problem with that I don't know how to identify if a user goes into a room that has an adjacent room already "built"

For example,

```
---    ---            ----------
|        |            |        |
   Start        5          4
|        |            |        |
---    ---            ---    ---
---    --- ---------- ---    ---
|        | |        | |        |
|    1          2          3
|        | |        | |        |
---    --- ---    --- ----------

```

If the user moves from Start > 1 > 2 > 3 > 4 > 5, then Room #5 needs to know that W contains the starting room, S is room #2 and in this case should not be available, and N can be either a new Room or a wall (nothing).

Perhaps I need a mix of the array and the linked rooms, or maybe I'm just looking at this the wrong way.

Is there a better way of building the data structure for this type of "maze"? Or am I on the right track with my current thought process, and am just missing a few pieces of information?

(In case you're interested, the project is a game very similar to Munchkin Quest)


答:
I won't use this code anyway, because the comment doesn't match with what the code does. The comment talks about integer, while the code uses unsigned int. Who knows what errors are buried within the depths of this function?

Seriously, this is where "Don't reinvent the wheel" becomes ridiculous and you forgot to take it with a grain of salt. Just write your own version from scratch, match it with the naming convention and style guide of your code (e.g. math_min_uint(x, y)), make sure it works (unit test or whatever) and go on with life and without copyright issues.

With growing experience, these trivial snippets you need again and again are just in your toolbox and you will rewrite them without thinking too much, or simply get them from your own library.


答:
Unlike many of the user here, I would simply suggest: Copy it!

Make sure the formatting of the code fits your coding standard and also you should probably remove or rewrite the comment. No one will ever know you copied it - when a piece of code is this simple, you might as well have written it from scratch. If your coding standard somehow requires the function to look exactly as it does in the snippet, so be it - as long as it looks as it would look if you had written it from scratch.

Think about it, this is hardly(!) the first time this exact piece has been written - when something is this trivial, there is little reason not to copy it, if you do not feel like writing it yourself.

Even having this discussion seems a little superfluous to me - we need to be pragmatic if we are to get any real work done!


答:
I'm releasing the following code under the BSD license.  As that license is a lot more permissive you shouldn't run into copyright issues if you use my implementation.  </p>

```<code>unsigned int min(unsigned int a, unsigned int b)
{
    return (a > b? b: a);
}
</code>```

Body:
I'm releasing the following code under the BSD license.  As that license is a lot more permissive you shouldn't run into copyright issues if you use my implementation.

unsigned int min(unsigned int a, unsigned int b)
{
    return (a > b? b: a);
}


问:
Has test driven development (TDD) actually benefited a real world project?
I am not new to coding. I have been coding (seriously) for over 15 years now. I have always had some testing for my code. However, over the last few months I have been learning test driven design/development (TDD) using Ruby on Rails. So far, I'm not seeing the benefit.

I see some benefit to writing tests for some things, but very few. And while I like the idea of writing the test first, I find I spend substantially more time trying to debug my tests to get them to say what I really mean than I do debugging actual code. This is probably because the test code is often substantially more complicated than the code it tests. I hope this is just inexperience with the available tools (RSpec in this case).

I must say though, at this point, the level of frustration mixed with the disappointing lack of performance is beyond unacceptable. So far, the only value I'm seeing from TDD is a growing library of RSpec files that serve as templates for other projects/files. Which is not much more useful, maybe less useful, than the actual project code files.

In reading the available literature, I notice that TDD seems to be a massive time sink up front, but pays off in the end. I'm just wondering, are there any real world examples? Does this massive frustration ever pay off in the real world?

I really hope I did not miss this question somewhere else on here. I searched, but all the questions/answers are several years old at this point. It was a rare occasion when I found a developer who would say anything bad about TDD, which is why I have spent as much time on this as I have. However, I noticed that nobody seems to point to specific real-world examples. I did read one answer that said the guy debugging the code in 2011 would thank you for have a complete unit testing suite (I think that comment was made in 2008).

So, I'm just wondering, after all these years, do we finally have any examples showing the payoff is real? Has anybody actually inherited or gone back to code that was designed/developed with TDD and has a complete set of unit tests and actually felt a payoff? Or did you find that you were spending so much time trying to figure out what the test was testing (and why it was important) that you just tossed out the whole mess and dug into the code?

答:
Though tests may be often considered just a way of doing too much by some people, I do think it's really worth the trouble in certain cases.

I've been developing a Killer Sudoku Solver for school for about 3 months, it uses many "strategies" to remove possibilities and solutions. The fact is that, an error in a possibility can be fatal and result in a problem to solve the sudoku because when some possibility is removed, you don't try it anymore, and if it was the solution, the program can't solve the grid anymore.

But it's really hard to test manually, I mean right there's a grid, I can see which stratgeies are doing what in a real world example, but I just can't check all each time a strategy apply because this represents too much data.

And strategies applied on a certain grid are quite "random", that's to say you won't use all on a particular grid.

So I wrote tests on each strategy, checking the result on every cell, using just simple situations (for instance just two cells have already removed possibilities) and it saved me hours a day when I unfortunately had a grid which couldn't be solved. Because I already knew where was the problem.

OwnerDisplayName: James

OwnerDisplayName: Skydreamer


答:
The advantage of TDD is that you figure out how to call your code before your write the actual code.

In other words, TDD helps with designing your API.

In my experience this results in better API's which in turn gives better code.

EDIT:  As I wrote, this was "in my experience", i.e. when writing "real world projects" but unfortunately this is with a closed source code base I cannot let the world see. I can understand from the comments that this is what is actually asked for, and not just a confirmation of the mere existence of such projects.

I have also found - again in my personal experience - that the real benefit show when you enter maintenance mode because requirements tend to change.  The cleaner API's made it much easier to express the new or altered requirements in test code, and all the tests makes it very easy to see for a future maintainer how the code is to be called and what can be expected back.

The test cases are running versions of the specification and allows you to see very, very easily how to invoke your API.  This is perhaps the single most useful form of "HOW"-documentation I've seen so far (compare to the "WHY"-documentation like JavaDoc) as you are certain it is correct (otherwise the test would fail).

Lately, I've had to maintain a scriptable ftp client with a very large set of options which all influence the way the application works.  TDD has been introduced lately for new functionality and the large test suite allows us to do hotfixes while being confident that the used functionality still works as expected.  In other words this transition proved to pay off very quickly.

Title: Has test driven development (TDD) actually benefited a real world project?

Body:
I am not new to coding. I have been coding (seriously) for over 15 years now. I have always had some testing for my code. However, over the last few months I have been learning test driven design/development (TDD) using Ruby on Rails. So far, I'm not seeing the benefit.

I see some benefit to writing tests for some things, but very few. And while I like the idea of writing the test first, I find I spend substantially more time trying to debug my tests to get them to say what I really mean than I do debugging actual code. This is probably because the test code is often substantially more complicated than the code it tests. I hope this is just inexperience with the available tools (RSpec in this case).

I must say though, at this point, the level of frustration mixed with the disappointing lack of performance is beyond unacceptable. So far, the only value I'm seeing from TDD is a growing library of RSpec files that serve as templates for other projects/files. Which is not much more useful, maybe less useful, than the actual project code files.

In reading the available literature, I notice that TDD seems to be a massive time sink up front, but pays off in the end. I'm just wondering, are there any real world examples? Does this massive frustration ever pay off in the real world?

I really hope I did not miss this question somewhere else on here. I searched, but all the questions/answers are several years old at this point. It was a rare occasion when I found a developer who would say anything bad about TDD, which is why I have spent as much time on this as I have. However, I noticed that nobody seems to point to specific real-world examples. I did read one answer that said the guy debugging the code in 2011 would thank you for have a complete unit testing suite (I think that comment was made in 2008).

So, I'm just wondering, after all these years, do we finally have any examples showing the payoff is real? Has anybody actually inherited or gone back to code that was designed/developed with TDD and has a complete set of unit tests and actually felt a payoff? Or did you find that you were spending so much time trying to figure out what the test was testing (and why it was important) that you just tossed out the whole mess and dug into the code?


答: Another advantage (in addition to those mentioned by the other people that have answered) kicks in when customer acceptance testers, or (heaven forbid) production users discover a bug.  Turn the bug report into a TDD-style test for the class that seems to be at fault.  Watch it fail.  Fix it.  Watch it pass.  Then you know that you've fixed the bug.  This technique has saved me hours.</p>


答:
How valuable a particular approach to testing is depends on how mission critical the system under development is, and how much some other mission critical system depends on it.  A simple guestbook script for your website could hardly be considered mission critical, but if the website it runs on could potentially be compromised by a bug that allowed unfiltered input to the database and that site offers some vital service, then it suddenly becomes a lot more important for the guestbook script to be thoroughly tested.  The same is also true of framework/library code.  If you develop a framework with a bug, then every application that uses that framework feature also has that same bug.

Test driven development gives you an extra layer of safety when it comes to tests. If you write the tests alongside or even after the code you want to test, then there's a real risk that you get the tests wrong.  If you write all the tests first, then how the code works internally can't influence what you write tests for, and therefore there's less possibility that you inadvertently write tests that think that a particular erroneous output is correct.

Test driven development also encourages your developers to write code that's easy to test, because they don't want to give themselves even more work to do!  Code that's easy to test tends to be code that's easy to understand, reuse and maintain.

And maintenance is where you will really reap the rewards of TDD.  The vast majority of the programming effort expended on software is maintenance related.  This means making changes to live code to give it new features, fix bugs or adapt it to new situations.  When making such changes, you want to be sure that the changes you make have the desired effect, and more importantly, they have no unexpected knock on effects.  If you have a full test suite for your code, then it's easy to verify that any changes you make are not breaking something else, and if the changes you make do break something else then you can quickly locate the reason why.  The benefits are long term.

You said the following in your question:

I see some benefit to writing tests for some things, but very few. And
  while I like the idea of writing the test first, I find I spend
  substantially more time trying to debug my tests to get them to say
  what I really mean than I do debugging actual code. This is probably
  because the test code is often substantially more complicated than the
  code it tests. I hope this is just inexperience with the available
  tools (rspec in this case).

This seems to suggest to me that you're not quite getting testing.  A unit test is supposed to be extremely simple, just a sequence of method calls, followed by an assertion to compare the expected result against the actual result.  They're meant to be simple because bugs in your tests would be disastrous, and if you introduce loops, branching or other program throw control into the test then it becomes more likely that the test will have a bug introduced into it.  If you're spending a lot of time debugging tests then it indicates that your tests are overly-complicated and you should simplify them.

If the tests can't be simplified, than that fact alone suggests that there's something wrong with the code under test.  For example if your class has long methods, methods with a lot of if/elseif/else or switch statements or a high number of methods that have complex interactions dictated by the current state of the class then tests will by necessity have to be extremely complex to provide full code coverage and test all eventualities.  If your class has hard coded dependencies on other classes then this again will increase the number of hoops you will have to jump to in order to effectively test your code.

If you keep your classes small and highly focused, with short methods with few execution paths and try to eliminate internal state then the tests can be simplified.  And this is kind of the crux of the matter.  Good code is inherently easy to test.  If the code isn't easy to test then there's probably something wrong with it.

Writing unit tests is something that benefits you in the long run, and avoiding them is simply storing up trouble for later.  You might not be familiar with the concept of technical debt, but it works a lot like financial debt.  Not writing tests, not commenting code, writing in hard coded dependencies and so in are ways of going into debt.  You "borrow" time by cutting corners early on and this might help you hit a tight deadline, but the time you save earlier on in the project is on loan.  Each day that goes by without cleaning up the code, commenting it properly or building a test suite will cost you interest.  The longer it goes on, the more interest accumulates.  Eventually, you'll discover your code has become a tangled mess that you can't make changes to without triggering unintended consequences.  The interest on the time loan you took out early in the project and failed to pay back later has come back to bite you and now you're effectively bankrupt - The time taken to fix the problems with the existing system exceeds the time it would take to rewrite it from scratch.

You could think of writing unit tests early and keeping them up to date as a form of "technical credit".  You're putting time in the bank by spending it early on in the project on following good practice.  You'll earn interest on this foresight later on when you get to the maintenance phase of the project.  When you want to make a change, you can easily validate the correctness of the change and that it doesn't have any unwanted side effects, and you can get updates out the door quickly and without fuss.  If bugs turn up, you can add a new unit test that exercises the bug, then fix the bug in the code.  When you next run the unit test you'll be able to verify that the bug was fixed, and that it didn't cause any other problems.  Further more, you'll avoid "regressions", where a previously fixed bug is reintroduced because there's nothing documenting why things have been changed.

TL:DR - Yes, they are a real world help, but they're an investment.  The benefits only become apparent later.


答:
Real world non-trivial example:

I had to write a data structure transformation function. Input would be a data structure (actually a nested data structure, much like a tree) and the output would be a similar data structure. I could not visualize the actual transformation in my mind. One of the main benefits of TDD (for me, anyways) is the enforcement of baby steps if you don't know how to proceed (see Kent Becks "TDD by Example"). Because I did not know where this was going I started with the simple base cases like empty or trivial inputs and worked my way up to more complicated cases until I figured I had them all covered. In the end I had a working algorithm and the tests that proved it. Not only do the tests prove that my implementation is working right now, they also keep me from screwing anything up later on. Because of test driving the implementation it is decoupled and the API is clean.


问:
Automatic programming: write code that writes code
After reading the book The Pragmatic Programmer, one of the arguments I found most interesting was "write code that writes code".

I tried searching over the net for some more explanations or articles about it, and while I found some good articles on the subject, I still haven't found any specific code implementation or good examples.

I feel it's still not a so common argument, something that lacks documentation or it's not embraced by so many people, and I would like to know more about it.

What do you think about the subject? Is it something that will really increase your productivity? What are some good resources on the subject, among books, blogs, slideshows, etc?

Some code examples would be greatly appreciated to allow me to better understand its implementation.

Here's the wiki page on the subject with various relevant programming techniques, like Meta Programming, Generative Programming and Code Generation.

答:
See Philip Greenspun's problem set 4 from MIT course 6.916: Software Engineering of Innovative Web Services (http://philip.greenspun.com/teaching/psets/ps4/ps4.adp).

Its objective says, "Teach students the virtues of metadata. More specifically, they learn how to formally represent the requirements of a Web service and then build a computer program to generate the computer programs that implement that service."

This is one of the problem sets potential ArsDigita (http://en.wikipedia.org/wiki/ArsDigita) recruits were required to solve during the first bubble.

The "SQL for Web Nerds" book Philip references in the pset has been moved to (http://philip.greenspun.com/sql/).


答:
What do you think about the subject?

Metaprogramming is most commonly associated with non-dynamic languages, since there's an harder time in achieving certain behaviours (such as implementing an ORM) without lots of non-productive and non-intelligent lines of code.

But even in more dynamic languages such as PHP, code generation can be a really life-saver and increase productivity in massive amount. In modern frameworks it's very common to have scaffolding that generates most of the common model, form, test and actions for a certain business object that you declare. It's one of the reasons why frameworks such as symfony or RoR have so much success, those code-generation tools make consistent code very quickly and boost the programmers productivity.

In web-sites, most of the interaction revolves around four main actions:

Create an element

Retrieve a set of elements (with possible filtering)

Update an element with new attributes

Delete a set of elements

At least everything that revolves around this 4 main actions could and IMHO SHOULD be achieved using code-generation tools to achieve maximum-productivity.

In my company, we use symfony, and its admin-generator is an exceptional tool, that even generates code in run-time (and caches it), which means we don't even need to use any kind of task or external tool to generate new code, we just need to clean our cache. I STRONGLY advise into using this kind of tool for CRUD operations.

But, doing what symfony awesome contributors did, is not an easy task. I've implemented some code-generation tasks myself and doing something that is truly consistent and with a broad implementation to cover most corner-cases is not easy.

Is it something that will really increase your productivity?

I believe that metaprogramming is very very important in lower-levels of work (frameworks, caching, compilers, etc.) but something that we must approach with extreme caution if we're doing things on the business-layer.

Using code-generation is without any question a major productivity-booster. Implementing your own code-generation tools, not so much unless you're building a framework yourself.

What are some good resources on the subject, among books, blogs, slideshows, etc?

The best resource to understand programming is always good and well-commented source code. I would say that looking into RubyOnRails and Symfony admin generators is a good idea.

Title: Automatic programming: write code that writes code

Body:
After reading the book The Pragmatic Programmer, one of the arguments I found most interesting was "write code that writes code".

I tried searching over the net for some more explanations or articles about it, and while I found some good articles on the subject, I still haven't found any specific code implementation or good examples.

I feel it's still not a so common argument, something that lacks documentation or it's not embraced by so many people, and I would like to know more about it.

What do you think about the subject? Is it something that will really increase your productivity? What are some good resources on the subject, among books, blogs, slideshows, etc?

Some code examples would be greatly appreciated to allow me to better understand its implementation.

Here's the wiki page on the subject with various relevant programming techniques, like Meta Programming, Generative Programming and Code Generation.


答:
It's an absurd situation, I agree, but you have only yourself to blame. If you are writing proprietary code, you should not be reading GPL-licensed source files, period. Remove math.c from your filesystem, keep the documentation, and feel free to re-implement any part of the API that you need. If you don't read the code, you don't need to worry if your own code turns out similar.

Wasteful, you say? The GPL intentionally prevents you from benefiting from free code without giving back to the ecosystem. If you can't or won't meet its terms, and you don't want to implement yet another math library, you can always buy one or find a free one that comes with a license you can accept.

Microsoft's programmers are not allowed to read open source code, to protect the company from legal problems. For purely ethical reasons, you should do the same with any program whose license you don't intend to adhere to.

You don't have a right to use this math.c, but nobody is trying to corner the market on implementations of min. The goal of the GPL is to increase programmer "freedom" (and the end user's freedom), not to restrict it. The GNU license, the FSF, and the Free Software Movement started with Richard Stallman, and Stallman started with re-implementing from scratch each new version of Symbolics lisp as it came out. The FSF would not (and could not) go after anyone for re-implementing a GPL library.


问:
Sign Language Recognition
I am a final year undergraduate student of Information Technology. My team and I have taken up "Sign Language Recognition" as our Final Year Project. We have just started with it and we are in the phase of information gathering (gathering data). We plan to use Instrumented Gloves as the input device. But we do not have much knowledge in the area.

Also, we came across the following methods for training the system for actual recognition of gestures and hence sign language.

Neural Networks

Symbolic Learning Algorithms

Hidden Markov Models

Instance Based Learning

Grammar based techniques

Please tell me which of them I should use for sign recognition.

Also, tell me about Instrumented Gloves and is there any specific variety which we should choose for our project?

答:
There is another approach available, recently I've worked on a project that used gabor wavelets in face recognition Wikipedia entry for Gabor wavelets. And I stumbled on a interesting project that fits your need.

The project revolves around a paper, rock & scissors game and the recognition of symbols used inside a game. It tracks the player trough the camera and recognized the hand gesture.

The project can be found on the following link (Ropesi project). There are some videos inside the svn trunk that demonstrate the use and application of the project.

Title: Sign Language Recognition


答:
I know some ASL (?) has been captured and recognised by computers in the past, and that was a while ago. I remember watching videos of this on VHS. 1994 at the latest.

Sign Languages (there's more than one) are typically multi-channel media — it's not just the handshapes, so the gloves may not be quite enough (depending on your aims). My ASL is almost non-existent, but British Sign Language uses something like this (pinch of salt required, I'm very rusty):

‘Phonology’:

26 hand-shapes (configurations of the fingers).

Various hand orientations

Various hand starting positions

Various types of hand movements

Shoulder shapes.

Head position and tilt. (in BSL, a slight ‘nod’ indicates first person)

Eyebrows and eyes.

Mouth shapes.

Overall expressions which are context-sensitive. Something bad may have happened, but your expression is expected to change briefly to the expression required by the sign.

Grammar:

Signing space (where, in relation to the body, signs are allowed)

Very different from English grammar. E.g. BSL generally follows an Object-Subject-Verb word order, where sentences like CAT DOG CHASED (‘the dog chased the cat’) are the norm.

Spatial pronouns: hand-spell a name, point to a location in your signing space, and you can then point back there rather than hand-spelling or signing the name.

Verb aspect: I don't know about ASL, but BSL has some seriously complex aspect. You can stress a sign by lengthening the ‘hold time’ (starting state of the sign) and making the movement abrupt. More aspect I can think of right now indicates whether something takes place slowly, quickly (and how slowly or quickly), direction of travel, the signer's attitude towards what's being signed, etc. ‘They stared at me for a long time and I was put off’ is essentially the single verb ‘SEE’ with lots of aspect.

Syntax: again, pretty different to what you be used to. BSL is somewhere between Japanese and Spanish, but that's probably an oversimplification.

Complications: fingerspelling follows slightly rules in BSL (not so much in ASL). There's a staggering amount of community-local slang (sign languages aren't written, so they're a lot like spoken languages before the invention of writing — in some cases, boys finishing boys' schools and girls finishing girls' schools graduated to find they had very divergent languages), and quite a few loanwords. My favourite one is (probably only Scottish) slang for ‘I love you’, which is an amalgam of the ASL letters I, L, Y (think standard Spiderman gesture) turned into a transitive verb (the sign moves from close to the signer's torso to the intended person): a completely invalid handshape in BSL, but turned into a BSL verb.

I think you'll be seriously hard-pressed to capture and parse successfully all of these channels. Perhaps reading a suitably limited subset may be a good idea: basic handshapes (ASL fingerspelling is very clear, and should be very easy today) and some basic motions. You may have to limit the complexity of the sentences you parse since you probably won't be able to capture all aspect reliably.

The software will feel to native signers a bit like a hearing learner of sign language, missing out on a lot. I suspect signers will adapt very quickly. After all, native English speakers can still understand a sentence even if some of the articles are missing.

Title: Sign Language Recognition

Body:
I am a final year undergraduate student of Information Technology. My team and I have taken up "Sign Language Recognition" as our Final Year Project. We have just started with it and we are in the phase of information gathering (gathering data). We plan to use Instrumented Gloves as the input device. But we do not have much knowledge in the area.

Also, we came across the following methods for training the system for actual recognition of gestures and hence sign language.

Neural Networks

Symbolic Learning Algorithms

Hidden Markov Models

Instance Based Learning

Grammar based techniques

Please tell me which of them I should use for sign recognition.

Also, tell me about Instrumented Gloves and is there any specific variety which we should choose for our project?


答:
Disclaimer: I am not an attorney. Use my advice at your own risk.

This implementation of min is not copyrightable, since there are only very few reasonable ways of writing it.

In the legal world, this is known as the merger doctrine (also known as the idea-expression divide). The (non-copyrightable) idea of the function is said to have "merged" with the (potentially copyrightable) expression. Therefore, the code is not subject to copyright -- you are free to use it.

To be on the safe side, don't copy it verbatim. Use different names for variables, apply your own formatting, don't copy comments word for word. The exact literal representation of this code may be covered by copyright.

Keep in mind that this doesn't guarantee someone won't sue you, but at least you will have a strong defense.

Also, bear in mind that even if a piece of code isn't protected by copyright, it might still be covered by a software patent (This is not the case for your min function).


问:
How to teach Exception Handling for New Programmers?
How do you go about teaching Exception Handling to Programmers. All other things are taught easily - Data Structures, ASP.NET, WinForms, WPF, WCF - you name it, everything can be taught easily.

With Exception Handling, teaching them try-catch-finally is just the syntactic nature of Exception Handling.

What should be taught however is - What part of your code do you put in the try block? What do you do in the catch block?

Let me illustrate it with an example.

You are working on a Windows Forms Project (a small utility) and you have designed it as below with 3 different projects.

UILayer

BusinessLayer

DataLayer

If an Exception (let us say of loading an XDocument throws an exception) is raised at DataLayer (the UILayer calls BusinessLayer which in turns calls the DataLayer), do you just do the following

```<code>//In DataLayer
try {
    XDocument xd_XmlDocument = XDocument.Load("systems.xml");
}
catch(Exception ex)
{
    throw ex;
}
</code>```

which gets thrown again in the BusinessLayer and which is caught in UILayer where I write it to the log file?

Is this how you go about Exception Handling?

答:
To explain exception handling, explain the concept behind it: The code where an error occurs frequently does not know how to properly handle that error.  The code that knows how to handle it properly could be the function that called that one, or it could be further up the call stack.

When you write a routine that calls a routine that might throw an exception, if you know how to handle that error correctly, put the call in a try block and put the error-handling code in the catch block.  If not, leave it alone and let something above you in the call stack handle the error.

Saying "catch ex, throw ex" is not a good way to do exception handling, since it doesn't actually handle anything.  Plus, depending on how the exception model in your language works, that can actually be harmful if it clears stack trace information that you could have used to debug the issue.  Just let the exception propagate up the call stack until it hits a routine that knows how to handle it.

ContentLicense: CC BY-SA 2.5


问:
When is unit testing inappropriate or unnecessary?
It seems to be generally assumed (on Stack Overflow at least) that there should always be unit tests, and they should be kept up to date. But I suspect the programmers making these assertions work on different kinds of projects from me - they work on high quality, long-lasting, shipped software where bugs are A Really Bad Thing.

If that's the end of the spectrum where unit testing is most valuable, then what's the other end? Where are unit tests least valuable? In what situations would you not bother? Where would the effort of maintaining tests not be worth the cost?

答:
In a fast paced smaller organization, I find that developers are so pressured to stay productive and move fast that they often simply don't bother to test their own changes.

We have a general policy that states that if you make a change (whether it is a bug fix or enhancement) the developer should test it him/herself before submitting the code for further QA.

We don't actually write unit tests for most instances because our screens are mostly designed in a way where if a change is made on the screen, the rest of the logic has to be traversed through in order to find out if the change was successful regardless.

I find it imperative that the developer does their own testing, whether it is documented or not, because they are the ones who best know where the potential weak points in the logic may be.

So I would say, even if you don't write unit tests for every little part of the system, common sense testing should be done regardless.


答:
We have benefited massively.

We are Tier 1 Merchant, which means that we process over six millions of payment transactions per year.

Our payment gateway system has thousands of unit and integration tests. These tests give us confidence in our ability to process payments. You want to be confident that your car brakes work, don't you? We want to be confident that we don't lose our business because we can't process payments.

Code coverage gives you that confidence. Of course it's not enough on its own, but it's a very good start.

Most of our payment gateway system was written using TDD. Some aspects were rather difficult to test, so we have decided to cut corners by sacrificing some code coverage. We will get back and address these issues eventually.

Personally, I find it difficult to write any logic before writing tests. Having said that, it took me a little while to start thinking in TDD way.

Visa PCI Reference: http://usa.visa.com/merchants/risk_management/cisp_merchants.html


问:
Should a git commit message mention the file that was modified?
In the first line of a git commit message I have a habit of mentioning the file that modified if a change doesn't span multiple files, for example:

```<code>Add [somefunc] to [somefile]
</code>```

Is this a good thing to do or is it unnecessary?

答:
I think the real question here is how limited in scope are your commits? If you wait to commit a variety of unrelated changes together in one commit, then you might feel the need to specify what files were changed for what purpose.

However, if you simply made more narrow commits more frequently, then a single commit would explain which files were modified and you could simply describe what the purpose was in the message.

More commits, more often. That's the way you can avoid being so verbose in your messages.

OwnerDisplayName: Matty


答:
It shouldn't

Everybody who is interested can see changes in a history

It's also not feasible in larger systems as many files might be auto generated

Title: Should a git commit message mention the file that was modified?

Body:
In the first line of a git commit message I have a habit of mentioning the file that modified if a change doesn't span multiple files, for example:

```<code>Add [somefunc] to [somefile]
</code>```

Is this a good thing to do or is it unnecessary?


问:
Why use Pascal with Cocoa/Cocoa Touch?
I'm surprised to find that it might be possible to use Pascal with the Cocoa and Cocoa Touch frameworks. This is an interesting turn of events, as Pascal was the favored language for Mac development for a short while early in the history of Macintosh.

It looks like someone has gone to a lot of trouble to make Pascal work with Objective-C frameworks like Cocoa and Cocoa Touch, but I'm not sure I see the point. Is this mainly a refuge for Pascal developers coming from other development environments like Delphi, or are there compelling reasons to use Pascal in place of Objective-C or other languages.

I don't mean to ask which language is "better." I'm just wondering if there's a reason beyond language preference that one would choose to use Pascal for MacOS X or iOS development.

答:
Some reasons beyond preference for picking a different language:

you or the other developers working on the project with you have more experience of the other language than of the vendor's preferred language

your project can benefit from libraries or other reusable code that's available when you use the other language

the vendor of the other language is providing some incentive like cost reduction or support

the tools available for working with the other language make you more efficient than the tools available for working with the vendor's preferred language

The Cocoa APIs are of course developed by the same company that drives the definition of the Objective-C language, and the two fit together very well. But that doesn't mean you should eschew all other languages when working with Objective-C; the runtime is very easy to integrate with other languages so there have been "Objective-*" products available since the 1990s.

Title: Why use Pascal with Cocoa/Cocoa Touch?


问:
What algorithm(s) can be used to achieve reasonably good next word prediction?
What is a good way of implementing "next-word prediction"? For example, the user types "I am" and the system suggests "a" and "not" (or possibly others) as the next word. I am aware of a method that uses Markov Chains and some training text(obviously) to more or less achieve this. But I read somewhere that this method is very restrictive and applies to very simple cases.

I understand basics of neural networks and genetic algorithms(though have never used them in a serious project) and maybe they could be of some help. I wonder if there are any algorithms that, given appropriate training text(e.g., newspaper articles, and the user's own typing) can come up with reasonably appropriate suggestions for the next word. If not (links to)algorithms, general high-level methods to attack this problem are welcome.

答:
It looks like the problem domain is a subset of string search.  By extending words to include white spaces, fuzzy string matching can be applied here.

You might want to consider/allow all user input as one word during training in addition to your dictionary.  This allows you to suggest next word but also suggests auto complete of word or phrases.

Here is a link to a compilation of fuzzy string search algorithms

http://ntz-develop.blogspot.com/2011/03/fuzzy-string-search.html


答:
This is what Google Supposedly ripped off. This seems like common sense for an array.</p>

```<code> 908     /**
 909      * Checks that fromIndex and toIndex are in range, and throws an
 910      * appropriate exception if they aren't.
 911      *
 912      * @param arrayLen the length of the array
 913      * @param fromIndex the index of the first element of the range
 914      * @param toIndex the index after the last element of the range
 915      * @throws IllegalArgumentException if fromIndex > toIndex
 916      * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
 917      *         or toIndex > arrayLen
 918      */
 919     private static void rangeCheck(int arrayLen, int fromIndex, int toIndex) {
 920         if (fromIndex > toIndex)
 921             throw new IllegalArgumentException("fromIndex(" + fromIndex +
 922                        ") > toIndex(" + toIndex+")");
 923         if (fromIndex < 0)
 924             throw new ArrayIndexOutOfBoundsException(fromIndex);
 925         if (toIndex > arrayLen)
 926             throw new ArrayIndexOutOfBoundsException(toIndex);
 927     }
</code>```

Body:
This is what Google Supposedly ripped off. This seems like common sense for an array.

 908     /**
 909      * Checks that fromIndex and toIndex are in range, and throws an
 910      * appropriate exception if they aren't.
 911      *
 912      * @param arrayLen the length of the array
 913      * @param fromIndex the index of the first element of the range
 914      * @param toIndex the index after the last element of the range
 915      * @throws IllegalArgumentException if fromIndex > toIndex
 916      * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
 917      *         or toIndex > arrayLen
 918      */
 919     private static void rangeCheck(int arrayLen, int fromIndex, int toIndex) {
 920         if (fromIndex > toIndex)
 921             throw new IllegalArgumentException("fromIndex(" + fromIndex +
 922                        ") > toIndex(" + toIndex+")");
 923         if (fromIndex < 0)
 924             throw new ArrayIndexOutOfBoundsException(fromIndex);
 925         if (toIndex > arrayLen)
 926             throw new ArrayIndexOutOfBoundsException(toIndex);
 927     }


问:
How do I review my own code?
I'm working on a project solo and have to maintain my own code. Usually code review is done not by the code author, so the reviewer can look at the code with the fresh eyes — however, I don't have such luxury. What practices can I employ to more effectively review my own code?</p>

答:
Back in college I was a writing tutor. It has certainly given me some perspectives on coding that I think many developers would never have thought of. One of the most important is to read your code aloud. It doesn't sound like much, but I will give a perfect example that I think everyone can relate to.

Have you ever written an email or a paper, reread multiple times to make sure its correct, then sent it, only to find that you have a glaring spelling error, typo or grammatical error? I just did this yesterday when I asked a client to press the shit key instead of the shift key. When you read in your head - you see what you want to see.

This is a shortcut for the 'just wait a day or a week or a month' suggestions others have made. If you read it aloud you catch the same things. I don't know why it is so effective, but after sitting with hundreds of students and having them read aloud, all I can say is that it works.

Title: How do I review my own code?


问:
Can we create a reference to DOM objects like document.location
As we have a wonderful concept called hooking where we can create a reference to a function and connect another function In the same way can we create a reference to DOM objects. For example can we create a function and hook it to document.location so that whenever document.location is used the other function must be triggered.

答: You can't do this. Setting document.location to anything will immediately trigger a redirect to whatever string representation the value has.</p>


问:
Scope of work contents in freelance development
One of my clients demanded to append screen shots of UI in the SOW. Also, I was asked to give a workflow diagram for the same. The project I am about to take is relatively small and my question is,

Should we always provide UI snap shots before project begins? (at least basic). Personally I feel this is not possible as UI keeps changing until agreed upon by client, which is waste of time before development.

Is it necessary to provide both Data Flow Diagram (DFD) and UI screen shot before development begins?

答:
Should we always provide UI snap shots before project begins?

If that's what the client asks for, yes.

UI keeps changing until agreed upon by client

Then get the client to agree on the UI design.

Is it necessary to provide both DFD and UI screen shot before development begins?

If the client asks for it, yes.  You can always state your case, and see what happens.


答:
Provide what the client wants.  If you want them as a client that is.

Having some mock ups for the UI is probably a good idea.  Covers your ass too.  You want there to be some decent detail in what the program is meant to do so the client doesn't keep coming up with new and wonderful things to add without paying.

It's true that there will be some evolution, but as stuff like that comes up you can amend the scope to reflect new agreements.  The cool thing there is that it requires your agreement.

So while I've not done much freelancing myself, it seems to me like a good idea to have a nice, detailed scope explaining what the program will do and more or less what it will look like.  I'd use some RAD tool for prototyping the UI...Qt designer or something.  If you can do it in the system you'll build the product in, all the better.

Where I currently work we actually have to do this kind of crap even for internal projects.  We treat the mucky-mucks like clients because they demand it.  Not allowed to do much of anything without 50 miles of paper and a month in committee.

Title: Scope of work contents in freelance development

Body:
One of my clients demanded to append screen shots of UI in the SOW. Also, I was asked to give a workflow diagram for the same. The project I am about to take is relatively small and my question is,

Should we always provide UI snap shots before project begins? (at least basic). Personally I feel this is not possible as UI keeps changing until agreed upon by client, which is waste of time before development.

Is it necessary to provide both Data Flow Diagram (DFD) and UI screen shot before development begins?


答:
Well, I know that I personally benefit by being twice as fast as my fellow developers and write less than half the bugs they do because they DON'T do TDD.  People that probably should be better than me even...I outperform them by at least a factor of 2.

I didn't get there right away.  I'm pretty good at writing code off the cuff and without harness.  Seemed like a big waste to write all this extra crap.  But it does several things, including (not exclusive):

Forcing a design that's geared toward decoupling and reuse (everything has to be reused in a unit test).

Providing a platform to develop code in small chunks and modules so I don't have to get everything figured out and finished before running a simple "Does it even compile and take input" kind of test.

Providing a quick test platform for making changes when people demand feature changes I wasn't expecting.

An example on this later bit is a project I am currently working on where the lead suddenly decided to TOTALLY rewrite the communication protocol it used for pretty much 0 reason.  I was able to respond to that change in 2 hours as I had decoupled that from everything else already and was able to work on it entirely independently until the very last tie it together and integrate test it step.  Most of my coworkers probably would have been at it for a day or more because their code would not be decoupled and they'd be changing here, there, everywhere...compiling it all...integration testing...repeat, repeat...  Takes a lot longer that way and is nowhere near as stable.


答:
I'm using TDD quite often at work. My experience is that TDD justifies itself because you don't pay additional time or effort, you save it.

Since I use TDD I spend much less time debugging or such. It just works from the start because I don't consider productive code as written as long as the tests don't pass.

QA reports much less bugs, so we save cost on repairing our code after a release. This is because TDD doesn't let you write code without a test so the code coverage is much better.

I can run my (productive) code much more often and quicker because I don't need to start the whole application server. Starting the unit test is an order of magnitude faster. Of course I only benefit from it when the test is already executable when I want to try out the productive code. When the tests come afterwards this benefit is missed.

I do much less manual testing. My colleagues who don't practice TDD spend a lot of time clicking through the application until they reach the point where the new code is executed. I only test manually once, just before I commit to version control.

Even if I use a debugger it's much quicker to debug the execution of a test than of the whole application.

Maybe you think of unit tests as regression tests. That is one of their purposes but understanding them as a tool for development makes them much more worthwhile.


答:
In or around 2001 I started working on a project which was making extensive use of business objects and data objects.  I was to be building the front-end website, but was hung up twiddling my thumbs because the business layer and data access layer weren't fully developed.  After a couple of weeks of that, I started to take a hard look at what those layers were doing.  Basically, they were exposing data returned from stored procedures as collections of objects with properties corresponding to the fields in the data, or were taking input parameters and sending them to stored procedures to be saved to database tables.  There was a lot of serialization / deserialization taking place between the two layers, there was Microsoft Transaction Server involved, an IDL / ODL type library ... but it all fit a pattern.

2 weeks later, I had a code generator worked out which would dump out IDL / ODL, and would also dump out the business and data objects.  It had taken the guy building the business and data layer objects 2 years to get to the point of debugging and testing these objects.  In 2 weeks, with code generation, we had the same output, but because it was all generated it was pretty well bug-free.

That code generator (lower-level CASE tool) followed me around through many different iterations, for about 8 to 10 years, because the principle was just so simple: you're doing something that needs to be done when talking to databases, it's pretty much repetitive coding, and once you get it right you don't have to worry with it any longer.

So, yes: use a code generator, particularly when the coding is repetitive and fits a well-defined pattern.

I've known people to use RegX macros to do similar things, or to use Excel formulas to do similar things (I do this as well).


答:
A metaprogramming example

I have a Ruby authorization library called Authority. It lets developers ask questions in their app with methods like current_user.can_read?(@post) and @post.readable_by?(current_user). These questions are answered by centralized authorizer classes.

This is the crucial part: Authority doesn't know which methods to define until it sees the user's configuration. The user configuration might contain:

```<code>config.abilities =  {
  ...
  :read      => 'readable',
  :microwave => 'microwavable',  # user-defined
  ...
}
</code>```

In that case, there needs to be a method like current_user.can_microwave?(@post).

Metaprogramming makes this possible: after reading the configuration, I know which methods to define:

```<code>Authority.verbs.each do |verb|
  class_eval <<-RUBY, __FILE__, __LINE__ + 1 # allows for a nice bracktrace
    def can_#{verb}?(resource)
      resource.#{Authority.abilities[verb]}_by?(self)
    end
  RUBY
end
</code>```

Body:
A metaprogramming example

I have a Ruby authorization library called Authority. It lets developers ask questions in their app with methods like current_user.can_read?(@post) and @post.readable_by?(current_user). These questions are answered by centralized authorizer classes.

This is the crucial part: Authority doesn't know which methods to define until it sees the user's configuration. The user configuration might contain:

config.abilities =  {
  ...
  :read      => 'readable',
  :microwave => 'microwavable',  # user-defined
  ...
}

In that case, there needs to be a method like current_user.can_microwave?(@post).

Metaprogramming makes this possible: after reading the configuration, I know which methods to define:

Authority.verbs.each do |verb|
  class_eval <<-RUBY, __FILE__, __LINE__ + 1 # allows for a nice bracktrace
    def can_#{verb}?(resource)
      resource.#{Authority.abilities[verb]}_by?(self)
    end
  RUBY
end


问:
Best way to set sys.path for "hot library" development in Python?
I have my Python source structured as follows:

```<code>+-branchname/
  +-dst/
  +-src/
  | +-library/
  | | +-cleese/
  | | | +-test/
  | | | | +-__init__.py
  | | | | +-test_cleese.py
  | | | +-__init__.py
  | | | +-cleese.py
  | | +-palin/
  | |   +-test/
  | |   | +-__init__.py
  | |   | +-test_palin.py
  | |   +-__init__.py
  | |   +-palin.py
  | +-productline/
  |    +-circus/
  |    | +-test/
  |    | | +-__init__.py
  |    | | +-test_circus.py
  |    | +-__init__.py
  |    | +-circus.py
  |    +-grail/
  |      +-test/
  |      | +-__init__.py
  |      | +-test_grail.py
  |      +-__init__.py
  |      +-grail.py
  +-branch_root_marker
</code>```

Entry points are in circus/ and grail/, as well as (possibly) each of the test/ directories, depending on how testing is implemented.

I have multiple copies of this source tree present on local storage at any one point in time (corresponding to various maintenance and feature branches), so I cannot set PYTHONPATH in my shell without some pain. (I would need to remember to change it each time I switched to work on a different branch, and I am very forgetful)

Instead, I have some logic that walks up the file tree, starting at the "current" file location, moving from leaf towards root, looking for branch_root_marker. Once the root directory of the current working copy is found, it adds library/ and productline/ to sys.path. I call this function from each entry-point in the system.

```<code>"""Add working copy (branch) to sys.path"""

import os
import sys

def _setpath():
    """Add working copy (branch) to sys.path"""

    markerfile = "branch_root_marker"
    path = ""
    if ("__file__" in locals() or globals()) and __file__ != "__main__":
        path = __file__
    elif sys.argv and sys.argv[0] and not sys.argv[0] == "-c":
        path = sys.argv[0]
    path = os.path.realpath(os.path.expandvars(path))
    while os.path.exists(path):
        if os.path.exists(os.path.join(path, markerfile)):
            break
        else:
            path = os.path.dirname(path)
        errormsg = " ".join(("Could not find", markerfile))
        assert os.path.exists(path) and path != os.path.dirname(path), errormsg

    path = os.path.join(path, "src")
    (_, subdir_list, _) = os.walk(path).next()
    for subdir in subdir_list:
        if subdir.startswith("."):
            continue
        subdir_path = os.path.join(path, subdir)
        if subdir_path in sys.path:
            continue
        sys.path.append(subdir_path)
_setpath()
</code>```

Currently, I need to keep a separate but identical copy of this function in each entry point. Even though it is quite a short function, I am quite distressed by how fragrantly the DRY principle is being violated by this approach, and would love to find a way to keep the sys.path modification logic in one place. Any ideas?

Note:- One thing that springs to mind is to install the sys.path modifying logic into a common location that is always on PYTHONPATH. Whilst this is not a terrible idea, it means introducing an installation step that needs to be carried out each time I move to a fresh environment; another thing to remember (or, more likely, forget), so I would like to avoid this if at all possible.

答: You have to use virtualenv. It create an isolated python environment. It is also recommended when you need different versions of third party packages depending of the version of your product.</p>


问:
In an MVC architecture, how closely coupled are the Model and View to the Controller?
I've got an app which uses MVC, but I'm struggling a little as to how the controller should be architected. For example, the View is only viewing some subset of the model's data at once. However, I'm unsure as to exactly how this should be arranged. Is it normal for the View or Model to directly call functions on the Controller, for example? Through some sort of interface? Or are they totally encapsulated and never know about the Controller or each other?

Just as an edit; this is a custom app not written in any web framework, so I'm not looking for framework-specific details here and have the freedom to make my own choice.

答:
Martin Fowler does a good job of describing the MVC paradigm. Here is a link to his article on it http://martinfowler.com/eaaDev/uiArchs.html

Note his quote about Separated Presentation "The idea behind Separated Presentation is to make a clear division between domain objects that model our perception of the real world, and presentation objects that are the GUI elements we see on the screen."


答:
I see some benefit to writing tests for some things, but very few. And while I like the idea of writing the test first, I find I spend substantially more time trying to debug my tests to get them to say what I really mean than I do debugging actual code.

I have been working TDD for the last three years, and my experience is the exact opposite. I spend less time writing unit tests that I would have debugging the code, had I not written the unit tests.

Not only do I do TDD, I work outside-in, i.e. I first implement the top/gui layer TDD. Implementing the top layer defines the requirements for the next layer in the system, which I develop using TDD, etc. until all code required for the feature has been implemented. Often, I experience that after I have implemented a feature like this, and I smoke test the feature in the actual system, it works the first time. Not all the time, but often.

And given that it takes a lot longer to smoke test a feature in the actual system than it takes to execute a couple of unit tests, I save humongous amounts of time. It is actually quicker for me to implement a feature using TDD than it is to not implement the feature not writing unit tests at all.

But writing unit tests is a skill that has to be learned and mastered, just like any other programming skill. When I started doing TDD I had 12 years of professional experience with programming, and I was a very accomplished programmer. I thought that writing large test suites for the system code would be a simple thing. But as the amount of test code grew, and different parts of the system got changed, and existing tests had to be modified, I learned that structuring and writing unit test is in itself a skill that has to be learned and mastered. Also not all code is equally testable. The system code has to be very loosely coupled in order to be efficiently testable. Actually learning TDD has helped me making the system code more loosely coupled.

But my current efficiency in working TDD comes from a combination of both mastering how to write unit tests, but also mastering the technology the system is implemented in (C# in this case).

Doing TDD while learning a new technology can be difficult, e.g. though I've been doing a bit of iPhone programming, I am not writing a significant amount of unit tests, because I do not master the language, objective c, nor do I master the library. So I have no idea how to structure my unit tests, even less how to structure the system code how to make it testable.

But how well does it work on real projects?

On the project I have been working on for the last couple of years, although there is a requirement that code should be sufficiently covered by unit tests, I am the only on the team writing the tests firsts. But the large test suite does give me confidence in being able to refactor the system, and have faith the system will work correctly if the test suite passes.

But unfortunately because many of the tests are written after the system code, quite a few of the tests themselves are faulty, i.e. they don't really test what they were intended to test. This imho cannot be avoided. Every time you write a piece of code, there is a probability of the code not working as you intended, i.e. there is a bug. The same goes for test code. Therefore there is a probability that you write a test that passes even though the code that it should be testing isn't working as intended.

Writing the test first, verifying not just that that you get a test failure, but that the test fails with exactly the error message you expect before implementing the system code seriously reduces the risk of a bug in the unit test code.

So to sum it up, in my experience once you have mastered the art of TDD, you will not just save time in the long run, you will save time up front. But it takes time, even for an experienced programmer, to master the art of TDD. And it takes even longer for a team of developers of varying skill to master the art of TDD.