答:
This can be solved by processing one line at a time, without backtracking.  You don't use DFS at all.  I won't rob you of the pleasure of coming to a solution on your own.  I'll just direct your attention to the possible sums of the first four lines:

```<code>9235 + 9096 +  973 + 3399
9235 + 9096 +  973 + 3350
9235 + 9096 + 3269 + 3350
9235 + 9096 + 3269 + 4788
9235 +  637 + 3269 + 3350
9235 +  637 + 3269 + 4788
9235 +  637 + 7039 + 4788
9235 +  637 + 7039 + 2476
</code>```

If you think about processing this one line at a time, you can see there is both a lot of repeated calculations here, and some paths you can obviously eliminate.  For example a path starting with 9235 + 637 + 3269 will always be smaller than a path starting with 9235 + 9096 + 3269, so you can prune it.  Each new line lets you prune almost half of the new paths.  Figure out what those are, and how to avoid repeating the sums, and you'll find the answer is quite simple.

Title: Given a tree calculating Max Sum from top to bottom suing DFS? optimization?

Body:
given a tree i want to calculate max sum of each path from top to bottom. I used DFS for the operation. Here is the function which takes root as input and gives max sum of the path from top to bottom :

```<code>   private int DFS_max(TreeNode root) {
    // TODO Auto-generated method stub
    if(root == null){
        //System.out.println(root.value);
        //System.out.println();
        return 0;
    }

    int lvalue = DFS_max(root.getLeftNode());
    int rvalue = DFS_max(root.getRightNode());

    //System.out.print(root.value+" ");

    return (Math.max(lvalue, rvalue)+root.value );
}
</code>```

however it takes to long time to execute following input:

```<code>9235
9096 637
973 3269 7039
3399 3350 4788 7546
1739 8032 9427 976 2476
703 9642 4232 1890 704 6463
9601 1921 5655 1119 3115 5920 1808
645 3674 246 2023 4440 9607 4112 3215
660 6345 323 1664 2331 7452 3794 7679 3102
1383 3058 755 1677 8032 2408 2592 2138 2373 8718
8117 4602 7324 7545 4014 6970 4342 7682 150 3856 8177
1966 1782 3248 1745 4864 9443 4900 8115 4120 9015 7040 9258
4572 6637 9558 5366 7156 1848 2524 4337 5049 7608 8639 8301 1939
7714 6996 2968 4473 541 3388 5992 2092 2973 9367 2573 2658 9965 8168
67 1546 3243 752 8497 5215 7319 9245 574 7634 2223 8296 3044 9445 120
7064 1045 5210 7347 5870 8487 3701 4301 1899 441 9828 3076 7769 8008 4496 6796
5256 2199 464 5164 4039 1014 8099 7932 1909 3051 4805 1698 8578 1771 5889 5711 9967
6830 2603 9256 3629 2793 5219 6534 8838 944 5113 4981 6811 6958 48 9463 7477 5723 1111
7907 9312 4756 8096 3564 7809 9326 2502 5346 6383 5658 3791 423 701 3417 5042 2669 3759 5017
8754 6389 4368 7284 2150 7288 6145 459 4079 1631 7595 620 2350 171 6401 4222 1182 5561 2669 7641
3335 696 6551 360 454 708 5378 7750 8156 3187 4263 8282 9494 9607 1989 435 1558 5920 909 6567 5174
1771 5573 4603 6962 5957 9870 3482 6287 324 6551 5035 7100 5595 6189 3178 6047 354 4873 1168 3815 8771 1222
8982 6194 3575 3673 5892 5035 8234 8414 7744 6956 6341 6824 4562 9416 6808 8836 1692 9636 609 5238 6918 1685 8565
7610 6713 1077 9905 9328 7107 4166 8230 4864 8540 1762 4870 7483 9504 2516 9634 7336 761 1805 5454 2967 530 6166 6541
9277 1113 1596 9327 4106 9159 6484 1666 3774 5001 6357 8586 5151 1306 8160 2201 8124 7684 6362 9309 7702 5800 1827 2679 9402
9080 7085 1053 5077 2129 8422 8489 8852 7628 6024 5841 4504 2658 8298 5860 6226 2157 5477 8728 4520 4513 590 6642 7711 3209 3005
4500 7462 8825 848 8698 3585 7756 3857 7587 9434 7531 7443 5232 4212 3761 2111 4765 2628 432 9750 8871 5534 3519 9777 2692 7383 7686
3624 8816 7672 7245 5646 4888 3871 5462 2170 1897 2787 823 8107 5186 5782 4911 2313 835 816 4192 8726 7262 903 7191 187 5542 4234 9292
5817 2292 5964 9704 836 5776 5457 9027 9782 9306 5636 1268 250 5976 3032 1188 4460 5327 8071 6400 229 5587 5243 3777 1265 4847 1853 1421 9092
704 2262 685 5345 716 1758 7567 3740 5354 480 9161 5544 1022 3196 8803 1074 3236 5157 3026 2407 9018 7720 4543 9281 3233 13 8065 996 5680 4485
9963 1991 4531 4900 8560 7771 6957 5041 9103 823 9644 5190 6393 3295 291 1344 8459 4311 6189 8997 6670 5018 7465 9360 1255 3737 714 891 6314 6900 3369
3160 5093 8864 404 3212 4571 5136 2730 6864 8175 9081 991 8629 6874 1727 9398 4353 1791 7975 1676 79 6005 173 5249 9092 9272 1827 401 6713 7010 26 8267
8974 4103 5046 5274 6983 4807 9583 1897 3563 2384 8047 476 2499 5930 8452 214 3611 7346 5579 7471 8807 8361 4272 5997 5233 6109 6024 4832 1692 5886 327 1273 3633
1377 4645 2518 160 5935 3329 2396 3755 3272 6328 8905 9729 2328 3103 4238 7738 8995 5798 1396 2157 6902 8463 558 1575 515 5827 3949 234 6437 6012 126 5832 2979 6441
7307 8791 3842 1132 657 7840 9032 640 289 5535 5045 2925 5151 5220 6760 4623 2934 7859 5524 7361 7679 3131 1427 3046 4833 4257 2937 5389 8209 128 3724 2300 4461 1466 4779
5267 8533 9 9710 7333 7839 986 2533 875 3863 9532 147 22 7337 1095 6244 267 7172 4391 9425 9587 3942 3000 5959 1211 5846 8321 6766 8081 8815 2253 9001 2992 2718 2738 4910
6435 2443 9071 4492 6216 6061 6768 3976 9095 2236 3682 9092 4889 5596 70 689 7730 1847 5340 394 7524 4099 3329 5672 7042 8078 6141 6914 6522 6675 3795 4000 8177 3662 3259 6130 7610
2258 5763 6708 7737 6758 5762 4507 3566 4424 8365 3451 2915 465 4607 5963 9007 1072 5565 9005 5753 8196 6975 7712 5498 5059 5742 8816 2030 3209 8568 4937 8719 345 728 1278 2792 3133 9997
8226 1983 721 6701 6953 9027 2801 5895 239 2827 701 1815 7406 2497 1211 7901 525 1956 638 7934 8869 8237 936 5126 9949 6296 633 6368 8425 6713 806 8251 8680 397 316 9989 2901 6176 5180
5883 4165 2973 4063 6614 3168 8186 5624 4303 8055 7803 3721 1023 9048 1845 3325 4237 3518 782 3410 5515 2521 4720 3050 785 6882 7356 3478 1374 9420 981 1986 5142 67 7113 3167 6122 2324 9764 9257
9240 2726 4783 4078 3959 9828 9244 4470 6945 5576 9405 8984 9255 9900 4457 6075 7944 8826 5918 3086 5487 7507 9357 2894 2955 2176 5932 7258 4504 9219 6115 4612 1390 5323 6949 5366 3494 9970 7190 9565 5099
408 1771 233 9549 9691 8154 641 4346 372 2372 5306 4199 9991 1790 2614 4628 9646 4980 1610 2803 3596 6476 6735 5484 6132 5633 2054 6181 1731 4350 891 4916 5913 7961 7657 4368 7146 7280 6168 5573 4644 7463
2764 4872 2984 1130 3119 1307 2067 9021 8833 320 175 1340 3573 5251 8588 6919 8844 2877 8567 5325 6300 3049 5378 9129 6921 5313 9471 9705 7350 7360 1923 107 219 1110 9836 2867 8386 2290 7486 8872 2663 8492 730
5867 8841 8856 5413 1612 2596 5748 5338 7189 203 5146 1741 595 8910 7746 4155 9357 3261 7284 2035 3615 2738 6013 7593 7917 1633 9843 2925 754 4269 7264 8673 5793 7381 6835 7263 7709 6751 7766 1013 8521 7056 6920 4360
7443 2273 3418 9801 8378 8974 8954 9246 4411 6370 7927 5950 7904 5051 6515 7396 8136 1045 3969 6132 5834 3021 2540 3863 5369 8259 4713 3878 938 7348 7709 8282 2613 8476 5590 9457 1787 9665 8699 9658 3258 1318 8696 8707 2945
2046 4951 7421 6082 7912 4707 3529 598 8938 5077 7661 4384 6996 9684 9235 3127 6083 6544 6007 7501 9347 6667 6444 4635 7229 4760 1094 8971 7614 4417 7722 1933 1969 208 5048 8094 1119 8218 1666 7993 522 4744 9958 4152 7693 89
9612 7380 3771 710 1762 5054 7126 8320 2685 1662 9388 8978 5499 4646 3294 8688 9370 5317 7359 4567 8370 5459 4536 2262 6300 5134 733 971 9561 6144 4359 7153 7467 8628 9912 6814 8260 5362 7016 4115 9541 9460 1306 981 3825 6374 5069
8361 3493 390 3674 4850 4541 9096 8460 2493 5224 6751 7965 2760 3920 8877 7202 7919 394 5969 8981 4346 5975 3758 2230 4641 1135 1125 9698 4879 3430 4465 1502 1795 4859 9068 1531 2233 5295 3901 906 3839 7849 6098 6405 1623 2772 5385 2056
9751 8824 6710 8920 1747 4906 1411 1538 5134 184 3420 9440 8450 7965 7169 8679 9609 7117 8177 1438 4561 4963 5590 1412 4378 7282 8360 8899 7026 4281 3187 2305 7333 6235 2890 2116 4971 8843 8424 9320 5605 6329 6432 2684 4828 9772 6893 8386 7931
9250 2232 1035 1163 989 51 7337 1713 4906 6565 2308 4321 3688 6762 3303 2175 1854 321 8894 8548 2141 9426 8111 3471 6968 5728 468 6697 4772 8928 8778 4151 4531 8724 4829 164 6951 5181 2656 1852 7463 9987 5372 5192 4444 2515 9302 4612 5865 120
</code>```

I wanted to optimize this code to run faster ? how can i do it? i am not able to figure out what goes wrong here?

Body:
This can be solved by processing one line at a time, without backtracking.  You don't use DFS at all.  I won't rob you of the pleasure of coming to a solution on your own.  I'll just direct your attention to the possible sums of the first four lines:

9235 + 9096 +  973 + 3399
9235 + 9096 +  973 + 3350
9235 + 9096 + 3269 + 3350
9235 + 9096 + 3269 + 4788
9235 +  637 + 3269 + 3350
9235 +  637 + 3269 + 4788
9235 +  637 + 7039 + 4788
9235 +  637 + 7039 + 2476

If you think about processing this one line at a time, you can see there is both a lot of repeated calculations here, and some paths you can obviously eliminate.  For example a path starting with 9235 + 637 + 3269 will always be smaller than a path starting with 9235 + 9096 + 3269, so you can prune it.  Each new line lets you prune almost half of the new paths.  Figure out what those are, and how to avoid repeating the sums, and you'll find the answer is quite simple.


问:
Why do many exception messages not contain useful details?
It seems there is a certain amount of agreement that exception messages should contain useful details.

Why is it that many common exceptions from system components do not contain useful details?

A few examples:

.NET List index access ArgumentOutOfRangeException does not tell me the index value that was tried and was invalid, nor does it tell me the allowed range.

Basically all exception messages from the MSVC C++ standard library are utterly useless (in the same vein as above).

Oracle exceptions in .NET, telling you (paraphrased) "TABLE OR VIEW not found", but not which one.

So, to me it seems that for the most part exception messages do not contain sufficient details to be useful. Are my expectations out of line? Am I using exceptions wrong that I even notice this? Or maybe my impression is wrong: a majority of exceptions do actually provide useful details?

答:
Exceptions do not contain useful details because the concept of exceptions has not matured yet enough within the software engineering discipline, so many programmers do not understand them fully, and therefore they do not treat them properly.

Yes, IndexOutOfRangeException should contain the precise index that was out of range, as well as the range that was valid at the time that it was thrown, and it is contemptible on behalf of the creators of the .NET runtime that it doesn't.  Yes, Oracle's table or view not found exception should contain the name of the table or view that was not found, and again, the fact that it does not is contemptible on behalf of whoever is responsible for this.

To a large part, the confusion stems from the misguided original idea that exceptions should contain human-readable messages, which in turn stems from a lack of understanding of what exceptions are all about, so it is a vicious cycle.

Since people think that the exception should contain a human-readable message, they believe that whatever information is carried by the exception should also be formatted into the human-readable message, and then they are either bored to write all the human-readable message-building code, or they are afraid that doing so might be divulging an inadvisable amount of information to whatever prying eyes might see the message. (The security issues mentioned by other answers.)

But the truth of the matter is that they should not be worrying about that because the exception should not contain a human-readable message.  Exceptions are things that only programmers should ever see and/or deal with. If there is ever a need to present failure information to a user, that has to be done at a very high level, in a sophisticated manner, and in the user's language, which, statistically speaking, is unlikely to be English.

So, for us programmers, the "message" of the exception is the class name of the exception, and whatever other information is pertinent to the exception should be copied into (final/readonly) member variables of the exception object.  Preferably, every single conceivable little bit of it.  This way, no message needs to (or should) be generated, and therefore no prying eyes can see it.

To address the concern expressed by Thomas Owens in a comment below:

Yes, of course, at some level, you will create a log message regarding the exception. But you already see the problem with what you are saying: on one hand, an exception log message without a stack trace is useless, but on the other hand, you don't want to let the user see the entire exception stack trace.  Again, our problem here is that our perspective is skewed by traditional practices. Log files have traditionally been in plain text, which may have been fine while our discipline was in its infancy, but perhaps not any more: if there is a security concern, then the log file must be binary and/or encrypted.

Whether binary or plain text, the log file should be thought of as a stream into which the application serializes debug information. Such a stream would be for the programmers' eyes only, and the task of generating debugging information for an exception should be as simple as serializing the exception into the debug log stream. This way, by looking at the log you get to see the exception class name, (which, as I have already stated, is for all practical purposes "the message",) each of the exception member variables which describe everything which is pertinent-and-practical-to-include-in-a-log, and the entire stack trace.  Note how the formatting of a human-readable exception message is conspicuously missing from this process.

P.S.

A few more of my thoughts on this subject can be found in this answer: How to write a good exception message

P.P.S.

It appears that a lot of people were being ticked off by my suggestion about binary log files, so I amended the answer once again to make it even more clear that what I am suggesting here is not that the log file should be binary, but that the log file may be binary, if need be.

ContentLicense: CC BY-SA 4.0


答:
I don't have an excess of C# experience, or C++ specifically, but I can tell you this - developer-written exceptions 9 out of 10 times are more useful than any generic exception you will ever find, period.

Ideally yes, a generic exception will point you to exactly why the error occurred and you'll be able to fix it with ease - but realistically, in large applications with multiple classes that can throw a wide variety of different kinds of exceptions, or the same kind of exceptions, it is always more valuable to write your own output for error return than it is to rely on the default message.

This is how it should be, because as many people have pointed out, some applications don't want to throw an error message that they don't want the user to see, for security reasons or to avoid confusing them.

Instead, you should anticipate in your design what types of errors might be thrown in your application (and there will always be errors) and write error-catching messages that help you identify the issue.

This won't always help you - because you can't always anticipate what error message will be useful - but it is the first step to understanding your own application better in the long-run.

Title: Why do many exception messages not contain useful details?

Body:
It seems there is a certain amount of agreement that exception messages should contain useful details.

Why is it that many common exceptions from system components do not contain useful details?

A few examples:

.NET List index access ArgumentOutOfRangeException does not tell me the index value that was tried and was invalid, nor does it tell me the allowed range.

Basically all exception messages from the MSVC C++ standard library are utterly useless (in the same vein as above).

Oracle exceptions in .NET, telling you (paraphrased) "TABLE OR VIEW not found", but not which one.

So, to me it seems that for the most part exception messages do not contain sufficient details to be useful. Are my expectations out of line? Am I using exceptions wrong that I even notice this? Or maybe my impression is wrong: a majority of exceptions do actually provide useful details?

ContentLicense: CC BY-SA 3.0


问:
Javascript inline event handling versus external jQuery event handlers
Working on a dynamic website that loads information from a JSON file and then populates the page with said elements.

My question has to do with event handling - as of now, I don't see any reason as to why I would need to add event handlers inline if I could just use the equivalent jQuery handler in an external script file. I could see the argument where one would say it allows for more control over events, but would that be true?

Here are the two methods I am looking at:

Inline:

```<code><div class="family" onclick="goToFamilyPage()">This Family</div>
</code>```

External/imported script:

```<code>$(document).on('click', '.family', function() {
    //do stuff
});
</code>```

What would be the benifit of one of these versus the other?

答: It's better to use event handlers. Event handlers keep JavaScript out of your HTML which is usually better for decoupling reasons. The only time in-line JavaScript is okay is if you inject it via a template. This is often done when with React.js because it generates a lot of HTML (which is arguably a template). </p>


问:
How is distribution of PKI certificates allowed?
As a verifier of Open Source compliance in open and proprietary code I sometimes come across such certs distributed with the source code (e.g https://github.com/bagder/ca-bundle/blob/e9175fec5d0c4d42de24ed6d84a06d504d5e5a09/ca-bundle.crt)

As I understand it the general idea of a CA / PKI / SSL certificate (e.g. as issued by CACert or Comodo) is that they be used as a public / private key pair, and hence it seems reasonable that a public key be freely distributable, but have found no opinion on the web to support that view. Neither on websites like Wikipedia, StackOverflow, nor in the documentation of the private certificate issuers.

Are such certs actually, or effectively, public domain; or do they need to be licensed for public distribution?

答:
The license is specified in the README.md for the project:

The converted file is licensed under the same licenses as the Mozilla
  source file: MPL 1.1, GPL v2.0 or LGPL 2.1

As such, the certificates are not public domain, and are explicitly licensed for public distribution under multiple licenses.

In other projects, the license of the certificate file would be the same as the license for any other source file in that project.  Note that it is not an inconsistency if a single file is found in multiple projects with differing licenses as the author may license their work with multiple licenses.  In the above example, the same file is released under three different licenses.

A developer would be in their rights to take this file, and release it under any one of those licenses.  For instance, you might find it in Project A licensed under MPL 1.1 only, and Project B licensed under GPL v2.0 only.  This is perfectly fine if the certificate file was take from this particular project, as it is explicitly released in all three.

Note that in this case, the developer just pulled the certificates from Mozilla and released them as a standalone project under the same licenses specified by the Mozilla project.  He could have done the same, choosing just one license, or he could have pulled them directly into any project that was compatible with MPL 1.1, GPL v2.0 or LGPL 2.1.  In this case, the file would be licensed (if acquired from there) only under the relevant license.


问:
How do you unit-test code using graph structures?
I am writing (recursive) code that is navigating a dependency graph looks for cycles or contradictions in the dependencies. However, I am not sure how to approach unit testing this. The problem is that one of our main concerns is will the code handle on all the interesting graph structures that can arise and making sure that all nodes will be handled appropriately.

While usually 100% line or branch coverage is sufficient to be confident that some code works, it feels like even with 100% path coverage you'd still have doubts.

So, how does one go about selecting graph structures for test cases to have confidence that their code could handle all the conceivable permutations you'll find in real world data.

PS- If it matters, all edges in my graph are labelled "must have" xor "cannot have" and there are no trivial cycles, and there is only one edge between any two nodes.

PPS- This additional problem statement was originally posted by the question's author in a comment below:

For all vertices N in forest F, for all vertices M, in F, such that if there are any walks between N and M they all must either use only edges labelled 'conflict' or 'requires'.

答:
1. Randomized test generation

Write an algorithm that generates graphs, have it generate a few hundred (or more) random graphs and throw each at your algorithm.

Keep the random seed of the graphs that cause interesting failures and add those as unit tests.

2. Hard-code tricky parts

Some graphs structures that you know are tricky you can code in right away, or write some code that combines them and pushes them to your algorithm.

3. Generate exhaustive list

But, if you want to be sure "the code could handle all the conceivable permutations you'll find in real world data.", you need to generate this data not from random seed, but by walking though all permutations. (This is done when testing subway rail signal systems, and gives you enormous amounts of cases that takes ages to test. For metro subways, the system is bounded, so there is an upper limit to the number of permutations. Not sure how your case applies)


问:
What default features is Windows missing that are required for programmers?
What features is Windows missing that can improve the productivity of a programmer. I know a lot of people would want some features from Linux and OSX ported or being created for Windows as well. What is missing for you ?

An example would be the option to have multiple workspaces. When not having the possibility to use dual monitors that can come in handy.

答:
The ability to write and run programs in various languages (C, C++, Python, Perl, Ruby ...) without having to install anything extra.

Having at least one text editor with syntax highlighting installed by default.

A package manager so that you can easily install extra libraries, version control systems, IDEs etc.

A powerful command line interface.

The ability to tweak the GUI for maximum efficiency (keyboard shortcuts, hot corners etc.)

manpages

Having the source code of the operating system and software packages easily available and licensed permissively so that you can reuse it.

Good performance on modest hardware.

ContentLicense: CC BY-SA 2.5


问:
Ant colony algorithm
I am a student working on an ant colony simulator for a course project. The algorithm for it is (obviously) an ant colony algorithm. I know there are various forms of the algorithm but all of those were too mathematically detailed for us so we took an approach in which we have :

An ant is born at a colony and must gather food from a source to sustain the colony.

All ants are similar.

The area in which the ant moves is a 1000x1000 grid, so every grid point serves as a valid point for an ant to occupy. Now, all the algorithms which I have come across involve treating vertices and edges separately but as we are restricting the ants movement to only four directions (up, down, left, right) I guess it doesn't matter where we put the pheromone.

The grid points mentioned above store the pheromone.

An ant drops pheromone only if it is carrying food.

For an ant at a position (i,j), it decides where to move in the next step by taking the pheromone amounts on its four adjacent nodes into account in a simple probabilistic formula,i.e. the probability of traveling to a node is given by (pheromone amount at particular adjacent node) / (sum of pheromone amounts in 4 adjacent nodes).

An ant cannot travel back to the position it just came from. It can only do so if it is at a site which has food or it is at its colony.

Now my concern is ( and what is actually happening in our program ) that when an ant FIRST reaches a position which has food and picks it up, then by the way our algorithm works, it can move anywhere!
This is because it will only leave a pheromone trail, once it has the food and not before and as it is the first ant, there is no existing trail.

If the ant can move anywhere, the ants that reach the food source after it will also mostly tend to follow it.. EVEN IF it is not moving back towards the colony. This defeats the purpose of the entire algorithm.

So my questions are

Is the above concern valid? If no, then why? If yes, then how to deal with it?

Do we need to make some changes in our basic understanding of the algorithm to actually make it work?

What are some other subtle yet important things that newbies like me may miss in this case?

答:
This isn't how ACO works. ACO only drops pheromones after ants have moved across all the points in the grid. You then evaluate something (perhaps total travel time) and then drop pheromones for good ants, and repeat.

They don't move to the same vertex twice, generally, though you can customize this for implementation specificness.

Pheromones aren't dropped each move, they drop after they move everywhere and something is evaluated to determine which ants are better. Ants which are better then drop phereomones (perhaps the best 25% performing ants).

Title: Ant colony algorithm


问:
Is directly using Make considered obsolete?
So I have been coming across many comments/posts/etc regarding creating makefiles directly, and how it is a silly thing to do in 2015. I am aware of tools such as CMake, and I actually use CMake quite often. The thing is, CMake is just creating the Makefile for you and helping to remove the tedium of doing it yourself. Of course it adds a lot of other great features... but its still a Makefile in the end.

So my question is, is the 'obsolete' talk regarding make referring to the entire Make utility, or just the idea of manually writing your own Makefiles? I do not use an IDE for C/C++ development at all (just emacs), so I have always written Makefiles.

If Make is considered outdated, what should a C/C++ dev be using to build small, personal projects?

答:
make (the tool or direct use of it via a Makefile) is not outdated, particularly for "small, personal projects" as you use it for.

Of course, you can also use it for larger projects, including those targeted for multiple platforms.  With target-specific variables you can easily customize how you build for different platforms.  Nowadays, Linux distributions come with cross-compiling toolchains (e.g. mingw-w64) so you can build a complete Windows software package (with installer if you like) from Linux, all driven from your Makefile.

Tools like cmake and qmake can be useful, but they are not without their problems.  They are usually fine for building an application itself along with any libraries (though I always had problems with qmake doing proper dependency checking between libraries and programs that use them), but I always struggle with the constraints of those tools when doing the rest of the job (creating installers, generating/installing documentation or translation files, doing unusual stuff like turning an archive into a shared library, etc.).  All of this can be done in make, though things like dependency tracking can require a little effort.

IDEs like Qt Creator and Eclipse can also import Makefile-based projects, so you can share with IDE-using developers.  I think the Qt Creator IDE is excellent as a C++ IDE, but after spending some time to become more effective with Emacs, and since I'm doing more Ada development, I'm finding myself preferring Emacs for everything.  To relate back to the question about make, as a post-link step in my Makefile, I update my TAGS file (for symbol navigation in Emacs), loaded with M-x visit-tags-table:

```<code>find $(SRC_DIR) $(TEST_DIR) -regex ".*\.[ch]\(pp\)?" -print | etags -
</code>```

Or for Ada development:

```<code>find $(SRC_DIR) $(TEST_DIR) -name "*.ad?" -print | etags -
</code>```

Body:
make (the tool or direct use of it via a Makefile) is not outdated, particularly for "small, personal projects" as you use it for.

Of course, you can also use it for larger projects, including those targeted for multiple platforms.  With target-specific variables you can easily customize how you build for different platforms.  Nowadays, Linux distributions come with cross-compiling toolchains (e.g. mingw-w64) so you can build a complete Windows software package (with installer if you like) from Linux, all driven from your Makefile.

Tools like cmake and qmake can be useful, but they are not without their problems.  They are usually fine for building an application itself along with any libraries (though I always had problems with qmake doing proper dependency checking between libraries and programs that use them), but I always struggle with the constraints of those tools when doing the rest of the job (creating installers, generating/installing documentation or translation files, doing unusual stuff like turning an archive into a shared library, etc.).  All of this can be done in make, though things like dependency tracking can require a little effort.

IDEs like Qt Creator and Eclipse can also import Makefile-based projects, so you can share with IDE-using developers.  I think the Qt Creator IDE is excellent as a C++ IDE, but after spending some time to become more effective with Emacs, and since I'm doing more Ada development, I'm finding myself preferring Emacs for everything.  To relate back to the question about make, as a post-link step in my Makefile, I update my TAGS file (for symbol navigation in Emacs), loaded with M-x visit-tags-table:

find $(SRC_DIR) $(TEST_DIR) -regex ".*\.[ch]\(pp\)?" -print | etags -

Or for Ada development:

find $(SRC_DIR) $(TEST_DIR) -name "*.ad?" -print | etags -


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
After working with PHP for about 13 years, and heavily with JS for about 4, there are a couple things I think PHP would do well to borrow from JS:

1) shorthand notation for Arrays and Objects. I believe this may have been discussed and shot down on Internals (so I hear – I don't like to see how the sausage is made), but I really, really find that the literal notation for arrays and objects in JS is a big productivity win.

For example:

```<code>$arr     = [1,2,3,4];
$assoc   = [foo=>'bar', baz=>'boo'];
$stdobj  = {foo->'bar', baz->'boo'};
</code>```

Is (IMHO) just much easier to write and cleaner than

```<code>$arr     = array(1,2,3,4); // not too bad
$assoc   = array("foo"=>'bar', baz=>'boo'); // not too bad either
$stdobj  = new stdClass; // this gets pretty rough
$stdobj->foo = 'bar';
$stdobj->baz = 'boo';
</code>```

I've heard that some concern about potential confusion was raised, but really, is this any more confusing than, say,  heredoc notation? At very least, making a stdClass object in PHP is verbose enough to discourage the practice, I think.

2) Being able to redefine previously-defined functions and methods would be really useful. It would particular simplify situations extending a class and instantiating the new class is either overly complex or impractical. I do think we should avoid redefinition of core/non-userspace functions and methods, though.

In addition to those two, I think PHP must transparently support unicode. This is becoming more and more of a problem for developers, and the solutions currently offered in PHP are confusing and frequently non-performant. Making all standard string functionality unicode-friendly out of the box would be a massive win for PHP programmers.

Thanks for asking!

Body:
After working with PHP for about 13 years, and heavily with JS for about 4, there are a couple things I think PHP would do well to borrow from JS:

1) shorthand notation for Arrays and Objects. I believe this may have been discussed and shot down on Internals (so I hear – I don't like to see how the sausage is made), but I really, really find that the literal notation for arrays and objects in JS is a big productivity win.

For example:

$arr     = [1,2,3,4];
$assoc   = [foo=>'bar', baz=>'boo'];
$stdobj  = {foo->'bar', baz->'boo'};

Is (IMHO) just much easier to write and cleaner than

$arr     = array(1,2,3,4); // not too bad
$assoc   = array("foo"=>'bar', baz=>'boo'); // not too bad either
$stdobj  = new stdClass; // this gets pretty rough
$stdobj->foo = 'bar';
$stdobj->baz = 'boo';

I've heard that some concern about potential confusion was raised, but really, is this any more confusing than, say,  heredoc notation? At very least, making a stdClass object in PHP is verbose enough to discourage the practice, I think.

2) Being able to redefine previously-defined functions and methods would be really useful. It would particular simplify situations extending a class and instantiating the new class is either overly complex or impractical. I do think we should avoid redefinition of core/non-userspace functions and methods, though.

In addition to those two, I think PHP must transparently support unicode. This is becoming more and more of a problem for developers, and the solutions currently offered in PHP are confusing and frequently non-performant. Making all standard string functionality unicode-friendly out of the box would be a massive win for PHP programmers.

Thanks for asking!


答:
The implementations I've seen from others, and the ones I've written for myself, have always had the ants release the pheromones along the path the traveled to get to food, once they have reached the food.  That is, the ants march from their colony to the food following a random walk; the paths followed by the ants from the colony to the food are then marked using pheromones only after the ants were successful in reaching the food.  The return trip is not explicitly simulated.  In general, multiple ants run their course before any pheromones are deposited for the current iteration.  The pheromones are then deployed for the successful paths, and a new round begins.

Usually, the ant's odds of stepping into a given node are weighted by the amount of pheromone times some measure of "goodness."  For instance, the goodness measure might be something like the inverse of the distance between the ant and the food--this will keep the ants trying to move towards the food, regardless of previous pheromone deposits.  The goodness could be further weighted to account for other factors, e.g. some nodes might be easier to travel through than others.  And as enderland points out, typically there is some form of path "selection" once all of the ants have successfully run their courses, where only some portion of the "best" paths are chosen for pheromone deposit.  However, you should still get reasonable paths even without selection, so long as your choice of "goodness" makes sense.

Title: Ant colony algorithm

Body:
I am a student working on an ant colony simulator for a course project. The algorithm for it is (obviously) an ant colony algorithm. I know there are various forms of the algorithm but all of those were too mathematically detailed for us so we took an approach in which we have :

An ant is born at a colony and must gather food from a source to sustain the colony.

All ants are similar.

The area in which the ant moves is a 1000x1000 grid, so every grid point serves as a valid point for an ant to occupy. Now, all the algorithms which I have come across involve treating vertices and edges separately but as we are restricting the ants movement to only four directions (up, down, left, right) I guess it doesn't matter where we put the pheromone.

The grid points mentioned above store the pheromone.

An ant drops pheromone only if it is carrying food.

For an ant at a position (i,j), it decides where to move in the next step by taking the pheromone amounts on its four adjacent nodes into account in a simple probabilistic formula,i.e. the probability of traveling to a node is given by (pheromone amount at particular adjacent node) / (sum of pheromone amounts in 4 adjacent nodes).

An ant cannot travel back to the position it just came from. It can only do so if it is at a site which has food or it is at its colony.

Now my concern is ( and what is actually happening in our program ) that when an ant FIRST reaches a position which has food and picks it up, then by the way our algorithm works, it can move anywhere!
This is because it will only leave a pheromone trail, once it has the food and not before and as it is the first ant, there is no existing trail.

If the ant can move anywhere, the ants that reach the food source after it will also mostly tend to follow it.. EVEN IF it is not moving back towards the colony. This defeats the purpose of the entire algorithm.

So my questions are

Is the above concern valid? If no, then why? If yes, then how to deal with it?

Do we need to make some changes in our basic understanding of the algorithm to actually make it work?

What are some other subtle yet important things that newbies like me may miss in this case?


问:
Is OOP hard because it is not natural?
One can often hear that OOP naturally corresponds to the way people think about the world. But I would strongly disagree with this statement: We (or at least I) conceptualize the world in terms of relationships between things we encounter, but the focus of OOP is designing individual classes and their hierarchies.

Note that, in everyday life, relationships and actions exist mostly between objects that would have been instances of unrelated classes in OOP. Examples of such relationships are: "my screen is on top of the table"; "I (a human being) am sitting on a chair"; "a car is on the road"; "I am typing on the keyboard"; "the coffee machine boils water", "the text is shown in the terminal window."

We think in terms of bivalent (sometimes trivalent, as, for example in, "I gave you flowers") verbs where the verb is the action (relation) that operates on two objects to produce some result/action. The focus is on action, and the two (or three) [grammatical] objects have equal importance.

Contrast that with OOP where you first have to find one object (noun) and tell it to perform some action on another object. The way of thinking is shifted from actions/verbs operating on nouns to nouns operating on nouns -- it is as if everything is being said in passive or reflexive voice, e.g., "the text is being shown by the terminal window". Or maybe "the text draws itself on the terminal window".

Not only is the focus shifted to nouns, but one of the nouns (let's call it grammatical subject) is given higher "importance" than the other (grammatical object). Thus one must decide whether one will say terminalWindow.show(someText) or someText.show(terminalWindow). But why burden people with such trivial decisions with no operational consequences when one really means show(terminalWindow, someText)? [Consequences are operationally insignificant -- in both cases the text is shown on the terminal window -- but can be very serious in the design of class hierarchies and a "wrong" choice can lead to convoluted and hard to maintain code.]

I would therefore argue that the mainstream way of doing OOP (class-based, single-dispatch) is hard because it IS UNNATURAL and does not correspond to how humans think about the world. Generic methods from CLOS are closer to my way of thinking, but, alas, this is not widespread approach.

Given these problems, how/why did it happen that the currently mainstream way of doing OOP became so popular? And what, if anything, can be done to dethrone it?

答:
I have witnessed and participated in many online debates about OOP. The proponents of OOP usually do not know how to write proper procedural code. It is possible to write procedural code that is highly modular. It is possible to separate code and data and ensure that functions can only write to their own data store. It is possible to implement the concept of inheritance using procedural code. More importantly, procedural code is slimmer, faster and easier to debug.

If you build single-file modules with strict naming conventions, procedural code is easier to write and maintain than OO and it will do the same or more and faster. And don't forget that when your application runs, it is always procedural no matter how many classes feature in your script.

Then you have the issue of languages like PHP, which are not truly Object Oriented and rely on hacks to fake stuff like multiple inheritance. The big shots who influence the direction of the language have turned PHP into a patchwork of inconsistent rules that have become too big for what it initially intended. When I see developers write huge templating classes for what was intended as a procedural templating language, I can't help but smile.

If you compare properly-written OO code with poorly-written procedural code, then you will always come to the wrong conclusion. Very few projects warrant an Object Oriented design. If you are IBM and manage a huge project that needs to be maintained for years by multiple developers, go for Object Oriented. If you are writing a small blog or shopping website for a client, think twice.

To answer the original question, OOP is hard because it does not solve real-life programming dilemmas without resorting to solutions that are 100 times more complicated than they should be. One of the most powerful solutions to many programming problems is the judicious use of global data. Yet the new-wave university graduates will tell you that it is a big no-no. Globally-available data is dangerous only if you are a clumsy programming bunny. If you have a strict set of rules in place and proper naming conventions, you can get away with having all of your data global.

It should be a mandatory requirement for any Object Oriented programmer to know how to write a chess-playing application in assembler for a maximum available memory of 16K. They would then learn how to trim the fat, cut the laziness and generate ingenious solutions.

Title: Is OOP hard because it is not natural?


问:
Who owns code if project cancelled
The problem: I am working on a freelance marketplace, and I decided to cancel project with one of my clients, because client is impossible to work with with limitless delays and lots of bugs in his backend. I want to give him a partial refund (partial because I worked for two months and there is 3k lines of code, though application still not working due to problems from his backend).

The question: who is "owner" of code which I have wrote? We did no agreement about it upon project was started. Can I tell him to not use my code? I understand, that he can ignore my forbid anyway, I just want to know if I have formal "right" to say so.

答:
This should have been specified in the contract (lessons learned...). In the best case for you, you would have specified that non-performance of contract terms by the client is grounds for cancellation, maybe a three-strikes rule or something. You would also have specified "intellectual property transfers on satisfaction of contract"; even in a cancellation, if both parties have lived up to those terms (meaning you've been paid what you are owed according to the contract thus far and have delivered accordingly), the contract is "satisfied".

That then makes it clear that what you have developed now belongs to your client. That is, of course, assuming that other than the client being the source of insurmountable delays, the customer was in good standing with regards to payment for services rendered. If the client is withholding payment, you own the code until the matter is resolved to either mutual satisfaction or the court's.

By the way, if the contract does not stipulate what portion of the payment you are entitled to and what you are not based on the work performed, then if you drafted this contract, be prepared to fork over every penny they gave you, and similarly, if they drafted it, you should be refunding nothing. As was correctly stated in a Big Bang Theory episode a few seasons back, ambiguity in a contract benefits the party that did not draft it, to the extent the law allows (the contract doesn't have to specify the obvious, such as illegalities of law, but if you are neither required nor prohibited by law or contract to take a certain action, you may do as you choose regarding said action, so if the contract doesn't stipulate settlement of partial completion, the money and the code will go to whomever didn't write this sieve of a contract).

Title: Who owns code if project cancelled


问:
MongoDB Embedded vs Reference Private info
I have searched extensively for a similar Mongo schema design and can't find relevant examples.

I have a store (with public info), each store has an account (with private account info).

```<code>// store object
{
  name: "Departement Store",
  email: "contact@store.com",
  account: { // private info not returned by API
    manager: "Steve",
    employees: [...]
  }
}
</code>```

The stores will be searched through a public API. I am limiting the search queries using MongoDB's features to limit the returned data:

```<code>db.stores.find({}, {account:0});
</code>```

My question: is it more efficient to keep the private data as a subdocument or in a separate collection? It seems a separate collection with account info is the best choice as I will be picking and choosing from an embedded document.

References:

mongo schema (embedding vs reference)

Embedded document vs reference in mongoose design model?

答:
As an update, this question was answered here: https://groups.google.com/forum/#!topic/mongodb-user/-1eXvkoxHUw

Summary: Keep data in one document, restrict data using MongoDB's built-in projection feature.


答:
When it comes to this sort of hard to test algorithm I would go for the TDD, where you build the algorithm based on tests,

TDD in short,

write the test

see it's failing

modify the code

make sure all tests are passing

refactor

and repeat the cycle,

In this particular situation,

First test would be, single node graph where algorithm should not return any cycles

Second one would be three node graph with no cycle where algorithm should not return any cycles

Next one would be to use three node graph with a cycle where algorithm should not return any cycles

Now you could test it against a bit more complex cycle depending on possibilities

One important aspect in this method is you need to always add a test for possible step (where you split possible scenarios into simple tests), and when you cover all possible scenarios usually algorithm gets evolved automatically.

Finally you need to add one or more complicated Integration tests to see if there any unforeseen issues (such as stack-overflow errors / performance errors when your graph is very large and when you use recursion)

Title: How do you unit-test code using graph structures?

Body:
I am writing (recursive) code that is navigating a dependency graph looks for cycles or contradictions in the dependencies. However, I am not sure how to approach unit testing this. The problem is that one of our main concerns is will the code handle on all the interesting graph structures that can arise and making sure that all nodes will be handled appropriately.

While usually 100% line or branch coverage is sufficient to be confident that some code works, it feels like even with 100% path coverage you'd still have doubts.

So, how does one go about selecting graph structures for test cases to have confidence that their code could handle all the conceivable permutations you'll find in real world data.

PS- If it matters, all edges in my graph are labelled "must have" xor "cannot have" and there are no trivial cycles, and there is only one edge between any two nodes.

PPS- This additional problem statement was originally posted by the question's author in a comment below:

For all vertices N in forest F, for all vertices M, in F, such that if there are any walks between N and M they all must either use only edges labelled 'conflict' or 'requires'.


答:
I might drop "required" from the title as I've developed for Windows happily for almost 20 years. Of course, I've developed quite a good toolbox of utilities and tools. See Scott Hanselmann's list for starters. It's top notch and look back all the way to 2003.

BTW, Windows 7 includes PowerShell which helps with the "decent shell" comments.

That said, It's always good to have better tools built in. Take any of the tools in Scott's list.

Realisitically, MS could certainly improve the UI of many built-in tools such as regedit, task mgr (cf. Process Monitor) and the event perf viewer tools. It would be good to have built-in support for multiple clipboards. From OSX, I'd like expose and their multi-desktop support is good. It would be nice if Windows natively (aka more easily) supported dragging text from text boxes.

XCode really sucks IMO so I would not want that on Windows. VS is much better but not built-in so maybe build-in VS Expess with an ability to upgrade. Of course, the OS footprint grows with this (like OSX's does) so there's a downside too.

distributed gcc is very good so that would be very welcome as a built-in framework for any compiler to use (see Incredibuild for a VS solution).

It would be nice if it were easier to get and use a Checked Build of the OS to find issues. Using debug cables is a bit extreme for the good info you get out of the Checked Build.  VMs may do this easily -- if so someone please comment with a link.

Title: What default features is Windows missing that are required for programmers?

Body:
What features is Windows missing that can improve the productivity of a programmer. I know a lot of people would want some features from Linux and OSX ported or being created for Windows as well. What is missing for you ?

An example would be the option to have multiple workspaces. When not having the possibility to use dual monitors that can come in handy.


问:
Defining acceptance criteria for a user story
I have been given a user story / epic which is display a web-page giving details about a retail store for a company.

Simply put, if the url was mywebsite.com/newyork it would display the new york store details
mywebsite.com/athens would display the athens details etc.
The things that would be displayed are things like opening hours, location, phone number

From my reading it looks like user story acceptance criteria are very high level. As such
I have 2 questions about acceptance criteria for my current project.

Questions

1) The product owner has put display Welcome to myRetailStore yyy where yyy is the name of the store page being displayed as a h1 tag at the top of the page underneath the main navigation bar

is that a relevant acceptance criteria? should the part about h1 tag be in the detail?(as it seems not high level enough to me)

2) assuming that there were 400 stores does checking the fact that Welcome to myRetailStore New York is displayed for New York mean that story has passed its acceptance criteria or would it need to be checked for all 400 stores?

答:
Personally, I would say an acceptance criteria of "Must be an
 tag" is not an appropriate acceptance criteria, unless the PO would be willing to reject the story if the team used some other tag and applied styling to make it look like an
 tag. In other words, is the use of
 truly a required part of the solution?

I would recommend engaging in a conversation with the PO to make sure what's really important, and why. Maybe there's a specific business reason for an h1 -- to support screen readers, perhaps? Or maybe the PO knows only enough HTML to be dangerous and doesn't realize that the tag isn't as important as the final rendering.

As for the second part, I would say that just because it shows up for new york is not sufficient. As a PO, I would write the acceptance criteria such that it's required that the proper greeting shows up for every supported store.

That doesn't mean that you have to have 400 test cases, but it does mean that you have a sufficient number of test cases to prove that all the edge cases and permutations are covered.

Remember: the goal of acceptance criteria is to help the team -- so they know when they are done. If being specific about tags helps the team, it's an appropriate criteria. If it gets in the way of the team doing it's job, it's not.

Body:
Personally, I would say an acceptance criteria of "Must be an <h1> tag" is not an appropriate acceptance criteria, unless the PO would be willing to reject the story if the team used some other tag and applied styling to make it look like an <h1> tag. In other words, is the use of <h1> truly a required part of the solution?

I would recommend engaging in a conversation with the PO to make sure what's really important, and why. Maybe there's a specific business reason for an h1 -- to support screen readers, perhaps? Or maybe the PO knows only enough HTML to be dangerous and doesn't realize that the tag isn't as important as the final rendering.

As for the second part, I would say that just because it shows up for new york is not sufficient. As a PO, I would write the acceptance criteria such that it's required that the proper greeting shows up for every supported store.

That doesn't mean that you have to have 400 test cases, but it does mean that you have a sufficient number of test cases to prove that all the edge cases and permutations are covered.

Remember: the goal of acceptance criteria is to help the team -- so they know when they are done. If being specific about tags helps the team, it's an appropriate criteria. If it gets in the way of the team doing it's job, it's not.


问:
Handling Business Logic/Validation Race Conditions
I'm working on a Training Enrollment web application with the following (simplified) features:

Maintenance (Add, Edit, Deactivation) of Trainings

Student sign-up

Student enrollment to Active Trainings

I've employed Onion Architecture. All my business logic/validation is in the Domain Layer and the Data Access Layer consists of ADO.NET components and stored procedures (no business logic whatsoever). The problem is that since the business logic/validation is in the domain, there may be a race condition in the following scenarios:

Scenario 1

Training A allows a maximum of 50 students only

Training A currently has 49 students enrolled

In the web application, two users are attempting to enroll simultaneously. At this point two threads spawned from two
concurrent requests to the web application are able to query 49
users, so both validations succeed in the Domain layer and both
users are able to enroll.

Scenario 2

Training A is created

Student A is attempting to enroll to Training A

While Student A is attempting to enroll to Training A, a Training Admin decides to deactivate Training A. A race condition occurs when
in the Domain layer, when the following happens:  In thread 1 of
User 1, validating whether Training A is active succeeds (returns
true) and at the same time;

In thread 2, the thread on which Training A is being deactived validates that there are no enrollments yet; so that both
validations succeed.

An obvious solution is to add business logic (checking for enrollment count, checking whether a Training is active) in my stored procedures but I'm hesitant to do this as it breaks the design.

My validation logic has a single point of entry and I can add a lock to such that the validation logic becomes a critical section so only one operation (validation and DB persistence) happens at a time, but this reduces concurrency.

Any alternative approach or how has this solved in the systems you've worked on?

答:
I would go with locking and making sure that validating the enrollment is single-threaded.

This is similar to any one of another similar scenarios where a potentially large number of users are attempting to secure a scarce resource: registering for class/training, booking a seat on an airplane, buying a movie theater ticket in advance for opening day of a blockbuster, etc. In other words, to ensure that a scarce resource is assigned correctly in these situations, you have to use concurrency.

Most of the time, users will be okay with the tiny bit of additional time and low chance of failure ("please try again"). These are the sorts of processes that involve charging credit cards, talking with external systems, etc. and we are used to the drawbacks.

I am not sure where your validation logic is exactly, but this is normally done in the database as a stored procedure. If nothing else, a procedure that locks the registration table for modification, inserts a row, and either returns the record ID or fails. Aside from the locking logic in your flavor of SQL, it should be two or three statements.


问:
Database Design for Inventory
I am starting to design a typical product based MySQL database but I keep running in circles on how to design the tables.

I have many types of products

Jeans

Tshirts

Dresses

Which have many of the same attributes

Size

Price

Colour

But some of the products have specific attributes, like length or logo or package.

Do I make a separate table for every product even though many of the columns are the same, or do I make a general product table and then have some sub-tables for specific products?

答:
Do not make a table for every product.

This problem has been solved many ways. Try this:

Make a product (or products) table, put your common product attributes in the product table, then make an attribute table and a productattribute table, something like:

```<code>attribute
---------
attributeId
attributeName
attributeDescription

productattribute
----------------
productId
attributeId
attributeValue
</code>```

Then you can assign arbitrary attributes to your products.

You can take the schema a little further if you like, using:

```<code>attribute
---------
attributeId
attributeName
attributeDescription
attributeType // [float, int, varchar, etc.]

productAttribute
----------------
productId
attributeId
attributeValueFloat
attributeValueInt
attributeValueVarChar
</code>```

This technique complicates your schema a bit, so be aware of what you are getting into if you decide to use the extra columns to store values by data type.

An alternative that might just suit your needs a little better would be to use a NoSQL Store like MongoDB for your products. Then you can store the attributes you need for each type of product without resorting to the complexity of a relational database schema.

Title: Database Design for Inventory

Body:
Do not make a table for every product.

This problem has been solved many ways. Try this:

Make a product (or products) table, put your common product attributes in the product table, then make an attribute table and a productattribute table, something like:

attribute
---------
attributeId
attributeName
attributeDescription

productattribute
----------------
productId
attributeId
attributeValue

Then you can assign arbitrary attributes to your products.

You can take the schema a little further if you like, using:

attribute
---------
attributeId
attributeName
attributeDescription
attributeType // [float, int, varchar, etc.]

productAttribute
----------------
productId
attributeId
attributeValueFloat
attributeValueInt
attributeValueVarChar

This technique complicates your schema a bit, so be aware of what you are getting into if you decide to use the extra columns to store values by data type.

An alternative that might just suit your needs a little better would be to use a NoSQL Store like MongoDB for your products. Then you can store the attributes you need for each type of product without resorting to the complexity of a relational database schema.


答:
First off, let me burst a bubble by saying even if the diag message is loaded with information that brings you to the exact code line and sub command in 4 seconds, chances are the users will never write it down or convey it to the support folks and you will be told "Well it said something about a violation... I don't know it looked complicated!"

I've been writing software and supporting the results of others software for more than 30 years now, and personally, the current quality of an exception message has virtually nothing to do with security, regardless of how the end results happened to fit their model of the universe, an much more to do with the fact that so many in our industry were originally self taught, and they just never included lessons in communications.  Maybe if we FORCED all new coders into a maintenance position for a couple of years where they had to deal with figuring out what went wrong, they would understand the importance of at least some form of precision.

Recently in an application being rebuilt, a decision was made that return codes would fall into one of three groups:

0 through   9 would be success through success with additional
information.

10 through  99 would be non fatal (recoverable)
errors, and

101 through 255 would be fatal errors.

(100 was for some reason left out)

In any particular workflow, our thought was reused or generic code would use generic returns (>199) for fatal errors, leaving us with 100 fatal errors possible for a work flow.  With slight differentiating data in the message, errors such as file not found could all use the same code and differentiate with the messages.

When the code came back from the contractors, you would not believe our surprise when virtually EVERY SINGLE FATAL ERROR was return code 101.

All that considered I think the answer to your question is the messages are so meaningless because when originally created, they were to be placeholders that no one got back to.  Eventually folks figured out how to fix issues not because of the messages but DISPITE them.

Since that time, the self taught folks simply never had a good example of what an exception should contain.  Add to that more users don't read the messages, much less try to pass it on to support (I've seen error messages that were cut and paste by the used that were then redacted before being sent on with the later comment that it seemed like a lot of information and I could not possibly want it all, so they randomly removed a bunch of it.

And lets face it, with way too many (not all but way too many) of the next generation of coders, if it is more work and does not add flash, just not worth it...

Last note:  If an error message includes an error/return code, it seems to me that somewhere in the executed modules there should be a line that reads something like "if condition return code-value"  and condition should tell you why the return code occurred.  This seems like a simple logical approach, but for the life of me, just TRY to get Microsoft to tell you what happened when a windows upgrade failed on CODE 80241013 or some other very unique identifier.  Kinda sad, isn't it?


问:
Should curly braces appear on their own line?
Should curly braces be on their own line or not? What do you think about it?

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

or should it be

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

or even

```<code>if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();
</code>```

Please be constructive! Explain why, share experiences, back it up with facts and references.

答: All I can say is that if you're a fan of method #3, you are going to be persecuted by every IDE code-formatter on earth.</p>


答:
Exceptions have a language- and implementation- specific cost.

For example, C++ exceptions are required to destroy all the living data between throwing call frame and catching call frame, and that is expensive. Hence, programmers do no wish to use exceptions a lot.

In Ocaml, exception throwing is nearly as fast as a C setjmp (its cost does not depend upon the number of traversed call frames), so developers can use it a big lot (even for non-exceptional, very common, cases). In contrast, C++ exceptions are heavy enough so you probably won't use them a lot like you would in Ocaml.

A typical example is some recursive search or exploration which can be "stopped" inside a quite deep recursion (e.g. find a leaf in a tree, or a unification function). In some languages it is quicker (so more idiomatic) to propagate that condition to every caller. In other languages, throwing an exception is quicker.

So depending on the language (and the habits of developers using it), an exception could carry a lot of useful details, or on the contrary be used as a quick non-local jump and carry only the very useful data.


问:
Why are native ES6 promises slower and more memory-intensive than bluebird?
In this benchmark, the suite takes 4 times longer to complete with ES6 promises compared to Bluebird promises, and uses 3.6 times as much memory.

How can a JavaScript library be so much faster and lighter than v8's native implementation written in C? Bluebird promises have exactly the same API as native ES6 promises (plus a bunch of extra utility methods).

Is the native implementation just badly written, or is there some other aspect to this that I'm missing?

答:
Bluebird author here.

V8 promises implementation is written in JavaScript not C. All JavaScript (including V8's own) is compiled to native code. Additionally user written JavaScript is optimized, if possible (and worth it), before compiled to native code. Promises implementation is something that would not benefit much or at all from being written in C, in fact it would only make it slower because all you are doing is manipulating JavaScript objects and communication.

The V8 implementation simply isn't as optimized as bluebird, it for instances allocates arrays for promises' handlers. This takes a lot of memory when each promise also has to allocate a couple of arrays (The benchmark creates overall 80k promises so that's 160k unused arrays allocated). In reality 99.99% of use cases never branch a promise more than once so optimizing for this common case gains huge memory usage improvements.

Even if V8 implemented the same optimizations as bluebird, it would still be hindered by specification. The benchmark has to use new Promise (an anti-pattern in bluebird) as there is no other way to create a root promise in ES6. new Promise is an extremely slow way of creating a promise, first the executor function allocates a closure, secondly it is passed 2 separate closures as arguments. That's 3 closures allocated per promise but a closure is already a more expensive object than an optimized promise.

Bluebird can use promisify which enables lots of optimizations and is a much more convenient way of consuming callback APIs and it enables conversion of whole modules into promise based modules in one line (promisifyAll(require('redis'));).


问:
General way to convert a loop (while/for) to recursion or from a recursion to a loop?
This problem is mainly focusing on the algorithm, maybe something abstract and more academic.

The example is offering a thought, I wanna a generic way, so example is only used as to make us more clearly about your thoughts.

Generally speaking, a loop can be converted to a recursive.

e.g:

```<code>for(int i=1;i<=100;++i){sum+=i;}
</code>```

And its related recursive is:

```<code>int GetTotal(int number)
{
   if (number==1) return 1;   //The end number
   return number+GetTotal(number-1); //The inner recursive
}
</code>```

And finally to simplify this, a tail-recursive is needed:

```<code>int GetTotal (int number, int sum)
{
    if(number==1) return sum;
    return GetTotal(number-1,sum+number);
}
</code>```

However, most cases aren't so easy to answer and analyze. What I wanna know is:

1) Can we get a "general common way" to convert a loop (for/while……) to a recursive? And what kinds of things should we pay attention to while doing conversion? It would be better to write detailed info with some samples and your persudo theories as well as the conversion process.

2) "Recursive" has two forms: Linely recursive and Tail-Recursive. So which is better to convert? What "rule" should we master?

3) Sometimes we need to keep the "history" of recursive, this is easily be done in a loop statement:

e.g:

```<code>List<string> history = new List<string>();
int sum=0;
for (int i=1;i<=100;++i)
{
   if(i==1) history.Add(i.ToString()+"'s result is:1.");
   else
   {
     StringBuilder sub = new StringBuilder();

      for(int j=1;j<=i;++j)
      {
          if(j==i) sbu.Append(j.ToString());
          else
          {
            sub.Append(j.ToString()+"+");
          }
      }
    sum +=i;
    sbu.Append("'s result is:"+sum+Environment.NewLine);
   }
}
</code>```

The result below is:

1's result is 1.

1+2's result is 3.

1+2+3's result is 6
…………

However I think it's hard to keep the history in a recursive, because a recursive-based algorithm focuses on to getting the last result and do a call-back return. So all of these are done through the stack maintained by the programming language assigning memory in the form of stack automatically. And how we can "manually" take each of the "stack values" out and return multiple values through a recursive algorithm?

And what about "from a recursive algorithm to a loop"? Can they be converted to each other (I think it should be done theoretically, but I want more accurate things to prove my thoughts).

答:
Actually you should break the function down first:

A loop has a few parts:

the header, and processing before the loop. May declare some new variables

the condition, when to stop the loop.

the actual loop body. It changes some of the header's variables and/or the parameters passed in.

the tail; what happens after the loop and return result.

Or to write it out:

```<code>foo_iterative(params){
    header
    while(condition){
        loop_body
    }
    return tail
}
</code>```

Using these blocks to make a recursive call is pretty straightforward:

```<code>foo_recursive(params){
    header
    return foo_recursion(params, header_vars)
}

foo_recursion(params, header_vars){
    if(!condition){
        return tail
    }

    loop_body
    return foo_recursion(params, modified_header_vars)
}
</code>```

Et voilà; a tail recursive version of any loop. breaks and continues in the loop body will still have to be replaced with return tail and return foo_recursion(params, modified_header_vars) as needed but that is simple enough.

Going the other way is more complicated; in part because there can be multiple recursive calls. This means that each time we pop a stack frame there can be multiple places where we need to continue. Also there may be variables that we need to save across the recursive call and the original parameters of the call.

We can use a switch to work around that:

```<code>bar_recurse(params){
    if(baseCase){
        finalize
        return
    }
    body1
    bar_recurse(mod_params)
    body2
    bar_recurse(mod_params)
    body3
}

bar_iterative(params){
    stack.push({init, params})

    while(!stack.empty){
        stackFrame = stack.pop()

        switch(stackFrame.resumPoint){
        case init:
            if(baseCase){
                finalize
                break;
            }
            body1
            stack.push({resum1, params, variables})
            stack.push({init, modified_params})
            break;
        case resum1:
            body2
            stack.push({resum2, params, variables})
            stack.push({init, modified_params})
            break;
        case resum2:
            body3
            break;
        }
    }
}
</code>```

Body:
Actually you should break the function down first:

A loop has a few parts:

the header, and processing before the loop. May declare some new variables

the condition, when to stop the loop.

the actual loop body. It changes some of the header's variables and/or the parameters passed in.

the tail; what happens after the loop and return result.

Or to write it out:

foo_iterative(params){
    header
    while(condition){
        loop_body
    }
    return tail
}

Using these blocks to make a recursive call is pretty straightforward:

foo_recursive(params){
    header
    return foo_recursion(params, header_vars)
}

foo_recursion(params, header_vars){
    if(!condition){
        return tail
    }

    loop_body
    return foo_recursion(params, modified_header_vars)
}

Et voilà; a tail recursive version of any loop. breaks and continues in the loop body will still have to be replaced with return tail and return foo_recursion(params, modified_header_vars) as needed but that is simple enough.

Going the other way is more complicated; in part because there can be multiple recursive calls. This means that each time we pop a stack frame there can be multiple places where we need to continue. Also there may be variables that we need to save across the recursive call and the original parameters of the call.

We can use a switch to work around that:

bar_recurse(params){
    if(baseCase){
        finalize
        return
    }
    body1
    bar_recurse(mod_params)
    body2
    bar_recurse(mod_params)
    body3
}

bar_iterative(params){
    stack.push({init, params})

    while(!stack.empty){
        stackFrame = stack.pop()

        switch(stackFrame.resumPoint){
        case init:
            if(baseCase){
                finalize
                break;
            }
            body1
            stack.push({resum1, params, variables})
            stack.push({init, modified_params})
            break;
        case resum1:
            body2
            stack.push({resum2, params, variables})
            stack.push({init, modified_params})
            break;
        case resum2:
            body3
            break;
        }
    }
}


问:
Serialization - can the output from a serializer be modified and then de-serialized
I am trying to serialize a Message object using ObjectOutputStream ,take the byte[ ] output of the serializer,encrypt it using an encryption tool and then trying to de-serialize it and cast it as an object. It gives an error - invalid stream header. Is it not possible to modify the OutputStream after serializing it and then de-serialize it? Excuse me if I am doing something atrocious, I am a novice to Java. Code for the serializer - serialMsg():

```<code>ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(this);
bytes = bos.toByteArray();
out.close();
</code>```

The output of the serializer is then used as below:

```<code>byte[] data = this.serialMsg(); // This is where I serialize the Message object
byte[] out = util.Encrypt(data, fromsk , to.toString(), param); // This is where I encrypt the byte[ ] - data and obtain an encrypted byte [ ] - out
</code>```

The object is then de-serialised as:

```<code>ByteArrayInputStream in = new ByteArrayInputStream(out);
ObjectInputStream objin = new ObjectInputStream(in) ;
msg = (Message)objin.readObject(); // This is where I cast the output of readObject into the type Message - the original type of the object that was serialized.
</code>```

I hope the objective behind this is clear. I am trying to modify the output stream and then trying to cast it back into the original type.

答:
The serialization API makes a specific promise: If you save the bytes created by a serialize() call, you can later feed them into a deserialize() call, and your object will be reconstructed. That is all it does.

You are doing something different: you are feeding a different stream of data to the deserializer. That isn't in its job description, so unsurprisingly it fails. It doesn't matter that the new data stream is intimately related to the original one; all that matters is that it isn't the same one.

To achieve what you want, you would have to understand how the serialization process works and custom-craft your transformation so that the reverse operation would succeed. That is technically possible, but it would mean that you basically have to do all the work that the library is supposed to do for you. At that point, there is no longer much point in using it at all, and you're better off using a different mechanism that serializes and encrypts data the way you want to.

Luckily, there are solutions that do both. See https://stackoverflow.com/questions/16950833/is-there-an-easy-way-to-encrypt-a-java-object for an example of a previous question about similar requirements.


问:
Is it okay to have code smells if it admits an easier solution to another problem?
A group of friends and I have been working on a project for the past little while, and we wanted to invent a nice OOP way of representing a scenario specific to our product. Basically, we're working on a Touhou-style bullet hell game, and we wanted to make a system where we could easily represent any possible behaviour of bullet we could dream up.

So that's exactly what we did; we made a really elegant architecture that allowed us to section off the behaviour of a bullet into different components that could be attached to bullet instances at will, kind of like Unity's component system. It worked nicely, it was easily extensible, it was flexible and covered all our bases, but there was a slight problem.

Our application also involves a heavy amount of procedural generation, namely we procedurally generate the behaviours of the bullets. Why is this a problem? Well, our OOP solution to representing bullet behaviour, while elegant, is a little complicated to work with without a human. Humans are smart enough to think of solutions to problems that are both logical and clever. Procedural generation algorithms aren't that smart yet, and we've found it difficult to implement an AI that uses our OOP architecture to its fullest potential. Admittedly, that is a flaw of the architecture is that it's not intuitive in all situations.

So to remedy this problem, we basically shoved all the behaviours offered by different components into the bullet class, so that everything we could ever imagine is offered directly in each bullet instance as opposed to in other associated component instances. This makes our procedural generation algorithms a little easier to work with, but now our bullet class is a huge god object. It is easily the largest class in the program so far with more than five times as much code as anything else. It's a bit of a pain to maintain as well.

Is it okay that one of our classes turned into a god object, just to make it easier to work with another problem? In general, is it okay to have code smells in your code if it admits an easier solution to a different problem?

答:
For inspiration, you might want to have a look at functional programming, or more precisely, tight-tailored types. The idea being that things don't work are impossible to represent in the type system you have available. For example, say you have a gun that has the components "shoot bullets" and "hold bullets". If they are two separate components, there's configurations that don't make sense - you can have a gun that shoots bullets but doesn't have any in its storage, or a gun that stores bullets but doesn't fire them.

At this level of complexity, you're thinking "right, a human will figure out this is useless, and avoid the impossible combinations". A better way might be to make it outright impossible to do this. For example, the component for "shoot bullets" might require a reference to the "hold bullets" component (or just hold it as part of itself outright, although that has it's own issues).

While your examples might be a lot more complicated, the key is still limiting the possible combinations, adding constraints. In a way, if it's too complicated for procedural generation to get right, it's probably too complicated anyway. Think about all the ways you're constraining yourself when designing the weapons - do you tell yourself "right, this gun already has a flamethrower, there's no point in adding a grenade launcher"? That's something you can incorporate in your heuristics. You might want to use a probability mechanism that's a bit more complicated than just giving a fixed chance of having each component - you might have components that tend to exclude each other, or components that tend to work well together. So you could modify the probabilities of selecting a new component based on the components you already have.

And last, consider whether it's actually a big enough problem. Is it ruining the fun of the game? Is the result guns that are useless or overpowered? How much? Is one out of 10 nonsensical? Games like Borderlands (with procedurally generated weapon effects) often ignore nonsensical effect combinations - what's the point of having a shotgun with a 16x scope? And yet that happens very often in Borderlands. It's just played for laughs, rather than being considered a failure of the generation mechanisms :)


问:
Transient life time and constructor injection
I'm working on a little light weight Dependency resolver found here

https://github.com/AndersMalmgren/DuoCode.SimpleInjector

Currently if you do

```<code>var instance = container.Get<Foo>();
</code>```

You get a new instance for each call to Get

This is correct when in a transient lifetime management. But what's the expected behavior when using constructor injection?

Lets say you have this chain of dependency, with constructor arguments

ClassOne ( ClassTwo, ClassThree )

ClassTwo ( ClassThree )

Now we do a container.Get<ClassOne>(); Should ClassThree be same for both ClassOne and ClassTwo?

edit: The question is what do you think most users expect the behavior of transient life time to be when coupled with constructor injection during one call to Get<T>.

edit: Both Ninject, Castle and Unity seems to create new instances so probably the thats the way it should work (And thats the way its working right now)

edit: hmmm. interesting StructureMap actually reuses the instance, here is a the output from a test I did (Numbers are hashcodes)

```<code>Ninject.StandardKernel 65778530 34340385

Microsoft.Practices.Unity.UnityContainer 9874138 2186493

Castle.MicroKernel.DefaultKernel 27253481 44856655

StructureMap.Container 14259084 14259084
</code>```

Code to test above
http://pastebin.com/xPpgupU1

edit:
Actually if you do not specify .LifestyleTransient() castle will default to the same behavior as StructureMap, meaning it will be same instance per Resolve

答:
The obvious, albeit obnoxious answer, would of course be "it depends"... ;)

Most of the resolvers in the "major" IoC containers out there allow you to specify this when defining the resolution schema. In Castle Windsor, for instance, you can define the lifetime as Singleton, Transient, Bound, Thread, ... (there is a bunch). Your example is a pretty clear cut "Bound" instance, IF ClassThree is a repository class. (Otherwise, it is of course not as clear cut.)

To elaborate, the real question is whether, in your example, the ClassOne and ClassTwo instances actually need to have access to the same instance of ClassThree, or if they in fact must have separate instances.

Ultimately, I think this is up to the user of the resolver as there is no real way to know if an arbitrary class should live or die. My suggestion would be to decide on a default implementation (I would choose transient) but provide support to modify the lifestyle accordingly.


问:
Why do many exception messages not contain useful details?
It seems there is a certain amount of agreement that exception messages should contain useful details.

Why is it that many common exceptions from system components do not contain useful details?

A few examples:

.NET List index access ArgumentOutOfRangeException does not tell me the index value that was tried and was invalid, nor does it tell me the allowed range.

Basically all exception messages from the MSVC C++ standard library are utterly useless (in the same vein as above).

Oracle exceptions in .NET, telling you (paraphrased) "TABLE OR VIEW not found", but not which one.

So, to me it seems that for the most part exception messages do not contain sufficient details to be useful. Are my expectations out of line? Am I using exceptions wrong that I even notice this? Or maybe my impression is wrong: a majority of exceptions do actually provide useful details?

答:
While I do agree that exceptions should contain as much information as possible, or at least be less generic. In the table not found case, the table name would be nice.

But you know more about what you were trying to do at the place in the code where you received the exception. While you often really can't do much to rectify the situation when something goes wrong in a library outside your control, you can add much more useful information on in which situation something has gone wrong.

In the case of table not found, it will not help you much if you are told that the table that cannot be found is called STUDENTS, because you do not have such a table, and that string is nowhere in your code.

But if you catch the exception and rethrow it with the SQL-statement you were trying to execute, you will be better off, as it turns out that you tried to insert a record with the name field being Robert'); DROP TABLE STUDENTS; (There is always an xkcd!)

So to combat the less than informative exceptions: try-catch-rethrow with more information specific to what you were trying to do.

I should probably add, for this to be more of an answer as to the why in the question, that a likely reason why the focus from the makers of the libraries has not been on making the exception messages better, is that they do not know why something has been tried that failed, that logic is in the calling code.


问:
What to use instead of IDs in selectors in CSS
I recently installed a csslint package for my Atom text editor. I keep getting warnings saying "Don't use IDs in selectors." I found this weird since I've always been using IDs in selectors in CSS, and I haven't really run into any coding or syntactic problems using them.

On StackOverflow, I found posts, like this one, stating that I shouldn't use IDs because they have priority over classes. However, I found another post that states I should use IDs because they have priority over classes. I understand both of these posts, but I still don't know if I should continue to use them or not.

Lets say I have this code as an example:

HTML

```<code><div id="opening-subject-container">
    <div class="subject"></div>
    <div class="subject"></div>
    <div class="subject"></div>
</div>
<div id="body-subject-container">
    <div class="subject"></div>
    <div class="subject"></div>
    <div class="subject"></div>
</div>
</code>```

CSS

```<code>.subject {
    width: 100%;
    height: 20px;
}
#opening-subject-container .subject {
    background-color: red;
}
#body-subject-container .subject {
    background-color: blue;
}
</code>```

where I want the first subjects in the opening container to be red and the remaining subjects in the body container to be blue.

If I shouldn't ever use IDs in CSS selectors, what should I use instead?

Thanks for everyone's advice. I decided to stick with using IDs since they are convenient and I am able to keep track of when I should use an ID and when not to. I got tired of the warning messages in the lint, so I just changed the source code and deleted some rules that display warnings like this.

答:
This is what I generally stick to.

The main purpose, in my opinion, of having a separate css file is that it may be shared among multiple pages, which may use the styles in different ways. By using css classes instead of IDs, it is less restrictive, letting you not worry about duplicate IDs, while the lower specificity allows easier customisation of the style (either in another css file, or in the HTML head).

When writing css in the HTML head, I think using IDs is fine when you are referencing a particular element on the page. You may later decide that the css referencing IDs would be useful on another page. As long as you keep the css in the head, rather than inline, it should be easy enough to refactor it into a separate css file, replacing IDs with classes where appropriate.


问:
What default features is Windows missing that are required for programmers?
What features is Windows missing that can improve the productivity of a programmer. I know a lot of people would want some features from Linux and OSX ported or being created for Windows as well. What is missing for you ?

An example would be the option to have multiple workspaces. When not having the possibility to use dual monitors that can come in handy.

答:
Copy/paste for multiple objects

Paste format-free (without font/size info)


问:
Correct usage of Bluebird promise
This is related to this question on promise performance. The current top answer states that using new Promise is

an anti-pattern in bluebird

And that promisify should be used instead. I understand that promisifycan be used for functions that are using callbacks. But if I have my own code that I want to get a promise from how should this be done?

For example at the moment I have a function that performs a rest call and I use:

```<code>return new Promise(function (resolve, reject) {
    ...
    resolve(data);
    ...
    reject(err);
}
</code>```

I can then use this with the normal .then(). So this is correct for ES6, but if performing it the way bluebird intends what is the correct implementation to be as efficient as possible? As I think that taking my code and changing it to be handled with callbacks simply to use promisify seems a bit nuts.  Potentially I may have got the wrong end of the stick.

答:
This question probably doesn't belong to programmers but

```<code>var request = function() {
    return new Promise(function(resolve, reject) {
      ...
      resolve(data);
      ...
      reject(err);
    }
};
</code>```

Is of course much slower than

```<code>var request = promisify(function(callback) {
    ...
    callback(null, data);
    ...
    callback(err);
});
</code>```

However, this isn't the anti-pattern. The anti-pattern is using new Promise when promisify or .then() would suffice. For instance, here request is most likely just using some other APIs that already are implemented as callbacks/promises. Then new Promise is an anti-pattern because you should just chain the existing promise or promisify the callback api and then chain from the promises returned.

Title: Correct usage of Bluebird promise

Body:
This question probably doesn't belong to programmers but

var request = function() {
    return new Promise(function(resolve, reject) {
      ...
      resolve(data);
      ...
      reject(err);
    }
};

Is of course much slower than

var request = promisify(function(callback) {
    ...
    callback(null, data);
    ...
    callback(err);
});

However, this isn't the anti-pattern. The anti-pattern is using new Promise when promisify or .then() would suffice. For instance, here request is most likely just using some other APIs that already are implemented as callbacks/promises. Then new Promise is an anti-pattern because you should just chain the existing promise or promisify the callback api and then chain from the promises returned.


问:
How to write a good exception message
I'm currently doing a code review and one of the things I'm noticing are the number of exceptions where the exception message just seems to reiterate where the exception occurred. e.g.

```<code>throw new Exception("BulletListControl: CreateChildControls failed.");
</code>```

All three items in this message I can work out from the rest of the exception. I know the class and method from the stack trace and I know it failed (because I've got an exception).

It got me thinking about what message I put in exception messages. First I create an exception class, if one does not already exist, for the general reason (e.g. PropertyNotFoundException - the why), and then when I throw it the message indicates what went wrong (e.g. "Unable to find property 'IDontExist' on Node 1234" - the what). The where is in the StackTrace. The when may end up in the log (if applicable). The how is for the developer to work out (and fix)

Do you have any other tips for throwing exceptions? Specifically with regard to the creating new types and the exception message.

答:
In this more recent question I made the point that exceptions should not contain a message at all.  In my opinion, the fact that they do is a huge misconception.  What I am proposing is that

The "message" of the exception is the (fully qualified) class name of the exception.

An exception should contain within its own member variables as many details as possible about precisely what happened; for example, an IndexOutOfRangeException should contain the index value that was found to be invalid, as well as the upper and lower values that were valid at the moment that the exception was thrown.  This way, using reflection you can have a message automatically constructed which reads like this: IndexOutOfRangeException: index = -1;  min=0;  max=5 and this, together with the stack trace, should be all the objective information that you need in order to troubleshoot the problem. Formatting it into a pretty message like "index -1 was not between 0 and 5" does not add any value.

In your particular example, the NodePropertyNotFoundException class would contain the name of the property that was not found, and a reference to the node that did not contain the property. This is important: it should not contain the name of the node; it should contain a reference to the actual node. In your particular case this may not be necessary, but it is a matter of principle and a preferred way of thinking: the primary concern when constructing an exception is that it must be usable by code which might catch it. Usability by humans is an important, but only secondary concern.

This takes care of the very frustrating situation which you may have witnessed at some point in time in your career, where you may have caught an exception containing vital information about what happened within the message text, but not in within its member variables, so you had to do string parsing of the text in order to figure out what happened, hoping that the message text will stay the same in future versions of the underlying layer, and praying that the message text will not be in some foreign language when your program is run in other countries.

Of course, since the class name of the exception is the message of the exception, (and the member variables of the exception are the specific details,) this means that you need lots and lots of different exceptions to convey all the different messages, and that is fine.

Now, sometimes, as we write code, we come across an erroneous situation for which we just want to quickly code a throw statement and proceed writing our code instead of having to interrupt what we are doing to go create a new exception class so that we can throw it right there. For these cases, I have a GenericException class which does in fact accept a string message as a construction-time parameter, but the constructor of this exception class is adorned with a great big huge bright purple FIXME XXX TODO comment stating that every single instantiation of this class must be replaced with an instantiation of some more specialized exception class before the software system gets released, preferably before the code gets committed.

Title: How to write a good exception message