问:
Alternatives to JDT Annotation - License issues
I have used the JDT Annotation library in my Java project as I am quite fond of what it offers. To be more exact, I used the @Nullable and @NonNullByDefault annotations as I can use the synergy with Eclipse to automatically analyse possible null values and what may lead to NullPointerException bugs.

Unfortunately, JDT Annotation is licensed under EPL1 which, as far as I know, is incompatible with GPL2 due to the former being a weak copyleft license and choice of some clauses. As the project should be published under a GPL2 license, I am exploring different options but have yet to fine any that would offer the same, or nearly the same, functionality.

I am not keen on adding null checks as they only clutter the code with what an annotation could have solved as well. But unfortunately it seems to be the only viable option? I am looking for some expertise regarding this matter. What I propose is to use Google's Preconditions to formulate preconditions such as:

```<code>Preconditions.checkArgument(providedArgument != null, "The provided argument must not be null!");
</code>```

respectively:

```<code>Preconditions.checkState(invariantField != null, "The field may not be null!");
</code>```

These will solve the problem of course and be more explicit, in my opinion, when it comes to documenting my contracts by code. I usually also report these with custom tags in my Javadoc, for example, @pre providedArgument != null or @inv invariantField != null.

I would be thankful for all

答: The null annotations are configurable in Eclipse. You can create your own set of @Null, @NonNull, and @NonNullByDefault annotations, and configure Eclipse to use them instead of standard ones from org.eclipse.jdt.annotation package. See here.


问:
Citations for inadvisability of globally unique password
I am having a disagreement with a client about the user authentication process for a system. The nub of it is that they want each user to have a globally unique password (i.e. no two users can have the same password).

I have wheeled out all the obvious arguments against this:

it's a security vulnerability,

it confuses identification with authentication,

it's pointless, etc.,

but they are insisting that there is nothing wrong with this approach.

I have done various gGoogle searches looking for authoritative (or semi-authoritative , or even just independent) opinions on this, but can't find any (mainly it's just such an obvious faux pas that it doesn't seem worth warning against, as far as I can tell).  Can anybody point me towards any such independent opinion, please?

EDIT: Thanks for all your answers, but I already understand the problems with this proposed approach/requirement, and can even explain them to the client, but the client wont't accept them, hence my request for independent and/or authoritative sources.

I'd also found the Daily WTF article, but it suffers from the problem that Jon Hopkins has pointed out - that this is such a self-evident WTF that it doesn't seem worth explaining why.

And yes, the passwords are going to be salted and hashed. In which case global uniqueness might well be difficult to ensure, but that doesn't solve my problem - it just means that I have a requirement that the client won't budge on, that's not only ill-advised, but is also difficult to implement. And if I was in a position to say "I'm not budging on salting and hashing", then I'd be in a position to say "I'm not implementing globally unique passwords".

Any pointers to independent and/or authoritative sources for why this is a bad idea still gratefully received...

答:
I just want to reinforce Murph's answer. Yes, it's a security problem and there is information disclosure vulnerabilities in implementing it. But from the client's point of view, he doesn't seem to be too worried about that.

What you should point out is that it's physically infeasible to actually implement a "unique password" check. If you're salting and hashing password, and not storing them as clear text, then it's O(n) (expensive) operations to actually perform the uniqueness check.

Can you imagine if you have 10,000 users, and it takes 30 seconds to go through every user's password to check for uniqueness every time someone new signs up or changes their password?

I think this is the response you need to take to your client.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
Why do most sites require email activation
Most popular applications nowadays require account activation by email. I've never done it with apps that I've developed so am I missing some crucial security feature?

By email activation I mean when you register to a site they send you an email that contains a link that you have to click before your account gets activated.

答:
A few frequently used reasons are:

Making sure the email address is valid.

Making sure the user owns the email address.

Making sure the user WANTS to subscribe.

Making sure that future communication can process properly.

Giving the user a confirmation that he subscribed and a digital trail.

ContentLicense: CC BY-SA 3.0


问:
Using words instead of numbers for versioning?
Would it be considered acceptable to use word compounds instead of numbers for version iterations?

For example in a pattern: "[Adjective] [Noun]"

The first version could be something like: "Auspicious Armadillo"

Thus on each sequential release the noun would change to the next letter of the alphabet and the version could be along the lines of: "Auspicious Bear"

Once the alphabet for the nouns runs out the Adjective gets changed and the Nouns can start over e.g: "Bewildered Armadillo" etc.

This would give me around 676 possible different versions to iterate through.

Assuming the project is small & short enough to fall within these 676 releases before a complete remake/overhaul, would such a versioning pattern be considered acceptable to use?

Or would it just create needless confusion and chaos?

I understand this might be somewhat opinion related, but I was hoping for some kind of a general consensus on whether this is an acceptable or terrible idea.

答:
The biggest issue with this is trying to tell someone else what version you have. Do I have Auspicious Armadillo? Or do I have Amourous Armadillo? or do I have Agitated Asp? In the end, users will refer to their version as version A.A or A.B or B.A, which is not that different from 1.1, 1.2 or 2.1, just limited to 26 versions at most. And if you ever want to introduce a 3rd rank of versions, what will you do? Alfred the Bewildered Armadillo?

You can, however, do what Mac, Android, some linux Distros and other software programs do, and assign these as codenames to stable versions. Your 1.0.0 can be Armadillo, your 1.3 can be Bear,...


答:
I think it depends on the possibilities that you give to your user. Can he or she send messages to other users and spam them with adverts? Can he or she post on your site and post viagra ads everywhere? Can he or she upload a lot of files and fill your precious server space. If anything of the above or something else that could be used for spamming or trashing up your server is existent, you want it to make as hard as possible for a spammers to sign up to your site. And so e-mail authentication is one another step that makes it hard for spammers to pretend to be a human.

To achieve this you should use email authentication with a form that makes it also hard for machines to be filled out with using a captcha or other techniques and you also should block trash mail services.

Title: Why do most sites require email activation

Body:
Most popular applications nowadays require account activation by email. I've never done it with apps that I've developed so am I missing some crucial security feature?

By email activation I mean when you register to a site they send you an email that contains a link that you have to click before your account gets activated.


问:
Is there any issue if ternary operator is used in super() method
I am using a ternary operator in super () method of my code. While the code went for review, I got a reply that

Strictly don’t use ternary operators in the Super() calls.

Is there any problem if we use ternary operators in the super() method?

答: I would reply to your reviewer and ask them to explain their comment. A critical part of the review process is understanding why code should be changed. Perhaps it doesn't adhere to the established coding standards, or similar code caused a problem in the past. Point is, ask why, in the spirit of understanding.


答:
Codenames are useful, particularly for searching. Finding information about Ubuntu 12.04 is much harder than finding information on Ubuntu Precise Pangolin, because "12.04" will also turn up blogs posted on April 12 or December 4, or at 4 o'clock on the 12th of March.

It can also be useful in effectively killing everything written about a Beta version when the real version is released and makes it irrelevant. For example, a search for Windows Vista does not turn up information written when it was known as Longhorn ... which is good, because many things had changed.

But I don't agree with your contention that codenames offer you MORE freedom by nature of there being only 10 digits and 26 letters. You are not limited to x.0 - x.9. You can easily have x.799, as long as any comparison you do is version-based rather than decimal- or string-based. *

So I would recommend having codenames but not using them as a versioning system.

*

```<code>decimal comparison: 1.799 < 1.9
string comparison: "1.799" < "1.9"
version comparison: 1.799 > 1.9
</code>```

Title: Using words instead of numbers for versioning?

Body:
Would it be considered acceptable to use word compounds instead of numbers for version iterations?

For example in a pattern: "[Adjective] [Noun]"

The first version could be something like: "Auspicious Armadillo"

Thus on each sequential release the noun would change to the next letter of the alphabet and the version could be along the lines of: "Auspicious Bear"

Once the alphabet for the nouns runs out the Adjective gets changed and the Nouns can start over e.g: "Bewildered Armadillo" etc.

This would give me around 676 possible different versions to iterate through.

Assuming the project is small & short enough to fall within these 676 releases before a complete remake/overhaul, would such a versioning pattern be considered acceptable to use?

Or would it just create needless confusion and chaos?

I understand this might be somewhat opinion related, but I was hoping for some kind of a general consensus on whether this is an acceptable or terrible idea.

Body:
Codenames are useful, particularly for searching. Finding information about Ubuntu 12.04 is much harder than finding information on Ubuntu Precise Pangolin, because "12.04" will also turn up blogs posted on April 12 or December 4, or at 4 o'clock on the 12th of March.

It can also be useful in effectively killing everything written about a Beta version when the real version is released and makes it irrelevant. For example, a search for Windows Vista does not turn up information written when it was known as Longhorn ... which is good, because many things had changed.

But I don't agree with your contention that codenames offer you MORE freedom by nature of there being only 10 digits and 26 letters. You are not limited to x.0 - x.9. You can easily have x.799, as long as any comparison you do is version-based rather than decimal- or string-based. *

So I would recommend having codenames but not using them as a versioning system.

*

decimal comparison: 1.799 < 1.9
string comparison: "1.799" < "1.9"
version comparison: 1.799 > 1.9


问:
Options for client-side encryption of local web databases
My scenario is as follows:

Web application, run from the browser, designed for mobile devices.

Uses WebSQL storage which may contain sensitive
data.

Uses Application Cache to enable offline use where there is no connectivity.

Can connect to an API where even more sensitive data can be downloaded. Authentication is handled with BASIC Authentication, and unencrypted data is transferred over the wire, as the application shall access the API in the following environments/scenarios:

On a private, secured, local Wi-Fi network.

Over the public internet, over a VPN connection.

Over the public internet, through a HTTPS connection.

So far, based on my limited knowledge, the security of sensitive data transferred over the wire is covered. However, the data 'at-rest' in the local WebSQL storage, and formatted in the HTML pages of the web application, is not secure.

The current concern is if a mobile device contains sensitive data, and it is lost or stolen, how to minimise the risk of the sensitive data being accessed.

As the application needs to be usable without interaction with the server, any software-based encryption would be contained on the client itself. This means that, presumably, attempting to encrypt the WebSQL database will be pointless as if a skilled intruder can bypass the hardware encryption, they can presumably determine the encryption/decryption logic as well?

The proposed solution for encryption of data at rest, is to use the built-in hardware encryption that is part of iOS and Android devices, requiring users to enter a password at the lock screen. There are related 'remote wipe' features as well that could be used.

Q: How 'secure' is the proposed solution? If the built-in hardware encryption is not enough, what are the best strategies for implementing client-side encryption of WebSQL data without need of interaction with a server?

Is the implementation of a software-based, data encryption/decryption solution, only going to give a marginal security benefit, as the encryption/decryption code can be accessed and reverse engineered? Is it just me, or is the main benefit of that merely marketing purposes, i.e. being able to 'say' that it is encrypted?

Interesting links:

https://security.stackexchange.com/questions/10529/are-there-actually-any-advantages-to-android-full-disk-encryption

Also...

Underlying storage mechanisms may vary from one user agent to the
  next. In other words, any authentication your application requires can
  be bypassed by a user with local privileges to the machine on which
  the data is stored. Therefore, it's recommended not to store any
  sensitive information in local storage.

https://www.owasp.org/index.php/HTML5_Security_Cheat_Sheet#Client-side_databases

Does this mean the only secure option is to produce a hybrid application? E.g. using Phonegap. Is this a great deal more secure, could it just be reverse engineered to view the JavaScript that encrypts/decrypts in the same way anyway?

答:
Mobile web app: If this is a web app, running from the browser and not in a native shell such as Phonegap, how do you use it offline? If it's already loaded and doesn't make requests (not to be bothered by connectivity jitter), yes, that's useful, but this also means that you can't start the app without a connection, right? Since you keep a lot of data on the client, a Phonegap app probably will be a better fit.

Security: Although, I don't know how secure the native storage encryption is (I don't believe it's unbreakable in any case, though), I am pretty sure you should stick to the presumption that the security of your local data isn't the app's responsibility - as you already said, people can protect their devices with password on screenlock. Also, will your app ask for a login on every start? I don't think you would want to force the user to sign-in every time he loads it. If my guess is correct, then what's stopping the intruder to simply fire-up the app and just read the data?

Caching sensitive data: Don't.


问:
How should I design a PHP class autoloader?
I have a fairly simple folder structure where the main classes are in a folder, and any classes used by those classes are in a subfolder with the same name as that class.

```<code>/exampleClass.php
/exampleClass/usedByExampleClass.php
</code>```

I am trying to come up with a simple autoloader for this naming convention.

So far, my idea is to use underscores in the class name wherever there might be a forward slash in the class path. This way I can simply replace all underscores with forward slashes in the autoloader, and load the class file.

This means that the class name found in file:

```<code>/exampleClass/usedByExampleClass.php
</code>```

would be:

```<code>exampleClass_usedByExampleClass
</code>```

These class names end up being very long however, and I would like to shorten them while still having a simple autoloader for this folder structure.

Any ideas or thoughts on how to achieve both short class names and a simple autoloader for this folder structure?

答:
Since no one mentioned it but now a days composer is the key thing to do auto-loading in PHP.

Its a widely use small system to autoload the classes found in any structure. With the aid of composer.json you can effectively customize your directory structure and just autoload the autloader file created

You can then download known github lib files that will easily plug into your projects

As it is best practice - don't reinvent the wheel.

tutorials (as the man of composer might be a bit slim) can be found in such places like http://code.tutsplus.com


问:
Separate namespace just for exceptions?
I was doing a code review and came across something odd which I've never seen before.  The developer decided to create a sub-namespace just to contain all the assembly's exceptions.

I thought I had read that this was explicitly not a good use of namespaces and that exceptions should be kept at the "lowest" namespace from which they are thrown, but I haven't found anything on MSDN (or anywhere else for that matter).  At the same time, it seems odd that I haven't come across this before in the framework itself or the third party libraries I've used.

Are there any guidelines exist that would push away from keeping all exceptions in a .Exceptions sub-namespace?

答:
The two main reasons for using namespaces are to avoid name collisions, and to add logical grouping. But since exception class names typically have the form "XYZException" (and other classes have not), those two requirements are already fulfilled by this naming convention. Thus adding an additional sub-namespace is unneccessary in a context where everybody follows the convention. It tries to solve a problem which is already solved, adding a needless complexity to the code.

Moreover, to my experience its better to use namespaces for partioning under semantical aspects of your domain, not for technical or syntactical grouping. When you start to put exception classes into a sub-namespace, the next decision will be to put all enums into a sub-namespace of its own, then all helper structs, and so on. Actually, I don't think this makes code any clearer or easier to navigate in, so I do not think it would be useful.

Title: Separate namespace just for exceptions?


问:
Making server logic independent of client interaction
I'm trying to make a realtime multiplayer web-game in node.js with express framework and socket.io library.
But I can't seem to make my server-side logic independent of client interactions.
I want client to interact only when I (server side logic) want but I can't seem to be able to do that. For example:

I want 2 users to
start playing a game. I have to first initialize the game, like set up environment, variables and stuff.. all in a separate, call it: The Game Logic. Only then can I "allow" the clients to interact.

But how am I supposed to carry on with my Game logic when my socket.on event is "calling the shots"?
With socket.io you have to define triggers like

```<code>io.sockets.on('connection', function(socket) {
    socket.on('event', function(data) {
        //supposed this is fired when client hits an "interact with X" button
    });
}
</code>```

All my logic seem to be dependent on these triggers. I only wanted client to be able to fire that event when I want (after I've set up the game env etc), but defining it like so, separated from my game logic, it creates problems like how am I supposed to transfer the execution control from socket into my game logic? And even if I managed to, there's that whole client "calling the shots" problem. I then have no control when client could want to interact.

Any advice what should I do?

答:
You need to make the client available for receiving a call.

You either "push" sample/source or setup a "client-server" sample/source

Another option would be to have the client call to the server at a scheduled time (like every 15 min) and if there is something you want to "say/do" it happens then.


问:
How important is it to clean up someone else's code when faced with a tight deadline?
(I'm talking about HTML / CSS code (not programming languages) but I think we also face the same issue as with programmers.)

I am the senior front-end designer in a team and I often have to re-work my juniors' output in tight deadlines.

I am faced with 2 problems:

Their coding style is a bit of a mess.

The aesthetics are not good.

Their coding style, I find, is a mixed bag with no proper convention / standard. I am torn between cleaning up the code or just dealing with their code (even copying how they do things).

I do find it frustrating to follow their coding style as I feel I might learn bad habits. But then, that is the fastest way of meeting the deadline.

For those with much more experience, which is more effective? Should I save the clean-up for later? Or clean-up along the way as I make the changes?

(I don't want to sound arrogant though but such is the reality. It will take them more years to write better code. I know, I wrote messy code when I was starting.)

答:
Improving overall quality is vastly superior to using a single person as a "filter" for a larger group. On that note:

Pair programming works like a souped-up version of code review for understanding how to develop - it's like the difference between reading and doing, telling and showing. Watching code evolve and quickly discussing changes is immensely helpful to understanding not just the how but the why of refactoring and good code. In my experience it's faster than developing alone, since ideas get tossed around continuously, ending with an overall higher quality result and better understanding of both the code and the other person's thinking.

Linting tools can verify that coding style is being followed. This teaches everyone how to format code, and errors should drop off quickly once developers remember the standard.

Make these part of the build process to ensure that it's fixed before committing.

Use language templates to ensure that your CSS, HTML, JavaScript and server-side code can be checked separately.

Validation tools can check that the generated output is sane. These should also be part of the build process.

OwnerDisplayName: anon

LastEditorDisplayName: anon


答:
I have worked in the past on medical applications running on portable devices that need to communicate with a central server, but need to also work when no network connection is present.

The first thing to do is to do a proper security analysis.  What are the risks to data, and how are you managing to protect the data against those risks. e.g.

Sensitive data transfer of TCP network to the server.

Storage of sensitive data on the device

Identification of user on the device

Identification of device to the server

access to sensitive data on the device by an identified user.

What is appropriate will vary with the nature of the sensitive data, and the product involved, but to give you a guide, here were the answers for that medical product...

Data over the network was encrypted by AES-256, and where ever possible we used a private APN network which connected to the server data centre via a private leased line.

On the device we stored sensitive medical information encrypted by AES-256 but without any patient identifiers.  Encryption key was device specific so data files could not be accessed by copying data to a different device.

Access to the software one the device was controlled by a 3 digit pin number.  This was probably the weakest aspect, as patients then typically chose simple pins (e.g. 123 or 147)

Each device identified itself with a client certificate to the server, and then had to supply additional hardware provided identifiers to the server to validate the device matched the servers expectations.  Only the server knew the identity of the patient that used that device, and server identification was all about confirming whether the device was authorised to connect to the server, and which device it was.

In our case, having access to past historic measurements was important to the patients, so patients could view their historic measurements if the device had successfully authenticated with the server in the past 24 hours, and its last successful socket connection had resulted in the device being authenticated.

Title: Options for client-side encryption of local web databases

Body:
My scenario is as follows:

Web application, run from the browser, designed for mobile devices.

Uses WebSQL storage which may contain sensitive
data.

Uses Application Cache to enable offline use where there is no connectivity.

Can connect to an API where even more sensitive data can be downloaded. Authentication is handled with BASIC Authentication, and unencrypted data is transferred over the wire, as the application shall access the API in the following environments/scenarios:

On a private, secured, local Wi-Fi network.

Over the public internet, over a VPN connection.

Over the public internet, through a HTTPS connection.

So far, based on my limited knowledge, the security of sensitive data transferred over the wire is covered. However, the data 'at-rest' in the local WebSQL storage, and formatted in the HTML pages of the web application, is not secure.

The current concern is if a mobile device contains sensitive data, and it is lost or stolen, how to minimise the risk of the sensitive data being accessed.

As the application needs to be usable without interaction with the server, any software-based encryption would be contained on the client itself. This means that, presumably, attempting to encrypt the WebSQL database will be pointless as if a skilled intruder can bypass the hardware encryption, they can presumably determine the encryption/decryption logic as well?

The proposed solution for encryption of data at rest, is to use the built-in hardware encryption that is part of iOS and Android devices, requiring users to enter a password at the lock screen. There are related 'remote wipe' features as well that could be used.

Q: How 'secure' is the proposed solution? If the built-in hardware encryption is not enough, what are the best strategies for implementing client-side encryption of WebSQL data without need of interaction with a server?

Is the implementation of a software-based, data encryption/decryption solution, only going to give a marginal security benefit, as the encryption/decryption code can be accessed and reverse engineered? Is it just me, or is the main benefit of that merely marketing purposes, i.e. being able to 'say' that it is encrypted?

Interesting links:

https://security.stackexchange.com/questions/10529/are-there-actually-any-advantages-to-android-full-disk-encryption

Also...

Underlying storage mechanisms may vary from one user agent to the
  next. In other words, any authentication your application requires can
  be bypassed by a user with local privileges to the machine on which
  the data is stored. Therefore, it's recommended not to store any
  sensitive information in local storage.

https://www.owasp.org/index.php/HTML5_Security_Cheat_Sheet#Client-side_databases

Does this mean the only secure option is to produce a hybrid application? E.g. using Phonegap. Is this a great deal more secure, could it just be reverse engineered to view the JavaScript that encrypts/decrypts in the same way anyway?


问:
Multiple entrance points in project
My question is related to C++ but it comes from Java actually.

When I was programming Java I had multiple classes, which were derived from a base "Test" class. Their purpose was to test things - run tests (unit tests/not unit tests).

In order to run a test, I had a public static void main in every class. So the matter of running such a test was to click run in Eclipse/Netbeans, whatever good IDE.

I know this question maybe IDE dependent, it actually boils down to a makefiles, but is it possible to maintain a similar structure in C++ IDEs?

Actually my question is: how do you deal with tests?

Do you put a huge main method with some switch/enum based statements to run the tests or make different build configurations for each test, or have different solution to this?

I know this question won't get a straightforward answer, but I'm curious how to deal with it so I can choose something for myself.

答:
You already have an accepted answer, but I think the answer is incomplete (especially since it said you can't define multiple application entry points as easily as java).

To implement multiple entry points into the same code/module with C++, you do the following:

create a new cpp file for each entry point (i.e. main-app.cpp, io-tests.cpp, db-tests.cpp, network-tests.cpp, etc).

each file should define it's own main function.

each file should have a separate binary target in your build system (make file?).

build and run targets as needed.

Basically it's as easy as writing multiple main functions, each in their own file.

This solution works best if your main() function (in the example above, the one defined in "main-app.cpp") is as thin as possible.

A good implementation would look similar to this:

main-app.cpp:

```<code>#include <application.hpp>

int main(int, char**) {
    application app(std::cin, std::cout); // run application with std i/o
    return app.run();
}
</code>```

db-tests.cpp:

```<code>#include <database.hpp>    // tested class
#include <unit-tests.hpp>  // unit testing fw

int main(int, char**) {
    database_test_suite suite;
    return suite.run();
}
</code>```

You would have no target that compiles both of these files together (so you would not have any linker error with multiple definitions for main).

Title: Multiple entrance points in project

Body:
You already have an accepted answer, but I think the answer is incomplete (especially since it said you can't define multiple application entry points as easily as java).

To implement multiple entry points into the same code/module with C++, you do the following:

create a new cpp file for each entry point (i.e. main-app.cpp, io-tests.cpp, db-tests.cpp, network-tests.cpp, etc).

each file should define it's own main function.

each file should have a separate binary target in your build system (make file?).

build and run targets as needed.

Basically it's as easy as writing multiple main functions, each in their own file.

This solution works best if your main() function (in the example above, the one defined in "main-app.cpp") is as thin as possible.

A good implementation would look similar to this:

main-app.cpp:

#include <application.hpp>

int main(int, char**) {
    application app(std::cin, std::cout); // run application with std i/o
    return app.run();
}

db-tests.cpp:

#include <database.hpp>    // tested class
#include <unit-tests.hpp>  // unit testing fw

int main(int, char**) {
    database_test_suite suite;
    return suite.run();
}

You would have no target that compiles both of these files together (so you would not have any linker error with multiple definitions for main).


问:
How should we handle extra cosmetic features in Scrum sprints?
I was reading the Scrum documents and it says that the tasks in Sprint should be "potentially shippable".

I am confused by what this means. Suppose in Sprint 1 the goal was, "user registration form".

How much detail do I need to add for something to be ready to ship? For example:

I can show the simple form with fields without any fancy styling and mark them as done

I can just do client side validation as mark as done but server side is also the option or both

I can also add some jQuery fancy tool tips, hover overs, captcha, colors, labels for the form

Then there is whole lot of styling about how to show error messages on screen

I can do endlessly on one topic. So how do we divide that and when I can think of that as shipping ready.

Or do I need to write each smallest possible thing like showing errors, popup or light box text as subtasks and put them as sprint. This would lead to 1000s of tasks for whole project.

I mean then again if some work for Internet Explorer and some for Firefox then again do I need to divide those as tasks as well. Time has to be spent on them and when manager asks me what you did in that time, I won't have any tasks to tell but in reality they all are part of User registration

答:
Besides the other great answers to this question, you can also think of the cosmetic features as the variable scope part of the scope-resources-time triangle. Make sure you fulfill the basic requirements of that story, and add the pretty stuff if you have time.

Scrum isn't supposed to guarantee delivery of certain features in a given time. It's supposed to give you the maximum useful work that's possible in a given time. If "optional" cosmetic features don't get done during that sprint, it should be because they weren't possible.


问:
NoSQL design - Storing project assignments
I currently have a planning tool using SQL tables that are sort of setup like this:

Date table (Contains dates & indicates if that day is a weekend / holiday etc)

Employee (Simple data)

Project (Simple data)

Assignments (Associates the three tables, key date + employee id + project id)

I have one SQL query that, for a specific month/year, a joined list of employees + dates + assignment, e.g. 01/01/2014 employee_1 project_1. In case of no assignments, it returned the date anyway, as this makes it the most manageable on the front-end.

I was toying around with node.js & mongodb for the first time today, and was wondering if my setup is something that could translate well to NoSQL.

I really like the idea of using the JSON notation all the way, but I figure that this might be one of those cases where I'm better off with a RDBMS?

答:
The number one thing that you should ask yourself: How big will data be?

NoSQL offers "collections" and easy data set which is a primary usage over traditional RBDMS. When I mean large I mean in the millions not thousands. An effective SQL can handle thousands if the design is proper. I have worked with large MySQL and when it is time to switch columns we got bounced by it so that is why we intermediately switch to NoSQL Mongodb solution but we are also still using RBDMS for other solutions like lookup tables. Thats my opinion.

Also please take a look at:
When would someone use MongoDB (or similar) over a Relational DBMS?

As your question have been debated before.


问:
Sprint pressure causes quality issues?
The burn down chart displays a clear deadline and the progress towards the deadline. When the progress is slow and the completion of the committed work is at risk, people start to get sloppy on design and code reviews and on the depth of testing. Quality suffers.

The question is whether in your organization you were successful to maintain high quality standards regardless of the time remaining to the end of the Sprint. Another question is whether perhaps it is best to drop the burn down chart to somewhat reduce the pressure or even move from Scrum or Kanban or other agile methodology that doesn't mandates iterations.

答:
The burn down chart does not display a deadline.  It displays your progress towards your team's commitment.  I think that is an important note.

If someone is utilizing your sprint to enforce a deadline, then you're not actually doing scrum.  You're just working in sprints, which is a very common problem when teams start to adapt scrum.

When the burndown chart represents your burn down of committed tasks, it is more in the hands of your team.  If your work is suffering, it's because you have committed to more than you can accomplish.  During the next sprint, your team should naturally agree to commit to less work to provide a higher quality product.

Title: Sprint pressure causes quality issues?


问:
What are the drawbacks of not declaring a class-method static?
On the 'Interfaces' trail on the Oracle website, we are presented with the following scenario:

Imagine a futuristic society where computer-controlled robotic cars
  transport passengers through city streets without a human operator.
  Automobile manufacturers write software (Java, of course) that
  operates the automobile—stop, start, accelerate, turn left, and so
  forth. Another industrial group, electronic guidance instrument
  manufacturers, make computer systems that receive GPS (Global
  Positioning System) position data and wireless transmission of traffic
  conditions and use that information to drive the car.

The auto manufacturers must publish an industry-standard interface
  that spells out in detail what methods can be invoked to make the car
  move (any car, from any manufacturer). The guidance manufacturers can
  then write software that invokes the methods described in the
  interface to command the car. Neither industrial group needs to know
  how the other group's software is implemented. In fact, each group
  considers its software highly proprietary and reserves the right to
  modify it at any time, as long as it continues to adhere to the
  published interface. (http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html)

So we create an interface like this:

```<code>public interface OperateCar {

   // constant declarations, if any

   // method signatures

   // An enum with values RIGHT, LEFT
   int turn(Direction direction,
            double radius,
            double startSpeed,
            double endSpeed);
   int changeLanes(Direction direction,
                   double startSpeed,
                   double endSpeed);
   int signalTurn(Direction direction,
                  boolean signalOn);
   int getRadarFront(double distanceToCar,
                     double speedOfCar);
   int getRadarRear(double distanceToCar,
                    double speedOfCar);
         ......
   // more method signatures
}
</code>```

and implement it as:

```<code>public class OperateBMW760i implements OperateCar {

    // the OperateCar method signatures, with implementation --
    // for example:
    int signalTurn(Direction direction, boolean signalOn) {
       // code to turn BMW's LEFT turn indicator lights on
       // code to turn BMW's LEFT turn indicator lights off
       // code to turn BMW's RIGHT turn indicator lights on
       // code to turn BMW's RIGHT turn indicator lights off
    }

    // other members, as needed -- for example, helper classes not
    // visible to clients of the interface
}
</code>```

So far so good.  Now suppose that, in addition, each car manufacturer is required to create a prototype car, and suppose that, for some reason, we wish to keep track of these prototype cars.  One solution is to add a new method to the OperateCar interface:

```<code>public OperateCar getPrototype();
</code>```

Then each implementing class could implement this method by returning its prototype car.  But there's a problem with this: the prototype car has nothing to do with any instantiation of the implementing class; instead, it belongs to the class itself.  In other words, if we didn't have the interface, we'd automatically declare this method as static.  But we can't do that here, because Java interfaces don't allow static methods.

What are the problems associated with not declaring a class-method static?  Is it OK in this case just to leave out the static keyword so that the code compiles?  Or are the drawbacks so great that it's better to look for another solution?

答:
the prototype car has nothing to do with any instantiation of the implementing class; instead, it belongs to the class itself. In other words, if we didn't have the interface, we'd automatically declare this method as static.

Is it possible that one "car" class might inherit the same prototype as another?

Could the 760i share a common prototype with, say, the 760?  If so, the implementation of getPrototype() would come from the superclass and so couldn't be static.

And anyway, if your aim is to "keep track" of prototypes, surely there could be be any number of them for a given, road-worthy, production model?

Your interface doesn't (and shouldn't) care how the method is implemented in any particular class - just so long as it is implemented.


答:
public OperateCar getPrototype(); is essentially a Factory Method.  Your question essentially boils down to this: if I have a Factory Method, but I'm not allows to put it into my interface, then how can I make it static?

The answer of course, is that you can't.  But you don't need that capability anyway.

I would expect a static factory method to be part of... a factory.  I would expect that factory method to return an instance of your interface.

In other words, you don't need the static method in your interface.  Once the object gets created, a static method in the interface would become useless anyway, unless you intend to spawn new objects from the existing object.

Title: What are the drawbacks of not declaring a class-method static?

Body:
On the 'Interfaces' trail on the Oracle website, we are presented with the following scenario:

Imagine a futuristic society where computer-controlled robotic cars
  transport passengers through city streets without a human operator.
  Automobile manufacturers write software (Java, of course) that
  operates the automobile—stop, start, accelerate, turn left, and so
  forth. Another industrial group, electronic guidance instrument
  manufacturers, make computer systems that receive GPS (Global
  Positioning System) position data and wireless transmission of traffic
  conditions and use that information to drive the car.

The auto manufacturers must publish an industry-standard interface
  that spells out in detail what methods can be invoked to make the car
  move (any car, from any manufacturer). The guidance manufacturers can
  then write software that invokes the methods described in the
  interface to command the car. Neither industrial group needs to know
  how the other group's software is implemented. In fact, each group
  considers its software highly proprietary and reserves the right to
  modify it at any time, as long as it continues to adhere to the
  published interface. (http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html)

So we create an interface like this:

```<code>public interface OperateCar {

   // constant declarations, if any

   // method signatures

   // An enum with values RIGHT, LEFT
   int turn(Direction direction,
            double radius,
            double startSpeed,
            double endSpeed);
   int changeLanes(Direction direction,
                   double startSpeed,
                   double endSpeed);
   int signalTurn(Direction direction,
                  boolean signalOn);
   int getRadarFront(double distanceToCar,
                     double speedOfCar);
   int getRadarRear(double distanceToCar,
                    double speedOfCar);
         ......
   // more method signatures
}
</code>```

and implement it as:

```<code>public class OperateBMW760i implements OperateCar {

    // the OperateCar method signatures, with implementation --
    // for example:
    int signalTurn(Direction direction, boolean signalOn) {
       // code to turn BMW's LEFT turn indicator lights on
       // code to turn BMW's LEFT turn indicator lights off
       // code to turn BMW's RIGHT turn indicator lights on
       // code to turn BMW's RIGHT turn indicator lights off
    }

    // other members, as needed -- for example, helper classes not
    // visible to clients of the interface
}
</code>```

So far so good.  Now suppose that, in addition, each car manufacturer is required to create a prototype car, and suppose that, for some reason, we wish to keep track of these prototype cars.  One solution is to add a new method to the OperateCar interface:

```<code>public OperateCar getPrototype();
</code>```

Then each implementing class could implement this method by returning its prototype car.  But there's a problem with this: the prototype car has nothing to do with any instantiation of the implementing class; instead, it belongs to the class itself.  In other words, if we didn't have the interface, we'd automatically declare this method as static.  But we can't do that here, because Java interfaces don't allow static methods.

What are the problems associated with not declaring a class-method static?  Is it OK in this case just to leave out the static keyword so that the code compiles?  Or are the drawbacks so great that it's better to look for another solution?


问:
Beginning Data Mining
For simplicity, my database has entities and transactions.  Each transaction has a DateCreated and a foreign key to the entity.  I'd like to have the ability to find entities that have had a recurring number of transactions within a close time proximity of other entities.

Simply, if entity A has had a transaction within 10 minutes of entity B, 5 different times.

The more I research on this topic, the more confused I'm becoming.

I ran through the Data Mining Algorithms and their AdventureWorks data mining tutorial. I think I need a clustering approach.

Mostly I'm looking for guidance on how this type of problem is typically approached.  In the end, my goal is to allow the user to select X minutes and Y occurrences, and display the result data back to them.  If I can offer any more information please let me know.

答:
I would treat the DateCreated column from entity A and entity B as a foreign key to another table that stores counts of A and B for those dates. You can drop the seconds for that foreign key.

You can then use that table to find all entity A records that have entity B records within X minutes of each other. That would be done by using a JOIN from the entity A table to the foreign date counts table.

Difficult to explain further without actually seeing the schema of the tables.

Title: Beginning Data Mining


答:
What you're describing is a mindset issue more than anything else.  Do not think of the burndown chart as measuring progress towards a deadline.  Instead, think of it measuring progress towards your estimated goal for this sprint.  Instead of your developer thinking "I have XYZ to complete and it needs to be done by the sprint end date", your developer should be thinking "I have XYZ complete and based on the amount of time I have, I should be able to finish it by the sprint end date".

If your chart doesn't burn down 100% it simply means that your estimated goal didn't match what your team was able to produce in the sprint period.  It's always beneficial to find out why.  Did you not allocate the correct effort during your planning session? Were your developers playing Counterstrike instead of doing their work?  Did your team members encounter impediments?  Was there a critical bug that pulled key resources away from their work?

These types of discussions should be happening in part during your daily standups, and at the very least should be surfaced in your sprint retrospective.  This feedback should be taken into consideration and applied to help improve your estimates in the future.

Fixing quality comes down to your team buying into the notion that there aren't repercussions for having to bump something into the next sprint provided that the reason for it is valid.

Title: Sprint pressure causes quality issues?

Body:
The burn down chart displays a clear deadline and the progress towards the deadline. When the progress is slow and the completion of the committed work is at risk, people start to get sloppy on design and code reviews and on the depth of testing. Quality suffers.

The question is whether in your organization you were successful to maintain high quality standards regardless of the time remaining to the end of the Sprint. Another question is whether perhaps it is best to drop the burn down chart to somewhat reduce the pressure or even move from Scrum or Kanban or other agile methodology that doesn't mandates iterations.


问:
How to indicate to a web server the language of a resource
I'm writing an HTTP API to a publishing server, and I want resources with representations in multiple languages. A user whose client GETs a resource which has Korean, Japanese and Trad. Chinese representations, and sends Accept-Language: en, ja;q=0.7 should get the Japanese.

One resource, identified by one URI, will therefore have a number of different language representations. This seems to me like a totally orthodox use of content negotiation and multiple resource representations.

But when each translator comes to provide these alternate language representations to the server, what's the correct way to instruct the server which language to store the representation under? I'm having the translators PUT the representation in its entirety to the same URI, but I can't find out how to do this elegantly. Content-Language is a response header, and none of the request headers seem to fit the bill.

It seems my options are

Invent a new request header

Supply additional metadata in a multipart/related document

Provide language as a parameter to the Content-Type of the request, like Content-Type: text/html;language=en

I don't want to get into the business of extending HTTP, and I don't feel great about bundling extra metadata into the representation. Neither approach seems friendly to HTTP caches either. So option 3 seems like the best way that I can think of, but even then it's decidedly non-standard to put my own specific parameters on a very well established content type.

Is there any by-the-book way of achieving this?

答:
You can find some guidance on designing URIs to support multilingual resources here:

http://restpatterns.org/Articles/Designing_URIs

Also, here's how Google's Maps API let's consumers specify a language:

```

Notice the URL parameter at the end: language=ru-RU

Note: this is referenced from this StackOverflow question:

How to indicate the language in the Google Maps API?

Body:
You can find some guidance on designing URIs to support multilingual resources here:

http://restpatterns.org/Articles/Designing_URIs

Also, here's how Google's Maps API let's consumers specify a language:

<script src="http://maps.google.com/maps/api/js?sensor=false&amp;language=ru-RU"
        type="text/javascript"></script>

Notice the URL parameter at the end: language=ru-RU

Note: this is referenced from this StackOverflow question:

How to indicate the language in the Google Maps API?


答:
The way I see it, the purpose of the burn down chart is:

To allow the team to drop sprint commitments early rather than late if won't make it. The idea is that it's better to finish the sprint with one story done rather than two half done, and that the PO would rather know on Monday that this feature won't get done by Friday, rather than discover during the acceptance meeting.

To provide data allowing the team to get better estimates and stabler velocity faster: a good looking burn down chart should means that the team has their act together (not necessarily that they get much done). A chart looking too good usually means it got doctored and is useless.

If the team does anything to make the burn down chart look good, then it defeats the purpose. Remember: the primary measure of progress is working (high quality) software. Not a good looking burn down chart or unrealistic commitments.

If there is outside pressure on the team to that effect, I'd recommend to stop communicating the burn down chart outside the team. It is a valuable tool, but can be corrupt way too easily.

(To be clear: it's normal for overcommitment to happen occasionally. But if it happens regularly, then the team isn't learning: a stable velocity, realistic estimates and good communication about what's a stretch goal and what is promised should keep rough sprints at bay)

Title: Sprint pressure causes quality issues?


问:
What's a "Professional Fit" interview?
So I went through an initial interview on school campus, and an on-site interview(one day, mostly technical interviews) with this company, and then a week later, I am told that there will be an additional phone interview with one of their hiring managers, called "Professional Fit Interview", which I have no idea what it is. Before I thought the on-site interview was gonna be the last round, at least that's the impression I got from them.

So what this "professional fit interview" might be? How should I prepare for it?

Thanks a lot!

A follow-up: Thank everyone for the replies. As everybody has mentioned, it's a HR type interview. The interviewer did some introduction of the team, then asked if I have some questions, and asked me a couple of questions like "where do you see yourself in 2 years". Anyway, a rejection email came about one week later.

答:
A 'Professional Fit interview' is usually a non-technical interview by one or more people from the department you'd be hired into. It could be the senior manager who ultimately pays your salary, but it could also be a couple of engineers who are comfortable talking around various subjects to see if you'd fit in with a team like theirs.

There are some 'positive indicators' that they may be looking for (understands team work, can communicate, familiar with SDLC) that may not have been on your CV/resume nor come up in the technical interviews, but they're looking for them. Try to spot these and answer in a positive fashion. E.g.:

Question: What coding style do you use?

Good Answer: I'll take cues from the style of surrounding lines of code to ensure consistency, or ask colleagues about the team style.

Bad Answer: I like to re-format all code I work on to fit my personal tab/brace/naming style. It's so much better than anything else (yes, I've heard this)

There are some items that would count as 'negative indicators'. It may be illegal/bad form to ask certain questions in an interview (e.g. in UK can't ask about family, marital status, gender or religion), so they may want to talk around the subject until you accidentally let slip something they feel may be a problem for them.

Yes, this is immoral, but it happens in real life. I have seen people rejected because they were gender-unsure even though they were brilliant programmers. I have also seen excellent engineers hired by HR departments but then get ostracised by the team as they just didn't get along with anyone in the team.

Don't volunteer anything you don't need to. For example, no need to mention that you're thinking of starting a family next year - it's none of their business, but some interviewers would immediately think "has outside commitments to distract him from the job". If you can get to the office by ~9am and do a full days' work, no need to make them think that you can't.

My top tips for getting through this:

Dress smart. You need to look 'professional', even if the dress code is metal T-shirt and ripped jeans.

Professional, objective responses. Don't run your mouth off over anything - you may be lulled into doing so (a common technique), but try to stay on-topic.

Do some homework before the interview. Try to have a better understanding of their company, their projects/goals, the market they operate in, etc. As this is interview is further through the process, you should be demonstrably more interested in the job.

Be straight with them. Tell the truth. If you don't know, just say - don't waste anyone's time. If you're caught bending the truth, you'd likely fail your probationary period or (worse) be sued.

Be alert - although the person interviewing you may seem detached from the job you've applied for, they may try to throw in the occasional technical question to make their own assessment of you or to see you how react. I once had a CTO-level guy in a finance company ask me to compare and contrast two embedded O/S's approach to device drivers. Yep, really.

Title: What's a "Professional Fit" interview?


答:
If I understand you correctly, a car manufacturer is the only source of cars (including the prototype). It's only the interface that must be public. And that interface should provide a way to access the prototype (for whatever reason) but no-one outside the manufacturing process will ever be building the prototype. Using these assumptions...

The interface should indeed have a method getPrototype() of some sorts. It's only a matter of how the prototype got inserted into the actual car implementation. That (actual) inserted prototype may easily be static.

```<code>class MyCarManufactory() {
    OperateCar buildNewCar(OperateCar prototype) {
        // build your car here
    }
}
</code>```

While your car may look like:

```<code>public class OperateBMW760i implements OperateCar {
    private static OperateCar prototype;

    OperateCar getPrototype() {
        return prototype;
    }

    int signalTurn(Direction direction, boolean signalOn) {
       // code to turn BMW's LEFT turn indicator lights on
       // code to turn BMW's LEFT turn indicator lights off
       // code to turn BMW's RIGHT turn indicator lights on
       // code to turn BMW's RIGHT turn indicator lights off
    }

    // other members, as needed -- for example, helper classes not
    // visible to clients of the interface
}
</code>```

There is no harm using an instance method to access a static field. In fact, the information about your prototype actually being static is not of anyone's concern.

Body:
If I understand you correctly, a car manufacturer is the only source of cars (including the prototype). It's only the interface that must be public. And that interface should provide a way to access the prototype (for whatever reason) but no-one outside the manufacturing process will ever be building the prototype. Using these assumptions...

The interface should indeed have a method getPrototype() of some sorts. It's only a matter of how the prototype got inserted into the actual car implementation. That (actual) inserted prototype may easily be static.

class MyCarManufactory() {
    OperateCar buildNewCar(OperateCar prototype) {
        // build your car here
    }
}

While your car may look like:

public class OperateBMW760i implements OperateCar {
    private static OperateCar prototype;

    OperateCar getPrototype() {
        return prototype;
    }

    int signalTurn(Direction direction, boolean signalOn) {
       // code to turn BMW's LEFT turn indicator lights on
       // code to turn BMW's LEFT turn indicator lights off
       // code to turn BMW's RIGHT turn indicator lights on
       // code to turn BMW's RIGHT turn indicator lights off
    }

    // other members, as needed -- for example, helper classes not
    // visible to clients of the interface
}

There is no harm using an instance method to access a static field. In fact, the information about your prototype actually being static is not of anyone's concern.


答:
With software, typically you have the following metrics:

Time scale.  You have the iteration.

Scope.  You have fixed the scope.

Resources.  You have the team members.

Quality.  Quality has to be 100%

When the pressure is on, which one do you sacrifice?  Do you expect the team to create more time scale by working overtime?  Do you drop stories?  Additional developers probably won't get up to speed quickly enough?  or do you just test the basics, and cross your fingers?

What I have seen happen in all the scrum teams I've worked with is that they are under pressure to continually increase 'scope' as its a measure of how good the team is, that to deliver on this, teams over work their hours, and that quality gets squeezed, as developers deliver late, and the end deadline cannot be moved.

What Scrum was intended to deliver was:

Time scale: we review the progress of the product at fixed, periodic occasions which ensure we are delivering features that the customer need.

Resources:  We have clarity over who is working in the team for the iteration. developers are not pulled around doing painful context switches.

Quality:  We value quality above all. We make sure that everything we produce is properly tested and if we have not tested it 100% then its not yet done.

Scope:  We are giving the business visibility over what we expect to deliver at the end of this iteration - based on our past experiences.

In this environment, when the pressure is on, its Scope that's sacrificed.

How to make scrum work?

That is the wrong question.  The right question is what kind of output does the company need from the development team?  Do they need a quality product? or do they need to release software to a deadline?

When they have come to terms with this, then they will be able to organise the appropriate environment for their developers.  Scrum, kanban, XP can all do this, but they are all environment dependent.

Title: Sprint pressure causes quality issues?


问:
Twitter Bootstap: Backwards compatibility?
I work for a university Digital Services team. Our university's main website uses the Ektron CMS (I have my own thoughts about this, but that's irrelevant). Because we maintain a university website, we need to make sure our website is extremely backwards compatible.

We are trying to make a decision as to whether Twitter Bootstrap is conducive to what we're trying to do. Upon review, I've found that Bootstrap uses the CSS preprocessor "*Less Css*". We're currently using *SASS*, which we compile via terminal using Ruby Compass. The downside I'm wondering about while using *Less Css* would be that it compiles using Rhino and Node.js. Would this create issues because

 Less CSS uses Node.js to compile; if someone does not have js enabled in their browser, will it not display the CSS?

 the CSS has to compile each time a page is rendered, will it slow down a pages load time?

What is most appealing to use is the grid system/glyphs/ and js plugins that comes with Bootstrap, which is good because we often have to create new content for events and other things happening in the university. However, it's extremely hard for us to give up cross compatibility.

What are benefits of Bootstrap?

What are draw backs of Bootstrap?

答:
As you can see in the comments above you do not have to use the LESS files and the javascript to compile on every page load.  You can download bootstrap with all of the css files already compiled for you.

Also depending on your server environment you can employ different plugins to precompile the css files for you.  I see you are using a .NET CMS so you should be able to employ some Visual Studio plugins to help you with this.  One such plugin is Mindscape Workbench which supports LESS and SASS (also CoffeeScript).  I've never used it but Scott Hanselman seems to like it.

One final thing to consider is that your site needs to be "extremely backwards compatible".  I am not sure if you are aware of this but bootstrap no longer supports IE7.  If this browser is not necessary then don't worry about it.  If it is then you can still use bootstrap but you will be left to write your own IE stylesheets to support bootstrap.


问:
How do login systems work?
I assume that when a user registers at a site, the password and username are stored inside of a database.

I've read that the password is often encrypted using a salt. So, is it safe to encrypt the passwords with a salt and to save it in the same schema with the username?

Secondly, how does authentication work? Companies like Google have giant databases of username/password pairs. How does validation work so quickly, and how is it implemented?

答:
This question has some faulty assumptions, I'll try and clear these up first:

Salts are not used as input to encryption but as input to one-way functions such as hashes.

Some sites may store databases of passwords, which is how they can be hacked and their users passwords stolen, but you should NOT do this. General practice is to store hashes of passwords (and salts, see above) and when a user tried to log in, hash their provided password and compare the hashes.

[Google does everything quickly. I don't know if they do map / reduce for authentication but they have a lot of smart people working on it, maybe this should be a separate question.]

So salted hashes are then stored somewhere on the server. In terms of security I don't think it makes any difference whether you store them in a file, a relational database or in a NOSQL database. For speed at 'web scale' then you probably want to have a look at NOSQL databases and caching the data rather than using IO to disk.

Title: How do login systems work?


问:
How do I evaluate if an Orchestration is the appropriate design pattern for a given problem?
Say that you're doing a code review, and you find yourself faced with an orchestration pattern:

```<code>class OrchestrationClass {
  private Configuration _configuration;
  private DataStore1 _dataStore1;
  private EfficientComputationService _service;
  private ResultPrettifier _formatter;

  public DoSomething () {
     with (data = _dataStore1.LoadForConfiguration(_configuration)) {
        return _formatter.PrettyPrint(_service.Process(data));
     }
  }
}
</code>```

Under which circumstances is this considered to be a valid pattern/anti-pattern (and how is the anti-pattern to be cleanedup/refactored)?

For context:

This recently came up in a code review, and several people mentioned the pattern/anti-pattern. Searches of the standard patterns literature, related Google search and scan through blog posts / wikis have all led to indirect mentions. Which leads me to believe that this pattern / anti-pattern hasn't yet had a formal treatment (or, if it has, it's not yet online). Hence - the question is here, where someone more experienced or widely read might be able to answer (or provide a reference)

答: Your code just looks like an example of the "Single Level of Abstraction" concept (note that I intentionally don't use the word "pattern" here), which is a good practice under normal circumstances. The idea of this concept is to have same level of abstraction for all statements inside a method.</p>


问:
Solution Checker Algorithm for a Game
For the moment I'm strictly speaking in Pseudocode. I'd only like to see if i'm on the right track. The game I'm talking about is similar to a application called FLOW.

In this game, you're given a nxn board(Always a square) and need to fill out each slot in the board. Similarly, when a board game is initialized, it will have objects like the set up below...

```<code>Board - 1 2 3 1
        0 0 0 0
        0 2 3 0
        0 0 0 0
</code>```

In this example - the objects are 1 2 and 3.

A solution would be as follows...

```<code>Board - 1 2 3 1
        1 2 3 1
        1 2 3 1
        1 1 1 1
</code>```

The whole purpose is to fill out the board game by connecting the starting object to the end object. What I have in mind is the following...

```<code>CheckSolution(1d representation of the boards state, int totalcolors) {

  // I would loop through the colors, a 0 is not a color - empty.
  // If the board has a 0 in the array, I would automatically return a false solution.
  // Then, I would call DepthFirstSearch on the color.
       // -- I would set a counter on this to count the # of colors, if this isn't equal to the total # of that particular color, I would return false.
  // Else, the solution is valid.
}
</code>```

Does this sound reasonable? Or is the better way to implement a solution checker.

答:
Your algorithm is essentially OK (although you could have expressed it much better...), if you mark all visited cells (e.g., by setting them to 0).

You can start the search (equivalent to a flood fill) while scanning the matrix, no need to make two passes.

I don't think that there is a way to avoid the "flood fill".

EDIT

Regarding "counting", you will rather have to check that each color is flood-filled only once. So, you would be better off allocating an array of booleans that tells you whether a color has been "filled" or not, initialized to false. So, each time you find a new start for a fill, you first check whether that color has not been seen already - if it has, it's not a solution. The only thing worthwhile counting is the number of fills. Instead of checking whether the array is "all trues" at the end, you can check that you have done totalcolors fills.

Title: Solution Checker Algorithm for a Game


答:
Passwords are encrypted in a repeatable one-way fashion. They are then stored in a file, database, or whatever as a [user]-> [encrypted password] pair.

When the user logs in, they enter a username and password.  The website or application may retrieve the stored encrypted password that matches that username before the user even enters their password, (via ajax or other asynchronous methods as soon as they switch fields from the username field to the password field).  This saves time, but the application still has to encrypt the password string entered by the user so that it can be compared with the encrypted version that is stored.

Title: How do login systems work?

Body:
I assume that when a user registers at a site, the password and username are stored inside of a database.

I've read that the password is often encrypted using a salt. So, is it safe to encrypt the passwords with a salt and to save it in the same schema with the username?

Secondly, how does authentication work? Companies like Google have giant databases of username/password pairs. How does validation work so quickly, and how is it implemented?


答:
Based on flow, the rules read:

Simple, but fun HTML5 puzzle game. Connect the dots by drawing a line with the mouse between the two dots with matching colors. Lines can not cross and you must fill in every square to completely solve the puzzle. Game features fun audio and 150 different levels. Not to difficulty to beat, but fun to play through once or twice.

The flood fill approach does not take into consideration that there is a single line that needs to connect the spots and may accept invalid solutions.

Consider the puzzle:

```
1 . . .
2 3 . .
. 3 . .
. . 2 1
```

The flood fill approach will accept all of:

```
1 1 1 1    1 1 1 1    1 1 1 1
2 3 1 1    2 3 3 1    2 3 2 1
2 3 1 1    2 3 3 1    2 3 2 1
2 2 2 1    2 2 2 1    2 2 2 1
```

as valid.  However, only the middle is a valid solution to the puzzle because no line was drawn to connect the 3s through other cells in the other two.  Furthermore, the 2s didn't end on the proper spot on the one in the right.

As such, your solution finder is not correct.  It needs the initial state of the puzzle, the solution, and ideally the path the line was drawn through in order to determine if a given solution is valid or not.

Title: Solution Checker Algorithm for a Game

Body:
For the moment I'm strictly speaking in Pseudocode. I'd only like to see if i'm on the right track. The game I'm talking about is similar to a application called FLOW.

In this game, you're given a nxn board(Always a square) and need to fill out each slot in the board. Similarly, when a board game is initialized, it will have objects like the set up below...

```<code>Board - 1 2 3 1
        0 0 0 0
        0 2 3 0
        0 0 0 0
</code>```

In this example - the objects are 1 2 and 3.

A solution would be as follows...

```<code>Board - 1 2 3 1
        1 2 3 1
        1 2 3 1
        1 1 1 1
</code>```

The whole purpose is to fill out the board game by connecting the starting object to the end object. What I have in mind is the following...

```<code>CheckSolution(1d representation of the boards state, int totalcolors) {

  // I would loop through the colors, a 0 is not a color - empty.
  // If the board has a 0 in the array, I would automatically return a false solution.
  // Then, I would call DepthFirstSearch on the color.
       // -- I would set a counter on this to count the # of colors, if this isn't equal to the total # of that particular color, I would return false.
  // Else, the solution is valid.
}
</code>```

Does this sound reasonable? Or is the better way to implement a solution checker.

Body:
Based on flow, the rules read:

Simple, but fun HTML5 puzzle game. Connect the dots by drawing a line with the mouse between the two dots with matching colors. Lines can not cross and you must fill in every square to completely solve the puzzle. Game features fun audio and 150 different levels. Not to difficulty to beat, but fun to play through once or twice.

The flood fill approach does not take into consideration that there is a single line that needs to connect the spots and may accept invalid solutions.

Consider the puzzle:

1 . . .
2 3 . .
. 3 . .
. . 2 1

The flood fill approach will accept all of:

1 1 1 1    1 1 1 1    1 1 1 1
2 3 1 1    2 3 3 1    2 3 2 1
2 3 1 1    2 3 3 1    2 3 2 1
2 2 2 1    2 2 2 1    2 2 2 1

as valid.  However, only the middle is a valid solution to the puzzle because no line was drawn to connect the 3s through other cells in the other two.  Furthermore, the 2s didn't end on the proper spot on the one in the right.

As such, your solution finder is not correct.  It needs the initial state of the puzzle, the solution, and ideally the path the line was drawn through in order to determine if a given solution is valid or not.


答:
There are many ways, but the basic one is called challenge-response.

This is where the user's password is never sent to the server, but is encrypted instead (using a hash algorithm). The hash is sent to the server, usually over an encrypted channel and saved for later.

When the user wants to login, he sends a login request, the server then encrypts a message of some sort (the challenge) and also generates the correct response (ie encrypts the challenge using the stored hash). The challenge is sent to the client who calculates what the response should be (by taking the user's password and re-generating the hash from the password). The client sends this encrypted response to the server who compares it to the pre-calcuated correct answer. If they match, the client must have the correct password in order to generate the correct response, and you let him have access.

The good part is that the password never gets sent to the server, except during the initial account creation stage, and even then its sent as a hash.

Title: How do login systems work?


答:
Generally speaking, huge corporations don't store the users in a database. They have an identity management system with the following structure (for sure it may vary from company to company but I think this is going to give you an idea):

Securized Person Directory (openLDAP, Active Directory, Oracle Identity Manager, ...)

They store here everything related to persons, name, mail, username, password (encrypted), etc... (there are many schemes to use). It's used for autentication only. Not accesible from the outside.

Authorization system (Kerberos for example)

Once you've logged in correctly, you need a system that give you access to the resource you're allowed to, this is done generating a session-ticket (valid only for a period of time). This ticket tells your application if you have access to which parts of it (The common way to organize this is with groups -> roles -> application permissions).

Single sign-on system.

Once you've logged in and you've got your ticket that grants you access to several resources within an organization, you can store it locally in your machine (for example with a Cookie) so that you don't have to give your username/password again and again when try to access other resource you've access to with the ticket (if your ticket expiry time have not expired yet).

Obviously this can be as complicated as you want, and you can develop this solutions ad-hoc for your company/project but this is the general idea behind.

When you develop a webapp for example, the best approach is to develop an authentication provider layer which can manage this kind of login/authorization systems as well as the simpler one username/password in a database.

Title: How do login systems work?


问:
Which features of shell scripting are relevant for PHP/Python development?
I'm a PHP/Python programmer learning Java and C#(.NET).

My main development OS is windows 7 but I've used Linux and I currently dual-boot with Ubuntu. My Linux knowledge however, is pretty limited. I can work with the command line on simple tasks but that's pretty much it. I don't do any shell scripting and I don't know many important commands.

My interests are web development, mobile apps and maybe some embedded stuff in the future.  Will shell scripting skills be useful for these interests and if so, how?

答:
If you're a PHP programmer, you should definitely know Linux. PHP was created on Linux, and PHP is an imporant part of the LAMP stack: Linux+Apache+MySQL+PHP. Even if you have the opportunity to develop for Windows servers now, your next job will probably have you developing for Linux servers, and you'll need to be familiar with the Linux environment so that you're not running afoul of Window specific 'isms of PHP.

In the mobile app space, knowing Linux will (sadly) have little relevance to the environments you're developing for. iPhone OS has nothing to do with Linux, and Android has you so tightly fenced into a virtual machine, you'll never know there's Linux beneath you. You could program for Linux on Meego or Maemo, but those have nowhere near the popularity of the iPhone and Android.

In the embedded space, you have to know Linux. Embedded Windows is rare, but embedded Linux is quite common. (Of course, bare-metal embedded programming is also quite common, so it depends where you want to go.)

If you learn Linux in depth over a number of years, you'll have some level of understanding of every part of the system from the kernel, through the bootup process, up to the command-line, and GUI.


问:
Complete immutability and Object Oriented Programming
In most OOP languages, objects are generally mutable with a limited set of exceptions (like e.g. tuples and strings in python). In most functional languages, data is immutable.

Both mutable and immutable objects bring a whole list of advantages and disadvantages of their own.

There are languages that try to marry both concepts like e.g. scala where you have (explicitly declared) mutable and immutable data (please correct me if I am wrong, my knowledge of scala is more than limited).

My question is: Does complete (sic!) immutability -i.e. no object can mutate once it has been created- make any sense in an OOP context?

Are there designs or implementations of such a model?

Basically, are (complete) immutability and OOP opposites or orthogonal?

Motivation: In OOP you normally operate on data, changing (mutating) the underlying information, keeping references between those objects. E.g. an object of class Person with a member father referencing another Person object. If you change the name of the father, this is immediately visible to the child object with no need for update. Being immutable you would need to construct new objects for both father and child. But you would have a lot less kerfuffle with shared objects, multi-threading, GIL, etc.

答:
Immutability can be simulated in an OOP language, by only exposing object access points as methods or read-only properties that do not mutate the data. Immutability works the same in OOP languages as it does in any functional language, except that you may be missing some functional language features.

Your presumption seems to be that mutability is a core feature of object-orientation. But mutability is simply a property of objects or values. Object-orientation encompasses a number of intrinsic concepts (encapsulation, polymorphism, inheritance, etc.) that have little or nothing to do with mutation, and you would still derive the benefits of those features, even if you made everything immutable.

Not all functional languages require immutability, either.  Clojure has a specific annotation that allows types to be mutable, and most of the "practical" functional languages have a way to specify mutable types.

A better question to ask might be "Does complete immutability make sense in imperative programming?"  I'd say the obvious answer to that question is no.  To achieve complete immutability in imperative programming, you would have to forego things like for loops (since you would have to mutate a loop variable) in favor of recursion, and now you're essentially programming in a functional manner anyway.


答:
In c# some types are immutable like string.

This seems to furthermore suggest that the choice has been strongly considered.

For sure it's really performance demanding to use immutable types if you have to modify that type hundred of thousand of times. That's the reason why it's suggested to use the StringBuilder class instead of the string class in this cases.

I've made an experiment with a profiler and using the immutable type is really more CPU and RAM demanding.

It's also intuitive if you consider that for modifying just one letter in a string of 4000 characters you have to copy every char in another area of the RAM.

Title: Complete immutability and Object Oriented Programming

Body:
In most OOP languages, objects are generally mutable with a limited set of exceptions (like e.g. tuples and strings in python). In most functional languages, data is immutable.

Both mutable and immutable objects bring a whole list of advantages and disadvantages of their own.

There are languages that try to marry both concepts like e.g. scala where you have (explicitly declared) mutable and immutable data (please correct me if I am wrong, my knowledge of scala is more than limited).

My question is: Does complete (sic!) immutability -i.e. no object can mutate once it has been created- make any sense in an OOP context?

Are there designs or implementations of such a model?

Basically, are (complete) immutability and OOP opposites or orthogonal?

Motivation: In OOP you normally operate on data, changing (mutating) the underlying information, keeping references between those objects. E.g. an object of class Person with a member father referencing another Person object. If you change the name of the father, this is immediately visible to the child object with no need for update. Being immutable you would need to construct new objects for both father and child. But you would have a lot less kerfuffle with shared objects, multi-threading, GIL, etc.


答:
OOP and immutability are almost completely orthogonal to each other. However, imperative programming and immutability are not.

OOP can be summarized by two core features:

Encapsulation: I will not access the contents of objects directly, but rather communicate via a specific interface (“methods”) with this object. This interface can hide internal data from me. Technically, this specific to modular programming rather than OOP. Accessing data via a defined interface is roughly equivalent to an abstract data type.

Dynamic Dispatch: When I call a method on an object, the executed method will be resolved at run time. (E.g. in class-based OOP, I might call a size method on a IList instance, but the call might be resolved to an implementation in a LinkedList class). Dynamic dispatch is one way to allow polymorphic behavior.

Encapsulation makes less sense without mutability (there is no internal state that could be corrupted by external meddling), but it still tends to make abstractions easier even when everything is immutable.

An imperative program consists of statements which are executed sequentially. A statement has side effects like changing the state of the program. With immutability, state cannot be changed (of course, a new state could be created). Therefore, imperative programming is fundamentally incompatible with immutability.

It now happens that OOP has historically always been connected with imperative programming (Simula is based on Algol), and all mainstream OOP languages have imperative roots (C++, Java, C#, … are all rooted in C). This does not imply that OOP itself would be imperative or mutable, this just means that the implementation of OOP by these languages allows mutability.


答:
The best practice would be to have a coding style guide, and have regular reviews, so that when you're approaching a deadline, you're not faced with this problem.

My recommendation is for you to show leadership, and spearhead the regular code review. Management doesn't get pushed from the top to ensure that regular code reviews happen, but my experience is that they will be impressed when a programmer steps up to schedule and hold regular code reviews.

There are many benefits for your people, who will:

learn better style

follow better practices

learn to research what they're doing

And some benefits for yourself, you will be:

more efficient during last-minute debugs (which will always happen)

recognized as both an expert and a leader by both your team and management

Title: How important is it to clean up someone else's code when faced with a tight deadline?

Body:
(I'm talking about HTML / CSS code (not programming languages) but I think we also face the same issue as with programmers.)

I am the senior front-end designer in a team and I often have to re-work my juniors' output in tight deadlines.

I am faced with 2 problems:

Their coding style is a bit of a mess.

The aesthetics are not good.

Their coding style, I find, is a mixed bag with no proper convention / standard. I am torn between cleaning up the code or just dealing with their code (even copying how they do things).

I do find it frustrating to follow their coding style as I feel I might learn bad habits. But then, that is the fastest way of meeting the deadline.

For those with much more experience, which is more effective? Should I save the clean-up for later? Or clean-up along the way as I make the changes?

(I don't want to sound arrogant though but such is the reality. It will take them more years to write better code. I know, I wrote messy code when I was starting.)


答:
If I am coding a windows app (or a mac app) why should I need to know Linux? Should a Ford mechanic know John Deer tractors?  It all depends on what you are doing, professionally or on your own "hobby" time.

Now, it doesn't hurt to know it.  In fact, I am a firm believer in "the more you know, the better off you are"

Title: Which features of shell scripting are relevant for PHP/Python development?

Body:
I'm a PHP/Python programmer learning Java and C#(.NET).

My main development OS is windows 7 but I've used Linux and I currently dual-boot with Ubuntu. My Linux knowledge however, is pretty limited. I can work with the command line on simple tasks but that's pretty much it. I don't do any shell scripting and I don't know many important commands.

My interests are web development, mobile apps and maybe some embedded stuff in the future.  Will shell scripting skills be useful for these interests and if so, how?


答:
Note, there's a culture among object oriented programmers where people assume if you're doing OOP that most of your objects will be mutable, but that's a separate issue from whether OOP requires mutability.  Also, that culture seems to be slowly changing toward more immutability, due to people's exposure to functional programming.

Scala is a really good illustration that mutability isn't required for object-orientation.  While Scala supports mutability, its use is discouraged.  Idiomatic Scala is very much object oriented and also almost entirely immutable.  It mostly allows mutability for compatibility with Java, and because in certain circumstances immutable objects are inefficient or convoluted to work with.

Compare a Scala list and a Java list, for example.  Scala's immutable list contains all the same object methods as Java's mutable list.  More, in fact, because Java uses static functions for operations like sort, and Scala adds functional-style methods like map.  All the hallmarks of OOP—encapsulation, inheritance, and polymorphism—are available in a form familiar to object-oriented programmers and used appropriately.

The only difference you'll see is when you change the list you get a new object as a result.  That often requires you to use different design patterns than you would with mutable objects, but it doesn't require you to abandon OOP altogether.


答:
Any straight answer is going to be extreme. Clearly there are cases in which the deadline is so tight that you must use ugly code, and there are cases where the code is so ugly that it's worth missing the deadline to improve it. What you need is methods to judge which you're in, and perhaps methods to set realistic deadlines that allow time to write better code.

Don't save the cleanup for later. Unless you habitually have periods with nothing to do but refactor, there is no "later" in which it will somehow become higher priority to tidy up the code than it is right now. The routine is "red, green, refactor", not "red, green, do something completely different for two weeks, refactor". Realistically you will not change the code until next time you're revisiting it for some other reason, and you'll probably be on a deadline then too. Your real options are to fix it now or leave it.

Of course well-styled code is better than badly-styled code, assuming you plan to ever read it again. If you plan never to read it again, then do not tidy it up. Ship the first thing that passes the tests. But that's a pretty rare scenario, for most programmers it happens approximately never. Ignoring that case, only you have the details of your real case to make a judgement how much it costs to fix vs. how much it costs (in increased future maintenance) to not fix it.

There are certain things that are no harder to fix at the point where the code requires maintenance, than they are to fix now. These don't actually benefit you much to fix now. The most obvious are trivial to fix (whitespace errors and the like) and so it's difficult to imagine that you have time to ask this question but not to fix them ;-) For that ones that are not trivial and are of this kind then OK, you have some code that isn't ideal but you must be pragmatic. It works and you're on a deadline. Use it.

There are certain things that are considerably easier to fix now than they will be later when (a) they're not so fresh in everyone's minds; (b) other things have been written that rely on them or imitate them. These are much more valuable to fix now, so prioritise them. If you don't have time in your deadlines to fix these, then you need to push as hard as you can for longer deadlines, because you are building up debt in your code base that you'll probably have to pay next time you visit the code.

The preferred method of fixing code is through a review process. Comment on the problems you have with it, and send it back to the junior to change. You might give examples of what you mean and leave the junior to find all the cases in the code that they apply to, but don't just finish their code for them. If you do then you give them no means to improve.

You should write common problems up into a style guide that says "don't do this, do this instead", and explains why. Ultimately the reason is allowed to be, "in order to make our code aesthetically consistent", but if you aren't prepared to write down your rules with some justification then you probably shouldn't be enforcing them either. Just leave each programmer free to choose.

Finally, beware of the tendency to tweak stuff indefinitely. The returns diminish, and you need to learn through experience where they're still good. It is absolutely essential that you form a realistic idea of what is good enough, or else you can't have that negotiation in which you make sure that your deadlines give you time to create "good enough" code. Spend your time on things that are not good enough.


答:
Yes, but you do not sound like you need to actively study it.

For me my familiarity with linux developed through use my use of it as my work OS. Piece by piece I learned the things I needed to know as they came up, and continue to do so. The internet is full of resources on how to do just about anything you would need to wrt linux, so instead I would suggest that you get good at reading man pages and documentation and let your brain absorb (and forget) the details of how to accomplish specific tasks as you go.

That being said there are certainly a few commands that you will be shunned from the linux world for not having a basic grasp of.


答:
Complete immutability of everything doesn't make much sense in OOP, or most other paradigms for that matter, for one very big reason:

Every useful program has side effects.

A program that does not cause anything to change, is worthless.  You may as well not have even run it, as the effect will be identical.

Even if you think you're not changing anything, and are simply summing up a list of numbers you somehow received, consider that you need to do something with the result -- whether you print it to standard output, write it to a file, or wherever.  And that involves mutating a buffer and changing the state of the system.

It can make a lot of sense to restrict mutability to the parts that need to be able to change.  But if absolutely nothing needs to change, then you're not doing anything worth doing.


问:
Can the Jacquard loom be considered stateless?
Can the Jacquard loom, pictured below complete with its chains of paper cards

be considered stateless? As far as I can tell I can tell, each operation is not dependant on the previous. Or did it have any concept of branching and/or looping?

答:
Well, the loom is stateful in that it knows what the current card is. (So it keeps track of line # according to the analogies from comments.) The program, however, is stateless, because each card just weaves a line with no knowledge of what came before or after. So loom: No. "Program": Yes. :)

Moreover, the loom is mutable, because it's always changing the state of "current card" rather than spawning a brand new loom where the next card is in front.

Moreover, both the loom and cards have side-effects, because they result in a new line of weaving in the rug or tapestry or whatever they're making.

I would say the loom is Object-Oriented, because it receives a message in the form of a chain of cards, and then iterates through that message to produce side-effects. So there. :P


答:
I think it depends on whether your definition of OOP is that it uses a message-passing style.

Pure functions don't have to mutate anything because they return values which you can store in new variables.

```<code>var brandNewVariable = pureFunction(foo);
</code>```

With message passing style, you tell an object to store new data instead of asking it what new data you should store in a new variable.

```<code>sameOldObject.changeMe(foo);
</code>```

It's possible to have objects and not mutate them, by making its methods pure functions that happen to live on the inside of the object instead of outside.

```<code>var brandNewVariable = nonMutatingObject.askMe(foo);
</code>```

But it's not possible to mix message passing style and immutable objects.

Body:
I think it depends on whether your definition of OOP is that it uses a message-passing style.

Pure functions don't have to mutate anything because they return values which you can store in new variables.

var brandNewVariable = pureFunction(foo);

With message passing style, you tell an object to store new data instead of asking it what new data you should store in a new variable.

sameOldObject.changeMe(foo);

It's possible to have objects and not mutate them, by making its methods pure functions that happen to live on the inside of the object instead of outside.

var brandNewVariable = nonMutatingObject.askMe(foo);

But it's not possible to mix message passing style and immutable objects.