问:
Why are people making tables with divs?
In modern web development I'm coming across this pattern ever more often. It looks like this:

```<code><div class="table">
    <div class="row">
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
    </div>
</div>
</code>```

And in CSS there is something like:

```<code>.table { display: table; }
.row { display: table-row; }
.cell { display: table-cell; }
</code>```

* (Class name are illustrative only; in real life those are normal class names reflecting what the element is about)

I even recently tried doing this myself because... you know, everyone's doing it.

But I still don't get it. Why are we doing this? If you need a table, then just make a blasted
 and be done with it. Yes, even if it's for layout. That's what tables are for - laying out stuff in tabular fashion.

The best explanation that I have is that by now everyone has heard the mantra of "don't use tables for layout", so they follow it blindly. But they still need a table for layout (because nothing else has the expanding capabilities of a table), so they make a
 (because it's not a table!) and then add CSS that makes it a table anyway.

For all the world this looks to me like putting arbitrary unnecessary obstacles in your way and then doing extra work to circumvent them.

The original argument for moving away from tables for layout was that it's hard to modify a tabular layout afterwards. But modifying a "faux-table" layout is just as hard, and for the same reasons. In fact, in practice modifying a layout is always hard, and it's almost never enough to just change the CSS, if you want to do something more serious than minor tweaks. You will need to understand and change HTML structure for serious design changes. And tables don't make the job any harder or easier than divs.

In fact, the only way I see that tables could make a layout difficult to modify, is if you abused them and created an ungodly mess. You can do that with divs too.

So... in an attempt to change this from a rant into a coherent question: what am I missing? What are the actual benefits of using a "faux-table" over a real one?

About the duplicate link: This isn't a suggestion to use another tag or something. This is a question about using a
 vs display:table.

答:
This is a common pattern for making responsive tables. Tabular data is tricky to display on mobiles since the page will either be zoomed in to read text, meaning tables go off the side of the page and the user has to scroll backwards and forwards to read the table, or the page will be zoomed out, usually meaning that the table is too small to be able to read.

Responsive tables change layout on smaller screens - sometimes some columns are hidden or columns are amalgamated, e.g. name and email address might be separate on large screens, but collapse down into one cell on small screens so the information is readable without having to scroll.

s are used to create the tables instead of
 tags for a couple of reasons. If
 tags are used then you need to override the browser default styles and layout before adding your own code, so in this case
 tags save on a lot of boilerplate CSS. Additionally, older versions of IE don't allow you to override default table styles, so using
s also smooths cross-browser development.

There's a pretty good overview of responsive tables on CSS-Tricks.

Edit: I should point out that I'm not advocating this pattern - it falls into the divitis trap and isn't semantic - but this is why you'll find tables made from divs.

Title: Why are people making tables with divs?

Body:
This is a common pattern for making responsive tables. Tabular data is tricky to display on mobiles since the page will either be zoomed in to read text, meaning tables go off the side of the page and the user has to scroll backwards and forwards to read the table, or the page will be zoomed out, usually meaning that the table is too small to be able to read.

Responsive tables change layout on smaller screens - sometimes some columns are hidden or columns are amalgamated, e.g. name and email address might be separate on large screens, but collapse down into one cell on small screens so the information is readable without having to scroll.

<div>s are used to create the tables instead of <table> tags for a couple of reasons. If <table> tags are used then you need to override the browser default styles and layout before adding your own code, so in this case <div> tags save on a lot of boilerplate CSS. Additionally, older versions of IE don't allow you to override default table styles, so using <div>s also smooths cross-browser development.

There's a pretty good overview of responsive tables on CSS-Tricks.

Edit: I should point out that I'm not advocating this pattern - it falls into the divitis trap and isn't semantic - but this is why you'll find tables made from divs.


问:
Why does CI stipulate that we should be able to rollback to any version of a software?
I was reading the book "Continuous delivery, reliable software deployments through build, tests and deployment automation ". And the author mentions that one should be able to rollback to any version of a software with one click.

I am wondering if this is really useful, and especially in the following scenarios :

You are working on web projects. Sounds to me that in this case, you don't really need the ability to rollback to any previous version. Being able to rollback the current release should be enough. Once it's deployed and working, why would you ever want to go back to a previous version ?

And actually this argument holds true if you are working on desktop applications.

Perhaps I misunderstood what he means by "being able to rollback to any version".

Does he mean the production environment or the development environment ? If it's the later that would make more sense - even if I still find it kind of unecessary for the web, source control branching should do the trick for desktop applications.

And still if it's the later, do you think that using tools like Entity Framework Code First Migration that allow you to recreate the database from the source code is enough to say that we have reach this standard ? Because then, with source control, we'd even have the referential data that need to be seeded for this particular version after the database is created.

答:
"Once it's deployed and working, why would you ever want to go back to a previous version ?" The key words here being "and working". In a perfect world, every new version would be thoroughly tested and completely accurate before it is deployed. But in real life, that doesn't always happen. What if you discover a critical bug that was introduced, not in the current version, but in the previous version? You many need to roll back two versions. Lots of applications these days, especially web sites, have a fairly high deployment rate. If you're putting out a new release every day, it wouldn't be shocking if a bug that was introduced three days ago wasn't discovered until today.

Even with a relatively slow release schedule, bugs could go undetected for a long period of time. Like many applications have "year end reporting". If we released a new version in January that created a bug in the year end reporting, it might go unnoticed for almost a year. (Whether rolling back a year's worth of releases is a practical solution, well, depends on the nature of the app and how much it is changing. Presumably any rollback is temporary, just until you get the current version fixed and can redeploy.)

ContentLicense: CC BY-SA 3.0


问:
Making a database and related operators using files and JSON in java
I'm trying to write a program that reads operations from a file. these operators look like below :

```<code>CREATE TABLE student(id:integer, gpa:decimal, name:string, family:string,isMale:Boolean)
INSERT INTO student(id,gpa,name,fami
SELECT id, name FROM student WHERE id=0
</code>```

then the program will have a parser that translates these lines and makes a database to do the operations.
after parsing and execution of each line ;a log will be made in a another file:

```<code>ERROR: Duplicate column name
family Table student created
ERROR: Table student already exists
ERROR: Invalid table name st
</code>```

as for the assignment I shouldn't use prepared packages for storing data like sql. so I've chosen JSON(JSON - simple) for making a more organized database and I will use regular expression for parser.

my first question is if I'm using the right tools for this task.

and my second question is how should I design the program so it will have a good OOP quality in respect to how classes and methods are written.

for example I'm writing a prototype code that reads simple lines from input file then simply splits them to an array and writes them into an output text file(see this question for the code I've written) . how should I design the objects.? should write and read parts be methods in a same class? should they be static methods?

答:
Should write and read parts be methods in a same class?

I would disagree with this because reading and writing are two separate responsibilities and if you want to follow good practices such as Single Responsibility Principle, I would separate them out into two classes. It might seem like an overkill but you will see that with your code growing in the future it will be easier to maintain.

If your code won't be growing and this is just a personal project then it is still a good idea to sharpen up your skills by following good practices.

Also, if you are dealing with databases I would change the name from Reader to Repository and from Writer to Persistence (you can append or prepend nouns to make them more specific of course).

Should write and read parts be methods in a same class? should they be static methods?

No. You should only use static methods, variables in an object-oriented world when you absolutely need to and you have a good argument. Bottom line is:

Don't use statics unless you really need to.

I would instead make the method nonstatic and new up the classes in your main method and call the read and write from the instance of the object instead.

Above is more general information for the future reference, however below you can find some more specific suggestions for changing your code:

1) Don't use global variables for jsonObject and output instead create them in your main method. As a matter of fact you don't even need jsonObject and output.

2) Let your reader method create jsonObject itself and populate it with data. Once data is populated on the newly created object you can then return it back.

3) Your writer method will also take a jsonObject and use that to write to the file.

4) The writer method doesn't really need to return anything.

Hope that makes sense.


问:
How to decide if object should request or receive data?
Deciding whether an object should request data (by calling a function) or receive data (by having a function called from another object) is probably dependent on the exact situation. So how do I decide how to handle this?

If a specific example could help:

I'm currently designing an app using the Kinect camera. I want to split the signal and pass it to multiple objects that process the data (there is some bookkeeping involved, because I need to dispose a frame before requesting the next one). What should I do? Get data from the Kinect and store it, so other objects can request it? Or should I pass the data to the objects that need it?

A drawing with generic names, arrows indicate how data should flow:

```<code>Kinect ---> KinectManager |---> DataProcessor
                          |---> DataHandler
                          |---> DataSomething
</code>```

My suspicion is the first case, because then I could have different objects request data, without KinectManager having to know about the objects. Though in the second case I could design an Interface with, for example, an Update() method that receives Kinect Data.

答:
Kinect manager can store Kinect data and emit an event or signal. Every other object listening to this event or signal can act upon it and retrieve these data.

This can be particularly useful if the other objects will not duplicate Kinect data to some other storage.


问:
What are common pitfalls of Cloud Development that you have run into?
I'm looking at beginning some work on a cloud based application and I'd be interested to hear of anybody's experiences of pitfalls they have run into particularly from a design/architectural standpoint when working with cloud platforms. Are there any expectations that might change significantly from regular web development practice? Things that you wish you had been aware of before you got started or that might have influenced your choice of platform had you been aware of them? I realise there are significant differences between the different options out there, but I feel there are significant enough similarities to warrant asking this as a general question.

Any experiences with particular platforms would also good- it would be interesting to see whether others have found similar things happening on other platforms too...

答:
The same pitfalls that people have on non-virtualized platforms.

Apps that don't scale horizontally.

Poor algorithm choices/implementations.

Absence of graceful reduction of features and performance in response to high load/ reduced resources.

Ignorance of the common/likely problems on the platforms you run on and having a plan to mitigate the those risks.

ContentLicense: CC BY-SA 2.5


问:
Is it possible to half-way synchronize javascript functions that include async calls?
I am wondering if there exists a way to half way synchronize javascript functions, where data is requested on the fly. I don't want to make it purely blocking (which I guess is impossible), I just want a nice way to write the overall algorithm in one piece.

Let's take the following example:

```<code>function(){
    command1;
    var x1 = something;
    async_function(x1, callback1);
}
function callback1(data){
    var x2 = command2(data);
    async_function2(x2, callback2);
}
function callback2(data1){
    command3(data1);
}
</code>```

I would like to write something like:

```<code>function(){
    command1;
    var x1 = something;
    call(async_function, [x1], callback1);
    var x2 = command2(data);
    call(async_function2, [x2], callback2);
    command3(data1);
}
</code>```

I tried playing around with the caller property of functions, but I'm not familiar enough with the execution environment.

I also tried writing a function "call" like above, using the apply function to pass in a custom callback which returns the result of the async function to it's caller.

What bugs me is that while programming\debugging, I have to follow the code from one function into another into another (just like the movie inception). I want one place to write the high-level algorithm without decomposing it into many functions.

For example, If I want to write A* algorithm, but the "getNeighbors" function is asynchronous.

答: Take a look on Promises/A+ https://promisesaplus.com/. Nice implementation of Promises/A+ instead of coming ecma6 native support is  https://github.com/tildeio/rsvp.js/</p>


问:
How can I close my Open Source project and what is required from me in order to make it closed source?
Let's say I wanted to close my "GPL v 2.0 (or similar)" licensed project, to which I'm the only contributor, and make it closed source.

Do I still need to make the existing "GPL v 2.0 (or similar)" licensed code available after closing the project or can I refuse giving out the source code for old revisions that was previously "GPL v 2.0 (or similar)" licensed?

Can I theoretically keep the the code "GPL v 2.0 (or similar)" licensed even after removing the public source code or do I have to distribute the source code if I'm using a "GPL v 2.0 (or similar)" license?

答:
This is really a legal question and I am not a lawyer. But from what I understand about contracts and software licenses in general:

(1) If you release software under an open-source license, then unless that license says that you have the right to revoke it -- in which case I don't think it would qualify as "open source" by definition -- then you cannot revoke the old license. You could certainly decide to stop providing new versions under open source. So you could take the open source product, use it as the basis for a new project, and then continue development of the new project as copyrighted software. But the portions that were released under open source would still be open source.

As I say, I'm not a lawyer, but I say this based on common understanding of contracts. If I sell you my used car for $2000, I can't come back a year later and say that I've changed my mind and I want another $1000 for it. We made a deal, a contract, and once it's agreed to I can't unilaterally change the terms. But just because I sold you a used car for $2000 doesn't mean that I am obligated to charge exactly $2000 for every future used car I might want to sell.

(2) Just because you released an open source project does not mean that you are obligated to continue to make the source available forever. There are lots of projects that have been started but then discontinued because the project became obsolete, the developer lost interest, the web site where it was being distributed went out of business, etc. Anyone who already has a copy could re-distribute it himself. Just like, if I give $20 to the Salvation Army today, I am under no obligation to give to them again next year. But I can't take back the money I gave them last year.


问:
What kind of base for Decorator: interface, abstract class, non-abstract
What should be at the top of inheritance tree of Decorator design pattern?
I mean the base for both components and decorators

non-abstract class: has data fields, implements methods

abstract class: has data fields, has only abstract (pure virtual) methods

interface: no data fields, has only abstract (pure virtual) methods

abstract class & interface: interface is the base for decorator, abstract class is the base for decorated components

Simple example

IText - interface declares getContent() method

AbstractText - abstract class  declares getContent() method and defines txt data
field

Text - non-abstract class, general, can be also used as base for other classes

HelloWorld  - non-abstract class, more specific than Text

HelloSomeone  - non-abstract class, extends Text with the data field name

Decorator abstract class for decorators (might be redundant?)

PrefixDecorator decorator class prefixes  getContent() with a string prefix

SuffixDecorator decorator class suffixes  getContent() with a string suffix

getContent() method that should return txt with optional additional data (suffixes and prefixes from decorators, name field in the HelloSomeone class)

What base class should be chosen?

non-abstract class

abstract class

interface

abstract class & interface

Code for last example

```<code>#include <iostream>
#include <string>
using namespace std;

/* Base for decorator & abstract: no fields, getContent()  is pure virtual */
class IText {
public:
    virtual string getContent() = 0;
    virtual ~IText() { }
};

/* Base: has a field, getContent()  is pure virtual */
class AbstractText : public IText {
protected:
    string txt;
public:
    virtual ~AbstractText() { cout << " AbstractText dtor" << endl; }
    AbstractText(string t = "...") : txt(t) { }
    virtual string getContent() = 0;
};

/* Concrete, general */
class Text : public AbstractText {
public:
    virtual ~Text() { cout << " Text dtor" << endl; }
    Text(string t) : AbstractText(t) { }
    virtual string getContent() { return txt; }
};

/* Concrete, more specific */
class HelloWorld : public AbstractText {
public:
    virtual ~HelloWorld() { cout << " HelloWorld dtor" << endl; }
    HelloWorld() : AbstractText("Hello world") {}
    virtual string getContent() { return txt; }
};

/* Additional field */
class HelloSomeone : public AbstractText {
private:
    string name;
public:
    virtual ~HelloSomeone() { cout << " HelloSomeone dtor" << endl; }
    HelloSomeone(string n) : AbstractText("Hello, "), name(n) { }
    string getContent() { return (txt + name + "!"); }
};

class Decorator : public IText {
public:
    virtual string getContent() = 0;
    virtual ~Decorator() { cout << " Decorator dtor" << endl; }
};

class PrefixDecorator : public Decorator {
private:
    IText *t;
public:
    PrefixDecorator(IText *te)  { t = te; }
    virtual ~PrefixDecorator() { cout << " PrefixDecorator dtor" << endl; delete t; }
    virtual string getContent() { return "---" + t->getContent(); }
};

class SuffixDecorator : public Decorator {
private:
    IText *t;
public:
    SuffixDecorator(IText *te)  { t = te; }
    virtual ~SuffixDecorator() { cout << " SuffixDecorator dtor" << endl; delete t; }
    virtual string getContent() { return t->getContent() + "---"; }
};

int main() {
    IText *t = new Text("some text");
    IText *hw = new HelloWorld();
    IText *hs = new HelloSomeone("Mark");
    cout << t->getContent() << endl;
    cout << hw->getContent() << endl;
    cout << hs->getContent() << endl;
    t = new PrefixDecorator(t);
    hw = new PrefixDecorator(hw);
    hw = new SuffixDecorator(hw);
    cout << t->getContent() << endl;
    cout << hw->getContent() << endl;
    cout << "DELETE Text" << endl;
    delete t;
    cout << "DELETE Helloworld" << endl;
    delete hw;
    cout << "DELETE HelloSomeone" << endl;
    delete hs;
}
</code>```

答:
What should be at the top of inheritance tree of Decorator design pattern?

How to discriminate:

non-abstract class - Only if it makes sense in your code to instantiate it in client code (also see: liskov substitution)

abstract class or interface - most common case; This is when it doesn't make sense for client code to instantiate it; To distinguish between abstract class and interface: If you look through your code and find that all specializations have data in common, move it to the base class (otherwise, remain with the interface).

abstract class and interface - if there are two cases when a part of your specializations have common code and a part don't, extract common code to separate class, and you end up with both cases.

My criteria is usually not derived from some pure rules that I respect to implement the decorator; Instead, I try to optimize for maintenance instead of purity.

You can also see that I do not particularly differentiate between abstract classes and interfaces; this is because in C++ there are no interfaces - only abstract classes (so the distinction feels a bit artificial).


问:
Too specific of namespacing/packaging
I'm about to start building a C# library for English and French morphology as a side project. The library will be later merged with other linguistic aspects (phonology, sentence parsing, etc). for other languages (Japanese and Russian).

Unfortunately, I have come across an issue in my design: my namespace hierarchy is a little crazy (in my opinion).

Here's the namespace for English sentence parsing (lexing stage):

Linguistics.English.Syntax.Parsing.Lex

The above namespace would include the necessary classes for using an existing English lexicon to parse a particular text.

The Japanese equivalent would be:

Linguistics.Japanese.Syntax.Parsing.Lex

They would be separate because the lexing process for each language is different. A more extreme example of the indicative present for French verb conjugations (inflections) would be:

Linguistics.French.Inflection.Verb.Indicative.Present

I know that I can just do using Linguistics.French.Inflection.Verb if I'm working on generating verb conjugation tables, but is the organization too specific?

More specifically, if/when do namespaces become too-specific? Am I being silly or is my concern actually a potential problem?

答:
Your question is opinion-based and open-ended, so I'm not offering anything undoubtedly acceptable, but

certainly, good naming is hard ← emphasis.

I've found many times that coming up with good names or good system of names if they can't be easily changed with the use of refactoring tools later on, once the pilot was delivered out to the wild, is more difficult then just writing code in between the coding convention hinted margins.

For instance renaming database tables and database fields while preserving the data and not breaking any stored procedures with dynamic queries is very tough technical task, best to be avoided. So good naming since the beginning can be very important sometimes.

That's why my advice is: before fixing down a namespacing rules, draw some inspiration from the name finding work already done by other developers developing linguistic libraries in programming languages supporting namespaces like Python, Java, C#...

Some lists of linguistic libraries:

Stack Overflow: Pluralize - Singularize

Stack Overflow: Java or Python for Natural Language Processing

From the above lists, NLTK (Python) and Stanford NLP (Java) look like libraries that should not be underestimated.

From the software design perspective, if you hide the language-specific implementation details behind interfaces and behind a factory pattern, then the language-specific libraries can use whatever internal naming convention they like, without exposing the names to the outside and without the risk of breaking anything.

That's what System.Data.Entity.Design.PluralizationServices.PluralizationService.CreateService Method does

Title: Too specific of namespacing/packaging


问:
Second Mainline Branch to Abandon Source Control Misuse?
I just learned about Source Control this week and came to the realization that my team uses it plain wrong.

One mainline to commit code to live. No other branches; that's it.

Branching features turned off for everyone except administrator

People create manual file backups and leave them littered around, because no branching

Working directories on shared drive: everyone edits the same files

Checkout is always exclusive, perhaps by design regarding shared drive files

Workflow is typically Edit-Checkout-ImmediateCheckin because of the exclusive locks. God forbid someone drops a project to work on something else and leaves it half-finished on the shared drive

The stigma is that source control is put into place for accountability reasons rather than for revision history: checking in to the sole live branch requires a support ticket "so we don't have another Office Space." Our test system is much more free: compile your file from the dev area and drop it into place in the staging area (also a shared folder) and see if it works. People like this freedom.

We are currently migrating our console applications to GUI, so a lot of things are being rewritten. I figure that this is the best time to introduce a change.

I was thinking about adding a second mainline for our new code that will "do it right this time," rather than clean up the mess we have now:

a new mainline for live code (if only for the new programs)

a Test Baseline branch under this new mainline for stable builds

on-demand workspace branches for new features and bugfixes

I've talked with two of four developers and have some buy-in from them, but they are concerned about the complications and extra steps it may bring to their workflow because they've never used branching before.

We use Surround SCM coupled with TestTrack for change request tickets, if that matters. I'm proposing checking in only to private workspace branches, then promoting branches up to mainline as we see fit.

答:
There's no need to start a new repository, just start branching.

Give leaders permission to merge onto trunk, everyone else must create a branch and commit their work there.  the only extra complication is having to create a branch (per ticket, recommended) and switch their working copy to the branch rather than trunk. You can get rid of the exclusive checkouts too at this point.

This will make things easier for devs, and will also give you a lot more traceability of what is on a release - it'll be only those branches that were merged to trunk. Once you have release day, you can also create a branch from trunk and call it something special so you have a snapshot of a release you could modify with those emergency bugfixes.


问:
Unix way of filtering/mapping/mapcatting records via the pipeline?
At home I use Linux and have for more than a decade.  At work we use Windows and so I find PowerShell more familiar.  I am a Linux/Unix fanboy at heart, but I've had greater success grokking the PowerShell pipeline.  The model of pipelining objects is useful because when it comes right down to it, in data processing we are often processing entities (things that have key/value pairs, i.e. attributes).

Clearly this is something Unix has been doing forever.  I suspect tools like sed and awk may play a part, but they're less intuitive to me.  In Unix you're piping raw text through the stream.  If you wanted to pipe operations over your personal address book you have to first consider how conducive the format of the incoming data is to pipeline processing.  I suspect that a record would appear on a single line.  I don't know if there's a community-favored data format/protocol for writing records that are easily piped between Unix programs.  Obviously, the format dictates what programs you use and how you use them (e.g. how you filter, map, and mapcat).

In PowerShell:

```<code>$input | ? { $_["contact_type"] -eq "Professional" } ;filtering
$input | % { $_["state_code"].ToUpperCase() }        ;mapping
$input | % { $_["phone_numbers"] -split ";" }        ;mapcatting
$input | % { $_["contact_type"] = "Friend"  }        ;mutating an attribute

;or when preferring to avoid mutation of the source data
$input | % { $h = $_.Clone(); $h["Surname"] = $_["Surname"].ToLower(); $h}
</code>```

I'm sure I could spend the day figuring out how I might accomplish this in Unix, but I am interested in something that is idiomatic and equal to the PowerShell legibility.  Choosing the right data format (CSV, XML, etc.) impacts the legibility of our pipeline logic.  It would feel awkward if the logic kept the line-of-text abstraction intact.  I would prefer some abstraction where the logic brings greater focus to the keys and values (i.e. the feel of "objects") than to the lines of text.

In Unix, if you could store your record data in any format what format would you pick in order to facilitate clear and concise pipeline processing?  Bash counterparts for the above examples would be appreciated.

答:
When bash and core utils are not enough, I turn to Perl. You can store your data in a text file, in XML, CSV, real database, or you have several serialisation modules available.

Once your contacts are in an array, you can easily apply all the operations (I don't know PowerShell, so they might not be exactly equivalent):

```<code>my @professionals = grep 'Professional' eq $_->{contanct_type}, @contacts;
my @upper         = map uc $_->{state_code}, @contacts;
my @numbers       = map { split /;/, $_->{phone_numbers} } @contacts;
$_->{contact_type} = 'Friend' for @contacts;
</code>```

The same applies to Python or Ruby.

Body:
When bash and core utils are not enough, I turn to Perl. You can store your data in a text file, in XML, CSV, real database, or you have several serialisation modules available.

Once your contacts are in an array, you can easily apply all the operations (I don't know PowerShell, so they might not be exactly equivalent):

my @professionals = grep 'Professional' eq $_->{contanct_type}, @contacts;
my @upper         = map uc $_->{state_code}, @contacts;
my @numbers       = map { split /;/, $_->{phone_numbers} } @contacts;
$_->{contact_type} = 'Friend' for @contacts;

The same applies to Python or Ruby.


问:
Does path coverage guarantee finding all bugs?
If every path through a program is tested, does that guarantee finding all bugs?

If not, why not? How could you go through every possible combination of program flow and not find the problem if one exists?

I hesitate to suggest that "all bugs" can be found, but maybe that is because path coverage isn't practical (as it is combinatorial) so it isn't ever experienced?

Note: this article gives a quick summary of coverage types as I think about them.

答:
What does it mean for every path to be tested?

The other answers are great, but I just want to add that the condition "every path through a program is tested" is itself vague.

Consider this method:

```<code>def add(num1, num2)
  foo = "bar"  # useless statement
  $global += 1 # side effect
  num1 + num2  # actual work
end
</code>```

If you write a test that asserts add(1, 2) == 3, a code coverage tool will tell you that every line is exercised. But you haven't actually asserted anything about the global side effect or the useless assignment. Those lines executed, but haven't really been tested.

Mutation testing would help find issues like this. A mutation testing tool would have a list of pre-determined ways to "mutate" the code and see if the tests still pass. For example:

One mutation might change the += to -=. That mutation would not cause a test failure, so it would prove that your test doesn't assert anything meaningful about the global side effect.

Another mutation might delete the first line. That mutation would not cause a test failure, so it would prove that your test doesn't assert anything meaningful about the assignment.

Still another mutation might delete the third line. That would cause a test failure, which in this case, shows that your test does assert something about that line.

In essense, mutation tests are a way to test your tests. But just like you'll never test the actual function with every possible set of inputs, you'll never run every possible mutation, so again, this is limited.

Every test we can do is a heuristic to move toward bug-free programs. Nothing is perfect.

Body:
What does it mean for every path to be tested?

The other answers are great, but I just want to add that the condition "every path through a program is tested" is itself vague.

Consider this method:

def add(num1, num2)
  foo = "bar"  # useless statement
  $global += 1 # side effect
  num1 + num2  # actual work
end

If you write a test that asserts add(1, 2) == 3, a code coverage tool will tell you that every line is exercised. But you haven't actually asserted anything about the global side effect or the useless assignment. Those lines executed, but haven't really been tested.

Mutation testing would help find issues like this. A mutation testing tool would have a list of pre-determined ways to "mutate" the code and see if the tests still pass. For example:

One mutation might change the += to -=. That mutation would not cause a test failure, so it would prove that your test doesn't assert anything meaningful about the global side effect.

Another mutation might delete the first line. That mutation would not cause a test failure, so it would prove that your test doesn't assert anything meaningful about the assignment.

Still another mutation might delete the third line. That would cause a test failure, which in this case, shows that your test does assert something about that line.

In essense, mutation tests are a way to test your tests. But just like you'll never test the actual function with every possible set of inputs, you'll never run every possible mutation, so again, this is limited.

Every test we can do is a heuristic to move toward bug-free programs. Nothing is perfect.


问:
Best way to define, start and stop threads in C#
I am making a little program, which have few Threads, constantly running.
At some point, I may want to stop one of them, and then, after random period of time, to start it again.
So first, what is the best way to define a Thread, here's my code

```<code>private void startCheckCommandThread() {
        isRunning = true;
        //commandThread = new Thread(checkForCommand);
        //commandThread.IsBackground = true;
        //commandThread.Start();

        new Thread(() => {
            Thread.CurrentThread.IsBackground = true;
            checkForCommand();
        }).Start();
    }
</code>```

The commented way, or the other one?
And here is how I am stopping and restarting them:

```<code>// get condition variable
if (condition) {
    isRunning = false;
    // here it must be 100% guaranteed that the Thread will stop
} else {
    startCheckCommandThread();
}
</code>```

So what is the best way to do it, mostly I am asking about stability (meaning error-proof) and maximum performance (as low CPU usage as possible, and as less memory allocation as possible)?

答:
With regards to the two ways of starting the thread, they are roughly equivalent, so it is a matter of whether you prefer a lambda.

For stopping the thread, the most error proof way is to check a field value for a change. This can be done using a memory barrier, for example, using a lock statement or a Monitor will automatically provide a memory barrier. The simplest way to synchronize the threads is to use a lock statement around all access and modification of a boolean field. The field would be contained in an object associated with the thread to be stopped.

When the variable changes, you exit the thread by returning from the top-level method that is executing in the thread.

Most developers do not "reuse" a thread. Once you exit it, it is gone -- you have to create a new one. You can reuse the object associated with the thread. While you could hold onto the thread, suspending it until you need it, generally this is considered poor design, as the thread is wasting resources while it is suspended. Also, it must block in such a way that it does not burn cycles while waiting.

If you are interested in maximum performance, you will may wish to look at synchronization using Interlocked. This is faster, but hard to use. Don't use it if you are just starting with multithreading. I recommend this web site for threading tutorials:
Threading in C#


答:
In the olden days, the table rendering engine "appeared" slower when you used percentages for column widths.  The engine essentially had to download the entire data set before it would then begin figuring out how big everything was to draw it on the screen.

The DIV engine was different.  As the browser encountered a DIV it would go ahead and place it and start filling the content inline.  Of course, div's might jump around as the data finished loading.  Hence why I have appeared in quotes above.  The time frame for completion of both was the same, however tables weren't drawn until the end which meant the user wasn't sure if it was loading or not for a second or two.

This became worse as tables were nested.

There were then (and still exist) ways to make table rendering FAR FAR faster.  Basically by giving it a hint that column sizes aren't changing, then the browser starts rendering tabular data immediately.  Ultimately this means that tables can actually display in the correct position faster than divs giving them the appearance of being better.

But that's not the whole story.  The rest of it is that most devs simply don't bother to learn their craft well enough to know this.  Instead they jump on various bandwagons and go with whatever code they can copy/paste from.  Even today I find that very very few web developers know the difference from one doctype to the next - and that is the number one reason why various sites have all sorts of workarounds to cover various browsers.

So, +1 to you for asking the question.

Title: Why are people making tables with divs?

Body:
In modern web development I'm coming across this pattern ever more often. It looks like this:

```<code><div class="table">
    <div class="row">
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
    </div>
</div>
</code>```

And in CSS there is something like:

```<code>.table { display: table; }
.row { display: table-row; }
.cell { display: table-cell; }
</code>```

* (Class name are illustrative only; in real life those are normal class names reflecting what the element is about)

I even recently tried doing this myself because... you know, everyone's doing it.

But I still don't get it. Why are we doing this? If you need a table, then just make a blasted
 and be done with it. Yes, even if it's for layout. That's what tables are for - laying out stuff in tabular fashion.

The best explanation that I have is that by now everyone has heard the mantra of "don't use tables for layout", so they follow it blindly. But they still need a table for layout (because nothing else has the expanding capabilities of a table), so they make a
 (because it's not a table!) and then add CSS that makes it a table anyway.

For all the world this looks to me like putting arbitrary unnecessary obstacles in your way and then doing extra work to circumvent them.

The original argument for moving away from tables for layout was that it's hard to modify a tabular layout afterwards. But modifying a "faux-table" layout is just as hard, and for the same reasons. In fact, in practice modifying a layout is always hard, and it's almost never enough to just change the CSS, if you want to do something more serious than minor tweaks. You will need to understand and change HTML structure for serious design changes. And tables don't make the job any harder or easier than divs.

In fact, the only way I see that tables could make a layout difficult to modify, is if you abused them and created an ungodly mess. You can do that with divs too.

So... in an attempt to change this from a rant into a coherent question: what am I missing? What are the actual benefits of using a "faux-table" over a real one?

About the duplicate link: This isn't a suggestion to use another tag or something. This is a question about using a
 vs display:table.


问:
What is proven as a good maximum length of a function?
Does function length affect the productivity of a programmer? If so, what is a good maximum number of lines to avoid productivity loss?

Since this is a highly opinionated topic please back up the claim with some data.

答:
Typically, I try to keep my methods/functions to what fits on the screen of a 1680x1050 monitor.  If it doesn't fit, then use helper methods/functions to parcel out the task.

It helps readability on both screen and paper.

ContentLicense: CC BY-SA 4.0


答:
I am making a little program, which have few Threads, constantly running. At some point, I may want to stop one of them, and then, after random period of time, to start it again. What is the best way to create a thread?

The best way is to not do it at all. If I have work that needs to be done in parallel to another program, the best practice is to start another process. If I have work that needs to be done asynchronously then I use the Task Parallel Library and let it manage my threads.

Threads are simply the wrong unit of granularity for most tasks. Threads are workers; rather than managing workers, instead manage tasks; let the TPL figure out how many workers are necessary.

mostly I am asking about stability (meaning error-proof)

Threading code is notoriously difficult to get right. You have to worry about coherency, memory barriers, non-atomic reads and writes, deadlocks, livelocks, ...  That's why using processes is far better.

If you have to keep everything in one process then use the highest level tool available. Again, do not attempt to manipulate threads directly. If you have asynchronous work to do, use the TPL. If you need to cancel some of that work, use cancellation tokens. Do not attempt to control threads directly; you will get it wrong.

If for some reason you don't want to use the TPL and you do want to use threads directly, then build a scheme whereby the threads communicate over well-defined, carefully-tested channels and have the code reviewed by experts. You don't ever want to abort a thread except under emergency conditions; doing so can corrupt your data structures in unusual ways. If you need a thread to shut down then you want to have a carefully designed and carefully implemented system that allows one thread to clearly signal another thread that it is time to shut down, and have that thread shut down cleanly.

and maximum performance (as low CPU usage as possible, and as less memory allocation as possible)?

I never understand why people say "I want to use threads to keep my CPU utilization low".  Threads are there to keep your CPU utilization high. You paid good money for those CPUs; use them!  The ideal situation is to have all the CPUs in your machine going at 100% all the time doing useful work. You wouldn't say that your goal was to build a factory where the workers were idle 95% of the time, so why would you do the same for a program?

Threads keep your CPU utilization high because if you're smart about it, you'll assign one thread of CPU-bound work to each CPU, and have that CPU do nothing else other than work on the problem you throw at it.  If you have more CPU-bound work than CPUs, and more threads to handle it, then the CPUs are going to be switching back and forth between threads and everything gets less efficient.

If you want to avoid memory allocation, by all means keep your thread count as low as possible. Threads are about the most memory-expensive resource you can possibly allocate. Each one by default consumes a million bytes of address space for the stack.

Title: Best way to define, start and stop threads in C#

Body:
I am making a little program, which have few Threads, constantly running.
At some point, I may want to stop one of them, and then, after random period of time, to start it again.
So first, what is the best way to define a Thread, here's my code

```<code>private void startCheckCommandThread() {
        isRunning = true;
        //commandThread = new Thread(checkForCommand);
        //commandThread.IsBackground = true;
        //commandThread.Start();

        new Thread(() => {
            Thread.CurrentThread.IsBackground = true;
            checkForCommand();
        }).Start();
    }
</code>```

The commented way, or the other one?
And here is how I am stopping and restarting them:

```<code>// get condition variable
if (condition) {
    isRunning = false;
    // here it must be 100% guaranteed that the Thread will stop
} else {
    startCheckCommandThread();
}
</code>```

So what is the best way to do it, mostly I am asking about stability (meaning error-proof) and maximum performance (as low CPU usage as possible, and as less memory allocation as possible)?


问:
Should I always throw the most specific or should I try to generalize exception types?
Say you normally have FooException.

```<code>/**
 * @throw FooException If Foo is invalid for searching.
 */
public bool exists(Foo a)
</code>```

But at some point you need to have two more specific exceptions for Foo.

```<code>/**
 * @throw FooSearchException (extends FooException) When "a" caused the error.
 * @throw FooReplacementException (extends FooException) When "b" caused the error.
 */
public int replace(Foo a, Foo b)
</code>```

Because you want be able to know which of the two parameters caused the error.

At this point, what should I do with the exists() method? Should I change it to throw the most specific Exception type or should I keep it generalized as much as possible to uniquely identify a problem in a single routine? The exists() method doesn't need to differentiate between Search and Replacement parameters, but it is still about a Search. What should I do?

(Note that the change won't affect existing catch()es since both FooSearchException and FooReplacementException extend FooException)

答:
Throw the most specific exception that already exists. It does no harm to the caller who doesn't care and will just catch the more general common superclass, but adds useful extra flexibility to a caller that distinguishes between them.

Be eager to change existing code from general → specific. It shouldn't break code, after all.

Be wary of changing existing code from specific → general, as that is more of a breaking change. If you realise another case should also be catered for though, then you've no choice: Never fake a general exception with a more specific case that does not apply.

Don't be inconsistent in your specificity though: Imagine a method that took an x and a y parameter and if x is out of a specific range throws an "argument out of range" exception, but if y is out of a specific range throws a general "argument" exception because catch it along with catching other issues with y. The result would just be confusing. (It is though fine to e.g. throw "argument out of range" if x or y are out of their respective ranges and "argument exception" if the combination of x and y is outside some collective range).

What I'm not covering here is the question of when to create another exception type to be more specific than what you have already got, which is a much more involved question. I will though say that I think it's worth considering them as "costing" something; if you're "spending" then what are you getting for your expense?


问:
What are arguments for Commercial Off the shelf (COTS) products?

Why should a company invest in a Commercial Off the shelf (COTS) product?

Is it the cost of in-house development, support or are there other reasons to not buy an COTS product?

By Commercial Off the shelf (COTS) products I mean products such as SharePoint, SAP, MS Dynamics. Not Word/Excel/Outlook.

By company I refer to a large enterprise.

答:
Based on experience, especially with a platform such as ERP, that companies use to run their business, it is quick for Management to go for the COTS ERP platform rather than actually look at what is already working, currently in use or look at other open source platforms that have a large support structure and following.
I hate to name products here but if anyone who knows ERP platforms, knows which ERP product I am talking about.

I see top down implementations and decisions being made, where the users are told that the purchase was a management decision, that everyone will have to work with it and that the company already invested too much in it. Have you ever heard of Black Swans?

Big commercial ERP's are presented as flexible and modifiable to your business process. You are given the usual 6 month time frame for implementation and a year later you are still in deployment mode. Users are hating it, it recreates work flows and departments have to spend tons of time and money re-training users on the new work flows. When it is not in place within six months, more money is thrown at it and more contractors are hired to work on issues that should have been identified if they took the bottom up approach.

Listen to your users, adapt current work flows to your ERP modules instead of just saying that is how "ERP" works. Forbid any changes are required to be made on the module, it usually means more money and time. They always give you the same old answer.

I work in a support group and our focus is our customers. We have SLA's we have to meet and the last thing we need is a support platform that creates more problems than the actual support issue. Everything should be designed to ensure that we meet our SLA's but the shift then becomes  that the company becomes internally focused as opposed to external, watching for our customers needs. Support staff spend way too much time making sure that each work order or ticket is filled out a specific way rather than actually having a tool for documenting how the issue of the client was received, troubleshot and resolved.

So, if asked whether I prefer COTS to in house? I would maybe select COTS products with good user feedback but really think about it if it were to run my whole business. Both have pros and cons like support, flexibility, system integration, upgrades and patches, and other system growth development.


问:
How do I find a good middle way to make this library safe for concurrent operations
I've made a little library called SignalR.EventAggregatorProxy

Before I push it into 1.0 state I need to fix so it works safely with concurrent operations. Easiest way is lock all operations but thats a huge performance impact.

The library queues event subscriptions and when a event comes in it checks the subscriptions and updates the clients using SignalR

This is the class that holds the subscriptions

There are 3 methods that write/read to the subscription collection(s) (I aggregate the subscription both on a client level and event level, so its two collections)

Subscribe

UnsubscribeConnection

Unsubscribe

And one that that reads

Handle

I realize since this is a library I can't make it optimum for all users of the library, but how do I find a good middle way that does not use locks?

I think the Handle method is the most important method and should be prioritized for performance over the other 3.

I made this little Unittest to test for Concurrency fail

update:
I choose to have locked writes and unlocked reads. The writes didnt mutate existing state but overwrite the collection completely.

答:
Don't.

It's not a static class, and they aren't static methods, so there's no reason why it shouldn't be up to calling code to avoid concurrent calls.

With static methods, then you would have to do some of the work to make it handle concurrent calls because calling code can't guarantee that it is the only calling code.

And of course with instance methods specifically geared at synchronising data-access or otherwise where being hit simultaneously by multiple threads is part of the point of it, then of course you have to be able to have that concurrent use.

But otherwise, you're just in the way. You're in the way of the user who knows they only ever hit the methods one at a time and so don't need any locking. You're in the way of the user who knows they hit the methods with several threads and therefore have coded a concurrency-handling strategy suitable to their use. And at the time of writing you're really in the way of someone who locks on the EventProxy object itself because you're using lock(this) so you're locking on an object the writer of the calling code should be able to think of as "theirs".


问:
Changing a design later down the track seems time consuming for its value
(For those who don't code, don't be intimidated by the code snippets in this question, they question is about approach to changing a design rather than the code design itself).

Recently I put forward  a technical design that looks like this

```<code>public class MyDatabaseLayer
{
    public ResponseCode runQuery(Query q)
    {
        try
           {
              //do database stuff
           }
        catch
            {
               //catch database exceptions (like bad username/password) and put them into a user friendly ResponseCode
            }
        return r;
    }

}
</code>```

However according to the 'throw early, catch late' principle, my design should look more like this:

```<code>public class MyDatabaseLayer
{
    public ResponseCode runQuery(Query q) throws SomeDatabaseExceptions
    {
        //do database stuff without handling exceptions
        return r;
    }
}
</code>```

The question is, it's already late in the design phase, and I've already thought about how the original solution would work.

The project is quite simple, and so I'm sure that there will be no problems in either coding the solution, nor modifying it in the future.

I think that changing the design at this stage is just going to delay it and have me going around in circles without actually delivering a working product.

The question is, what techniques are there for dealing with this kind of issue, of whether I refactor the code to make it 'perfect' vs getting on and delivering it as 'good enough'?

答:
I think that changing the design at this stage is just going to delay
  it and have me going around in circles without actually delivering a
  working product.

I think this is the money quote. You are not there to write good or beautiful code. You are there to create software that creates value for someone and that is sold. Good design is not a goal in itself. It is desirable only insofar as it allows you to create better software, e.g., by making it easier to maintain or to extend.

Agile software development addresses exactly this issue. The agile way of looking at you issue would be to deliver the suboptimal agreed-upon design now to have a working piece of software as soon as possible... but be very open to refactoring later.

There of course is a lot of leeway involved here. Nobody advocates just sitting down to code "to get something working fast" without planning what you are doing and doing actual design work beforehand. But if you feel the impulse of deviating from a planned course of action before having a working product, to improve design, then agile software development would tell you to step on that impulse and not act on it. Get something out the door, collect feedback, and then think about refactoring.

OwnerDisplayName: dwjohnston

OwnerDisplayName: Stephan Kolassa


答:
What's the Right Size, Really?

Depends on the language you use, but in general (and for my personal taste):

Ideally, less than 25 lines.

Acceptably, less than 35 lines.

If it's more, then it's something I need to come back to later and rework.

But realistically, any size it needs to be when you need to deliver something and that it makes more sense on the moment to spit them out like that, makes it even easier sometimes for someone to review before shipping. (but still get back to it later).

(Recently my team ran a program on our codebase: we found class with 197 methods and another with only 3 methods but one of them was 600 lines. Cute game: what's the worse of the 2 evils?)

Now for a more zen answer... In general it's considered a good practice (TM) to quote one or two great men, so here goes:

Everything should be made as simple as possible, but not simpler. - A. Einstein

Perfection is finally attained not when there is no longer anything to add, but when there is no longer anything to take away. - A. de Saint Exupéry

Addendum on Comment Styles

As an addendum to this, your functions should have clear names explaining their intent. Regarding comments, I usually don't comment inside a function:

comments say "why?",

code says "how?".

A comment block at the top of each function (that requires explanation) is enough. If your function is small and function names are explicit enough, then you should just need to say what you want to achieve and why. I use inline comments only for fields in some languages or on block starts for functions that break that 25-35 line rules if the intent is unclear. I use a block comment inside the code when an exceptional situations occurs (a catch block where you don't need or want to do anything should have a comment saying why, for instance).

For more, please read my answer on Style and recommendations of commenting code

Title: What is proven as a good maximum length of a function?

Body:
Does function length affect the productivity of a programmer? If so, what is a good maximum number of lines to avoid productivity loss?

Since this is a highly opinionated topic please back up the claim with some data.


答:
Ask yourself three questions:

Do we have the resource to change the design now? If not, leave it alone.

Is a design change now likely to add more value to the product over its lifetime? If not, leave it alone.

Is there something better that I could be doing with my resources? If so, do it instead.

The point of doing anything, be it building software, designing a product, doing chores etc. is to replace a low value alternative for a higher one. for example, I clean my kitchen floor because I value its cleanliness over the effort it takes to clean it.

So, if "improvements" to a design are intended to make it confirm to a certain design principle, but don't add any real value, then there is no point in making them.

The problem with all this is that nobody can be cerain what will happen in the future. This means that any effort I put in to improving things today might well be wasted effort. For example, I get the oil in my car changed regularly because doing so will, hopefully, help to extend its life. However, if my car gets written off just after an oil change then I've wasted my money.

The solution to this dilemma is to make a best guess based on the information that I have available. As an aid to doing so, people have come up with rules or principles that guide them in ways to add most value at least cost. This is where things like software design principles come in, but similar heuristics can be applied to many other areas of life.

The challange is picking the right principle at the right time. Of coruse, there are no hard-and-fast rules for doing so, but fortunately, there are (not surprisingly) principles that you can apply.

Here are some:

Understand why something is considered best practice.

Understand the the types of situations to which the principle pertains

... and to which it doesn't.

Compare these to your current situation.

Unsterstand the cost of imlementing the principle.

...and the benefits that are likely to result from applying it.

Determine whether you have the resource to apply the principle now.

Learn from experience, both yours and that of others who have done similar work.

Consider whether you could make incremental improvements, rather than trying to change everything all at once.

One final thing to remember is that costs and benefits are complex and often slippery things. Going back to my example of cleaning my kitchen floor, the time I spend cleaning it has both immediate benefits (it looks nicer), mid-term benefits (my wife is happy, and our relationship improves as a result) and long-term benefits (it lasts longer, we're not likely to pick up nasty diseases from the mouldy stuff that festers in the corners). The immediate benefits may not seem so important... but some of the others are critical. Many of the benefits of good design in software are similar. In particular, good design frees up "headspace" that can be used to solve other - often deeper - problems.

Title: Changing a design later down the track seems time consuming for its value

Body:
(For those who don't code, don't be intimidated by the code snippets in this question, they question is about approach to changing a design rather than the code design itself).

Recently I put forward  a technical design that looks like this

```<code>public class MyDatabaseLayer
{
    public ResponseCode runQuery(Query q)
    {
        try
           {
              //do database stuff
           }
        catch
            {
               //catch database exceptions (like bad username/password) and put them into a user friendly ResponseCode
            }
        return r;
    }

}
</code>```

However according to the 'throw early, catch late' principle, my design should look more like this:

```<code>public class MyDatabaseLayer
{
    public ResponseCode runQuery(Query q) throws SomeDatabaseExceptions
    {
        //do database stuff without handling exceptions
        return r;
    }
}
</code>```

The question is, it's already late in the design phase, and I've already thought about how the original solution would work.

The project is quite simple, and so I'm sure that there will be no problems in either coding the solution, nor modifying it in the future.

I think that changing the design at this stage is just going to delay it and have me going around in circles without actually delivering a working product.

The question is, what techniques are there for dealing with this kind of issue, of whether I refactor the code to make it 'perfect' vs getting on and delivering it as 'good enough'?

OwnerDisplayName: Kramii


问:
Measuring new capabilities in a software project and comparing vs incremental capability improvement
Given two software projects X and Y relating to some Product A -

Project X offers some new capabilities.

Project Y offers incremental capabilities.

Y's features  can be measured: we know its uses, access patterns, etc. Product A understands how to monitor Y and quantify its improvements.

Project X offers totally new capabilities; these capabilities will combine with existing project A capabilities as well as other, unplanned, ways. How do you quantify the unexpected ways that users will use it in? In particular, what kind of ROI can you reckon for Project X, what kind of % improvement to your customer base will happen?

An example might be: do you maintain a library in your standard company components, or do you build a totally new one?

Or, do you continue working with your PHP installation, or do you make a leap to Haskell?

Or, do you deliver an improved feature, or a totally new feature?

A glance through the software engineering Google search seems to only give standard source code metrics; product management search gives only standard business metrics.

答:
The way you measure the ROI depends on the effect of the projects on the overall product. For totally behind-the-scenes work (library improvement or replacement, implementation language, etc.), you would probably look at server load, system performance, defect rate, future/estimated engineering time savings, etc. For a user-facing feature, you would look at things like customer satisfaction, defect rate, user engagement rates, etc.

In your case, I think you would measure project X the same way you measured project Y when it was new. If you are unsure whether to do X or not, then you basically have to make an educated guess. This is risk, and it is unavoidable. You can do a cost/benefit analysis to determine if the rewards justify the effort.

If you cannot expect or predict the ways in which users will use the results of X, then there is no way to measure them beforehand. What you can do is mock up X, show it to some users, and observe their reaction. Use a prototyping tool or some quick and dirty code as a proof of concept. This may give you a sense of how the proposed feature will be received and used.


答:
For me, a function is any length it needs to be. Most of the time that I divide it up is when I will reuse code.

Basically, I'll stick to the principal 'high cohesion, low coupling' and there is no constraint on length.


问:
Server and Client apps that will send files and other info to each other
I am trying to do a Server and Client programs, that will communicate with each other, but I can't figure out the best way to do it, so let me explain what I need:

The Server app should be able to accept both files and other info (like string arrays, if possible) from the client app.

The client app must be able to receive commands from the Server app (like SEND_REPORT, STOP_SELF....)

The whole server-client communication should be direct

I have tried using a FTP server for that, but it requires a third party program for that to work (unless I make my Server app a FTP server itself).
So now I am trying to do it with TcpClient and NetworkStream, but I figured out there would be no way to distinguish if the sent info is a file, or a simple string array.

Here is what I have so far, the server side code:

```<code>private void handleClient(TcpClient client) {
        NetworkStream stream = client.GetStream();
        stream.WriteByte(1);
        FileStream fileStream = File.Open(le_path, FileMode.Create);
        int read;
        int totalRead = 0;
        byte[] buffer = new byte[1024];
        while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) {
            fileStream.Write(buffer, 0, read);
            totalRead += read;
        }
        fileStream.Dispose();
        client.Close();
    }
</code>```

This code does create a file, but it is bugged, or I don't know, it never leaves the while loop and never goes to Dispose and Close... I can access the file, when I close the program.

Here is the client app code:

```<code>client = new TcpClient();
client.Connect(serverIP, serverPort);
byte[] file = File.ReadAllBytes(Constants.TARGET_PATH_LOGS + "squad.jpg");
byte[] fileBuffer = new byte[file.Length];
NetworkStream stream = client.GetStream();
stream.Write(file, 0, fileBuffer.GetLength(0));
</code>```

So here is what I am asking you:

If this is the best way to do it, how can I make the receive code recognizes if it's a file that is sent, or a simple array list data, and how do I make it able to accept any file (meaning to properly get it's name, metadata...)

If not, please tell me another way to do what I need.

答: npinti provides a good example of some code, but in general what you are doing is a very common scenario. The server you are looking to make is a basic web service, often these days using a RESTful API model over HTTP. The client packs up some data in a predefined format of your choosing, and transmits its to a URL of your choosing on the server. The server can send messages to the client using something like WebSockets, which work like simple TCP/IP connections but can pass through most firewalls.</p>


问:
Rethrow the same exception to provide more info
Is it a good practice to rethrow the same exception to provide more specific information? For example:</p>

```<code>var sitemap = "a string containing an XML document";
try {
   // throw InvalidXmlException if the document is not well formed
   parse(sitemap);
} catch (InvalidXmlException e) {
   throw new InvalidXmlException("The sitemap is not well formed: " + e.getMessage());
}
</code>```

答: Generally the rule for exceptions is, don't create a new exception type, and don't re-throw, unless you are sure that the caller is going to be able to do something different with the new information you provide (i.e. you are providing more information, such as a better error message, or you provide information to recover).</p>


答:
Providing more context information is always good. But there is an issue in the code that I wanted to point out (perhaps an issue with the API - the underlying exception class). You are not passing the root cause. Don't append e.getMessage() it may be redundant. Instead set the root cause like this

```<code>catch(SameExceptionClass e) {
    throw new SameExceptionClass("Some more Details", e);
}
</code>```

When this exception gets printed it will contain your message from e and the additional details you just added. If your exception class doesn't accept the root cause consider adding a constructor that can accept it. Not providing root cause leads to problems related to "swallowed" exceptions, where you will not know the real point where the original exception occured.

But yes do this ONLY if you feel you will add more value or more context info in your new exception.

Title: Rethrow the same exception to provide more info

Body:
Is it a good practice to rethrow the same exception to provide more specific information? For example:</p>

```<code>var sitemap = "a string containing an XML document";
try {
   // throw InvalidXmlException if the document is not well formed
   parse(sitemap);
} catch (InvalidXmlException e) {
   throw new InvalidXmlException("The sitemap is not well formed: " + e.getMessage());
}
</code>```

Body:
Providing more context information is always good. But there is an issue in the code that I wanted to point out (perhaps an issue with the API - the underlying exception class). You are not passing the root cause. Don't append e.getMessage() it may be redundant. Instead set the root cause like this

catch(SameExceptionClass e) {
    throw new SameExceptionClass("Some more Details", e);
}

When this exception gets printed it will contain your message from e and the additional details you just added. If your exception class doesn't accept the root cause consider adding a constructor that can accept it. Not providing root cause leads to problems related to "swallowed" exceptions, where you will not know the real point where the original exception occured.

But yes do this ONLY if you feel you will add more value or more context info in your new exception.


答:
What should be the maximum height of a building? Depends on where the build is, or the height you want it to be.

You may get different answers from different people which come from different city.

Some script functions and kernel interrupt handlers are very long.


答:
There's something else here that no one has mentioned yet: Abstraction.   Perhaps more importantly, leaky abstractions?

Does it make sense to let your DataService throw an IO or Database exception? I'd say no, because it "leaks" the underlying implementation to the client code. Your FooController shouldn't care whether DataService is talking to a database or file system. All it needs to know is that the data it asked for couldn't be retrieved. So, yes. Re-throw the exception and add the additional information (properly preserving the stack trace) at the proper level of abstraction. In the example I provided, at the level of the DataService.


问:
Is there a common reason a more technical/traditional web developer should use a CMS for his/her own purposes?
Note

When this question was originally posted months ago, I worded it to sound relatively neutral.  Whereas it has been answered in a way that seems probably valid and that I would be tempted to accept, I think I just really need to update the question to bring my basic concern front-and-center at the beginning, leaving all the earlier, more neutral contents in place:

As far as I have seen, CMSs get in the programmer's way a lot for what seems to be little to no benefit for a developer.  Maybe a journalist needs this kind of hand-holding to build a website, but when I tried a CMS out myself (it was WordPress), there was zero perceivable benefit, even in terms of content management!  Do a programmer, an artist, and a journalist all need to work together in a way that the artist and journalist can change their content without involving the developer?  Fine - that's why you put content in its own separate files and code accordingly.  Do you need to load the same, updated contents in multiple places? Use scripting languages and such to accomplish this. You do not need a CMS that disables and hinders the programmer in many ways in order to do this.

It was not my intention to put something like this at the top, but I think part of the problem I'm having understanding this is not being communicated well below, so I've put this at the top for clarity.  If someone can answer this in a way I can understand, I'll pretty much accept their answer.

The Concept of a CMS

The basic idea behind a CMS is to combine web development, artistry, journalism, and so on into a single, user-friendly* aggregate, by which an organization can not only develop a website, but also better coordinate such an effort and potentially more easily automate certain parts of the process.

.

.

.

*...Well..."user-friendly" seems to be somewhat conditional on there being a team of people working together on a project, particularly if they are not all programmers.

Background behind the Question

I remember being tested by an organization some time ago to see if I could write something in particular and get it up and working on a cloned WordPress instance, and part of this had to do with the fact that I had not previously been exposed to WordPress.  In fact, this was my first time using a CMS, and I developed a little bit of a bad taste for the concept.  What should have been a relatively trivial programming assignment with HTML, CSS, JavaScript, and PHP turned out to be a minefield just trying to circumnavigate all sorts of seemingly unreasonable restrictions, assumptions, and so on built in to the CMS.

I'm going to come back to the positive side of a CMS in just a second, but first some example negatives in the case of WordPress:

PHP was not supported natively.  If memory serves me correctly, it took a plugin to enable it, not a configuration change.

It was unnecessarily difficult to read, let's say, a list of countries out of a json file.   The file had to be stored in an unnatural location to make WordPress allow it to be read by JavaScript, and the simple fact that the file's extension was .json was something WordPress felt was "too dangerous" or "too complicated and low-level" for a normal programmer to ever want to deal with.

Line breaks were inserted into the HTML, without user feedback to the developer, even when the HTML was written directly by using the code editor.  And I know there's a setting in the WordPress configuration to change this, but aside from having to run back to the system administrator to get read/write access to the installation files to change it, their documentation gives you two function calls to insert into a certain file without telling you where in that file to insert them.  Put them in the wrong place (the file is thousands of lines long), and WordPress won't work.  - This breaks JavaScript containing blank lines for formatting.

And before it was over with, there got to be maybe 20 or so different completely unnatural roadblocks I had to get around to implement a very basic contact form.

So now the positive side:

Months later I attended a WordCamp with an open mind, hoping to find out why so many people would prefer this over "ordinary" web development.  The basic answer I got out of that is more-or-less the following:

You're not always going to work with other programmers.  Especially if you have a somewhat popular site, then artists, journalists, bloggers, musicians, and other kinds of talented people will either become a part of the team or work alongside it.  Oftentimes your non-programmer clientele will need to make frequent changes to the website (sometimes altering the way data is presented, not just the data itself), and having a nice, big GUI that acts like a server with multiple users that manages this - and helps automatically integrate content into code - can really save time, trouble, and stress.

Alright...So what if you don't have non-programmer artists, journalists, bloggers, etc. consistently involved?  And in particular, what if you're the only one who's really making very many modifications to the site?

Yes, you can separate content from presentation through a CMS, but if you code like you're supposed to, it'll already be quite separate in your files and site structure.

And yes, people keep saying there are all sorts of plugins, but is that any better to a programmer than there being all sorts of SDKs in more code-style development platforms?  What's more is that, at least in the case of WordPress, many of these plugins are there for no other reason than to get past serious roadblocks imposed specifically by the fact that you're using the CMS (such as points 1 and 2).

Personal Opinion

I'm not sold very much on the idea of a CMS at all, even when coordinating with more artist-like people.  It's too much trouble for what appears to be too little gain.  As a general rule, every layer of abstraction costs you the ability to do and to control certain things you may want to utilize, and a good programmer will mostly separate content from code anyway.

This is enough to allow clients to just copy and paste files with the content over an FTP or something without assistance from the developer.

I know my experience has only been with WP, but supposedly, 20% of web developers these days use it.  I honestly saw very little reason to use a CMS, at least until they really improve...BUT I am trying to keep an open mind and listen for things I may have missed.

The Question

So something I have been wanting to ask on here for a while, because nobody has explained this very well:

The idea of a CMS is fairly popular right now.  Many people almost automatically flock to one, even if they are experienced web developers accustomed to using text editors.  Why would you want to do this, thereby introducing certain kinds of obstacles, in situations where you're not dealing with a bunch of people who are not programmers?

答:
It's a tool, like any other tool.  If it's a poor version of the tool, you look for a better quality one.

I've often thought that a Wiki would be a good tool to have in any software development shop.  Basically, what you want is a giant searchable electronic multimedia diary, where everyone can contribute.  While it has some of the features of a CMS or DMS (including the ability to link and categorize documents), it also has the ability to chronicle the thoughts, difficulties, solutions and conversations that the developers have, so that they can return to it later for reference.

Sound familiar?

You don't need artists to maintain such a repository.  You just need people with the willingness to communicate.


答:
The best way to manage threads is to not do it.

Use of threading is not an objective, it is a means to an end, viz. concurrency. In C# we achieve concurrency without direct thread management by virtue of async/await, or sometimes (as mentioned by others) lambda expressions, most commonly via PLINQ.

It is expensive, slow and subject to availability to start and stop threads. Instead, the above approaches use a pool of preallocated threads. The resources are marshalled at set up and tear down of the process by code written by people with significant thread management experience.

They also have access to the platform developers, and full scale test teams who also have appropriate experience. It is unlikely that any application development team can match that.


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
Things I would like, as a former long-time PHP apologist:

Shorter syntax for arrays. PHP arrays are one of the awesomest features of the language because of their flexibility, but it's a drag to write some_array_method($argity, array('key' => $value));. I believe this proposal was already eviscerated on the PHP mailing list unfortunately.

finally support

Attributes/annotations. These allow you to add custom behavior to a method in a way that allows code reuse. For example, in an MVC framework, one could define an AuthorizeAttribute that would indicate that a controller or action method requires the user to be authorized. The framework itself would be responsible for looking for the attributes and acting on them accordingly. I believe PHPUnit already uses a sort of attribute by putting them in docblock comments, which can be read using reflection, but putting actual functionality in docblock comments is certainly a hack.

Shorter lambda syntax. Instead of having to write function($x){ return $x*2;}, maybe I could write $x => return $x*2, or something. This is again something just sort of makes it a drag to use this feature. For example $results = array_filter(array(1,2,3), function($a) { return $a % 2; }): vs $results = array_filter(array(1,2,3), $a => return $a % 2 ); The former just has so much more plumbing that's basically irrelevant to the actual work you're trying to accomplish.

A built-in Decimal (fixed-point math) that supported math operations through the normal operators would be kind of nice, since we don't have operator overloading.

MOAR MAGIC METHODS. Magic methods are great. I could see PHP adding operator overloading via magic methods (I know this will basically never happen.) But in general, they provide really great ways to hook into the language and do cool things.


问:
How do sites like SquareSpace and Wix support multiple design templates?
How do these guys do it? I've worked on a couple multi-tenant sites and I have a hard time wrapping my head around how you would go about having each page of your site support many designs. Sure you could create a partial for each page or module for each template but that seems like a maintenance nightmare.

How would you architect a site that can support multiple design templates? I'm most familiar with Ruby on Rails but am looking for a more high level answer.

答:
Generally speaking, the way this works is to have "components" that themselves have HTML structure, but allow their positioning within "cells" within the template. You might choose a layout that has a large cell and then three smaller cells beneath it, for example; you could then put a big image slider component in the big cell, and images with captions in the cell below. Once you have the data model, the implementation of controllers is relatively trivial.

Visually, the example above might look like this:

```<code>[       1       ]
[ 2 ] [ 3 ] [ 4 ]
</code>```

There may be another template that is simpler, something like a blog with a sidebar:

```<code>[    1    ] [ 2 ]
</code>```

There would be options for components that can be inserted into the template. You may see an image slider, for example; a blog component that pulls from a configurable back-end field; a simple photo with a caption; an ad. A rendering process might look like this:

Determine which site is being requested.

Look up the template for the site.

Look up the configured components for the site.

Do a union of all of the data requirements for the components.

Perform a query (or a few) for the data requirements.

Provide the data to the views and render them.

It is complicated in a few ways, but fundamentally it isn't very different from typical web application rendering.

Body:
Generally speaking, the way this works is to have "components" that themselves have HTML structure, but allow their positioning within "cells" within the template. You might choose a layout that has a large cell and then three smaller cells beneath it, for example; you could then put a big image slider component in the big cell, and images with captions in the cell below. Once you have the data model, the implementation of controllers is relatively trivial.

Visually, the example above might look like this:

[       1       ]
[ 2 ] [ 3 ] [ 4 ]

There may be another template that is simpler, something like a blog with a sidebar:

[    1    ] [ 2 ]

There would be options for components that can be inserted into the template. You may see an image slider, for example; a blog component that pulls from a configurable back-end field; a simple photo with a caption; an ad. A rendering process might look like this:

Determine which site is being requested.

Look up the template for the site.

Look up the configured components for the site.

Do a union of all of the data requirements for the components.

Perform a query (or a few) for the data requirements.

Provide the data to the views and render them.

It is complicated in a few ways, but fundamentally it isn't very different from typical web application rendering.


问:
An algorithm for finding converse duplicates of ordered pairs
Given an array of ordered pairs of values, what algorithm will find converse duplicates? [Converse meaning the same values, but in the opposite order.]

That is, given [ab,ac,ad,bc,bd,ca,db] is there an efficient way to find ca and db, being the converse duplicates for ac and bd?

The application is simple enough: the ordered pairs are edges in a directed graph and if there is a converse edge then a single double-ended edge is to be drawn rather than one edge in each direction. The values are strings, being node names.

It can be viewed as a lookup in a sparse array. Given coordinates (a,b), check whether (b,a) exists. However, common programming languages do not (appear to) provide sparse 2d arrays.

I have written a solution in ruby using hash-of-hash, but it's about 20 lines of awkward code and an unsatisfying outcome. Writing the same code in a language like C# or Java would be longer. A better solution is sought, in pseudocode or a description (steps) of the algorithm. Either way, I am seeking an answer that describes how to find the solution as well as the benefits and drawbacks of the particular algorithm.

I haven't attempted to define 'efficient' or 'better', and performance is not an overriding consideration for a drawing of a few hundred nodes.

The nodes are not sorted, so the default algorithm would be, for each pair, to form the converse and brute-force search the preceding half. A binary search would require a prior sort. A solution based on hash indexing should be much faster.

答:
Here's a way...in python

```<code>ordered = lambda x, y: (x, y) if x <= y else (y, x)

def make_hash(edges):
    edge_hash = {}
    for x,y in edges:
        edge = ordered(x, y)
        edge_hash[edge] = edge_hash.setdefault(edge, 0) + 1
    return edge_hash

edges = ['ab', 'ac', 'ad', 'bc', 'bd', 'ca', 'db']

for edge, count in make_hash(edges).items():
    print ''.join(edge), 'uni' if count == 1 else 'bi'
</code>```

It creates a dictionary (hash) that is indexed by the sorted order of the edges. If there are two entries, we know it is has a converse duplicate. If only one, it is not. The dictionary is returned and the count of matching (in any order) entries.

Body:
Here's a way...in python

ordered = lambda x, y: (x, y) if x <= y else (y, x)

def make_hash(edges):
    edge_hash = {}
    for x,y in edges:
        edge = ordered(x, y)
        edge_hash[edge] = edge_hash.setdefault(edge, 0) + 1
    return edge_hash

edges = ['ab', 'ac', 'ad', 'bc', 'bd', 'ca', 'db']

for edge, count in make_hash(edges).items():
    print ''.join(edge), 'uni' if count == 1 else 'bi'

It creates a dictionary (hash) that is indexed by the sorted order of the edges. If there are two entries, we know it is has a converse duplicate. If only one, it is not. The dictionary is returned and the count of matching (in any order) entries.


问:
Why are objects instantiated this way?
Some times I see an object instantiated this way.

```<code>ICustomer oCustomer = new Customer
</code>```

Obvious but the Customer class is implementing ICustomer interface in this example. Are there any advantages of instantiating an object that way? From my understanding, if a class in implementing an interface it is already following the contract. What is the name of that practice and is there a disadvantage of instantiating an object "normal"(what I usually do) way? I know there are already some existing questions out there, but they don't really highlight the advantages and disadvatages

Interface instantiation vs class instantiation

```<code>Customer oCustomer = new Customer
</code>```

答:
There is one, very important distinction that I think that you're overlooking.

The code you provided is for three things: the declaration of a variable, the instantiation of an object, and initializing that variable with that object.

There is no interface implementation here. Customer needs to implement ICustomer (or do one or two other tricks) for that to compile successfully, but there's no actual implementation going on here.

Now that the terminology is out of the way, let's focus on the meat of the problem: is one better?

This sort of thing falls into the realm of program to an interface. When you declare your variable, you need to give it a type. That type should define the sort of things the variable can do. It is a contract you make with future programmers (or yourself) that oCustomer can only do these sorts of things. You should decide this contract regardless of the source you use to initialize the variable.

If this variable only needs the interface, then using the interface as its type is clearly defining what it can (and can't) do. If this variable really needs to be a full Customer, then double check that you really need that. If you do, then go ahead and make it a Customer. This provides clear communication to future programmers (or you) that the variable needs to be of that type. And if the variable is just some placeholder for your initializer; if its type doesn't really matter, then use var.

The benefits of programming to an interface are described in depth in the link above, but they boil down to allowing you to be flexible. Software inevitably changes. By coding to an interface, you allow this code to remain blissfully unaware when Customer changes - or if you need tomorrow to initialize oCustomer with a VipCustomer instead.

This sort of thing applies in many places throughout programming, not just variable declarations.

Title: Why are objects instantiated this way?


答:
How you create it is not better or worse in any way.

Let's think about it:

You either set objects or get objects (i.e. passing them into a constructor, method or returning them from a method).

In either case as long as you are providing an interface for setting and getting you can new up your object in any way you want because either way you will be able to leverage polymorphism, abstraction and encapsulation - and that's the whole point of the whole program to interface not to implementation principle, which is what your core question is about.

Title: Why are objects instantiated this way?

Body:
Some times I see an object instantiated this way.

```<code>ICustomer oCustomer = new Customer
</code>```

Obvious but the Customer class is implementing ICustomer interface in this example. Are there any advantages of instantiating an object that way? From my understanding, if a class in implementing an interface it is already following the contract. What is the name of that practice and is there a disadvantage of instantiating an object "normal"(what I usually do) way? I know there are already some existing questions out there, but they don't really highlight the advantages and disadvatages

Interface instantiation vs class instantiation

```<code>Customer oCustomer = new Customer
</code>```