问:
Creating a separate table for images or adding "image fields" to many tables?
I need to create a database in which several tables have images.

For example, users have profile pictures and uploaded ones and products have many pictures, as well.

Is it better to have one SQL table "images" or add "images" to every table that contains them?

Also, how would you add many images into one column?

I've read about the advantages of storing the file paths vs the actual files in the database but what about a long string with many file paths vs many rows?

For example

INSERT INTO images (userid, image1, image2, image3)
VALUES (autoincrementedPK 'pathtofile1', 'pathtofile2', 'pathtofile3')
```
<p>or</p>
<pre class="lang-sql prettyprint-override"><code>INSERT INTO images (userid, images)
VALUES (autoincrementedPK, 'pathtofile1, pathtofile2, pathtofileN')
</code>```

Which option is better and why? Is option two viable? and if so, how would you implement it?

答:
First about storing file paths:

Having several image path columns (imagepath1, imagepath2 ... imagepathN ) violates 1NF.

Storing several comma-separated image paths in the same column also violates 1NF.

When you violate the simplest of normal forms, you will have a lot of headaches in the future.

The correct thing to do is create a separate table for images. That table would have a FK with the user table (userid). You then insert into that table as many image paths as you want to any given user.

Regarding storing actual images as BLOBS.

Same rules about NF1 apply. Same separate table for images applies.

In this case having separate tables for BLOBS is good because the DBA can put the image tables in a separate tablespace, optimizing the disk IO.

Even in the case users are allowed only one image, denormalization by creating a separate table with a one-to-one relationship is recommended.

Note: I can't give you syntax because I'm not familiar with MySQL datatypes.


问:
How to best do cross-browser cross-platform visual CSS regression testing?
Background:

Visual CSS regression testing is where you screenshot (part of) one version of a webpage in a browser and compare it against a screenshot of the previous version of the same webpage in the same browser. This prevents unintentional changes from happening due to browser version upgrades or changes in the page itself (e.g. refactoring CSS), because we can diff the two screenshots and flag the new version for review by a human developer if there are any differences. If the difference(s) are intentional, the developer approves the change and marks the new screenshot as the new norm/reference/baseline screenshot. By taking screenshots of the same page in different browsers on different platforms, we can extend this to cross-browser cross-platform CSS regression testing.

With that long explanation now out of the way:

What is the best way to do cross-browser cross-platform CSS regression testing?

I'm trying to see what might be usable for Bootstrap.

答:
As of December 2014, the best options for cross-browser CSS regression testing seem to be:

CrossBrowserTesting.com

Proprietary cloud service; Costs money

Sounds like it can do the diff-ing and approval management and norm/reference/baseline tracking for you? I haven't actually tried this service out.

WebdriverCSS

A Selenium-based tool that offers a web UI to track, review, and approve differences

Seems to be backed by Sauce Labs somewhat

Wraith-Selenium

A fork of Wraith that adds Selenium support. The original Wraith is limited to CasperJS (i.e. Firefox/Gecko & WebKit only).

Downside: Not sure if this project is established enough yet to survive long-term.

Depicted—dpxdt

Doesn't support cross-browser testing directly, but it does offer a "Diff My Images" option to import screenshots taken from other tools (e.g. Selenium). (The default setup only uses PhantomJS.)

Offers a web UI to track, review, and approve differences

For cross-OS tests for the Selenium-based options, you either need to setup your own cluster of test machines or use a for-pay cloud option such as Sauce Labs, Browserstack, etc.

Both Sauce Labs and Browserstack currently offer free accounts for open-source projects.

ContentLicense: CC BY-SA 3.0


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答: Use Visual SourceSafe.</p>

ContentLicense: CC BY-SA 2.5

Body: Use Visual SourceSafe.


问:
How to organize conversion logic for strategy pattern?
I have a Color class. It has a property model which is a class that implements ColorModel interface, this property could be a RGB, Hex or HSL classes which implementing ColorModel interface.

```<code>// Color.php
class Color {

    protected $model;

    public static function factory (Model $model) {
        return new Color($model);
    }

    public function __construct (Model $model) {
        $this->model = $model;
    }

    public function getModel () {
        return $this->model;
    }

    public function set ($color) {
        $this->model->set($color);
    }

    public function raw ($string = false) {
        return $this->model->raw($string);
    }

    public function check (Color $color) {
        return get_class($this->model) === get_class($color->getModel());
    }

    public function isModel ($type) {
        return $type === $this->model->getName();
    }

    // Converter probably suppose to be a strategy which converts color model to another color model
    public function convert (Converter $convert) {
        // I'm stack here...
    }

}

// ColorModel.php
interface ColorModel {

    // Parser is a class which parses input string/int and converts it to components
    public function __construct (Parser $parser, $x, $y, $z);

    public function raw ($string = false);

    public function set ($color);

    public function getName ();

}
</code>```

I'm not sure how to implement the conversion of ColorModels. How can I implement conversion of those different models without having to create every class for each set (RGB2HSL, HSL2RGB. Let's say I add LAB class four another classes: LAB2RGB, LAB2HSL, HSL2LAB, RGB2LAB, and more, and more)? It's possible at all?

Thank you for attention!

答:
If you have a ColorModel that can represent all possible colors and that you can convert to without loss of information, then you can designate that ColorModel as the 'canonical' model.

The conversion between arbitrary ColorModels then becomes a two-step process: First you convert from the source model to the canonical model and after that you convert from the canonical model to the target model.

This means that for each ColorModel, you need one Converter that can convert between that model and the canonical model (in both directions). For the canonical model this Converter would implement the identity transformation, so that you don't need special logic if the source or target model happens to be the canonical model.


问:
Why is the hashCode method usage of HashSet not specified in the API?
I was trying to debug my code which uses a HashSet and searching through the SO, I found out that I needed to override the hashCode method as well. The strange part is, checking the related API, I did not see any part in it mentioning about the hashCode method. Quoting the definition of the add method of HashSet as seen in the API:

public boolean add(E e)

Adds the specified element to this set if it is not already present.
  More formally, adds the specified element e to this set if this set
  contains no element e2 such that (e==null ? e2==null : e.equals(e2)).
  If this set already contains the element, the call leaves the set
  unchanged and returns false.

Now in the quotation above, I don't see anywhere that mentions about the hashCode method. Shouldn't the correct statement have been like:

... if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)) AND if this set contains no element e2 such that (e==null ? e2==null : e.hashCode() == e2.hashCode()).

Now if you say that: "If o1.equals(o2) returns true, o1.hashCode() == o2.hashCode() MUST evaluate to true as well.", then I would ask three questions:

Where is that fact specified? (in general, or in the API)

Even if that fact is specified somewhere, where in the API it is specified that HashSet makes use of the hashCode method?

If that fact is indeed correct, why isn't the compiler enforces overriding the hashCode method, whenever the equals method is overridden?

答:
... if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)) AND if this set contains no element e2 such that (e==null ? e2==null : e.hashCode() == e2.hashCode()).

The above statement is not correct. It is and should be possible to add an object e1 to a HashSet or a Set in general, where the set contains an element e2, which fulfills e1.hashCode() == e2.hashCode() && e1.equals(e2) == false.

You can easily create examples for this: Imagine a class Person with the attributes name, surname and resident city. The equals method compares all attributes and the hashCode method uses the hash code of the resident city. The contract of equals and hashCode is fulfilled, but with the above contract of add, it would not be possible to add to persons to a set, that live in the same city.

The documentation of HashSet does not explicitly state the use of the method hashCode (I would consider that a implementation detail. The important thing you need to know is, that HashSet fulfills the contract of Set). However there is a hint in the documentation:

This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets.


问:
Adding non distinct elements to a dictionary
Suggestions on a good pattern to follow to add elements to a dictionary where you want to add an element if it does not exist, else do nothing

The 2 approaches I can think of are

```<code>if(!dict.CcontainsKey(i))
    dict.Add(i,true);
</code>```

And

```<code>try
{
    dict.Add(i,true);
}
catch (ArgumentException e)
{
//Do Nothing
}
</code>```

In the case where repetitions are expected to be minimal, is the 2nd method preferred?

答:
From my point of view I would always go for the first approach: it is readable, do not contains the ugly try-catch block, and clearly contains the intent.
Are you sure it should be an exception when adding and failing? Worse, you do nothing in that case. I'm not sure that is the intent of the code.
First one also seems more the desired logic. </p>


答:
That depends on how you want your code to react.

If you simply want do do 'nothing', I'd prefer the first way, you suggested. It's simple, and clean.

The exception could be useful, if you do not expect any duplicate elements, but there suddenly are. You can handle that exception in the catch-block, for example, tell the user, that such an element already exists, or 'rethrow' it to the caller. Going that way, you enable someone else to react, if any duplicate element is detected.

Title: Adding non distinct elements to a dictionary

Body:
Suggestions on a good pattern to follow to add elements to a dictionary where you want to add an element if it does not exist, else do nothing

The 2 approaches I can think of are

```<code>if(!dict.CcontainsKey(i))
    dict.Add(i,true);
</code>```

And

```<code>try
{
    dict.Add(i,true);
}
catch (ArgumentException e)
{
//Do Nothing
}
</code>```

In the case where repetitions are expected to be minimal, is the 2nd method preferred?


答:
You can write a small shell script (~5 lines) to launch a browser and capture the window with imagemagick's import. I use this for Firefox:

```<code>firefox -no-remote "$1" &
sleep 10
window_id=$(xwininfo -tree -root | grep Navigator | awk '{print $1}')
import -window $window_id "$1.png"
wmctrl -c Firefox
</code>```

The only unusual thing here is using wmctrl instead of kill to close Firefox, so it won't go into recovery mode next time it runs. It should be pretty obvious how you can modify this for Chrome or other browsers (you may need to play around with xwininfo to figure out how to find the browser's main window).

You can add a line or two to compare the new image with the previous one using imagemagick's compare.

I'm interpreting this question as asking how to do this rather than asking for off-site resources, since that would be off-topic. There are a number of scripts floating around on the web that do more or less the same thing.

Title: How to best do cross-browser cross-platform visual CSS regression testing?

Body:
Background:

Visual CSS regression testing is where you screenshot (part of) one version of a webpage in a browser and compare it against a screenshot of the previous version of the same webpage in the same browser. This prevents unintentional changes from happening due to browser version upgrades or changes in the page itself (e.g. refactoring CSS), because we can diff the two screenshots and flag the new version for review by a human developer if there are any differences. If the difference(s) are intentional, the developer approves the change and marks the new screenshot as the new norm/reference/baseline screenshot. By taking screenshots of the same page in different browsers on different platforms, we can extend this to cross-browser cross-platform CSS regression testing.

With that long explanation now out of the way:

What is the best way to do cross-browser cross-platform CSS regression testing?

I'm trying to see what might be usable for Bootstrap.

Body:
You can write a small shell script (~5 lines) to launch a browser and capture the window with imagemagick's import. I use this for Firefox:

firefox -no-remote "$1" &
sleep 10
window_id=$(xwininfo -tree -root | grep Navigator | awk '{print $1}')
import -window $window_id "$1.png"
wmctrl -c Firefox

The only unusual thing here is using wmctrl instead of kill to close Firefox, so it won't go into recovery mode next time it runs. It should be pretty obvious how you can modify this for Chrome or other browsers (you may need to play around with xwininfo to figure out how to find the browser's main window).

You can add a line or two to compare the new image with the previous one using imagemagick's compare.

I'm interpreting this question as asking how to do this rather than asking for off-site resources, since that would be off-topic. There are a number of scripts floating around on the web that do more or less the same thing.


问:
Historical precedent for why Prolog is less popular than SQL in Imperative Programming?
It seems that writing Declarative SQL is very popular in Imperative Programming. However, it also seems that writing Declarative Prolog could save a lot of complexity but this is not very common.

Is there a historical precedent for this apparent preference of SQL over Prolog?

If the reason is lack of native support by Imperative languages, then is it possible to answer why the language creators didn't find it useful to natively support Prolog in the first place?

To provide some specific examples:

Example 1

Evaluating a loan application might be just a few lines of code in Prolog, like the SELECT/JOIN query that is just a few lines of code in SQL, but it seems the advantage is not as obvious as SQL.

Example 2

Here is another example problem and the solution in Prolog. The following constraint logic program represents a simplified dataset of john's history as a teacher:

```<code>teaches(john, hardware, T) :- 1990 ≤ T, T < 1999.
teaches(john, software, T) :- 1999 ≤ T, T < 2005.
teaches(john, logic, T) :- 2005 ≤ T, T ≤ 2012.
rank(john, instructor, T) :- 1990 ≤ T, T < 2010.
rank(john, professor, T) :- 2010 ≤ T, T < 2014.
</code>```

The following goal clause queries the dataset to find out when john both taught logic and was a professor:

```<code>:- teaches(john, logic, T), rank(john, professor, T).
</code>```

Result:

```<code>2010 ≤ T, T ≤ 2012.
</code>```

In the above example it will be easy with SQL to get the same result. But suppose that you have this data in an Array.  Then it is not as easy to get the same results using SQL.  And in the case of data stored in an array, I believe that the Prolog code will be easier to write and maintain.

答:
The reason is actually pretty simple.  It has nothing to do with how useful the language is for a given task and everything to do with how maintainable the code is.

Reading an SQL statement, many developers will be able to determine what most basic queries do without knowing the language.  They might have a harder time in the case of complex examples but adapting existing code or working from samples is relatively easy.  The barrier to comprehension is quite low for the vast majority of queries.

You read a few lines of prolog and many developers will go slightly cross-eyed and leave the task for someone else, and possibly go for a lie down.  The predicate syntax of prolog simply does not lend itself to easy reading.

Update:

Based on the code sample, languages that implement collections should do well.  I implemented a solution in C#/Linq and it wasn't significantly larger than the prolog sample (once you accounted for the static typing and definitions required).  There was an extra step involved in some interim work to merge the lists to make a single timeline to be searched but it was not a significant amount of work.


问:
Serving a Website as only Cached HTML Pages
Lets say that I want to develop a website where all pages will be dynamically generated and 'printed' into static HTML files.  I will then serve these HTML files from a container (such as an Amazon EC2 instance) that has no server side languages or database running in the background.

I will make a script to have the HTML files automatically refreshed at a set period.

My reasons for doing this would be to decouple the link between traffic to my website and server load (in other words,  so my website can scale without any need for additional CPU / RAM on the server).

Here are some benefits that i expect from doing it this way

I want a cheap way to host a high traffic website that can accommodate large spikes in traffic (from viral content)

I want it to load as fast as possible -- without any delay from generating content dynamically for each visitor.

My Questions are as follows:

What are the downsides of structuring a website this way?

Is this flat out a bad idea?

What is this type of architecture called?

My Background

I have made a few simple web apps using PHP / mySQL and am familiar with javascript, hmtl, css--- basically a new / amateur web developer.

答:
What are the downsides of structuring a website this way?

Obviously, the downside is inability to do typical "dynamic" stuff like CRUD with forms. Of course, you can still use some 3rd party API for contact forms and comments, like Disqus or Muut.

Is this flat out a bad idea?

No, it is an excellent solution for static sites. It is indeed very fast, yet very limited to its' use case.

Take a look at Jekyll (and sites using it) and similar static site generators. It is pretty easy to start with, there are lots of tutorials. GitHub pages is one of free hosting platforms for static sites, integrated with Jekyll. You can set up custom domain, so it should fit your needs. I'm not saying it's the best, it's just the one I use.

What is this type of architecture called?

"Static website/page generator". It is not an architectural pattern name, just the category of software. I don't think there is any specific term other than just "static website".

I will make a script to have the HTML files automatically refreshed at a set period.

Just push updated content when you change something, that is more efficient.


问:
Introduce Data Transfer Objects or expose complex data model in REST
We are working on an MVVM application. Jersey (backend) exposing a REST interface and AngularJS (frontend) being the only consumer of this interface. The application uses a complex database model (data model), which is different from the model presented to the user in the browser (view model).

Currently we have came across the following dilemma:

to introduce Data Transfer Object (DTO) classes that will contain all the required attributes to invoke complex business logic operations on our model

expose the existing complex data model without introducing DTO classes

Approach 1 will allow to simply the clients of the REST interface, as they will not have to understand the data model and will only have to provide the values of all the required attributes in the DTO classes. However, this approach requires an introduction of a mapping layer in the backend, from/to the data model to/from the view model.

Approach 2 results in less code in the backend, but will probably make the code in the frontend more complex as it will have to do the mapping of user input to the existing data model.

From the REST design perspective approach 2 seems to be better, but is exposing the data model in REST always the best solution?

答:
expose the existing complex data model without introducing DTO classes

One major flaw of this approach is that of coupling data access layer with API. It can go very bad very quickly if those models are used elsewhere except API. I currently work on a project where both web interface and JSON API (kind of REST, but not quite) use the same Hibernate entities - it is fragile, since every change in one place affects the other. Reusability just doesn't work this way, I guess.

Sometimes you just have to have DTOs when models just don't fit into API. For example, if you have some tricky validation rules or some data you want to hide from API clients. You can go nuts with annotations, and yet it will not always work.

I also work on other project which also have both JSON API and web interface, but API uses it's own data access layer (jOOQ). It works fine, despite the fact there are two ways to access the data. It's just easier to write custom queries for API and fill the data into DTOs to begin with than to have some layer of "transformers" from data entities to DTOs. It also works much faster than any ORM and eliminates the whole class of problems related to lazy fetching and "Open Session/EntityManager in View" pattern.

So, I recommend using DTOs, and also considering using separate non-ORM data access layer for API. ORM is good for web interfaces (and probably RPC-style APIs), but seems to cause a lot of troubles with REST - it is related to the idea of CQRS.


答:
What are the downsides of structuring a website this way?

The main problem is dealing with pages that change per user. For example, your website has an user system, so for each user that logs in, would you then generate a new page and cache it?

Is this flat out a bad idea?

No, it's an excellent idea. As a matter of fact, static content is often served like this.

What is this type of architecture called?

I don't think it has a specific name.

There's some things I would like to recommend to you.

I want a cheap way to host a high traffic website that can accommodate large spikes in traffic (from viral content)

First of all, what do you define as high traffic? My $10 a month VPS can serve thousands of pages per second on just a single of core, running nginx.

See if you can't get around with a caching solution first. There are plenty available or you could roll your own specific to what you need. Making a basic one is generally pretty simple and it gives you control over what pages you want cached and which you don't.

Title: Serving a Website as only Cached HTML Pages

Body:
Lets say that I want to develop a website where all pages will be dynamically generated and 'printed' into static HTML files.  I will then serve these HTML files from a container (such as an Amazon EC2 instance) that has no server side languages or database running in the background.

I will make a script to have the HTML files automatically refreshed at a set period.

My reasons for doing this would be to decouple the link between traffic to my website and server load (in other words,  so my website can scale without any need for additional CPU / RAM on the server).

Here are some benefits that i expect from doing it this way

I want a cheap way to host a high traffic website that can accommodate large spikes in traffic (from viral content)

I want it to load as fast as possible -- without any delay from generating content dynamically for each visitor.

My Questions are as follows:

What are the downsides of structuring a website this way?

Is this flat out a bad idea?

What is this type of architecture called?

My Background

I have made a few simple web apps using PHP / mySQL and am familiar with javascript, hmtl, css--- basically a new / amateur web developer.


答:
You shouldn't use exceptions for flow control. Beside that, your first version is shorter, more understandable, more obviously correct (I don't have to check the docs that ArgumentException is the right exception type) and most likely more efficient.

Because of all that, the first version is a much better choice.


答:
I believe this is primarily historical thing.

SQL was primarily used in businesses for making business applications. Some companies build their livelyhood on selling SQL solutions and they used their money to advertise and push SQL into minds of many. This was especially empowered by how important data is for business people. This is why SQL won over it's many competitors and is so widely known and used even today.

Prolog on the other way was mostly known in academic sphere, usually in area of artificial intelligence. Academic people rarely push their tools and ideas on others in a way business does. It usually requires some company to advertise a technology that was born in academia for it to spread among common developers. Also, while data is extremely important, the "business rules" are not so. While they might seem important, they are much less important than data. Business rules can usually be fixed easily. Trying to fix "broken" data is usually much harder problem. So businesses focused much more on getting their data solutions than their business rules solutions.

Title: Historical precedent for why Prolog is less popular than SQL in Imperative Programming?

Body:
It seems that writing Declarative SQL is very popular in Imperative Programming. However, it also seems that writing Declarative Prolog could save a lot of complexity but this is not very common.

Is there a historical precedent for this apparent preference of SQL over Prolog?

If the reason is lack of native support by Imperative languages, then is it possible to answer why the language creators didn't find it useful to natively support Prolog in the first place?

To provide some specific examples:

Example 1

Evaluating a loan application might be just a few lines of code in Prolog, like the SELECT/JOIN query that is just a few lines of code in SQL, but it seems the advantage is not as obvious as SQL.

Example 2

Here is another example problem and the solution in Prolog. The following constraint logic program represents a simplified dataset of john's history as a teacher:

```<code>teaches(john, hardware, T) :- 1990 ≤ T, T < 1999.
teaches(john, software, T) :- 1999 ≤ T, T < 2005.
teaches(john, logic, T) :- 2005 ≤ T, T ≤ 2012.
rank(john, instructor, T) :- 1990 ≤ T, T < 2010.
rank(john, professor, T) :- 2010 ≤ T, T < 2014.
</code>```

The following goal clause queries the dataset to find out when john both taught logic and was a professor:

```<code>:- teaches(john, logic, T), rank(john, professor, T).
</code>```

Result:

```<code>2010 ≤ T, T ≤ 2012.
</code>```

In the above example it will be easy with SQL to get the same result. But suppose that you have this data in an Array.  Then it is not as easy to get the same results using SQL.  And in the case of data stored in an array, I believe that the Prolog code will be easier to write and maintain.


问:
Scoping behavioral variations to dynamic extents
While reading a paper in the context of Aspect Oriented Programming, I encountered following statement:

Aspects enable scoping variations in space (with a rich variety of
  static pointcuts), in time (with dynamic aspects), and in the control
  flow (with the corresponding pointcuts). Scoping a variation to the
  dynamic extent of an expression is however challenging, since scoping
  between threads is not easily realized with aspects.

I am already familiar with AOSD: it's primary function is to modularise crosscutting concerns. Yet it is unclear to me what they mean with 'scoping variations', especially the last one: 'scoping a variation to the dynamic extent to an expression'.

Could someone elaborate on what these scoping variations mean ?

答:
Here is my understanding.

```<code>Aspects enable scoping variations in space (with a rich variety of static pointcuts),
</code>```

This means that a specific section of code can do different things.

```<code>in time (with dynamic aspects),
</code>```

This means that from the time that you hit one point in code to another, behavior is changed by the aspect.

```<code>and in the control flow (with the corresponding pointcuts).
</code>```

The flow of function calls changes.

```<code>Scoping a variation to the dynamic extent of an expression is
however challenging, since scoping between threads is not
easily realized with aspects.
</code>```

Suppose that you have a multi-threaded program with message passing between threads.  The dynamic extent of an expression is everything that is part of computing that expression, including work done by other threads.

So here is what they are trying to achieve.  Threads A and B are both communicating with a worker thread C.  They want what C does to be affected by the state of the thread asking for the work.  But  A and B are independent threads, in different states with different aspects triggered.  This means that you cannot get the desired behavior from C with any of the above mechanisms.

Judging from the abstract, their method for achieving this is to pass information in the message that will cause C to delegate important decisions back to the originating thread, which can then be controlled by the aspect to have correct behavior.  I have to wonder what the resulting overhead of this behavior is in terms of extra message passing and context switches.

(There is an old saying, "To debug code you have to be twice as clever as you were when you wrote it.  So if you write code that is as clever as you can, then by definition you are not smart enough to debug it."  This is why I'm suspicious of AOP, no matter what benefits its adherents have convinced themselves they are gaining...)

Body:
Here is my understanding.

Aspects enable scoping variations in space (with a rich variety of static pointcuts),

This means that a specific section of code can do different things.

in time (with dynamic aspects),

This means that from the time that you hit one point in code to another, behavior is changed by the aspect.

and in the control flow (with the corresponding pointcuts).

The flow of function calls changes.

Scoping a variation to the dynamic extent of an expression is
however challenging, since scoping between threads is not
easily realized with aspects.

Suppose that you have a multi-threaded program with message passing between threads.  The dynamic extent of an expression is everything that is part of computing that expression, including work done by other threads.

So here is what they are trying to achieve.  Threads A and B are both communicating with a worker thread C.  They want what C does to be affected by the state of the thread asking for the work.  But  A and B are independent threads, in different states with different aspects triggered.  This means that you cannot get the desired behavior from C with any of the above mechanisms.

Judging from the abstract, their method for achieving this is to pass information in the message that will cause C to delegate important decisions back to the originating thread, which can then be controlled by the aspect to have correct behavior.  I have to wonder what the resulting overhead of this behavior is in terms of extra message passing and context switches.

(There is an old saying, "To debug code you have to be twice as clever as you were when you wrote it.  So if you write code that is as clever as you can, then by definition you are not smart enough to debug it."  This is why I'm suspicious of AOP, no matter what benefits its adherents have convinced themselves they are gaining...)


答:
There is another reason. Practically speaking, SQL is useful for data persisted on disk. So databases are used to store data for a "long" time (several months). Every SQL database (e.g. PostgreSQL, MySQL, Oracle, ....) is managing data on disks (or SSDs, i.e. hardware which could keep data if properly powered down). However, most Prolog implementations I am aware of are working in memory, and cannot be used to keep data reliably (data persistent after a power outage, at least a programmed one). And SQL implementations can deal with terabytes of data....

Of course, a DBMS does not write immediately to the disk (but later). But the Prolog interpreters I heard of never write (implicitly) their fact & rule bases to persist them to disk.

(Some language implementations do have persistence ability, e.g. SBCL with save-lisp-and-die... but I know no Prolog doing that).

Pragmatically speaking, SQL is for databases -on disks-, but  Prolog is a programming language (for source code in textual files).


问:
Features of a routing system
I have been tinkering with the idea of creating a routing system as a learning experience and not for some production purpose.

I have trying to decide what features are a must have and what features are best handled elsewhere in a system. I have come up with a short list of features and I would like to get some feedback on it. Are there things missing? Or are there anything that is just pure overkill? The list goes a follows:

Regular expression matching against URI

Matching HTTP request scheme

Matching HTTP request method

Checking if a request is a normal request or an AJAX request.

I have chosen to use regular expressions so that I have the possibility of using capture groups to match a dynamic URI. Regarding the overheat of regular expressions I think the worst can be reduced by producing clever expressions and only matching until a match is found.

答:
Everyone has their own wishlist for routing.  Which is why so many people have looked over the landscape, decided that everyone else's routing is bad, and written a new one.

That said, the top of my wishlist includes hierarchical routing.  That is, based on the start of the URL you should be able to route to a component that takes the next component and routes that as well.  This has a performance benefit (you don't have to check at the top level for every URL in components we know you are not in) and also a code modularity benefit (when working on one component, you do not need to be messing with code for other ones).

And the top of the wishlist for any SEO purposes is going to include the ability to have URL rewriting where external SEO friendly URLs which are maintained in a dynamic table get remapped to internal URLs that reflect your application structure.

And esoterically at the application level, I like modular components inside of pages.  Which means that inside of a top level page you might have a component for a sidebar over here, another one for an ad unit over there, and so on.  If you like that design, then you might want to consider reusing your routing logic both for finding a top level URL, and for finding a component inside of your application.  One of the nice things about operating this way is that you can set up components as things that return a data structure, and that data structure can be both consumed inside of your application while generating a page, or exposed as JSON for an AJAX request.  However this is idiosyncratic, and don't try it if it doesn't sound interesting to you.

Title: Features of a routing system


问:
Decentralized Data Management - encapsulating databases into microservices
I've recently been taking a course on Software design and there was a recent discussion/recommendation about using a 'microservices' model where components of a service are separated into microservice sub-components that are as independent as possible.

One part that was mentioned was instead of following the very often seen model of having a single database that all the microservices talk to, you would have a separate database running for each of the microservices.

A better worded and more detailed explanation of this can be found here:
http://martinfowler.com/articles/microservices.html under the section
Decentralized Data Management

the most salient part saying this:

Microservices prefer letting each service manage its own database,
  either different instances of the same database technology, or
  entirely different database systems - an approach called Polyglot
  Persistence. You can use polyglot persistence in a monolith, but it
  appears more frequently with microservices.

Figure 4

I like this concept and, among many other things, see that as a strong improvement on maintenance and having projects with multiple people working on them. That said, I am by no means an experience software architect. Has anyone ever tried to implement it? What benefits and hurdles did you run into?

答:
Let's talk positives and negatives of the microservice approach.

First negatives.  When you create microservices, you're adding inherent complexity in your code.  You're adding overhead.  You're making it harder to replicate the environment (eg for developers).  You're making debugging intermittent problems harder.

Let me illustrate a real downside.  Consider hypothetically the case where you have 100 microservices called while generating a page, each of which does the right thing 99.9% of the time.  But 0.05% of the time they produce wrong results.  And 0.05% of the time there is a slow connection request where, say, a TCP/IP timeout is needed to connect and that takes 5 seconds.   About 90.5% of the time your request works perfectly.  But around 5% of the time you have wrong results and about 5% of time your page is slow.  And every non-reproducible failure has a different cause.

Unless you put a lot of thought around tooling for monitoring, reproducing, and so on, this is going to turn into a mess.  Particularly when one microservice calls another that calls another a few layers deep.  And once you have problems, it will only get worse over time.

OK, this sounds like a nightmare (and more than one company has created huge problems for themselves by going down this path).  Success is only possible you are clearly aware of the potential downside and consistently work to address it.

So what about that monolithic approach?

It turns out that a monolithic application is just as easy to modularize as microservices.  And a function call is both cheaper and more reliable in practice than an RPC call.  So you can develop the same thing except that it is more reliable, runs faster, and involves less code.

OK, then why do companies go to the microservices approach?

The answer is because as you scale, there is a limit to what you can do with a monolithic application.  After so many users, so many requests, and so on, you reach a point where databases do not scale, webservers can't keep your code in memory, and so on.  Furthermore microservice approaches allow for independent and incremental upgrades of your application.  Therefore a microservice architecture is a solution to scaling your application.

My personal rule of thumb is that going from code in a scripting language (eg Python) to optimized C++ generally can improve 1-2 orders of magnitude on both performance and memory usage.  Going the other way to a distributed architecture adds a magnitude to resource requirements but lets you scale indefinitely.  You can make a distributed architecture work, but doing so is harder.

Therefore I would say that if you are starting a personal project, go monolithic.  Learn how to do that well.  Don't be distributed because (Google|eBay|Amazon|etc) are.  If you land in a large company that is distributed, pay close attention to how they make it work and don't screw it up.  And if you wind up having to do the transition, be very, very careful because you're doing something hard that is easy to get very, very wrong.

Disclosure, I have close to 20 years of experience in companies of all sizes.  And yes, I've seen both monolithic and distributed architectures up close and personal.  It is based on that experience that I am telling you that a distributed microservice architecture really is something that you do because you need to, and not because it is somehow cleaner and better.


问:
How to avoid re-implement business rules in Business Intelligence tools
I have a question about business rules and Business Intelligence tools.

The team working on Business Intelligence report tries to re-implement business rules in their report. Our application does calculation, transformation of raw data, and implement complex business rules .... I think the BI team doesn't need to re-implement already coded business rules and do not have to use raw but already transformed data.

What is the best way to provide transformed data to the Business Intelligence team ?

Save more data in our table to provide already transformed data ?

Create views or tables with the transformed data ?

Use Web Service ?

...

答:
There is no "best way", it always depends. The very first thing you have to clarify is if the BI team really want to reuse the existing business rules, and if the team managing the existing application has enough resources to provide and maintain an external interface to the business logic. Such reuse will create an encoupling between the two teams and their components. For example, if some business rules change, the BI team might have to wait for the application's team until they change the interface - but if the application's team has no time for the next 3 weeks, and the BI team needs the change tomorrow, you have a problem.

Assumed both teams agree to reuse some business logic - ask the BI people what kind of interface they prefer. What tools do they use, are those SQL bound, do they allow easy acess to a web service? If the question is "views vs. tables with additional attribute", you should start with views if possible (much less hassle with redundant data), and use addtional data in your tables only if you encounter measurable performance problems. You also did not tell us how the existing business rules are encoded - when they are currently not in a view, only in your application, you might have no other choice than to provide the calculation results in form of some additional attributes within an existing table.


答:
As @svick pointed out, one should not use exceptions for flow control.

Doubtful approach #2 also introduced a potential bug into your code, or at least behavior that you haven't foreseen (these both are synonymous to me).

The thing is that trying to duplicate a key is not the only case where Dictionary would throw an ArgumentException. Another one is attempting to add null to the Dictionary (in which case an ArgumentNullException is thrown, to be precise - but it's a subclass of ArgumentException, so it will still be handled by your catch clause).

Dictionaries in C# don't accept nulls as keys. If i happens to be null, then we've got some information which can't be persisted in dict, and it could indicate there's something wrong elsewhere in your code. But this piece of code that you posted carelessly gobbles this important warning signal, making it more difficult to identify the root cause of the bug in future.

That's another reason for not relying on exceptions when you don't need to, especially not relying on them in the way that gets your code to ignore them...

And finally, I would suggest that you use the third approach:

```<code>dict[i] = true;
</code>```

Definitely the cleanest. You would know it if you took a look at the documentation.

Checking documentation is the best way of preventing oneself from reinventing the wheel. You don't need to come up with your own "pattern", it's already there for you.

(With this solution I assume that your code never has to set any values back to false - the snippets you posted don't imply it).

Body:
As @svick pointed out, one should not use exceptions for flow control.

Doubtful approach #2 also introduced a potential bug into your code, or at least behavior that you haven't foreseen (these both are synonymous to me).

The thing is that trying to duplicate a key is not the only case where Dictionary would throw an ArgumentException. Another one is attempting to add null to the Dictionary (in which case an ArgumentNullException is thrown, to be precise - but it's a subclass of ArgumentException, so it will still be handled by your catch clause).

Dictionaries in C# don't accept nulls as keys. If i happens to be null, then we've got some information which can't be persisted in dict, and it could indicate there's something wrong elsewhere in your code. But this piece of code that you posted carelessly gobbles this important warning signal, making it more difficult to identify the root cause of the bug in future.

That's another reason for not relying on exceptions when you don't need to, especially not relying on them in the way that gets your code to ignore them...

And finally, I would suggest that you use the third approach:

dict[i] = true;

Definitely the cleanest. You would know it if you took a look at the documentation.

Checking documentation is the best way of preventing oneself from reinventing the wheel. You don't need to come up with your own "pattern", it's already there for you.

(With this solution I assume that your code never has to set any values back to false - the snippets you posted don't imply it).


问:
Going from cutting edge to maintaining legacy projects
I have an Access 03 program with a bunch of VBA code that is in use and the end user wants new functionality. I am finding it very difficult to add new functionality because my brain wants to use the most recent .NET technologies and VBA is not recent at all.

How should I go about "rolling back" technologies in my head to keep my frustration levels to a minimum?

Also my boss said it wasn't in the budget to rewrite the project from access and vba to some sort of form and SQL combo (which I could probably pound out in a few days, which is the same amount of time that I feel that it will take me to look up and implement in the old system).

答:
Turn on the Nirvana, roll up your flannel shirt's sleeves, stroke your beard and just get down to work.

Kidding aside, I find it somewhat unpleasant to "roll back" from VS 2010 to Visual Studio for Applications.  BUT, I find it a fulfilling challenge to employ methodologies such as formal Design Patterns, Inversion of Control, automated unit testing, etc. in the older environment.


问:
What do you call classes that do arbitrary work in your project?
I work on a lot of projects with different teams. Every project has its own conventions, including what to call arbitrary classes that don't lend themselves to obvious names.

As a counter-example, it's usually pretty obvious what you should name your models (UserModel, AlbumModel, etc.). The same goes for repositories, installers, controllers and views.

But inevitably there are classes that aren't as clear-cut. For example, I'm working on a project right now that has a ForumService that does the following:

Connect to the forum database and start a forum session

Retrieve forum posts and comments

Create posts and comments

At first, the name ForumService made sense. But then I read more about service-oriented programming and realized that many developers may consider a service to be something different entirely (like a web service). So now I'm considering whether I should call it ForumProvider or just Forum.

The team I work with full-time likes to name classes like this "Tasks" (e.g. AuthenticationTasks, UserTasks). We also have a lot of "Helpers" (e.g. ViewHelpers) and "Utilities" (e.g. HtmlUtilities) for smaller classes. Some developers don't like these ambiguous names just because they're ambiguous.

What do you normally use and why? Do most people generally prefer to avoid names like "Helpers" and "Utilities", and is there a good reason?

答:
Naming things can be tricky - A good rule of thumb is that if you are having trouble naming a class/function clearly then you should read it as a red-flag that you haven't thought about the architecture or design enough yet and should probably stop coding until you have.

For naming stick to the name of the object/concept being modelled and exclude the design patterns / non-object names for classes unless there is a specific reason to include them.  Some examples are...

the class is purely or primarily implementing that pattern like SomethingFactory.

a distinction is needed to avoid ambiguity like StringBuilder.

the architecture (mvvm/mvc/mvp etc) uses it as a convention like DisplayPostViewModel.

In the case of your class it sounds like you're best off using something like Forum since that is the concept you're modelling.  You'd then need classes for the various objects it needs Post and Template for example.  You may want a ForumFactory to create the forum object and create a Dal object for it.


问:
REST backend restricted access only for humans
I will design a REST backend that will work with my database. I want users to access this data by viewing my webpage (I will work with an MVC JS framework) without logging in.

At the same time, I want to prevent users making direct API calls to my backend so they can't take advantage of my data. (I am gathering some kind of statistics aggregating from many sites).

Is that somehow possible? I was thinking of generating a session based on a captcha but maybe there is a better solution I haven't thought about.

tldr: I want only my code running in the browser to access my backend.

P.S I know people can use selenium to scrap my site, I want to make it difficult / not a good solution for them.

答:
Then just don't make a public API. Make your web server build the HTML in the back-end and simply return it as a whole. KISS.

If you want to build a HTML/JS front-end that calls public JSON/whatever REST services, there will be hundreds of ways to call the services directly¹, even it means to simulate a browser (which is really not as hard as it sounds). The Captcha-based session seems like the only secure choice, but then why go as far as to force the user to do something so annoying, such as filling a Captcha along with every request², if you can simply use server-side HTML builders and get rid of the public API?

¹: I can't think of any reason to be afraid of that, but I digress.

²: If it isn't with every request, it must be a session with an expiration date. Until that date, a user can fill the Captcha, get the session ID and just throw it into a program that calls your public APIs.


问:
Clean architecture: should users go in the use case layer or the domain layer?
I recently read this article about Clean Architecture, as I'm trying to get out of some usual OO habits (interface design everywhere, but what does it do???), and program something that describes what the system does instead of how the system is built (to paraphrase "Uncle" Bob).

Once that article gets to the use case layer, the author mentions he left users until that layer because users are specific to the application, then makes a reference (that I really don't think I got) to how if it were a board game it wouldn't have users, but it would still have all the domain objects, in his case orders and products.

But the way I see it, in a web app (some light SaaS) users are part of the domain. Imagine a cloud document store like Dropbox: they store documents, so it seems a document is definitely a domain object. But they also have users don't they? Their business involves storing documents for users, and without users wouldn't that violate an aspect of their business?

I just don't get why users aren't considered part of the system in the same way documents or other things are. Can someone clarify this principle and the reasons behind it for me?

答:
The author makes the distinction between what is in the "board game" or not with the following example:

eBay the website and eBay the board game both need buyers, sellers, items, and bids – but only eBay the website needs users, sessions, cookies, login/logout etc.

See how he mentions "buyers" and "sellers"? These are just different names for "users", but put in the context of the business.

The main point of the separation is that your business model (or as Uncle Bob puts it, "application agnostic business rules") do not need to know about the current user's authentication and authorization methods, or that it has a password, or uses Facebook or Google. Back to the eBay example, the business only needs to know that, in the context of the Order X, user Y is the buyer while user Z is the seller. This is what's important to make the business run - this is what the application does.

Always remember that the idea is to make the business rules completely agnostic of the delivery mechanism. You may have Users as part of your business model, there is nothing bad about it - Dropbox certainly needs, as you pointed out. But be sure to strip away anything related to how the user interacts with the system. This level of detail can be dealt with mostly by the delivery mechanism, and in some part by the application-specific business rules.

For instance, in some apps I've made, I check the user's authorizations within my use-cases, but the authentication methods are decoupled as plugins to be implemented from outside the applications. This has allowed me to easily add login options such as Faceebok, Twitter and Google, without affecting the structure of the applications.


问:
Is there a convention about the standard port for testing and developing in node.js?
I'm trying to get started with node.js.

For example en Java and .net programmer often use the port 8080?
Is there a convention like that in node.js?

I know that any port above 1024 will do it but I will like to follow the conventions so working with other programmers would be easier.

I heard that it is Ryan Dahl's (the creator of node.js) favorite port.
Where can I find what is his favorite port?

答:
The traditional web server port is 80.  However, this is a port in the privileged area on many systems (requiring the administrator of the machine to run the program that listens to that port).

This rules out 80 and 800 as options for ports to set up a server on.  The next value in that series would be 8000.  Many web servers are configured to listen on port 8000 (or the developers just use that as a convention - more on this below).  Some go to 8080, or 8888 for their development port areas, but 8000 is the next value in the series.  The key bit being that they are unique.  You can't have two different programs both listening to the same port.

Tomcat happens to have its configuration files shipped to listen on port 8080 - though this may have changed with other version.  This may be because some web developers are also running an apache httpd server on port 8000 (I've occasionally run that configuration myself - it's not uncommon) as part of the technology stack in use.

That the default configuration of a program that responds to web requests listens on port 8000 should be no surprise at all and is a convention for development servers that dates back since at least when I fired up NCSA HTTPd on port 8000 on a machine I didn't have root on.

This is a convention for development web servers or things you don't want root running (application servers vs a slim httpd proxy) and is unlikely related to any developer's favorite numbers.  It's a port.  It's a convention for developers that long predates Node (or even Javascript).


问:
PHP MVC as backend for iOS app
So, essentially, the question is, to develop a PHP back-end to an iOS application, would you implement an MVC architecture on the PHP side? Or no, since the client side (iOS) already has an MVC architecture?

Or, since we're just passing happy little JSON packets in between front / back end, both server and client should employ MVC architecture? Thus we can implement "private api key" authentication and other security measures at the device level?

Any ideas suggestions welcomed.

答: I use MVC in both. Yes the views server-side are very simple, but that's ok. Still nice to have separation of concerns for all the usual reasons.</p>

Title: PHP MVC as backend for iOS app


问:
Is it bad to use DI to inject constructor parameters at runtime?
These are two classes, the first one I inject an instance of type IEngine while the second one I inject owner's name, tickets and engine.

Version 1:

```<code>public class Car
{
    public Car(IEngine engine)
    {
        // do something here
    }

    public void PrintOwnerName()
    {
    }
}
</code>```

Version 2:

```<code>public class Car
{
    // owner's name, tickets history of this car, and the engine.
    public Car(string ownerName, List<string> tickets, IEngine engine)
    {
    }

    public void PrintOwnerName()
    {
    }
}
</code>```

I was wondering if the version 2 is bad design. If so, why is it bad?

答:
IMHO, it depends upon the parameters. I've used DI to inject cross cutting concerns, such as logging and session management. I think this is good use of DI as the magic of DI does not affect the class-specific logic.

Injecting instance specific parameters seems to be asking for trouble. Not the least of which is someone else trying to work out how your program works. Sometimes you write a bit of extra code to make the program simpler and easier to understand.


问:
Best practices for geolocation
We are writing a flight search engine. We want to pre-fill the departure airport for mobile users with the closest one to their location. To do that, our plan is to

Find a list of airports with their latitude/longitude.

Find the user geolocation using something like HTML5 Geolocation (which asks the user for permission).

Calculate the distance between the user's location and every airport to find the closest one.

Fill the departure form.

Is this a standard way of proceeding? I am a junior programmer and I am not used to this kind of problem. Is there any obstacle I should bear in mind while developing my solution? I have the feeling the algorithm to calculate the distance between one point and 300 locations might get a bit heavy.

答:
This sort of spatial query is routinely handled by spatially enabled databases like mysql, postgres, oracle and sql server.  I'm sure there are others I'm leaving out.

The search then becomes a sql query using whatever geometry type is defined for your database.  The particular topic you're interested in is called a nearest neighbor query.

Check out this link for more details on how to write a query like that for sql server:
http://msdn.microsoft.com/en-us/library/ff929109.aspx.  Due to OGC standardization, you'll find very similar options across many databases and geospatial libraries.

The basic idea behind this scenario is to create a table that holds the locations of all the airports you're interested in as point geometry types.  You then define a spatial index on that column which partitions the space.  This spatial index is really a special tree structure (like a quadtree http://en.wikipedia.org/wiki/Quadtree or http://en.wikipedia.org/wiki/R-tree) which can allow large amounts of data to be excluded from the manual distance searching.

This also allows you to do some more interesting queries easily, like show me all airports within 5 miles.

Title: Best practices for geolocation


答:
The decision which parameters a constructor should have is the same decision which parameters an arbitrary function should have - it should have exactly the parameters which are needed to create a specific, ideally easy to understand, abstraction. And if your abstraction of a car encapsulates exactly those three things, version 2 reflects that much better than version 1.

In your first version, you would have to provide owner name and tickets differently, probably by setting those properties afterwards. But if those properties must be always provided, it is IMHO a better design enforce this by constructor parameters.

One thing you have to care for is that the number of parameters passed through the constructor does not grow to a point where the code becomes hard to understand. For example, when you have a lot more parameters for your car like vendor, color, number of seats, number of doors, list of previous owners, needed driving licence for this type of car, and so on, then you should obviously not pass them all through the constructor (at least, not one by one). One approach to handle this can be to introduce one or more service facades. Another approach might be to add some properties (for things which are optional or might be changed later, as described in @Stephen's answer).

To make decision which is the best solution, however, one has to look at the actual parameters and their meaning, you cannot make a good decision just on "number and types" of the parameters. I assume your "car" example is just a placeholder for something different in your real program, for which the situation might be different, but to discuss it in terms of a car: the owner's name is typically a property of the owner, not of the car, and the list of tickets is AFAIK something associated with the owner, too. So you might consider to introduce an Owner class for this example, where the owner has a name and a list of tickets. So this leads to a constructor

```<code> public Car(Owner owner, IEngine engine)
</code>```

However, taking Stephen's advice into account, assuming the owner of a car can change over the lifetime of a car object, it might be indeed better to stick to your original version 1, provide a getter and a setter for the "current owner" and implement your PrintOwnerName() function with regards to the fact that the owner of the car might be "unknown" (which means uninitialized).

Title: Is it bad to use DI to inject constructor parameters at runtime?

Body:
These are two classes, the first one I inject an instance of type IEngine while the second one I inject owner's name, tickets and engine.

Version 1:

```<code>public class Car
{
    public Car(IEngine engine)
    {
        // do something here
    }

    public void PrintOwnerName()
    {
    }
}
</code>```

Version 2:

```<code>public class Car
{
    // owner's name, tickets history of this car, and the engine.
    public Car(string ownerName, List<string> tickets, IEngine engine)
    {
    }

    public void PrintOwnerName()
    {
    }
}
</code>```

I was wondering if the version 2 is bad design. If so, why is it bad?

Body:
The decision which parameters a constructor should have is the same decision which parameters an arbitrary function should have - it should have exactly the parameters which are needed to create a specific, ideally easy to understand, abstraction. And if your abstraction of a car encapsulates exactly those three things, version 2 reflects that much better than version 1.

In your first version, you would have to provide owner name and tickets differently, probably by setting those properties afterwards. But if those properties must be always provided, it is IMHO a better design enforce this by constructor parameters.

One thing you have to care for is that the number of parameters passed through the constructor does not grow to a point where the code becomes hard to understand. For example, when you have a lot more parameters for your car like vendor, color, number of seats, number of doors, list of previous owners, needed driving licence for this type of car, and so on, then you should obviously not pass them all through the constructor (at least, not one by one). One approach to handle this can be to introduce one or more service facades. Another approach might be to add some properties (for things which are optional or might be changed later, as described in @Stephen's answer).

To make decision which is the best solution, however, one has to look at the actual parameters and their meaning, you cannot make a good decision just on "number and types" of the parameters. I assume your "car" example is just a placeholder for something different in your real program, for which the situation might be different, but to discuss it in terms of a car: the owner's name is typically a property of the owner, not of the car, and the list of tickets is AFAIK something associated with the owner, too. So you might consider to introduce an Owner class for this example, where the owner has a name and a list of tickets. So this leads to a constructor

 public Car(Owner owner, IEngine engine)

However, taking Stephen's advice into account, assuming the owner of a car can change over the lifetime of a car object, it might be indeed better to stick to your original version 1, provide a getter and a setter for the "current owner" and implement your PrintOwnerName() function with regards to the fact that the owner of the car might be "unknown" (which means uninitialized).


答:
If a property meets the following criteria then I make it a constructor parameter:

The class is dependent on it for operation

It has no reason to change over the lifetime of the object

Its value is known at object creation

If it meets these criteria, then it's a constructor parameter.  If it only meets one or two of the criteria then it's almost certainly a settable property.

Constructor parameters are supposed to be used to inject the dependencies of the object.  Use them for that and profit.


问:
What is a login-queue?
some of you should know what a login queue is. You start your game, like world of warcraft, league of legends, ..., type in your username and password, klick "log in" and then it happens: Login Queue, position: x.

What i want to ask is, what actually is a login queue on the serverside? I mean, if you take league of legends and klick log in, the server will first check your logindata and then place you in the loginqueue (or not, if your password is wrong). So what i don't understand is, why is there a queue. If the server had enough time to check your logindata, whats the problem by just setting the "is-loggedin" flag? Why is there a queue needed?

答:
(If it is WoW specific question then the forums or the gaming stack exchange is a better place - My answer is more generic and is from patterns used in enterprise systems as well)

Login Queues are usually used in server side software systems that have limited total resources and Quality of Service parameters mandate that the user is allocated atleast a certain amount of resources on the server to have an acceptable user experience.

Example: In case of an online game, each user needs a certain amount of CPU cycles and memory space to have an acceptable user experience (like no lag). So game servers implement a queue so that too many users don't choke up the server resulting in a bad use experience for all the users. So if the authentication system simply sets a "is-loggedin" flag after validating your credentials then the total number of concurrent users will not be capped resulting in degraded performance for the users.

In enterprise systems, such mechanisms are used for heavy on-demand resources like remote desktops, etc.

Title: What is a login-queue?


答:
If you don't want your users to view the data in the format that is returned by the API to the client side JS, then you can do the client side processing/aggregation on the server itself and return the aggregated data via your API. This way the API will only return the data that the users are allowed to see and your JS framework works just as a presentation layer (you might do away with MVC on the client side).

There is no comprehensive way to prevent your users from accessing data that is accessed by your client side JS code. If it were a compiled app (java applet, etc) you could make it more difficult for the user to view the data from the API but even then the data can still be retrieved.

Title: REST backend restricted access only for humans

Body:
I will design a REST backend that will work with my database. I want users to access this data by viewing my webpage (I will work with an MVC JS framework) without logging in.

At the same time, I want to prevent users making direct API calls to my backend so they can't take advantage of my data. (I am gathering some kind of statistics aggregating from many sites).

Is that somehow possible? I was thinking of generating a session based on a captcha but maybe there is a better solution I haven't thought about.

tldr: I want only my code running in the browser to access my backend.

P.S I know people can use selenium to scrap my site, I want to make it difficult / not a good solution for them.


答:
Version 1 is better than version 2. The reason for that is, a car should not know anything about an owner or any tickets. As cars are objects in our real world, think about it:

Can a car exist without having an owner or tickets? - Certainly yes.

Therefore, remove those from car and make car an independent class that is only dependent of what it is dependent in our world: an engine and possibly other technical properties.

Next, think about what determines the owner of a car. That would normally be a government-service that has a map to assign an owner to a car. Same goes for tickets. You can go even further and say that it does not even depend on that car itself but rather on the license that the government has given to the combination of the car and the owner.

But in your case a more simple modelation will be sufficient I guess, like having only one car-owner-service / car-ticket-service.

One of the many advantages of this modelation is for example, that you can give a college the car class so that he can use it anywhere he wants without having to know anything about tickets or having to deal with car owners. Furthermore, later you may come into a situation where you want a car to be able to have for example multiple owners, one for each country? Or maybe even more properties like a list of the ones allowed to drive it? In this case, you don't need to change the car class for that, but only the mentioned service. With your version 1 you are therefore violation the SRP.

In a nutshell: yes, version 2 is bad design. Go with the first version (and remove PrintOwnerName).


问:
Creating a sort of 'in-language compiler'
I'm not saying I want to create a whole new compiler that's completely independent. I'm using C# Windows Forms and I want users to be able to write filtering syntax in a textbox withing my managed application in a basic query language, for example:

```<code>inCategory(Animals)
where(animal.age > 40)
take animal;
</code>```

It's basically a simplifed version of LINQ. But I want this logic to be enclosed in some separate class, so I can say something like this:

```<code>var dataQuery = FilterCompiler.Compile(filterTextBox.Text);
dataQuery.Execute();
</code>```

I'm not saying 'gimee the code', but some psuedocode / basic logic structure for this 'compiler' would be nice since I am kind of clueless about this subject. Like for example,

What sort of text analysis would this FilterCompiler need to do?

What would be the type of dataQuery?

Would this require any knowledge of compiler grammar?

Would I need to use any unmanaged code?

How can I keep the compiling as independent as possible so that it does not depend too much on what type of data I have? Currently I have a List, but things change, I might have a database with the information in it soon.

答:
A lot of the answers above recommend using parser generators (which are programs that you supply with a description of your language and which then produce code you can compile to parse it). I would actually recommend against this approach. It can often be tricky to understand what's going wrong when such parsers fail, and getting them to produce sensible error messages is an artform of its own.

For simple languages, it can  actually be easier to hand-code your own recursive descent parser.   Here's a simple example to get you started.


问:
Running an HTML/JS/CSS only app on Android without external Phonegap/Cordova etc
Is it possible to run a small and simple game on android using only CSS/JS/HTML?

E.g I have built a small game using the all too known 3 folder stucture and I was wondering if there is any easy way to run it on Android tablets without using Phonegap or Cordova.

The scenario I am imagining is this:

I drop the folder in the tablets filesystem

I point the browser to that local URL

then bookmarking it for easier finding.

Is that possible to do?

答: You can transfer files to your phone right? So why not just transfer the files, fire up your browser and give it a try? On my phone the URL to the Downloads folder looks like file:///storage/emulated/0/Download/. Let us know if it works.</p>


问:
Escape a GameLogic god class.
When programming a simple game as an example. I always tend to get left with a large GameLogic class somewhere which is reponsible for gluing together all of the other portions of the software.

A Common example of the GameLogic class I talk about contains functions such as these.

```<code>startNewGame();
showAd();
prepareLevel();
startLevel();
gameComplete();
restartLevel()
gameOver();
</code>```

This class can become very large.

Is there any advice for how better to structure my future games? Should I be splitting these functions out into dedicated classes somehow as to reduce the complexity of the god class?

答:
When the game is simple, such a class should not be that large.

When the game progresses to large, you should split it up in the way that feels the most natural to you. I tend to end up with a simple finite state machine for the application state, then run a kernel (i.e updating prioritized tasks) in each state.

These tasks often live in a 'scene' so I can load the MainMenuScene, and then it can load LevelOne. Each scene in turn has the ability to run 'tasks'. A task is simply something that can be updated, and can send and receive messages to other tasks.

Lastly, game objects that live in the 'scene' are both a task and it follows the decorator pattern so that I can add aspects of behavior to one or many of the objects in the scene.

As an example:

```<code>FSM
   State (start)
      Task (load assets and saves)
      ...
   State (main menu)
      Task (listen for menu selection)
   State (level1)
      Task & Kernel level1 main
         GameObject (player)
            Component (camera)
            Component (rigidbody)
            Task (physics)
</code>```

Maybe this makes sense, maybe not. Tell me in a comment and I can try to make it easier to understand.

Also, this is just one way to go about it - not sure The One True Way exists.

Title: Escape a GameLogic god class.

Body:
When the game is simple, such a class should not be that large.

When the game progresses to large, you should split it up in the way that feels the most natural to you. I tend to end up with a simple finite state machine for the application state, then run a kernel (i.e updating prioritized tasks) in each state.

These tasks often live in a 'scene' so I can load the MainMenuScene, and then it can load LevelOne. Each scene in turn has the ability to run 'tasks'. A task is simply something that can be updated, and can send and receive messages to other tasks.

Lastly, game objects that live in the 'scene' are both a task and it follows the decorator pattern so that I can add aspects of behavior to one or many of the objects in the scene.

As an example:

FSM
   State (start)
      Task (load assets and saves)
      ...
   State (main menu)
      Task (listen for menu selection)
   State (level1)
      Task & Kernel level1 main
         GameObject (player)
            Component (camera)
            Component (rigidbody)
            Task (physics)

Maybe this makes sense, maybe not. Tell me in a comment and I can try to make it easier to understand.

Also, this is just one way to go about it - not sure The One True Way exists.


问:
Class design - should methods call other methods?
I'm writing a very basic custom class for coupons and I've come up with a basic layout for the class, which consists of a number of small methods as I generally understand is a best practice.

What I'm unsure of is how the flow of a class should be dictated. Right now the code looks something like this:

```<code>public function isCouponValid($coupon) {
    if (strlen($coupon) != 8) return false;

    $query = $this->db->prepare('SELECT coupon_code FROM coupons WHERE coupon_code=:coupon');
    try ($query->execute(array(':coupon' => $coupon))) {
        while ($row = $query->fetch()) {
            return true;
        }
    } catch (PDOException $e) {
        $log->addError('Could not execute SQL query: '.$query.' '.$e->getMessage());
    }

    return false;
}

public function isCouponUsed($coupon) {
    if (self::isCouponValid($coupon)) {
        $query = $this->db->prepare('SELECT coupon_used FROM coupons WHERE coupon_code=:coupon');
        try ($query->execute(array(':coupon' => $coupon))) {
            while ($row = $query->fetch()) {
                return ($row['coupon_used'] == '1') ? true : false;
            }
        } catch (PDOException $e) {
            $log->addError('Could not execute SQL query: '.$query.' '.$e->getMessage());
        }
    }

    return false;
}

public function setCouponUsed($coupon) {
    if (self::isCouponValid($coupon) && !self::isCouponUsed($coupon)) {
        etc...
    }
}
</code>```

Basically I have these checks integrated into the class right now - isCouponUsed() calls isCouponValid() in order to check that it's valid first. Is this a good idea, or is it better for me to use isCouponValid() outside of the class and then pass that value to isCouponUsed(), such that isCouponUsed() should just be concerned with validating a coupon and not check if that code is valid first?

答:
I think this comes down to encapsulation.

If you have to offer public methods to check Coupons, then you can't guarantee that the user of your API will call isCouponValid before calling isCouponUsed, so you have to add the extra check. But these situations are always questionable, and usually suggests that your design does not follow principles such as TellDon'tAsk.

But - and I believe this is the case here - if the validations are part of the behavior of an object, such as the setCoupon method seems to suggest, then you can encapsulate them as private methods (implementation details) of the object. As soon as they are encapsulated, the object is in full control of the order of execution, so you can choose to only call isCouponUsed when the coupon is indeed valid, such as already implemented in the if statement of the setCoupon method.


问:
How do we provide valid time estimates during Sprint Planning without doing "too much" design?
My team is getting up to speed with Scrum, but most of us are more familiar with non-agile or  "pseudo-"agile methodologies. The part that is the biggest hurdle for us is running an efficient Sprint Planning meeting where we break our backlog items into tasks, and estimate hours. (I'm using the terminology from the VS2010 Scrum Template; apologies if I use the wrong word somewhere.)

When we try to figure out how long a task is going to take, we often fall into the trap of designing the feature at the code level -- table layout, interfaces, etc -- in order to figure out how long that's going to take.

I'm pretty sure this is not the appropriate place to be doing that kind of design. We  should be scheduling tasks for these design meetings during the sprint. However, we are having trouble figuring out how else to come up with meaningful estimates for the tasks.

Are there any practical habits/techniques/etc. for making a judgement call about how long a feature is going to take, without knowing how you plan to implement it? If our time estimates are going to change significantly once the design has been completed, how can we properly budget our Sprint backlog ahead of time?

EDIT:

Just to clarify, since some of the comments/answers are very valid but I think addressing the wrong question.

We know that what we're doing is not right, and that we should be building time into the sprint for this design. Conceptually all of the developers understand that. We also also bringing in a team member with Scrum experience to keep us on track if we start going off into the weeds.

The problem is that, without going through this design process, we are finding it difficult to provide concrete time estimates for anything. We are constantly saying things like "well if we design it this way it might take 8 hours but if we end up having to do this other way instead that will take about 32 but it might not be as bad once we start trying to write it...".

I also assume that this process will get better once we have some historical velocity to work from, but many of the technologies and architectural patterns we are using are new to us. But if potentially-wildly-wrong estimates are just a natural part of adapting this process then we will just need to recondition ourselves to accept that :)

答:
We have been operating on the basis of estimating the story 'cold' during the sprint planning with just some limited discussion. The estimates are really quite inaccurate despite the setting up of teams with a reasonably narrow focus... mainly due to the existence of a lot of undocumented, uncommented legacy code with no real over all idea of what is actually supposed to be happening and a staff that has largely changed since the original was written.

What we are trying now is to spend some time ahead of planning investigating each story - and here only one dev will investigate one story... We hope that this will mean that the dev who investigated will be able to provide some clarification and insight to help the estimation. So far this has helped on the occasions it has been tried.

I have yet to be convinced that the additional investigation really makes the estimates enough more accurate to justify the cost but we will try it for a few sprints to see.


答:
You should try drawing it out on a sheet of paper or in some kind of UML mocking program. It will take a few iterations to sort out what seems to model most accurately which roles should be assigned to which classes.

Given your example though, you have a few things that are completely unrelated in the same class:

```<code>startNewGame();
showAd();
prepareLevel();
startLevel();
gameComplete();
restartLevel()
gameOver();
</code>```

Your main method should really only initialize and call start on a game object.

I think that your prepareLevel method should be in another class(the level class)

I am thinking something like:

```<code>Main
--------

public static void main (String[] args){

  new Game().start

}

Game
-------

// Should be the main driving class for menus and such, but shouldn't do any real work
// as that should be in renderers, input processors.Should do all the calls such as:
//   -- Show menu
//   -- Start()

public start(){
  Campaign c = new Campaign();
  gameCore.loadCampaign(c)
}

GameCore
---------
// Game logic not related to rendering.

loadCampaign(Campaign c){
   LevelProcessor.startCampaign(c); // -- maybe this shows your screen and such
}

Campaign
---------
// List of levels, in order

LevelProcessor
-----------

// Makes some calls to load all the assets in your level, shoves it to your game container.

Container
-----------
// Handles the calls and stuff to a renderer which draws your view, handles calls to
// Input handlers and such.
</code>```

Title: Escape a GameLogic god class.

Body:
When programming a simple game as an example. I always tend to get left with a large GameLogic class somewhere which is reponsible for gluing together all of the other portions of the software.

A Common example of the GameLogic class I talk about contains functions such as these.

```<code>startNewGame();
showAd();
prepareLevel();
startLevel();
gameComplete();
restartLevel()
gameOver();
</code>```

This class can become very large.

Is there any advice for how better to structure my future games? Should I be splitting these functions out into dedicated classes somehow as to reduce the complexity of the god class?

Body:
You should try drawing it out on a sheet of paper or in some kind of UML mocking program. It will take a few iterations to sort out what seems to model most accurately which roles should be assigned to which classes.

Given your example though, you have a few things that are completely unrelated in the same class:

startNewGame();
showAd();
prepareLevel();
startLevel();
gameComplete();
restartLevel()
gameOver();

Your main method should really only initialize and call start on a game object.

I think that your prepareLevel method should be in another class(the level class)

I am thinking something like:

Main
--------

public static void main (String[] args){

  new Game().start

}

Game
-------

// Should be the main driving class for menus and such, but shouldn't do any real work
// as that should be in renderers, input processors.Should do all the calls such as:
//   -- Show menu
//   -- Start()

public start(){
  Campaign c = new Campaign();
  gameCore.loadCampaign(c)
}

GameCore
---------
// Game logic not related to rendering.

loadCampaign(Campaign c){
   LevelProcessor.startCampaign(c); // -- maybe this shows your screen and such
}

Campaign
---------
// List of levels, in order

LevelProcessor
-----------

// Makes some calls to load all the assets in your level, shoves it to your game container.

Container
-----------
// Handles the calls and stuff to a renderer which draws your view, handles calls to
// Input handlers and such.


答:
Should I be splitting these functions out into dedicated classes somehow as to reduce the complexity of the god class?

Yes, that's a good idea. A good place to start might be to break up your single monolithic class into smaller classes with related functionality. Managing levels seems to be a common theme, so maybe creating a LevelManager class that contains prepareLevel(), startLevel(), and restartLevel(). Code related to ads could be moved to an AdManager class.

The exact details of how you refactor this will greatly depend on how your game is currently implemented, but I hope this gives you a good idea of how to start.

Title: Escape a GameLogic god class.


答:
You should be concerned about classes driving the behaviour of other classes. This means to be wary(not necessarily always avoiding) the dot operator.

Suppose you are a pizza delivery guy, and you come to my house looking to deliver me a pizza, are you going to reach into my wallet and take my money? What if my money is on the fridge? This is called high coupling.

It means that in order to program additional functionality the PizzaGuy class always has to know about the implementation of the PizzaOrderer. It is a better idea for the PizzaGuy object to simply ask the PizzaOrderer for some money. The pizza guy can then be reused for different instances of the PizzaOrder class such as:

```<code>SearchesCouchForMoneyPizzaOrderer
PayingWithDebitForATenDollarOrderGuy

...
</code>```

This is called the law of demeter, and is an important rule for reducing coupling, allowing for reuse of your code.

Title: Class design - should methods call other methods?

Body:
I'm writing a very basic custom class for coupons and I've come up with a basic layout for the class, which consists of a number of small methods as I generally understand is a best practice.

What I'm unsure of is how the flow of a class should be dictated. Right now the code looks something like this:

```<code>public function isCouponValid($coupon) {
    if (strlen($coupon) != 8) return false;

    $query = $this->db->prepare('SELECT coupon_code FROM coupons WHERE coupon_code=:coupon');
    try ($query->execute(array(':coupon' => $coupon))) {
        while ($row = $query->fetch()) {
            return true;
        }
    } catch (PDOException $e) {
        $log->addError('Could not execute SQL query: '.$query.' '.$e->getMessage());
    }

    return false;
}

public function isCouponUsed($coupon) {
    if (self::isCouponValid($coupon)) {
        $query = $this->db->prepare('SELECT coupon_used FROM coupons WHERE coupon_code=:coupon');
        try ($query->execute(array(':coupon' => $coupon))) {
            while ($row = $query->fetch()) {
                return ($row['coupon_used'] == '1') ? true : false;
            }
        } catch (PDOException $e) {
            $log->addError('Could not execute SQL query: '.$query.' '.$e->getMessage());
        }
    }

    return false;
}

public function setCouponUsed($coupon) {
    if (self::isCouponValid($coupon) && !self::isCouponUsed($coupon)) {
        etc...
    }
}
</code>```

Basically I have these checks integrated into the class right now - isCouponUsed() calls isCouponValid() in order to check that it's valid first. Is this a good idea, or is it better for me to use isCouponValid() outside of the class and then pass that value to isCouponUsed(), such that isCouponUsed() should just be concerned with validating a coupon and not check if that code is valid first?

Body:
You should be concerned about classes driving the behaviour of other classes. This means to be wary(not necessarily always avoiding) the dot operator.

Suppose you are a pizza delivery guy, and you come to my house looking to deliver me a pizza, are you going to reach into my wallet and take my money? What if my money is on the fridge? This is called high coupling.

It means that in order to program additional functionality the PizzaGuy class always has to know about the implementation of the PizzaOrderer. It is a better idea for the PizzaGuy object to simply ask the PizzaOrderer for some money. The pizza guy can then be reused for different instances of the PizzaOrder class such as:

SearchesCouchForMoneyPizzaOrderer
PayingWithDebitForATenDollarOrderGuy

...

This is called the law of demeter, and is an important rule for reducing coupling, allowing for reuse of your code.


答: Additional to Jit Bs answer, I think especially for LoL it is not just the fact that you can login, but rather that you can then start a game. Starting a game seems to aquire quite some serverside resources, having a game running, too. Therefore, if all the people login at once and start a game and play there will be a huge peak in the need of server resources. However, if you have to wait 20 minutes to login, a few players will already be finished with their game.</p>

Title: What is a login-queue?

Body:
some of you should know what a login queue is. You start your game, like world of warcraft, league of legends, ..., type in your username and password, klick "log in" and then it happens: Login Queue, position: x.

What i want to ask is, what actually is a login queue on the serverside? I mean, if you take league of legends and klick log in, the server will first check your logindata and then place you in the loginqueue (or not, if your password is wrong). So what i don't understand is, why is there a queue. If the server had enough time to check your logindata, whats the problem by just setting the "is-loggedin" flag? Why is there a queue needed?


答:
On the simplest level, the server received a username and password and asks the database 'do you have a username and password hash that matches this'.  The database then says either yay or nay.  That is quick and doesn't require much of a queue.  For user experience reasons, this is done with priority, as you don't want a user to wait 5 minutes to find out they mistyped their password.

But, there is often more work that needs to be done before one is actually 'in' the system.  For example, are you a first time user.  Is your subscription paid.  Do you have any new notifications awaiting you.  What security access should you be given.  What about running any logic that is supposed to run on user log in.  All that requires resources before you can be given the welcome screen.  As I've mentioned, the 'is the password correct' is done with far higher priority for reasons of user experience, but the rest of this requires sitting in the queue.

For most applications, this is so small a demand that you don't see a queue until you go use a far more demanding part of the application.  For many business systems, logging in doesn't require a queue, but running a report does.  But it is possible for a system to be under such demand that it doesn't have the resources to immediately display a welcome screen and thus has to put you in a queue until enough resources are ready to handle your request.

One should note that complex systems can require login queue to different parts, even if you don't actually have to re-authenticate.  For example, you login to a system, you get put in a queue until enough resources are available to judge your access level, determine notifications, and run background business logic.  Then you click on a report button, and get stuck in a short queue until enough resources are available to authenticate you in the report system (using information passed in from the previous system) and return the list of reports you are able to run.  Then you click a report, enter the data, and are put into a much longer report queue while you wait for enough resources to run your report.

For online games in particular, there is both a queue to get into the main interface and a queue to get into the game, as the user interface/account management is often separated from the actual game for various reasons (for example, having all your account servers in one location, even if it gives some users greater latency, isn't a problem as 75ms vs. 300ms latency while handling account interactions isn't a big deal, but you want your game servers closer to give the least latency possible because 75ms vs. 300ms is a big deal during game play).

Title: What is a login-queue?


答:
You can also deliver the app from a website. Either just use the files on the website like a typical web app or you can create a manifest file and the browser will cache the files to the local system and will automatically check if the files need to be refreshed.

http://www.codeproject.com/Articles/467724/HTML-Offline-Capabilities-Using-the-Cache-Manifes

Title: Running an HTML/JS/CSS only app on Android without external Phonegap/Cordova etc

Body:
Is it possible to run a small and simple game on android using only CSS/JS/HTML?

E.g I have built a small game using the all too known 3 folder stucture and I was wondering if there is any easy way to run it on Android tablets without using Phonegap or Cordova.

The scenario I am imagining is this:

I drop the folder in the tablets filesystem

I point the browser to that local URL

then bookmarking it for easier finding.

Is that possible to do?


问:
A separate endpoint specifically for sync in a REST api
I am working on a multi client/single server app. Communication between the two happens via RESTful API. There are several resources that need to stay in sync across all clients, including images captured from camera, likes and comments on these images, user profiles and user followers/followings. My current approach involves GETing all resources changed on server since last sync, like GET /images?since=<last-sync-timestamp>, GET /users/:id/followers?since=<last-sync-timestamp> etc. and POSTing all client changes since last sync to the same endpoints, like POST /images, POST /user/:id/followers

The main drawback to this approach is way too many network calls - For each resource I need to sync, I need to perform at least 2 network calls.

So I am thinking about introducing a new endpoint like /sync which provides all syncable resources that have changed since last sync timestamp. Both client and server will need to parse the JSON and put the respective data in appropriate tables, but now, no matter how many resources I have to sync, I will only need to perform two network calls, but change the structure of the JSON as reosurces get added/removed.

Any thoughts on why the second approach is superior/inferior to the first one?

答:
Second approach is a bad/inferior idea.

You lose the ability to cache individual resources using standard caching methods (both on the server and client).

You lose the ability to sync individual resource state using HTTP headers and timestamps

You lose the ability to update resources as you go (why wait to push a change to the server, just push it when user is ready to push it)

You will have a catch all content type for every single resource you have, rather than one for each resource type (ie your JSON will have to incorporate all types of data

Your client will be overly complex, instead of dealing with changing a resource and pushing it to server it has to handle the sync resource.

All to avoid making more small network calls. If you use HTTP headers and gzip compression these calls should be small to tiny, so what is big deal? You gain so much more than you lose.