问:
How to make sure that reported issues are not caused by wrong credentials or typos of the client?
I have found myself a few times in the situation where a client reports an issue like 'I can no longer login to my account'.

Sure enough when trying to login with the client's credentials myself everything works. After that, you start testing in other environments and situations, but still it works every time.

After numerous tests you start to wonder if the user is using the right credentials. Some clients get offended when asking this. Others are so sure that they enter the right credentials, they don't even bother trying the credentials that you send them.

How can I make sure that the client is using the right credentials?

答:
You can't, because the user is already convinced that he/she is using the right credentials.

The best that you can do is to reset their account and inform them of their new password along with instructions on how to proceed.

If you have access to their 'old' password (which is a security risk of itself), then you could just send out a reply telling the user that you have 'changed' their password to that value and that they should use that password from now on.


问:
Word recognition in a string without spaces or punctuation marks
I have a small C# project that reads a file and gives me an output: a string that does not contain spaces nor any types of punctuation marks. It may also contain a few misspellings.

Ex.
Output:
 THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG

I wonder if there is a way to analyze this string by using text mining/data mining and/or regular expressions to indentify the words (preferably nounds, verbs and so forth.) in the string?

I want to read a bunch of files giving me different outputs and put them in statistical order from the one with the most found words to the one which only contain a string of mumbo jumbo.

Also, if the string contain misspellings like:

THEQUICGBROWNFOSJUMPSOVERTHHLAZYDOG

I know that regular expression can calculate the "distans" from a misspelled word and find the most matching one (using a corpus and probability) but this might prove more of a challenge as the string does not have any spaces or punctuation marks.
Any ideas how I can solve this?

答:
Here is the general approach:

Read a dictionary file and organize all words in a trie data structure. Many Unix systems have such files in the /usr/share/dict/ directory.

Find possible matches of a prefix of your input in the trie. This will usually produce multiple matches, for example theologyisabout begins with theology and the.

If we remove the matched prefixes, we get a set of possible continuations, on which we repeat step 2.

We then end up with a vast tree of possible interpretations.

There are two problems with this:

there will be an exponential amount of interpretations

we might miss interpretations because of an unknown word, or some unknown grammatical form

We can solve both of these problems by fuzzy matching. When we look up prefixes in the trie, we allow letters to be missing, inserted or changed. However, each such aberration increases the Levenshtein distance. If one interpretation has a too high  summed Levenshtein distance, we can prune that interpretation and concentrate on other branches. You could also keep the branches in a priority queue and always investigate the branches with the lowest current edit distance, which is most likely to be a sensible interpretation – not unlike Dijkstra's pathfinding algorithm.

Note that multiple prefix sequences with different edit distances might lead to the same remaining string. You can therefore keep your progress in a data structure that allows parts to be shared. This caching will likely be beneficial for performance. If you in fact try to implement a variant of Dijkstra's algorithm here, a known tail would correspond to a visited node in the graph.

The difficult part is how to actually perform the fuzzy matching. E.g. you could decide on a maximum edit density of x edits per character (0 <= x <= 1), and abort an interpretation if it is guaranteed that this interpretation will have a higher density. For a given string with length l we can therefore determine an edit budget b = x · l. This budget is less important when matching prefixes in the trie, but this trie is only useful if there are less edits than characters in the prefix. An edit budget like b = floor(c / 2) with a prefix of length c might be sensible. How much edits you allow is not only a metric for how garbled texts you allow your system to “understand”, but also a performance setting – smaller budgets run faster, as less alternatives have to be investigated.

ContentLicense: CC BY-SA 3.0


问:
How would another popular language avoid having to use the factory pattern while managing similar complexity as in Java/Java EE?
Factory pattern (or at least the use of FactoryFactory..) is the butt of many jokes, like here.

Apart from having verbose and "creative" names like RequestProcessorFactoryFactory.RequestProcessorFactory, is there anything fundamentally wrong with the factory pattern if you have to program in Java/C++ and there is a usecase for Abstract_factory_pattern?

How would another popular language (for example, Ruby or Scala) avoid having to use it while managing similar complexity?

The reason I am asking is I see mostly the criticism of factories mentioned in the context of the Java/Java EE ecosystem, but they never explain how other languages/frameworks solve them.

答:
As so often, people misunderstand what's going on (and that includes many of the laughers).

It's not the factory pattern per se that's bad as much as the way many (maybe even most) people use it.

And that no doubt stems from the way programming (and patterns) is taught. Schoolkids (often calling themselves "students") get told to "create X using pattern Y" and after a few iterations of that think that that's the way to approach any programming problem.

So they start applying a specific pattern they happen to like in school against anything and everything, whether it's appropriate or not.

And that includes university professors who write books about software design, sadly.

The culmination of this was a system I had the distinct displeasure of having to maintain which had been created by one such (the man even had several books about object oriented design to his name, and a teaching position in the CS department of a major university).

It was based on a 3 tier pattern, with each tier itself a 3 tier system (have to decouple...). On the interface between each set of tiers, on both sides, was a factory to produce the objects to transfer data to the other tier, and a factory to produce the object to translate the received object to one belonging to the receiving layer.

For each factory there was an abstract factory (who knows, the factory might have to change and then you don't want the calling code to have to change...).

And that whole mess was of course completely undocumented.

The system had a database normalised to 5th normal form (I kid you not).

A system that was essentially little more than an address book that could be used to log and track incoming and outgoing documents, it had a 100MB codebase in C++ and over 50 database tables. Printing 500 form letters would take as long as 72 hours using a printer connected directly to the computer running the software.

THAT's why people scoff patterns, and specifically people focusing singlemindedly on a single specific pattern.


答:
In general, there is this trend that Java programs are horrendously over-engineered [citation needed]. Having many factories is one of the most common symptoms of over-engineering; that's why people make fun of those.

In particular, the problem Java has with factories is that in Java a) constructors are not functions and b) functions are not first-class citizens.

Imagine you could write something like this (let Function be a well-known interface of the JRE)

```<code>// Framework code
public Node buildTree(Function<BranchNode, Node, Node> branchNodeFactory) {
    Node current = nextNode();
    while (hasNextNode()) {
        current = branchNodeFactory.call(current, nextNode());
    }
    return current
}

// MyDataNode.java
public class MyBranchNode implements BranchNode {

    public MyBranchNode(Node left, Node right) { ... }
}

// Client code
Node root = buildTree(MyBranchNode::new);
</code>```

See, no factory interfaces or classes. Many dynamic languages have first-class functions. Alas, this is not possible with Java 7 or earlier (implementing the same with factories is left as an exercise to the reader).

So, the alternative is not so much "use a different pattern", but more "use a language with a better object model" or "don't over-engineer simple problems".

Title: How would another popular language avoid having to use the factory pattern while managing similar complexity as in Java/Java EE?

Body:
Factory pattern (or at least the use of FactoryFactory..) is the butt of many jokes, like here.

Apart from having verbose and "creative" names like RequestProcessorFactoryFactory.RequestProcessorFactory, is there anything fundamentally wrong with the factory pattern if you have to program in Java/C++ and there is a usecase for Abstract_factory_pattern?

How would another popular language (for example, Ruby or Scala) avoid having to use it while managing similar complexity?

The reason I am asking is I see mostly the criticism of factories mentioned in the context of the Java/Java EE ecosystem, but they never explain how other languages/frameworks solve them.

Body:
In general, there is this trend that Java programs are horrendously over-engineered [citation needed]. Having many factories is one of the most common symptoms of over-engineering; that's why people make fun of those.

In particular, the problem Java has with factories is that in Java a) constructors are not functions and b) functions are not first-class citizens.

Imagine you could write something like this (let Function be a well-known interface of the JRE)

// Framework code
public Node buildTree(Function<BranchNode, Node, Node> branchNodeFactory) {
    Node current = nextNode();
    while (hasNextNode()) {
        current = branchNodeFactory.call(current, nextNode());
    }
    return current
}

// MyDataNode.java
public class MyBranchNode implements BranchNode {

    public MyBranchNode(Node left, Node right) { ... }
}

// Client code
Node root = buildTree(MyBranchNode::new);

See, no factory interfaces or classes. Many dynamic languages have first-class functions. Alas, this is not possible with Java 7 or earlier (implementing the same with factories is left as an exercise to the reader).

So, the alternative is not so much "use a different pattern", but more "use a language with a better object model" or "don't over-engineer simple problems".


问:
Was getting a computing science degree easier 10 years ago
I am currently a 3rd year computing science student at a Canadian University. I find it quite challenging, and extremely interesting. One thing  that i have noticed is that each person i speak to that took a class 3 or so years ago learned much less than i did in the same class, and people who are taking 1st year classes are doing more than i remember doing in my 1st year classes. Is this just me remembering stuff bad, or do you believe that getting a computing science degree was easier 10 (or even 5) years ago? </p>

答:
Things change.  30 years ago, in computer graphics class, if you could light up a dot on a screen, you were doing good.  Today, recursive ray tracing in C++ is a routine undergraduate programming assignment - and the images some of the kids produce are IMPRESSIVE.

Teaching methods change.  30 years ago, the introductory numerical methods class taught methods, and spent a little time on how to derive them, but not much on serious, detailed analysis.  A few years ago, when I had the opportunity to retake the class, I discovered that it was now a SERIOUS math class: it could have been subtitled "Applications of Taylor's Theorem to Error Analysis".  (I enjoyed the class the first time.  I had a WONDERFUL time in it the second time.)

Your perspective on what is easy or difficult changes.  A few years ago, I sat in on a vector calculus class, partly as something to do that summer, while unemployed and job-hunting and waiting for my formal university readmission to come through, partly to gear up for tensor calculus.  I was surprised at how easy it was for me.

ContentLicense: CC BY-SA 2.5


答:
Factories have many advantages which allow for elegant application designs in some situations. One is that you can set the properties of objects you later want to create in one place by creating a factory, and then hand that factory around. But often you don't actually need to do that. In that case using a Factory just adds additional complexity without actually giving you anything in return. Let's take this factory, for example:

```<code>WidgetFactory redWidgetFactory = new ColoredWidgetFactory(COLOR_RED);
Widget widget = redWidgetFactory.create();
</code>```

One alternative to the Factory pattern is the very similar Builder pattern. The main difference is that the properties of the objects created by a Factory are set when the Factory is initialized, while a Builder is initialized with a default state and all properties are set afterwards.

```<code>WidgetBuilder widgetBuilder = new WidgetBuilder();
widgetBuilder.setColor(COLOR_RED);
Widget widget = widgetBuilder.create();
</code>```

But when overengineering is your problem, replacing a Factory with a Builder is likely not much of an improvement.

The most simple replacement for either pattern is of course to create object-instances with a simple constructor with the new operator:

```<code>Widget widget = new ColoredWidget(COLOR_RED);
</code>```

Constructors, however, have a crucial drawback in most object-oriented languages: They must return an object of that exact class and can not return a sub-type.

When you need to choose the sub-type at runtime but don't want to resort to creating a whole new Builder or Factory class for that, you can use a factory-method instead. This is a static method of a class which returns a new instances of that class or one of its sub-classes. A Factory which does not maintain any internal state can often be replaced with such a factory-method:

```<code> Widget widget = Widget.createColoredWidget(COLOR_RED); // returns an object of class RedColoredWidget
</code>```

A new feature in Java 8 are method references which allow you to pass methods around, just like you would do with a stateless factory. Conveniently, anything which accepts a method reference also accepts any object which implements the same functional interface, which can also be a full-fledged Factory with internal state, so you can easily introduce factories later, when you see a reason for doing so.

Body:
Factories have many advantages which allow for elegant application designs in some situations. One is that you can set the properties of objects you later want to create in one place by creating a factory, and then hand that factory around. But often you don't actually need to do that. In that case using a Factory just adds additional complexity without actually giving you anything in return. Let's take this factory, for example:

WidgetFactory redWidgetFactory = new ColoredWidgetFactory(COLOR_RED);
Widget widget = redWidgetFactory.create();

One alternative to the Factory pattern is the very similar Builder pattern. The main difference is that the properties of the objects created by a Factory are set when the Factory is initialized, while a Builder is initialized with a default state and all properties are set afterwards.

WidgetBuilder widgetBuilder = new WidgetBuilder();
widgetBuilder.setColor(COLOR_RED);
Widget widget = widgetBuilder.create();

But when overengineering is your problem, replacing a Factory with a Builder is likely not much of an improvement.

The most simple replacement for either pattern is of course to create object-instances with a simple constructor with the new operator:

Widget widget = new ColoredWidget(COLOR_RED);

Constructors, however, have a crucial drawback in most object-oriented languages: They must return an object of that exact class and can not return a sub-type.

When you need to choose the sub-type at runtime but don't want to resort to creating a whole new Builder or Factory class for that, you can use a factory-method instead. This is a static method of a class which returns a new instances of that class or one of its sub-classes. A Factory which does not maintain any internal state can often be replaced with such a factory-method:

 Widget widget = Widget.createColoredWidget(COLOR_RED); // returns an object of class RedColoredWidget

A new feature in Java 8 are method references which allow you to pass methods around, just like you would do with a stateless factory. Conveniently, anything which accepts a method reference also accepts any object which implements the same functional interface, which can also be a full-fledged Factory with internal state, so you can easily introduce factories later, when you see a reason for doing so.


答:
Factories of one sort or another are found in pretty much any object-oriented language under appropriate circumstances.  Sometimes you just plain need a way to select what kind of object to create based on a simple parameter like a string.

Some people take it too far and try to architect their code to never need to call a constructor except inside a factory.  Things start to get ridiculous when you have factory factories.

What struck me when I learned Scala, and I don't know Ruby, but believe it is much the same way, is that the language is expressive enough that programmers aren't always trying to push the "plumbing" work to external configuration files.  Rather than being tempted to create factory factories to wire your classes together in different configurations, in Scala you use objects with traits mixed in.  It's also relatively easy to create simple DSLs in-language for tasks that are often way over-engineered in Java.

Also, as other comments and answers have pointed out, closures and first class functions obviate the need for many patterns.  For that reason, I believe many of the anti-patterns will start disappearing as C++11 and Java 8 gain widespread adoption.


问:
Just one class - Java
I've written a program in Java, it's only fairly small and I started programming and ended up just building one big class with everything inside it.

The program works fine and exactly how I wanted it to, however, when writing up the documentation I've realized that it doesn't follow any sort of architecture pattern like MVC or 3-tier and seems most like a monolithic system. Is this likely to be detrimental?

Maintainability is fairly important but the code is well commented and could be extended fairly easily if somebody wanted to add an extra algorithm for example. I'm just wondering if this is bad practice and whether it will be looked down upon?

It is for part of a project so it will get assessed, I do have time to split it up into classes but it could be unnecessary work I feel and I wouldn't really know how to split it up. When I say a big class, its all relative but its about 1750 lines of code.

I guess the main question is; it works as it is so is there any need to split it up into classes? Are monolithic systems particularly bad (not sure if it even is a monolithic system!)?

答:
Think about it in these terms:

If I were to look at it with the purpose of modifying some code, how long will it take me to find where to do so without talking to you first?

Is some code repeated? Can you avoid that?

What if you need to invoke a method from another class - can you do it easily?

Did you write unit tests?

Do they pass?

If not, try to write some - probably by doing so it will become apparent how you need to refactor your class.

Lots have been written on this topic, but you need to be bitten by this before you can truly understand what are its consequences.

Title: Just one class - Java


答:
I don't know if it's harder or easier, but definitely different.

I'm only a couple years out, but I've noticed that current students appear to me to have a more abstracted knowledge base, but lack fundamentals which cause them to falter on simple tasks.

It's the whole 'calculator debate': "They can do higher order math using a calculator, but can barely multiply without one."1

1 I'm not advocating the truth of that particular debate, just using it as a reference point in understanding my point.

Title: Was getting a computing science degree easier 10 years ago

Body: I am currently a 3rd year computing science student at a Canadian University. I find it quite challenging, and extremely interesting. One thing  that i have noticed is that each person i speak to that took a class 3 or so years ago learned much less than i did in the same class, and people who are taking 1st year classes are doing more than i remember doing in my 1st year classes. Is this just me remembering stuff bad, or do you believe that getting a computing science degree was easier 10 (or even 5) years ago? </p>


答:
Your question is tagged with "Java", no surprise you're asking why is the Factory pattern being mocked: Java itself comes with a nicely packaged abuses of that pattern.

For example try loading an XML document from a file and run an XPath query against it. You need something like 10 lines of code just to setup the Factories and Builders:

```<code>DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();

Document xmlDocument = builder.parse(new FileInputStream("c:\\employees.xml"));
XPath xPath =  XPathFactory.newInstance().newXPath();

xPath.compile(expression).evaluate(xmlDocument);
</code>```

I wonder if the guys designing this API ever worked as developers or did they just read books and throw things around. I understand they just didn't want to write a parser themselves and left the task to others but it still makes for an ugly implementation.

Since you're asking what's the alternative here's loading the XML file in C#:

```<code>XDocument xml = XDocument.Load("c:\\employees.xml");
var nodes = xml.XPathSelectElements(expression);
</code>```

I suspect newly hatched Java developers see the Factory madness and think it's OK to do that - if the geniuses who built Java themselves have used them that much.

Factory and any Other patterns are tools, each suited for a particular job. If you apply them to jobs they aren't suited for you're bound to have ugly code.

Body:
Your question is tagged with "Java", no surprise you're asking why is the Factory pattern being mocked: Java itself comes with a nicely packaged abuses of that pattern.

For example try loading an XML document from a file and run an XPath query against it. You need something like 10 lines of code just to setup the Factories and Builders:

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();

Document xmlDocument = builder.parse(new FileInputStream("c:\\employees.xml"));
XPath xPath =  XPathFactory.newInstance().newXPath();

xPath.compile(expression).evaluate(xmlDocument);

I wonder if the guys designing this API ever worked as developers or did they just read books and throw things around. I understand they just didn't want to write a parser themselves and left the task to others but it still makes for an ugly implementation.

Since you're asking what's the alternative here's loading the XML file in C#:

XDocument xml = XDocument.Load("c:\\employees.xml");
var nodes = xml.XPathSelectElements(expression);

I suspect newly hatched Java developers see the Factory madness and think it's OK to do that - if the geniuses who built Java themselves have used them that much.

Factory and any Other patterns are tools, each suited for a particular job. If you apply them to jobs they aren't suited for you're bound to have ugly code.


答:
You have written an application which is a God Object, maybe even with a Megamoth (MEGA MOnolithic meTHod).

This style of programming isn't object-oriented. It is procedural. There is nothing wrong about procedural programming per-se. There are many important programs which work very well and are sufficiently maintainable even though they are completely procedural. But usually these aren't written in object-oriented languages like Java.

As you noticed it is not impossible to write a procedural program in an object-oriented programming language like Java. But the whole philosophy of Java is build around object-orientation. When you do not use it, you are missing out on the most useful features of the language and its API while having a lot of syntax padding which has no benefit to you at all.

Not every problem is suitable for an object-oriented solution. Some problems fit much better into a procedural programming style. When you encounter such a problem, you would be well-advised to pick a procedural programming language to solve it. That's why there are so many programming languages available: So you can pick the right tool for every job.

Title: Just one class - Java

Body:
I've written a program in Java, it's only fairly small and I started programming and ended up just building one big class with everything inside it.

The program works fine and exactly how I wanted it to, however, when writing up the documentation I've realized that it doesn't follow any sort of architecture pattern like MVC or 3-tier and seems most like a monolithic system. Is this likely to be detrimental?

Maintainability is fairly important but the code is well commented and could be extended fairly easily if somebody wanted to add an extra algorithm for example. I'm just wondering if this is bad practice and whether it will be looked down upon?

It is for part of a project so it will get assessed, I do have time to split it up into classes but it could be unnecessary work I feel and I wouldn't really know how to split it up. When I say a big class, its all relative but its about 1750 lines of code.

I guess the main question is; it works as it is so is there any need to split it up into classes? Are monolithic systems particularly bad (not sure if it even is a monolithic system!)?


问:
The optimal recipe problem
Suppose I have a list of Ingredients In My Fridge which are going off soon, and a list of Recipes which use up various Ingredients. (Some of which I don't currently have.)

Is there an algorithm which produces the optimal set of Recipes, where an optimal set maximises the number of Ingredients In My Fridge used up and minimises the number of Ingredients I Have To Buy From The Store?

(Alternate formulation: In a card game, I can combine some Cards according to various Rules; I can also obtain new Cards in various ways. How do I find the best set of Rules to use up the most Cards I have for the minimum effort in obtaining new Cards?)

答:
sounds like a path finding problem, you start at a node X and want to move several steps with the least cost.

cost is increased when you buy things and stays the same when you don't.

I suggest a flood-fill or minimax with alfa-beta culling until you find a node where your fridge is empty. (after which you will need to buy anyway)

Title: The optimal recipe problem


答:
This is the Exact Cover problem, one of the original 21 problems shown by Karp to be NP-complete in his classic 1972 paper that established the importance of NP-completeness.

Wikipedia's description is:

given a collection S of subsets of a set X, an exact cover is a subcollection S* of S such that each element in X is contained in exactly one subset in S*.

The basic problem is, given S and X, does S contain an exact cover of X?

Here X is the set of contents of your refrigerator, and S is the collection of recipes.  The task is to find a subset S* of recipes such that each ingredient from X is used by exactly one recipe.

Exact Cover is known to remain NP-complete even when every recipe requires no more than 3 ingredients.  If every recipe has 2 or fewer ingredients, there is a polynomial-time algorithm based on finding a maximal matching in a bipartite graph.

The analogous problem, of whether there is a cover S* that covers at least n elements of X, is also NP-complete.  Similarly, one can rephrase this as an optimization problem: find the subset S* that covers the maximum possible number of elements. An efficient solution to this optimization problem would solve the NP-complete decision problem, so is at least as difficult as the decision problem.

As is usual with NP-complete problems, one can say the following:

A good algorithm that works for all instances of the problem is certainly out of reach at present, and probably does not exist.

Branch-and-bound tree search will find a good solution quickly for many instances of the problem, and for small instances.

Straightforward approaches (say, always selecting the recipe with the greatest number of available ingredients) may produce results that are never too far from optimal. There is a lot of research on this sort of thing, and it should not be hard to uncover some.

Wikipedia also mentions an algorithm of Donald Knuth which efficiently performs an exhaustive search of
the solution space (which may be very large) by representing the recipes as rows of a matrix.

Title: The optimal recipe problem

Body:
Suppose I have a list of Ingredients In My Fridge which are going off soon, and a list of Recipes which use up various Ingredients. (Some of which I don't currently have.)

Is there an algorithm which produces the optimal set of Recipes, where an optimal set maximises the number of Ingredients In My Fridge used up and minimises the number of Ingredients I Have To Buy From The Store?

(Alternate formulation: In a card game, I can combine some Cards according to various Rules; I can also obtain new Cards in various ways. How do I find the best set of Rules to use up the most Cards I have for the minimum effort in obtaining new Cards?)


答:
The approach that I would take is a least-errors approach.

1) Create a set of symbols to represent each food stuff.

2) Represent the contents of your fridge as a string of symbols. The string is ordered and multiple items are represented as multiple symbols. Liquids, etc, should be represented by multiple cup-fractions (i.e., 6 x 1/4 cup of milk).

3) Represent each recipe the same way.

Now, do a least errors pattern match of each recipe string against the fridge string.

I had experience, once upon a time, with Early recognizers. I don't know if that helps.

Title: The optimal recipe problem


问:
Can I use a package visible constructor for creation?
I need a class where this can be done:

```<code>// user program
elder_tales.Player p = elder_tales.generate_player();
elder_tales.level_up_player( p );
</code>```

but not:

```<code>// user program
elder_tales.Player p = new ...whatever
p.set_stats();
p.set_server();
p.calculate_experience()
elder_tales.level_up_player( p )
</code>```

Basically, I want the package to do the instantiating while not allowing the user to do their own instantiating; because instances of type Player are constructed in a complex manner, I decided not to put too much strain on the user to create them with a public constructor.

答:
It's called a Factory Method. You just have to make it static, so that you can call it on a class, rather than an instantiated object.

```<code>public static Player generate_player()
{
    elder_tales.Player p = new ...whatever
    p.set_stats();
    p.set_server();
    p.calculate_experience();
    return p;
}
</code>```

This method goes in your Player class, or whatever utility class you're using to generate players.  There isn't a way to put bare factory methods or constructor methods outside of a class, as far as I know.

To disable Player's constructor so that only the factory method can use it, omit the constructor's access modifier.  That defaults it to Package Private access.

Body:
It's called a Factory Method. You just have to make it static, so that you can call it on a class, rather than an instantiated object.

public static Player generate_player()
{
    elder_tales.Player p = new ...whatever
    p.set_stats();
    p.set_server();
    p.calculate_experience();
    return p;
}

This method goes in your Player class, or whatever utility class you're using to generate players.  There isn't a way to put bare factory methods or constructor methods outside of a class, as far as I know.

To disable Player's constructor so that only the factory method can use it, omit the constructor's access modifier.  That defaults it to Package Private access.


问:
What is the pattern for a safe interface in C++
Note: the following is C++03 code, but we expect a move to C++11 in the next two years, so we must keep that in mind.

I'm writing a guideline (for newbies, among others) about how to write an abstract interface in C++. I've read both articles of Sutter on the subject, searched the internet for examples and answers, and made some tests.

This code must NOT compile!

```<code>void foo(SomeInterface & a, SomeInterface & b)
{
   SomeInterface c ;               // must not be default-constructible
   SomeInterface d(a);             // must not be copy-constructible
   a = b ;                         // must not be assignable
}
</code>```

All the behaviors above find the source of their problem in slicing: The abstract interface (or non-leaf class in the hierarchy) should not be constructible nor copiable/assignable, EVEN if the derived class can be.

0th Solution: the basic interface

```<code>class VirtuallyDestructible
{
   public :
      virtual ~VirtuallyDestructible() {}
} ;
</code>```

This solution is plain, and somewhat naive: It fails all our constraints: It can be default-constructed, copy-constructed and copy-assigned (I'm not even sure about move constructors and assignment, but I have still 2 years to figure it out).

We can't declare the destructor pure virtual because we need to keep it inline, and some of our compilers won't digest pure virtual methods with inline empty body.

Yes, the only point of this class is to make the implementers virtually destructible, which is a rare case.

Even if we had an additional virtual pure method (which is the majority of the cases), this class would be still copy-assignable.

So, no...

1st Solution: boost::noncopyable

```<code>class VirtuallyDestructible : boost::noncopyable
{
   public :
      virtual ~VirtuallyDestructible() {}
} ;
</code>```

This solution is the best, because it is plain, clear, and C++ (no macros)

The problem is that it still doesn't work for that specific interface because VirtuallyConstructible can still be default-constructed.

We can't declare the destructor pure virtual because we need to keep it inline, and some of our compilers won't digest it.

Yes, the only point of this class is to make the implementers virtually destructible, which is a rare case.

Another problem is that classes implementing the non-copyable interface must then explicitly declare/define the copy constructor and the assignment operator if they need to have those methods (and in our code, we have value classes that can still be accessed by our client through interfaces).

This goes against the Rule of Zero, which is where we want to go: If the default implementation is ok, then we should be able to use it.

2nd Solution: make them protected!

```<code>class MyInterface
{
   public :
      virtual ~MyInterface() {}

   protected :
      // With C++11, these methods would be "= default"
      MyInterface() {}
      MyInterface(const MyInterface & ) {}
      MyInterface & operator = (const MyInterface & ) { return *this ; }
      MyInterface(MyInterface && ) noexcept {}
      MyInterface & operator = (MyInterface && ) noexcept { return *this ; }
} ;
</code>```

This pattern follows the technical constraints we had (at least in user code): MyInterface cannot be default-constructed, cannot be copy-constructed and cannot be copy-assigned.

Also, it imposes no artificial constraints to implementing classes, which are then free to follow the Rule of Zero, or even declare a few constructors/operators as "= default" in C++11/14 without problem.

Now, this is quite verbose, and an alternative would be using a macro, something like:

```<code>class MyInterface
{
   public :
      virtual ~MyInterface() {}

   protected :
      DECLARE_AS_NON_SLICEABLE(MyInterface) ;
} ;
</code>```

The protected must remain outside the macro (because it has no scope).

Correctly "namespaced" (that is, prefixed with the name of your company or product), the macro should be harmless.

And the advantage is that the code is factored in one source, instead of being copy pasted in all interfaces. Should the move-constructor and move-assignment be explicitly disabled the same way in the future, this would be a very light change in the code.

Conclusion

Am I paranoid to want the code to be protected against slicing in interfaces? (I believe I'm not, but one never knows...)

What is the best solution among the ones above?

Is there another, better solution?

Please remember that this is a pattern that will serve as a guideline for newbies (among others), so a solution like: "Each case should have its implementation" is not a viable solution.

Bounty and results

I awarded the bounty to coredump because of the time spent to answer the questions, and the relevance of the answers.

My solution to the problem will probably go to something like that:

```<code>class MyInterface
{
   DECLARE_CLASS_AS_INTERFACE(MyInterface) ;

   public :
      // the virtual methods
} ;
</code>```

... with the following macro:

```<code>#define DECLARE_CLASS_AS_INTERFACE(ClassName)                                \
   public :                                                                  \
      virtual ~ClassName() {}                                                \
   protected :                                                               \
      ClassName() {}                                                         \
      ClassName(const ClassName & ) {}                                       \
      ClassName & operator = (const ClassName & ) { return *this ; }         \
      ClassName(ClassName && ) noexcept {}                                   \
      ClassName & operator = (ClassName && ) noexcept { return *this ; }     \
   private :
</code>```

This is a viable solution for my problem for the following reasons:

This class cannot be instantiated (the constructors are protected)

This class can be virtually destroyed

This class can be inherited without imposing undue constraints on inheriting classes (e.g. the inheriting class could be by default copiable/moveable)

The use of the macro means the interface "declaration" is easily recognizable (and searchable), and its code is factored in one place making it easier to modify (a suitably prefixed name will remove undesirable name clashes)

Note that the other answers gave valuable insight. Thank you to all you who gave it a shot.

Note that I guess I can still put another bounty on this question, and I value enlightning answers enough that should I see one, I would open a bounty just to assign it to that answer.

答:
The canonical way to create an interface in C++ is to give it a pure virtual destructor. This ensures that

No instances of the interface class itself can be created, because C++ does not allow you to create an instance of an abstract class. This takes care of the not constructible requirements (both default and copy).

Calling delete on a pointer to the interface does the right thing: it calls the destructor of the most-derived class for that instance.

just having a pure virtual destructor doesn't prevent assignment on a reference to the interface. If you need that to fail as well, then you must add a protected assignment operator to your interface.

Any C++ compiler should be able to handle a class/interface like this (all in one header file):

```<code>class MyInterface {
public:
  virtual ~MyInterface() = 0;
protected:
  MyInterface& operator=(const MyInterface&) { return *this; } // or = default for C++14
};

inline MyInterface::~MyInterface() {}
</code>```

If you do have a compiler that chokes on this (which means it must be pre-C++98), then your option 2 (having protected constructors) is a good second-best.

Using boost::noncopyable is not advisable for this task, because it sends the message that all classes in the hierarchy should be non-copyable and it can thus create confusion for more experienced developers who wouldn't be familiar with your intentions for using it like this.

OwnerDisplayName: paercebal

ContentLicense: CC BY-SA 4.0

Body:
The canonical way to create an interface in C++ is to give it a pure virtual destructor. This ensures that

No instances of the interface class itself can be created, because C++ does not allow you to create an instance of an abstract class. This takes care of the not constructible requirements (both default and copy).

Calling delete on a pointer to the interface does the right thing: it calls the destructor of the most-derived class for that instance.

just having a pure virtual destructor doesn't prevent assignment on a reference to the interface. If you need that to fail as well, then you must add a protected assignment operator to your interface.

Any C++ compiler should be able to handle a class/interface like this (all in one header file):

class MyInterface {
public:
  virtual ~MyInterface() = 0;
protected:
  MyInterface& operator=(const MyInterface&) { return *this; } // or = default for C++14
};

inline MyInterface::~MyInterface() {}

If you do have a compiler that chokes on this (which means it must be pre-C++98), then your option 2 (having protected constructors) is a good second-best.

Using boost::noncopyable is not advisable for this task, because it sends the message that all classes in the hierarchy should be non-copyable and it can thus create confusion for more experienced developers who wouldn't be familiar with your intentions for using it like this.


问:
Can this argument be enough?
We have two C++ classes named Important and Small

The class Small use a few methods and attributes from the class Important, but not all.

Since our application is performance critical, instead of copying all attributes (possibly pointers) of Important that are needed by Small and redefine the few methods in Small, we decided to just let Small hold a pointer on Important.

Can performance justify such a design choice?

答:
In line with RAII, I would certainly make sure that you had a reference-counting smart pointer (shared_ptr) instead of a raw pointer. Besides that, there's nothing inherently wrong with what you've described.

However, as many people have noted already, it is impossible to give an accurate answer without two things:

Code. Are you turning your code into an incomprehensible mess when there is an easier option? The heck if I know. I haven't seen your code. I am not asking for code (I wouldn't read it even if you gave it to me), but I am asking you to take this advice with a grain of salt. Just because I said there was nothing wrong doesn't mean it is right.

Performance Numbers. Is this really something that will affect the performance of your program? Without solid numbers I can't say for sure and neither can you.

Title: Can this argument be enough?


答:
First, you define the constructor as "package private" by omitting the access modifier. This makes it so that the constructor can be called from same package, but not from package that is using your package.

Then you create a static method that creates and returns the concrete instance. This will have same code as you have written.

Title: Can I use a package visible constructor for creation?

Body:
I need a class where this can be done:

```<code>// user program
elder_tales.Player p = elder_tales.generate_player();
elder_tales.level_up_player( p );
</code>```

but not:

```<code>// user program
elder_tales.Player p = new ...whatever
p.set_stats();
p.set_server();
p.calculate_experience()
elder_tales.level_up_player( p )
</code>```

Basically, I want the package to do the instantiating while not allowing the user to do their own instantiating; because instances of type Player are constructed in a complex manner, I decided not to put too much strain on the user to create them with a public constructor.


答: What about using an hermeneutic approach give every recipy certain points based on different criteria. E.g buying an ingredient 5 points for every ingredient. The one with lowest points wins</p>

Title: The optimal recipe problem


问:
When is it worth NOT using a Factory?
I'm employing TDD quite a bit these days and really enjoying myself - everything seems to flow better and be naturally better constructed and organized. However, while writing a bit of IO code, utilizing System.IO.Streams, and I was wondering - when is it ever worth not using a factory? Because in Streams case, it certainly seems better to not use a factory.

Generally, for more complex types that I have defined, such as a class that controls the authentication of something and interfaces with a database, you would probably use a dependency injection container and have this resolved at runtime without ever needing to actually create one.

However, in some circumstances, when you need to create a lot of these instances, you would create a Factory to construct that type - such as:

```<code>class Foo
  Foo(Bar bar, Foobar foobar, Fuzz fuzz)
  ...
end
</code>```

Here, because you don't want to expose how to directly create this object to the clients that need it, you expose a Factory that will create them and inject that into the client instead. This has the benefit of allowing you to replace the factory at any time you want with something else and is generally used for creating instances of types which have derived types.

```<code>class FooFactory
   void Create(Bar, Foobar, Fuzz)
end
</code>```

However, back to my Stream point - would it even be worth creating a Factory for a decorator around a Stream? For example, in my project I have BinaryDataStream, which reads my data from a Streeam. The BinaryData is in a custom format, and takes a Stream argument in it's constructor. Using new seems to violate everything I know that I've learned since I started using TDD, because I am giving the dependent in which it needs to know explicitly about how to get it's collaborator However a factory seems overkill.

Thoughts?

EDIT: I think I need to clarify. I don't mean avoiding new() all the time, as obviously it has it's use in tying up dependencies and the like. however, I meant in the following situation (copy-pasta from comments):

What I meant was that I have been told it is intrinsically evil to
  use the new() operator to a collaborator from inside the type that
  uses the collaborator, and that it is better to either a) pass an
  injected type or b) pass a factory (if you need to create an unknown
  number of those types). By using new() inside the collaborator you
  tie how to create that object and where to create it directly to the
  thing that requires it, and that it is better to inject a preconfigured
  instance into the constructor if you need one instance of it, or inject
  a factory into the constructor if you need to create multiple/undetermined
  number of instances

答:
For any factory pattern to be usable, it needs a parameter to know what concrete instance to create. With Factory Method and Abstract Factory this "parameter" is type the creation method is on, which is achieved with polymorphism. With "plain" factory pattern, only way to achieve that is to pass the parameter into creation method. Also, this creation process should be complex, not just switch based on enum, if-else chain or something like that. It is also worth when there are multiple different places where the factory is used.

If you have Factory class that doesn't have method parameter, the creation logic is simple or is only used in single place, then I would consider it needless overengineering and needless abstraction. Simple method would be enough.

Also, just because the creation is in different class, doesn't mean it is decoupled. The calling code is still heavily tied to the Factory class. You would need to use abstract factory to have really decoupled code. Also, the whole "new is bad" mentality is dangerous, you should drop it. Creating objects is important part of OOP code. Trying to encapsulate even that will quickly result in overengineering and needless abstractions. Also note, that constructors themselves are sort of factories. They smake sure the instance is created in valid state base and to do that, they ask for required data.

Title: When is it worth NOT using a Factory?


问:
What encoding is used by javax.xml.transform.Transformer?
Please can you answer a couple of questions based on the code below (excludes the try/catch blocks), which transforms input XML and XSL files into an output XSL-FO file:

```<code>File xslFile = new File("inXslFile.xsl");
File xmlFile = new File("sourceXmlFile.xml");
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer(new StreamSource(xslFile));
FileOutputStream fos = new FileOutputStream(new File("outFoFile.fo");
transformer.transform(new StreamSource(xmlFile), new StreamResult(fos));
</code>```

inXslFile is encoded using UTF-8 - however there are no tags in file which states this.
sourceXmlFile is UTF-8 encoded and there may be a metatag at start of file indicating this.

am currently using Java 6 with intention of upgrading in the future.

What encoding is used when reading the xslFile?

What encoding is used when reading the xmlFile?

What  encoding will be applied to the FO outfile?

How can I obtain the info (properties) for 1 - 3? Is there a method call?

How can the properties in 4 be altered - using configuration and dynamically?

if known - Where is there info (web site) on this that I can read - I have looked without much success.

答:
To answer part of the question following code works for me. This can take input encoding and convert the data into output encoding.</p>

```<code>ByteArrayInputStream inStreamXMLElement = new ByteArrayInputStream(strXMLElement.getBytes(input_encoding));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document docRepeat = db.parse(new InputSource(new InputStreamReader(inStreamXMLElement, input_encoding)));
Node elementNode = docRepeat.getElementsByTagName(strRepeat).item(0);

TransformerFactory tFactory = null;
Transformer transformer = null;
DOMSource domSourceRepeat = new DOMSource(elementNode);
tFactory = TransformerFactory.newInstance();
transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, output_encoding);

ByteArrayOutputStream bos = new ByteArrayOutputStream();
StreamResult sr = new StreamResult(new OutputStreamWriter(bos, output_encoding));

//          StringWriter sW = new StringWriter();
//          StreamResult resultRepeat = new StreamResult(sW);

transformer.transform(domSourceRepeat, sr);
byte[] outputBytes = bos.toByteArray();
strRepeatString = new String(outputBytes, output_encoding);
</code>```

Body:
To answer part of the question following code works for me. This can take input encoding and convert the data into output encoding.

ByteArrayInputStream inStreamXMLElement = new ByteArrayInputStream(strXMLElement.getBytes(input_encoding));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document docRepeat = db.parse(new InputSource(new InputStreamReader(inStreamXMLElement, input_encoding)));
Node elementNode = docRepeat.getElementsByTagName(strRepeat).item(0);

TransformerFactory tFactory = null;
Transformer transformer = null;
DOMSource domSourceRepeat = new DOMSource(elementNode);
tFactory = TransformerFactory.newInstance();
transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, output_encoding);

ByteArrayOutputStream bos = new ByteArrayOutputStream();
StreamResult sr = new StreamResult(new OutputStreamWriter(bos, output_encoding));

//          StringWriter sW = new StringWriter();
//          StreamResult resultRepeat = new StreamResult(sW);

transformer.transform(domSourceRepeat, sr);
byte[] outputBytes = bos.toByteArray();
strRepeatString = new String(outputBytes, output_encoding);


答:
Here, because you don't want to expose how to directly create this object to the clients that need it, you expose a Factory that will create them and inject that into the client instead.

If clients know the object exists, it's usually fine for them to know how to make it. If you have an interface then maybe you need some factory to make the concrete instance, but for TDD you're just going to mock it anyways.

Your example factory is just a passthru. Your client already knows everything needed to build the object, so replacing the factory is just as hard as replacing the constructor call.

When is it worth NOT using a Factory?

This is the wrong mode of thought.

You should default to not using factories. Factories are only necessary when you need to abstract away object creation. Since you should (in general) limit the creation of objects that require such abstraction, you should use factories sparingly. Instead, most of your objects will just take some interface and not care where it came from.

Only add complexity when it is necessary.

Title: When is it worth NOT using a Factory?

Body:
I'm employing TDD quite a bit these days and really enjoying myself - everything seems to flow better and be naturally better constructed and organized. However, while writing a bit of IO code, utilizing System.IO.Streams, and I was wondering - when is it ever worth not using a factory? Because in Streams case, it certainly seems better to not use a factory.

Generally, for more complex types that I have defined, such as a class that controls the authentication of something and interfaces with a database, you would probably use a dependency injection container and have this resolved at runtime without ever needing to actually create one.

However, in some circumstances, when you need to create a lot of these instances, you would create a Factory to construct that type - such as:

```<code>class Foo
  Foo(Bar bar, Foobar foobar, Fuzz fuzz)
  ...
end
</code>```

Here, because you don't want to expose how to directly create this object to the clients that need it, you expose a Factory that will create them and inject that into the client instead. This has the benefit of allowing you to replace the factory at any time you want with something else and is generally used for creating instances of types which have derived types.

```<code>class FooFactory
   void Create(Bar, Foobar, Fuzz)
end
</code>```

However, back to my Stream point - would it even be worth creating a Factory for a decorator around a Stream? For example, in my project I have BinaryDataStream, which reads my data from a Streeam. The BinaryData is in a custom format, and takes a Stream argument in it's constructor. Using new seems to violate everything I know that I've learned since I started using TDD, because I am giving the dependent in which it needs to know explicitly about how to get it's collaborator However a factory seems overkill.

Thoughts?

EDIT: I think I need to clarify. I don't mean avoiding new() all the time, as obviously it has it's use in tying up dependencies and the like. however, I meant in the following situation (copy-pasta from comments):

What I meant was that I have been told it is intrinsically evil to
  use the new() operator to a collaborator from inside the type that
  uses the collaborator, and that it is better to either a) pass an
  injected type or b) pass a factory (if you need to create an unknown
  number of those types). By using new() inside the collaborator you
  tie how to create that object and where to create it directly to the
  thing that requires it, and that it is better to inject a preconfigured
  instance into the constructor if you need one instance of it, or inject
  a factory into the constructor if you need to create multiple/undetermined
  number of instances


问:
How to consider the login function collecting requirements of an application? is it a user requirement?
I am working on an application that expected to the user logs in when the application is started (as for example it is in Skype: the user open the application and appear to him a login mask when he insert the username and password to start work with the application)

Now I am preparing some use case diagram and I am collecting the application requirements (I have to write some documentation)

Can I consider it as a user requirement? Or what is it?

答:
It is a user requirement:

1) Security is a user requirement: "I don't want other people to see my data."

2) Work flow is a user requirement: "Don't show me web pages or commands that are not part of my responsibility."

3) Good support is a user requirement: Help Desk: "What page are you on?" User: "The one with the big you can't do that message".

4) Auditing is a user requirement: "Who changed that record?"


问:
Using a relational database vs JSON objects for event/activity data
I am working on a project where I am trying to decide between using a standard SQL relational database or JSON objects to store data about an event or activity.

The project will store data on multiple event types so I have decided to just describe one event type for this question.

The live music event (described in full using the JSON schema at the bottom of this question) is an object that stores data such as where the event will take place, the time/date of the event and the cost of the event. The live music event object has both one-to-one (event--> name, event --> description) and one-to-many (event--> venues, event--> dates, event--> ticket types) relationships. Furthermore, the event object can contain one or more performer IDs, which link to the performer object. The performer object stores data on musicians who are performing at the live music event.

The data will be queried by users using both simple ("Find me events with 'x' name") and complex ("Find me events with 'x' music genre and 'y' cost within a radius of 'z' from my current location") queries. The data will be submitted by users using a web form.

As you can probably tell from the defined JSON schema, I was originally going to use JSON objects to store this data but I've heard from some people who say that because my data is purely relational, I should stick to the older methods.

I would appreciate any thoughts on the pros and cons of each approach given my needs. If you need anything clarified, please feel free to ask.

```<code>{
    "event": {
        "eventID":{
            "type":"string"
        },
        "eventType":{
            "type":"array",
            "eventTypeItem":{
                "type":"string"
            }
        },
        "eventName":{
            "type":"string"
        },
        "eventDescription":{
            "type":"string"
        },
        "eventVenueList":{
            "type":"array",
            "eventVenueListID":{
                "type":"integer"
            }
        },
        "eventURL":{
            "type":"string"
        },
        "eventTwitter":{
            "type":"string"
        },
        "eventFB":{
            "type":"string"
        },
        "eventInstagram":{
            "type":"string"
        },
        "eventEmail":{
            "type":"string",
            "format":"email"
        },
        "eventContactPerson":{
            "type":"string"
        },
        "eventDoorTime": {
            "type":"string",
            "format":"date-time"
        },
        "eventPerformerIDList":{
            "type":"array",
            "liveMusicPerformerID":{
                "type":"integer"
            }
        },
        "eventSetList":{
            "type":"array",
            "eventPerformerID":{
                "type":"integer"
            },
            "eventPerformerStartTime":{
                "type":"string",
                "format":"date-time"
            },
            "eventPerformerEndTime":{
                "type":"string",
                "format":"date-time"
            }
        },
        "eventDateList": {
            "type":"array",
            "eventDateItem": {
                "type":"string",
                "format":"date-time"
            }
        },
        "eventDateStartTime": {
            "type":"string",
            "format":"date-time"
        },
        "eventDateEndTime": {
            "type":"string",
            "format":"date-time"
        },
        "eventTicket":{
            "type":"array",
            "eventTicketType":{
                "type":"string"
            },
            "eventTicketLowPrice":{
                "type":"number"
            },
            "eventTicketHighPrice":{
                "type":"number"
            },
            "eventDatesAdvancePrice": {
                "type":"number"
            }
        }
    },
    "performer": {
        "performerID": {
            "type":"integer"
        },
        "performerType": {
            "type":"string"
        },
        "performerName": {
            "type":"string"
        },
        "performerAlternateName": {
            "type":"array",
            "performerAlterateNameItem":{
                "type":"string"
            }
        },
        "performerGenreList": {
            "type":"array",
            "performerGenreItem":{
                "type":"string"
            }
        },
        "performerURL": {
            "type":"string"
        }
    }
}
</code>```

答:
I think your question really boils down to:  When should I use a NoSQL approach vs. RDBMS?  You settled on JSON early (a NoSQL-ish decision), perhaps because you've got Ajax consumers.

The answer of course to when to use NoSQL approaches vs. RDBMS's is basically about what type of data you're working with and what consumers you anticipate having.  If your data is essentially relational (fairly flat hierarchies, no weird data types like images or audio, predictable relationships between the schemas that can be easily described in keys), and your consumers are anticipated to eventually include people who want to do Business Intelligence queries (ad hoc querying), then an RDBMS is the way to go.  It's fairly easy to turn a query into a JSON representation, so it doesn't significantly burden your Ajax consumers -- it just adds a little transformation coding into your endpoints (REST/SOAP/whatever).  Conversely, if your data is very hierarchical (deep schemas), contains weird data types like images, audio, video, etc., there are few relationships between entities, and you know that your end users will not be doing BI, then NoSQL/storing JSON may be appropriate.

Of course, even these general guidelines aren't rock solid.  The reason Google developed Google File System, MapReduce (work which was used by Doug Cutting to build Hadoop at Yahoo) and later BigQuery (a NoSQL oriented [schemaless] way of managing large scale data) was precisely because they had a lot of ad hoc BI requests, and they couldn't get relational approaches to scale up to the tera/peta/exa/zetta/yotta scales they were trying to manage.  The only practical approach was to scale out, sacrificing some of ad-hoc-query user friendliness that an RDBMS provides, and substituting a simple algorithm (MapReduce) that could be coded fairly easily for any given query.

Given your schema above, my question would basically be:  Why wouldn't you use an RDBMS?  I don't see much of a reason not to. Our profession is supposed to be engineering oriented, not fashion oriented, so our instinct should be to pick the easiest solution that works, right?  I mean, your endpoints may have to do a little translation if your consumers are Ajaxy, but your data looks very flat and it seems likely that business users are going to want to do all kinds of ad hoc querying on things like music events (Which event was most attended within 50 miles of our capital city last year?)

'Go not to the elves for counsel, for they will say both no and yes.' -- Frodo


问:
Is there any performance benefit in checking the item count prior to executing a foreach loop?
I saw this in code and was wondering if there is any performance benefit to checking the item count prior to looping:

```<code>if (SqlParams.Count > 0)
    foreach (var prm in SqlParams)
        cmd.Parameters.Add(prm);
</code>```

I always prefer to do a null check instead and let the foreach loop just hop out if there are 0 items.

```<code>if (SqlParams != null)
    foreach (var prm in SqlParams)
        cmd.Parameters.Add(prm);
</code>```

Isn't that the better way?

答:
Short answer is: NO.

Details: SqlParameterCollection implements IEnumerable interface that allow you to use the foreach loop, the foreach itself insure that you don't get exception but in one condition that is System.NullReferenceException taking into your consideration that Null exception has nothing to do with (Count) property, you can have 0 params in the collection and the variable is initialized (not null).

So what do you need to do, simply check for null before the foreach syntax.


答:
Consider system performance vs. a single execution. If the list is non-empty 99% of the time, then you are paying the cost of an extra check almost all the time.

On the other hand, if the list is empty 99% of the time, then it might work out differently (although I wonder if the extra invocation offsets any time you save -- remember we're talking about micro- or nano-seconds in this example).

So you can't just consider a single pass running in one thread, you have to consider the system's performance all together.

Title: Is there any performance benefit in checking the item count prior to executing a foreach loop?

Body:
I saw this in code and was wondering if there is any performance benefit to checking the item count prior to looping:

```<code>if (SqlParams.Count > 0)
    foreach (var prm in SqlParams)
        cmd.Parameters.Add(prm);
</code>```

I always prefer to do a null check instead and let the foreach loop just hop out if there are 0 items.

```<code>if (SqlParams != null)
    foreach (var prm in SqlParams)
        cmd.Parameters.Add(prm);
</code>```

Isn't that the better way?


问:
Coding style for chained function calls
A common thing you need to do is to take a value, do something with it by passing it to a function, and then do some more with the return value, in a chain. Whenever I run into this type of scenario, I get unsure about how best to write the code.

As an example, let's say I have a number, num, and need to take the floored square root of it and turn it into a string. Here are a few possibilities (in JavaScript).

I might simply pass num to one function at a time, and replace num with the return value:

```<code>function floorSqrt(num) {
    num = Math.sqrt(num);
    num = Math.floor(num);
    num = String(num);
    return num;
}
</code>```

This is nice since I don't need the original num any more, but in practice it might be confusing to start with one thing (a number) and end up with something completely different (a string).

I can save each step in a new variable:

```<code>function floorSqrt(num) {
    var sqrtNum = Math.sqrt(num);
    var floorSqrt = Math.floor(sqrtNum);
    var stringNum = String(floorSqrt);
    return stringNum;
}
</code>```

Although it seems wasteful to declare all those variables and come up with good names for them.

Or I can just do it all as a one-liner:

```<code>function floorSqrt(num) {
    return String(Math.floor(Math.sqrt(num)));
}
</code>```

But for more than two functions that approach gets incredibly unreadable, almost like code golf.

It seems to me like the most beautiful way to do this would be with some stack-based language, which might look something like this (pseudo code):

```<code>[sqrt floor toString]
</code>```

Is there a way to do something similar with JavaScript? List some functions, run one at a time, and use the return value of each one as the argument for the next? The closest is how some libraries like jQuery or Underscore.js allow you to chain methods, something like this:

```<code>function floorSqrt(num) {
    return _.chain(num).sqrt().floor().toString().value();
}
</code>```

I'm sure many wise people have thought wise things about this. What are some thoughts on pros and cons of the different styles?

答:
As Doc Brown says, this is a fluent interface, and is easily achievable in javascript, to use your example:

```<code>Number.prototype.sqrt=function(){return Math.sqrt(this);};
Number.prototype.floor=function(){return Math.floor(this);};
String.prototype.alert=function(){alert(this);return this;}

(5).sqrt().floor().toString().alert();  //alerts "2"
</code>```

Title: Coding style for chained function calls

Body:
As Doc Brown says, this is a fluent interface, and is easily achievable in javascript, to use your example:

Number.prototype.sqrt=function(){return Math.sqrt(this);};
Number.prototype.floor=function(){return Math.floor(this);};
String.prototype.alert=function(){alert(this);return this;}

(5).sqrt().floor().toString().alert();  //alerts "2"


答:
I have no idea whether things are easier or harder now than they were 10 or 25 years ago.

But I do know that my particular institute of learning (Imperial College, London) is not going to have let things slide...

The problem with computing is that things are still changing at a staggering rate - when I did my degree (82-85) there was very little notion of "objects", now OO is fundamental. Design Patterns was published in '94 -  the things it addresses were in many cases not yet Phd theses then - yet now you'd hope they're fundamental (those patterns that have not further evolved) to a good course.

You will remember best that which you're doing now, your school should be developing its course continuously - and above all it should be teaching you to think not (just) to code (teaching you a mental/philosophical framework that allows you to write good code, not simply teaching you the mechanics of particular languages).


问:
How to measure team productivity over time using consistent story sizes?
How do I measure team productivity over time using consistent story sizes?

To take a simple example, if I can do a story every two days, then I can do five stories in a two-week sprint. By definition (as one story is two days), I will continue to complete five stories per sprint forever. In order to demonstrate improvement over time, I would need a new measurement, for example, value, right?

答:
Don't do this.  You're not going to like this, but you're missing the point of story card sizing.  It's NOT to measure productivity.  It's to measure relative complexity of work.  These are not the same thing, and never will be.  See, there's a fuzzy correlation between requirement complexity and time to completion, but that's ALL that it is.  Your goal should not be to measure productivity at such a fine grain level.  Rather, measure that you're getting a few more points done per iteration, until you can't any more (you start missing commitments).  At that point, you've reached a hard bottleneck, and your retrospectives should tell you what that bottleneck is.  Then, you can either clear the bottleneck (if it's in your control), or you can raise it to your management as something they need to clear (or not, if they're happy with the business value delivery rate you're achieving).

The point is gradual improvement over time until you reach a definable bottleneck, not some arbitrary measure of productivity.  This is knowledge work, not bolt turning.  How do you measure the productivity of a doctor, or a lawyer, or a marketing department?  You can measure some things, but they're REALLY high level and incomplete/misleading (like number of patients treated per month for doctors, or number of trials attended by year for a lawyer, or measurable market upturn after a campaign vs. cost of the campaign for a marketing department).  Programming is more or less the same.  The smart play is to "get more done over time", not try to define what "more" means precisely.


问:
assembly.GetTypes() vs assembly.DefinedTypes.Select(t => t.AsType());
```<code>public static IEnumerable<Type> GetAccessibleTypes(this Assembly assembly)
    {
        try
        {
#if NET40
            return assembly.GetTypes();
#else
            return assembly.DefinedTypes.Select(t => t.AsType());
#endif
        }
        catch (ReflectionTypeLoadException ex)
        {
            // The exception is thrown if some types cannot be loaded in partial trust.
            // For our purposes we just want to get the types that are loaded, which are
            // provided in the Types property of the exception.
            return ex.Types.Where(t => t != null);
        }
    }
</code>```

What are differences between assembly.GetTypes() and assembly.DefinedTypes.Select(t => t.AsType())?

Original code:
https://entityframework.codeplex.com/SourceControl/latest#src/Common/AssemblyExtensions.cs

答:
At a minimum, the returned objects are different types, with one being an array of Types and the other being a generic IQueryable<Type>.

Here is the code from Assembly.GetTypes()

```<code>[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine | ResourceScope.Assembly, ResourceScope.Machine | ResourceScope.Assembly)]
public virtual Type[] GetTypes()
{
    Module[] m = GetModules(false);

    int iNumModules = m.Length;
    int iFinalLength = 0;
    Type[][] ModuleTypes = new Type[iNumModules][];

    for (int i = 0; i < iNumModules; i++)
    {
        ModuleTypes[i] = m[i].GetTypes();
        iFinalLength += ModuleTypes[i].Length;
    }

    int iCurrent = 0;
    Type[] ret = new Type[iFinalLength];
    for (int i = 0; i < iNumModules; i++)
    {
        int iLength = ModuleTypes[i].Length;
        Array.Copy(ModuleTypes[i], 0, ret, iCurrent, iLength);
        iCurrent += iLength;
    }

    return ret;
}
</code>```

Body:
At a minimum, the returned objects are different types, with one being an array of Types and the other being a generic IQueryable<Type>.

Here is the code from Assembly.GetTypes()

[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine | ResourceScope.Assembly, ResourceScope.Machine | ResourceScope.Assembly)]
public virtual Type[] GetTypes()
{
    Module[] m = GetModules(false);

    int iNumModules = m.Length;
    int iFinalLength = 0;
    Type[][] ModuleTypes = new Type[iNumModules][];

    for (int i = 0; i < iNumModules; i++)
    {
        ModuleTypes[i] = m[i].GetTypes();
        iFinalLength += ModuleTypes[i].Length;
    }

    int iCurrent = 0;
    Type[] ret = new Type[iFinalLength];
    for (int i = 0; i < iNumModules; i++)
    {
        int iLength = ModuleTypes[i].Length;
        Array.Copy(ModuleTypes[i], 0, ret, iCurrent, iLength);
        iCurrent += iLength;
    }

    return ret;
}


问:
Design of high performance file processing web application
I'm trying to design a web app with ability to scale but can't wrap my heads around few concepts. I want to design it right but im not a experienced programmer, i have more of a system engineering background.

Basic architecture look like this:

Web Server -> File processing server -> NoSQL DB -> Search server

So the main scenario is follows:

User uploads a file via site

File is send for processing to a server(python script)

Results of processing is send to NoSQL DB

Results processed by search server and returned to user

We can scale web frontends via load balancing. Something like nginx+apache.

Database scaling is taking care by Cassandra or MongoDB. Search scaling is taking care by elasticsearch or sphinx clustering.

Now I want to be able to add multiple file processing servers in case file uploaded is too big. So I need to somehow split file into chunks and process it simultaneously on multiple nodes plus if node goes down while working it shouldn't affect anything and data must be saved. So I need something else which will be allocating tasks to my file processing servers, balancing load and control execution of tasks.

How to design custom applications for that kind of things? Should I use message queuing?

答:
I'm not sure I quite follow what you're doing (like what does "file is sent for 'processing'" mean -- processing?).  Maybe that's not all that important for the context.

I guess my first instinct would be to ask why your "processing" can't happen on your app server (as part of the upload process).  Then, whatever scaling solution you use for your app server, your "processing" scales with it.

However, I also get the hint that perhaps you're trying to design a massively scalable solution, with independently tunable subsystems, so you probably aren't wanting to link your app server to your "processing" event.  In that case, there are a few different ways to go.

I've used message queuing (as you suggested) for this type of problem before.  Then, you just fire up additional listeners as your load increases.  You have to be careful about what triggering mechanism you use though, and you have to deal with transaction processing appropriately (syncpoints / rollback and commits), otherwise queuing can become a mess to debug.  It seems trivial, but in my experience, it's not.  When everything's working, it's great, but you really have to test the heck out of the cloudy-day scenarios to make sure you don't get dropped messages or messages processed more than once.  "Guaranteed delivery" isn't all it's cracked up to be.

I also recently solved a problem like this using a shared memory data grid (Hazelcast).  The API actually implements a queue for you, so you don't have all the overhead of setting up a queue manager as you would with the solution above.  In my case I was needing to run a transformation process against hundreds of billions of rows of data from a table, and by writing a multithreaded app that spun up table readers at different points in the table, I  threw the records into the data grid, and I wrote a separate process that I could instantiate as many times as necessary to transform the data -- so it scaled as far as I needed it to.  I suppose it's just a variation on the solution above.  I took a process that took about 3 days to run in the original approach, to about 15 minutes, but it was spread across a 50 node cluster for those 15 minutes.


问:
When doing social application development, is it ok to use my company credentials for all client work?
As a web application developer, recently my work in creating Social Applications has taken a lot of momentum (specifically, Social Login buttons.)

Is it ok to use my company's social network developer credentials for this? I don't want to sign each client up for between 1 and 20 different services based on their needs. It's a lot easier to just open up my Google Console and click 'new.'

答:
This depends upon what you and your company want to do as well as what the client wants.  If you are creating keys under your developer account, the client may not like that as it can interfere with going to another company.

On the otherhand, your company may like it very much as it is one more reason to stay with your company. Check with your company.


问:
Do resumable exceptions make any sense?
Following up my previous question I wonder if resumable exceptions make any sense. It looks like nobody uses them in Java. Don't they use resumable exceptions because of Java limitations or just because they don't really need them?

Suppose, I want to create a file in a directory, which should exist but does not. I would probably prefer use a resumable exception (i.e. throw an exception, catch it and create the directory, and resume the execution) instead of testing if the directory exists every time I create a file.  Does it make sense in general ?

答:
The real point of resumable exceptions is that the place where the exception happens is often not the right place to decide what to do about it. The OP's missing directory exception may occur inside some low level utility library, which which can be used by many different systems.

If the client code is a batch program then there may be nothing better to do than clean up, log the error and die. However, if the error occurs in an interactive application it makes perfect sense to prompt the user to either create the directory or specify an alternative one and continue. You do not want the utility library to know about the different ways to deal with the missing directory and throwing an ordinary exception loses your current context/state.

With resumable exceptions (or a continuation) you can let client code decide what to do about the missing directory with the option of resuming from where the error occurred, possibly using a different directory.

The utility library just throws a resumable exception (or an exception containing the current continuation) without any coupling to how the issue may possibly be resolved.

OwnerDisplayName: Misha

Title: Do resumable exceptions make any sense?


问:
Where does one draw the line between inspiration and plagiarism?
Suppose one would like to use in an iOS app only one function from a GPLv3 library that contains a large number of them. One cannot simply link the whole library beacuse otherwise the resulting software, having to be GPLv3, would be incompatible with the App Store. Can one "take inspiration" from the source code of the library to write a function that would perform the same task?

I understand that this is a fine line, but I wonder if there is a rule of thumb.

答:
The simple answer is that in most cases and within reasonable limits yes, it's ok. Some provisos.

Copyright law gives you two basic mechanisms, which depend somewhat on the country.

In many cases the use small pieces of code copied from a large work is permitted as "fair use" or "fair dealing". The limits are not well defined, but the principle is solid.

It is always permitted to examine a copyright work in the process of creating your own. The three step process is (a) study the code (b) extract the principles of operation (c) write all new code based on the same principles.

As I tell people repeatedly, if you make no money out of it and harm no-one then just do your best, acknowledge the work of others and don't worry too much. If you make money out of your product or services and/or if you may cause damage to someone, you must take competent legal advice. That won't protect you, but it will warn you about the risks and possibly help to mitigate them.


问:
Storing tokens during lexing stage
I am currently implementing a lexer that breaks XML files up into tokens, I'm considering ways of passing the tokens onto a parser to create a more useful data structure out of said tokens - my current plan is to store them in an arraylist and pass this to the parser , would a link list where each token points to the next be better suited? Or is being able to access tokens by index easier to make a parser for? Or is this all a terrible strategy?

Also if anyone has used antlr , I know it uses a token stream to pass tokenized input to the parser, how can the parser make decisions on if the input is valid / create a data structure if it does not have all the tokens from the input yet?

答:
Common parsing techniques rely on inspecting a single 'current' token from a stream of such tokens. In some variations a certain amount of lookahead is required, but is usually provided from within the parser and not by indexing forwards and backwards across the lexer stream.

In other words the data structure you will most likely need is some kind of stream. The usual way of implementing this is with a function-based API, with functions like peek() and movenext().

Given a 'stream of token', the details of how you structure that internally are relatively unimportant. You might use an in-memory queue, a producer-consumer queue, a yield/generator or any of a multiplicity of other techniques.

My strong recommendation would be to do the 'simplest thing that could possibly work'. The interesting and challenging parts of your problem are yet to come.

Title: Storing tokens during lexing stage


问:
Performance of One API vs Multiple API's
I was having a conversation with a colleague and although my opinion makes sense to me, I wasn't able to back it up. I'm in the process of creating an API that will be hit hundreds of thousands of times per day. It's fairly simple, and will just be doing some inserts into a relational database. There are essentially 3 functions I would need to create. The question is, what would have better performance, creating one API with different controllers (using .NET Web API or NodeJS something like that) or 3 different API's.

My thought is that, for example with the .NET Web API, no matter whether there are 1 or 3 they are all being hosted, and using the same resources. His thought was that having 3 API's would be 3 times faster because it would have 3 times the resources. I simply didn't have the proof to disprove that.

答:
I think the performance cost of 1 copy versus 3 for an API being hit "hundreds of thousands of times per day" is fairly negligible; either way, they must both share some of the same resources, and be subject to the same potential bottlenecks.

What I'd be more concerned with is the additional cognitive overhead of having 3 APIs, in terms of server maintenance, codebase maintenance and development for the consumers of the API(s). Regardless of whether having 3 distinct APIs gives any kind of performance boost, I would question whether it actually makes sense.

For example, having create, read and update actions for a resource on separate APIs (and by separate I mean differing (sub)domains eg readApi.example.com versus writeApi.example.com) makes no sense. The only thing this does is force developers to remember that reading and writing a resource live in different places, and force you to document that fact.

If it turns out that one action is a lot more costly than any other, or is being a resource hog, you might consider putting the API behind a load balancer which directs all requests for that action to a different server, but crucially keeps the API URIs intact. I suspect this is may actually be what your colleague is meaning by having more than 1 API.

However, in the case of a pair of APIs for disparate subsystems, which happen to share a database, separated APIs might make sense.


问:
How to design an IDisposable that unconditionally needs to be disposed?
Consider a class that implements IDisposable, and that has members in such a way that it will never become eligible for garbage collection when it is not disposed. And as it will not be garbage collected, it will not have the chance to use the destructor for cleaning up.

As a result, when it is not disposed (e.g. unreliable users, programming errors), resources will be leaked.

Is there a general approach how such a class can be designed to deal with such a situation or to avoid it?

Example:

```<code>using System;

class Program
{
    static void Main(string[] args)
    {
        new Cyclical();
        GC.Collect();
        GC.WaitForPendingFinalizers();
        Console.ReadKey();
    }
}

class Cyclical
{
    public Cyclical()
    {
        timer = new System.Threading.Timer(Callback, null, 0, 1000);
    }

    System.Threading.Timer timer;

    void Callback(object state)
    {
        Console.Write('.');  // do something useful
    }

    ~Cyclical()
    {
        Console.WriteLine("destructor");
    }
}
</code>```

(Omitted IDisposable to keep example short.) This class uses a Timer to do something useful at certain intervals. It needs a reference to the Timer to avoid it is garbage collected.

Let’s assume the user of that class will not dispose it. As a result of the timer, somewhere some worker thread has a reference to the Cyclical instance via the callback, and as a result, the Cyclical instance will never become eligible for garbage collection, and its destructor will never run, and resources will leak.

In this example, a possible fix (or workaround) could be to use a helper class that receives callbacks from the Timer, and that does not have a reference, but only a WeakReference to the Cyclical instance, which it calls using that WeakReference.

However, in general, is there a design rule for classes like this that need to be disposed to avoid leaking resources?

For the sake of completeness, here the example including IDispose and including a workaround/solution (and with a hopefully less distracting name):

```<code>class SomethingWithTimer : IDisposable
{
   public SomethingWithTimer()
   {
      timer = new System.Threading.Timer(StaticCallback,
         new WeakReference<SomethingWithTimer>(this), 0, 1000);
   }

   System.Threading.Timer timer;

   static void StaticCallback(object state)
   {
      WeakReference<SomethingWithTimer> instanceRef
         = (WeakReference<SomethingWithTimer>) state;
      SomethingWithTimer instance;
      if (instanceRef.TryGetTarget(out instance))
         instance.Callback(null);
   }

   void Callback(object state)
   {
      Console.Write('.');  // do something useful
   }

   public void Dispose()
   {
      Dispose(true);
      GC.SuppressFinalize(this);
   }

   protected virtual void Dispose(bool disposing)
   {
      if (disposing)
      {
         Console.WriteLine("dispose");
         timer.Dispose();
      }
   }

   ~SomethingWithTimer()
   {
      Console.WriteLine("destructor");
      Dispose(false);
   }
}
</code>```

If disposed, the timer will be disposed.

If not disposed, the object will become eligible for garbage collection.

答:
If your class contains a IDisposable field you'll need to make that also IDisposable so it can be explicitly Dispose its own fields. Or otherwise guarantee the Dispose happens eventually by adding a Finalize method.

Note that using the destructor for cleanup is not enough because they are not guaranteed to run (at least not in java).

```<code>class Cyclical: IDisposable
{
    public Cyclical()
    {
        timer = new System.Threading.Timer(Callback, null, 0, 1000);
    }

    System.Threading.Timer timer;

    public void Dispose()
    {
        timer.Dispose();
    }

    protected virtual void Finalize()
    {
        Dispose();
    }

    void Callback(object state)
    {
        Console.Write('.');  // do something useful
    }

    ~Cyclical()
    {
        Console.WriteLine("destructor");
        Dispose();
    }
}
</code>```

Body:
If your class contains a IDisposable field you'll need to make that also IDisposable so it can be explicitly Dispose its own fields. Or otherwise guarantee the Dispose happens eventually by adding a Finalize method.

Note that using the destructor for cleanup is not enough because they are not guaranteed to run (at least not in java).

class Cyclical: IDisposable
{
    public Cyclical()
    {
        timer = new System.Threading.Timer(Callback, null, 0, 1000);
    }

    System.Threading.Timer timer;

    public void Dispose()
    {
        timer.Dispose();
    }

    protected virtual void Finalize()
    {
        Dispose();
    }

    void Callback(object state)
    {
        Console.Write('.');  // do something useful
    }

    ~Cyclical()
    {
        Console.WriteLine("destructor");
        Dispose();
    }
}


答:
If you can access tokens with an index, there's the temptation to jump ahead or behind, and you can do so, however you generally wind up with very hard code to understand.  Good parsers have a grammar which determines what they should look for next based on where they are in the grammar, and if the grammar is done right, you should never be faced with ambiguity (not know what type of tokens to expect next).

Doing it this way is simpler to write and condenses the problem in creating a good grammar rather than writing a good parser.  It does not really matter if you're using linked lists or an array (unless you're going to be parsing very large XML files, in which case maybe linked lists would be safer).  However, the parser should generally treat this input as a Queue, even if it could jump ahead otherwise with an index.  Lookaheads do exist, but you shouldn't require it for XML grammar.

Hope that helps.

Title: Storing tokens during lexing stage

Body:
I am currently implementing a lexer that breaks XML files up into tokens, I'm considering ways of passing the tokens onto a parser to create a more useful data structure out of said tokens - my current plan is to store them in an arraylist and pass this to the parser , would a link list where each token points to the next be better suited? Or is being able to access tokens by index easier to make a parser for? Or is this all a terrible strategy?

Also if anyone has used antlr , I know it uses a token stream to pass tokenized input to the parser, how can the parser make decisions on if the input is valid / create a data structure if it does not have all the tokens from the input yet?


问:
How important is graceful degradation of JavaScript?
Should web developers continue to spend effort progressively enhancing our web applications with JavaScript, ensuring that features gracefully degrade, thereby ensuring accessibility?  Or should we spend that time focused on new features or other areas of development?

The subtext of that question would be:  How many of our customers/clients/users utilize our websites or applications with JavaScript disabled?  Do you have any projects with requirements that specifically demand JavaScript functionality (almost all of mine do), and do those requirements also demand graceful degradation?

For the sake of asking this question, I pulled up programmers.stackexchange.com without JavaScript enabled, and I was greeted with this message: "Programmers - Stack Exchange works best with JavaScript enabled".  It was difficult to log in, albeit the site seemed to generally work okay.  (I wasn't able to vote up any questions.)

I think this is a satisfactory approach to development.  Imagine the effort involved in making all of the site's features work with plain old HTML and server-side logic. On the other hand, I wonder how many users have been alienated by this approach.

We've all been trained (at least the good developers among us) to use progressive enhancement and to ensure our web applications' dynamic features degrade gracefully.  Is this progressive enhancement just pissing into the wind, or do some of our customers actually utilize certain web services without JavaScript enabled?

答:
When using the console on Linux, I sometimes use Lynx when a GUI is not available. To the best of my knowledge lynx has no JavaScript support at all.

I've also used older mobile browsers with poor if any JavaScript support.

However in those circumstances I don't expect to get full usability from the site. I am usually just using the Internet to look something up quickly (e.g. get a phone number). Therefore I think that your site's non-JavaScript interface should be limited to a passive reference role. Stack Exchange is a great example of this, you can look up answers, but you can't up-vote. It's just there to be used as a reference.


问:
Testing abstract class' behavior
I'm currently refactoring an existing design, which was created without TDD. There is a class hierarchy with one abstract base class and two subclasses. In the original design, these classes were mostly just data holders without much behavior. I have identified some functionality which should be implemented in the base class, and I'd like to write tests for this functionality now. But since the class is abstract, I cannot instantiate it (obviously).

Note: The functionality I'd like to test doesn't invoke any pure virtual methods.

```<code>class Base {}; // Is abstract

TEST(BaseTest, doesSomethingAmazing) {
    Base aBase; // <-------- Not possible!!!
    ASSERT_THAT(aBase.amazeMe(), Eq(AMAZING_RESULT));
}
</code>```

Edit: To clarify a few things:

Inheritance does actually make sense in this situation - both subclasses map to specific domain concepts, and polymorphism helps keep the surrounding code clean

There is behavior which will be used in both subclasses, and which needs data that is common to both classes. So I think it makes sense to put it in a common super class.

I can think of several possible solutions, but none of them seems optimal to me:

Add a subclass to the test code, which implements all pure virtual functions. Downside: Hard to name that subclass in a concise way, understanding the tests becomes harder

Instantiate an object of the subclass instead. Downside: Makes the tests pretty confusing

Add empty implementations to the base class. Downside: Class is not abstract anymore

I tend towards option 3, to make the tests as clear as possible, but I'm not really satisfied with that. Is there a better way I'm not aware of?

答:
You could do the following:

create an abstract base class with only pure virtual methods, for example AmazingObjectInterface;

add a subclass called BasicAmazingObject that defines the non-virtual methods that you need to test;

finally, your 2 original subclasses becomes subclasses of BasicAmazingObject.

This allows you to separate what varies and test what is needed properly.
Obviously, yo would introduce then one more class, but this is the price to pay for the lack of interface support (in the java sense) in C++.

Title: Testing abstract class' behavior