答:
Thread safety means correctness in the face of the exponentially many possible interactions between concurrent processes. Many concurrency-related bugs occur only in a small minority of possible interleavings (but still occur in production because "One in a million is next Tuesday"). Additionally, testing in general is better at finding bugs than assuring their absence. These facts combined mean that software testing has a very hard time giving any confidence for the absence of thread safety bugs.

There is a lot of research into improving this state, by devising techniques that more efficiently find an interleaving that triggers a bug. However, the cost/benefit ration is still rather bad compared to testing for other kinds of bugs.

A more effective approach may be to adopt discipline that is guaranteed to prevent data races. For example, data that is not shared between threads at all doesn't cause problems, and immutable data can't cause data races either. This means using better abstractions than shared-everything-mutable-memory with bare locks. Actors, message passing, map-reduce, fork-join workers that don't share data (serialize the accumulation of the partial results), and other paradigms have greater probability of correct code. Even if these tools can't express everything you'd like to parallelize, you can try doing as much as possible with them.

Unfortunately, Java the language doesn't provide a lot of tools to enforce such discipline, but using libraries/frameworks that provide them and perhaps perform run-time checks are better than nothing. There are also tools (for C++ at least, don't know if something similar exists for Java) that try to enforce proper locking discipline by associating the secured data with the lock and trying to make sure the data is not accessed while the lock isn't held.

Title: Testing concurrency/thread-safety

Body:
A program I have wrote uses multiple threads and I believe my program is thread-safe but how can I really know?

I've read a number of examples online and none of them describe how to test the code is actually thread-safe or not, nor have I found a reliable way to cause a conflict.

Most of what I've tested regarding concurrency has mostly been cross your fingers and hope stuff. Indeed there have been a few instances where the code would conflict on a regular basis, but what can I do to reassure the people using my code, and myself, that the code is robust and reliable?


问:
Why would a program use a closure?
After reading many posts explaining closures here I'm still missing a key concept: Why write a closure?  What specific task would a programmer be performing that might be best served by a closure?

Examples of closures in Swift are accesses of an NSUrl and using the reverse geocoder. Here is one such example. Unfortunately, those courses just present the closure; they do not explain why the code solution is written as a closure.

An example of a real world programming problem that might trigger my brain to say, "aha, I should write a closure for this", would be more informative than a theoretical discussion.  There is no shortage of theoretical discussions available on this site.

答:
There are two main use cases for closures:

Asynchrony.   Let's say you want to perform a task that will take a while, and then do something when it's done.  You can either make your code wait for it to be done, which blocks further execution and can make your program unresponsive, or call your task asynchronously and say "begin this long task in the background, and when it completes, execute this closure", where the closure contains the code to execute when it's done.

Callbacks.  These are also known as "delegates" or "event handlers" depending on the language and platform.  The idea is that you have a customizable object that, at certain well-defined points, will execute an event, which runs a closure passed in by the code that sets it up.  For example, in your program's UI you might have a button, and you give it a closure that holds the code to be executed when the user clicks on the button.

There are several other uses for closures, but those are the two main ones.

ContentLicense: CC BY-SA 3.0

Title: Why would a program use a closure?


问:
Clean Code comments vs class documentation
I'm having some discussions with my new colleagues regarding commenting. We both like Clean Code, and I'm perfectly fine with the fact that inline code comments should be avoided and that class and methods names should be used to express what they do.

However, I'm a big fan of adding small class summaries that tries to explain the purpose of the class and what is actually represents, primarily so that its easy to maintain the single responsibility principle pattern. I'm also used to adding one-line summaries to methods that explains what the method is supposed to do. A typical example is the simple method

```<code>public Product GetById(int productId) {...}
</code>```

I'm adding the following method summary

```<code>/// <summary>
/// Retrieves a product by its id, returns null if no product was found.
/// </summary
</code>```

I believe that the fact that the method returns null should be documented. A developer that wants to call a method should not have to open up my code in order to see if the method returns null or throws an exception. Sometimes it's part of an interface, so the developer doesn't even know which underlying code is running?

However, my colleagues think that these kinds of comments are "code smell" and that "comments are always failures" (Robert C. Martin).

Is there a way to express and communicate these types of knowledge without adding comments? Since I'm a big fan of Robert C. Martin, I'm getting a bit confused. Are summaries the same as comments and therefore always failures?

This is not a question about in-line comments.

答:
There are some excellent answers here and I don't want to repeat what they say. But let me add a few comments. (No pun intended.)

There are lots of statements that smart people make -- about software development and many other subjects, I suppose -- that are very good advice when understood in context, but which silly people than take out of context or apply in inappropriate situations or take to ridiculous extremes.

The idea that code should be self-documenting is one such excellent idea. But in real life, there are limitations on the practicality of this idea.

One catch is that the language may not provide features to document what needs to be documented clearly and concisely. As computer languages improve, this becomes less and less of an issue. But I don't think it has completely gone away. Back in the days when I wrote in assembler, it made a lot of sense to include a comment like "total price=price of non-taxable items plus price of taxable items plus price of taxable items * tax rate". Exactly what was in a register at any given moment was not necessarily obvious. It took many steps to do a simple operation. Etc. But if you're writing in a modern language, such a comment would just be a restatement of one line of code.

I always get annoyed when I see comments like, "x=x+7; // add 7 to x". Like, wow, thanks, if I had forgotten what a plus sign means that might have been very helpful. Where I might really be confused is in knowing what "x" is or why it was required to add 7 to it at this particular time. This code might be made self-documenting by giving a more meaningful name to "x" and using a symbolic constant instead of 7. Like if you had written "total_price=total_price + MEMBERSHIP_FEE;", then a comment is probably not needed at all.

It sounds great to say that a function name should tell you exactly what a function does so that any additional comments would be redundant. I have fond memories of the time I wrote a function that checked if an item number was in our database Item table, returning true or false, and which I called, "ValidateItemNumber". Seemed like a decent name. Then someone else came along and modified that function to also create an order for the item and update the database, but never changed the name. Now the name was very misleading. It sounded like it did one small thing, when really it did much more. Later someone even took out the part about validating the item number and did that somewhere else, but still didn't change the name. So even though the function now had nothing to do with validating item numbers, it was still called ValidateItemNumber.

But in practice, it is often impossible for a function name to completely describe what the function does without the name of the function being as long as the code that makes up that function. Is the name going to tell us exactly what validations are performed on all parameters? What happens on exception conditions? Spell out every possible ambiguity? At some point the name would get so long that it just becomes confusing. I'd accept String BuildFullName(String firstname, String lastname) as a decent function signature. Even though that does not spell out whether the name is expressed "first last" or "last, first" or some other variation, what it does if one or both parts of the name are blank, if it imposes limits on the combined length and what it does if that's exceeded, and dozens of other detail questions one might ask.


答:
By way of explanation, I'm going to borrow some code from this excellent blog post about closures. It's JavaScript, but that's the language most blog posts that talk about closures use, because closures are so important in JavaScript.

Let's say you wanted to render an array as an HTML table. You could do it like this:

function renderArrayAsHtmlTable (array) {
  var table = "
";
  for (var idx in array) {
    var object = array[idx];
    table += "
" + object + "
";
  }
  table += "
";
  return table;
}
```
<p>But you're at the mercy of JavaScript as to how each element in the array will be rendered. If you wanted to control the rendering, you could do this:</p>
<pre class="lang-javascript prettyprint-override"><code>function renderArrayAsHtmlTable (array, renderer) {
  var table = "<table>";
  for (var idx in array) {
    var object = array[idx];
    table += "<tr><td>" + renderer(object) + "</td></tr>";
  }
  table += "</table>";
  return table;
}
</code>```

And now you can just pass a function that returns the rendering you want.

What if you wanted to display a running total in each Table Row? You would need a variable to track that total, wouldn't you? A closure allows you to write a renderer function that closes over the running total variable, and allows you to write a renderer that can keep track of the running total:

function intTableWithTotals (intArray) {
  var total = 0;
  var renderInt = function (i) {
    total += i;
    return "Int: " + i + ", running total: " + total;
  };
  return renderObjectsInTable(intArray, renderInt);
}
```

The magic that is happening here is that renderInt retains access to the total variable, even though renderInt is repeatedly called and exits.

In a more traditionally object-oriented language than JavaScript, you could write a class that contains this total variable, and pass that around instead of creating a closure. But a closure is a much more powerful, clean and elegant way of doing it.

Further Reading

MDN on Closures

How do JavaScript closures work?

Title: Why would a program use a closure?

Body:
After reading many posts explaining closures here I'm still missing a key concept: Why write a closure?  What specific task would a programmer be performing that might be best served by a closure?

Examples of closures in Swift are accesses of an NSUrl and using the reverse geocoder. Here is one such example. Unfortunately, those courses just present the closure; they do not explain why the code solution is written as a closure.

An example of a real world programming problem that might trigger my brain to say, "aha, I should write a closure for this", would be more informative than a theoretical discussion.  There is no shortage of theoretical discussions available on this site.

Body:
By way of explanation, I'm going to borrow some code from this excellent blog post about closures. It's JavaScript, but that's the language most blog posts that talk about closures use, because closures are so important in JavaScript.

Let's say you wanted to render an array as an HTML table. You could do it like this:

function renderArrayAsHtmlTable (array) {
  var table = "<table>";
  for (var idx in array) {
    var object = array[idx];
    table += "<tr><td>" + object + "</td></tr>";
  }
  table += "</table>";
  return table;
}

But you're at the mercy of JavaScript as to how each element in the array will be rendered. If you wanted to control the rendering, you could do this:

function renderArrayAsHtmlTable (array, renderer) {
  var table = "<table>";
  for (var idx in array) {
    var object = array[idx];
    table += "<tr><td>" + renderer(object) + "</td></tr>";
  }
  table += "</table>";
  return table;
}

And now you can just pass a function that returns the rendering you want.

What if you wanted to display a running total in each Table Row? You would need a variable to track that total, wouldn't you? A closure allows you to write a renderer function that closes over the running total variable, and allows you to write a renderer that can keep track of the running total:

function intTableWithTotals (intArray) {
  var total = 0;
  var renderInt = function (i) {
    total += i;
    return "Int: " + i + ", running total: " + total;
  };
  return renderObjectsInTable(intArray, renderInt);
}

The magic that is happening here is that renderInt retains access to the total variable, even though renderInt is repeatedly called and exits.

In a more traditionally object-oriented language than JavaScript, you could write a class that contains this total variable, and pass that around instead of creating a closure. But a closure is a much more powerful, clean and elegant way of doing it.

Further Reading

MDN on Closures

How do JavaScript closures work?


问:
Testing concurrency/thread-safety
A program I have wrote uses multiple threads and I believe my program is thread-safe but how can I really know?

I've read a number of examples online and none of them describe how to test the code is actually thread-safe or not, nor have I found a reliable way to cause a conflict.

Most of what I've tested regarding concurrency has mostly been cross your fingers and hope stuff. Indeed there have been a few instances where the code would conflict on a regular basis, but what can I do to reassure the people using my code, and myself, that the code is robust and reliable?

答:
You have not told us what kind of multi-threading you do, but I presume you do multi-threading of the locking kind, (you use the synchronized keyword of java,) otherwise you probably would not be asking the question.

As testing has gained ground in the software engineering discipline during the last decade or so, multi-threading of the locking kind has fallen from favor proportionally.  That's because multi-threading code of the locking kind cannot really be tested.

Instead, the modern line of thinking with respect to multi-threading is to prefer mechanisms which eliminate dependencies between threads. This way, the code can be properly tested in a sequential fashion, and it is (sort of) guaranteed to work when put in parallel threads, because the parallel threads do not depend on each other.

One very important tool for accomplishing this is message passing.  This means that each thread receives data to operate upon in a message queue, and sends processed data out via another message queue.  The messages are immutable objects, so it is impossible for one thread to inadvertently modify the contents of a message, causing corruption in a different thread.  Essentially, locking is still used, but it is localized in just one small class, the class that implements the actual message queue, which can be safely be presumed to already be thoroughly tested and in perfect working order.

If you have a lot of data to process, you might think that collecting it and packaging it into immutable objects and placing it in queues might represent a significant overhead, but actually this tends to be offset (sometimes greatly offset) by the fact that once a thread has a chunk of data to process, it can work on it without having to keep locking it all the time. You see, every time you try to lock something which happens to already be locked by another thread, your thread gets placed in a waiting state, which is a huge performance penalty.

Title: Testing concurrency/thread-safety


问:
Loop Invariants in Python
I have a bit of experience with loop invariants but I'm not really clear on them. I'm trying to learn them through an example in Python. Can someone point one out or help me understand? </p>

<p>I've searched both on programmers.SX and on the web but the only things I could find were invariants and design by contract -- nothing on loop invariants. </p>

答:
I found a very good explanation, which includes an example of usage, here:

http://www.cs.uofs.edu/~mccloske/courses/cmps144/invariants_lec.html

The example with red and blue marbles in the jar totally explained the trick.
I will try to summarise so that the answer complies with stack rules (some parts might be a copy-paste of the original).

-Suppose there is a jar and it contains a certain amount N of RED or BLUE marbles (N >=1).

-You also have an unlimited amount of RED marbles on the side.

```<code>PROCEDURE:

while (N > 1):
   pick any two marbles from the jar

   if (marbles have same colour):
      remove marbles
      put 1 RED marble in the jar

   else:  // marble have different colour
      remove picked RED marble
      put picked BLUE marble back
</code>```

Examining this procedure you can see that N decreases by one at each iteration.
So, if you know that at the beginning the jar contained N marbles, after N-1 loops it will contain only 1. This is an intuitive but informal argument that "loop terminates after finitely many iterations".

Suppose the amount of RED and BLUE marbles in the jar is initially known. Let's try to predict the colour of the last marble in the jar at the end of the procedure.

Formally, we are trying to find a function

```<code>f: N × N --> {BLUE, RED},

domain: set of ordered pairs of natural numbers,

range: is the set {BLUE, RED})
</code>```

that satisfies the following condition:

```<code>For all K and M (such that at least one of them is non-zero),
if we begin with K RED marbles and M BLUE marbles in the jar,
then the last marble remaining in the jar is necessarily of color f(K,M).
</code>```

The way to identify this function is to first find an invariant of the loop that works on the amount of BLUE marbles in the jar.

Considering one iteration of the loop and its effect on the number of BLUE marbles:

```<code>Case 1: both marbles have same colour:
    subcase 1.1: marbles are BLUE (number of BLUE marble decreases by 2)
    subcase 1.2: marbles are RED (number of BLUE marble stays the same)

Case 2: marbles have different colour: (number of BLUE marble stays the same)
</code>```

We can appreciate how one single loop iteration has no effect on the parity of the number of BLUE marbles. M will remain odd or even (depending on the beginning state) as a result of the iteration.

This property will hold true for any number of iterations.

```<code>Let us denote:
 Big_K the number of BLUE marbles in the jar at the beginning
 small_k the number of BLUE marbles currently in the jar

then an invariant of the loop is:

  small_k is odd if and only if Big_K is odd

This can be also expressed in a different way:

  (both Big_K and small_k are odd) or (both Big_K and small_k are even)
</code>```

Suppose the number of BLUE marbles initially in the jar, Big_K, were odd.
"Recall that because a loop invariant holds at the end of every iteration, it holds, in particular, at the end of the last iteration."

Then the last marble in the jar must be BLUE, because otherwise small_k = 0 (even).
Similarly, if Big_K were even, the last marble must be RED, because otherwise k = 1 (odd).

Function f is as follows:

```<code>f(Big_K,M) = { RED   if Big_K is even
            { BLUE  if Big_K is odd
</code>```

all credit goes to
Robert McCloskey
http://www.cs.uofs.edu/~mccloske/
for his very helpful explanation on Loop Invariants

Title: Loop Invariants in Python

Body:
I found a very good explanation, which includes an example of usage, here:

http://www.cs.uofs.edu/~mccloske/courses/cmps144/invariants_lec.html

The example with red and blue marbles in the jar totally explained the trick.
I will try to summarise so that the answer complies with stack rules (some parts might be a copy-paste of the original).

-Suppose there is a jar and it contains a certain amount N of RED or BLUE marbles (N >=1).

-You also have an unlimited amount of RED marbles on the side.

PROCEDURE:

while (N > 1):
   pick any two marbles from the jar

   if (marbles have same colour):
      remove marbles
      put 1 RED marble in the jar

   else:  // marble have different colour
      remove picked RED marble
      put picked BLUE marble back

Examining this procedure you can see that N decreases by one at each iteration.
So, if you know that at the beginning the jar contained N marbles, after N-1 loops it will contain only 1. This is an intuitive but informal argument that "loop terminates after finitely many iterations".

Suppose the amount of RED and BLUE marbles in the jar is initially known. Let's try to predict the colour of the last marble in the jar at the end of the procedure.

Formally, we are trying to find a function

f: N × N --> {BLUE, RED},

domain: set of ordered pairs of natural numbers,

range: is the set {BLUE, RED})

that satisfies the following condition:

For all K and M (such that at least one of them is non-zero),
if we begin with K RED marbles and M BLUE marbles in the jar,
then the last marble remaining in the jar is necessarily of color f(K,M).

The way to identify this function is to first find an invariant of the loop that works on the amount of BLUE marbles in the jar.

Considering one iteration of the loop and its effect on the number of BLUE marbles:

Case 1: both marbles have same colour:
    subcase 1.1: marbles are BLUE (number of BLUE marble decreases by 2)
    subcase 1.2: marbles are RED (number of BLUE marble stays the same)

Case 2: marbles have different colour: (number of BLUE marble stays the same)

We can appreciate how one single loop iteration has no effect on the parity of the number of BLUE marbles. M will remain odd or even (depending on the beginning state) as a result of the iteration.

This property will hold true for any number of iterations.

Let us denote:
 Big_K the number of BLUE marbles in the jar at the beginning
 small_k the number of BLUE marbles currently in the jar

then an invariant of the loop is:

  small_k is odd if and only if Big_K is odd

This can be also expressed in a different way:

  (both Big_K and small_k are odd) or (both Big_K and small_k are even)

Suppose the number of BLUE marbles initially in the jar, Big_K, were odd.
"Recall that because a loop invariant holds at the end of every iteration, it holds, in particular, at the end of the last iteration."

Then the last marble in the jar must be BLUE, because otherwise small_k = 0 (even).
Similarly, if Big_K were even, the last marble must be RED, because otherwise k = 1 (odd).

Function f is as follows:

f(Big_K,M) = { RED   if Big_K is even
            { BLUE  if Big_K is odd

all credit goes to
Robert McCloskey
http://www.cs.uofs.edu/~mccloske/
for his very helpful explanation on Loop Invariants


问:
Count amount of points for XY options (in poll) where options dont have equal amount of points
I have a code where I want to avoid using a for/each loop to count the amount of points options in poll have together. Reason is, every option has different ammount of points and I want to get number of votes by counting options and points they have together and then dividing total points (votes) by those points...

I have a list of options where every option has a different amount of points. I think this is easier to understand:

Option 1 = 7 points

Option 2 = 6 points

Option 3 = 5 points

Option 4 = 4 points

Option 5 = 3 points

Option 6 = 2 points

Option 7 = 1 point

Is there some easy math way of getting to number of points (in this case 28) without using:

```<code>$options = array("lala", "lalala", "flflf", "qddwq", "adslalsd", "wqdqowdq", "acaca");
$points = 0; $i = 1;
foreach($options as $option){
    $points = $points + $i;
    $i++;
}
echo $points;
</code>```

Or

```<code>$points = 0;
$options_num = 7;

for ($i=1; $i <= $options_num; $i++){
      $points = $points + $i;
}
echo $points;
</code>```

I just want to make as small load on the server as possible, mainly when users won't be limited with amount of options they can insert and I am sure there has to be some simple math I can use, but I'm just not getting it.

答:
The sum

```<code>7 + 6 + 5 + 4 + 3 + 2 + 1 = 28
</code>```

Corresponds to a Triangular Number of the form

```<code>(n * (n + 1)) / 2
</code>```

i.e. (7 * (7 + 1) / 2 = 28.

Body:
The sum

7 + 6 + 5 + 4 + 3 + 2 + 1 = 28

Corresponds to a Triangular Number of the form

(n * (n + 1)) / 2

i.e. (7 * (7 + 1) / 2 = 28.


问:
Member: Use unique IDs vs domain object
After a couple of useful answers on whether I should use domain object or a unique id as method/function parameter here Identifier vs domain object as a method parameter , I have a similar question re: members (the previous questions discussion didn't manage to cover this).
What are the pros and cons of using unique IDs as member vs object as member. I'm asking in reference to strongly typed languages, like Scala/C#/Java. Should I have
(1)

```<code>User( id: Int, CurrentlyReadingBooksId: List[Int])
Book( id: Int, LoanedToId: Int )
</code>```

or (2), preferred to (1) After going through: Should we define types for everything?

```<code>User( id: UserId, CurrentlyReadingBooksId: List[ BookId] )
Book( id: BookId, LoanedToId: UserId )
</code>```

or (3)

```<code>User( id: Int, CurrentlyReadingBooks: List[Book])
Book( id: Int, LoanedTo: User)
</code>```

While I cannot think of benefits to having the object (3), one benefits to having IDs (2) & (1) is that when I am creating the User object from DB, I don't have to create the Book object, which may in turn depend on the User object itself, creating an endless chain. Is there a generic solution to this problem for both RDBMS and No-SQL (if they are different)?

Based on some answers so far, rephrasing my question: (with use of IDs supposed to be in wrapped types)
1) Always use IDs?
2) Always use Objects?
3) Use IDs when there is a risk of recursion in serializing and deserializing, but use objects otherwise?
4) Anything else?

EDIT: If you answer that Objects should be used always or for some cases, please make sure to answer the biggest concern other answerers have posted => How to get data from DB

答:
Yes, there are benefits to either way, and there's also a compromise.

List<int>:

Save memory

Faster initialization of type User

If your data comes from a relational database (SQL), you don't have to access two tables to get users, just the Users table

List<Book>:

Accessing a book is faster from user, the book has been preloaded into memory. This is nice if you can afford to have a longer start up in order to get faster subsequent operations.

If your data comes from a document store database like HBase or Cassandra then the values of books read are likely on the User record, so you could have easily gotten the books "while you were there getting the user".

If you have no memory or CPU concerns I would go with List<Book>, the code that uses the User instances will be cleaner.

Compromise:

When using Linq2SQL, the code generated for the entity User will have a EntitySet<Book> which is lazy loaded when you access it. This should keep your code clean and the User instance small (memory footprint wise).

Title: Member: Use unique IDs vs domain object


问:
How to design a class to check if geometric figures collide?
I am making a basic game with geometric figures.

I am trying to design now how to calculate if the figure collides with another figure in an Array List of figures (called entitiesList).

I have:

```<code>Class Entity {
   ...
   public boolean collidesWith(Entity anotherEntityInMap) {}
}
</code>```

But I can't figure out how I  should make this. I guess I must know what kind of figure is anotherEntity. For example, I can have squares, triangles and circles. Each figure has diverse calculations, and it must be abstracted.

答:
The most academically proper way of doing it would be to have a two-dimensional matrix of collision detection methods, one method for each possible pair of figures, so each method would have knowledge of precisely what figures are being checked, so as to do the checking in the best way possible.  Unfortunately, this is too much work for very little benefit.

The quickest, dirtiest, simplest, hackiest and most inaccurate way of doing it would be to treat all shapes equally, consider them all to be circles, and just check the distance between their centerpoints to determine if they collide.

A practical solution which is not too difficult to implement and yields accurate results is to have each shape contain a polygon representation of itself, and simply make use of a single polygon collision detection algorithm to detect collision between the polygon representations of any two shapes.


答:
First, you can wrap some common logic in all shapes.

Try to see if objects collide according to their AABB; all shapes implement getAABB().

You may also call getBoundingBox() or getBoundingSphere() before trying to check if they really intersect.

The above should allow you to quickly filter all shapes that certainly do not collide (your bounding boxes are over-approximations of your shapes). But if there remain entities for which over-approximations overlap, you cannot be sure that they do not collide and you have to be more precise. You may implement douple-dispatch:

Typically, this is done using a Visitor.

Each shape, Rectangle, Circle implements collideWithRectangle, collideWithCircle, and so on...

You want to avoid repeating yourself, so if you implement a test for Rectangle against Circle, you can reverse the arguments when checking for collision between a Circle and a Rectangle and call the existing method.

Complex entities are most of the time easily represented by a union of simpler shapes, but you can also use arbitrary polygons.

Title: How to design a class to check if geometric figures collide?

Body:
I am making a basic game with geometric figures.

I am trying to design now how to calculate if the figure collides with another figure in an Array List of figures (called entitiesList).

I have:

```<code>Class Entity {
   ...
   public boolean collidesWith(Entity anotherEntityInMap) {}
}
</code>```

But I can't figure out how I  should make this. I guess I must know what kind of figure is anotherEntity. For example, I can have squares, triangles and circles. Each figure has diverse calculations, and it must be abstracted.


答:
Robert Harvey's comment about emitting a circle from the center to approximate the shape was good.  You can alternatively use rectangles/triangles on a 2D surface, such as in your game, or a rectangular prism / some triangular equivalent in a 3D environment.  You may also divide each of your shapes into a collection of these smaller shapes to approximate the actual shape on a finer scale (using elliptical or straight-edged shapes), and this is basically how a lot of CPU-heavy games run as efficiently as they do.

That being said, you could make all these objects extend the same base class.  Then in that class, there would be an overridable method/property called getCollisionComponentShapes, which would return an array or ArrayList of the shapes.  This would be the elliptical shapes, rectangles, and/or triangles mentioned earlier that would be used to approximate the polygon.  That reduces everything to, let's say, three functions, assuming you just stick with straight-edged shapes:

```<code>detectCollisionReRe(pRect1:Rectangle, pRect2:Rectangle):Boolean
detectCollisionReTr(pRect1:Rectangle, pTri2:Triangle):Boolean
detectCollisionTrTr(pTri1:Triangle, pTri2:Triangle):Boolean
</code>```

Then in your base class, there would be a presumably static method:

```<code>detectCollisionShapes(pBaseClassRef1:BaseClass, pBaseClassRef2:BaseClass):Boolean
</code>```

and this would just run through the collision shapes of each instance and run one of the three functions above for each combination.

This would be one big way to handle the general case.  In your geometry game, I would advise going ahead and using some sort of generic ellipse shape with variable curvature for your components, in addition to rectangles and triangles.  Even with variable curvature, you can use sophomore-level math, and that'll only bring the list up to six functions.

As a side note, you probably wouldn't need this in your game, but if you were designing a AAA game, it might be good to look for ways to cache results and cut corners in other ways.

Body:
Robert Harvey's comment about emitting a circle from the center to approximate the shape was good.  You can alternatively use rectangles/triangles on a 2D surface, such as in your game, or a rectangular prism / some triangular equivalent in a 3D environment.  You may also divide each of your shapes into a collection of these smaller shapes to approximate the actual shape on a finer scale (using elliptical or straight-edged shapes), and this is basically how a lot of CPU-heavy games run as efficiently as they do.

That being said, you could make all these objects extend the same base class.  Then in that class, there would be an overridable method/property called getCollisionComponentShapes, which would return an array or ArrayList of the shapes.  This would be the elliptical shapes, rectangles, and/or triangles mentioned earlier that would be used to approximate the polygon.  That reduces everything to, let's say, three functions, assuming you just stick with straight-edged shapes:

detectCollisionReRe(pRect1:Rectangle, pRect2:Rectangle):Boolean
detectCollisionReTr(pRect1:Rectangle, pTri2:Triangle):Boolean
detectCollisionTrTr(pTri1:Triangle, pTri2:Triangle):Boolean

Then in your base class, there would be a presumably static method:

detectCollisionShapes(pBaseClassRef1:BaseClass, pBaseClassRef2:BaseClass):Boolean

and this would just run through the collision shapes of each instance and run one of the three functions above for each combination.

This would be one big way to handle the general case.  In your geometry game, I would advise going ahead and using some sort of generic ellipse shape with variable curvature for your components, in addition to rectangles and triangles.  Even with variable curvature, you can use sophomore-level math, and that'll only bring the list up to six functions.

As a side note, you probably wouldn't need this in your game, but if you were designing a AAA game, it might be good to look for ways to cache results and cut corners in other ways.


问:
What is the difference between requirements and specifications?
I've been tasked with developing requirements and specifications for a project our group is starting.

I realized that I don't know the difference; a Google search just confused me more -- it seems some people say that specifications are requirements, but at a lower level.

答:
In my research, I have found Specifications to be used for patents and House Construction (as part of a contract).

The definition of a requirement from Webster's Unabridged Dictionary (3rd New Int'l Ed.) is:

a) something that is wanted or needed: Necessity
 b) something called for or demanded: a requisite or essential condition: a required    quality, course, or kind of training

I think the above shows them to be clearly different.  I guess you could call spec's lower level requirements, but I think it is a perversion of the term requirement imho.


问:
With sufficiently advanced static typing, what are the advantages of dynamic type systems?
This question appears to be fairly well tread, for example:

Do dynamic typed languages deserve all the criticism?

What is the supposed productivity gain of dynamic typing?

etc.

However, most questions and answers seem to compare statically typed languages like Java and C++ with dynamically typed languages like Python and JavaScript. This seems to be a different comparison - Java and C++ are verbose, non-interactive, and generally difficult to work with for reasons outside of their type systems.

I'm more interested in using static languages like Swift or Haskell as the basis of the comparison.

These languages have REPLs, interactive coding, or equivalents

These languages have type inference (as does C++)

These languages have easy-to-use "generics"

These languages have ADTs, which solves problems like JSON parsing

We can imagine a variant of Swift with a form of Structural Typing, where:

```<code>func foo(bar) { return bar.baz() }
</code>```

Is valid syntax for any call in which an object with a baz() member is passed, and the return type is that of the object's baz() - effectively creating an anonymous protocol Foo<T> with member func baz() -> T.

This can be translated to JavaScript by s/func/function/g, but all of the type safety would be lost.

What's the advantage of dynamic typing, compared a static typed language with a good type system?

答:
Fundamentally, if the type system is there, the programmer has to deal with it. It can be made rather "flexible" (i.e., stays out of your way in situations where  type system like Java's would be a pain) and implicit (so type annotations can be left out when they don't add value), but the programmer has to deal with it. Even if every practical, correct program needs no type annotations at all and "just works" (a pipe dream IMHO), programmers do write wrong programs — catching those mistakes is the whole point of a type system, after all.

Presented with an type error, the programmer then needs to understand the type system to understand the error. In general type systems that allow more implicitness and are more flexible (in the aforementioned sense) are more complex and harder to understand. Of course, for a given degree of implicitness and flexibility, good design and good error messages can make a difference, but there is a limit. That is not to say this is a bad trade off, but it is a trade off.

In practice, the type systems you name don't fulfill the above condition of correct programs "just working". You may argue that they enforce better programming style, and I'd agree, but they reject valid programs of the style people actually write. This causes friction. There are many upsides, of course, but you seem to suggest that one can just stop writing JavaScript and get all the correctness guarantees for free. That is not true, one has to understand the type system and get used to phrasing programs in a way the type system understands. As an example, in Haskell you can't just have subtyping and inheritance. This is a trade off that buys Haskell certain advantages, and it's a perfectly valid school of design, but it also makes different designs harder to implement.


答:
The purpose of closures is simply to preserve state; hence the name closure - it closes over state.
For the ease of further explanation, I'll use Javascript.

Typically you have a function

```<code>function sayHello(){
    var txt="Hello";
    return txt;
}
</code>```

where the scope of the variable(s) is bound to this function. So after execution the variable txt goes out of scope. There is no way of accessing or using it after the function has finished execution.

Closures are language construct, which allow - as said earlier - to preserve the state of the variables and so prolong the scope.

This could be useful in different cases. One use case is the construction of higher order functions.

In mathematics and computer science, a higher-order function (also functional form, functional or functor) is a function that does at least one of the following:1

takes one or more functions as an input

outputs a function

A simple, but admittely not all too useful example is:

```<code> makeadder=function(a){
     return function(b){
         return a+b;
     }
 }

 add5=makeadder(5);
 console.log(add5(10));
</code>```

You define a function makedadder, which takes one parameter as input and returns a function. There is an outer function function(a){} and an inner function(b){}{}.Further you define (implicitely) another function add5 as the result of calling the higher order funtion makeadder. makeadder(5) returns an anonymous (inner) function, which in turn takes 1 parameter and returns the sum of the parameter of the outer function and the parameter of the inner function.

The trick is, that while returning the inner function, which does the actual adding, the scope of the parameter of the outer function (a) is preserved. add5 remembers, that the parameter a was 5.

Or to show one at least somehow usefull example:

```<code>  makeTag=function(openTag, closeTag){
     return function(content){
         return openTag +content +closeTag;
     }
 }

 table=makeTag("<table>","</table>")
 tr=makeTag("<tr>", "</tr>");
 td=makeTag("<td>","</td>");
 console.log(table(tr(td("I am a Row"))));
</code>```

Another common usecase is the so called IIFE = immediately invoked function expression.
It is very common in javascript to fake private member variables. This is done via a function, which creates a private scope = closure, because it is immediatly after definition invoked. The structure is function(){}(). Notice the brackets () after the definition.
This makes it possible to use it for object-creation with revealing module pattern.
The trick is creating a scope and returning an object, which has access to this scope after execution of the IIFE.

Addi's example looks like this:

```<code> var myRevealingModule = (function () {

         var privateVar = "Ben Cherry",
             publicVar = "Hey there!";

         function privateFunction() {
             console.log( "Name:" + privateVar );
         }

         function publicSetName( strName ) {
             privateVar = strName;
         }

         function publicGetName() {
             privateFunction();
         }

         // Reveal public pointers to
         // private functions and properties

         return {
             setName: publicSetName,
             greeting: publicVar,
             getName: publicGetName
         };

     })();

 myRevealingModule.setName( "Paul Kinlan" );
</code>```

The returned object has references to functions (e.g. publicSetName), which in turn have access to "private" variables privateVar.

But these are more special use cases for Javascript.

What specific task would a programmer be performing that might be best served by a closure?

There are several reasons for that. One might be, that it is natural for him, since he follows a functional paradigm. Or in Javascript: it is mere necessity to rely on closures to circumvent some quirks of the language.

Title: Why would a program use a closure?

Body:
The purpose of closures is simply to preserve state; hence the name closure - it closes over state.
For the ease of further explanation, I'll use Javascript.

Typically you have a function

function sayHello(){
    var txt="Hello";
    return txt;
}

where the scope of the variable(s) is bound to this function. So after execution the variable txt goes out of scope. There is no way of accessing or using it after the function has finished execution.

Closures are language construct, which allow - as said earlier - to preserve the state of the variables and so prolong the scope.

This could be useful in different cases. One use case is the construction of higher order functions.

In mathematics and computer science, a higher-order function (also functional form, functional or functor) is a function that does at least one of the following:1

takes one or more functions as an input

outputs a function

A simple, but admittely not all too useful example is:

 makeadder=function(a){
     return function(b){
         return a+b;
     }
 }

 add5=makeadder(5);
 console.log(add5(10));

You define a function makedadder, which takes one parameter as input and returns a function. There is an outer function function(a){} and an inner function(b){}{}.Further you define (implicitely) another function add5 as the result of calling the higher order funtion makeadder. makeadder(5) returns an anonymous (inner) function, which in turn takes 1 parameter and returns the sum of the parameter of the outer function and the parameter of the inner function.

The trick is, that while returning the inner function, which does the actual adding, the scope of the parameter of the outer function (a) is preserved. add5 remembers, that the parameter a was 5.

Or to show one at least somehow usefull example:

  makeTag=function(openTag, closeTag){
     return function(content){
         return openTag +content +closeTag;
     }
 }

 table=makeTag("<table>","</table>")
 tr=makeTag("<tr>", "</tr>");
 td=makeTag("<td>","</td>");
 console.log(table(tr(td("I am a Row"))));

Another common usecase is the so called IIFE = immediately invoked function expression.
It is very common in javascript to fake private member variables. This is done via a function, which creates a private scope = closure, because it is immediatly after definition invoked. The structure is function(){}(). Notice the brackets () after the definition.
This makes it possible to use it for object-creation with revealing module pattern.
The trick is creating a scope and returning an object, which has access to this scope after execution of the IIFE.

Addi's example looks like this:

 var myRevealingModule = (function () {

         var privateVar = "Ben Cherry",
             publicVar = "Hey there!";

         function privateFunction() {
             console.log( "Name:" + privateVar );
         }

         function publicSetName( strName ) {
             privateVar = strName;
         }

         function publicGetName() {
             privateFunction();
         }

         // Reveal public pointers to
         // private functions and properties

         return {
             setName: publicSetName,
             greeting: publicVar,
             getName: publicGetName
         };

     })();

 myRevealingModule.setName( "Paul Kinlan" );

The returned object has references to functions (e.g. publicSetName), which in turn have access to "private" variables privateVar.

But these are more special use cases for Javascript.

What specific task would a programmer be performing that might be best served by a closure?

There are several reasons for that. One might be, that it is natural for him, since he follows a functional paradigm. Or in Javascript: it is mere necessity to rely on closures to circumvent some quirks of the language.


问:
How can I maintain my technical skills after becoming a project manager?
As I advance in my career, I have found that I do less technical work and more project management work.  I joke that I am getting dumber every day.  Each time I go back to doing technical work it seems to be a little harder to get things going.  What suggestions do people have for maintaining technical expertise throughout your career?</p>

答:
Been there for a while.

Understand that PMs normally don't do coding.

If you stick to doing both you might end up being below average in either.

If you want to become a PM, fight for a position that doesn't require you to do coding.

Also, figure out if becoming a PM is really an advance in your career. Excellent engineers
might earn more than average PMs.

ContentLicense: CC BY-SA 2.5


答:
Closures are equivalent to objects implementing a run() method, and inversely, objects can be emulated with closures.

The advantage of closures is that they can be used easily anywhere you expect a function: a.k.a. higher-order functions, simple callbacks (or Strategy Pattern). You don't need to define an interface/class to build ad-hoc closures.

The advantage of objects is the possibility to have more complex interactions: multiple methods and/or different interfaces.

So, using closure or objects is mostly a matter of style. Here is an example of things that closures make easy but is inconvenient to implement with objects:

 (let ((seen))
    (defun register-name (name)
       (pushnew name seen :test #'string=))

    (defun all-names ()
       (copy-seq seen))

    (defun reset-name-registry ()
       (setf seen nil)))
```

<p>Basically, you encapsulate a hidden state that is accessed only through global closures: you don't need to refer to any object, only use the protocol defined by the three functions.</p>

<hr>

<ul>
<li>I am extending the answer to address this comment from supercat*. </li>
</ul>

<p>I trust supercat's first comment on the fact that in some languages, it is possible to control precisely the lifetime of objects, whereas the same thing is not true for closures. In the case of garbage-collected languages, however, the lifetime of objects are generally unbounded, and it is thus possible to build a closure that could be called in a dynamic context where it should not be called (reading from a closure after a stream is closed, for example).</p>

<p>However, it is quite simple to prevent such misuse by capturing a control variable that will guard the execution of a closure. More precisely, here is what I have in mind (in Common Lisp):</p>

<pre class="lang-lisp prettyprint-override"><code>(defun guarded (function)
  (let ((active t))
    (values (lambda (&rest args)
              (when active
                (apply function args)))
            (lambda ()
              (setf active nil)))))
</code>```

Here, we take a function designator function and return two closures, both of them capturing a local variable named active:

the first one delegates to function, only when active is true

the second one sets action to nil, a.k.a. false.

Instead of (when active ...), it is of course possible to have an (assert active) expression, which could throw an exception in case the closure is called when it should not be. Also, keep in mind that the unsafe code might already throw an exception by itself when used badly, so you rarely need such a wrapper.

Here is how you would use it:

(use-package :metabang-bind) ;; for bind

(defun example (obj1 obj2)
  (bind (((:values f f-deactivator)(guarded (lambda () (do-stuff obj1))))
         ((:values g g-deactivator)(guarded (lambda () (do-thing obj2)))))

    ;; ensure the closure are inactive when we exit
    (unwind-protect
         ;; pass closures to other functions
         (progn
           (do-work f)
           (do-work g))

      ;; cleanup code: deactivate closures
      (funcall f-deactivator)
      (funcall g-deactivator))))
```

Note that the desactivating closures could also be given to other functions as well; here, the local active variables are not shared between f and g; also, in addition to active, f only refers to obj1 and g only refers to obj2.

The other point mentioned by supercat is that closures can lead to memory leaks, but unfortunately, it is the case for almost everything in garbage-collected environments.
If they are available, this can be solved by weak pointers (the closure itself might be kept in memory, but does not prevent garbage-collection of other resources).

Title: Why would a program use a closure?

Body:
Closures are equivalent to objects implementing a run() method, and inversely, objects can be emulated with closures.

The advantage of closures is that they can be used easily anywhere you expect a function: a.k.a. higher-order functions, simple callbacks (or Strategy Pattern). You don't need to define an interface/class to build ad-hoc closures.

The advantage of objects is the possibility to have more complex interactions: multiple methods and/or different interfaces.

So, using closure or objects is mostly a matter of style. Here is an example of things that closures make easy but is inconvenient to implement with objects:

 (let ((seen))
    (defun register-name (name)
       (pushnew name seen :test #'string=))

    (defun all-names ()
       (copy-seq seen))

    (defun reset-name-registry ()
       (setf seen nil)))

Basically, you encapsulate a hidden state that is accessed only through global closures: you don't need to refer to any object, only use the protocol defined by the three functions.

I am extending the answer to address this comment from supercat*.

I trust supercat's first comment on the fact that in some languages, it is possible to control precisely the lifetime of objects, whereas the same thing is not true for closures. In the case of garbage-collected languages, however, the lifetime of objects are generally unbounded, and it is thus possible to build a closure that could be called in a dynamic context where it should not be called (reading from a closure after a stream is closed, for example).

However, it is quite simple to prevent such misuse by capturing a control variable that will guard the execution of a closure. More precisely, here is what I have in mind (in Common Lisp):

(defun guarded (function)
  (let ((active t))
    (values (lambda (&rest args)
              (when active
                (apply function args)))
            (lambda ()
              (setf active nil)))))

Here, we take a function designator function and return two closures, both of them capturing a local variable named active:

the first one delegates to function, only when active is true

the second one sets action to nil, a.k.a. false.

Instead of (when active ...), it is of course possible to have an (assert active) expression, which could throw an exception in case the closure is called when it should not be. Also, keep in mind that the unsafe code might already throw an exception by itself when used badly, so you rarely need such a wrapper.

Here is how you would use it:

(use-package :metabang-bind) ;; for bind

(defun example (obj1 obj2)
  (bind (((:values f f-deactivator)(guarded (lambda () (do-stuff obj1))))
         ((:values g g-deactivator)(guarded (lambda () (do-thing obj2)))))

    ;; ensure the closure are inactive when we exit
    (unwind-protect
         ;; pass closures to other functions
         (progn
           (do-work f)
           (do-work g))

      ;; cleanup code: deactivate closures
      (funcall f-deactivator)
      (funcall g-deactivator))))

Note that the desactivating closures could also be given to other functions as well; here, the local active variables are not shared between f and g; also, in addition to active, f only refers to obj1 and g only refers to obj2.

The other point mentioned by supercat is that closures can lead to memory leaks, but unfortunately, it is the case for almost everything in garbage-collected environments.
If they are available, this can be solved by weak pointers (the closure itself might be kept in memory, but does not prevent garbage-collection of other resources).


问:
Is an application supposed to recover from a exception thrown in PHP?
What if the programmer uses Exceptions for debugging? Would it be better in that case to just report the failure and immediately interrupt the script since ideally all bugs should be fixed radically?

Is this a correct way of using exceptions in PHP?

Related reading: exceptions in PHP

Thanks

答:
It depends

Based on what your application is doing and the necessity of the function that threw the exception will determine whether to fail immediately or continue processing.

For instance:

Scenario 1:

User attempts to update their password.

Password hashing function fails and throws an exception

In this case the application should interrupt immediately and display an error to the user.

Scenario 2:

User is navigating through site, interacting normally

Process updates last seen timestamp (ie- this user was last seen 5 minutes ago...)

Update fails and throws an exception

In this case, I would argue, the application should fail silently (but still logging the issue) and continue working as normal from the user's point of view.

Essentially, if critical functionality is broken due to an exception, interrupt immediately, otherwise gracefully degrade (and log).


答:
What you're probably looking for are assertions, not exceptions.

In general, exceptions should be thrown when something bad is happening that you can't do anything about in the current code scope.  For example, your function's purpose is to open a file, but the file specified in the function's parameter is not present on the storage medium.

Exceptions shouldn't be used as a generalized debug mechanism.  If you want to know whether something is happening or not in a script, log it, capture the behavior in a unit test, or examine it using a debugger, rather than using an exception.

Exceptions signal something that you expect to happen, even though it's an error condition that you cannot do anything about.  You might reasonably expect that someone will hand you the path to a file that does not exist.  But that doesn't mean that your code is incorrect; it just means that the caller didn't provide adequate conditions to succeed.

Assertions are different; they signal a problem with your code.  They are more semantically correct to use for debugging purposes than exceptions, which have a different purpose.

Title: Is an application supposed to recover from a exception thrown in PHP?

Body:
What if the programmer uses Exceptions for debugging? Would it be better in that case to just report the failure and immediately interrupt the script since ideally all bugs should be fixed radically?

Is this a correct way of using exceptions in PHP?

Related reading: exceptions in PHP

Thanks


答:
This is not specific to PHP, so I will answer the general case.

There are two types of failures in web applications:

Script failed to initialize. Examples: could not connect to database; required header file not found; other fatal error.

Script initialized, but there is an error condition in the business logic. Examples: user enters incorrect password.

In the first case there is not much you can do to handle the error other than put up a generic white page saying "sorry, site's broke." In the second case you can easily trap the error and output something meaningful to the user even if it is "sorry, can't do that, try something else."

If you cannot continue processing due to a fatal error, kill the page. Cut your losses and go home. If you can continue processing, then do so.

But, what if the programmer uses Exceptions for debugging?

Why would you put in special exceptions for debugging in production? Sure, go ahead and throw random exceptions in dev or test to test your error-handling logic, but in production you want to be as safe as possible. Specifically for web applications, this means:

Never leak sensitive data such as filesystem paths, file names (e.g. *.inc files in PHP), or database credentials.

Never leak database schema information even for known applications (e.g. WordPress or other open-source web applications).

Never leak variable names or other internal data that may give an attacker clues as to how to exploit your web application.

Never output unsanitized data.

Always try to give the user an out: can you at least spit out a link to make it easy to retry the operation or go to a safe page (e.g. /)?


问:
What is the difference between K&R and One True Brace Style (1TBS) styles?
I have read the Wikipedia article on Indent Styles, but I still don't understand. What is the difference between K&R and 1TBS?</p>

答: The problem, in general with KR brace style is in code refactoring.  When moving code around it is easy to miss that there are no braces around something, move it incorrectly (or move something under it thinking it is conditionally executed) and then either scratch your head when something no longer works, or be unfortunate and be in a code area not well tested and the bug goes unnoticed until a black hat finds a way to exploit it.  A quick trip into the debugger easily finds the problem if you notice it, but if you don't...</p>


问:
Should I try to separate state from implementation?
Right now I'm working with some code that combines state and operations.

It looks something like this (note: doesn't actually deal with Cars/Trucks. I'm abstracting the business logic here, and apologize in advance that the analogy doesn't entirely make sense)

TruckImpl {
    // Fields/Properties
    int Mileage
    bool MissionAccomplished
    // ... and many, many more

    // Constructor
    TruckImpl TruckImpl(IRentalAgreement agreement)

    // methods
    void Drive() {
        // Sets a whole bunch of fields/properties which are subsequently used to make decisions in Park()
        GetCarFromDealer()
        Haul()
    }
    void GetCarFromDealer()
    void Haul()

    // Return to rental company if done, otherwise park at home
    void Park()
}

CarImpl {
    // Fields
    int Mileage
    bool MissionAccomplished

    // Constructor
    CarImpl CarImpl(IRentalAgreement agreement)

    // methods
    // Sets a whole bunch of fields/properties which are subsequently used to make decisions in Park()
    void Drive() {
        // Sets a whole bunch of fields/properties which are subsequently used to make decisions in Park()
        GetCarFromDealer()
        Race()
    }
    void GetCarFromDealer()
    void Race()

    // Return to rental company if done, otherwise park at home
    void Park()
}
```

<p>It's used in some code that looks similar to the following pseudocode:</p>

<pre class="lang-cpp prettyprint-override"><code>RentalVehicleHandler {
    IVehicleImplFactory factory;

    Handle(IRentalAgreement agreement) {
        impl = factory.Create(agreement)

        impl.Drive()
        impl.Park()
    }
}

Main() {
    while(true) {
    var agreements = GetAgreements();

    foreach(var agreement in agreements) {
        handler.Handle(agreement)
    }

}
</code>```

In the above code, we're getting batches of "RentalAgreements", but still processing each of them individually. Now, I want to handle Cars and Trucks slightly separately. For Trucks, I will still Drive() then Park() each individually. For Cars, I want to GetCarFromDealer() individually, but then Race() the entire batch of cars at once before Parking them. I might want to do something similar for Trucks in the future, but maybe not.

I thought that it would be helpful to separate my state from my implementation like below: (to start, no batching-related stuff added yet):

// One per rental agreement
RentalVehicle {
    #Properties
    RentalAgreement agreement
    int Mileage
    bool MissionAccomplished
    //(...all of the TruckImpl propertiies?)
}

// Can handle any number of RentalAgreements, maybe multiple
CarDriver {

    RentalVehicle Drive(RentalVehicle vehicle)
    RentalVehicle Park(RentalVehicle vehicle)
}

TruckDriver {
    RentalVehicle Drive(RentalVehicle vehicle)
    RentalVehicle Park(RentalVehicle vehicle)
}
```

Is this a helpful/reasonable thing to do? Or is it just a bunch of extra work that will gain me no advantage?  I think it will help me both with the problem at hand and help me with further refactoring, but I've also tried a few other things that were dead-ends and I don't want to spend a bunch of time refactoring this for no reason.

答:
This is perfectly reasonable. In fact, that change is a textbook example of the functional programming paradigm, which is gradually becoming more popular these days.

The key ideas from functional programming that are relevant here are that you should strive to have mostly pure functions with no state or side effects and mostly immutable variables that get defined once and never change. When striving for this, it's typical to end up writing code like State finalState = changeStuff(initialState), which is basically what you have in your last snippet. If you do this, I would go all the way and make RentalVehicle an immutable type (which I think in C# is done by making its properties readonly).

The benefit of pure immutable things is simply that they are a lot easier to reason about than mutable stateful side-effecty things. If a function has no side effects, and its return value depends solely on what arguments you pass it, then it's not going to surprise you very often. The main drawback (if we ignore performance concerns) is that the real world is stateful, and so are many of the things that our code has to do. Going 100% functional for all of your renting, hauling and racing logic is probably not a good idea unless you have enough functional programming experience to find such code intuitive (or you're working in a functional language that has tools like monads to make it easier). However, splitting your code into "pure" and "impure" parts is often a good idea no matter what you're working on, as it limits the places where you have to worry about error-prone mutable state manipulations (again, assuming any potential performance loss is a non-issue).

I can't tell you whether that particular part of the codebase would actually benefit from more purity, but it's certainly not an unreasonable thing to try.


问:
Dealing with date fields across browsers
I'm building a web application with multiple forms which all require date fields, and these fields need to be supported across IE, Chrome, and the like.

Our application currently packages the output of the forms as a JSON object which we feed into GsonBuilder to convert them into a java object for persistence.

Our GsonBuilder object currently accepts a format of 'yyyy-MM-dd'. In Chrome, our forms seem to be utilizing HTML5, which include a date picker in the date fields, and the browser seemingly does some magic and GsonBuilder accepts the date with no issues. In IE, however, there is no date picker and the users need to hand-bomb a date, which has to be in the exact specified format for GsonBuilder to accept the field.

So today I've been trying to work out what a good solution to this problem would be, and there are almost so many possibilities that it seems hard to identify the proper one to use.

So far I've considered using the jquery mask plugin to enforce the proper format in IE, however I don't know how this would work in Chrome as the date fields include a date picker which already enforce format.

I've also considered propagating a specific server error back up to the front-end when a user enters an incorrect format in IE. This seems like a bad solution because it would cause guessing games for the user.

Surely, at some point I need to enforce data integrity in IE, but I am not sure what the best way of doing this is. Is there a common pattern that people use to deal with this issue?

答: You could just use a date picker polyfill like https://github.com/chemerisuk/better-dateinput-polyfill</p>


问:
Method documents differs between Java docs and Android docs
Some times I see problematic differences between Java doc and Android doc in about method documents.For example in about setReadable (boolean readable, boolean ownerOnly) method you can see java doc says that:

Throws: SecurityException - If a security manager exists and its
  SecurityManager.checkWrite(java.lang.String) method denies write
  access to the file

But Android docs does not say any thing about throwing exception.Also we know that Docs say:

Any Exception that can be thrown by a method is part of the method's
  public programming interface. Those who call a method must know about
  the exceptions that a method can throw so that they can decide what to
  do about them.

So when we do not see any throw condition in Android documents of a method,

Does it mean method will not throw exception any way?Or it may be forgotten?

Do we need to check documents for any simple method for probability difference between Java and Android?Is it possible?

Note:
I know that

Dalvik, the virtual machine used in Google's Android platform, uses a
  subset of Harmony for the core of its Class Library.

But I do not think that means possibility of different implementation of a same method in same class.

答:
Yes, it is very possible to to have different implementations of the same methods in the same class between Android and Oracle Java.

Remember, Android does not use the JVM. The only similarity between Android's Java and Oracle's Java is the API. Android does not use traditional Java, it uses an API that is "Java-like".

For instance, there is a difference in implementation between Oracle's HTTPURLConnection and Android's HTTPURLConnection. The methods in that class do not behave the same way between platforms.

In your particular example, remember you are comparing two different platforms. The Android platform has a permissions model and a different way to handle file management, so it kind of makes sense why API for file management would differ between the two.

This does not mean that there no similar methods in Android's Java that throw Exceptions, just that this particular one does not. If you are more familiar with Oracle's Java than you are with the Android platform, I would recommend treating the Android platform as different from what you may be used to.


问:
Which SPDX license is equivalent to 'All Rights Reserved'?
I've got a package.json that's expecting a SPDX-approved license acronym, but I can't find one that means 'proprietary commercial license, all rights reserved'.

Is there one for non-FOSS, where I want to specify that I want to allow no reuse?

答:
As of npm 3.10 you have to use UNLICENSED:

{ "license": "UNLICENSED"}
```
<p>or</p>
<pre class="lang-json prettyprint-override"><code>{ "license": "SEE LICENSE IN <filename>"}
</code>```

The value of license must either one of the options above or the identifier for the license from this list of SPDX licenses. Any other value is not valid.

The following is no longer valid for current versions of npm

For npm versions before 3.10 you may use:

{ "license" : "LicenseRef-LICENSE" }
```
<p>Then include a <code>LICENSE</code> file at the top level of the package. It could be as short as:</p>
```(c) Copyright 2015 person or company, all rights reserved.
```

But you might want to be more explicit about what is not allowed.

Body:
As of npm 3.10 you have to use UNLICENSED:

{ "license": "UNLICENSED"}

or

{ "license": "SEE LICENSE IN <filename>"}

The value of license must either one of the options above or the identifier for the license from this list of SPDX licenses. Any other value is not valid.

The following is no longer valid for current versions of npm

For npm versions before 3.10 you may use:

{ "license" : "LicenseRef-LICENSE" }

Then include a LICENSE file at the top level of the package. It could be as short as:

(c) Copyright 2015 person or company, all rights reserved.

But you might want to be more explicit about what is not allowed.

ContentLicense: CC BY-SA 4.0


问:
GPLv3 frontend and BSD backend, do I have to disclose the backend source?
I've gone through a couple of Question on GPL here, but all of them are related to the compiled languages, libraries and distribution.

My web project has a backend that is BSD licensed. The front end is a GPLv3 licensed JavaScript framework which renders a background image that doesn't link to anything from the backend and only renders in the web browser.

Am I required to make available the backend code to the public if I use the GPLv3 licensed library? We are not modifying the GPLv3 licensed library, just using it as is.

Update

I've contacted the library author here is his reply:

I am not a lawyer, so all I can say is that The Library is made
  available under the GPLv3. Including it as a dependency in a
  commercial program does not, to my understanding, violate GPLv3.
  Including a modified version of it without releasing the source to the
  modified version would.

答:
This could be argued either way.  Sencha, makers of ExtJS, claim that if you use the GPLv3 version of Extjs in the frontend, the combined work (both frontend and backend) are covered by the GPL:

For example: let’s take a mortgage processing software program. Let’s say that the application has a front-end (that generates web pages linked to Ext JS JavaScript) that communicates over JSON/HTTP with a backend service. This backend service contains approval and validation logic for this application alone. Even if only the front-end uses Ext JS code, you should consider that the combination of front and back ends constitutes the application, and the source code for both back and front end would need to be provided to the application’s end users under GPLv3 if the application is used by an end-user who is not part of the same legal entity that holds the GPLv3 license to the Ext JS code.

However they also say that ancillary functions provided by a separate backend may not be considered part of the combined work.

http://www.sencha.com/legal/open-source-faq/

No clear answer is possible without many more details. I'd start by asking the owner of the GPL code to see how they interpret it.


问:
Why would a program use a closure?
After reading many posts explaining closures here I'm still missing a key concept: Why write a closure?  What specific task would a programmer be performing that might be best served by a closure?

Examples of closures in Swift are accesses of an NSUrl and using the reverse geocoder. Here is one such example. Unfortunately, those courses just present the closure; they do not explain why the code solution is written as a closure.

An example of a real world programming problem that might trigger my brain to say, "aha, I should write a closure for this", would be more informative than a theoretical discussion.  There is no shortage of theoretical discussions available on this site.

答:
A couple of other examples:

Sorting

Most sort functions operate by comparing pairs of objects. Some comparison technique is needed. Restricting the comparison to a specific operator means a rather inflexible sort. A much better approach is to receive a comparison function as an argument to the sort function. Sometimes a stateless comparison function works fine (e.g., sorting a list of numbers or names), but what if the comparison needs state?

For example, consider sorting a list of cities by distance to some specific location. An ugly solution is to store the coordinates of that location in a global variable. This makes the comparison function itself stateless, but at the cost of a global variable.

This approach precludes having multiple threads simultaneously sorting the same list of cities by their distance to two different locations. A closure that encloses the location solves this problem, and it gets rid of the need for a global variable.

Random numbers

The original rand() took no arguments. Pseudorandom number generators need state. Some (e.g., Mersenne Twister) need lots of state. Even the simple but terrible rand() needed state. Read a math journal paper on a new random number generator and you'll inevitably see global variables. That's nice for the developers of the technique, not so nice for the callers. Encapsulating that state in a structure and passing the structure to the random number generator is one way around the global data problem. This is the approach used in many non-OO languages to making a random number generator reentrant. A closure hides that state from the caller. A closure offers the simple calling sequence of rand() and the reentrancy of encapsulated state.

There's more to random numbers than just a PRNG. Most people who want randomness want it distributed a certain way. I'll start with numbers randomly drawn from between 0 and 1, or U(0,1) for short. Any PRNG that generates integers between 0 and some maximum will do; simply divide (as a floating point) the random integer by the maximum. A convenient and generic way to implement this is to create a closure that takes a closure (the PRNG) and the maximum as inputs. Now we have a generic and easy to use random generator for U(0,1).

There are a number of other distributions besides U(0,1). For example, a normal distribution with a certain mean and standard deviation. Every normal distribution generator algorithm I've run across uses a U(0,1) generator. A convenient and generic way to create a normal generator is to create a closure that encapsulates the U(0,1) generator, the mean, and the standard deviation as state. This is, at least conceptually, a closure that takes a closure that takes a closure as an argument.

Title: Why would a program use a closure?


问:
Application development with fully dynamic controls and processes based on database
All software development projects are moving into separation of design, logic , data in patterns like MVC , MVVM and others.

Strangely i got a very strange requirement for a new software; that is :

It is required to have all controls/fields of the screen to be based in the database with their access rules which user is allowed to see which field or control

This is requested so the clients DB Admin be able to remove any field from the screen or change access level(view edit,none) of any field to a user!

I have suggested other ways of maintaining user access and roles, but the client is insisting of having everything each and every single screen control in the database to have full control on the software's screen content by their DB admin.

Is this way of maintaining screen and their content and controls in database has a name or is there a design pattern for that ?!
i know doing the software in this will harm the client but can't provide enough justification for that.

My question is : Is doing software in the described way is recommended or not and why?

答:
First off, be aware of the Inner platform effect and do everything in your power to avoid it. Even if you do go the ultra-flexible route, the key to actually succeeding is ironically to fully understand its pitfalls.

However, if a platform of this flexibility is truly what is needed/what management knows it thinks it wants... at least avoid reinventing the DB inside the DB. Databases are dynamic and you application can create its own tables as well as examining their structures so avoid making massive key/value table. To do this, make a MetaRepository class that is responsible for creating/reading the table structures of your on the fly tables.

Usually having a business logic layer is a good idea, but here, it may just get in the way since adding any specific business logic for a dynamically generated entity may prove to be very difficult.

MVC is great, even if you have to use a dynamic view model. I have never seen a GUI application that does not benefit from MVC.

Getting back to your final question, DO EVERYTHING POSSIBLE TO AVOID GOING DOWN THIS ROUTE! There is already an application that can be configured to do anything you need it to... it's called a code compiler...


答:
PHP can be used to help to show a real example in a different language.

```<code>protected function registerRoutes($dic)
{
  $router = $dic['router'];

  $router->map(['GET','OPTIONS'],'/api/users',function($request,$response) use ($dic)
  {
    $controller = $dic['user_api_controller'];
    return $controller->findAllAction($request,$response);
  })->setName('api_users');
}
</code>```

So basically I am registering a function which will be executed for the /api/users URI. This is actually a middleware function which ends up being stored on a stack. Other functions will be wrapped around it. Pretty much like Node.js/Express.js does.

The dependency injection container is available (via the use clause) inside the function when it gets called. It's possible to make some sort of route action class, but this code turns out to be simpler, faster and easier to maintain.

Title: Why would a program use a closure?

Body:
PHP can be used to help to show a real example in a different language.

protected function registerRoutes($dic)
{
  $router = $dic['router'];

  $router->map(['GET','OPTIONS'],'/api/users',function($request,$response) use ($dic)
  {
    $controller = $dic['user_api_controller'];
    return $controller->findAllAction($request,$response);
  })->setName('api_users');
}

So basically I am registering a function which will be executed for the /api/users URI. This is actually a middleware function which ends up being stored on a stack. Other functions will be wrapped around it. Pretty much like Node.js/Express.js does.

The dependency injection container is available (via the use clause) inside the function when it gets called. It's possible to make some sort of route action class, but this code turns out to be simpler, faster and easier to maintain.


问:
Testing concurrency/thread-safety
A program I have wrote uses multiple threads and I believe my program is thread-safe but how can I really know?

I've read a number of examples online and none of them describe how to test the code is actually thread-safe or not, nor have I found a reliable way to cause a conflict.

Most of what I've tested regarding concurrency has mostly been cross your fingers and hope stuff. Indeed there have been a few instances where the code would conflict on a regular basis, but what can I do to reassure the people using my code, and myself, that the code is robust and reliable?

答:
You can't (realistically) prove thread safety exhaustively for a language like Java, but there are ways to detect some bugs.

The official behaviour of your Java program when run on several threads is defined by Chapter 17 of the JLS. The only way to prove that a program is thread safe is by applying all those rules in a theoretical way, which in most scenarios is too complex.

There are a few static analysis tools that can help, such as FindBugs, but they will only cover the most obvious errors.

There are some stress testing tools such as jcstress that will run your code many times until they get confident that they behave as expected - but some concurrency bugs will only appear on specific hardware / JVMs. For example the memory model of x86 CPUs is fairly strong and will never display concurrency bugs that would show up on weaker memory models.

Similarly, some JVMs will optimise your code more aggressively then others and will trigger more bugs by doing so (for example: variable hosting).

In the end, a reasonable path is a combination of:

in-depth understanding of the memory model to avoid as many pitfalls as possible at design time

a good testing framework (e.g. jcstress) that you run on various computers (mixing OSes and CPUs) to hopefully spot any remaining issues

Title: Testing concurrency/thread-safety


问:
Is using nested try-catch blocks an anti-pattern?
Is this an antipattern? It is an acceptable practice?</p>

```<code>    try {
        //do something
    } catch (Exception e) {
        try {
            //do something in the same line, but being less ambitious
        } catch (Exception ex) {
            try {
                //Do the minimum acceptable
            } catch (Exception e1) {
                //More try catches?
            }
        }
    }
</code>```

答:
There nothing mentioned as Anti Pattern in java anywhere.
Yes we call few things good practice and bad practice.

If a try/catch block is required inside a catch block its required you cant help it.
And there is no alternative. As a catch block can't work as try part if exception is thrown.

For Example :

```<code>String str=null;
try{
   str = method(a);
}
catch(Exception)
{
try{
   str = doMethod(a);
}
catch(Exception ex)
{
  throw ex;
}
</code>```

Here in the above example  method throws exception but the doMethod (used for handling method exception) even throw exception. In this case we have to use the try catch within try catch.

some thing which is suggested not to do is ..

```<code>try
{
  .....1
}
catch(Exception ex)
{
}
try
{
  .....2
}
catch(Exception ex)
{
}
try
{
  .....3
}
catch(Exception ex)
{
}
try
{
  .....3
}
catch(Exception ex)
{
}
try
{
  .....4
}
catch(Exception ex)
{
}
</code>```

Body:
There nothing mentioned as Anti Pattern in java anywhere.
Yes we call few things good practice and bad practice.

If a try/catch block is required inside a catch block its required you cant help it.
And there is no alternative. As a catch block can't work as try part if exception is thrown.

For Example :

String str=null;
try{
   str = method(a);
}
catch(Exception)
{
try{
   str = doMethod(a);
}
catch(Exception ex)
{
  throw ex;
}

Here in the above example  method throws exception but the doMethod (used for handling method exception) even throw exception. In this case we have to use the try catch within try catch.

some thing which is suggested not to do is ..

try
{
  .....1
}
catch(Exception ex)
{
}
try
{
  .....2
}
catch(Exception ex)
{
}
try
{
  .....3
}
catch(Exception ex)
{
}
try
{
  .....3
}
catch(Exception ex)
{
}
try
{
  .....4
}
catch(Exception ex)
{
}


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
What's the simplest thing that could
  possibly work?

— Ward Cunningham

LastEditorDisplayName: Roger Pate


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答: that as a programmer you know everything about latest hardware trends, overclocking, case mod, etc. friends and relatives consult you when they buy their gears.</p>


问:
How do you go about understanding others' code?
What do you do to understand some code that you didn't write? Or code that you wrote long time ago and don't remember what it does anymore.

Do you have some technique that you go about? Do you analyze the structures first, or the public methods, or do you draw flow charts, etc.? Or do you fire up the debugger and just step through it? Or do you just ad-hoc your way through until you understand it?

答:
I use a mix of:

Writing tests for it

Changing it to see how it break

Refactoring

Not necessarily in this order :-) It's astonishing how much easier it becomes to understand what a piece of code does after some refactoring.


答:
Not an anti-pattern per se, but a code pattern that tells you need to refactor.

And it's pretty easy, you just have to know a rule of thumb which is writing no more than a try block in the same method. If you know well to write related code together, usually is just copying and pasting each try block with its catch blocks and pasting it inside a new method, and then replace the original block with a call to this method.

This rule of thumb is based on Robert C. Martin's suggestion from his book 'Clean Code':

if the keyword 'try' exists in a function, it should be the very first
  word in the function and that there should be nothing after the
  catch/finally blocks.

A quick example on "pseudo-java". Suppose we have something like this:

```<code>try {
    FileInputStream is = new FileInputStream(PATH_ONE);
    String configData = InputStreamUtils.readString(is);
    return configData;
} catch (FileNotFoundException e) {
    try {
        FileInputStream is = new FileInputStream(PATH_TWO);
        String configData = InputStreamUtils.readString(is);
        return configData;
    } catch (FileNotFoundException e) {
        try {
            FileInputStream is = new FileInputStream(PATH_THREE);
            String configData = InputStreamUtils.readString(is);
            return configData;
        } catch (FileNotFoundException e) {
            return null;
        }
    }
}
</code>```

Then we could refactor each try catch and in this case each try-catch block tries the same thing but in different locations (how convenient :D), we have only to copy paste one of the try-catch blocks and make a method of it.

```<code>public String loadConfigFile(String path) {
    try {
        FileInputStream is = new FileInputStream(path);
        String configData = InputStreamUtils.readString(is);
        return configData;
    } catch (FileNotFoundException e) {
        return null;
    }
}
</code>```

Now we use this with the same purpose as before.

```<code>String[] paths = new String[] {PATH_ONE, PATH_TWO, PATH_THREE};

String configData;
for(String path : paths) {
    configData = loadConfigFile(path);
    if (configData != null) {
        break;
    }
}
</code>```

I hope that helps :)

Title: Is using nested try-catch blocks an anti-pattern?

Body:
Is this an antipattern? It is an acceptable practice?</p>

```<code>    try {
        //do something
    } catch (Exception e) {
        try {
            //do something in the same line, but being less ambitious
        } catch (Exception ex) {
            try {
                //Do the minimum acceptable
            } catch (Exception e1) {
                //More try catches?
            }
        }
    }
</code>```

Body:
Not an anti-pattern per se, but a code pattern that tells you need to refactor.

And it's pretty easy, you just have to know a rule of thumb which is writing no more than a try block in the same method. If you know well to write related code together, usually is just copying and pasting each try block with its catch blocks and pasting it inside a new method, and then replace the original block with a call to this method.

This rule of thumb is based on Robert C. Martin's suggestion from his book 'Clean Code':

if the keyword 'try' exists in a function, it should be the very first
  word in the function and that there should be nothing after the
  catch/finally blocks.

A quick example on "pseudo-java". Suppose we have something like this:

try {
    FileInputStream is = new FileInputStream(PATH_ONE);
    String configData = InputStreamUtils.readString(is);
    return configData;
} catch (FileNotFoundException e) {
    try {
        FileInputStream is = new FileInputStream(PATH_TWO);
        String configData = InputStreamUtils.readString(is);
        return configData;
    } catch (FileNotFoundException e) {
        try {
            FileInputStream is = new FileInputStream(PATH_THREE);
            String configData = InputStreamUtils.readString(is);
            return configData;
        } catch (FileNotFoundException e) {
            return null;
        }
    }
}

Then we could refactor each try catch and in this case each try-catch block tries the same thing but in different locations (how convenient :D), we have only to copy paste one of the try-catch blocks and make a method of it.

public String loadConfigFile(String path) {
    try {
        FileInputStream is = new FileInputStream(path);
        String configData = InputStreamUtils.readString(is);
        return configData;
    } catch (FileNotFoundException e) {
        return null;
    }
}

Now we use this with the same purpose as before.

String[] paths = new String[] {PATH_ONE, PATH_TWO, PATH_THREE};

String configData;
for(String path : paths) {
    configData = loadConfigFile(path);
    if (configData != null) {
        break;
    }
}

I hope that helps :)


问:
TDD in theory only
A little over a year ago I was fortunate enough to be able to take a 9 month break from work.  I decided that in that time time I would hone my C# skills.  I started working on a bunch of projects and forced myself to follow TDD.

It was a fairly enlightening process.

It was tough at first, but over time I learned how to write more testable code (which, as it turns out, tends to be more SOLID code) and in the process I also sharpened my OO design skill.

Now I'm back in the workforce and I'm noticing something odd.

I prefer not to follow TDD.

I find TDD slows me down and actually makes it harder to design a clean application.

Instead, I've adopted a slightly (massively) different approach:

Pick a vertical slice of work

Develop a functioning prototype

Refactor until everything is nice and tidy

Sit back an appreciate the beautifully SOLID and testable code I've written.

You may have noticed that step 1 wasn't "define the public surface of my test target" and step 2 wasn't "test the bejesus out of said public surface."  You may have also noticed that none of the steps involve testing.  I'm writing testable code, but I'm not testing it... just yet.

Now, I'd like to make it clear that I'm not actually foregoing any kind of testing.  The code I'm writing works.  It works because I'm testing it manually.

I'd also like to make it clear that I'm not foregoing all automated testing either.  This is where my process is different.  And this is why I'm asking this question.

TDD in theory.  Not in practice.

My process has evolved a bit and I've struck a balance between TDD and no tests that I find very productive and also reasonably safe.  It goes as follows:

Implement a working vertical slice of work with testing in mind, but don't write any tests.

If down the road (eg, a month later) that slice needs modification

Write Unit Tests, Integration Tests, Behaviour Tests, etc that guarantee the slice of work is correct

Modify the code

If that slice doesn't need modification,

Do nothing

By simply shifting the burden of writing tests from before writing the code to before modifying the code I've been able to produce much more working code.  And, when I do get around to writing tests I write far fewer of them but cover nearly as much ground (higher ROI).

I like this process, but I'm concerned it might not scale well.  Its success hinges on developers being diligent about writing tests before they change things.  And that seems like a pretty big risk.  But, TDD has the very same risk.

So, am I going to [BT]DD hell, or is this a common form of pragmatic coding and testing?

I'd like to keep working this way.  What can I do to make this process work in the long term?

Note:

I am the sole developer on my projects and I am responsible for everything:  Requirements gathering, design, architecture, testing, deployment, etc.  I suspect this is why my process is working.

答:
This is a good question, and FWIW I'll throw in my two cents.

About a year ago I was coding in Salesforce, a platform which had an ingrained mechanism which forced you to not necessarily write tests before you coded, but rather forced you to write tests in general.

The way it worked was that the system would force you to write tests, and it would make a calculation of the number of lines of your code that were tested into a percentage. If all code throughout your production instance fell below 75% tested .. Salesforce no more work.

The end result of this was that every time you did anything in Salesforce you had to write or update tests. While I'm sure this has a huge impact on the market share of Salesforce, in terms of the life of a developer it was a massive pain in the ass.

A lot of the time you were just trying to get through a small ticket, and then testing comes in and doubles your development time, for a feature that you just know works.

Then the awkward concept of TDD swept through our department, right down to our databases. Our architects wanted to push out thorough testing into every aspect of our IT department. Slight pain in the ass, meet even greater pain in the ass.

Back then TDD never really made sense to me, and even now it still doesn't. A lot of the functionality I've written in my current role takes place in a similar mechanism to that which you've mentioned: in vertical slices which I refine until they work. When I was in that old role, and still now I often don't know what my code is going to do until I actually write it, so the idea that I can write tests to drive the code I'm going to write just.. doesn't make sense to me, is cumbersome, and mostly a waste of time.

All of that said, tests are wonderful and magical things which make everything right in the world. They make your code correct, they ensure your app does what you think it does, and generally everything smoother. The question then isn't whether you write your tests before you code, or after you code, the question is how much time are you going to commit to testing. That's the real problem, at least in my software development experience. Testing takes time and money and you have to do it within the framework of competing interests.

And so, in general I agree with you: TDD in practice is a bit awkward and cumbersome. At that point you need to keep in mind what works best in your current situation. If you're writing critical code, just make sure it's tested in general. If you've got the time, give TDD a try and see if it adds anything to the process.

Title: TDD in theory only