问:
How to best model an application's settings?
My application has a configuration file and a "Settings" window. When the user confirms the changes in this window they are applied and written to the config file.

These settings are often changed and referenced throughout my program. I'm trying to figure out how to model the accessing and manipulating of these settings. On the one hand, I can't reference the GUI elements directly, that just seems like very bad practice. On the other hand I can't keep reading and writing to the config file because I don't want certain changes to settings to persist, e.g. the current username of the user logged in needs to be stored somewhere; I can't store it in the config file because I don't want the application to "remember" the user having accessed the system.

So is the solution to have a ConfigObj object, containing all the settings of the program, which is is accessible to all modules of the codebase? Is this a common solution?

But there is a problem which I don't know how to solve, demonstrated in the following scenario:

Program starts, the ConfigObj object is initialised with the config file.

User opens the "Settings" window. The GUI controls are populated with the values from the ConfigObj.

One of the values in the "Settings" window is "COM Port", and if the user changes it and clicks "Save Settings" its value will be written to ConfigObj as well as the config file.

The user closes the "Settings" window and opens another window "Find USB Port". This window finds an available COM port and assigns it to ConfigObj.Port. This change is rather temporary and isn't written to the config file, but now the global-wide selected port for the application is set to this, and other functions depend on this value.

Now the user opens the "Settings" window again: the program should display the current settings of the program, i.e. what's in ConfigObj, but how does it know to do this instead of populating from the config file as in Step 1?

I suppose I could compare all values between the config file and ConfigObj, but is there a more correct way? What's the cleanest way to handle application-wide configuration?

答:
Given that your application needs that kind of complexity, then here are my 5 cents (I will use Java code):

Settings are split in two categories acording to whether or not they take immediate effect when they are altered.

dynamic: have an immediate effect in the application's behavior

static: don't have an immediate effect in the application's behavior and only take effect on application restart, or on config reload.

The scope of altering a setting can be:

memory

disk

memory and disk

I think the Configuration object should implement this interface:

```<code>import java.util.List;
import java.util.Map;

public interface Configuration {
    // key is the name of a setting
    public void reload(); // reloads from disk without restarting app
    public String getValue(String key); // gets value of setting identified by key
    public String getOldValue(String key); // gets old value of setting identified by key
    public String setValueToMemory(String key); // alters value of setting identified by
                                                // key only in memory (will be lost after reload or restart)
    public String setValueToMemoryAndDisk(String key); //alters value of setting identified by key
                                                       //both in memory and disk (will persist after reload or restart)
    public String isDirty(String key); // indicates whether or not this setting is "dirty",
                                       // meaning it's value is different from disk.
    public Setting getSetting(String key); // return setting metadata
    public void dump(); // prints all key-value pairs
    public List<Setting> getSettings(); // gets a list of all settings (metadata)
    public Map<String,String> getValues(); // gets a map with key-value pairs
}
</code>```

In order for the Config Window to be able to visually indicate whether a setting is dynamic or static, a list of Setting objects should exist

```<code>public interface Setting {
    public String getName();
    public String setName(String name);
    public String getTag();
    public String setTag(String tag);
    public boolean isDynamic();
}
</code>```

Body:
Given that your application needs that kind of complexity, then here are my 5 cents (I will use Java code):

Settings are split in two categories acording to whether or not they take immediate effect when they are altered.

dynamic: have an immediate effect in the application's behavior

static: don't have an immediate effect in the application's behavior and only take effect on application restart, or on config reload.

The scope of altering a setting can be:

memory

disk

memory and disk

I think the Configuration object should implement this interface:

import java.util.List;
import java.util.Map;

public interface Configuration {
    // key is the name of a setting
    public void reload(); // reloads from disk without restarting app
    public String getValue(String key); // gets value of setting identified by key
    public String getOldValue(String key); // gets old value of setting identified by key
    public String setValueToMemory(String key); // alters value of setting identified by
                                                // key only in memory (will be lost after reload or restart)
    public String setValueToMemoryAndDisk(String key); //alters value of setting identified by key
                                                       //both in memory and disk (will persist after reload or restart)
    public String isDirty(String key); // indicates whether or not this setting is "dirty",
                                       // meaning it's value is different from disk.
    public Setting getSetting(String key); // return setting metadata
    public void dump(); // prints all key-value pairs
    public List<Setting> getSettings(); // gets a list of all settings (metadata)
    public Map<String,String> getValues(); // gets a map with key-value pairs
}

In order for the Config Window to be able to visually indicate whether a setting is dynamic or static, a list of Setting objects should exist

public interface Setting {
    public String getName();
    public String setName(String name);
    public String getTag();
    public String setTag(String tag);
    public boolean isDynamic();
}


问:
Mutable AST vs. different immutable ASTs
I am writing a toy compiler. During the semantic passes, I want to add information to the AST. Which of the following is the best approach?

Define 1 mutable AST type whose fields are updated with each pass

Define multiple immutable ASTs, each of which are an input and output of a semantic pass

A mix of both?

答:
It depends on what information you want to add, if your AST is self contained well, how many passes you'll make where you modify the AST, and a handful of other conditions which may or may not matter for you.

In general, I would try to avoid modifying the AST. That can easily get you into the situation where your code needs to start caring what state the AST is in (is the added info missing, or just not added yet?). That sort of temporal coupling is troublesome in any software, along with the usual issues that accompany mutable state.

ContentLicense: CC BY-SA 3.0


问:
Is it okay to return the "wrong" HTTP status code in order to show a more user-friendly error page?
Located here, RFC 7231 is all about the HTTP protocol (status codes)

I'm developing an in-house web application for my university's department and I'm at a (probably unimportant) impasse.

I'm reducing users' access to resources based on role (student, faculty, staff) and have it working just fine. However, when a user attempts to access a resource and is denied access, the HTTP specification says that I should use a 403: Forbidden, marking that the user does not have access to the resource, or "hide" the resource by returning a 404: Not Found.

I could do that, but I want to make the site a bit more user-friendly and instead redirect them to their previous page with a flash (NOTE that I did not say 'Adobe Flash'; see comments) message instead of having a 403/4 page with links back to different parts of the site. I think it's a pretty UX-friendly feature.

However, that would involve redirecting via a 303: See Other, which more or less violates the standard.

Obviously it really doesn't matter as this is an in-house project for a lab at my university and nobody here is going to be complaining, but imagine this site were under the Google umbrella.

So, is it bad practice to deviate from the [HTTP] standard like this?

Edit: There seems to be a lot of confusion, so let me give an example:

User with id = 1 attempts to access mydomain.com/projects/2 through their profile (by clicking a link). User 1 is the owner of project 2, so the server accepts the requests and renders the page with the project.

User 1 then types mydomain.com/projects/3 into the URL. User 1 is not the owner of project 3. Therefore, when the request gets to the server, the server denies it.

Now, there are two options:

1.) The server redirects the user to /projects/2 (their previously visited page, which would of course always be a valid one) with a helpful notification at the top such as "Sorry, but you do not have permission to access XXXX" or

2.) The server renders a 403: Forbidden page, or a 404: Not Found page, which would probably have that same text (if it was a 403), and maybe even a JavaScript-enabled "back" link

Personally, the redirect seems way more user friendly to me, and eliminates seeing an unfriendly page like 403: Forbidden and having to click a "back" button. However, doing the redirect goes against the HTTP protocol standard.

答:
It sounds like your use case is:

When the user indicates they want to do XYZ, the browser sends a request to
  the server, which sends back a nice friendly reply page saying the user
  isn't allowed to do that.

In that case, from the HTTP server's point of view, the request isn't forbidden. You can have the server reply with status 200 without feeling guilty or thinking that you're deviating from anything.

Another common use case is:

When the user isn't allowed to do XYZ, the XYZ button in the browser
  is disabled (or alternatively, not shown at all.)

In that case, you still need to check permission at the server, because people can use F12 tools to enable the button, or synthesize the kind of request a more privileged user might do. In that situation, replying with a 403 is common.(Though you want to limit how much information you expose.)

I think it's worth mentioning that the permission model assumed by the HTTP spec is fairly simple. If the user is sometimes allowed to do XYZ and sometimes not, or if the logic for determining whether XYZ is allowed is complicated, then the use case I think you're doing (number 1 above) is perfectly sensible.

Update: (in response to updated question)

What I was trying to say above was that you should distinguish between (a) users who are trying to bypass your access controls and (b) users who generally have permission do to the sort of thing they're trying to do, but need to make an adjustment in order for the request to be permitted under the current circumstances. You should not do a friendly UX for group (a), in fact the less information you give them the better. Group (b) might need a friendly UX, if the permission rules are complicated and there might be a way for them to fix the request to make it permitted.

In your updated question you say:

User 1 then types mydomain.com/projects/3 into the URL. User 1 is not
  the owner of project 3. Therefore, when the request gets to the server,
  the server denies it.

The question I encourage you to ask yourself is, why does the server deny it? If the very existence of project 3 is a secret from user 1, then pretend it doesn't exist and return a 404. More likely (especially in an academic setting) they're allowed to know the name and owner of the project, so return them a page that has that information, but not everything the project owner gets. If they're not logged in, or their role doesn't provide access to any projects, then returning a 403 might makes sense for any URL starting with mydomain.com/projects/. But it's all about who's allowed to see what and why.

When the user chooses not to click one of the links you provided, and instead hovers over them to see the format, then types in a URL that sort of looks like those links to see what it does, your responsibility to give good UX has ended and the user is straying towards group (a).

On the flip side, if it's something they're allowed to see, you should have a better UX for it than expecting the user to guess the URL. For example, if one of the features of the site is the ability to join a project the user didn't create themselves, then the user needs an easy way to see projects they might want to join.


问:
Removing old (semantically versioned) NuGet packages
We are running into issues with our NuGet server when we reach 100 packages.

We have multiple packages, all semantically versioned (3 digits), from multiple projects, in our NuGet repository.

What is the best way to clean the older packages up without violating the NuGet packaging philosophy?

For now, we are considering a scheduled job that periodically parses the package file names, and keeps one of each minor revision (with the highest bugfix value), reasoning that this would be the version that most consumers of the package would want. We have also considered cleaning up all, but one of each major version (with the highest minor value). Are these sound approaches?

UPDATE: Due to working in a dysfunctional funding environment, development time, although more expensive than hardware, is more easily obtained, so while it may be cheaper to fix the server itself; experience in the environment tells us that the cleanup approach described above will be more easily accomplished than fixing the server.

答: We sidestepped the problem by replacing the Nuget server with a UNC folder share.</p>


答:
Don't be consumed by UX in these situations. A 403 or 404 code is extremely useful information to have. Some users may not understand it, but translating it into something else in a misguided attempt to make it user friendly is a bad idea. You need to show any 400 or 500 level error to users so the users can report them to you.

If a user gets a 404, that's a problem that needs to be fixed. If you are the help desk and someone calls in saying, "I clicked on a link and something weird happened and I got this strange message...," now you have to waste time trying to figure out what is going on. If they call in and say, "I got a 404 error...," now you know exactly what is happening, and you can respond much more quickly and precisely. Users should not see these errors often, so there is no need to pretty up the page or obscure the meaning.

You should also be logging 400 and 500 errors, too. Because sometimes users won't report the errors. Log them, and check the logs often. It can be shocking to see how many errors occur that you never hear about.

Title: Is it okay to return the "wrong" HTTP status code in order to show a more user-friendly error page?

Body:
Located here, RFC 7231 is all about the HTTP protocol (status codes)

I'm developing an in-house web application for my university's department and I'm at a (probably unimportant) impasse.

I'm reducing users' access to resources based on role (student, faculty, staff) and have it working just fine. However, when a user attempts to access a resource and is denied access, the HTTP specification says that I should use a 403: Forbidden, marking that the user does not have access to the resource, or "hide" the resource by returning a 404: Not Found.

I could do that, but I want to make the site a bit more user-friendly and instead redirect them to their previous page with a flash (NOTE that I did not say 'Adobe Flash'; see comments) message instead of having a 403/4 page with links back to different parts of the site. I think it's a pretty UX-friendly feature.

However, that would involve redirecting via a 303: See Other, which more or less violates the standard.

Obviously it really doesn't matter as this is an in-house project for a lab at my university and nobody here is going to be complaining, but imagine this site were under the Google umbrella.

So, is it bad practice to deviate from the [HTTP] standard like this?

Edit: There seems to be a lot of confusion, so let me give an example:

User with id = 1 attempts to access mydomain.com/projects/2 through their profile (by clicking a link). User 1 is the owner of project 2, so the server accepts the requests and renders the page with the project.

User 1 then types mydomain.com/projects/3 into the URL. User 1 is not the owner of project 3. Therefore, when the request gets to the server, the server denies it.

Now, there are two options:

1.) The server redirects the user to /projects/2 (their previously visited page, which would of course always be a valid one) with a helpful notification at the top such as "Sorry, but you do not have permission to access XXXX" or

2.) The server renders a 403: Forbidden page, or a 404: Not Found page, which would probably have that same text (if it was a 403), and maybe even a JavaScript-enabled "back" link

Personally, the redirect seems way more user friendly to me, and eliminates seeing an unfriendly page like 403: Forbidden and having to click a "back" button. However, doing the redirect goes against the HTTP protocol standard.


答:
Syntax trees should be immutable. Otherwise, they are clearly a lie.

The syntax tree represents the syntactic input of the user- so unless you're going to go and mutate their source code text, it's a complete non-starter to mutate the tree.

If the semantic passes need to work with a tree, they need their own semantic tree. Arbitrarily re-using a completely different tree that has a completely different purpose and fundamental meaning is a bad plan.

Semantic trees aren't really trees at all anyway, it's trivial to produce programs with e.g. recursive functions that are graphs, whereas syntax trees actually are trees.

Title: Mutable AST vs. different immutable ASTs

Body:
I am writing a toy compiler. During the semantic passes, I want to add information to the AST. Which of the following is the best approach?

Define 1 mutable AST type whose fields are updated with each pass

Define multiple immutable ASTs, each of which are an input and output of a semantic pass

A mix of both?


问:
Are Git branches, in fact, "homeomorphic endofunctors mapping submanifolds of a Hilbert space"?
As we all know:

Git gets easier once you understand branches are homeomorphic endofunctors mapping submanifolds of a Hilbert space

Which seems like jargon, but on the other hand,

All told, a monad in X is just a monoid in the category of endofunctors of X, with product × replaced by composition of endofunctors and unit set by the identity endofunctor.

is funny because it is true.

Can I avoid merging mistakes by reading this simple text?

答:
It's a joke, as confirmed by the author and Jörg W Mittag's answer explains in more detail.

But truth can be stranger than fiction…

There has been work of formalizing version control, in particular patch theory by David Roundy which is the basis of Darcs (a distributed version control system that preceded the more popular Bazaar, Git and Mercurial by a couple of years but never reached their popularity). The main objective of the theory is to model merging and, in particular, conflict resolution. The Darcs wiki has an introduction to the theory and a few pointers as well as a bibliography (unmaintained so outdated if you want a recent view on the subject, but it does list a 2009 survey paper by Petr Baudiš) and a list of talks (which includes more recent material). There's also a wikibook. One seminal paper is A Principled Approach to Version Control by Andres Löh, Wouter Swierstra and Daan Leijen3.

Patch theory does lead to a categorical model, which has been more recently explored in A Categorical Theory of Patches by Samuel Mimram and Cinzia Di Giusto and Homotopical Patch Theory by Carlo Angiuli, Ed Morehouse, Daniel R. Licata and Robert Harper. In Mimram and Di Giusto's work, the model has files as objects and patches as morphisms. I think that makes merging a branch a functor — an endofunctor if you're working in a single repository. “Homeomorphic endofunctor” doesn't make sense to me. And with homotopy theory involved (a concept from calculus — that's the branch of mathematics that studies things like manifolds and Hilbert spaces — which has recently been applied to a fundamental model of mathematics called homotopy type theory), submanifolds of a Hilbert space might not be so far out...


问:
Where to master HTML, CSS and Javascript?

Possible Duplicate:

  What should a developer know before building a public web site?

I gotten interested in web-development lately. I am still a student. I learnt basics of HTML, CSS and JavaScript. Then I thought I should improve my server side scripting. So I am learning Struts2 and I am doing better there. Now I have decided I should finally put my skill to some use.

So my friend and I have decided to come up with a fun website for our class. But now I am realizing that, though I know server-side scripting to a good extent (not great, just good considering I am a beginner), I am nowhere near good in the basic elements viz. HTML, CSS and JavaScript. I mean, I can't do cool stuff with it.

I am aware of w3schools, but it would be great if you can point out a more intuitive place where I can learn to do all the cool stuff in a short time.

Some of the problems I am facing are:

1) How should I design the basic layout of my website?

2) How can I use 3rd party APIs like that of Facebook graph?

答:
How should I design the basic layout
  of my website?

Consider using a CSS template like the ones here to build your website.  You can always take the template apart to see how it works.

How can I use 3rd party APIs like that
  of Facebook graph?

Facebook Graph is a REST API.  You hand it a prefabricated URL, and it returns a result to you in JSON.  There is a JavaScript SDK for Facebook that you can use to access Facebook data using the Facebook Graph API.

ContentLicense: CC BY-SA 2.5


问:
For DI, where to create dependencies (new objects) specifically within framework code?

Basic requirement

I'm making a framework for learning purposes (and likely usage on personal sites).

I'm using dependency injection in classes and I'm trying to design where would be a good place to instantiate dependency objects.

Note: This is in the framework, not front end (so not templates etc).

So when a class has a dependency from another class or a configuration file (config files are classes), I need to instantiate the dependency object somewhere to be able to pass it into the new class (DI).

I've managed to create logical places for all other things within the framework, but cannot seem to work out and design a logical and purposeful place to instantiate dependency objects.

Framework structure

The basic structure of my framework is:

htaccess sends all requests to index.php

index.php includes() bootstrap.php

bootstrap.php loads all framework components

"Components" are things like SPL Autoload Register, setting up error display with ini_set(), other things.

All these components are in separate files and are called by bootstrap.php.

There are a number of system components, but bootstrap.php loads much more, a lot of which will require a dependency injecting in. So this is not a pointless exercise for little return.

Currently doing this in bootstrap.php

I'm currently instantiating the dependency objects in bootstrap.php prior to instantiating the new system class. However I feel this is making bootstrap.php a bit messy, cluttered, and such things should perhaps live else where (e.g. in a dependency layer, and dependency namespace, not bootstrap namespace).

Example

Example of a system class with dependencies in bootstrap.php, it's a class which manages if errors are displayed or not:

(Class autoloading is on.)

bootstrap.php:

```<code>// Get the dependency from config file
$errorConfig = new errorConfig();
$dependency = $errorConfig->getErrorConfig();

// Instantiate system file, injecting config dependency from above
$displayErrors = new displayErrors();
$run = $displayErrors->runDisplayErrors($dependency);
</code>```

displayErrors.php:

```<code>class displayErrors {

  public function runDisplayErrors($dependency) {
    ini_set('display_errors', $dependency);
  }

}
</code>```

So $dependency in this case will be a value from the config file of either "on" or "off".

config.php:

```<code>class errorConfig {

  public function getErrorConfig() {
    return "on";
  }

}
</code>```

So in bootstrap.php I am instantiating the class which holds the dependency (such as a config class), calling the dependency class method to get the dependency, and passing the object into the class which requires the dependency.

NOTE: The way I am actually retrieving the config data is being worked on, that is irrelevant here as it will be an object, and I'm asking about where to instantiate the config class to get the object, not how.

Doing it this way means bootstrap.php is full of dependencies, and this is not what bootstrap.php should be for (based on my opinion and design ideas, I could be wrong).

bootstrap.php is a loader file which is just for loading the systems (ie setting up error display), and not for instantiating and managing dependencies.

Dependency injection container

I could use a dependency injection container (DIC) (and I am reading about the advantages etc) but as far as my current knowledge of DIC shows, this does not resolve where to instantiate the dependency objects.

A DIC would just move the issue around, and I'd just be instantiating the DIC within bootstrap.php instead of the dependency class directly.

My questions

In terms of application architecture and design, where would it be good to instantiate dependency objects, or even a DIC, to keep things clean, organised, and tidy?

Do I need to add some layer which bootstrap.php calls once and then dependency objects are instantiated within that layer?

If you feel instantiating the dependency objects within bootstrap.php is ok, please let me know. I'd be interested in another view on this. Personally, I'm against it as it makes bootstrap.php smell, and bends its purpose.

答:
Most dependency injection containers can be configured to create the dependencies as well as inject them.  No need to have a separate process to create dependencies.

Here is a simple example using the PHP Pimple container(http://pimple.sensiolabs.org/)

```<code>// This is the importer service definition
$dic['arbiter_schedule_importer_games_with_slots_xml'] = function() use ($dic) {
  return new ImporterGamesWithSlotsXml(
    $dic['arbiter_db_conn']
  );
};
// This is the import command definition
$dic['arbiter_schedule_import_command'] = function() use ($dic) {
  return new ImportCommand(
    $dic['arbiter_schedule_importer_games_with_slots_xml']
  );

// This creates the command and creates/injects the importer service dependency.
$importCommand = $dic->get('arbiter_schedule_import_command');
</code>```

And yes, you do have to create and configure the container somewhere but that should be it as far as bootstrapping goes.

Body:
Most dependency injection containers can be configured to create the dependencies as well as inject them.  No need to have a separate process to create dependencies.

Here is a simple example using the PHP Pimple container(http://pimple.sensiolabs.org/)

// This is the importer service definition
$dic['arbiter_schedule_importer_games_with_slots_xml'] = function() use ($dic) {
  return new ImporterGamesWithSlotsXml(
    $dic['arbiter_db_conn']
  );
};
// This is the import command definition
$dic['arbiter_schedule_import_command'] = function() use ($dic) {
  return new ImportCommand(
    $dic['arbiter_schedule_importer_games_with_slots_xml']
  );

// This creates the command and creates/injects the importer service dependency.
$importCommand = $dic->get('arbiter_schedule_import_command');

And yes, you do have to create and configure the container somewhere but that should be it as far as bootstrapping goes.


问:
Is there any reason to use C++ instead of C, Perl, Python, etc.?
As a Linux (server side) developer, I don't know where and why should I use C++.

When I'm going for performance, the first and last choice is C.

When "performance" isn't the main issue, programming languages like Perl and Python would be good choices.

Almost all open source applications I know in this area have been written in C, Perl, Python, Bash script, AWK or even PHP, but no one uses C++.

I'm not discussing other areas like GUI or web applications, I'm just talking about Linux, CLI and daemons.

Is there any satisfactory reason to use C++?

答:
There's actually a single answer to all questions formed like this. The best reason to use tech X instead of tech Y (where X and Y are roughly on the same level [like just about all contemporary programming languages are]) is because you already know X and don't know Y.

(but after Haskell arrived, there has been no reason to use anything else)


问:
Is there a need to keep tests for simple (self-contained) functions?
Consider this:

```<code>public function polynominal($a, $b, $c, $d)
{
    return  $a * pow($x, 3) + $b * pow($x, 2) + $c * $x + $d;
}
</code>```

Suppose you write various tests for the above function and prove to yourself and others that "it works".

Why not then remove those tests, and live happily ever after?  My points is that some functions do not need to be tested continuously after they have been proven to work.  I am looking for counter-points that state, yes these functions still need to be tested, because: ...   Or that yes, these do not need to be tested...

答:
Developer Documentation

How do I (as another developer) know that this has been tested?

If I want to fix a bug in the self contained function, how do I know that I am not introducing a bug that you had already considered?

Complexity indicator: # of tests can be a good measure of how complex something is.  This may indicate that you shouldn't touch it because it is mature and stable or that it is bloated and coupled.

User Documentation

Pending poor doc, I can look and see if {zero, negative values, empty sets, etc} are accepted and what the expected return value is.

It also gives a good example of how I should use the object/function


问:
matching usernames with their password
We are working on a simple login/registration form. Our login script checks to see if the username and password exist in the same row of the database. If it does exist, we bring the user to a welcome page.

However, our problem lies when we check to see if the password exists in the database because we have applied the password_hash() function to the user submitted password. This encryption method is one-way and not reversible (to my knowledge). Here is the code for the login script:

```<code><?php
//will correspond with 'loginLogin.html page
require("opendboLogin.php");
$user = $_POST['username'];
$password = $_POST['password'];

$stmt2 = $conn->stmt_init();
$stmt2 = $conn->prepare("SELECT * FROM login WHERE alogin = ? AND apassword = ?");
$stmt2->bind_param("ss", $user, $password);
$stmt2->execute();
$stmt2->store_result();
$numberofrows = $stmt2->num_rows; //this is an integer!!
$stmt2 -> close();

if($numberofrows > 0) //if username and password combination exists in a row
{
    echo 'login successful!';
}
else
{
    echo 'Incorrect username and/or password, dumbass!';
}
?>
</code>```

I was thinking perhaps we could encrypt the password AGAIN inside this script and see if the two hashes match, however the encryption changes each time regardless of whether the same exact password was hashed!

As of right now the username/password combination will never exist and will always hit the last "else" statement. Any ideas how to check for the correct username/password combination?

答:
Typically I'd just search the table for the record that contains the matching username. If that record doesn't exist the user doesn't exist so there is no need to go any further.

If the record does exist that record would have the password hash on it for that user. Take the password given by the user, hash it in the same way, compare to the hash in your record.

Title: matching usernames with their password


答:
Attempt to fetch the user record based on the username (but use LIKE instead of = so that case doesn't matter. Usernames should not be case sensitive.

If you managed to fetch a user record (then the user exists) and you can compare the passwords to validate the login.

About password security

Store the passwords using a function like password_hash() so that they're far more secure than being stored plain text (a huge no-no). This will generate unique salt each time so yes the hash will be different each time. Don't worry about that.

To validate the password the user is logging in with against the stored password, use password_verify() and pass it the password they posted and the stored hash from the database. The function will take care of the salt and comparison. This is the function that I think you might've missed when reading about password hashing.

Bonus

After successful login you should check to see if the password needs re-hashed (over time the "cost" of the algorithms are updated). Simply pass the stored hash to password_needs_rehash() to see if you should re-hash and re-save the password.

Title: matching usernames with their password

Body:
We are working on a simple login/registration form. Our login script checks to see if the username and password exist in the same row of the database. If it does exist, we bring the user to a welcome page.

However, our problem lies when we check to see if the password exists in the database because we have applied the password_hash() function to the user submitted password. This encryption method is one-way and not reversible (to my knowledge). Here is the code for the login script:

```<code><?php
//will correspond with 'loginLogin.html page
require("opendboLogin.php");
$user = $_POST['username'];
$password = $_POST['password'];

$stmt2 = $conn->stmt_init();
$stmt2 = $conn->prepare("SELECT * FROM login WHERE alogin = ? AND apassword = ?");
$stmt2->bind_param("ss", $user, $password);
$stmt2->execute();
$stmt2->store_result();
$numberofrows = $stmt2->num_rows; //this is an integer!!
$stmt2 -> close();

if($numberofrows > 0) //if username and password combination exists in a row
{
    echo 'login successful!';
}
else
{
    echo 'Incorrect username and/or password, dumbass!';
}
?>
</code>```

I was thinking perhaps we could encrypt the password AGAIN inside this script and see if the two hashes match, however the encryption changes each time regardless of whether the same exact password was hashed!

As of right now the username/password combination will never exist and will always hit the last "else" statement. Any ideas how to check for the correct username/password combination?


问:
Merging from unfinished feature branches and code review
We are using the git flow workflow, and it sometimes happens that we have long-lived feature branches. Of course we can merge from the develop branch into our feature branch, when another feature branch gets finished and merged to the develop branch. However, is it a good idea to merge directly from other feature branches, i.e. before they have been finished? Won't that create code review duplication and potential conflicts, because reviewers could end up reviewing the same commit(s) multiple times, potentially with diametrically opposing comments from different reviewers if the change is controversial, without anyone realising? Or, the same logical change could diverge in the two feature branches, and then become two slightly different changes.

Ideally we want our stories to be independent, but even if they are theoretically independent, there is often some partial changes such as low-level refactoring and fixup work in one branch that we might want to reuse in another branch.

What do you suggest we do in such a situation? Manually copying and pasting changes doesn't seem to help, it seems to in fact merely hide the problem. Sure, we can try to avoid this problem by giving more priority to code review and demos, trying to make stories smaller, etc., but I think this problem will still occur from time to time.

答:
This is a common problems with all source control systems. It is a communication problem, perhaps made worse by the ease with which extensive changes can be made globally. You have outlined the most common solutions:

Make the work done in a feature branch smaller, so that it is easier to integrate, and compare to the main branch.

Make it a priority to integrate feature branches as soon as possible. Don't allow branches to become stale.

Some other ideas:

Don't allow "low-level refactoring and fixup work" in any branch except one, the most important branch.

When you compare changes in a feature, only compare against the original source it was branched from. You may have to re-do the work to integrate.

Anyone who is going to do extensive global changes must communicate with all other people working on all other branches. Try to get all branches merged before these types of changes are made. Put a freeze on further branching until it is completed.


问:
How do I write tests against an eventually consistent service?
I'm building a service on top of Google App Engine Datastore, which is an eventually consistent data store. For my application, this is fine.

However, I'm developing tests that do things like PUT object and then GET object and checking properties on the returned object. Unfortunately, because the datastore is eventually consistent, these simple tests aren't reproducible.

How do you test an eventually consistent service?

答:
Use one of the following:

After PUT, retry GET N times until success. Fail if no success after N tries.

Sleep between PUT and GET

Unfortunately, you have to pick magic values (N or sleep duration) for both of these techniques.

ContentLicense: CC BY-SA 4.0


问:
Polymorphic template container: shared_ptr vs reference_wrapper
Assuming we have two classes:

```<code>class A
{
    ...
}
class B : public A
{
    ...
}
</code>```

Would it be better to write

```<code>std::deque<shared_ptr<A> > container;
</code>```

or

```<code>std::deque<reference_wrapper<A> > container;
</code>```

to create a container which is able to contain references to both of these classes and why?

In my case, the class containing the container wouldn't care, if a reference somehow became invalid.

However are there any caveats to take into account, when choosing one approach over the other?

答:
It's mostly a question of lifetime and ownership.  A container using reference_wrapper doesn't own its objects or manage their lifetime, a container using shared_ptr does.

If your container shouldn't own its objects, then use reference_wrapper.

If it should own its objects, then I'd take a third option. Boost.Pointer Container has template classes such as boost::ptr_deque that store polymorphic types and manage ownership themselves, without the overhead of shared_ptr or the awkward syntax of having to dereference shared_ptr for each element.


问:
Where does authorization fit in a layered architecture?
Typically, I place authorization decisions in my server side controllers.  These have been RESTful endpoints recently, but I think the same stands for MVC type architectures.  For the sake of argument assume that it's role based authorisation.  A protected method will be annotated or make checks and return 403s if necessary.

Now, given that authorisation is in fact a business rule - "only administrators can list X" for example, I'm thinking they should be pushed down a layer.  When a controller asks the business layer to perform the operation, the service or business layer informs the controller it's not authorised.

Is this a reasonable approach?  Are there disadvantages to this?

I'm loathe to have an AuthorisationService that essentially holds a bunch of static procedural coded rules to do this but maybe it makes sense to keep all access logic in one place. Is it a cross cutting concern that should be kept separate?

So I'm asking if anyone has done this and how they achieved it in a clean way or if there are any good resources I could read.  I'm using Java fwiw but this is a language agnostic question.

I've checked out the related questions on here and they're very thin on the ground and answers.  For example: Validation and Authorisation in Domain Models and Carrying that through a Service Layer to MVC

I'm reading the spring security docs which make some good arguments for it being a cross cutting concern, but I'm worried it's just the "spring way" and would like wider perspectives.  It also ties your application to a specific framework.

答:
I like pushing authorization checks down as low as they can go! (But no further!)

You're still free to write automated authorization tests against layers "above" this. And some rules may only be applicable or make sense in higher layers like your service layer (CanView/CanSerialize?). But, I generally think the safest authorization strategy is also "DRY-est" strategy: Keep authorization as low as possible, in the most "common" or "shared" code as you can (without over-complicating the auth rules).

Think about the alternative. If your authorization rules are tested and enforced only in the service layer, leaving your poor domain objects to bend to the wills of a moody service objects, you'll often be required to enforce each individual rule more than once, in multiple objects and multiple places in each object, and in more complicated code.

Furthermore, when your analytics team hires a consulting firm to write reporting services using your domain objects, you don't want to have to trust those developers! (Or whatever. You build additional services or calls over the same objects for any reason.) You won't want to crack open the big book of business rules and hope to enforce those rules properly again; you want your domain to already know them and enforce them.


问:
Design periodic batch notification system
Problem:

I am trying to design a system which takes requests from customers in
real time and log them in a database. For example - request to
purchase an item.

The customer then gets a unique request-ids for his request and also
is asked to wait for 'X' days because the request is being processed.

Then the system notifies the item providers by batching all these
requests in one single email periodically (lets say 4 hours).

Item providers update items in their repository and publish them to
customers.  And then customer gets a notification that item providers
have responded for his request.

Design:

I'm thinking of using a workflow based system for this use case. With
  following components (high level) -

```<code>Synchronous API:
 - Receive request from customer.
 - Record the request in the database.
 - Also start an asynchronous workflow, return request id as a response.
</code>```

Workflow does the following :

```<code>Workflow Step 1:
 - Get the list of item providers
 - Notify them

Workflow Step 2: (This workflow steps gets executed after "X" days)
 - Send a response email back to the customer
</code>```

But I'm having hard time to support the batching use-case. Is there
  any way I can efficiently batch the customer requests and send
  notification every 4 hours without having to write a cron job
  separately?

I'd appreciate any suggestions/help on this.

答:
Your design seems that it can benefit from Asynchronous Messaging

Messages can be sent through different pipelines to multiple receiving applications and scheduled for execution at certain time (the scheduling can be a built-in feature of the message bus (middle-ware) or can be baked in your solution (reply with with a shceudled task id message and send the task off to a different application to be executed later)

Batching can happen within this architecture as a gateway app that collected messages with certain property values, group them together, and then send them as a different message (the batch message) every certain time frame.

Now I know that what I explained here is very abstract, but bear in mind also that explaining the whole architecture here wouldn't be practical either.

I hope that this answer could push you towards reading more about the architecture pattern for Messaging, and I'd be happy to answer other more specific questions later.


问:
Persisting Large/Complex Entities with the Command Pattern -- Am I doing it right?
I am in the process of designing and building a large-scale inventory management software-as-a-service that will, hopefully, live a long and fruitful life. Therefore I am exerting a lot of effort up-front to ensure the application will be maintainable and horizontally scabale. I really enjoyed this talk by Mathias Verraes on decoupling which inspired to try out the Command Pattern as it lends itself to highly decoupled and very explicit code.

In terms of technology, I'm using Laravel 5 and Doctrine 2 backed by a MySQL database.

Although Mathias speaks on the subject of "getting out of the CRUD mindset", I think we can all agree that many situations exist where the business language does in fact reflect CRUD. For example, the logistics manager says "I need to CREATE a Purchase Order which I will then SUBMIT to the Supplier". The "SUBMIT" portion lights up as a great use-case for a Command, but not so much the CREATE part.

Let me explain my position in hopes someone can agree/disagree and maybe point me in a better direction.

I feel as though the Command Pattern is not particularly well-suited for the act of handling a CREATE request for a complex object, like a Purchase Order. In my domain, the Purchase Order holds information such as:

User-defined Order Number / Identifier (e.g., PO1234)

Supplier for which the Order will be submitted to

The Ship To Address

The Bill To Address

The Requested Shipping Method and Courier

NET Terms

The Monetary Currency

A Sale Order and Customer if the order is to be Drop Shipped

One or more Line Items

If I understand correctly, the Command Object should essentially be a relatively simple DTO that provides a contract to the outside world to interact with the application. "If you want to CREATE a new Purchase Order, populate this object with data and send it down the bus". As a developer, it is beautifully explicit to issue a CreatePurchaseOrderCommand to the application-- I like how that sounds, but when it comes to execution it just feels clumsy.

By clumsy, I mean it seems awkward to extrapolate all of the above data from the Request object and new-up a CreatePurchaseOrderCommand with no fewer than 9 arguments, some of which would be arrays, maybe a ValueObject or two (or would that introduce coupling??).

I've mocked up some code that looks like this:

EDIT I've updated the OrderController to reflect my needs of outputting a JSON encoded object after a successful CREATE in order to satisfy the needs of my client-side framework. Is this considered a good approach? I have no issue with injecting the repository into the Controller as it will almost certainly be needed for other read methods.

OrderController.php

```<code>public function __construct(ValidatingCommandBus $commandBus, OrderRepositoryInterface $repository) { .. }
public function create(CreateOrderRequest $request){
     $uuid = UUID::generate();
     $command = new CreatePurchaseOrderCommand($uuid, $request->all());

     try
     {
         $this->commandBus->execute($command);
         $order = $this->repository->findByUuid($uuid);
         return $this->response()->json([
             'success' => true,
             'data'    => $order->jsonSerialize()
         ]);
     }catch(OrderValidationException $e)
     {
         return $this->response()->json([
             'success' => false,
             'message' => $e->getMessage()
         ]);
     }
}
</code>```

ValidatingCommandBus.php (decorates BaseCommandBus)

```<code>public function __construct(BaseCommandBus $baseCommandBus, IoC $container, CommandTranslator $translator) { .. }
public function execute(Command $command){
    // string manipulation to CreatePurchaseOrderValidator
    $validator = $this->translator->toValidator($command);

    // build validator class from IOC container
    // validates the command's data, might throw exception
    // does *not* validate set constraints e.g., uniqueness of order number
    // this is answering "does this look like a valid command?"
    $this->container->make($validator)->validate($command)

    // pass off to the base command bus to execute
    // invokes CreatePurchaseOrderCommandHandler->handle($command)
    $this->baseCommandBus->execute($command)
}
</code>```

CreatePurchaseOrderCommandHandler.php

```<code>public function __construct(PurchaseOrderBuilderService $builder, PurchaseOrderRepositoryInterface $repository){ .. }
public function handle(CreatePurchaseOrderCommand $command){

    // this again? i'm pulling the same data as I pulled from the
    // Request object back in the Controller, now I'm just getting
    // the same data out of the Command object. Seems repetitive...
    $order = $this->builder->build([
       $command->order_number,
       $command->supplier_id,
    ]);

    // now maybe I should handle set constraints?
    // ensure order number is unique, order is not stale... etc.
    $orderNumberIsUnique = new OrderNumberIsUniqueSpecification($this->repository);
    if ( ! $orderNumberIsUnique->isSatisfiedBy($order) ){
        throw new \ValidationException("The Order Number is not unique");
    }

    // ok now I can persist the entity...
    try
    {
        // start a transaction
        $this->repository->persist($order);
    }catch(SomeDbException $e)
    {
        // roll back transaction
        // cant return anything so i'll throw another exception?
        throw new ErrorException('Something went wrong', $e);
    }

    // no return here as that breaks the CommandBus pattern :|
}
</code>```

From a code perspective I think that seems like the logical way to go about things in terms of placement of validation and such. But, at the end of the day, it doesn't feel like the right solution.

I also don't like that I can't return a value from the Command Bus which leaves me with the choice of switching to generating a UUID before persisting (currently relying on AUTO INC from MySQL) or performing a lookup on the other unique identifier (the order number) which may not work for all entities (i.e., not every entity/aggregate will have some other form of unique identifier besides the database ID).

Am I using and understanding the Command Pattern correctly? Are my concerns valid (see comments in code examples). Am I missing something about the Command Pattern? Any input would be great!!

答:
In my app, the logic flow goes

Controller builds DTO

Controller dispatches to Command Bus

Command Bus Calls Events

Event Handlers dispatch to the Command Bus as well

Command Handler returns a response DTO to the controller

Controller generates a response to the client based on the response

Your application seems similar. Decoupling is also an issue for me. However, the problem of chaining (or nesting) commands or events hasn't been an issue. Keep a list of generated UUIDs and associated objects in every command chain, if possible.


答: Have look on Head First Web Design.</p>

Title: Where to master HTML, CSS and Javascript?

Body:
Possible Duplicate:

  What should a developer know before building a public web site?

I gotten interested in web-development lately. I am still a student. I learnt basics of HTML, CSS and JavaScript. Then I thought I should improve my server side scripting. So I am learning Struts2 and I am doing better there. Now I have decided I should finally put my skill to some use.

So my friend and I have decided to come up with a fun website for our class. But now I am realizing that, though I know server-side scripting to a good extent (not great, just good considering I am a beginner), I am nowhere near good in the basic elements viz. HTML, CSS and JavaScript. I mean, I can't do cool stuff with it.

I am aware of w3schools, but it would be great if you can point out a more intuitive place where I can learn to do all the cool stuff in a short time.

Some of the problems I am facing are:

1) How should I design the basic layout of my website?

2) How can I use 3rd party APIs like that of Facebook graph?

Body: Have look on Head First Web Design.


问:
Should I use nhibernate for a one row settings table
I am using nhibernate in a quite big project.

The system has a settings table which has 10 columns and one row, there is always a row and it should not be deleted only modified.
Concurrency can be a problem as many clients can increment columns in the table like LastReceiptId.

I'm thinking, it can't be a good idea to use nhibernate to solve this.

With raw sql I can use a transaction and lock the table with for example: With (TABLOCKX, HOLDLOCK) while I select and update the LastReceiptId.

Do you have any reasons to use or not use nhibernate in a situation like this?

答:
Your post gives me the (maybe false?) impression that you are questioning the use of NHibernate in full, because of a minor problem which cannot be perfectly solved by an ORM directly. Actually, in such a situation I would try to create a workaround for the minor problem (maybe I got you wrong, and that is what you already have in mind).

For the case you described, I am pretty sure some additional stored procedures can be utilized for solving your problem (assumed you are using a database system with full stored procedure support). For example, if you need custom INSERT operations with specific handling of IDs and/or locking, encapsulate the operation in a stored procedure and combine it with NHibernate like shown here. I am not an expert on NHibernate, but you will find more information on combining it with stored procedures on Stackoverflow.


答:
The question is one of ownership

You make no mention of who owns the objects going into the container. Since the shared_ptr is an option, there is probably some form of shared ownership and dynamic storage allocation. A clear definition of who owns the objects and how they are observed (i.e. who can observe them) will frame much of the implementation.

In my specific case, the class containing the container actually wouldn't care if a reference somehow became invalid.

The container is playing an observer role.

However there might be a more generalised answer and a 'rule of thumb', when one should use one approach over the other.

Given the semantics of the the reference_wrapper there is a reasonable expectation that the object being referred to is valid whilst the reference_wrapper is valid. In your case this may not apply, but in general this is true and any maintenance done on the code at a later date may well assume this.

Rule of thumb

Allow the lifetime of the shared ownership objects to be managed with a std::shared_ptr and use the "observer" std::weak_ptr in the container.

If the lifetime of the objects is not shared and somehow tied to the lifetime of container itself (via automatic storage duration), then the reference_wrapper is viable (in a similar way it could even be a raw pointer).

Title: Polymorphic template container: shared_ptr vs reference_wrapper

Body:
Assuming we have two classes:

```<code>class A
{
    ...
}
class B : public A
{
    ...
}
</code>```

Would it be better to write

```<code>std::deque<shared_ptr<A> > container;
</code>```

or

```<code>std::deque<reference_wrapper<A> > container;
</code>```

to create a container which is able to contain references to both of these classes and why?

In my case, the class containing the container wouldn't care, if a reference somehow became invalid.

However are there any caveats to take into account, when choosing one approach over the other?


问:
Purpose of encrypted product ID/key in shopping carts
I'm a newbie for PHP ecommerce applications. For my academic activities, I need to complete a shopping cart system with basic shopping cart functions. I have studied several apps which are already developed. I noticed that most of them are using encrypted product ids. I mean they are not just plain numbers. As I think the purpose is to make it ambiguous for those who see it and think about some malicious activity. Not related with the security directly.

I know this is not suitable question for SO. I do not want any source code. Can anyone please answer to give me some light in this area?

Update
I might be wrong definitely. Should be a hash there. Please find this example product edit url. I really meant such a thing.

```<code>example.com/product/dc85058a-a69e-11e5-e112-44da4901619b/edit
</code>```

答:
This is the GUID format. Please find the sequence of 32 hex digits grouped into chunks of 8-4-4-4-12. This proves your url consists a GUID.
Read More about GUID here.

If you are going to use GUIDs as your product identifiers, please research about it. There are debates over performance issues.
No one is going to encrypt their id fields.


问:
Unit Testing without DI
I am starting a small ASP.NET MVC project, each task on the board must come with unit tests. The project is small, just a few pages with not that much processing, so I decided not to implement DI. My thoughts being DI is for larger projects with dependency graphs.

However, now I am writing tests it has made me realise testing is more difficult. There is no constructor injection going on, so mocking these objects being used by the controller actions is proving troublesome.

If there are objects being instantiated on the action due to lack of contructor injection how can you mock them to test?

答:
If there are objects being instantiated on the action due to lack of contructor injection how can you mock them to test?

You can refactor your code to encapsulate all code that should be mocked away into a
seperate protected methods and then use partial-mocks to replace that logic.

Example (in java)

Original

```<code>protected void moveFiles(File[] destFiles, File[] sourceFiles) {
    int pos = 0;
    while (pos < fileCount) {
        File sourceFile = sourceFiles[pos];
        File destFile = destFiles[pos];

        // do some processing. i.e. rename destFile if it already exists.

        // do the copy. the test should not execute this
        sourceFile.renameTo(destFile)
        pos++;
    }
}
</code>```

refactored:

```<code>protected void moveFiles(File[] destFiles, File[] sourceFiles) {
    int pos = 0;
    while (pos < fileCount) {
        File sourceFile = sourceFiles[pos];
        File destFile = destFiles[pos];

        // do some processing. i.e. rename destFile if it already exists.
        osFileMove(destFile, sourceFile);
        pos++;
    }
}

/** can be replaced by mock/stub in unittests */
protected boolean osFileMove(File destFile, File sourceFile) {
    return sourceFile.renameTo(destFile);
}
</code>```

in the test you can replace osFileMove with a fake (example uses java  org.mockito.Mockito)

```<code>import static org.mockito.Mockito.*;

FileCommands sut;
@Before
public void setup() {
    sut = spy(new FileCommands());
    doReturn(true).when(sut).osCreateDirIfNeccessary(any(File.class));
    doReturn(true).when(sut).osFileCopy(any(File.class), any(File.class));
    doReturn(true).when(sut).osFileMove(any(File.class), any(File.class));
    doReturn(true).when(sut).osDeleteFile(any(File.class));
}
</code>```

If you later decide to use ioc you can move the os-spcific file operations osxXXXX into a seperate class plus an interface

Title: Unit Testing without DI

Body:
If there are objects being instantiated on the action due to lack of contructor injection how can you mock them to test?

You can refactor your code to encapsulate all code that should be mocked away into a
seperate protected methods and then use partial-mocks to replace that logic.

Example (in java)

Original

protected void moveFiles(File[] destFiles, File[] sourceFiles) {
    int pos = 0;
    while (pos < fileCount) {
        File sourceFile = sourceFiles[pos];
        File destFile = destFiles[pos];

        // do some processing. i.e. rename destFile if it already exists.

        // do the copy. the test should not execute this
        sourceFile.renameTo(destFile)
        pos++;
    }
}

refactored:

protected void moveFiles(File[] destFiles, File[] sourceFiles) {
    int pos = 0;
    while (pos < fileCount) {
        File sourceFile = sourceFiles[pos];
        File destFile = destFiles[pos];

        // do some processing. i.e. rename destFile if it already exists.
        osFileMove(destFile, sourceFile);
        pos++;
    }
}

/** can be replaced by mock/stub in unittests */
protected boolean osFileMove(File destFile, File sourceFile) {
    return sourceFile.renameTo(destFile);
}

in the test you can replace osFileMove with a fake (example uses java  org.mockito.Mockito)

import static org.mockito.Mockito.*;

FileCommands sut;
@Before
public void setup() {
    sut = spy(new FileCommands());
    doReturn(true).when(sut).osCreateDirIfNeccessary(any(File.class));
    doReturn(true).when(sut).osFileCopy(any(File.class), any(File.class));
    doReturn(true).when(sut).osFileMove(any(File.class), any(File.class));
    doReturn(true).when(sut).osDeleteFile(any(File.class));
}

If you later decide to use ioc you can move the os-spcific file operations osxXXXX into a seperate class plus an interface


答:
Here's a question: does this look like DI?

```<code>public class MyCar
{
    private IEngine _engine;

    public MyCar(IEngine engine)
    {
        _engine = engine;
    }

    public MyCar()
        : this(new MyV8Engine())
    {

    }
}
</code>```

It should, because it IS DI. Dependency Injection is about injecting a dependency into an object, instead of placing the burden of new'ing up or finding the dependency on the object that requires it. DI is not about using a framework, it is a design pattern that solves an issue.

It is very valid for small applications to use constructor-based injection and new'ing up objects in default constructors. The reason you don't see this as an example of DI is because often times your dependency graph quickly becomes very big and unwieldy and the move to a DI framework rapidly becomes advantageous as your application grows.

Title: Unit Testing without DI

Body:
I am starting a small ASP.NET MVC project, each task on the board must come with unit tests. The project is small, just a few pages with not that much processing, so I decided not to implement DI. My thoughts being DI is for larger projects with dependency graphs.

However, now I am writing tests it has made me realise testing is more difficult. There is no constructor injection going on, so mocking these objects being used by the controller actions is proving troublesome.

If there are objects being instantiated on the action due to lack of contructor injection how can you mock them to test?

Body:
Here's a question: does this look like DI?

public class MyCar
{
    private IEngine _engine;

    public MyCar(IEngine engine)
    {
        _engine = engine;
    }

    public MyCar()
        : this(new MyV8Engine())
    {

    }
}

It should, because it IS DI. Dependency Injection is about injecting a dependency into an object, instead of placing the burden of new'ing up or finding the dependency on the object that requires it. DI is not about using a framework, it is a design pattern that solves an issue.

It is very valid for small applications to use constructor-based injection and new'ing up objects in default constructors. The reason you don't see this as an example of DI is because often times your dependency graph quickly becomes very big and unwieldy and the move to a DI framework rapidly becomes advantageous as your application grows.


问:
Restful User/Password Authentication
I'm currently designing a REST-API with the following properties:

Backend for a single page application (Later Apps)

Integrated user database for each instance

HTTPS/TLS only

Authentication with a username / password combination

My current approach for the authentication process is the following:

(Client) POST Username&Password to /api/users/action/auth

(Server) Authenticate User, Generate token, Send token to client

(Client) Use Authorization-Header with token for subsequent request

(Client) DELETE /api/users/action/auth to invalidate the token

The token will expire after some idle time.

I've chosen this design because I don't like the idea of storing the plain authentication data on the clients device.

Reading a lot of other questions and articles on this topics I don't think this approach is the best. The following questions arose:

Does the token generation and usage for subsequent requests violate the stateless-principle of REST?

Is this procedure secure? (XSRF?)

Is there a better design approach? I thought OAuth may be an overkill

EDIT:

Regarding 'secure':

The application will contain a lot of sensitive information so security is quite important. Assuming the secure usage of HTTPS (only TLS, strong DH-Group, No export mods etc.) are there any easy to exploit security flaws in this approach?

Regarding 'better':

I choose this model because it's easy to implement on both sides. I put a thought into using HMAC(token, 'POST' || '/api/resource' || timeInterval) as token for each request, my conclusion was that this would add unnecessary complexity without improving security. (Already using TLS)

答:
The statelessness of REST refers to the side of the server. If you pass around your token in every request this becomes part of the state that is being sent from the client and therefore does not violate the statelessness of your server.

This differs from, for example, managing state on the server where you keep information in the session server-side. A session-id sent along with the request and associated with information on the server breaks statelessness as the webserver is now maintaining a state.

As far as 'better' and 'secure' goes, there is no definitive answer to that question. The question is what degree of security you need, what you want and how far you are willing to go to implement it.

Title: Restful User/Password Authentication


答:
First of all, don't put REST above solving problems efficiently. In order for clients to be able to log in you need to somehow store some state. Whether or not you consider this to be against the REST mantra doesn't really matter, you need to do it anyway.

You could make digitally signed tokens containing all session information, and not store those on the server. But for most purposes that doesn't achieve anything practical.

I assume that you store the token in JavaScript memory on the client, send it as a special header with every request, and only return sensitive data or change data when the correct token is set in that header. In that case you should be safe from XSRF, those holes typically only arise when you use cookies.

Is there a better design? Possibly, but given your description, your's is probably good enough.

Title: Restful User/Password Authentication

Body:
I'm currently designing a REST-API with the following properties:

Backend for a single page application (Later Apps)

Integrated user database for each instance

HTTPS/TLS only

Authentication with a username / password combination

My current approach for the authentication process is the following:

(Client) POST Username&Password to /api/users/action/auth

(Server) Authenticate User, Generate token, Send token to client

(Client) Use Authorization-Header with token for subsequent request

(Client) DELETE /api/users/action/auth to invalidate the token

The token will expire after some idle time.

I've chosen this design because I don't like the idea of storing the plain authentication data on the clients device.

Reading a lot of other questions and articles on this topics I don't think this approach is the best. The following questions arose:

Does the token generation and usage for subsequent requests violate the stateless-principle of REST?

Is this procedure secure? (XSRF?)

Is there a better design approach? I thought OAuth may be an overkill

EDIT:

Regarding 'secure':

The application will contain a lot of sensitive information so security is quite important. Assuming the secure usage of HTTPS (only TLS, strong DH-Group, No export mods etc.) are there any easy to exploit security flaws in this approach?

Regarding 'better':

I choose this model because it's easy to implement on both sides. I put a thought into using HMAC(token, 'POST' || '/api/resource' || timeInterval) as token for each request, my conclusion was that this would add unnecessary complexity without improving security. (Already using TLS)


问:
Is there a purpose for using pull requests on my own repo if I am the only developer?
So I got started with a real project of mine on GitHub and things are going pretty well and ideas are flowing a lot faster than I initially thought. In order to keep things organized, I setup some branches so I can develop different features separately.

Now when I push my branch to GitHub, I have that section where I have two buttons : Pull Request and Compare with the name of the branch I recently pushed to. I understand the purpose of the Compare button but I don't get why I would want to create a pull request on my own repo.

Can someone explain me why I would do that? Is it useful to make pull request on my own repo if I am the only developer?

答:
Pull requests are created so someone can review the work, make comments, suggestions, make or request edits and then merge the code to master.

In your case the someone is you.

As the sole developer you still should review your own work, refactor it and merge it to master when ready.

One approach I use a lot is to try to 'put on another hat', 'try other personas'.  So sit for a short while and place yourself in the situation of: newbie to the group; junior developer; colleague you respected in the past, etc.  Try and look at it through their eyes and try to think of simply what could you do to make the change more obvious, better written with even better names that avoid tribal and domain knowledge as much as possible.

So, as you have indicated, you should work in branches when you want to separate out features and changes that aren't ready for master.  You can do all that in branches (you don't even need pull requests to manage them if you do the PR tasks anyway, but it may provide useful structure for you).

Also, I will sometimes find that my change isn't working, but rather than the horror of trying to back it out from master, maybe now mixed with other master changes, I can just do it all in a branch which I can then ignore / delete if it starts to go wrong.  This is a huge benefit.

So you should work in branches and not commit directly to master until you decide to merge the entire branch.

These are guidelines - and not rules - to follow.  I intentionally break them sometimes.  For example, yesterday I committed a typo fix to master.

5 years later update:  All the above still works well for me.  I've recently created many PRs that only I see and approve for myself.  The process of having a PR helps me put on that 'different hat' to review my own work.

Frequent things I pick up in my code reviews of my own code:

commented out code (this is very common)

print (debug) statements

missing or poor tests- missing abstractions

poor naming

edge cases

parameter defaults


答:
I'm surprised nobody has mentioned this yet, but C++ introduced us to references, which almost solve all of the problems and pitfalls of pointers:

```<code>void ModifyVar(int& var)
{
    var = 5;
}

int test = 4;
ModifyVar(test);
</code>```

Instead of:

```<code>void ModifyVar(int * var)
{
    *var = 5;
}

int test = 4;
ModifyVar(&test);
</code>```

Much safer and easier too... and without the overhead of passing-by-value.

Title: Is there any reason to use C++ instead of C, Perl, Python, etc.?

Body:
As a Linux (server side) developer, I don't know where and why should I use C++.

When I'm going for performance, the first and last choice is C.

When "performance" isn't the main issue, programming languages like Perl and Python would be good choices.

Almost all open source applications I know in this area have been written in C, Perl, Python, Bash script, AWK or even PHP, but no one uses C++.

I'm not discussing other areas like GUI or web applications, I'm just talking about Linux, CLI and daemons.

Is there any satisfactory reason to use C++?

Body:
I'm surprised nobody has mentioned this yet, but C++ introduced us to references, which almost solve all of the problems and pitfalls of pointers:

void ModifyVar(int& var)
{
    var = 5;
}

int test = 4;
ModifyVar(test);

Instead of:

void ModifyVar(int * var)
{
    *var = 5;
}

int test = 4;
ModifyVar(&test);

Much safer and easier too... and without the overhead of passing-by-value.


答:
Its good practice to expose only the options a user is authorized for.

This forces authorization to be a cross cutting concern. The "View" needs to know what a user is allowed to do before it can build options and menus for display.

The back end should not trust the front end to make security decisions so must check authorization itself.

There may be business rules that effect authorization depending on data e.g. "Only users with a balance over $5000 can invoke a foreign currency transfer" or "Only a user located at Head Office can view these accounts". So some authorization logic is required within the the business logic.

There are also Technical authorizations to consider - who is allowed to view the logs, who can backup/restore the database etc.

So in the end every component in your may have some specific security and/or authorization requirements, in practice its almost impossible to wrap this up into a separate "authorization layer".

Title: Where does authorization fit in a layered architecture?

Body:
Typically, I place authorization decisions in my server side controllers.  These have been RESTful endpoints recently, but I think the same stands for MVC type architectures.  For the sake of argument assume that it's role based authorisation.  A protected method will be annotated or make checks and return 403s if necessary.

Now, given that authorisation is in fact a business rule - "only administrators can list X" for example, I'm thinking they should be pushed down a layer.  When a controller asks the business layer to perform the operation, the service or business layer informs the controller it's not authorised.

Is this a reasonable approach?  Are there disadvantages to this?

I'm loathe to have an AuthorisationService that essentially holds a bunch of static procedural coded rules to do this but maybe it makes sense to keep all access logic in one place. Is it a cross cutting concern that should be kept separate?

So I'm asking if anyone has done this and how they achieved it in a clean way or if there are any good resources I could read.  I'm using Java fwiw but this is a language agnostic question.

I've checked out the related questions on here and they're very thin on the ground and answers.  For example: Validation and Authorisation in Domain Models and Carrying that through a Service Layer to MVC

I'm reading the spring security docs which make some good arguments for it being a cross cutting concern, but I'm worried it's just the "spring way" and would like wider perspectives.  It also ties your application to a specific framework.


问:
Commercial use of an open source software
I can sell a software which uses an open source library as long as I provide the source of this software with the binaries.

Can I make the source available only to those who bought the software?

Can the customers give the source code to anybody? Will this happen? How is it considered by the open source community?

This question was raised in this discussion. It concerns the GPL license of the CGAL library, but I would like a general answer if possible.

答:
Can I make the source available only to those who bought the software?

Yes. There are no (open-source) licenses that require you to provide the source code to just anybody. The most that is required is that you provide the source code to those people that have obtained a legitimate copy of the software itself.

Can the customers give the source code to anybody? Will this happen?

One of the universal rights that an open-source license grants is the right to redistribute copies of the software that is covered by the license. And an open-source license can't put restrictions on such redistribution, such as a minimum price that must be paid.

So, if you sell software that is under an open-source license, then your customers automatically get the right to redistribute that software and to do so at a lower price that what you charge.

If the software package proves to be popular, then there will almost certainly be people who take advantage of that right.

Now, if your software package uses a library with a copyleft license (for example, the GPL), then your entire software package must be made available under an open-source license. This does not forbid selling the software, but it makes the business case for doing so very weak as each of your customers can undercut your price.


问:
Is using hashes for primary keys a good idea?
The Austrian electronic ID card relies on the so-called sector identifiers. For example a hospital gets to identify a person by getting a sectorId for that person, which is computed roughly as follows:

```<code>sha1(personalId + "+" + prefix + sectorId); // prefix is constant and irrelevant
</code>```

Is that a good idea? I think the possibility of collision, no matter how small, poses a risk.

In hashtables, when there's a collision, you have other means of establishing equality, but with primary keys you can't possibly have two that are identical. That can be circumvented by a composite key, but then the point of a unique sector identifier is lost.

Is it ok to do that and is there a good way to have it that way without it breaking at some point?

答:
Hashes will inevitably collide if they're smaller than all possible combinations of data.

See this excellent answer: https://softwareengineering.stackexchange.com/a/145633

If primary keys are not supposed to be meaningful (human readable; containing retrievable traits of data), I would just go with GUIDs.

Yes, theoretically they can collide as well, but heat death of the universe is likely to happen first. See https://stackoverflow.com/a/184897

EDIT: addressing @DocBrown's counterpoints to clear things up (and to avoid lengthy discussion in comments)

Generating the identifier out of person id or sector id was not OP's requirement (indeed, he admitted that resorting to GUIDs was what he suggested himself).

I never claimed GUIDs are suitable as an overall replacement for SHA-1, or hashing in general (of course they're not), I'm only saying they could be used in this particular case - for uniquely identifying some entities. As this is what they're for by definition.

It was never a requirement that these identifiers must be reconstructible from the data (which is an advantage of hash functions). Please evaluate my answer within the context of the actual question.


答:
C++ vs Python vs Perl can't be judged easily. It depends on the project and requirements.

C++ has an arsenal of utilities from long ago, running in many platforms. But it is painful to start walking through streams for just passing String to Integer and reverse.

C++ on the other hand, has an awful deal with dependencies on libraries. Once you compile something in GCC X or VC++ Y, then you can't rely that the code will run by the next version of those tools. The same hell is on Windows, the same hell is on Unix too.

Perl, takes its power from Unix world but especially as a regular expression tool. This is what it is used most of the time. Along with some pretty serious tools that even Java can't do it in a normal way (check out how to upload a file to a web server), Perl is "just do it".

Python is easy, flexible and a dynamic language. So easy that you can send an integer to a function, the script expects string, yet you can have a result! Unexpected though, but a result. So it the programmer needs to be very cautious. IDLE offers some debugging, but when you have TELNET'ed to a system, or SSH'ed in three levels down and you want to find your problem, the debugger won't be there to stand next to you. But, it can do some great math work fast.

Java is an ecosystem of buzzwords, alien technologies, and big words and when you want to just upload a file to webserver, you find that you can do it only if the server has JSP.
If you want to call system libraries or system functions like monitoring you find that you have to dig out a lot. And perhaps to reach JNI and OK...you think then..."Why, Lord?"

Apart from that, Java is a great tool for business suites, and multithreading, I liked it a lot.

Fast to make a program and show to your CV "Oh, I know that technology too" and your want-to-be boss, be amazed! Even though, the technology might not be that needed... (OK, folks, I hate the Spring Framework....)


问:
Testing async code: are long sleeps acceptable?
I am testing some AngularJS code using Selenium. Angular updates the DOM in unpredictable order, sometimes completely async (via setTimeout), so it is difficult to know when the DOM has been completely updated after an AJAX request (or if the AJAX request has finished or not). (Because of this, all solutions that purely hooks the AJAX requests but not Angular itself are unstable.)

I was fully prepared to find all the places in Angular I need to hook to detect the end of a rendering cycle and inject loads of JS to hook them, then it was suggested to me that I could add sleeps until the result is stable.

Personally, I really hate sleeping in tests. It feels hacky as hell and unnecessarily slows down the already slow Selenium tests. But in this case, sleeping is much simpler and more maintainable.

What are your opinions on this?

答:
Do not do this

Sleeps are unpredictable. You never know when your test environment happens to be downloading Windows Updates when the virusscanner runs and the timeout happens to be a second too short. Your tests will become brittle and useless because you'll have to run every failed scenario multiple times to make sure it was an actual failure. And sleeps force you to wait for the entire time of the sleep, so you are forever torn between big sleeps (which seldom fail) and small sleeps (which terminate and therefore run your tests quicker)

Instead, Selenium offers builtin Waits to handle this. This differs from sleeps because a Selenium wait will continue as soon as the element you are waiting for becomes available. Because they are part of your test framework, you don't have to maintain this code as well.

Basically, what you do is have your AJAX call change the DOM in an observable way: a remote call to fetch a list would put the list element with id "myRemoteList" on the page when loading is finished and Selenium would wait for that element to become visible. The point is that even asynchronous code has an observable outcome and you should wait for the result to become available. Just like you would if you were testing manually, or the user would when working with the application.

I set timeouts in my tests for 60 seconds: if it hasn't loaded then it will never load because something bad happened and I'm also guaranteed it won't timeout because my laptop is doing some background thing.


问:
Is it okay to return the "wrong" HTTP status code in order to show a more user-friendly error page?
Located here, RFC 7231 is all about the HTTP protocol (status codes)

I'm developing an in-house web application for my university's department and I'm at a (probably unimportant) impasse.

I'm reducing users' access to resources based on role (student, faculty, staff) and have it working just fine. However, when a user attempts to access a resource and is denied access, the HTTP specification says that I should use a 403: Forbidden, marking that the user does not have access to the resource, or "hide" the resource by returning a 404: Not Found.

I could do that, but I want to make the site a bit more user-friendly and instead redirect them to their previous page with a flash (NOTE that I did not say 'Adobe Flash'; see comments) message instead of having a 403/4 page with links back to different parts of the site. I think it's a pretty UX-friendly feature.

However, that would involve redirecting via a 303: See Other, which more or less violates the standard.

Obviously it really doesn't matter as this is an in-house project for a lab at my university and nobody here is going to be complaining, but imagine this site were under the Google umbrella.

So, is it bad practice to deviate from the [HTTP] standard like this?

Edit: There seems to be a lot of confusion, so let me give an example:

User with id = 1 attempts to access mydomain.com/projects/2 through their profile (by clicking a link). User 1 is the owner of project 2, so the server accepts the requests and renders the page with the project.

User 1 then types mydomain.com/projects/3 into the URL. User 1 is not the owner of project 3. Therefore, when the request gets to the server, the server denies it.

Now, there are two options:

1.) The server redirects the user to /projects/2 (their previously visited page, which would of course always be a valid one) with a helpful notification at the top such as "Sorry, but you do not have permission to access XXXX" or

2.) The server renders a 403: Forbidden page, or a 404: Not Found page, which would probably have that same text (if it was a 403), and maybe even a JavaScript-enabled "back" link

Personally, the redirect seems way more user friendly to me, and eliminates seeing an unfriendly page like 403: Forbidden and having to click a "back" button. However, doing the redirect goes against the HTTP protocol standard.

答:
The protocol exists, there is a clear answer for what to do.  This isn't anything super secret - it is an "in-house web application for my university's department."  Do the thing that confuses your users and applications the least in the way that allows for proper expansion in a way that is also consistent.

Consider the proposed page flow:

User goes to /foo/1

User lacks access to /foo/1 but has access to /foo/2

User is redirected to /foo/2 (30X response)

and the page flow of

User goes to /foo/1

User lacks access to /foo/1 but has access to /foo/2 and /foo/3

???

and the page flow of

User goes to foo/1

User lacks access to any resources

???

The problem is that the page flow for the first case cannot be applied to the page flow to the second one.  This means that you are either going to have separate logic handling each case, or you are going to have something that surprises a user ("yesterday I was able to access my page via /foo/1, but today it doesn't work after I created a new project").

"Dumb" code is easier to understand both for the user and the coder. While trying to anticipate your users' needs is good thing, providing them something that they really aren't asking for is the wrong thing.

Consider the situation:

Professor A sends Professor B a link to the project that Professor A has and asks for feedback from Professor B on it.

Professor B clicks the link, gets automagically redirected to their own project.

Confusion results.

Following the http specification makes it clear what you should do. Serve a 403 page.

So, serve up the 403 page. This doesn't mean you need to make it an ugly 403 page that the server has as the default. State that the user is asking for a resource that they don't have access to.  Show them what resources they do have access to.  Allow them to click those links to get to where they may want to go.

Don't try to make the software too smart or clever. It is important for the users of the software to be able to enter the mental model of how it works. If there are too many edge and corner cases for how the software works, or it works in surprising ways sometimes - this isn't good. Clever is not something to strive for in code, and it isn't something to strive for in UX either.


答:
Keep your DTO's simple

You are right that having a command with 9 arguments in the constructor is ugly. But do you really HAVE to put those things into the constructor? Make your fields public, create your command with an empty constructor and just assign to the fields. The point of constructor arguments is to have guaranteed valid entities, since you are just using a DTO and validation will be performed by another entity there is not much point in hiding data or having complicated constructors. Public fields all the way for commands.

Nothing wrong with value-DTO's

If you have a Command that is composed of a set of fields that belong together, feel free to map these into a value object that belongs to your DTO. There is no hard rule that says you shouldn't do this.

Commands do not return anything

A command is a change to objects in your domain. You should have no need to return anything from your commandbus. Why would you need to return the id? You created the order, as requested by the command, and that's it.
There is one exception you might consider however and that is...

Validation

Simple validation such as not null/not empty, valid dates, regex-for-email all belongs in a validator. The call to this validator is chained before the call to your commandhandler to the handler is guaranteed to be receiving a valid command.

For complex validation, there are different opinions you can look into. Some people say that even complex validation that requires you do touch the database ('username already taken') should not belong on the validator, some prefer to have all this validation on the validator (which requires repositories) and perform no validation on the command whatsoever. In the end, you have to decide on a strategy to handle failures to validate commands.

Depending on your preference, this might lead you to ValidationResults being returned from your commandbus, trapping and displaying CommandValidationExceptions when you call the commandbus...

Title: Persisting Large/Complex Entities with the Command Pattern -- Am I doing it right?

Body:
I am in the process of designing and building a large-scale inventory management software-as-a-service that will, hopefully, live a long and fruitful life. Therefore I am exerting a lot of effort up-front to ensure the application will be maintainable and horizontally scabale. I really enjoyed this talk by Mathias Verraes on decoupling which inspired to try out the Command Pattern as it lends itself to highly decoupled and very explicit code.

In terms of technology, I'm using Laravel 5 and Doctrine 2 backed by a MySQL database.

Although Mathias speaks on the subject of "getting out of the CRUD mindset", I think we can all agree that many situations exist where the business language does in fact reflect CRUD. For example, the logistics manager says "I need to CREATE a Purchase Order which I will then SUBMIT to the Supplier". The "SUBMIT" portion lights up as a great use-case for a Command, but not so much the CREATE part.

Let me explain my position in hopes someone can agree/disagree and maybe point me in a better direction.

I feel as though the Command Pattern is not particularly well-suited for the act of handling a CREATE request for a complex object, like a Purchase Order. In my domain, the Purchase Order holds information such as:

User-defined Order Number / Identifier (e.g., PO1234)

Supplier for which the Order will be submitted to

The Ship To Address

The Bill To Address

The Requested Shipping Method and Courier

NET Terms

The Monetary Currency

A Sale Order and Customer if the order is to be Drop Shipped

One or more Line Items

If I understand correctly, the Command Object should essentially be a relatively simple DTO that provides a contract to the outside world to interact with the application. "If you want to CREATE a new Purchase Order, populate this object with data and send it down the bus". As a developer, it is beautifully explicit to issue a CreatePurchaseOrderCommand to the application-- I like how that sounds, but when it comes to execution it just feels clumsy.

By clumsy, I mean it seems awkward to extrapolate all of the above data from the Request object and new-up a CreatePurchaseOrderCommand with no fewer than 9 arguments, some of which would be arrays, maybe a ValueObject or two (or would that introduce coupling??).

I've mocked up some code that looks like this:

EDIT I've updated the OrderController to reflect my needs of outputting a JSON encoded object after a successful CREATE in order to satisfy the needs of my client-side framework. Is this considered a good approach? I have no issue with injecting the repository into the Controller as it will almost certainly be needed for other read methods.

OrderController.php

```<code>public function __construct(ValidatingCommandBus $commandBus, OrderRepositoryInterface $repository) { .. }
public function create(CreateOrderRequest $request){
     $uuid = UUID::generate();
     $command = new CreatePurchaseOrderCommand($uuid, $request->all());

     try
     {
         $this->commandBus->execute($command);
         $order = $this->repository->findByUuid($uuid);
         return $this->response()->json([
             'success' => true,
             'data'    => $order->jsonSerialize()
         ]);
     }catch(OrderValidationException $e)
     {
         return $this->response()->json([
             'success' => false,
             'message' => $e->getMessage()
         ]);
     }
}
</code>```

ValidatingCommandBus.php (decorates BaseCommandBus)

```<code>public function __construct(BaseCommandBus $baseCommandBus, IoC $container, CommandTranslator $translator) { .. }
public function execute(Command $command){
    // string manipulation to CreatePurchaseOrderValidator
    $validator = $this->translator->toValidator($command);

    // build validator class from IOC container
    // validates the command's data, might throw exception
    // does *not* validate set constraints e.g., uniqueness of order number
    // this is answering "does this look like a valid command?"
    $this->container->make($validator)->validate($command)

    // pass off to the base command bus to execute
    // invokes CreatePurchaseOrderCommandHandler->handle($command)
    $this->baseCommandBus->execute($command)
}
</code>```

CreatePurchaseOrderCommandHandler.php

```<code>public function __construct(PurchaseOrderBuilderService $builder, PurchaseOrderRepositoryInterface $repository){ .. }
public function handle(CreatePurchaseOrderCommand $command){

    // this again? i'm pulling the same data as I pulled from the
    // Request object back in the Controller, now I'm just getting
    // the same data out of the Command object. Seems repetitive...
    $order = $this->builder->build([
       $command->order_number,
       $command->supplier_id,
    ]);

    // now maybe I should handle set constraints?
    // ensure order number is unique, order is not stale... etc.
    $orderNumberIsUnique = new OrderNumberIsUniqueSpecification($this->repository);
    if ( ! $orderNumberIsUnique->isSatisfiedBy($order) ){
        throw new \ValidationException("The Order Number is not unique");
    }

    // ok now I can persist the entity...
    try
    {
        // start a transaction
        $this->repository->persist($order);
    }catch(SomeDbException $e)
    {
        // roll back transaction
        // cant return anything so i'll throw another exception?
        throw new ErrorException('Something went wrong', $e);
    }

    // no return here as that breaks the CommandBus pattern :|
}
</code>```

From a code perspective I think that seems like the logical way to go about things in terms of placement of validation and such. But, at the end of the day, it doesn't feel like the right solution.

I also don't like that I can't return a value from the Command Bus which leaves me with the choice of switching to generating a UUID before persisting (currently relying on AUTO INC from MySQL) or performing a lookup on the other unique identifier (the order number) which may not work for all entities (i.e., not every entity/aggregate will have some other form of unique identifier besides the database ID).

Am I using and understanding the Command Pattern correctly? Are my concerns valid (see comments in code examples). Am I missing something about the Command Pattern? Any input would be great!!


答: This former SO article tells you how to calculate the collision probability. For SHA-1, b is 160. The number of people living in austria is below 10 millions. Even if each living person in austria is registered in a hospital with a unique person/sector ID, that just makes a collision probability of less than 3.5 x 10^-35. I guess that should be small enough for most practical purposes.

Title: Is using hashes for primary keys a good idea?

Body:
The Austrian electronic ID card relies on the so-called sector identifiers. For example a hospital gets to identify a person by getting a sectorId for that person, which is computed roughly as follows:

```<code>sha1(personalId + "+" + prefix + sectorId); // prefix is constant and irrelevant
</code>```

Is that a good idea? I think the possibility of collision, no matter how small, poses a risk.

In hashtables, when there's a collision, you have other means of establishing equality, but with primary keys you can't possibly have two that are identical. That can be circumvented by a composite key, but then the point of a unique sector identifier is lost.

Is it ok to do that and is there a good way to have it that way without it breaking at some point?