问:
Determining the winning condition for Tic-Tac-Toe
I'm writing a tic-tac-toe game in C++ and now I found a function to check if a player has a winning board for a connect four game.

The function looks like this:

```<code>bool haswon(int64_t board)
{
    int64_t y = board & (board >> 7);
    if (y & (y >> 2 * 7)) // check \ diagonal
        return true;
    y = board & (board >> 8);
    if (y & (y >> 2 * 8)) // check horizontal -
        return true;
    y = board & (board >> 9);
    if (y & (y >> 2 * 9)) // check / diagonal
        return true;
    y = board & (board >> 1);
    if (y & (y >> 2))     // check vertical |
        return true;
    return false;
}
</code>```

I would be looking for an explanation of the above function.

Then I could perhaps try to implement the same thing for my tic-tac-toe. I'm fairly OK with the bitwise operators

```<code>#include <iostream>
#include <bitset>

namespace tictactoe {

    constexpr std::size_t N = 3;

    using board = std::bitset<N*N>;

    constexpr char NOUGHT = 'O';
    constexpr char CROSS = 'X';

    bool curr_move_noughts = true;

    board combined() {
        return noughts | crosses;    // combined bit board for both players
    }

}
</code>```

答:
The pure fact you don't understand this function should be a big warning sign not to implement your Tic-Tac-Toe winning test in a similar manner. If you do, you will probably not understand your own code in a few weeks any more.

Instead, use a two-dimensional array or vector, and some loops to check the winning conditions. And don't think too much about speed or memory space as long as you don't experience any significant, measurable bottlenecks.


问:
How do I review code changes that are the result of syncing?
At my current job we develop code on a release branch and then do a code review. After all rework is done the final changes are also synced/merged to the 'main branch'. We want to be sure that all changes are synced correctly. What's a good way to review this sync work?

Note: the initial versions of files in the release branch and 'main branch' can be different. Thus it doesn't always help to compare the latest version in the release branch with the latest version in the main branch. (You then still see the 'initial differences' between both branches, although you don't see any 'sync changes' anymore).

My idea was to compare the 'delta' on the release branch with the 'delta' on the main branch. By using the GNU diff tool I can generate these two delta's, and then compare them in a file compare tool. Is this a good idea?

Note: we use ClearCase.

Just to clarify: We can't (or don't want to) rebase the release brach to the main branch, just for code review. That would again be a possible way to make mistakes. The release branch contains the code which our customers run. The main branch is used for splitting of new release branches in the future.

答:
You should update your version of the main branch against the latest version of the main branch, pulling in changes that have occurred since you branched off for your feature branch.  Once this is done you can then compare your differences alone.

Example using git:

First git rebase (or git merge but I prefer git rebasein case of code conflicts) the feature branch against the main branch.  You will need to resolve any code conflicts.

Then you can do a git diff directly to the main branch.

n.b. Do a git fetch first to make sure you are doing your rebase/merge and diff against the latest version of the main branch.

I don't know the syntax for ClearCase but the process will likely be similar.

ContentLicense: CC BY-SA 3.0


问:
How to work on not User Story related tasks
I'd like to create a developer task collector where I'd put all issues that I see need some work but are not User Story related (e.g. fix some not visible quirks in startup animation, scan code with lint, enable EasyTracker in application, clean unused resources, etc.).

I don't know when we'll have time to work all those issues, maybe next Sprint we'll do one of them and two Sprints later we'll work one etc.

How to deal with it in Scrum/Sprint planning? Also should Product Owner decide what to do and when?

答:
If you're talking about a single product/project and a single pool of developers, I would strongly recommend having just one product backlog with all the items you mentioned included in it. Having two backlogs will be an admin nightmare, and I'd imagine that you and the product owner will be fighting for resources to work on your respective backlogs.

If your user stories are expressed in terms of their business value, you should have no problems getting them planned into sprints. I am currently scrum master on a project with user stories like:

As a developer I want to rename tables and columns to reflect a recent change in business terminology so that it is easy for new developers to understand the system.

As a developer I want to implement improved logging of errors so that I can more easily diagnose problems reported to me.

As a sysadmin I want the spurious errors filling up the system's logs to be eliminated so that log noise doesn't prevent me from identifying problems.

If your product owner still refuses to include any of these in a sprint even when expressed in non-technical language and in terms of their business benefits, then perhaps you have the wrong product owner.

If you find yourself in that unhappy position but aren't able to change the product owner it might be useful to remind them that every system needs maintenance. I've also found describing the concept of technical debt, and how it always needs to be paid off at some point, a helpful analogy.

Lastly, you may find that some of those finer technical points which aren't currently being done should in fact be part of implementing the features your product owner wants. Building on some of your examples above, I would say that the user story to implement start-up animation wasn't properly completed if it has "quirks", whether visible or not. Likewise if you have standards for static code analysis metrics then a user story should only be considered done if the developer has used Lint to measure those metrics and proven that the code meets your standards. If these are generic standards they should be in your definition of done. If they are user-story-specific points then they can be conditions of acceptance on the user story.


问:
Passing by value multiple times vs. Creating a public class variable
Suppose I have a series of methods across different classes that all use the same five core variables defined in my main method. I could chain these five variables as method arguments from one method to the next, or I could simply define these five variables as public class variables and reference their path each time I want to use them.

What is considered more readable, and what is more efficient it terms of processing time? These values will not change throughout their lifespan in the program and take the form of Boolean values, multidimensional int[] arrays, and single dimensional int[] arrays.

答:
In this case, I would have to say create an object that holds them - like a "Data" class, which you can then instantiate. This provides a nice single point of access to the data. But, in this case, it does take up some extra space on the heap. (I'm not sure how concerned you should be with this though, java has automatic garbage collection)

Another advantage is that now your objects have to be less in-the-know about eachother. When you use a data object to encapsulate the data, you can send that to the method so your sender doesn't know exactly what the method will use. This is an advantage, as you can easily extend the method later to use some more information from the data object. Imagine the method only uses the boolean values and single-dimensional arrays, you really want your sender to know this? I'd say, just pass the data object, and trust the method to fetch the data it needs and perform the operations)

In this way, it's also easier to extend upon this. Do you suddenly, for one class, need more data? Add it to the data-object. Do you, at some point, wish to verify that all the data is correct? Add setter methods to the data object to protect it from flawwed input.

As I don't know how your program is designed exactly, this is what I would do considering all the information you have provided, and keeping in mind the option to expand upon your implementation in unforseen ways later on.


问:
the better url for a API: /api or api
when you make a API, what is a better practice ?

```<code>http://webapp/api
</code>```

or

```<code>http://api.webapp/
</code>```

why ?

I started with the API in http://webapp/api and the description of the service in http://webapp. but now, I would like separate the description of the API in differents repositories, for this reason, I'm thinking in change the url API to http://api.webapp/.

is a good idea/practice ?

答:
One benefit of http://webapp/api is that if you are developing the web site and the api as part of the same code base, you don't really need to do any special handling to deploy the api - it's just one web application that you have to deploy.

If you did use api.webapp, for this case, then you would probably have to do some special handling during initial setup of the application.

For http://api.webapp/ on the other hand, you use a different host name in the url (assuming you also have a web application running at http://webapp/).

This means that it could point to a different IP address - or it could point to the same IP - depending on DNS configuration. So by using this, you could have the api and web application be served by the same physical server to begin with, and later have the option of separating the two, without breaking your public interface!

So the first could be easier to setup initially, the latter gives you more options.

Title: the better url for a API: /api or api


问:
Java exception handling design
I am trying to design a simple exception handling strategy for web services middleware using some ideas from here: http://northconcepts.com/blog/2013/01/18/6-tips-to-improve-your-exception-handling/.

However I think it is worth it to have two exception classes inheriting from RuntimeException instead of just one.

The idea is to use one class to represent general faults (NPE, etc.) that can't be handled in place, and my strategy is to catch and log them in a single fault barrier so developers/devOps can troubleshoot them.  These exceptions should be wrapped and passed back hiding some implementation details to the users of the API?

The other class will represent the exceptions that should be passed back to the users of the API since they are expecting them and know how to handle them (say specific exceptional conditions that are part a web services API).

Any drawbacks of using these two exception classes or is it better to use just one class for everything?

Thanks.

答: I'd stick with one. Anytime you have an exception that isn't catastrophic, it isn't an exception. Log it to warn or error level then move on. Otherwise, you've just reinvented checked exceptions.</p>

Title: Java exception handling design


问:
How best to version control massive configuration for an application?
Apologies if this doesn't make sense, English is not my first language.

I'm working on an application where workflow is split into 'rules' that are defined on several pages of an Excel spreadsheet, a VB script strips out the descriptions of the states etc and leaves only numbers, then exports this configuration as MySQL that is then imported into the database from which the application works.

We have 2-3 developers working on the spreadsheet. Often the spreadsheet is opened from it’s location on a shared network drive, minor changes made and sometimes the version number is not incremented.

This makes it very hard to track changes and also who made them and why. Ideally we would pull the spreadsheet to a working directory, do a diff and commit changes then push them to a master repository. It seems like there are no viable tools to do such a thing with Excel.

So my question is what would be a better way to support a very large configuration, make it version controllable and still human readable?

答:
The first thing to do is to move to version control without modifying anything. Just get the files in there. If you discover any breakage later you can still retry.

Enforce a "lock" on the sources until you reach step 4.

Convert everything to a non-binary format. In the case of Excel you should be able to convert to OOXML, or you could go for a simpler format like ODS.

Verify that it all still works.

You can do this on a per-file basis if you want the files to be available as much as possible while doing the conversion. Or you could automate the conversion and (unless you have truly insane amounts) get it done in seconds.

At this point you're one step away from separating code and data properly (as @FrustratedWithFormsDesigner suggested), at which point you can leave the desert of horrible embedded code for the luxury of code reuse, non-procedural code and automated testing.


答:
The idea is to use one class to represent general faults (NPE, etc.)
  that can't be handled in place, and my strategy is to catch and log
  them in a single fault barrier so developers/devOps can troubleshoot
  them. These exceptions should be wrapped and passed back hiding some
  implementation details to the users of the API?

It sounds to me like you are doing this wrong. Don't wrap general faults in your code in other exceptions. That'll just make it harder for users of your API to figure out what's going on. Don't create your own fault barriers or log exceptions. The entire web application should have one fault barrier which logs all exceptions. All that you can accomplish by adding your own is logging things twice. Don't add another one for your middleware.

Title: Java exception handling design

Body:
I am trying to design a simple exception handling strategy for web services middleware using some ideas from here: http://northconcepts.com/blog/2013/01/18/6-tips-to-improve-your-exception-handling/.

However I think it is worth it to have two exception classes inheriting from RuntimeException instead of just one.

The idea is to use one class to represent general faults (NPE, etc.) that can't be handled in place, and my strategy is to catch and log them in a single fault barrier so developers/devOps can troubleshoot them.  These exceptions should be wrapped and passed back hiding some implementation details to the users of the API?

The other class will represent the exceptions that should be passed back to the users of the API since they are expecting them and know how to handle them (say specific exceptional conditions that are part a web services API).

Any drawbacks of using these two exception classes or is it better to use just one class for everything?

Thanks.


答:
I don't think this is a good idea. This introduces coupling in a very non-obvious way.

Consider a class or a service. It has clearly defined tasks, it's methods are well documented, it can be swapped out for something else that has the same interface/contract.

Suppose it encounters an exception. The service then can decide whether it is recoverable or not. That, in itself, is fine - if the service determines a failure is recoverable, it should recover. End of story.

Your version is quite different. In your question you are saying "The service decides whether the situation is recoverable by the caller". This is bad. How does your service know that? Why does it care for who calls it? Is it only callable from a very specific other class?

You mention NPEs as "general failure". It might not be. It might be a misconfiguration or bad data sent from a bad user, not programmer errors (Some may argue that it is a  programmer error to not account for that possibility, but that's not the point here). Is an IO exception a "general failure"? It might mean either that you need to use a backup connection (simple recovery), or someone ripped out the network adapter from a live system (not that simple to recover from). None of your classes, save the very last thread exception handler can decide whether the app can recover from something or not.

If you change the caller code to deal with some type of exception that was previously "unrecoverable", how do you know that you need to change the part that throws this exception?

The other point I disagree with you on is:

...inheriting from RuntimeException...

...should be passed back to the users of the API since they are expecting them...

I don't think this is a good usage of unchecked exceptions.

If the users of the API are supposed to be expecting these exceptions, why not make them checked and enforce it? Then unchecked exceptions will propagate all the way up and may be logged in a specific way - that will mean exactly what you want - None of the calling code was expecting or could deal with this exception. While "expected" exceptions will have to be dealt with, even if the calling code insists that all it does is log it (or even silently swallows it).

This has the extra benefit that API changes are documented! You can add more "expected exceptions" if they are runtime - and none will notice until it's already live! Whilst with checked once you won't be able to compile if you don't deal with the situation.

Title: Java exception handling design


问:
BPMN(business process modelling and notation)
I was curious to find out the advantages of black box pools over white box pools and vice versa. I know blackbox pools are used to model an external participant, whist whitebox pools are used in modelling entities whose process we are interested in. But is there really any  advantage of using one over the other or can we just pick and choose?</p>

答:
Your question maybe just a misunderstanding - you seem to believe there is a difference between those types of pools. But according to this documentation about BPMN, there is technically no difference between black-box and white-box pools - at least, when we talk about the notation. The only difference is the fact a black box pool is typically kept empty, and that is actually what it makes a "black box" - you don't see what is going on inside.

However, specific BPMN tools may introduce differences between those two kind of pools, assumed they provide you with two different symbols or elements. Maybe they use a slightly different notation, maybe they forbid actually to model the inner activities in a black-box-pool, or maybe they make no difference at all. So if you want to know how your modeling tool behaves, check the manual of your tool.


问:
Name/Fix for Production Code Whose Sole Purpose is to Facilitate Testing?
The linked "duplicate" question is an iffy match at best, because it's asking

is pattern X OK (YES/NO)

and I'm clearly already in the NO camp, and subsequently asking

what is pattern X called

what steps can be taken to fix pattern X

(neither of which are addressed by the linked question).

I recently did a code review on a block of code that looked something like this:

```<code>public class MyClass
{
    private ISomething mySomething;
    // ...Other variables omitted for brevity

    public MyClass() { mySomething = new Something();  }

    /// <summary>
    /// Constructor - ONLY USE THIS FOR UNIT TESTING
    /// </summary>
    public MyClass(ISomething something) { mySomething = something; }

    public void MyMethod()
    {
        // Gets called by the framework, and changes the internal state of the class by using mySomething...
    }

    // Other methods...
}
</code>```

I'm concerned specifically with the overloaded constructor. It was added purely to test this class, and will make its way into production code.

Is there a name for this pattern/anti-pattern, and what can be done to solve it?

For clarification, the implementation of Something was added specifically for the purpose of being able to add an overloaded constructor to MyClass. It's used nowhere else. Its existence is an instance of the very issue I'm concerned about.

ISomething is very tightly coupled to MyClass. It needn't have been extracted. Implementation and interface might as well look like:

```<code>public interface ISomething
{
    string GetClassName();
}

public class Something : ISomething
{
    public string GetClassName() { return "MyClass"; }
}
</code>```

That means that MyClass.MyMethod()'s body could just be replaced with return "MyClass";

However, the interface abuse/premature optimization seems like a separate issue and not in the spirit of the original question (i.e. consider it a given that the class/interface is structured like so and leave it as a separate [but valid] concern).

答:
It was added purely to test this class, and will make its way into production code.

This is shortsighted...

Having a constructor to pass in dependencies isn't done just to test the class. It's done to make your class flexible. The parameterless constructor that has a hard dependency on a concrete Something is more of the anti-pattern due to the tight coupling, and is added only for programmer convenience.


答:
One term which has been used for this recently is test induced design damage.

Telastyn is correct that your code snippet isn't actually a very good example of this concept, though.

A more common occurence is that a test wants to set up a class to be in a particular state during its "arrange" phase, but due to encapsulation, doesn't have any way to do that directly. So the test has to choose either to execute a series of steps to get the object to the desired state (which requires coupling the test to much more than just the particular statement it's trying to verify), or to break encapsulation. Choosing the latter option requires potentially-dangerous modifications to production code.

Title: Name/Fix for Production Code Whose Sole Purpose is to Facilitate Testing?

Body:
The linked "duplicate" question is an iffy match at best, because it's asking

is pattern X OK (YES/NO)

and I'm clearly already in the NO camp, and subsequently asking

what is pattern X called

what steps can be taken to fix pattern X

(neither of which are addressed by the linked question).

I recently did a code review on a block of code that looked something like this:

```<code>public class MyClass
{
    private ISomething mySomething;
    // ...Other variables omitted for brevity

    public MyClass() { mySomething = new Something();  }

    /// <summary>
    /// Constructor - ONLY USE THIS FOR UNIT TESTING
    /// </summary>
    public MyClass(ISomething something) { mySomething = something; }

    public void MyMethod()
    {
        // Gets called by the framework, and changes the internal state of the class by using mySomething...
    }

    // Other methods...
}
</code>```

I'm concerned specifically with the overloaded constructor. It was added purely to test this class, and will make its way into production code.

Is there a name for this pattern/anti-pattern, and what can be done to solve it?

For clarification, the implementation of Something was added specifically for the purpose of being able to add an overloaded constructor to MyClass. It's used nowhere else. Its existence is an instance of the very issue I'm concerned about.

ISomething is very tightly coupled to MyClass. It needn't have been extracted. Implementation and interface might as well look like:

```<code>public interface ISomething
{
    string GetClassName();
}

public class Something : ISomething
{
    public string GetClassName() { return "MyClass"; }
}
</code>```

That means that MyClass.MyMethod()'s body could just be replaced with return "MyClass";

However, the interface abuse/premature optimization seems like a separate issue and not in the spirit of the original question (i.e. consider it a given that the class/interface is structured like so and leave it as a separate [but valid] concern).


答:
It's called "production code included for the sole purpose of facilitating testing."

If you're using it a lot, I'd say it's an anti-pattern.  The way you mitigate it is to write your classes using dependencies which conform to an Interface and are supplied using Dependency Injection, and then use stubs and mocks to isolate the class for testing.

But the reality is that it's hard to isolate some classes.  Despite its reputation for testability, ASP.NET MVC has some features in it like HttpContext that are notoriously difficult to mock.  Classes that are designed to perform file handling can be difficult to test without helper code, because you have to set up elaborate file and folder scenarios to test them.  So I can see legitimate reasons for including such code.


答:
For methods of a class which are solely for testing purposes, I have seen the name maintenance hatch in the past. And similar to real maintenance hatches in physical machines, those methods sometimes have their purpose. For example, if you are going to make some legacy code testable when it has grown too big after some years of evolving, maintenance hatches can be of great value.

But I also agree to the other answers here, such methods should be an exception, and when you keep classes and components small, with well designed interfaces, you seldom need them.


问:
Bulk update in client-server application
Sometimes when coding a client-server application, the client needs to make a bulk update. For example: "mark all pending orders as dispatched". To implement these I typically write specific controller methods, which perform the required database operation.

It crossed my mind that theoretically this could be done without specific controller methods. In a simple approach, the client could iterate through the pending orders (which it can already access) and mark each as dispatched (again, it already has a call to do this). The problem with that approach is that it causes many network round-trips, increasing latency.

But this made me wonder, is there some kind of generic client-server query/update language? I would hesitate to allow SQL from client to server, unless I could create some very tight controls to prevent SQL injection. But in principle I want to client to tell the server to "UPDATE orders SET status='dispatched' WHERE status='pending'" - and the server to action this, while enforcing any security controls applicable to the current user.

I figured this probably already has a solution, I just don't know the name of it - hence this question. Any help appreciated.

Edit: on reflection, maybe this is a bad idea. When I explicitly code a controller, I can ensure the database has appropriate indexes to make the update efficient. If the query only exists on the front-end, then ensuring appropriate indexes are in place creates an uncomfortable front/back dependency.

答: Look into the SQL COPY command. It can take data as input and insert it into a table. So, SQL injection would not be an issue. You would just have to require a data-format for the file, or build an interface for the user to specify it.</p>


问:
how python updates references to variables
For this while loop below. It is clear how the v1,v2,v3 are updated to new data objects based on the equation. But I do not understand how u1,u2,u3 retains the original values of v1,v2,v3.Can someone help clarify? So u1 points to the original data referenced by v1 but not the new reference for v1. </p>

```<code>def findModInverse(a,m):
    if gcd(a,m) != 1:
        return None
    u1,u2,u3 = 1,0,a
    v1,v2,v3 = 0,1,m

    while v3 != 0:
        q = u3 // v3
        v1,v2,v3,u1,u2,u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3
    return u1 % m

    mod = findModInverse(7,26)
</code>```

答:
The right hand side of an assignment is evaluated first.

Then, if there are multiple targets, then the right-hand side should be a sequence and each element of that result is assigned from left-to-right to the targets.

This means that you first get a tuple with:

```<code>((u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3)
</code>```

and then the results of that expression are assigned to the v1, v2, v3, u1, u2, u3 targets from left to right.

So first, the current values of v1, v2 and v3 are stored, and these 3 names are only rebound to their new values after all the right-hand-side expressions have been evaluated.

Also see How does swapping of members in the python tuples (a,b)=(b,a) work internally?

Body:
The right hand side of an assignment is evaluated first.

Then, if there are multiple targets, then the right-hand side should be a sequence and each element of that result is assigned from left-to-right to the targets.

This means that you first get a tuple with:

((u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3)

and then the results of that expression are assigned to the v1, v2, v3, u1, u2, u3 targets from left to right.

So first, the current values of v1, v2 and v3 are stored, and these 3 names are only rebound to their new values after all the right-hand-side expressions have been evaluated.

Also see How does swapping of members in the python tuples (a,b)=(b,a) work internally?


答:
Think of it as a binary number where all the ones are your pieces.  To simplify my explanation, I'll just consider one row of 8.  The rest all work similarly.

Consider a winning case of four in a row:  11110000.  board && (board >> 1) gives you 1110000, which is all the ones with a one immediately adjacent to the left.  Doing this again with y & (y >> 2) does the same check, but for two to the left.  The combination of the two yields a non-zero value when you get four in a row.

The other offsets do the same thing, but wrapping to the next row instead of checking immediately adjacent squares.  8 wraps immediately below, 7 wraps below but one to the left, and 9 wraps below but one to the right.

This happens to be possible because of the powers of two involved.  In a 3x3 grid you can't do something similar.  You can use it to check for two in a row or four in a row, but not three.

That being said, even if the bit-shifting did work for tic-tac-toe, you shouldn't use it.  Connect four has 4,531,985,219,092 possible games, so it makes sense to optimize this function as much as possible, to be able to compute a deeper tree in a reasonable time, even if that means sacrificing some readability.  Tic-tac-toe has only 255,168 possible games, which means you can recalculate every combination on every move in a naïve way, and still have time to spare.  In such cases, readability should be paramount.

There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies.

—Turing award winner Tony Hoare

The reason you don't optimize when you don't have to is the bugs are no longer obvious.  For example, the following board is incorrectly reported as a win:

```<code>10000001
00000010
00000100
00000000
00000000
00000000
00000000
00000000
</code>```

Title: Determining the winning condition for Tic-Tac-Toe

Body:
I'm writing a tic-tac-toe game in C++ and now I found a function to check if a player has a winning board for a connect four game.

The function looks like this:

```<code>bool haswon(int64_t board)
{
    int64_t y = board & (board >> 7);
    if (y & (y >> 2 * 7)) // check \ diagonal
        return true;
    y = board & (board >> 8);
    if (y & (y >> 2 * 8)) // check horizontal -
        return true;
    y = board & (board >> 9);
    if (y & (y >> 2 * 9)) // check / diagonal
        return true;
    y = board & (board >> 1);
    if (y & (y >> 2))     // check vertical |
        return true;
    return false;
}
</code>```

I would be looking for an explanation of the above function.

Then I could perhaps try to implement the same thing for my tic-tac-toe. I'm fairly OK with the bitwise operators

```<code>#include <iostream>
#include <bitset>

namespace tictactoe {

    constexpr std::size_t N = 3;

    using board = std::bitset<N*N>;

    constexpr char NOUGHT = 'O';
    constexpr char CROSS = 'X';

    bool curr_move_noughts = true;

    board combined() {
        return noughts | crosses;    // combined bit board for both players
    }

}
</code>```

Body:
Think of it as a binary number where all the ones are your pieces.  To simplify my explanation, I'll just consider one row of 8.  The rest all work similarly.

Consider a winning case of four in a row:  11110000.  board && (board >> 1) gives you 1110000, which is all the ones with a one immediately adjacent to the left.  Doing this again with y & (y >> 2) does the same check, but for two to the left.  The combination of the two yields a non-zero value when you get four in a row.

The other offsets do the same thing, but wrapping to the next row instead of checking immediately adjacent squares.  8 wraps immediately below, 7 wraps below but one to the left, and 9 wraps below but one to the right.

This happens to be possible because of the powers of two involved.  In a 3x3 grid you can't do something similar.  You can use it to check for two in a row or four in a row, but not three.

That being said, even if the bit-shifting did work for tic-tac-toe, you shouldn't use it.  Connect four has 4,531,985,219,092 possible games, so it makes sense to optimize this function as much as possible, to be able to compute a deeper tree in a reasonable time, even if that means sacrificing some readability.  Tic-tac-toe has only 255,168 possible games, which means you can recalculate every combination on every move in a naïve way, and still have time to spare.  In such cases, readability should be paramount.

There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies.

—Turing award winner Tony Hoare

The reason you don't optimize when you don't have to is the bugs are no longer obvious.  For example, the following board is incorrectly reported as a win:

10000001
00000010
00000100
00000000
00000000
00000000
00000000
00000000


问:
How to introduce Google Analytics code in a modular way?
We are working on a very large codebase. It's basically a web-based operating system, with its own file system and applications. The system's UIs are generated dynamically with Javascript.

We've decided to introduce Google Analytics to track various user activities.

Our concern is that in order to send data to Google Analytics servers on these events we'd have to scatter analytics code in all event handlers. Even if we wrap the analytics calls in a module, we'd still have to call it. E.g. usual code:

```<code>$(importButton).on('click', function() {
    // ... call import module to do import stuff
})
</code>```

becomes, roughly speaking

```<code>$(importButton).on('click', function() {
    // ... call import module to do import stuff
    analytics.registerEvent('import')
})
</code>```

And so the analytics code becomes extremely tightly coupled to the interface logic.

How do we introduce analytics in a modular fashion, without scattering analytics calls over all event handler functions?

答:
You don't have to change existing code, because you can just add more event handlers. JavaScript naturally supports multiple event handlers on a single element, and it's even easier with libs/frameworks like jQuery:

```<code>// in existing code:
$('#button').on('click', function (event) {
    console.log('normal behavior');
});

// somewhere else:
$('#button').on('click', function (event) {
    console.log('user tracking');
});
</code>```

This does not affect performance significantly and you can always improve it with event delegation.

Body:
You don't have to change existing code, because you can just add more event handlers. JavaScript naturally supports multiple event handlers on a single element, and it's even easier with libs/frameworks like jQuery:

// in existing code:
$('#button').on('click', function (event) {
    console.log('normal behavior');
});

// somewhere else:
$('#button').on('click', function (event) {
    console.log('user tracking');
});

This does not affect performance significantly and you can always improve it with event delegation.


问:
Speech Recognition in the .NET framework is not efficient
I want to create a Virtual Keyboard that can catch whatever key you 'speak' and send the keystroke to the active application. The Virtual Keyboard part and linking it to Speech Recognition will be done easily but the problem I am suffering is that the Speech Recognition is inefficient!

For example I say 'c' and it takes it as 'v' or something. This is extremely irritating and though it works with the microphone on my Logitech headset, it still doesn't recognize what I am saying sometimes... It's worse with the default microphone on my Lenovo laptop.

But it is weird that the Google speech recognition thing on the Google Search Engine works perfectly, with or without mike... Why is that?

Is there a way to improve my program?

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Speech.Synthesis;
using System.Speech.Recognition;
using System.Threading;

namespace TextToVoice
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        SpeechSynthesizer sSynth = new SpeechSynthesizer();
        PromptBuilder pBuilder = new PromptBuilder();
        SpeechRecognitionEngine sRecognize = new SpeechRecognitionEngine();

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            pBuilder.ClearContent();
            pBuilder.AppendText(textBox1.Text);
            sSynth.Speak(pBuilder);

        }

        private void button2_Click(object sender, EventArgs e)
        {
            button2.Enabled = false;
            button3.Enabled = true;
            Choices sList = new Choices();
            sList.Add(new string[] { "one", "2", "3", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"});
            Grammar gr = new Grammar(new GrammarBuilder(sList));
            try
            {
                sRecognize.RequestRecognizerUpdate();
                sRecognize.LoadGrammar(gr);
                sRecognize.SpeechRecognized += sRecognize_SpeechRecognized;
                sRecognize.SetInputToDefaultAudioDevice();
                sRecognize.RecognizeAsync(RecognizeMode.Multiple);

            }

            catch
            {
                return;
            }
        }

        void sRecognize_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {

            if (e.Result.Text == "exit")
            {
                Application.Exit();
            }
            else if (e.Result.Text == "how are you")
            {
                sSynth.Speak("I am fine");
                textBox1.Text = "";
                pBuilder.ClearContent();
            }
            else if (e.Result.Text == "hey")
            {
                sSynth.Speak("Hello sir");
                textBox1.Text = "";

            }
            else
            {
                textBox1.Text = textBox1.Text + " " + e.Result.Text;

            }

            }

        private void button3_Click(object sender, EventArgs e)
        {
            button2.Enabled = true;
            button3.Enabled = false;
        }
        }
    }
</code>```

Okay an edit..
Basically is there a way to create a program that can improve the application's UNDERSTANDING of what I am speaking? Like Windows Speech Recognition does by making us read text and then understanding how I speak words or whatever, except that that is too tedious :P

答:
The quality of speech recognition depends on many parameters:

Microphone: as you noted, a headset microphone is better than the one in your laptop. Studio microphones will give the best results, I imagine.

Environment: you'll have hard time making speech recognition work in a noisy environment compared to a quiet one (ideally a studio).

Pronunciation: for instance, I'm not a native English speaker and have a poor accent, and when I tried to use Google's speech recognition, half of the time, Google understands something else. At the same time, it understands practically everything when my girlfriend is speaking.

Dictionary: if you pronounce words which actually exist, speech recognition engine may improve its process by using a dictionary of words. For example, if you pronounce "elephant", it has a good chance of getting it right. If you tell "eglefont", none of the engines will be able to write the word.

Contextual subsets: if the dictionary is bound to a context, it will be easier for the engine to understand you. For example, asking the engine to type what you say is much more difficult than asking it to understand just four commands: "start", "stop", "move left" and "move right".

While the first three points may help improving the recognition in general, I think you should first focus on the last two points.

What is happening, I imagine, is that the recognition engine in your application is trying to understand words, and is unable to do that because you are pronouncing only letters. I don't think the fact that you've specified just letters is relevant: it may be that the Grammar is still interpreting this as words, although Windows' Text to Speech understands that single letters are actually letters, not words.

Since speech recognition in Windows can also be trained for a specific voice/pronunciation, there might be a way to train it for specific words (in your case, single letters). This being said, I haven't used this part of .NET Framework, so I don't know how much is it customizable.

Also related: Jeff Atwood, Whatever Happened to Voice Recognition?


问:
Understanding Visual Studio Community Edition license
Recently Microsoft has released a free version of Visual Studio: Visual Studio Community Edition

the license says

IF YOU COMPLY WITH THESE LICENSE TERMS, YOU HAVE THE RIGHTS BELOW.

INSTALLATION AND USE RIGHTS.

a.   Individual license. If you are an individual working on your own
  applications to sell or for any other purpose, you may use the
  software to develop and test those applications.

b.   Organization licenses. If you are an organization, your users may
  use the software as follows:

·       Any number of your users may use the software to develop and
  test your applications released under Open Source Institute
  (OSI)-approved open source software licenses.

·       Any number of your users may use the software to develop and
  test your applications as part of online or in person classroom
  training and education, or for performing academic research.

·       If none of the above apply, and you are also not an enterprise
  (defined below), then up to 5 of your individual users can use the
  software concurrently to develop and test your applications.

·       If you are an enterprise, your employees and contractors may
  not use the software to develop or test your applications, except for
  open source and education purposes as permitted above. An “enterprise”
  is any organization and its affiliates who collectively have either
  (a) more than 250 PCs or users or (b) more than one million US dollars
  (or the equivalent in other currencies) in annual revenues, and
  “affiliates” means those entities that control (via majority
  ownership), are controlled by, or are under common control with an
  organization.

c.   Demo use. The uses permitted above include use of the software in
  demonstrating your applications.

d.   Backup copy. You may make one backup copy of the software, for
  reinstalling the software.

As an "Individual" I'm interested in the clause "a", however it's not that clear and explicit. for me it sounds a bit restrictive as it does not cover a wide range of usage (Open source, freelance work, contribution to applications you don't own etc), the confusion comes exactly from the terme 'OWN' used in the sentence,
I may be misinterpreting the whole thing as English is not my native language.
So how would you interpret the sentence?
Can we assume that we can use a software if the license does not make it clear, for example "it's not allowed to use it in this or that senario" as for "Entreprises" in the clause "b"?

答:
Clause (a): "... working on your own applications ..."
The example cited by Dudley is a situation where the small agency is creating what's known as a "work for hire" -- the work in question will belong to the Fortune 500 firm. Normally it is not the small agency's "own application".  The agency cannot, for example, sell it or give it away on street corners or open-source it -- because the created work belongs to the Fortune 500 firm.  Note that this would still be true if the company outsourcing the work to the small agency was a small company.  US law is clear in these situations: works which normally would be the property of their creator(s) are the property of the outsourcing firm.  The size of the outsourcing firm is not the controlling factor. It is the nature of the outsourcing relationship.  (The same ownership rules prevail when you agree to do development work for a firm as a temporary contractor.)

In order for the small agency to claim the work as its own -- and therefore be able to argue that clause (a) applies -- it should have a provision in its contractual agreement with the firm that specifies the small agency retains ownership of the software and other intellectual property it creates during the engagement.  It can also include a provision that grants the firm an unrestricted, perpetual right to use the software for its internal operations and/or make it available for use by its customers as a mobile store-locator.

Be aware that most firms will not readily agree to leave ownership of the intellectual property with the developer, and most other developers competing for the business will not ask for such terms.


问:
Would you use C, today, for a software project?
If yes, where and why would you use it?

If no, please provide an explanation to why C is not acceptable to you.

答:
Yes, I would use C in a severely resource-constrained embedded system. I may use C++ instead because it makes it easy to promote strong interfaces between software components, but only if all engineers working on the project understand that C++ is easy to misuse leading to code size bloat (virtual functions and templates are examples of things to avoid).

I also saw a C++ programmer trying to create a 10K object on a 1K stack, not a good idea.

ContentLicense: CC BY-SA 2.5


问:
How to solicit new product recommendations from existing clients?
My company is working on developing a new product that is similar (but larger in scope) than our existing, primary application. It will incorporate most of the functionality of our current application (except where that functionality isn't currently being used) and eventually supplant it.

Our initial thought was to solicit product suggestions and feedback on mock-ups from certain members of our current clientele who have made multiple feature suggestions in the past. This seemed good in theory, as we could get a larger perspective from our projected user base as well as getting buy-in from those customers who might have had feature requests they previously made indefinitely postponed.

In practice what we're getting is a lot of silence. We have meetings with this group every two weeks to get their feedback and suggestions. However, they rarely - if ever - have anything to add. We've tried emailing out to them a few weeks in advance, asking for their suggestions on a certain feature that we intend to design and mock-up for them on x date, and no suggestions come back to us. When we ask for feedback on existing mock-ups during the meetings, the response is always along the lines of "Oh, that looks good...I'll get back to you if I think of any problems." This leaves us extremely anxious.

TLDR: The concern is that while our design may look great to us and our business team, our customer base won't like it (there are many areas it is radically different, based on things we implemented poorly the first time around). Can anyone offer any suggestions on ways we can better solicit feedback?

Edit: Please note that I'm not asking how to proceed without client involvement. Rather, I'm looking for suggestions on how to convince people that it's in their best interest to be more involved.

答:
You really can't "solicit" those requests.

What you have to do is go out and LIVE with those clients, and see how they are ACTUALLY using your product, and see what is ACTUALLY eating them alive, causing them to curse you and your ancestors in languages long forgotten except for the specific purpose of calling down the wrath of gods best left undisturbed.

THAT'S how you find out what they NEED.

Talking to their managers WON'T WORK.

And understand something: I'm not spouting something I read in some book somewhere.  I walked the walk on this one.  Thirty years ago, I got tagged to do what today would be called a simple bug-tracker.  We got lots of input from management on what they thought they wanted.  I threw almost all of that in the circular file next to my desk, and went out to the Systems Integration Lab and talked to the guys in the trenches about what they actually did.  What they really needed was immediately blindingly obvious.

And that's what I built.

And it was a screaming howling success.


问:
Notify about starting event
I am having quite a hard time figuring out how to solve this problem. Basically I have a mini social network with notifications and events. I want to add such functionality where 1 day before an event is about to start and 1 hour before the event starts, users participating in the event get notifications that the event is respectively starting in 1 day or 1 hour.

I'm using MySQL + PHP so this is how I think about it:

In my events table I have a column of type DATETIME which holds the starting date and time of each event. In order to be able to send notifications for starting events I need to run checks and this is where I'm having a bit of trouble. If I check with this technique

```<code>SELECT * FROM events WHERE starting > NOW() AND starting - INTERVAL 1 DAY < NOW()
</code>```

I will check for events with a starting time between 00:00 today and 23:59 today. However this means that I am only supposed to run 1 check per day which is not reliable and is also impossible to solve the 1 hour before event starts notification problem. Also I think this would be inefficient because this query is not a simple select, meaning that only one of the expressions will benefit from the index, the other one will still have to loop through all results the first one found. I suppose this may be a minimalist concern but it matters to me.

Can anyone suggest another solution to this problem? I am not looking for complete code but an idea that can be realized in either MySQL or PHP, but I'm looking for it to be efficient and simple.

Also another concern I have, as a side question: in time, the table events will eventually get filled up with events and many if not most of them will be past events that have already happened, therefore I am asking myself if it would be a good idea to create another table for past events and move those there, in order to not slow down mysql when searching for events that are about to start to send out notifications?

答:
Create a table which will store information about notifications:

```<code>TABLE notifications
    event_id
    user_id
    datetime // date and time when notification must be sent
</code>```

Every time someone joins some event, you should insert a new row in the notifications table.

To notify users, you need script which will perform a mysql query like:

```<code>SELECT * FROM notifications WHERE `datetime` <= NOW()
</code>```

After selecting users, notify them and delete the rows from table.

This script may be started automatically by cron. The shorter the interval between script starts, the more precise the notification.

Title: Notify about starting event

Body:
Create a table which will store information about notifications:

TABLE notifications
    event_id
    user_id
    datetime // date and time when notification must be sent

Every time someone joins some event, you should insert a new row in the notifications table.

To notify users, you need script which will perform a mysql query like:

SELECT * FROM notifications WHERE `datetime` <= NOW()

After selecting users, notify them and delete the rows from table.

This script may be started automatically by cron. The shorter the interval between script starts, the more precise the notification.


答:
One multi-lingual/multi-platform programmer's thoughts ...

Are the methods in question in the same class as main?  If so, they can manipulate the values regardless of the declared access (public/private....). So I assume your question refers to methods which are defined in some other classes.  The performance impact of the various options will be irrelevant 99.99% of the time. Not worth spending brain cycles there.

If my main method needs read/write access to a group of variables and a group of methods in other classes need only read access to those variables, I'm inclined to think of the variables are being part of "the context" of all those computations.  Defining a "context object" in main's class -- what Dylan called "Data" -- makes for neater source code, especially if the variables receive their value during context's initialization and these values are never changed.  The question then becomes: do I pass the context as an argument when I call the methods or do I make it public/protected/package access?

The best reason for me to pass the context explicitly when I call the methods is that doing so makes it blatantly obvious that the methods use the context variables -- a programmer reading my code doesn't need to examine each and every method to determine whether it depends on the context. In that case I would explicitly declare the context private if I don't want it directly referenced from any subclass of main's class, or protected if I'm willing to permit a subclass to directly reference it -- because, for example, the subclass needs to extend the initialization logic for context.

If I decided not to worry about making that dependence obvious, I might declare the context to have package (I'm feeling a little wild and crazy) or public access (I'm completely high and throwing caution to the winds).  Personally I favor getting crazy and high somewhere other than my code ;-)

Title: Passing by value multiple times vs. Creating a public class variable

Body:
Suppose I have a series of methods across different classes that all use the same five core variables defined in my main method. I could chain these five variables as method arguments from one method to the next, or I could simply define these five variables as public class variables and reference their path each time I want to use them.

What is considered more readable, and what is more efficient it terms of processing time? These values will not change throughout their lifespan in the program and take the form of Boolean values, multidimensional int[] arrays, and single dimensional int[] arrays.


答:
The idea is to use one class to represent general faults

There are no "general" faults. NPE, for example, can be thrown manually, so you can't even tell if it's intentional or not. There are also misused exception classes or something you just don't know about. How would the "wrapping" look in the code? I imagine:

```<code>try {
    //...
} catch (ExceptionType1 e) {
    throw new MyException(e);
} catch (ExceptionType2 e) {
    throw new MyException(e);
} catch (...) {
    //...
} catch (ExceptionTypeN e) {
    throw new MyException(e);
}
</code>```

I've seen lots of that - it is horrible to maintain.

my strategy is to catch and log them in a single fault barrier

Just catching and logging is not always the right way. Here are the rules I try to use:

If exception can be handled, it should be. No need to tell a user about it, unless it can only be handled by a user.

If it cannot be handled, then:

If you can provide additional information about the context - wrap it. Wrapper exception should accept initial exception as it's cause (getCause()), so stack trace is not broken.

If you cannot provide additional information - rethrow it, because it may be handled somewhere above.

Top-level catching is an extreme measure in case something really unexpected happened. I consider it a safety net which prevents showing ugly stack traces to users, who can potentially have malicious intents.

Exceptions should be logged as soon as possible, providing helpful message with enough information about a context to figure out what's happened. If exception is caught and handled, no need to log full stack trace - simple warning would be enough.

Consider logging error message and stack trace with different warning levels: e.g. ERROR for message, DEBUG for stack trace. That way you can keep your logs clean, turning DEBUG logging level only when needed to see a full details. Also you can put log messages with different log levels in separate log files.

Title: Java exception handling design

Body:
The idea is to use one class to represent general faults

There are no "general" faults. NPE, for example, can be thrown manually, so you can't even tell if it's intentional or not. There are also misused exception classes or something you just don't know about. How would the "wrapping" look in the code? I imagine:

try {
    //...
} catch (ExceptionType1 e) {
    throw new MyException(e);
} catch (ExceptionType2 e) {
    throw new MyException(e);
} catch (...) {
    //...
} catch (ExceptionTypeN e) {
    throw new MyException(e);
}

I've seen lots of that - it is horrible to maintain.

my strategy is to catch and log them in a single fault barrier

Just catching and logging is not always the right way. Here are the rules I try to use:

If exception can be handled, it should be. No need to tell a user about it, unless it can only be handled by a user.

If it cannot be handled, then:

If you can provide additional information about the context - wrap it. Wrapper exception should accept initial exception as it's cause (getCause()), so stack trace is not broken.

If you cannot provide additional information - rethrow it, because it may be handled somewhere above.

Top-level catching is an extreme measure in case something really unexpected happened. I consider it a safety net which prevents showing ugly stack traces to users, who can potentially have malicious intents.

Exceptions should be logged as soon as possible, providing helpful message with enough information about a context to figure out what's happened. If exception is caught and handled, no need to log full stack trace - simple warning would be enough.

Consider logging error message and stack trace with different warning levels: e.g. ERROR for message, DEBUG for stack trace. That way you can keep your logs clean, turning DEBUG logging level only when needed to see a full details. Also you can put log messages with different log levels in separate log files.


问:
Is there a standard to imitating an async filestream
Im trying to replace an async filestream method, which is reading data from a Hid Device and feeding it to the UI. Ive considered writing the output into a log and then importing that log again, but that just seems to over complicated.

The whole reason behind this is to be able to test the program without the controller beeing connected. So either I create a test file which can be read into to create the desired output or i just completley randomize the dataset.

Is there another maybe better way of handling this?

答: Read from a pipe instead of the device. My guess is you won't have to change anything if you do that. Then you can write whatever you want to the pipe and retain all the async goodness.</p>


问:
Pretty splitting of lines?
```<code><?php
        if (in_array(exec("pboxsvc pboxlib.bin DeterminarTipoSpool' $idJob"),
                     ['IPP','PSFORM','PBSSFORM','PDF'])):
    ?>
</code>```

How would you refactor that line to be "eye-candy" and actually note what is going on easily?

I often come to the need of splitting lines in conditionals having functions, or arrays, etc, is there any online compilation?

答:
There are a couple of competing styles for formatting function arguments. All of them make sense, but have differences regarding vertical and horizontal space usage, commentability, and how clearly diffs will point out the change.

The styles can first be divided by where they place the first function argument: On the same line or on the second line:

```<code>// same line
foo(bar,
    baz)

// separate line
foo(
    bar,
    baz
)
</code>```

Placing the argument on the same line is more compact, but placing everything on a line of its own leads to better diffs: If we see that the line foo(bar, was changed, we do not immediately know whether the function or the argument were changed.

The second choice is how to align arguments on the consecutive lines. We can either use a fixed indent, or align them with the parentheses of the function call:

```<code>// fixed indent
foobar(
    baz,
    qux
)

// align with parens
foobar(baz,
       qux)
</code>```

Using a fixed indent keeps the total indentation of the arguments smaller, leaving more horizontal space to be used. You could e.g. use this space for a line comment to explain what each argument means. Aligning the arguments at the opening parenthesis looks better, especially when you do not place the first argument on a line of its own. The remaining line for each argument is rather short, which also happens to discourage deep nesting. Whether or not that's a good thing is another debate.

However you decide to place your arguments, it is important that they are vertically aligned. So this style makes little sense:

```<code>foobar(baz,
    qux)
</code>```

Then, we can choose where to place the closing parenthesis. We can either put it immediately after the last argument (which is nice and compact), or put it on a line of its own, where we can align it with the function name, the opening parenthesis, or somewhere in between.

```<code>// same line
foobar(baz,
       qux)

// align with function name
foobar(
  baz,
  qux,
)

// align with opening paren
foobar(
       baz,
       qux,
      )

// somewhere in between
foobar
  (
    baz,
    qux
  )
</code>```

Using a line of its own has the advantage that adding a line for another argument only marks that line as changed in a diff; otherwise the previous line would also be changed because you have to remove the parenthesis. If you place the closing parenthesis on a line of its own and your language supports this (PHP does), then you should also put a comma after the last argument as well, for this same reason.

If you align the closing paren with the function name, this creates a strong visual relation between the function and the closing paren, but aligning it with the opening paren clearly demarks the block of arguments. The exact same arguments as for bracing style apply here, where some ecosystems favour “egyptian brackets”, while others prefer to put each brace on a line of its own.

So, there's a good argument for almost any style. The important part is to make a well-informed choice and stick to it. I prefer styles that enhance diffability and allow deep nesting:

```<code>foobar(
  baz,
  qux,
)
</code>```

Title: Pretty splitting of lines?

Body:
There are a couple of competing styles for formatting function arguments. All of them make sense, but have differences regarding vertical and horizontal space usage, commentability, and how clearly diffs will point out the change.

The styles can first be divided by where they place the first function argument: On the same line or on the second line:

// same line
foo(bar,
    baz)

// separate line
foo(
    bar,
    baz
)

Placing the argument on the same line is more compact, but placing everything on a line of its own leads to better diffs: If we see that the line foo(bar, was changed, we do not immediately know whether the function or the argument were changed.

The second choice is how to align arguments on the consecutive lines. We can either use a fixed indent, or align them with the parentheses of the function call:

// fixed indent
foobar(
    baz,
    qux
)

// align with parens
foobar(baz,
       qux)

Using a fixed indent keeps the total indentation of the arguments smaller, leaving more horizontal space to be used. You could e.g. use this space for a line comment to explain what each argument means. Aligning the arguments at the opening parenthesis looks better, especially when you do not place the first argument on a line of its own. The remaining line for each argument is rather short, which also happens to discourage deep nesting. Whether or not that's a good thing is another debate.

However you decide to place your arguments, it is important that they are vertically aligned. So this style makes little sense:

foobar(baz,
    qux)

Then, we can choose where to place the closing parenthesis. We can either put it immediately after the last argument (which is nice and compact), or put it on a line of its own, where we can align it with the function name, the opening parenthesis, or somewhere in between.

// same line
foobar(baz,
       qux)

// align with function name
foobar(
  baz,
  qux,
)

// align with opening paren
foobar(
       baz,
       qux,
      )

// somewhere in between
foobar
  (
    baz,
    qux
  )

Using a line of its own has the advantage that adding a line for another argument only marks that line as changed in a diff; otherwise the previous line would also be changed because you have to remove the parenthesis. If you place the closing parenthesis on a line of its own and your language supports this (PHP does), then you should also put a comma after the last argument as well, for this same reason.

If you align the closing paren with the function name, this creates a strong visual relation between the function and the closing paren, but aligning it with the opening paren clearly demarks the block of arguments. The exact same arguments as for bracing style apply here, where some ecosystems favour “egyptian brackets”, while others prefer to put each brace on a line of its own.

So, there's a good argument for almost any style. The important part is to make a well-informed choice and stick to it. I prefer styles that enhance diffability and allow deep nesting:

foobar(
  baz,
  qux,
)


问:
Who writes the technical 'user stories' in scrum
I know that a product owner should write a user story in scrum.

A user story is describing a feature for the end user.

But who describes what needs to be technically developed and how it needs to be implemented

and where is that information stored concerning scrum?

That would really interest me!

I see a big lack of knowledge in our company when developer start to implement the story but they do not know HOW to implement it!

For example they have to deal with a legacy COM API and have no idea how to handle it or they are not that technically skilled with WPF/WEB or whatever.

How does scrum help that people to start with the user story?

答:
Non-agile-hater here. Fleshing out the details of implementation and determining the tasks that need to be done happens during the sprint planning meeting, which will turn the user stories into actual tasks/requirements for the sprint. The failure of many agile processes is that the sprint planning meeting is actually supposed be done largely by the developers...if it is just the product owners, they'll just decide to get the moon. This is where you'd come up with a (rather nebulous) user story like:

```<code>As a non-technical user, I need to have a simpler interface with the API
</code>```

While the product owner defines which user stories are the highest priority, then the programmers take those priorities and turn them into a list of tasks (called the sprint backlog). This is where you get the idea of how you are going to implement things...the sprint backlog can be as technical as you please. This is also where you'll find out "to achieve a simpler API, we'll have to refactor that crazy COM API. Anyone know how to use that?". When the answer is "Hell No" you'll start to see that the scope of that user story might be larger than it seems. Given that, you should could break the user story into the tasks:

Document and understand the current API

Design new API

Implement new API

Whatever...

Given this, it is OK to negotiate the user stories to break them into smaller changes. The agile methodology means that you want to approach what the person wants in incremental steps. So you may say "Hey look. We can't overhaul the API in just one iteration. Lets split it into 'As a non-technical customer, I need a well documented API' ect".

Body:
Non-agile-hater here. Fleshing out the details of implementation and determining the tasks that need to be done happens during the sprint planning meeting, which will turn the user stories into actual tasks/requirements for the sprint. The failure of many agile processes is that the sprint planning meeting is actually supposed be done largely by the developers...if it is just the product owners, they'll just decide to get the moon. This is where you'd come up with a (rather nebulous) user story like:

As a non-technical user, I need to have a simpler interface with the API

While the product owner defines which user stories are the highest priority, then the programmers take those priorities and turn them into a list of tasks (called the sprint backlog). This is where you get the idea of how you are going to implement things...the sprint backlog can be as technical as you please. This is also where you'll find out "to achieve a simpler API, we'll have to refactor that crazy COM API. Anyone know how to use that?". When the answer is "Hell No" you'll start to see that the scope of that user story might be larger than it seems. Given that, you should could break the user story into the tasks:

Document and understand the current API

Design new API

Implement new API

Whatever...

Given this, it is OK to negotiate the user stories to break them into smaller changes. The agile methodology means that you want to approach what the person wants in incremental steps. So you may say "Hey look. We can't overhaul the API in just one iteration. Lets split it into 'As a non-technical customer, I need a well documented API' ect".


问:
Why is cleverness considered harmful in programming by some people?
I've noticed a lot of questions lately relating to different abstraction techniques, and answers saying basically that the techniques in question are "too clever." I would think that part of our jobs as programmers is to determine the best solutions to the problems we are given to solve, and cleverness is helpful in doing that.

So my question is: are the people who think certain abstraction techniques are too clever opposed to cleverness per se, or is there some other reason for the objection?

EDIT: This parser combinator is an example of what I would consider to be clever code. I downloaded this and looked it over for about half an hour. Then I stepped through the macro expansion on paper and saw the light. Now that I understand it, it seems much more elegant than the Haskell parser combinator.

答:
This is my understanding of the issue, based on my experience and the other answers:

Code that took cleverness to write, but comes out readable and maintainable is not considered harmful. However, most developers would not call that kind of code "clever"; they may use a different term like "elegant". There may or may not be some debate about whether such code exists.

Production code that requires significant time and effort to understand even by a seasoned developer familiar with the language is "clever" and considered harmful by everyone.

Production code that requires significant time and effort by inexperienced developers is considered harmful by some. I've seen answers either way, and I've worked with developers who've said explicitly that they would prefer to keep everything "lowest common denominator".


问:
What do I use for a variant in a UML class diagram?
Does standard UML specify how a variant (aka tagged union, discriminated union, sum type, etc) should be depicted in a class diagram? </p>

答:
A classifier in UML can encompass multiple subclassifiers that form something they call a "generalization set" which can be a complete partitioning of the instances of a superclass.  There's a graphical notation for this in class diagrams.  So, you can have a classifier C that has subclasses P Q R ... with the property that any instance of C must be an instance of exactly one of P Q R ... That is the closest I've been able to come to a UML visualization of union.  OOP folk seem to think of the superclass "coming first" and then deriving the subclasses, which is not quite the same "feel" as the union perspective which is about defining C in terms of P Q R.  But if you think of the UML class diagram as describing possible run-time object graphs rather than picturing source code, the generalization set with a superclass that has no attributes or operations may be close to what you want.

UML class diagrams are really inadequate to visually depict basic logical relationships like disjunction, etc


问:
Should I hide fields in REST resource representations based on the user's security role?
What is the best practice for exposing different fields for a resource based on user's role/ACL privileges in the system?

Let's say I have an endpoint, groups/{:group_id}.  My business rules state the following:

Non-authenticated users can see only: name and ID fields

Authenticated users can see: name, ID, managers, and access_code fields

Group managers can see name, ID, managers, access_code and members.

Respectively, the records may look like:

```<code>/* Non-Authenticated User */
{
    "id": "abe80d",
    "name": "Foobar Group"
}

/* Authenticated User */
{
    "id": "abe80d",
    "name": "Foobar Group",
    "access_code": "abc123",
    "managers": {
        "_href": "http://example.org/people/bds983a",
        "_href": "http://example.org/people/cde03rf",
    }
}

/* Manager */
{
    "id": "abe80d",
    "name": "Foobar Group",
    "access_code": "abc123",
    "managers": {
        "_href": "http://example.org/people/bds983a",
        "_href": "http://example.org/people/cde03rf",
    },
    "members": {
        "_href": "http://example.org/people/bds983a",
        "_href": "http://example.org/people/cde03rf",
        "_href": "http://example.org/people/jvs239a",
        "_href": "http://example.org/people/nnd9323",
    }
}
</code>```

Should this be a single endpoint/URI that shows different sets of fields for different authentication levels, or should I somehow break these up into three different URIs?

It seems like different URLs for the same resource is bad, but a client not knowing exactly what fields would be retrieved is also bad?  Is there a best practice in this situation?

答:
Usually a single resource URI because you want separation of concerns between WHERE the resource lives and WHO accesses it.

In your case, "WHO" accesses the resource is determined based on two parameters: Is the user authenticated? If so, what is the level of authorization?

For the level of authorization, you may implement it using groups, and may add groups over time, or change the authorization level of various groups over time. That should not change where the data needs to be retrieved from by a client.

A practical example is that when a client (e.g. a native app on a mobile device) consumes your API, it will authenticate the user and render the view based on the data it gets back. If (on the server side), new groups are added or a user's authorization level is changed, it should not have any impact on the client code.

It seems like different URLs for the same resource is bad, but a
  client not knowing exactly what fields would be retrieved is also bad?
  Is there a best practice in this situation?

Clients are generally expected to handle these cases. If you had separate URIs, you still have the problem that a URI is being hit which requires higher privileges than what the user has, in which case, the request will have to just fail. More importantly, without authentication having been performed, how does a client even know which URL to hit?

On the other hand, if the client was coded to expect data according to various authorization levels, the code would be generic enough to handle future cases where what data is returned is changed. This is important because a resource should generally not be assumed to stay constant and not evolve over time.

There are fortunately many tools and techniques available both in XML and JSON to handle arbitrary amount of data returned from the server so long as the schema contract was not violated.

In the example, you provided, I would code my client to have the schema for all five fields, but expect any field other than name and ID to be null. If it's not null, render it to the user, but if it is, either don't show it, or provide an appropriate message. In the future, if you decided to allow authenticated users to not see access_code or non-authenticated users to see managers, the client code would not have to change.


问:
How to design large applications with little planning experience
I understand there is plenty of information on the internet about planning and implementing said solid plan in building a large software application, but I was hoping to get something a little more specific to aid my approach for this specific instance.

Some Background:

We're a web hosting company that has a team of 3 developers. My colleague and lead developer has been with the company a few years, and up until myself, and another developer were hired, he was the sole one looking after all the company's projects.

All three of us have very little experience in leading a team, or even working with other developers in a meaningful sense. We've all come from small business backgrounds where input has simply gone in our ears, and code has come out.

There's some benefits to our position as well; our team is fairly autonomous. Apart from a few directives given by management, we have total control and freedom in managing our projects, deadlines and the tools used to implement our solutions. It's a pretty great gig, but we're all around the same age (early-mid twenties) and so there's not so much team-lead experience there.

The Application:

Our current billing system is the oft maligned WHMCS - which is a plight of many other hosting companies I'm sure. As a result, we've been tasked with designing a replacement that has all of the features we need specifically for our operations.

At the start of the year, my lead developer began working on it. This was the traditional case of 'begin prototyping and see what happens'. While his code was great, and the foundation solid, there was zilch going on in terms of scoping (the designer hadn't even looked at it yet), and now the code base is starting to creak under it's own weight, and it's barely a third done.

Me:

I've come along from a small web design business where I was considered the 'go-to' guy, so I took it upon myself in many instances to attempt planning a project that more than once has saved the profit margin from dipping into the red. This has helped a little in convincing the lead developer to adopt a more careful, structured approach that allows us to work as a team, and have this quite critical piece of software not be a steaming mess of bug fixes and hacky patch-ups.

I'm a journeyman developer, so I'm not well versed in best practices, I don't know three or five or ten programming languages, but I can code. And I'm a great communicator (in real life, not when writing questions like this ~_~), so I hope what I learn here will be able to directly translate into something that benefits our small team.

The actual question:

For a big old 'TLDR;' here: What are the preferred methods of planning a large codebase? We're our own masters in this, so we have no guidance. Muchas gracias in advance!

答:
The issue you are facing IMHO is a growing amount of technical debt. While usually attributed to poor design, I attribute to overall poor software engineering practices. The problem is, once you've accumulated some, you'll have to pour a bunch of resources in to get out of it before you start seeing major improvements. But in the end, I promise the work will pay off.

I'd say make sure to build it iteratively. IMHO you want to get to a usable and testable code base ASAP, so figure out the minimum set of functionality you'll need to have a product. Not even a competitive product, just a thing that works. This should help keep you focused and keep you from adding too many YAGNI features. If you get into the swing of quick iterations, you can also use them as a vehicle for slowly increasing your software control capabilities.

You didn't mention it in your post, but you had better be using some sort of version control. Make sure you have an issue tracker (its all in my head is a terrible way to track issues). Make sure you fix bugs before moving on to adding features. Implement a continuous integration and test server. Not all of these are necessary for all projects, and they come with a pretty steep cost for setup and training, but they are worth it in the end.

When possible you want to split your code into reusable modules. Got a bit of code that handles authentication? Put it in its own module. Ect. It is very possible to do this too much, but done well it can increase your code re-usability. In some build systems this can also be a mechanism for caching the build, so that you only remake or retest elements of the code that have changed.

Finally, I suggest adopting a company wide coding standard and enforce it through code reviews. One of the highlights of your post to me was "lead developer began working on it". It sounds like only one guy is touching the code...this scares the crap out of me. You need to have shared ownership of the code, else when the lead gets tired of working on this code base and moves to a different company you'll be up the creek without a paddle. Coding standards help make all the code in the company "feel" the same, which can help readibility, but I do enjoy code reviews. Done correctly, they can really be used as a learning tool and help everyone understand all of the code to some degree (done poorly they can serve to only make all your engineers hate each other.)


问:
Understanding UML composition better
The difference between Composition and Aggregation in UML (and sometimes in programming too) is that with Composition, the lifetime of the objects composing the composite (e.g. an engine and a steering wheel in a car) is dependent on the composite object. While with Aggregation, the lifetime of the objects making up the composite is independent of the composite.

However I'm not sure about something related to composition in UML.

Say ClassA is composed of an object of ClassB:

```<code>class ClassA{
    ClassB bInstance;
    public ClassA(){
        bInstance = new ClassB();
    }
}
</code>```

This is an example of composition, because bInstance is dependent on the lifetime of it's enclosing object.

However, regarding UML notation - I'm not sure if I would notate the relationship between ClassA and ClassB with a filled diamond (composition) or a white diamond (aggregation).

This is because while the lifetime of some ClassB instances is dependent of ClassA instances - there could be ClassB instances anywhere else in the program - not only within ClassA instances.

The question is: if some ClassB objects are composed with ClassA objects (and thus are dependent on the lifetime of the ClassA objects), but some are not - would the relationship between the two classes in UML be an aggregation or a composition relationship??

答:
Is your composition intended to model situations where an object is part of another object in the way a particular screw may be part of a truck?  Not every screw is part of a truck.  If so you should not use the composition relationship.  UML2 includes another notion of a composite object which has parts making up a whole.

If class A is a composite aggregation of class B, then every instance of B must have a related instance of A which aggregates it.  Not what you want.

In the situation you describe, instances of class A are composite objects which contain instances of class B as parts.  This doesn't rule out the possibility of instances of B that aren't part of A objects.  The relationship between A and B is neither aggregation nor composition.  The terminology (composition relationship vs composite structure/part) is confusing, but we're stuck with it.

Title: Understanding UML composition better


问:
Why do so many namespaces start with com
I've noticed that a lot of companies use "reverse domain name" namespaces and I'm curious where that practice originated and why it continues. Does it merely continue because of rote practice, or is there an outstanding architecture concept I might be missing here?

Also note questions such as: https://stackoverflow.com/questions/189209/do-you-really-use-your-reverse-domain-for-package-naming-in-java that sort of answer my question but not 100%

(If it makes you feel any better, I'm really curious if I should be using it for my javascript namespacing efforts, but I'm more curious about then when and why, and that should help guide me on the javascript answer, nota bene: "window")

Example of this practice extending to folders and files:

答:
I think a minor detail was not mentioned in the other answers: The reason that the .com TLD is the most popular one, is that in the early days of the Web, Web-browsers like Netscape Navigator "auto-appended" .com if it was missing in the address (eg. if the name-lookup failed). So if you typed "shareware", it would be expanded to "http://shareware.com" (or "http://www.shareware.com"; I don't remember the www detail).
.com domains are probably still the most popular.</p>


答:
I would for some projects. Definitely would if I have to implement an embedded system, say for an autonomous aircraft's controller. Might even go lower level on some parts with assembly.

If it fits the project, I have no problem with it.

If you want to develop a web-application, hmm, probably not (or I'd need to see a very strong and fact-supported justification).

I would also use it from other projects mainly developed with other languages when a bottleneck has been clearly identified and an optimization can be implemented using native code. For instance, a Java solution which needs to be perform intensive computations for some advanced rendering (say, a rendering engine or something). You could default to a Java implementation if it's not a supported platform, but provide a natively compiled implementation from C for some supported platforms, and get a nice performance boost.

Title: Would you use C, today, for a software project?

Body:
If yes, where and why would you use it?

If no, please provide an explanation to why C is not acceptable to you.


问:
How best to version control massive configuration for an application?
Apologies if this doesn't make sense, English is not my first language.

I'm working on an application where workflow is split into 'rules' that are defined on several pages of an Excel spreadsheet, a VB script strips out the descriptions of the states etc and leaves only numbers, then exports this configuration as MySQL that is then imported into the database from which the application works.

We have 2-3 developers working on the spreadsheet. Often the spreadsheet is opened from it’s location on a shared network drive, minor changes made and sometimes the version number is not incremented.

This makes it very hard to track changes and also who made them and why. Ideally we would pull the spreadsheet to a working directory, do a diff and commit changes then push them to a master repository. It seems like there are no viable tools to do such a thing with Excel.

So my question is what would be a better way to support a very large configuration, make it version controllable and still human readable?

答:
I'd like to post some ideas and information, which you can pick and choose from, as it's partly a matter of taste, opinion and what resources you have available.

Personally, I recommend using git in situations where you need to group files together. It's the only version control software I know of, that can safely do this. I recommend having your own git-server (gitolite is very good for this purpose).

I have the following setup:

gitolite + git for version control + gitweb for an easy overview.

A CGI-script on the same server, which is basically a "visitor
counter".

The CGI-script opens a file, reads a number from it, increments the number and stores it back into the file; it also packs the date, the seconds/minutes/hours and other information into one single packet and sends to the requesting user.
The requesting user is a shell-script, which is executed every time I compile (build) using Xcode (on Mac). If you're not using Xcode, you can put it in your Makefile.

The reason it's a CGI-script that bumps the version number, is that you need one central place (and only one) with atomic access, so that you always get a unique number.

It does not matter if you get version 0.1.4 and your buddy gets version 0.1.5 and your buddy submits version 0.1.5 before you submit your version; the most important thing here is that the version numbers are always unique.
-And if you don't like your version number, just request another one. ;)


问:
Why is PHP so hated?
Lately I've been coming across several jokes and comics about how apparently awful PHP is. </p>

<p>As a complete ignorant of the language, why is this? Is it my own perception or is this the overall general feeling on the programming community? </p>

答:
Note: This is written from a highly opinionated stance.

See also: PHP: A Fractal of Bad Design

Long ago, when the web was young, you wrote a web app in perl.  That was really it.  That was your only choice (unless you really liked working with strings in C). (And yes, I'm glossing over great swaths of ASP and the like... I'd rather forget those days.)  There were great and large applications of the web written in perl.  And there were many, many pieces of... well, crap written in perl.  You can still find them if you look - buggy CGI scripts that someone slapped together that don't even come close to sanitizing their inputs.

As the web became more enterprisey, the great and huge applications moved to other frameworks that were better designed for handling thousands of connections (perl at that time wasn't).  Those who could learn a new language moved on to Java (that was the best choice for many frameworks).  Those who couldn't, well, there was this language that looked a lot like perl and did some things better (didn't need to fork a process for each request).  It was php.

Php grew, organically... if you can call a Frankenstein monster organic.  Lots of hacks (did you know the original hash function for function names was strlen?).  Partial things added to the core language (rather than libraries) that still remain there today. Its not that pretty.  (Poke at reddit's /r/lolphp which pokes fun of many of these inconstancies... did you know that -1 month is always 30 days?)

And while great and huge things have been built in php (look at wordpress as an example), it is still a monster under the covers with esoterica about how things work (or don't work, or what parts of things work most of the time).

It's the quick and easy language to learn so a lot of people who don't want to spend time learning a language use it. And then when it breaks and you have to maintain it now? Well, a language that allows such lack of discipline from coders who don't always understand what they are doing makes for some very 'interesting' bugs.

Its the language of quick tossed together websites and half baked wordpress plugins.  Where some 16 year old wrote the code for their neighbor for $20 or a college student for beer money... knowing that they'll never look at it again.  Go browse Stack Overflow's php tag for a bit and consider that you may be maintaining that code some day.

Remember that everyone else's code always sucks.  And if you have to deal with someone else's code in php - it sucks.

Title: Why is PHP so hated?


问:
How deep is enough to represent an algorithm in UML sequence diagram?
I have three simple classes. LoginController, UsersCatalog and User. UsersCatalog has an array of User. I have to represent a simple process of login.

LoginController has a method login(username, password) that simply  calls a method authenticate(username, password) with the same parameters.

Now, it's obvious that the method authenticate seeks for a matching User object and returns it. The question is: Is it necesary to represent the seek algorithm? Isn't representing the seek algorithm too much low level?

In the other side, the access to User class is inside the seek algorithm, so if i don't represent it, then i don't represent the access to the User class.

This is part of a wider question. There are any criteria for how deep is enough to represent an algorithm in UML squence diagram?

答: Sequence diagrams are good for specifying the order of message exchanges between principle objects of interest: User, LoginController, ... etc.  When an object receives a message, the reception should cause some logic internal to the object (specified by the object's class) to run.  The algorithm that describes what that logic does is not documented in the sequence diagram.  It might be documented in an activity diagram (flow chart) that is linked to the class.  If you wish to visually describe the algorithm, use the activity diagram.


问:
Name/Fix for Production Code Whose Sole Purpose is to Facilitate Testing?
The linked "duplicate" question is an iffy match at best, because it's asking

is pattern X OK (YES/NO)

and I'm clearly already in the NO camp, and subsequently asking

what is pattern X called

what steps can be taken to fix pattern X

(neither of which are addressed by the linked question).

I recently did a code review on a block of code that looked something like this:

```<code>public class MyClass
{
    private ISomething mySomething;
    // ...Other variables omitted for brevity

    public MyClass() { mySomething = new Something();  }

    /// <summary>
    /// Constructor - ONLY USE THIS FOR UNIT TESTING
    /// </summary>
    public MyClass(ISomething something) { mySomething = something; }

    public void MyMethod()
    {
        // Gets called by the framework, and changes the internal state of the class by using mySomething...
    }

    // Other methods...
}
</code>```

I'm concerned specifically with the overloaded constructor. It was added purely to test this class, and will make its way into production code.

Is there a name for this pattern/anti-pattern, and what can be done to solve it?

For clarification, the implementation of Something was added specifically for the purpose of being able to add an overloaded constructor to MyClass. It's used nowhere else. Its existence is an instance of the very issue I'm concerned about.

ISomething is very tightly coupled to MyClass. It needn't have been extracted. Implementation and interface might as well look like:

```<code>public interface ISomething
{
    string GetClassName();
}

public class Something : ISomething
{
    public string GetClassName() { return "MyClass"; }
}
</code>```

That means that MyClass.MyMethod()'s body could just be replaced with return "MyClass";

However, the interface abuse/premature optimization seems like a separate issue and not in the spirit of the original question (i.e. consider it a given that the class/interface is structured like so and leave it as a separate [but valid] concern).

答:
Two possible cases when you may want to change your production code for testing purposes:

If you have complex functionality in the class

And your open interface does several things combined

so you can not test each of the functionality separately

this means when a combined test fails you still don't know which part is broken

YES, it is good to separate that functionality into subclasses and test them

If you want to test internal implementation

This brakes the refactoring/encapsulation principles because

your business logic will not brake with new implementation

but your tests will brake, which is BAD since tests should verify object behavior from its user perspective.

So the answer is that the anti-pattern (item 2) logically breaks intention and purpose of encapsulation. I vote for the violation of encapsulation principle.


答: Assuming you do not accept the argument (which I believe is well worth considering) that the fact that the separated ISomething is required for testing tells you that it may also be required kn future to make your class more flexible, one possible fix would be to mark the constructor as deprecated and disable deprecation warnings for the line of the test class that uses it. This seems much better than internal, as that does little to prevent actual use.</p>