问:
eCommerce use case: removing a product
I am starting to design the database schema for the eCommerce element of a web service I am creating.

The thing I'm trying to get my head around is how to deal with the use case of a seller (user of my web service) deleting a product.

The issue I have is that this product could be referenced in a customers basket, to be paid orders, pending orders, deliveries, past orders etc...

This problem is surely one that everyone developing such a system has come across. I'm just wondering if there is a best practice way to address it?

Can it be addressed at the database schema level? Or maybe it just requires certain validation checks on database data before allowing a product to be deleted, or to stop an error if a customer is trying to pay for an order that had a reference to a product, but that reference has been deleted (i.e. product was deleted).

答:
The standard approach is to mark the product as inactive, discontinued or otherwise not visible.  Deleting an entry from the database has an entire cascade of events that can be problematic.

This could be something as simple as a boolean, or a MySQL-esque enum, or its own table to join in (if you want to distinguish the difference between inactive (not yet available and not visible) and discontinued (previously available and not visible).

Consider a schema that is something like:

```
 +---------------+     +----------------+
 | Product       |     | Product_state  |
 |---------------|     |----------------|
 | id (PK)       |  +--+ id (PK)        |
 | status (FK)   +--+  | visibile       |
 | sku           |     | desc           |
 | vendor (FK)   |     +----------------+
 | desc          |
 | ...           |
 +---------------+
```

Make sure you have all the appropriate indexes on the tables (see Bitmap vs B-tree in Oracle and bitmap index at wikipedia).  This, combined with the proper view will allow you to simplify the query logic.

Rarely do products exist on their own.  As you mention:

The issue I have is that this product could be referenced in a customers basket, to be paid orders, pending orders, deliveries, past orders etc...

Removing the product from the database would either leave dangling references to things that don't exist.  Even more 'fun' is if the database was constructed with foreign keys that cascade, that cascade of events becomes even more "fun" with a cascade of deletes that wipes out data, or sets the values to null (depending on how the cascade is set up - see Foreign key at Wikipedia).  Note that you can use this approach in some RDBMs to prevent people from messing up the master table by using the restrict option on foreign keys.

You wouldn't just use this for 'in a cart' as a thing, but as you mentioned, paid orders, pending, deliveries, warranties, etc...  Restricting the foreign key delete will give you a database error if you try to delete where it shouldn't be and it will be enforced by the database itself, rather than trying to implement checks in code.

Using the foreign key constraints will also make sure that your database maintains referential integrity - preventing people from accidentally linking an order to something that doesn't exist (which is just as bad as deleting).  It can also improve performance of reads (see Does Foreign Key improve query performance?)

For oracle, you can read about the constraints on foreign keys: 13.1.17.2 Using Foreign Key Constraints

For mysql, you can read about 14.2.7.6 InnoDB and foreign key constraints

Title: eCommerce use case: removing a product

Body:
The standard approach is to mark the product as inactive, discontinued or otherwise not visible.  Deleting an entry from the database has an entire cascade of events that can be problematic.

This could be something as simple as a boolean, or a MySQL-esque enum, or its own table to join in (if you want to distinguish the difference between inactive (not yet available and not visible) and discontinued (previously available and not visible).

Consider a schema that is something like:

 +---------------+     +----------------+
 | Product       |     | Product_state  |
 |---------------|     |----------------|
 | id (PK)       |  +--+ id (PK)        |
 | status (FK)   +--+  | visibile       |
 | sku           |     | desc           |
 | vendor (FK)   |     +----------------+
 | desc          |
 | ...           |
 +---------------+

Make sure you have all the appropriate indexes on the tables (see Bitmap vs B-tree in Oracle and bitmap index at wikipedia).  This, combined with the proper view will allow you to simplify the query logic.

Rarely do products exist on their own.  As you mention:

The issue I have is that this product could be referenced in a customers basket, to be paid orders, pending orders, deliveries, past orders etc...

Removing the product from the database would either leave dangling references to things that don't exist.  Even more 'fun' is if the database was constructed with foreign keys that cascade, that cascade of events becomes even more "fun" with a cascade of deletes that wipes out data, or sets the values to null (depending on how the cascade is set up - see Foreign key at Wikipedia).  Note that you can use this approach in some RDBMs to prevent people from messing up the master table by using the restrict option on foreign keys.

You wouldn't just use this for 'in a cart' as a thing, but as you mentioned, paid orders, pending, deliveries, warranties, etc...  Restricting the foreign key delete will give you a database error if you try to delete where it shouldn't be and it will be enforced by the database itself, rather than trying to implement checks in code.

Using the foreign key constraints will also make sure that your database maintains referential integrity - preventing people from accidentally linking an order to something that doesn't exist (which is just as bad as deleting).  It can also improve performance of reads (see Does Foreign Key improve query performance?)

For oracle, you can read about the constraints on foreign keys: 13.1.17.2 Using Foreign Key Constraints

For mysql, you can read about 14.2.7.6 InnoDB and foreign key constraints


问:
What's the difference between a function and a method?
I've heard that methods are more Object-Oriented than functions.  I was wondering if someone could show me an example of a function and a method and explain the differences between methods and functions?

I have taken 3 quarters of Java programming and functions have never been mentioned, I want to know the differences, strengths and weaknesses.

答:
Speaking strictly, a procedure is a subroutine that is executed purely for its side effects (like printing something to the screen) and returns no values.  A function is a subroutine that always returns the same value given the same inputs and has no side effects.  A method is a procedure or function that is associated with a class or object.

The confusing part is when people use these terms, they're not always referring to the pure definitions.  For the sake of convenience and consistency, programming languages don't always make a distinction between functions, procedures, and methods.  They have one or two ways to declare a subroutine, and whether it's technically a function, procedure, or method depends on how the programmer is using it.

In Java, for example, a procedure is created by having a void return type on a method.  A function is a method with a return type and no side effects, like:

```<code>int add(int x, int y) {
    return x + y;
}
</code>```

People whose only programming experience is in a language like Java often don't even realize there's a difference, because in Java it usually doesn't matter in a practical sense.  In a java-only context, programmers often refer to any subroutine as a function, even by those who know the difference, and they mostly go uncorrected except by the very pedantic.

ContentLicense: CC BY-SA 3.0

Body:
Speaking strictly, a procedure is a subroutine that is executed purely for its side effects (like printing something to the screen) and returns no values.  A function is a subroutine that always returns the same value given the same inputs and has no side effects.  A method is a procedure or function that is associated with a class or object.

The confusing part is when people use these terms, they're not always referring to the pure definitions.  For the sake of convenience and consistency, programming languages don't always make a distinction between functions, procedures, and methods.  They have one or two ways to declare a subroutine, and whether it's technically a function, procedure, or method depends on how the programmer is using it.

In Java, for example, a procedure is created by having a void return type on a method.  A function is a method with a return type and no side effects, like:

int add(int x, int y) {
    return x + y;
}

People whose only programming experience is in a language like Java often don't even realize there's a difference, because in Java it usually doesn't matter in a practical sense.  In a java-only context, programmers often refer to any subroutine as a function, even by those who know the difference, and they mostly go uncorrected except by the very pedantic.

ContentLicense: CC BY-SA 4.0


问:
If I fork an open source project and make improvements in the fork, will it or I offend the original authors?
I have identified a couple of open source projects on github.com that are not being kept up to date for many months. I have used them for personal use, and now want to make enhancements to them and start maintaining the code base and write sample clients that use these projects. I've sent pull requests to the authors and also followed up with emails via their personal / technical website contact page, with no responses from either 1 of them.

I know that I can fork a project on github and be on my way. What I would like to know is

If I Fork an open source project and make improvements in the fork, will it or I offend the original authors? Meaning, could the original authors get upset down the line if my version of the project becomes popular and their version (the ones they are not maintaining or accepting pull requests actively) wanes in usage and popularity. A similar situation would be how Wordpress was forked from B2 and I think initially Mat Mullenweg and original B2 author had some difference of opinion / annoyances.

Are there any licensing issues and copyright issues that I should be aware of? At present, the license.MD for both Projects says Apache License Version 2.0, January 2004 http://www.apache.org/licenses/

答:
Eric Raymond wrote a thoughtful piece about this at one time.  The important point I think is

When you lose interest in a program, your last duty to it is to hand it off to a competent successor.

Basically, will you offend them? It really depends on the them. What would be good to do is to  contact the developer and ask what she or he would thinks or prefers. Maybe that developer will say, why don't I make you a/the maintainer of the project, or maybe the developer will say, oh I thought no one cared, why don't you send me some pull requests and I'll push up some updates I have locally, or maybe the developer will say !#@$@ in which case yeah go ahead and fork it.

Of course you must absolutely follow the terms of the license (which have some interestting twists but it's an osi approved license so it's okay to fork) and make sure you understand what they are.


问:
Writing a unit test for a platform dependent unit
I have a method to be tested which depends on the OS, what's the best approach for testing the method depending on the OS? Is it to test on every OS that I have I require? Is there a better approach for running the tests on only one system?

Some more specific information is that I have a method which is dependent on the OS using Python's platform.system method in a if-else statement and I need to test that which all the possible outcomes from this method.

This method looks like:

```<code>def updateString():
    if platform.system() == 'Darwin':
        return "http://download.com/to/OSX/version"
    elif platform.system() == 'Linux':
        return "http://download.com/to/Linux/version"
    elif platform.system() == 'Windows':
        return "http://download.com/to/Windows/version"
    else:
        return "Seek advice on how to update."
</code>```

答:
If you target multiple OSs, you most probably have to test your program on each of them. These tests should typically include running your test suite on the desired OS. So the straightforward solution for unit testing the above method is to adapt the expected result on platform.system() exactly the same way you showed above:

```<code>def testUpdateString():
    var expectedResult=""
    if platform.system() == 'Darwin':
        expectedResult="http://download.com/to/OSX/version"
    elif platform.system() == 'Linux':
        expectedResult="http://download.com/to/Linux/version"
    elif platform.system() == 'Windows':
        expectedResult="http://download.com/to/Windows/version"
    else:
        expectedResult="Seek advice on how to update."
    assertEqual(expectedResult,updateString())
</code>```

Of course, the drawback is that you cannot get a full test coverage of your code when you run the tests on just one OS. In this example, this is probably acceptable, but if the "real" methods you want to test are more complicated, it may become more practicle to unit test the different parts without actually changing the OS. If that's the case, refactor the core part into a separate method which gets platform.system() as a parameter:

```<code>def updateStringPerSystem(opSys):
    if opSys == 'Darwin':
        return "http://download.com/to/OSX/version"
    elif opSys == 'Linux':
        return "http://download.com/to/Linux/version"
    elif opSys == 'Windows':
        return "http://download.com/to/Windows/version"
    else:
        return "Seek advice on how to update."

def updateString():
     return updateStringPerSystem(platform.system())
</code>```

Now you can write unit tests for updateStringPerSystem, passing all os strings you like for different tests, allowing to test the different branches for OS1, OS2, OS3, etc. even when you are running your test suite only under OS1.

Note that this works only for basic unit tests. As soon as you want to test a function which actually uses the return value for updateString in a OS dependent way, you cannot expect to test Windows functionality when running your suite under Linux, or vice versa.

Body:
If you target multiple OSs, you most probably have to test your program on each of them. These tests should typically include running your test suite on the desired OS. So the straightforward solution for unit testing the above method is to adapt the expected result on platform.system() exactly the same way you showed above:

def testUpdateString():
    var expectedResult=""
    if platform.system() == 'Darwin':
        expectedResult="http://download.com/to/OSX/version"
    elif platform.system() == 'Linux':
        expectedResult="http://download.com/to/Linux/version"
    elif platform.system() == 'Windows':
        expectedResult="http://download.com/to/Windows/version"
    else:
        expectedResult="Seek advice on how to update."
    assertEqual(expectedResult,updateString())

Of course, the drawback is that you cannot get a full test coverage of your code when you run the tests on just one OS. In this example, this is probably acceptable, but if the "real" methods you want to test are more complicated, it may become more practicle to unit test the different parts without actually changing the OS. If that's the case, refactor the core part into a separate method which gets platform.system() as a parameter:

def updateStringPerSystem(opSys):
    if opSys == 'Darwin':
        return "http://download.com/to/OSX/version"
    elif opSys == 'Linux':
        return "http://download.com/to/Linux/version"
    elif opSys == 'Windows':
        return "http://download.com/to/Windows/version"
    else:
        return "Seek advice on how to update."

def updateString():
     return updateStringPerSystem(platform.system())

Now you can write unit tests for updateStringPerSystem, passing all os strings you like for different tests, allowing to test the different branches for OS1, OS2, OS3, etc. even when you are running your test suite only under OS1.

Note that this works only for basic unit tests. As soon as you want to test a function which actually uses the return value for updateString in a OS dependent way, you cannot expect to test Windows functionality when running your suite under Linux, or vice versa.


问:
what kind of functions and/or classes are impossible to unit test and why
Main excuse from the developer for not having a good unit testing is "Code is not designed in a unit testable fashion." I am trying to understand what type of design and code that can't be unit tested. </p>

答:
Several factors may render the code difficult to unit test. When this is the case, refactoring helps in improving the code in order for it to be testable.

Some examples of code which would probably be difficult to test:

A 1000-LOC function,

Code which heavily relies on global state,

Code which requires concrete, complicate to build objects, such as database context, instead of relying on interfaces and Dependency Injection,

Code which performs slowly,

Spaghetti code,

Legacy code which was modified for years with no care about readability or maintainability,

Difficult to understand code which has no comments or hints about the original intention of the author (for example code which uses variable names such as function pGetDp_U(int i, int i2, string sText).

Note that the lack of clear architecture doesn't render code difficult to unit test, since unit tests concern small parts of the code. Unclear architecture would still have a negative impact on integration and system testing.


答:
Common examples of code people don't wish to unit test:

Code which directly interacts with i/o (reading files, direct network calls, …).

Code which directly update the UI.

Code which directly references singletons or global objects.

Code which implicitly change the object or sub-object state.

Using a mock framework, all of these examples can be unit tested. It's just work to setup the mock replacements for the internal dependencies.

Things which truly can't be unit tested:

Infinite loops (for a thread manager, driver, or some other type of long running code)

Certain types of direct assembly operations (which some languages support)

Code which requires privileged access (not impossible, just not a good idea)

Title: what kind of functions and/or classes are impossible to unit test and why

Body: Main excuse from the developer for not having a good unit testing is "Code is not designed in a unit testable fashion." I am trying to understand what type of design and code that can't be unit tested. </p>


答:
There are a lot of things that make code difficult to unit test.  Coincidentally a lot of those also happen to make code difficult to maintain:

Law of Demeter violations.

Creating objects inside a method instead of injecting dependencies.

Tight coupling.

Poor cohesion.

Relies heavily on side effects.

Relies heavily on globals or singletons.

Does not expose much intermediate results.  (I once had to unit test a ten page long math function with a single output and no available intermediate results.  My predecessors basically hard-coded whatever answer the code happened to give).

Depends heavily and directly on services which are difficult to mock, like databases.

Runtime environment is significantly different from development environment, like an embedded target.

Units only available in compiled form (like a third-party DLL).


答:
My main three groups for this are:

code that relies on external services

systems that don't allow testers to modify state independently of the application.

test environments that don't replicate the production setup.

This is what I've experienced the most as a developer turned QA engineer.


答:
Using the mock framework, you can patch platform.system().

from unittest.mock import patch

…

def testUpdateStringWithDarwin():
    with patch('platform.system', MagicMock(return_value="Darwin")):
        result = updateString()

        assert result == "http://download.com/to/OSX/version", "should be Darwin!"
```

Title: Writing a unit test for a platform dependent unit

Body:
I have a method to be tested which depends on the OS, what's the best approach for testing the method depending on the OS? Is it to test on every OS that I have I require? Is there a better approach for running the tests on only one system?

Some more specific information is that I have a method which is dependent on the OS using Python's platform.system method in a if-else statement and I need to test that which all the possible outcomes from this method.

This method looks like:

```<code>def updateString():
    if platform.system() == 'Darwin':
        return "http://download.com/to/OSX/version"
    elif platform.system() == 'Linux':
        return "http://download.com/to/Linux/version"
    elif platform.system() == 'Windows':
        return "http://download.com/to/Windows/version"
    else:
        return "Seek advice on how to update."
</code>```


问:
Which way to terminate reading loop is the preferred approach?
When you have to iterate a reader where the number of items to read is unknown, and the only way to do is it to keep reading until you hit the end.

This is often the place you need an endless loop.

There is the always true that indicates there must be a break or return statement somewhere inside the block.

```<code>int offset = 0;
while(true)
{
    Record r = Read(offset);
    if(r == null)
    {
        break;
    }
    // do work
    offset++;
}
</code>```

There is the double read for loop method.

```<code>Record r = Read(0);
for(int offset = 0; r != null; offset++)
{
    r = Read(offset);
    if(r != null)
    {
        // do work
    }
}
</code>```

There is the single read while loop. Not all languages support this method.

```<code>int offset = 0;
Record r = null;
while((r = Read(++offset)) != null)
{
    // do work
}
</code>```

I'm wondering which approach is the least likely to introduce a bug, most readable and commonly used.

Every time I have to write one of these I think "there has to be a better way".

答:
I would take a step back here. You're concentrating on the picky details of the code but missing the larger picture. Let's take a look at one of your example loops:

```<code>int offset = 0;
while(true)
{
    Record r = Read(offset);
    if(r == null)
    {
        break;
    }
    // do work
    offset++;
}
</code>```

What is the meaning of this code? The meaning is "do some work to each record in a file".  But that is not what the code looks like. The code looks like "maintain an offset. Open a file. Enter a loop with no end condition. Read a record. Test for nullity."  All that before we get to the work!  The question you should be asking is "how can I make this code's appearance match its semantics?"  This code should be:

```<code>foreach(Record record in RecordsFromFile())
    DoWork(record);
</code>```

Now the code reads like its intention.  Separate your mechanisms from your semantics.  In your original code you mix up the mechanism -- the details of the loop -- with the semantics -- the work done to each record.

Now we have to implement RecordsFromFile(). What's the best way of implementing that?  Who cares? That's not the code that anyone is going to be looking at. It's basic mechanism code and its ten lines long. Write it however you want. How about this?

```<code>public IEnumerable<Record> RecordsFromFile()
{
    int offset = 0;
    while(true)
    {
        Record record = Read(offset);
        if (record == null) yield break;
        yield return record;
        offset += 1;
    }
}
</code>```

Now that we are manipulating a lazily computed sequence of records all sorts of scenarios become possible:

```<code>foreach(Record record in RecordsFromFile().Take(10))
    DoWork(record);

foreach(Record record in RecordsFromFile().OrderBy(r=>r.LastName))
    DoWork(record);

foreach(Record record in RecordsFromFile().Where(r=>r.City == "London")
    DoWork(record);
</code>```

And so on.

Any time you write a loop, ask yourself "does this loop read like a mechanism or like the meaning of the code?"  If the answer is "like a mechanism", then try to move that mechanism to its own method, and write the code to make the meaning more visible.

Body:
I would take a step back here. You're concentrating on the picky details of the code but missing the larger picture. Let's take a look at one of your example loops:

int offset = 0;
while(true)
{
    Record r = Read(offset);
    if(r == null)
    {
        break;
    }
    // do work
    offset++;
}

What is the meaning of this code? The meaning is "do some work to each record in a file".  But that is not what the code looks like. The code looks like "maintain an offset. Open a file. Enter a loop with no end condition. Read a record. Test for nullity."  All that before we get to the work!  The question you should be asking is "how can I make this code's appearance match its semantics?"  This code should be:

foreach(Record record in RecordsFromFile())
    DoWork(record);

Now the code reads like its intention.  Separate your mechanisms from your semantics.  In your original code you mix up the mechanism -- the details of the loop -- with the semantics -- the work done to each record.

Now we have to implement RecordsFromFile(). What's the best way of implementing that?  Who cares? That's not the code that anyone is going to be looking at. It's basic mechanism code and its ten lines long. Write it however you want. How about this?

public IEnumerable<Record> RecordsFromFile()
{
    int offset = 0;
    while(true)
    {
        Record record = Read(offset);
        if (record == null) yield break;
        yield return record;
        offset += 1;
    }
}

Now that we are manipulating a lazily computed sequence of records all sorts of scenarios become possible:

foreach(Record record in RecordsFromFile().Take(10))
    DoWork(record);

foreach(Record record in RecordsFromFile().OrderBy(r=>r.LastName))
    DoWork(record);

foreach(Record record in RecordsFromFile().Where(r=>r.City == "London")
    DoWork(record);

And so on.

Any time you write a loop, ask yourself "does this loop read like a mechanism or like the meaning of the code?"  If the answer is "like a mechanism", then try to move that mechanism to its own method, and write the code to make the meaning more visible.


问:
.NET Programming and POCO classes
I was having a think tonight while pondering over some application I need to change and it got me thinking. Entity Framework Entities are POCO (Plain old CLR Objects) and models used in ASP.NET MVC are usually also POCO. This basically means just properties, no methods.

Now OO programming normally allows an object to encapsulate its functionality, which includes its properties as well as its methods, this allows for polymorphism to happen. With the rise of POCO classes being used, design patterns like generic repositories have become more popular. When in the past my objects would have had their own CRUD operations, I now have them on a repository.

Is this just an evolution in OO where CRUD operations are removed from the objects to allow them to be decoupled or maybe CRUD operations shouldn't have been at object level in the past and I was in the wrong? heck, maybe both are perfectly legit and always have been. Its just an observation that got me thinking, so figured I would seek other opinions.

答:
POCO in no way implies there are not methods -- though most of the examples one sees use much of the MVC auto binding features that mainly deal with properties and ignore methods.

Having persistence embedded in your model objects violates separation of concerns and makes it very hard to do things like unit test the objects without standing up a database. It isn't a function of the model object but a function if a different class such as a repository.

Title: .NET Programming and POCO classes


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答:
I've been working with a web system for a while where all parameters passed had to be named P1, P2, P3 etc. No chance in hell to know what they where for without extensive documentation.

Also - although not strictly a coding standard - in the same system, every single file was to be named xyz0001.ext, xyz0002.ext, xyz0003.ext, etc - where xyz was the code for the application in itself.

OwnerDisplayName: CB Du Rietz

ContentLicense: CC BY-SA 2.5


问:
Coworker that detrimentally picks on every minutia
Hypothetically speaking imagine that there exists a coworker that has a very shallow understanding of computing. To avoid stereotyping lets give this coworker the gender neutral name Chris.

Now Chris' diagnostic ability is low and can't figure out the correct IP addresses to set his/her virtual machines to. Chris also fails to merge code properly and overwrites a commit I made fixing something, thereby re-introducing a bug. I let this slide, refix the bug and do not make a sound about it to management.

Given a task Chris either 1) complains that there isn't sufficient information resulting in 2) you provide Chris with inordinately detailed instructions to satisfy 1). The more detail you provide in a list of steps to carry out, the more chance of an error being present in your instructions. Chris gets these instructions, tries to execute them, fails and it becomes your fault because your instructions aren't good enough. How do you deal with this?

答:
I know, its hard working with people who are not as good as you!  but I'm sorry thats life, and as you get better you will find this happens more and more often  ;)

However, the best strategy is to identify the areas of technical weakness.  e.g. lack of knowledge of TCP/IP, cannot translate a task request into a suitable algorythm, etc..  and then ask the questions, does this person have sufficent skills for the tasks at hand? Does the time taken in supporting and developing this person cost more than their personal output produces? are they learning and improving?

If the net effect on the team over the long term looks negative and there is no evidence that it will improve significantly then you can be sure that your managers will want to know. However, it is quite possible that this person has the potential, but that you are not the person to do the training and support.

I would guess that this co worker is slightly out of their depth, and is not getting the support they need to start being productive.  Likewise, you are struggling with this person not being a total geek, and find it dificult to provide support at the right level.


问:
Why not embed styles/scripts in HTML instead of linking?
We concatenate CSS and JavaScript files to reduce the number of HTTP requests, which improves performance. The result is HTML like this:

```<code><link rel="stylesheet" href="all-my-css-0fn392nf.min.css">
<!-- later... -->
<script src="all-my-js-0fn392nf.min.js"></script>
</code>```

If we've got server-side/build logic to do all this for us, why not take it one step further and embed those concatenated styles and scripts in the HTML?

```<code><style>.all{width:100%;}.my{display:none;}.css{color:white;}</style>
<!-- later... -->
<script>var all, my, js;</script>
</code>```

That's two fewer HTTP requests, yet I've not seen this technique in practice. Why not?

答:
The separation of content from the styling of its presentation is usually a bigger advantage than fewer http requests.

Separating out all the styling enables and encourages reuse and shared files.

The contents of the files will also be more static and available for caching on both servers and clients for both that page and other pages that are visited.

To you specific question though...If the server is made to do the minification itself it makes the assets harder to maintain and to debug issues.  However many frameworks do now do this at the file level, e.g. all cs and all js.  For example the ruby on rails framework now minifies its assets for production.  5-10 extra http requests are usually not the bottleneck, its more if there are 100+ http requests (which you often get with images).

The extra step of actually including the code in the pages itself would have the disadvantage of bigger pages that you'd have to manage the download sequence carefully and the page not being able to display content often without the rest of the (now large) page being downloaded.


答:
Because saving HTTP requests is of little use when you achieve it by breaking caching. If the stylesheets and scripts are served separately, they can be cached very well and amortized over many, many requests to wildly different pages. If they're mushed in the same HTML page, they have to be re-transmitted with every. Single. Request.

This page's HTML, for example is 13 KB right now. The 180 KB of CSS hit the cache, and so did the 360 KB of JS. Both cache hits took minuscle amounts of time and consumed practically no bandwidth. Whip out your browser's network profiler and try it on some other sites.

Title: Why not embed styles/scripts in HTML instead of linking?

Body:
We concatenate CSS and JavaScript files to reduce the number of HTTP requests, which improves performance. The result is HTML like this:

```<code><link rel="stylesheet" href="all-my-css-0fn392nf.min.css">
<!-- later... -->
<script src="all-my-js-0fn392nf.min.js"></script>
</code>```

If we've got server-side/build logic to do all this for us, why not take it one step further and embed those concatenated styles and scripts in the HTML?

```<code><style>.all{width:100%;}.my{display:none;}.css{color:white;}</style>
<!-- later... -->
<script>var all, my, js;</script>
</code>```

That's two fewer HTTP requests, yet I've not seen this technique in practice. Why not?


问:
Minimax in a bayesian game with multiple players who do not play in order
Premise: I know that such a game would be better solved by MCTS, however, from a theoretical point of view, would it be possible to apply minimax to a bayesian multiplayer game where the order of playing is determined by result of the previous turn?

Game description:

Players: {A,B,C,D} (A and C are the maximizing team while B and D are the minimizing team)

Bayesian to set for example players' cards.

Turn 1: A->B->C->D

Turn 2(the order depends of the actual epilogue of Turn 1): C->D->A->B

Turn 3: B->C->D->A

...

Turn N: game ends.

My feeling is that wouldn't be possible because after Turn 1 finished, in minimax standard definition, I must be able to start the next turn from a known player, while chance should be only applied to game's payoffs. Any opinion would be helpful.

答:
Minmax for multiplayer games shouldn't be dependent on the turn order of the other
players, it depends on how well you are doing verses all of the other players.

At any terminal node, your evaluation considers some function of your standing
verses the rest of your opponents collective standing; who is going to move next isn't relevant.

That said, multiplayer games have lots of imponderables when developing evaluation
functions;  there isn't any "correct" framework for dealing with coalition and kingmaker scenarios, and the practical aspects of limited depth search make horizon effects particularly severe.


问:
What HTTP status codes need to be checked for this network task to perform smoothly?
My office department logs in to the ISP Server through a keep-alive-browser login page. This, for better performance, is encapsulated in to a small python script.
This is what it does (Pseudo code)

```<code>1.CheckForActiveInternet
2.if not active
     Login
     KeepAlive
3.else
     report
</code>```

In step 1, a host like "www.google.com" is checked for active connection. A status code is returned and this is exactly what my doubt is; what would this code be? 200 or 202? Incase google redirects to .co.** urls the status code would be 302 which even complicates it further since our ISP redirects too, when there is no active internet connection.

You could see that if we check 302 for deciding on weather or not we'd be needing a login, it could be either the google redirecting or our ISP itself. So what could be done here? The current script checks:

```<code>if status in (200, 202, ""):
    Connection is Active
</code>```

This is quite vague isn't it? When is an empty string returned as status code? A non-redirecting site like wikipedia.org might do the trick I thought, but I don't know how feasible this method would be.

答:
Microsoft does this in Windows by attempting to download a specific URL and checking whether it has specific, static content:

When the PC seems to be connected to the network, Windows will download http://www.msftncsi.com/ncsi.txt (and http://ipv6.msftncsi.com/ncsi.txt to check IPv6 connectivity) and check that the response body contains the string "Microsoft NCSI". If it does not, then something is wrong with the Internet connectivity, and the yellow triangle with the exclamation mark appears in the user's taskbar.

You can use a similar algorithm in your own program. By checking for the returned text to match something you expect, from a known web site which does not return 302 redirects, you can be sure whether the computer has Internet connectivity.


答:
Anyway given a task Chris either 1)
  complains that there isn't sufficient
  information resulting in 2) you
  provide Chris with inordinately
  detailed instructions to satisfy 1).
  The more detail you provide in a list
  of steps to carry out, the more chance
  of an error being present in your
  instructions.

Having been in both your position and Chris's, I might be able to explain things a bit.  I hear you saying that you're giving Chris tasks, but you don't mention involving him in coming up with those instructions.  You're probably trying to help him do the right thing, but that's probably not how he sees it.  When you're in Chris's place, it's difficult not to think of what you're trying to do as saying "OK, here's your work.  Now do your job, drone."

In other words, the solution isn't to give Chris more instructions.  In fact, you should give him no instructions.  Instead, you should help him come up with a course of action.  Once Chris sees his role in the process, he might very well turn into a different person altogether.

Title: Coworker that detrimentally picks on every minutia

Body:
Hypothetically speaking imagine that there exists a coworker that has a very shallow understanding of computing. To avoid stereotyping lets give this coworker the gender neutral name Chris.

Now Chris' diagnostic ability is low and can't figure out the correct IP addresses to set his/her virtual machines to. Chris also fails to merge code properly and overwrites a commit I made fixing something, thereby re-introducing a bug. I let this slide, refix the bug and do not make a sound about it to management.

Given a task Chris either 1) complains that there isn't sufficient information resulting in 2) you provide Chris with inordinately detailed instructions to satisfy 1). The more detail you provide in a list of steps to carry out, the more chance of an error being present in your instructions. Chris gets these instructions, tries to execute them, fails and it becomes your fault because your instructions aren't good enough. How do you deal with this?


问:
Transport information screens
I need to create an information service on trains to deliver live information.  I am looking for some ways to go about this.

There are already existing LCD monitors in many of the train wagons.  They are powered from the battery.  When the train is moving, I would like the screens to display the following information:
i) about the route, next stops etc.
ii) news items
iii) video adverts to be shown when the train is within a GPS 'corridor'.

For this to work, we need to place GPS on board.  We also need to be connected to the internet to be able to get live data (for the news items) and to be able to push new video content when it becomes available.  I don't want to have to visit each train wagon just to load up new data.

I had originally thought I would need to have an app built in Android that did all this, but I think it would be easier all round if I could get this to work via HTML5 on a browser.  So far I have come up with the following 2 hardware possibilities:

1) Buy cheap, 2nd-hand tablets with broken screens (as I should still be able to control it using a mouse).  They should have GPS capability either in-built or via a dongle and be internet-enabled (likely a SIM card).  Output the display to the LCD screen.
2) Install a laptop with the same capabilities.

With 1) it is possible to buy older tablets or with cracked screens etc. so the cost can be kept lower, although it would be impossible to get a standard type (which would be far easier to maintain).  They can be bolted onto the back of the monitor.  The disadvantage is that the output from the tablet may not be high enough resolution when blown up onto an LCD

With 2), a laptop, the resolution issue can be more easily overcome.  It also may be easier to source working laptops with broken/missing screens.

I imagine that I will need to send information about the GPS location to a server every 10 seconds or so, maybe in a simple GET in a URL, so that I can present the information on a web-page.  This might work for information like the next stop, and news feeds, but the videos will likely be longer than 10 seconds.  So how do I deliver the content?

Among the things I am wondering is if a browser connected to the internet can do all this.  The location needs to be continually updated.  Instead of simply playing everything on a loop, things happen when the train is in certain areas e.g. approaching/leaving a station.  One way to do it is send the GPS data back every 15 seconds and then refresh the browser web-page to display content based on that GPS location and direction.

Additionally, would video content cache correctly?  When a browser needs to show that content, it would be nice if there wasn't a lot of lag as it tries to download a new video (or display an existing one).

And, although using machines with broken screens, which are more cost-effective and less of a target for theft, they become less user-friendly.  What happens in the event of a power-outage?  It is possible to reboot everything correctly to have the browser displaying everything and connected to the GPS and internet?

Lots for me to solve :)

答:
Content management in this kind of environment can actually be pretty tricky business, depending on what you want... I would try to keep it simple.

You will need an application on the client side that is responsible for loading data. This could be as simple as a script that runs as a cron-job on a little linux box (like raspberry-pi) that runs once a day (at 2am if possible) which would kickoff an RSYNC to a folder stored on your central server. This script would need to be smart enough stop the user visible UI, do the RSYNC, check the data to make sure its not corrupted (by maybe computing an checking a hash code), and then restart the user facing UI. Please note that this component could also be something very sophisticated that runs all the time and establishes a persistent TCP connection with the server where an administrator could push updates to the device(s) on demand. Whatever it is, this component needs to be extremely robust... and able to recover from errors. Use Python ;)

If you are using RSYNC you could keep a separate folder for each train or route in order to keep the volume of transferred data down.

The user facing component could be written as a stand alone app in the preferred language for the platform (java for android) or in HTML5/Javascript or in a mixed application (Maybe java or QT UI with an embedded web browser?). The code/binaries for this component could be shipped to the device via your data distribution mechanism. The app would monitor the GPS coordinates and display content as necessary (assuming all the content is pre-loaded). The content needs to ship with meta-data to let the UI know when/where to display content.

The complexity of the central server will scale with the complexity of the client application and the capabilities you want...You might want to write a web app with a nice REST interface for the clients to use, or not. You probably want implement some way for client applications to inform you of problems (a crashing load). This could be done by exposing a REST interface for clients to use...

Rasberry Pi would be a good choice for client side hardware. Check out the following:

http://www.cooking-hacks.com/3g-gprs-shield-for-raspberry-pi-3g-gps

(Disclaimer: I've never used this so have no idea how well it works.)

Title: Transport information screens


答:
Just two different approaches each with their own merits.

https://stackoverflow.com/questions/1519669/data-access-layer-or-having-object-with-crud-methods

Title: .NET Programming and POCO classes

Body:
I was having a think tonight while pondering over some application I need to change and it got me thinking. Entity Framework Entities are POCO (Plain old CLR Objects) and models used in ASP.NET MVC are usually also POCO. This basically means just properties, no methods.

Now OO programming normally allows an object to encapsulate its functionality, which includes its properties as well as its methods, this allows for polymorphism to happen. With the rise of POCO classes being used, design patterns like generic repositories have become more popular. When in the past my objects would have had their own CRUD operations, I now have them on a repository.

Is this just an evolution in OO where CRUD operations are removed from the objects to allow them to be decoupled or maybe CRUD operations shouldn't have been at object level in the past and I was in the wrong? heck, maybe both are perfectly legit and always have been. Its just an observation that got me thinking, so figured I would seek other opinions.


问:
What kind of user authentication do I need in for a restful web api
I am doing a restful web api with asp.net Web API 2

I do not want to use any form of cookies or basic authentication (send user/pass in cleartext thus SSL needed)

I do not use/need claims stuff.

I have not decided yet about asp.net self hosting or IIS.

I just want to send an encrypted token between client server via SSL.

I am using Entity framework 6, .NET 4.5.1 and I just want to do CRUD-actions on my user table.

Not more.

What is the project template/library/approach I should start with to do the above?

答:
Use HMAC with a client ID.

The client uses their "secret" salt to sign the message and then send the server the generated hash along with its ID. The server looks up what the "secret" should be based on the ID the client sent, regenerates the hash with the fetched secret as the salt. If the server-generated hash matches the client-provided hash, then the request is legitimate.

I'm not a ASP/.NET person, so I can't provide any info on libs nor technical approach, but here's some pseudo code:

client

```<code>var messageBody = 'POST PLAIN TEXT BODY';
var clientId = '12345';
var secret = 'abcdef';
var digest = createHash(messageBody,secret); // function createHash(string,salt)
var url = 'http://example.org/api?clientId='+clientId+'&hmac='+digest;
sendRequest(url,messageBody); // function sendRequest(url,postbody)
</code>```

server

```<code>var messageBody = 'POST PLAIN TEXT BODY';
var clientId = '12345'; // from GET query
var hmac = '...'; // from GET query
var secret = lookupSecret(clientId);
var digest = createhash(messageBody,secret);
if ( hmac == digest ) {
    // success, handle messageBody
} else {
    // error
}
</code>```

Consider using a nonce to prevent man-in-the-middle attacks, if that is of concern to you.

Body:
Use HMAC with a client ID.

The client uses their "secret" salt to sign the message and then send the server the generated hash along with its ID. The server looks up what the "secret" should be based on the ID the client sent, regenerates the hash with the fetched secret as the salt. If the server-generated hash matches the client-provided hash, then the request is legitimate.

I'm not a ASP/.NET person, so I can't provide any info on libs nor technical approach, but here's some pseudo code:

client

var messageBody = 'POST PLAIN TEXT BODY';
var clientId = '12345';
var secret = 'abcdef';
var digest = createHash(messageBody,secret); // function createHash(string,salt)
var url = 'http://example.org/api?clientId='+clientId+'&hmac='+digest;
sendRequest(url,messageBody); // function sendRequest(url,postbody)

server

var messageBody = 'POST PLAIN TEXT BODY';
var clientId = '12345'; // from GET query
var hmac = '...'; // from GET query
var secret = lookupSecret(clientId);
var digest = createhash(messageBody,secret);
if ( hmac == digest ) {
    // success, handle messageBody
} else {
    // error
}

Consider using a nonce to prevent man-in-the-middle attacks, if that is of concern to you.


答:
I've been using Extension Methods for stuff like this lately.

The POCO contains logic which only makes sense for the object itself. Business logic or coordinated object logic goes into a BL extension. Data access can go either into a data access layer or a data access extension.

```<code>namespace MyApp
{
    public class MyClass
    {
        public string id;
        public string name;
        public int quantity;
        public decimal price;
    }
}

namespace MyAppBL
{
    public static class MyClassBL
    {
        public static decimal PriceInCart(this MyClass myObject)
        {
            return myObject.quantity > 10 ? myObject.price * 0.9m : myObject.price;
        }
    }
}

namespace MyAppDA
{
    public static class MyClassDA
    {
        public static void Create()
        {
            …
        }

        public static void Read(string myObject)
        {
            …
        }

        public static void Update(this MyClass myObject)
        {
            …
        }

        public static void Delete(this MyClass myObject)
        {
            …
        }
    }
}
</code>```

This give you a very nice myObject.PriceInCart() and myObject.Save() while keeping your class focused on the data. Of course for static methods you need to have MyAppDA.Create() instead of MyApp.Create().

Title: .NET Programming and POCO classes

Body:
I've been using Extension Methods for stuff like this lately.

The POCO contains logic which only makes sense for the object itself. Business logic or coordinated object logic goes into a BL extension. Data access can go either into a data access layer or a data access extension.

namespace MyApp
{
    public class MyClass
    {
        public string id;
        public string name;
        public int quantity;
        public decimal price;
    }
}

namespace MyAppBL
{
    public static class MyClassBL
    {
        public static decimal PriceInCart(this MyClass myObject)
        {
            return myObject.quantity > 10 ? myObject.price * 0.9m : myObject.price;
        }
    }
}

namespace MyAppDA
{
    public static class MyClassDA
    {
        public static void Create()
        {
            …
        }

        public static void Read(string myObject)
        {
            …
        }

        public static void Update(this MyClass myObject)
        {
            …
        }

        public static void Delete(this MyClass myObject)
        {
            …
        }
    }
}

This give you a very nice myObject.PriceInCart() and myObject.Save() while keeping your class focused on the data. Of course for static methods you need to have MyAppDA.Create() instead of MyApp.Create().


问:
Does Open Source lead to bad coding?
I have a thought that I tried asking at SO, but didnt seem like the appropriate place. I think that source sites like Google Code, GitHub, SourceForge... have played a major role in the history of programming. However, I found that there is another bad thing to these kind of sites and that is you may just "copy" code from almost anyone, not knowing if it is good(tested) source or not.

This line of thought has taken me to believe that source code websites tend to lead many developers (most likely unexperienced) to copy/paste massive amounts of code, which I find just wrong.

I really dont know how to focus the question well, but basic thought would be:

Is this ok? Is Open Source contributing to that or I'm just seeing ghosts...

Hope people get interested because I think this is an important theme.

答:
At first there's no exact definition of good code. You may take two parts of good code and combine them, and get bad code. Just because code styles are different.

Bad programmer copy-paste bad code, write bad code.

Good programmer copy-paste good code, write good code. Good programmer will not paste bad code.

But open source give us great chance not write same code again and again, but

Title: Does Open Source lead to bad coding?


问:
Is curl something that's not expected to be installed on servers
Is curl something that's not expected to be installed on servers?
I'm working for a small development shop and 99% of the problems that I'm having is regarding curl. Most of the projects that I'm working on involves calling a web API. Most web API's suggests using curl by default since you have to pass in a POST data in the request. Every time I complain to my senior that the server that I'm working on doesn't have curl installed the excuse that I'm always getting is that curl is not needed you can always use file_get_contents.

So the question: is curl something that's not expected to be installed on servers that runs PHP, should I always develop using file_get_contents and not curl? Are there any advantages of using file_get_contents over curl or vise versa?

If it helps, the context here is wordpress plugins, shopify apps, drupal modules and other bits of code that a lot of people can install.

答:
The Requests library may be a good solution to your problem:
http://requests.ryanmccue.info/

This library will take care of falling back to another request method such as file_get_contents() if libcurl is not installed on the server.


答:
As Wyatt said, POCO and POJO in no way implies no methods. I think that stems from not knowing what non-POCO and non-POJO is.

First versions of ORM technologies weren't POCO and POJO simply because it required the entities to inherit some base class from the framework itself. In case of Java, Entity Beans .In case of Entity Framework, POCO wasn't possible in very first version and each entity was required to inherit Entity base class.

This requirement created dependence of your data model on the persistence technology, which makes lots of things hard or impossible. Things like unit testing the model requires mocking the bean/entity framework which proved to be practically impossible. You also cannot use the model with different persistence technology or you cannot use the model in different context, like in mobile environment.

So your assumption that POCO is about non-existence of methods is wrong. POCO is about being able to use the model in separation from it's persistence technology.

What you are talking about is probably closes to Anemic Domain Model vs proper domain model.

Title: .NET Programming and POCO classes


问:
Handling changes to data types and entries in a database migration
I'm fully redesigning a site that indexes a number of articles with basic search functionality.  The previous site was written about a decade ago, and I'm salvaging about 30,000 entries with data stored in less-than-ideal formats.  While I'm moving from MSSQL to MySQL, I don't need to make any "live" changes, so this is not a production-level migration issue so much as a redesign.

For instance, dates are stored the same as tags/subjects about the articles, but in strings as "YYYYMMDDd" (the lowercase d stands for "date" in the string).  Essentially, before or after I move from the previous database format to a new one, I'm going to need to do a lot of replacement of individual entries.  While I understand how to do operations with regular expressions in non-database issues, my database experience isn't robust enough to know the best way to handle this.

What is the best (or standard) way to handle major changes like this?  Is there an SQL operation I should be looking into?  Please let me know if the problem isn't clear--I'm not entirely sure what kind of answer I'm looking for.

答:
Have you considered writing some Java/C#/other language of your choice to do this? If this is just a one off Extraxt, Transform, Load process then you could just cobble together some code that reads rows from the original database, performs some transformation (eg: parsing the date string and converting it into a date object) before saving it to the new database. You can make this code as nice as you need/want: feel free to create POCO/DTO classes for both the old and new database designs and use an ORM tool like (N)Hibernate to handle the mappings. You can have a DateParser interface/base class that is appropriately implemented/extended. And so on.

While I appreciate that I haven't given you a concrete "Do it this way to solve your problem" answer, I hope the above information will get you moving in the right direction. For what it's worth, I recently worked in a team that specialised in data migration between a variety of systems and all this information comes from my experiences there. I am more than happy to expand on anything if you want more information, please just ask in the comments.


答:
Simply because Web performance really matters !
99% times it will give you faster end-user response times.

Here are a few exampels from Velocity Conf.

Bing – A page that was 2 seconds slower resulted in a 4.3% drop in revenue/user.

Google – A 400 millisecond delay caused a 0.59% drop in searches/user.

Yahoo! – A 400 milliseconds slowdown resulted in a 5-9% drop in full-page traffic.

Shopzilla – Speeding up their site by 5 seconds increased the conversion rate 7-12%, doubled the number of sessions from search engine marketing, and cut the number of required servers in half.

Mozilla – Shaving 2.2 seconds off their landing pages increased download conversions by 15.4%, which they estimate will result in 60 million more Firefox downloads per year.

Netflix – Adopting a single optimization, gzip compression, resulted in a 13-25% speedup and cut their outbound network traffic by 50%.

From Steve Souders, pioneer in Web Performance Optimization,

80-90% of the end-user response time is spent on the frontend - Start
  here first.

Using external files produces faster pages because the JavaScript and CSS files are cached by the browser/networks/proxies (as defined in HTTP protocol with Cache headers). JavaScript and CSS that are inlined in HTML documents get downloaded every time the HTML document is requested. This reduces the number of HTTP requests that are needed, but increases the size of the HTML document. If you're using Jquery-like scripts, it's easy to refrence 300 KB of scripts and do not believe that everyone has a 100 MBits/s bandwidth with low latency, running a single application -the browser- opened on your web site. 99% times it will give you faster end-user response times.

The frequency with which external JavaScript and CSS components are cached relative to the number of HTML documents requested is also important. If users on your site have multiple page views per session and many of your pages re-use the same scripts and stylesheets (bundles), there is a greater potential benefit from cached external files.

But inlining is -sometimes- preferable for single page application or web sites with one single page view per session. There is no golden rule, and generally forget it as it concerns mainly very specific web sites really involved by end-user performance.

You can read here why performance matters (Disclaimer : I am the author)


答:
Minimize duplicate coding. for save time (You can reuse the style and JS function coded for one page).

Minimize change effort. (If your client ask you to change the button color of the web site. you need to go one page by one ).

Reduce the load time (If your CSS and JS duplicate it means individual pages size increase and time consuming to download. but common CSS JS no need to download again and again).

Remote usage. (you can place your common CSS js JS in a remote place. not the same hosted server)

Reduce Bug fixing time. If there is a bug in one function you need to go page by page to fix the bugs in embedded JS and CSS.

To increase SEO (simply separate content with meta data)

Cleaner and understandably of code (If you embed all in one file debug and code clarity gone away. and each page will be a very long page).

Additionally this will help you to reduce the size of the product.

But still you can consider to embed most unique thing in the same page.


问:
How to manage potentially outdated data from WikiMedia API
I am writing a web application that pulls small parts of articles from Wikipedia and presents them to users.

I do not wish to delete entries of the articles because I do not want to be sending a ridiculous amount of requests to the WikiMedia API, putting unnecessary load on them.

My question is, since Wikipedia is by nature, collaborative and dynamic, what would be the best way to serve reasonably updated content to users (the content does not have to reflect the current article 100%, but it shouldn't be too far behind) without constantly querying their servers?

I'm leaning towards storing the snippets of the articles in my database along with a timestamp  and whenever an user requests an article with a timestamp over x days, I would re-query the API and update the entry in my database.

The other problem with that is I am grabbing the articles via client-side Javascript, then calling an API on my server to store it. Updating an article would look like:

User queries article -> my server returns article -> client-side checking decides the timestamp is too old -> client-side re-queries WikiMedia and displays the content to the user -> client-side fires request to my server to store the data.

This seems like it could be done better, but I do not want to be querying WikiMedia directly from my server...

How could I make this better?

Architecture: SlimPHP framework, RethinkDB + PHP driver, jQuery/JS, HTML, CSS

答:
It is not a good idea to store on your server data originating from (possibly malicious) client.

client-side fires request to my server to store the data.

Since client-side code is in hands of client, isn't it possible to feed your server with false data?

So your caching layer should decide which articles to reload on server side based on time since last synchronization, and possibly do synch on client demand.

To minimize load on peer servers you can request only HTTP header (see HEAD on Wikipedia and Responses). This way server responses instantly with no need to generate whole page dynamically.


问:
Where do service implementations fit into the Microsoft Application Architecture guidelines?
The guidelines discuss the service layer with its service interfaces and data/message/fault contracts. They also discuss the business layer with its logic/workflow components and entities as well as the 'optional' application facade.

What is unclear still to me after studying this guide is where the implementations of the service interfaces belong. Does the application facade in the business layer implement these interfaces, or does a separate 'service facade' exist to make calls to the business layer and it's facade/raw components?

(With the former, there would be less seemingly trivial calls to yet another layer, though with the latter I could see how the service layer could remove the concerns of translating business entities to data contracts from the business layer.)

答:
Think about a cake, each layer is put separately and contains all the ingredients that define this layer.

You can make a similar cake recipe with a different 3rd layer or use this layer in another cake recipe. If the layers taste good together (interfaces), the recipe (application) will work.

The goal of each layer is to provide different and specific tastes without mixing them together so that the tastes are easy to understand individually and easy to change.

The Service Layer is a specific component to interface your business with your UI or service clients and add another decoupling step between your final consumers and your business.
The implementation of the service interfaces does not contains -a lot of- business logic but is -only- a serving hatch to your Business Layer.

So yes, the implementations of these services interfaces are in the Service Layer and reflect only the contracts : don't do too much here, it is not your business (check the Design Considerations).

The Application Facade is another serving hatch to hide the inner logic of your business elements and provides an easier way to access the business logic. If you have of facade, your services should point to it.


问:
Session management in a Service Oriented Architecture
Where should you manage a users session in a SOA? Should you manage it in the Web Service or in the client and why?

My application is SPA
(Considering that this will be the stacked that will be used
Apache CXF for Web Services
AngularJS for making REST calls)

答:
I think session should be managed of Client side as far as possible in SPAs.In SOA ,  Mostly service are viewed as stateless and puting state logic inside it will be deviation. Servies ae meant to perform the task without botherig about sessions.
However maintaing session on client side increasese the complexity a lot.</p>


问:
Implementation of algorithm to generate chess positions
I am interested in developing a program that generates an endgame table-base for the chess.

I have gone through the technical papers of the greats like Shannon and Ken Thompson. I have found that retrograde analysis is used for the generation.

How can I generate all positions in a KBBK chess endgame which are mates in 0?

答:
The number of all possible possitions involving KBBK and a checkmate is not that great at all: 32 squares for the light-squared bishop * 32 for the dark-squared bishop * 62 for the White king (64 - 2 already taken by both bishops) * all squares where the Black king is checked by one of the bishops (it must be in check, otherwise it's not checkmate yet - or not a "mate in 0", if you prefer).

So - given that generating endgame tablebases is computationally intensive - you could easily find all the positions by brute force. It'll be super quick. It's a tiny fraction of total work you have to do anyway.

For all 63488 positions that KBB can occupy (and you could cut this number down because chessboard is symmetrical - 63448 / 2 (mirrored horizontally) / 2 (mirrored vertically) = 15862), so for every one out of these 15 thousands positions find all squares where Black king is checked by one of the bishops.

Now for each of these squares see if there is any square the Black king could go to to escape from check. If there isn't any - it's a checkmate position. Rinse and repeat.


问:
Scrum is methodology or framework?
I am confuse about scrum .it is methodology or Framework?.
I want to use scrum for development but i want to develop scrum tool but i am confuse scrum is methodology or framework?</p>

答:
Sources such as Scrum.org, Scrum Alliance, and even Wikipedia do refer to Scrum as a framework. Something to consider, though, is that Scrum is at the project management level, not at the product development level. It defines activities and artifacts to run a project and manage work, without any specifics as to how to go about designing, building, and testing software - those pieces will need to come from something else, although there are many common characteristics of the Agile methodologies.

However, although many sources call Scrum a framework, a purist would say that if you aren't doing everything that Scrum calls for, you aren't doing Scrum. That would imply that it's more of a methodology, a complete package that's meant to be used as-is (see ScrumBut for more on this). However, in reality, there are very few process methodologies that will work for everyone as-is, and some level of tailoring or adjustment is needed.

Title: Scrum is methodology or framework?


问:
Calculator with 3+ values
I am new to c++ and have been making the good old Calculator. I have gone forward from a 2 value calculator to a 3 value calculator and wondered.. How is it possible to make a 10 digit calculator (purely using +,-,*,/) that doesn't forever to code.. I have a if statement which returns what happens if the operators are + and + or + and - etc.. and if i was to go to 4 value, i would be writing 64 ifs, and 5 value would be 256 if statements.

Is there a way to change this such that it wouldn't require writing out so many if statements?

Here is my the important parts of the code:

Calculator.cpp:

```<code>#include "stdafx.h"
#include <iostream>
#include "headers.h"
using namespace std;

int main()
{
int nInput1 = GetUserInput();
char chOperation = GetMathematicalOperation();
{
    if (chOperation == '=')
    {
        cout << "The answer is: " << nInput1 << endl;
        return 0;
    }
}
int nInput2 = GetUserInput();
char chOperation2 = GetMathematicalOperation();
{
    if (chOperation2 == '=')
    {
        int nResult = CalculateResult(nInput1, chOperation, nInput2);
        cout << "The answer is: " << nResult << endl;
        return 0;
    }
}

int nInput3 = GetUserInput();

int nResult = CalculateResult2(nInput1, chOperation, nInput2, chOperation2, nInput3);

PrintResult(nResult);
}
</code>```

CalculateResult.cpp:

```<code>#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int CalculateResult(int nX, char chOperation, int nY)
{
if (chOperation == '+')
    return nX + nY;
if (chOperation == '-')
    return nX - nY;
if (chOperation == '*')
    return nX * nY;
if (chOperation == '/')
    return nX / nY;

return 0;
}
</code>```

GetMathematicalOperation.cpp:

```<code>#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

char GetMathematicalOperation()
{
cout << "Please enter an operator (+,-,*,/ or =): ";

char chOperation;
cin >> chOperation;
return chOperation;
}
</code>```

CalculateResult2.cpp:

```<code>#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int CalculateResult2(int nX, char chOperation, int nY, char chOperation2, int nZ)
{
if (chOperation == '+' && chOperation2 == '+')
    return nX + nY + nZ;
if (chOperation == '+' && chOperation2 == '-')
    return nX + nY - nZ;
if (chOperation == '+' && chOperation2 == '*')
    return nX + nY * nZ;
if (chOperation == '+' && chOperation2 == '/')
    return nX + nY / nZ;

if (chOperation == '-' && chOperation2 == '+')
    return nX - nY + nZ;
if (chOperation == '-' && chOperation2 == '-')
    return nX - nY - nZ;
if (chOperation == '-' && chOperation2 == '*')
    return nX - nY * nZ;
if (chOperation == '-' && chOperation2 == '/')
    return nX - nY / nZ;

if (chOperation == '*' && chOperation2 == '+')
    return nX * nY + nZ;
if (chOperation == '*' && chOperation2 == '-')
    return nX * nY - nZ;
if (chOperation == '*' && chOperation2 == '*')
    return nX * nY * nZ;
if (chOperation == '*' && chOperation2 == '/')
    return nX * nY / nZ;

if (chOperation == '/' && chOperation2 == '+')
    return nX / nY + nZ;
if (chOperation == '/' && chOperation2 == '-')
    return nX / nY - nZ;
if (chOperation == '/' && chOperation2 == '*')
    return nX / nY * nZ;
if (chOperation == '/' && chOperation2 == '/')
    return nX / nY / nZ;
return 0;
}
</code>```

答:
Probably what you want to try first is an RPN calculator.  With RPN, you push the numbers onto a stack, then pop them off when someone enters an operator.  It's easier to implement than an infix calculator, but lets you write arbitrarily long expressions and evaluate them as you go along.

The next step would be to use the shunting yard algorithm to convert an infix expression into an RPN expression.  It's too long to include the details here, but it is a well-known algorithm.

The next step would be to write a full expression parser, which is quite an advanced topic, but extremely flexible and useful.  There are many tools available to help you do this.

Either way, you probably want to do some research on stacks, queues and trees, and maybe try out a couple test programs using a stack before tackling a calculator again.  C++ has a stack implementation in its standard library that would be a good starting point to learn.

Title: Calculator with 3+ values


答:
Programming is all about data structures and algorithms. In your
example, there is no apparent data strcture: your functions are
working with raw user input and directly provide the answer, without
introducing any intermediary structure to represent the logic of
the computation.

As a practical consequence of the well-known equation

```<code>programs = data structures + algorithms
</code>```

the absence of adequate data structure forces you to represent
the logic of the computation in the algorithms part, that is,
in your code. This is why your code looks so complicated, with that
large number of ifs.  And your instinct is right, whenever your
code looks complicated, it shall ring a bell yelling there is
something wrong and that something is typically that you are using
the wrong data structure.

The abstraction you are missing here is what is called an algebraic
expression, which you can think of as an unevaluated expression.  So
now, I will answer your question on how to write your calculator—but I
strongly suggest you change the problem instead, and write another
type of calculator.

Here are the steps to write a calculator supporting arbitrarily
complicated expressions:

Implement Binary expression trees as an abstract class
Expression having two concrete descendants, one Leaf for the
numbers (leaves) and one other Node for the operations (nodes).

Follow the so called Visitor pattern to write an evaluator for
your expressions. You want to write an evaluator taking an
Expression and evaluating it, the Visitor pattern is the common
way to tell if the Expression is actually a Leaf or a Node.

Write a parser to transform user input into an
expression. This is a tedious task, but there is automatic tools to
help you there, such as Bison.

If you are a beginner, these three steps are challenging because they
will expose you to many new concepts of programming simultaneously:
abstract data structures, input/output and parsers.
A much more tractable exercise
is to write a reverse polish notation (RPN) calculator: with such a
calculator, instead of telling the
computer to compute 3 + 4 * 5 you tell it to compute 4 5 * 3 +
which greatly simplifies the logic of the program:

Instead of working with binary expression trees and thus with
abstract and concrete classes, you only work with a stack of
numbers: the data structure used is much simpler.

Because of 1., there is no need to use the contorted visitor
pattern.

Reading input and evaluate it is much easier in RPN
than in the usual infix notation, because there is no need
to pay attention to priority rules.

Once you are satisfied with your example, you can look for the program
bc(1) on a Linux box, it is a complete reverse polish notation
calculator, you may want to study its features or its code (in C) to
find more challenges!

Title: Calculator with 3+ values

Body:
I am new to c++ and have been making the good old Calculator. I have gone forward from a 2 value calculator to a 3 value calculator and wondered.. How is it possible to make a 10 digit calculator (purely using +,-,*,/) that doesn't forever to code.. I have a if statement which returns what happens if the operators are + and + or + and - etc.. and if i was to go to 4 value, i would be writing 64 ifs, and 5 value would be 256 if statements.

Is there a way to change this such that it wouldn't require writing out so many if statements?

Here is my the important parts of the code:

Calculator.cpp:

```<code>#include "stdafx.h"
#include <iostream>
#include "headers.h"
using namespace std;

int main()
{
int nInput1 = GetUserInput();
char chOperation = GetMathematicalOperation();
{
    if (chOperation == '=')
    {
        cout << "The answer is: " << nInput1 << endl;
        return 0;
    }
}
int nInput2 = GetUserInput();
char chOperation2 = GetMathematicalOperation();
{
    if (chOperation2 == '=')
    {
        int nResult = CalculateResult(nInput1, chOperation, nInput2);
        cout << "The answer is: " << nResult << endl;
        return 0;
    }
}

int nInput3 = GetUserInput();

int nResult = CalculateResult2(nInput1, chOperation, nInput2, chOperation2, nInput3);

PrintResult(nResult);
}
</code>```

CalculateResult.cpp:

```<code>#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int CalculateResult(int nX, char chOperation, int nY)
{
if (chOperation == '+')
    return nX + nY;
if (chOperation == '-')
    return nX - nY;
if (chOperation == '*')
    return nX * nY;
if (chOperation == '/')
    return nX / nY;

return 0;
}
</code>```

GetMathematicalOperation.cpp:

```<code>#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

char GetMathematicalOperation()
{
cout << "Please enter an operator (+,-,*,/ or =): ";

char chOperation;
cin >> chOperation;
return chOperation;
}
</code>```

CalculateResult2.cpp:

```<code>#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int CalculateResult2(int nX, char chOperation, int nY, char chOperation2, int nZ)
{
if (chOperation == '+' && chOperation2 == '+')
    return nX + nY + nZ;
if (chOperation == '+' && chOperation2 == '-')
    return nX + nY - nZ;
if (chOperation == '+' && chOperation2 == '*')
    return nX + nY * nZ;
if (chOperation == '+' && chOperation2 == '/')
    return nX + nY / nZ;

if (chOperation == '-' && chOperation2 == '+')
    return nX - nY + nZ;
if (chOperation == '-' && chOperation2 == '-')
    return nX - nY - nZ;
if (chOperation == '-' && chOperation2 == '*')
    return nX - nY * nZ;
if (chOperation == '-' && chOperation2 == '/')
    return nX - nY / nZ;

if (chOperation == '*' && chOperation2 == '+')
    return nX * nY + nZ;
if (chOperation == '*' && chOperation2 == '-')
    return nX * nY - nZ;
if (chOperation == '*' && chOperation2 == '*')
    return nX * nY * nZ;
if (chOperation == '*' && chOperation2 == '/')
    return nX * nY / nZ;

if (chOperation == '/' && chOperation2 == '+')
    return nX / nY + nZ;
if (chOperation == '/' && chOperation2 == '-')
    return nX / nY - nZ;
if (chOperation == '/' && chOperation2 == '*')
    return nX / nY * nZ;
if (chOperation == '/' && chOperation2 == '/')
    return nX / nY / nZ;
return 0;
}
</code>```

Body:
Programming is all about data structures and algorithms. In your
example, there is no apparent data strcture: your functions are
working with raw user input and directly provide the answer, without
introducing any intermediary structure to represent the logic of
the computation.

As a practical consequence of the well-known equation

programs = data structures + algorithms

the absence of adequate data structure forces you to represent
the logic of the computation in the algorithms part, that is,
in your code. This is why your code looks so complicated, with that
large number of ifs.  And your instinct is right, whenever your
code looks complicated, it shall ring a bell yelling there is
something wrong and that something is typically that you are using
the wrong data structure.

The abstraction you are missing here is what is called an algebraic
expression, which you can think of as an unevaluated expression.  So
now, I will answer your question on how to write your calculator—but I
strongly suggest you change the problem instead, and write another
type of calculator.

Here are the steps to write a calculator supporting arbitrarily
complicated expressions:

Implement Binary expression trees as an abstract class
Expression having two concrete descendants, one Leaf for the
numbers (leaves) and one other Node for the operations (nodes).

Follow the so called Visitor pattern to write an evaluator for
your expressions. You want to write an evaluator taking an
Expression and evaluating it, the Visitor pattern is the common
way to tell if the Expression is actually a Leaf or a Node.

Write a parser to transform user input into an
expression. This is a tedious task, but there is automatic tools to
help you there, such as Bison.

If you are a beginner, these three steps are challenging because they
will expose you to many new concepts of programming simultaneously:
abstract data structures, input/output and parsers.
A much more tractable exercise
is to write a reverse polish notation (RPN) calculator: with such a
calculator, instead of telling the
computer to compute 3 + 4 * 5 you tell it to compute 4 5 * 3 +
which greatly simplifies the logic of the program:

Instead of working with binary expression trees and thus with
abstract and concrete classes, you only work with a stack of
numbers: the data structure used is much simpler.

Because of 1., there is no need to use the contorted visitor
pattern.

Reading input and evaluate it is much easier in RPN
than in the usual infix notation, because there is no need
to pay attention to priority rules.

Once you are satisfied with your example, you can look for the program
bc(1) on a Linux box, it is a complete reverse polish notation
calculator, you may want to study its features or its code (in C) to
find more challenges!


问:
Is it a good idea to const-qualify the fields of structure in C?
Consider the following program:

```<code>#include <stdlib.h>
#include <stdio.h>

typedef struct S_s {
    const int _a;
} S_t;

S_t *
create_S(void) {
    return calloc(sizeof(S_t), 1);
}

void
destroy_S(S_t *s) {
    free(s);
}

const int
get_S_a(const S_t *s) {
    return s->_a;
}

void
set_S_a(S_t *s, const int a) {
    int *a_p = (int *)&s->_a;
    *a_p = a;
}

int
main(void) {
    S_t s1;
    // s1._a = 5; // Error
    set_S_a(&s1, 5); // OK
    S_t *s2 = create_S();
    // s2->_a = 8; // Error
    set_S_a(s2, 8); // OK

    printf("s1.a == %d\n", get_S_a(&s1));
    printf("s2->a == %d\n", get_S_a(s2));

    destroy_S(s2);
}
</code>```

I'm not aware of anything particularly bad with this kind of design, but there might be impact when compiler is heavily optimizing the code and some considerations I'm missing.

Is it a good idea to use const in C as a mechanism of write access control in such a way?

答:
No, using const in such a way is not a good idea.

By declaring your structure fields as const, you are declaring an intention that those fields will never change their value. If you then change the value after all, you are misleading both human readers of your code and the compiler. The first makes the code harder to understand and the second can be the cause for subtle bugs in your program.

If you want to avoid direct access to the members of your structure, then you can just use it as an opaque type:

```<code>//in s.h:
typedef struct S_s S_t;

S_t *create_S(void);
void destroy_S(const S_t *s);
int get_S_a(const S_t *s);
void set_S_a(S_t *s, const int a);

//in s.c
#include "s.h"
struct S_s {
    const int _a;
};

S_t *
create_S(void) {
    return calloc(1, sizeof(S_t));
}

void
destroy_S(const S_t *s) {
    free((S_t *)s);
}

int
get_S_a(const S_t *s) {
    return s->_a;
}

void
set_S_a(S_t *s, const int a) {
    s->_a = a;
}

// In main.c
#include "s.h"
int
main(void) {
    // const S_t s1; // Error: size of S_t unknown here
    S_t *s2 = create_S();
    // s2->_a = 8; // Error: members of S_t unknown here
    set_S_a(s2, 8); // OK

    printf("s2->a == %d\n", get_S_a(s2));

    destroy_S(s2);
}
</code>```

Body:
No, using const in such a way is not a good idea.

By declaring your structure fields as const, you are declaring an intention that those fields will never change their value. If you then change the value after all, you are misleading both human readers of your code and the compiler. The first makes the code harder to understand and the second can be the cause for subtle bugs in your program.

If you want to avoid direct access to the members of your structure, then you can just use it as an opaque type:

//in s.h:
typedef struct S_s S_t;

S_t *create_S(void);
void destroy_S(const S_t *s);
int get_S_a(const S_t *s);
void set_S_a(S_t *s, const int a);

//in s.c
#include "s.h"
struct S_s {
    const int _a;
};

S_t *
create_S(void) {
    return calloc(1, sizeof(S_t));
}

void
destroy_S(const S_t *s) {
    free((S_t *)s);
}

int
get_S_a(const S_t *s) {
    return s->_a;
}

void
set_S_a(S_t *s, const int a) {
    s->_a = a;
}

// In main.c
#include "s.h"
int
main(void) {
    // const S_t s1; // Error: size of S_t unknown here
    S_t *s2 = create_S();
    // s2->_a = 8; // Error: members of S_t unknown here
    set_S_a(s2, 8); // OK

    printf("s2->a == %d\n", get_S_a(s2));

    destroy_S(s2);
}


问:
Designing online exam
I need to design an online exam server for an exam like GRE in which question difficulty increases if you answer correctly and decreases if you answer wrong.

Questions are multiple choice questions

Difficulty scale of question is 1-10, 1 being the easiest and 10 being
  the hardest.

If two continuous questions are answered wrong, decrease the
  difficulty by 1 and if two questions answered right increase the
  difficulty by 1.

Test starts with a question of difficulty level of 4.

Question carries marks equal to its difficulty.

My question is: Which data structure should I use to store the questions?  Which is the best algorithm to fetch the question by its difficulty, etc.?

I am currently considering a doubly linked-list:

```<code>struct node {

    int data;
    node *prev;
    node *next;
    int n
    int MAX;
};
</code>```

Here, 2 n's we need to store.  One is MAX (actual size) and n is possible random size to pick questions from n - MAX we selected already for each double linked list you can add extra int data where you can store prev link, next link, pointer to array, int Maxdata(MAX size), int n(current size).

Each node is a pointer to an array of questions for each level.  If the answer is correct, it moves next node and picks the random questions from that list, otherwise it moves to the previous node and picks a question.

For example, let's say an array has 10 questions 1 - 10.  Since the array size is n = 10, you know that

now you selected a random question rand() % 10 = 6 th questions

now swap the question number 6 & 10, make n-- and return the 6th question

now n = 9 so next time 10th will not be considered

random will return 1 - 9 only

Is there any better way of doing it?

答:
A database table for your questions might look like this:

```<code>QuestionID          PK
Question            Text
Difficulty          Int
</code>```

Keep track of the questions already asked and answered in another table:

```<code>StudentID           FK
TestID              FK
QuestionID          FK
AnswerID            FK  (assumes multiple choice)
</code>```

Possible answers to questions (multiple choice):

```<code>AnswerID            PK
QuestionID          FK
Answer              Text
IsTheCorrectAnswer  boolean
</code>```

Title: Designing online exam

Body:
A database table for your questions might look like this:

QuestionID          PK
Question            Text
Difficulty          Int

Keep track of the questions already asked and answered in another table:

StudentID           FK
TestID              FK
QuestionID          FK
AnswerID            FK  (assumes multiple choice)

Possible answers to questions (multiple choice):

AnswerID            PK
QuestionID          FK
Answer              Text
IsTheCorrectAnswer  boolean


问:
Are 'The Pragmatic Programmer' and 'The Mythical Man Month' good books for people with limited practical experience programming
I was once told to read the books titled 'The Pragmatic Programmer' and 'The Mythical Man Month'. I have very little experience programming (basic HTML, CSS and JS).

If I were to purchase these books, read through them, would it be beneficial to me with such a limited understanding or would I benefit from them?

I ask because I am currently learning HTML5 and CSS3 from an online source and want some general reading material to add to my kindle.

答:
The Pragmatic Programmer is a book that deals with how you look at code and software as a whole and the process of writing the code.  It is primarily emphasizing the code that finds itself in a larger software project than one would typically find in javascript on web pages.  This isn't to say that the things that one learns while reading it won't be applicable (and some are very applicable at a universal level), but if you are working on things that will take you a few days at most and then move on to something completely different, the improvements that it gives you will not be as substantial.

If you find yourself working on projects that last weeks and months and remain working on the project with the same code base, the lessons that are in the pragmatic programmer are most applicable.  Quick one off scripts and tweaks to existing code is less likely to benefit from the book.  However, one will typically find themselves moving up to bigger projects as they learn more about the craft of coding and such will find the material in the book to become more and more applicable as they progress.

Consider lessons such as:

When is ok software good enough?

How bad is it to duplicate code?

What is an estimate?

When to use plain text (rather than machine friendly values)

Design by contract, assertions, and exceptions

The Mythical Man Month is a book about the lessons learned in the old days (that frequently need to be learned again and again) about project management.  To the extent that programmers find themselves dealing with project managers and need to know how to interact with them, its a good thing to know.  However, the lessons in there are not as often directly applicable to the code that one is writing.

Consider things such as:

Why does adding more people to a late project make it later?

How does one organize a software development team?

How does a project get a year late?

These things are not ones that programmers typically have to deal with - its more your manager and team lead that will find these things to be useful.  And, it needs to be taken with the appropriate grains of salt from the context - the book is old (and good - but its old).  Essays about bug rates in PL/I need to be taken in context that its PL/I and things have changed a little bit since then (though there's No Silver Bullet (that's another essay)).


问:
What can Go chan do that a list cannot?
I want to know in which situation Go chan makes code much simpler than using list or queue or array that is usually available in all languages.

As it was stated by Rob Pike in one of his speeches about Go lexer, Go channels help to organize data flow between structures that are not homomorphic.

I am interested in a simple Go code sample with chan that becomes MUCH more complicated in another language (for example C#) where chan is not available.

I am not interested in samples that use chan just to increase performance by avoiding waiting of data between generating list and consuming the list (which can be solved by chunking) or as a way to organize thread safe queue or thread-safe communication (which can be easily solved by locking primitives).

I am interested in a sample that makes code simpler structurally disregarding size of data.

If such sample does not exist then sample where size of data matters.

I guess desired sample would contain bi-directional communication between generator and consumer.

Also if someone could add tag [channel] to the list of available tags, that would be great.

答:
I want to know in which situation Go chan makes code much simpler than using list or queue or array that is usually available in all languages.

Let's say you have a routine that generates Fibonacci numbers (as a stand-in for something more complex). The main routine needs to "get the next number" when it needs it. The main routine should not be coupled to the Fibonacci routine, so it must not store the Fibonacci state.

So where do you store the Fibonacci state in between calls? In a language without threads/coroutines, you would have to write a lot of extra code to store this state, and that storage code would have to be changed every time you need to store slightly different state. That "store the state" code is brittle and has nothing to do with the actual calculation.

So it's much simpler to spin that routine off into it's own thread of execution. (real thread of language thread). Then we can ask it to generate the next value when needed and neither side worries about state. Yay.

You can use Arrays for this communication, but you will need to write a bunch of code: Locking the array (to prevent races), handling the "array full" case, handling the array wrap-around case, handling the array underflow case, etc. A queue is more similar, but doesn't have all the same semantics (not always mutithread safe, doesn't always wake up the receiver, etc)

Having a channel makes it 100 times more obvious what you are doing. Once you get used to channels, you will use them all the time. Not having channels is like not having a Map/Dictonary/Hash data structure. People survived for many years without them, but once you have them, you see all kinds of places they are useful. You'll start organizing your code around the CSP concept.

Gone are the days where you can buy a single-core computer (or even a single-core phone.) Therefore, communication between threads/processes is only going to get more important over time. If you (or your language) can only think in terms of single-CPU processing, you will be a dinosaur.

Concurrency is not parallelism, it's better.

Title: What can Go chan do that a list cannot?


答:
I was once told to read the books titled 'The Pragmatic Programmer' and 'The Mythical Man Month'. I have very little experience programming (basic HTML, CSS and JS). If I were to purchase these books, read through them, would it be beneficial to me with such a limited understanding or would I benefit from them?

No. Not at this point.

I ask because I am currently learning HTML5 and CSS3 from an online source and want some general reading material to add to my kindle.

Good. But don't feel obliged to read the resources "cover-to-cover".

Instead, find real problems(*) to solve and then solve them.

Mix in a dash of that HTML5 and CSS3 that you are learning.

Rinse and repeat.

Bonus points if you commit your solution to GitHub.

( * ) Find real problems that pertain to the technologies which you are learning.

(**) If small "one-off" problems are making you bored, try to create a brand-new application from scratch.

Title: Are 'The Pragmatic Programmer' and 'The Mythical Man Month' good books for people with limited practical experience programming

Body:
I was once told to read the books titled 'The Pragmatic Programmer' and 'The Mythical Man Month'. I have very little experience programming (basic HTML, CSS and JS).

If I were to purchase these books, read through them, would it be beneficial to me with such a limited understanding or would I benefit from them?

I ask because I am currently learning HTML5 and CSS3 from an online source and want some general reading material to add to my kindle.