问:
Good practice -apply paradigm to a language that is not fit for it
For example, what happens if a coder tries to code in purely functional-style paradigm in OO-paradigm language(Java)? Will it work? Or the OO nature of Java will not let it happen?

Also, is applying wrong paradigm to language unfitting to it a bad practice or not?
Is it like trying to drive a jet on road instead of flying it?

答:
Most often it is not a great idea to try to directly write functional code, especially pure functional code, in OO languages. This seems to be the consensus around here.

A possible alternative is to do that "indirectly", so to speak, by using a language that is binary compatible with your OO language.

For example, on the JVM you have Scala, or, if you want it more Haskell-like, you have Frege. Both languages can interface with Java. In fact, the Frege compiler creates Java source code and uses the ordinary Java compiler to compile it to bytecode, hence, writing Frege code could be seen as the most efficient way to write pure functional, non-strict Java code.
While Scala compiles directly to bytecode, as far as I know. But this does not hinder interoperability.

Likewise, instead of writing functional C#, you could try F#, which is essentially a ML dialect with support for .NET and C# interoperability.


问:
Are there languages that expand on the STL's iterator types?
Many languages use the concept of an iterator. The c++ STL expands on this with input iterators, output iterators, forward, bidirectional, random access and others. As far as I know, these distinctions don't exist in other languages. In this talk the author of the STL, Alexander Stepanov, talks about iterators (among other things), and mentions the idea and of 2-dimensional iterators. I haven't seen these anywhere.

Question 1: Are there other languages/ libraries that expand on iterators and/or use 2-dimensional iterators?

Question 2: Could anyone point me to some good resources on iterator theory (if that is what it's called)?

答:
Well, Java's ListIterator is bidirectional. In general I am not sure how much linguistic support is needed for iterators. Some syntactic sugar sometimes helps (see Scala's for loop for the most advanced I know of off hand).

As to iterator theory, I'm pretty sure ever iterator is itself a data structure, or is backed by one. Therefore I'd wager there is no "iterator theory", the study of data structures covers it.

The data structure I can think of that generalizes iteration the most is http://en.wikipedia.org/wiki/Zipper_%28data_structure%29

ContentLicense: CC BY-SA 3.0


问:
Writing data driven reflection based tests to ensure design completeness
When writing software I'm often forced to at some point to make a decision that involves a design pattern of "by convention" naming and behavioral patterns.  This normally makes me feel kind of slimy as a .NET developer because nearly everything is statically typed (arguably even the dynamic type is statically typed, but others have covered this well, go read their blogs, they will thank you for it.)

Naturally I encountered others with opposing views who felt that in many cases, convention based naming and behavioral patterns are actually helpful in that they allow for cleaner, more readable, and more consistent code. It was even stated that depending on how far that convention is taken, for instance into a type reflection name determined behavior scenario, that it might even enforce good naming by breaking functionality if naming in inconsistent with the established conventions.

All of this brought me around to the place where the love and passion for development goes to die, "Testing."  I came up with the following hypothesis:

Using naming conventions and associated behavioral or structural rules associated with those conventions, it should be possible to write tests for the product that enforce that behaviors and structures associated with names are implemented correctly by reflecting the available target binaries. Furthermore it should also be possible to enforce a by convention design that doesn't allow for the misuse of naming conventions by means of having names that fall under the naming conventions that don't follow those same behavioral or structural rules to be used inappropriately (i.e something with the word Locator in the type name that doesn't implement the service locator pattern.)

Has anyone ever investigated this kind of architectural and design testing and provability? What have your experiences been with writing architecture and convention tests?  What challenges have you faced and what solutions have you devised?  Are there frameworks or tools for doing this?  Is there research on the subject done that has been peer reviewed?

答:
Yep, this would be great in theory…

Indeed, naming design patterns improves readability. This is actually the goal of design patterns in the first place. It's much simpler to say:

I used an abstract factory, but maybe we should start switching to a builder for more flexibility.

to your colleague when explaining the structure of your code, rather than:

I made a parent class which is inherited by a few other classes, given that each of those classes have an intent to create complex objects; now, we should start creating those objects by calling different methods which will progressively extend each object, because it will allow us to customize the way we extend them depending on the circumstances.

The first version is clear (unless the person you speak to has no idea what a factory or a builder is). The second version is difficult to understand and is subject to interpretation.

Enforcing naming conventions for design patterns is useful as well. This would permit the beginners to be accustomed more quickly with those patterns. Learning and applying design patterns is hard, and a help from a static checking tool would greatly improve the learning curve. If you tried to implement a wrapper, but instead created an adapter, static checking tool will show you your mistake, with a bonus point of telling you that you're actually using an adapter.

…but it's hard to do in practice

So, can you enforce naming conventions for design patterns in practice?

I'm not so sure. Here are a few reasons:

A design pattern is easy to understand for an human, but not for a machine. It's not like a strict rule such as "You should always enclose objects which implement IDisposable into a using" : such statement is easy to check for an application like FxCop/Code analysis. A design pattern is... well, a pattern. It doesn't have a strict structure; there are multiple ways to implement it, while even slightest changes can destabilize a static checker.

For example, take a strategy pattern. Outside an academic simplistic example, the static checker would have a hard time knowing if the pattern is used or not. Example:

```<code>/// <param name="combine">A function which takes two consecutive entries and combines
/// them into a single entry to print.</param>
public void GeneratePdf(
    Consignee consignee,
    IEnumerable<Entry> entries,
    Func<Entry, Entry, ComplexEntry> combine)
{
}
</code>```

The behavior can be switched at runtime by using a different function as an argument of combine parameter. This doesn't mean that this is a strategy pattern. Maybe in order to combine several entries, some advanced techniques should be used, those techniques being held by the caller library, so using them from the called one is impossible, because of circular dependencies.

In the same way, definitions are not strict enough.

The IDisposable rule above is extremely strict. You have an object with a specific interface? Either you put it inside a using, and the rule will be satisfied, or you don't. Most rules (as well as the one with IDisposable) have exceptions, but those exceptions are also extremely strict and precise.

Design patterns, on the other hand, have definitions, but those definitions can be bent in order to accommodate different situations. For example, would a static readonly field be a singleton? What about a property with a backing field and a lock? Those two situations are radically different, and still, they can represent a singleton.

Imagine how hard it would be to check if something is an adapter or a fluent interface. For example, would any method of a class which returns an instance of the class itself be considered a fluent interface?

Static checking is mostly used by developers who know their job. They mostly don't need a tool which would tell that they are using Strategy keyword, but not using a strategy pattern. Either they are actually using a strategy pattern, and the static checker was wrong, or they are consciously naming the class/method in this way, without any intent of using an actual strategy pattern.

Beginners, i.e. persons who can actually benefit from such static checker, wouldn't use it, because they don't know how to use static checkers, and even if they know, they see such tools more as a disturbance, an annoying thing which bothers them with lots of hard to understand warnings.

To conclude, enforcing naming conventions for design patterns is a difficult task, and would very probably give a lot of false positives and false negatives. It will not be very useful, but may be very annoying instead.

By the way, there is a sort of very smart static checkers: your peers. If somebody misuses a design pattern, it will be highlighted during a code review. Static checkers are excellent to do basic repetitive work, like checking the conformity of the code to strict rules. Keep this basic checking for them, while the choices requiring thinking and making decisions will remain a task of developers checking the code during a code review.

Body:
Yep, this would be great in theory…

Indeed, naming design patterns improves readability. This is actually the goal of design patterns in the first place. It's much simpler to say:

I used an abstract factory, but maybe we should start switching to a builder for more flexibility.

to your colleague when explaining the structure of your code, rather than:

I made a parent class which is inherited by a few other classes, given that each of those classes have an intent to create complex objects; now, we should start creating those objects by calling different methods which will progressively extend each object, because it will allow us to customize the way we extend them depending on the circumstances.

The first version is clear (unless the person you speak to has no idea what a factory or a builder is). The second version is difficult to understand and is subject to interpretation.

Enforcing naming conventions for design patterns is useful as well. This would permit the beginners to be accustomed more quickly with those patterns. Learning and applying design patterns is hard, and a help from a static checking tool would greatly improve the learning curve. If you tried to implement a wrapper, but instead created an adapter, static checking tool will show you your mistake, with a bonus point of telling you that you're actually using an adapter.

…but it's hard to do in practice

So, can you enforce naming conventions for design patterns in practice?

I'm not so sure. Here are a few reasons:

A design pattern is easy to understand for an human, but not for a machine. It's not like a strict rule such as "You should always enclose objects which implement IDisposable into a using" : such statement is easy to check for an application like FxCop/Code analysis. A design pattern is... well, a pattern. It doesn't have a strict structure; there are multiple ways to implement it, while even slightest changes can destabilize a static checker.

For example, take a strategy pattern. Outside an academic simplistic example, the static checker would have a hard time knowing if the pattern is used or not. Example:

/// <param name="combine">A function which takes two consecutive entries and combines
/// them into a single entry to print.</param>
public void GeneratePdf(
    Consignee consignee,
    IEnumerable<Entry> entries,
    Func<Entry, Entry, ComplexEntry> combine)
{
}

The behavior can be switched at runtime by using a different function as an argument of combine parameter. This doesn't mean that this is a strategy pattern. Maybe in order to combine several entries, some advanced techniques should be used, those techniques being held by the caller library, so using them from the called one is impossible, because of circular dependencies.

In the same way, definitions are not strict enough.

The IDisposable rule above is extremely strict. You have an object with a specific interface? Either you put it inside a using, and the rule will be satisfied, or you don't. Most rules (as well as the one with IDisposable) have exceptions, but those exceptions are also extremely strict and precise.

Design patterns, on the other hand, have definitions, but those definitions can be bent in order to accommodate different situations. For example, would a static readonly field be a singleton? What about a property with a backing field and a lock? Those two situations are radically different, and still, they can represent a singleton.

Imagine how hard it would be to check if something is an adapter or a fluent interface. For example, would any method of a class which returns an instance of the class itself be considered a fluent interface?

Static checking is mostly used by developers who know their job. They mostly don't need a tool which would tell that they are using Strategy keyword, but not using a strategy pattern. Either they are actually using a strategy pattern, and the static checker was wrong, or they are consciously naming the class/method in this way, without any intent of using an actual strategy pattern.

Beginners, i.e. persons who can actually benefit from such static checker, wouldn't use it, because they don't know how to use static checkers, and even if they know, they see such tools more as a disturbance, an annoying thing which bothers them with lots of hard to understand warnings.

To conclude, enforcing naming conventions for design patterns is a difficult task, and would very probably give a lot of false positives and false negatives. It will not be very useful, but may be very annoying instead.

By the way, there is a sort of very smart static checkers: your peers. If somebody misuses a design pattern, it will be highlighted during a code review. Static checkers are excellent to do basic repetitive work, like checking the conformity of the code to strict rules. Keep this basic checking for them, while the choices requiring thinking and making decisions will remain a task of developers checking the code during a code review.


问:
Ensuring that headers are explicitly included in CPP file
I think it's generally good practice to #include the header for any types used in a CPP file, regardless of what is already included via the HPP file. So I might #include <string> in both my HPP and CPP, for example, even though I could still compile if I skipped it in the CPP. This way I don't have to worry about whether my HPP used a forward declaration or not.

Are there any tools that can enforce this #include coding style? Should I enforce this coding style?

Since the preprocessor/compiler doesn't care whether the #include is coming from the HPP or CPP, I get no feedback if I forget to follow this style.

答:
Should I enforce this coding style?

Probably not.  My rule is this: header file inclusion cannot be order dependent.

You can verify this quite easily with the simple rule that the first file included by x.c is x.h.


答:
This is one of those "should" rather than "shall" kinds of coding standards. The reason is that you would pretty much have to write a C++ parser to enforce it.

A very common rule for header files is that they must stand by themselves. A header file must not require that some other header files be #included before including the header in question. This is a testable requirement. Given some random header foo.hh, the following should compile and run:

```<code>#include "foo.hh"
int main () {
   return 0;
}
</code>```

This rule has consequences with regard to use of other classes in some header. Sometimes those consequences can be avoided by forward declaring those other classes. This isn't possible with a lot of the standard library classes. There's no way to forward declare a template instantiation such as std::string or std::vector<SomeType>. You have to #include those STL headers in the header even if the only use of the type is as an argument to a function.

Another problem is with stuff that you incidentally drag in. Example: consider the following:

file foo.cc:

```<code>#include "foo.hh"
#include "bar.hh"

void Foo::Foo () : bar() { /* body elided */ }

void Foo::do_something (int item) {
   ...
   bar.add_item (item);
   ...
}
</code>```

Here bar is a class Foo data member that is of type Bar. You've done the right thing here and have #included bar.hh even though that would have to have been included in the header that defines class Foo. However, you haven't included the stuff used by Bar::Bar() and Bar::add_item(int). There are many cases where these calls can result in additional external references.

If you analyze foo.o with a tool such as nm, it will appear that the functions in foo.cc are calling all kinds of stuff for which you haven't done the appropriate #include. So should you add #include directives for those incidental external references foo.cc?  The answer is absolutely not. The problem is that it is very hard to distinguish those functions that are called incidentally from the ones that are called directly.

Title: Ensuring that headers are explicitly included in CPP file

Body:
I think it's generally good practice to #include the header for any types used in a CPP file, regardless of what is already included via the HPP file. So I might #include <string> in both my HPP and CPP, for example, even though I could still compile if I skipped it in the CPP. This way I don't have to worry about whether my HPP used a forward declaration or not.

Are there any tools that can enforce this #include coding style? Should I enforce this coding style?

Since the preprocessor/compiler doesn't care whether the #include is coming from the HPP or CPP, I get no feedback if I forget to follow this style.

Body:
This is one of those "should" rather than "shall" kinds of coding standards. The reason is that you would pretty much have to write a C++ parser to enforce it.

A very common rule for header files is that they must stand by themselves. A header file must not require that some other header files be #included before including the header in question. This is a testable requirement. Given some random header foo.hh, the following should compile and run:

#include "foo.hh"
int main () {
   return 0;
}

This rule has consequences with regard to use of other classes in some header. Sometimes those consequences can be avoided by forward declaring those other classes. This isn't possible with a lot of the standard library classes. There's no way to forward declare a template instantiation such as std::string or std::vector<SomeType>. You have to #include those STL headers in the header even if the only use of the type is as an argument to a function.

Another problem is with stuff that you incidentally drag in. Example: consider the following:

file foo.cc:

#include "foo.hh"
#include "bar.hh"

void Foo::Foo () : bar() { /* body elided */ }

void Foo::do_something (int item) {
   ...
   bar.add_item (item);
   ...
}

Here bar is a class Foo data member that is of type Bar. You've done the right thing here and have #included bar.hh even though that would have to have been included in the header that defines class Foo. However, you haven't included the stuff used by Bar::Bar() and Bar::add_item(int). There are many cases where these calls can result in additional external references.

If you analyze foo.o with a tool such as nm, it will appear that the functions in foo.cc are calling all kinds of stuff for which you haven't done the appropriate #include. So should you add #include directives for those incidental external references foo.cc?  The answer is absolutely not. The problem is that it is very hard to distinguish those functions that are called incidentally from the ones that are called directly.


答: You may be interested in D's ranges.  They are supposed to be based on STL iterators only cleaned up and easier to use.  Here is a pretty good article on them. It even suggests higher order ranges though I don't know if those actually get used in D.</p>

Title: Are there languages that expand on the STL's iterator types?

Body:
Many languages use the concept of an iterator. The c++ STL expands on this with input iterators, output iterators, forward, bidirectional, random access and others. As far as I know, these distinctions don't exist in other languages. In this talk the author of the STL, Alexander Stepanov, talks about iterators (among other things), and mentions the idea and of 2-dimensional iterators. I haven't seen these anywhere.

Question 1: Are there other languages/ libraries that expand on iterators and/or use 2-dimensional iterators?

Question 2: Could anyone point me to some good resources on iterator theory (if that is what it's called)?


问:
Use functions inside a loop declaration
What's the best practice?

This :

```<code>for ($i = 0; $i < count($array); $i++) {
//stuff
}
</code>```

Or, what I usually do :

```<code>$count = count($array);
for($i = 0; $i < $count; $i++) {
//stuff
}
</code>```

Is it the same with the magic of compiler optimization?

答:
Profile and see it yourself.

In general, the first sample will execute count() on every iteration. This may drastically reduce the performance.

But:

In some languages and/or some cases, compilers may optimize it. But I wouldn't rely on it, since most of the time, optimizing such thing is risky.

The performance difference may be too minor to bother.

For example, in C#, using a for (var i = 0; i < collection.Count(); i++) on a lazy collection which hits a database may lead to a disaster. No compilers would optimize this, since they won't know if you're just reading a read-only database or if you're reading it while at the same time modifying it as well. But in all cases, you shouldn't use for in a first place in such context.

A rule of thumb:

Use a variable outside for if you know that the collection will not change when you're in a loop,

Count the number of elements in a for if the collection size might change when you're in a loop,

Ask yourself it other techniques, like simply iterating through a collection until it ends, are not more appropriate.

Title: Use functions inside a loop declaration


答:
it depends on whether //stuff changes $array (i.e. the length of the array).

The first variant is more explicit since you can directly see that the length of the array is the limit of the loop, it could be slightly slower than the second, but in interpreted languages this should not be too much of a problem.

Title: Use functions inside a loop declaration

Body:
What's the best practice?

This :

```<code>for ($i = 0; $i < count($array); $i++) {
//stuff
}
</code>```

Or, what I usually do :

```<code>$count = count($array);
for($i = 0; $i < $count; $i++) {
//stuff
}
</code>```

Is it the same with the magic of compiler optimization?


问:
Is this pattern bad?
I notice that when I code I often use a pattern that calls a class method and that method will call a number of private functions in the same class to do the work. The private functions do one thing only. The code looks like this:

```<code>public void callThisMethod(MyObject myObject) {
    methodA(myObject);
    methodB(myObject);  // was mehtodB before
}

private void methodA(MyObject myObject) {
    //do something
}

 private void methodB(MyObject myObject) {
    //do something
}
</code>```

Sometimes there are 5 or more private methods, in the past I have moved some of the private methods into another class, but there are occasions when doing so would be creating needless complexity.

The main reason I don't like this pattern is that is not very testable, I would like to be able to test all of the methods individually, sometimes I will make all of the methods public so can I can write tests for them.

Is there a better design I can use?

答:
It's a good pattern. This is what Uncle Bob refers to when he talks about extracting til you drop.

It shouldn't affect your tests though. You should only be testing the public interface. Yes, you can reflect your way in and test the private methods, but you're still going to have to test them again when you test your public methods, so it doesn't solve the perceived problem.

The "problem" comes when you're testing a private method multiple times because you have multiple public methods using them.

Sometimes, in fact more frequently than you might think, this doesn't matter. Particularly if you're testing by behaviour, rather than trying to test each line of code. All you want to know is "Does this public method do what it's supposed to do?" You don't care about the implementation details.

It does matter, however, when you're testing the same piece of complex logic repeatedly, because it adds multiple tests to each behaviour. At that point, simply extract it into a service and mock it out.

Title: Is this pattern bad?


问:
How to ascertain from the users if performance tuning has had the desired effect
So you've made some code changes that should hopefully speed up some part of an application. But there is just one problem - you don't know how it will perform in live.

Different networks, different machines, different memory, different configuration, different times of day, different users, different server loads etc etc etc

So...

(a) Do you ask them if that bit of the application has got faster?

(b) Do you ask them to monitor that part of the application?

Or...

(c) Do you just ask them to see if they notice any difference in the application in general? After all, you can't be 100% sure you haven't affected something else.

Each of these approaches would seem to have problems (I know this as I've tried them all):

(a) You're asking a leading question. Before such a fix goes life, there is an emperor's new clothes scenario. The developer believes the code should be faster so there is some kind of crusade to get everyone believing it before it goes live. So...it goes live. Some people say it is faster, some slightly slower and others about the same. What then?

(b) Again: Some people say it is faster, some slightly slower and others about the same. What then?

(c) You're no longer asking a leading question, but you start getting hit with a whole torrent of issues that people have known about for months (maybe years) but you've now opened Pandora's box. How can you be sure which if these (if any) are new issues?

Or maybe I should be asking different questions entirely. Any thoughts?

EDIT:

No doubt there are processes leading up to this point that could potentially be improved. But the nub of the question is this:

The change is tested and has been put live. You have a myriad of stats to prove the changes should improve performance. Your boss has given the stats a once over but now wants to make sure the users are happy before signing off the release. What question(s) should you be asking the users?

答: Add a configuration switch to choose between old and new coding and put it into the production system. Run it one week with each setting, measure, and compare.</p>


答: The particular optimization in question goes by a couple of names typically hoisting or loop invariant code motion.  It is a fairly common optimization performed by compilers.  If you are in a compiled language don't worry about it, it is probably taken care of.  If you are in an interpreted language then weather or not it happens is less certain.  </p>

Title: Use functions inside a loop declaration


问:
Writing a Compiler Compiler - Insight on Use and Features

This is part of a series of questions which focuses on the sister project to the Abstraction Project, which aims to abstract the concepts used in language design in the form of a framework.  The sister project is called OILexer, which aims to construct a parser from grammar files, without the use of code injection on matches.

Some other pages associated to these questions, related to structural typing, can be viewed here, and ease of use, found here.  The meta-topic associated to an inquiry about the framework and the proper place to post can be found here.

I'm getting to the point where I'm about to start extracting the parse tree out of a given grammar, followed by a Recursive Descent parser which uses DFA to discern forward paths (similar to ANTLR 4's LL(*)), so I figured I'd open it up to get insight.

In a parser compiler, what kinds of features are ideal?

So far here is a brief overview of what's implemented:

Templates

Look ahead prediction, knowing what's valid at a given point.

Rule 'Deliteralization' taking the literals within rules and resolving which token they're from.

Nondeterministic Automata

Deterministic Automata

Simple lexical state machine for token recognition

Token automation methods:

Scan - useful for comments: Comment := "/*" Scan("*/");

Subtract - Useful for Identifiers: Identifier := Subtract(IdentifierBody, Keywords);

Ensures the identifier doesn't accept keywords.

Encode - Encodes an automation as a series X count of base N transitions.

UnicodeEscape := "\\u" BaseEncode(IdentifierCharNoEscape, 16, 4);

Makes a unicode escape in hexadecimal, with hex 4-transitions.  The difference between this and: [0-9A-Fa-f]{4} is the resulted automation with Encode limits the allowed set of hexadecimal values to the scope of IdentifierCharNoEscape.  So if you give it \u005c, the encode version will not accept the value.  Things like this have a serious caveat: Use sparingly.  The resulted automation could be quite complex.

What isn't implemented is CST generation, I need to adjust the Deterministic automations to carry over the proper context to get this working.

For anyone interested, I've uploaded a pretty printed of the original form of the T*y♯ project.  Each file should link to every other file, I started to link in the individual rules to follow them, but it would've taken far too long (would've been simpler to automate!)

If more context is needed, please post accordingly.

Edit 5-14-2013:
I've written code to create GraphViz graphs for the state machines within a given language.  Here is a GraphViz digraph of the AssemblyPart.  The members linked in the language description should have a rulename.txt in their relative folder with the digraph for that rule.  Some of the language description has changed since I posted the example, this is due to simplifying things about the grammar.  Here's an interesting graphviz image.

答:
I've been working on a lot of parsing recently, and some of the key features are:

A programmatic API -- so it can be used from within a programming language, ideally by simply importing a library.  It can have a GUI or BNF-like interface as well, but the programmatic one is the key, because you can re-use your tooling, IDE, static analysis, testing, language abstraction facilities, programmer familiarity, documentation generator, build process, etc.  Plus, you can interactively play with tiny parsers, which dramatically reduces the learning curve.  These reasons place it at the top of my "important features" list.

Error reporting, as @guysherman mentioned.  When an error is found, I want to know where the error was and what was going on when it happened.  Unfortunately, I haven't been able to find good resources for explaining how to generate decent errors when backtracking comes in to play.  (Although note @Sk-logic's comment below).

Partial results.  When parsing fails, I want to be able to see what was successfully parsed from the part of the input that was before the location of the error.

Abstraction.  You can never build in enough functions, and the user will always need more, so trying to figure out all the possible functions up-front is doomed to failure.  Is this what you mean by templates?

I agree with your #2 (look-ahead prediction).  I think it helps to generate good error reports.  Is it useful for anything else?

Support for building a parse tree as parsing occurs, perhaps:

a concrete syntax tree, for which the structure of the tree corresponds directly to the grammar and includes layout information for error reporting of later phases.  In this case, the client shouldn't have to do anything to get the right tree structure -- it should depend directly on the grammar.

An abstract syntax tree.  In this case, the user is able to fiddle with any and all parse trees

Some kind of logging.  I'm not sure about this one; maybe to show a trace of the rules the parser has tried, or to keep track of junk tokens such as whitespace or comments, in case (for instance) you want to use the tokens to generate HTML documentation.

Ability to deal with context sensitive languages.  Not sure how important this one is, either -- in practice, it seems cleaner to parse a superset of a language with a context-free grammar, then to check context-sensitive constraints in additional later passes.

Custom error messages, so that I can tune the error reports in specific situations and perhaps more quickly understand and fix problems.

On the other hand, I don't find error-correction particularly important -- although I'm not up to date on current progress.  The problems I've noticed are that the potential corrections that the tools supply are: 1) too numerous, and 2) don't correspond to the actual mistakes made, and so aren't all that helpful.  Hopefully this situation will improve (or perhaps has already done so).

ContentLicense: CC BY-SA 4.0


答:
What I would keep an eye out for though is the amount of times you're passing around your initial object parameter. If all of your private methods are operating on the main parameter, it may be a bit of a code smell. E.g. if you have:

```<code>class Foo {
    public void callThisMethod(Bar myBarObject) {
        methodA(myBarObject);
        methodB(myBarObject);
        methodC(myBarObject);
        methodD(myBarObject);
        methodE(myBarObject);

        …

        methodZ(myBarObject);

    }
}

class Bar {
    …
}
</code>```

This points to low cohesion between the methods of Foo with that class — The methods seem to have more in common with Bar than with Foo. If that's the case, consider moving related methods into the class that they're operating on (see the Law of Demeter).

If that's not the case though, there's nothing wrong with having methods that do just one thing, or with testing your application via it's public methods rather than the private internals (as you can still 'exercise' all of the use cases of these methods, but it leaves you freer to refactor these methods later on if you so choose).

Title: Is this pattern bad?

Body:
I notice that when I code I often use a pattern that calls a class method and that method will call a number of private functions in the same class to do the work. The private functions do one thing only. The code looks like this:

```<code>public void callThisMethod(MyObject myObject) {
    methodA(myObject);
    methodB(myObject);  // was mehtodB before
}

private void methodA(MyObject myObject) {
    //do something
}

 private void methodB(MyObject myObject) {
    //do something
}
</code>```

Sometimes there are 5 or more private methods, in the past I have moved some of the private methods into another class, but there are occasions when doing so would be creating needless complexity.

The main reason I don't like this pattern is that is not very testable, I would like to be able to test all of the methods individually, sometimes I will make all of the methods public so can I can write tests for them.

Is there a better design I can use?

Body:
What I would keep an eye out for though is the amount of times you're passing around your initial object parameter. If all of your private methods are operating on the main parameter, it may be a bit of a code smell. E.g. if you have:

class Foo {
    public void callThisMethod(Bar myBarObject) {
        methodA(myBarObject);
        methodB(myBarObject);
        methodC(myBarObject);
        methodD(myBarObject);
        methodE(myBarObject);

        …

        methodZ(myBarObject);

    }
}

class Bar {
    …
}

This points to low cohesion between the methods of Foo with that class — The methods seem to have more in common with Bar than with Foo. If that's the case, consider moving related methods into the class that they're operating on (see the Law of Demeter).

If that's not the case though, there's nothing wrong with having methods that do just one thing, or with testing your application via it's public methods rather than the private internals (as you can still 'exercise' all of the use cases of these methods, but it leaves you freer to refactor these methods later on if you so choose).


问:
Re-architecting a classic inheritance design
I have the opportunity to rewrite a core piece of a project (C#) that is inheritance-heavy and feels increasingly restrictive in how it is designed. The scenario is pretty simple, imagine an application that is built to handle various small tasks. Every task is unique in it's functionality so it implements an ITask interface with a few simple methods that get implemented by each task class (e.g. Init(), Start(), Stop(), etc).

In addition to the ITask interface there is also an abstract BaseTask class that all tasks inherit from. This BaseTask class is sort of an 'everything but the kitchen sink' approach that contains useful pieces of functionality that the tasks often require. For example, all tasks record their status and progress the exact same way so this logic is defined in the BaseTask and available to all children through a protected method. Or to give another example, some tasks have to send email notifications out when certain conditions are met, so again, the BaseTask provides access to the core smtp functionality of the app for this purpose. There are many examples of these kind of 'helper' methods/properties

The problem of course is that this base class has already grown unwieldy and cluttered with properties and methods that are not universal to all tasks and it's starting to introduce more problems than it is solving. For example, anytime a change is required to the base class you find yourself in a position where you might wind up breaking some (or all) of the tasks. It also just seems like its breaking encapsulation and the single responsibility principal. It's also quite clear how this happened in the first place (and a common occurrence too). Initially this was a very small, specialized application but it blew up in terms of scope and size very quickly and what was initially probably not a bad decision architecturally has proven inflexible and awkward.

Where would you start with something like this? How would you approach the problem and what principals or design patters would you choose? Thank you very much

答: Do like @pdr suggested, it is a good solution. To avoid the interface hell mentioned in a comment, consider to use the Observer pattern. That way, you can add plugins with new functionality at any time without changing any existing (task) code.


问:
What is the name of λx.λf.fx (like reverse apply) in lambda calculus? Does the corresponding function have a standard name in programming?
What is the name of λx.λf.fx in lambda calculus?

Does the corresponding function have a standard name in functional programming languages, like Haskell?

In object oriented programming, is there a usual name for a method foo which takes a function as an argument, such that x.foo(f) returns f(x)?

答:
In Haskell, \x.\f.f x is flip ($) which as $ is read as apply, I would read as reverse apply.

Roughly based on https://stackoverflow.com/questions/4090168/is-there-an-inverse-of-the-haskell-operator


问:
How to handle conflicts between developers in your team?
This is happening in every team.

For some reasons, conflicts arise in the team and they affect the overall motivation and productivity.

What is your recommended approach to solve that common problem?

Examples:

one part of the team wants to implement dependency injection, the other part think it's a waste of time.

some developers think the rest of the team is slowing down development (which explains why they are late on the schedule)

personal incompatibilities between one or more developers

one developer refuse to talk to another one (without apparent reason)

答:
You should have them battle it out in a "tech off" each side gets a box of parts--a disassembled computer, he who gets the machine built and booting first wins.

if that doesn't work for you, you should try a machete fight, or even a chainsaw fight.

ContentLicense: CC BY-SA 2.5


答:
I'm wondering if you're trying to implement the Command Pattern via private methods, and you might find switching to a command pattern easier for what you are doing.

What you have now is this:

```<code>public void callThisMethod(MyObject myObject) {
    methodA(myObject);
    mehtodB(myObject)
}

private void methodA(MyObject myObject) {
    //do something
}

private void methodB(MyObject myObject) {
    //do something
}
</code>```

You could implement the same thing using commands and a dispatcher.

```<code>public interface Command {
    void Execute(Context c);
}

public class Context {
    // this holds shared data
}

public class Dispatcher
{
    private List<Command> _commands = new List<Command>();

    public void Add(Command cmd)
    {
       _commands.Add(cmd);
    }

    public void Run(Context c)
    {
       foreach(Command cmd in _commands) { cmd.Execute(c); }
    }
}
</code>```

You would then implement your private methods now as commands.

```<code>public class CommandA : Command { ... }
public class CommandB : Command { ... }
</code>```

Any special state information is defined in the Context class which will be passed to each command. To run the code you would add the commands to the dispatcher and run it.

```<code>Dispatcher d = new Dispatcher();
d.Add(new CommandA());
d.Add(new CommandB());
d.Run(new Context());
</code>```

The advantage of this approach is that it decouples the commands from each other, and you use the Context class to make everything work together. You can also add logic to what commands are created, and what parameters are used to instantiate them.

Some other tips, you can create singletons of commonly used commands to reduce overhead in creating new ones all the time.

This approach is highly testable as each command can be isolated.

The downside is that a large collection of commands can become difficult to maintain. It's better to create fat commands that can do a lot of things, than simple small commands in large number.

Title: Is this pattern bad?

Body:
I'm wondering if you're trying to implement the Command Pattern via private methods, and you might find switching to a command pattern easier for what you are doing.

What you have now is this:

public void callThisMethod(MyObject myObject) {
    methodA(myObject);
    mehtodB(myObject)
}

private void methodA(MyObject myObject) {
    //do something
}

private void methodB(MyObject myObject) {
    //do something
}

You could implement the same thing using commands and a dispatcher.

public interface Command {
    void Execute(Context c);
}

public class Context {
    // this holds shared data
}

public class Dispatcher
{
    private List<Command> _commands = new List<Command>();

    public void Add(Command cmd)
    {
       _commands.Add(cmd);
    }

    public void Run(Context c)
    {
       foreach(Command cmd in _commands) { cmd.Execute(c); }
    }
}

You would then implement your private methods now as commands.

public class CommandA : Command { ... }
public class CommandB : Command { ... }

Any special state information is defined in the Context class which will be passed to each command. To run the code you would add the commands to the dispatcher and run it.

Dispatcher d = new Dispatcher();
d.Add(new CommandA());
d.Add(new CommandB());
d.Run(new Context());

The advantage of this approach is that it decouples the commands from each other, and you use the Context class to make everything work together. You can also add logic to what commands are created, and what parameters are used to instantiate them.

Some other tips, you can create singletons of commonly used commands to reduce overhead in creating new ones all the time.

This approach is highly testable as each command can be isolated.

The downside is that a large collection of commands can become difficult to maintain. It's better to create fat commands that can do a lot of things, than simple small commands in large number.


答:
Most languages allow you to initialize multiple variables during the declaration of a for statement. In all languages the condition component of a for statement is evaluated for each iteration of the loop. So the following for($i=0; $i < foo(); $i++) would result in the function foo() being called in each iteration. As long as foo() continues to return a value higher than $i the loop to continue.

This is true in C++, C#, Java and PHP.

Now, in the last example let's assume the function foo() returns a constant value, but it's computationally heavy to calculate it. Therefore, calling foo() for each iteration would slow the execution of the code.

There are two common practices to solve this problem.

```<code>$x = foo();
for($i = 0; $i < $x; $i++) {.....}
</code>```

And

```<code>for($i = 0, $x = foo(); $i < $x; $i++) {....}
</code>```

I prefer the second as it's easier to read what $x does, and what it's used for.

EDIT:

To answer the question, if compiler optimization takes place. The answer is No. All compilers that I've seen will continue to evaluate the condition statement of a for loop for each iteration. If that condition contains a function call such as count() then it will be executed each time.

Title: Use functions inside a loop declaration

Body:
Most languages allow you to initialize multiple variables during the declaration of a for statement. In all languages the condition component of a for statement is evaluated for each iteration of the loop. So the following for($i=0; $i < foo(); $i++) would result in the function foo() being called in each iteration. As long as foo() continues to return a value higher than $i the loop to continue.

This is true in C++, C#, Java and PHP.

Now, in the last example let's assume the function foo() returns a constant value, but it's computationally heavy to calculate it. Therefore, calling foo() for each iteration would slow the execution of the code.

There are two common practices to solve this problem.

$x = foo();
for($i = 0; $i < $x; $i++) {.....}

And

for($i = 0, $x = foo(); $i < $x; $i++) {....}

I prefer the second as it's easier to read what $x does, and what it's used for.

EDIT:

To answer the question, if compiler optimization takes place. The answer is No. All compilers that I've seen will continue to evaluate the condition statement of a for loop for each iteration. If that condition contains a function call such as count() then it will be executed each time.


问:
Threads or ThreadPool? Fixed or Dynamic ThreadPool?
I have a java program which listens on a port for input. Based on Input, it calls a webservice and then returns a success/failure back to the client program.

I fork a thread for each client connection. The response back to the client which connects to the program has to be quick.

These are the choices I am considering

use regular threads

use ExecutorService with newFixedThreadPool

use ExecutorService with newCachedThreadPool

The reason I am considering Pools is because my threads are shortlived - they just call a webservice, return result to the client and close the connection.

I don't think newFixedThreadPool would be the right thing because then connections would be waiting in queues to get a thread.

newCachedThreadPool would have been perfect except for one thing - threads die after a minute. In my case, I get bursts of connections - i.e. multiple connections and then there may be a lull for a few minutes and then again bursts. I think the threads in the CachedThreadPool would die and and would again have to be recreated - so in this case, it may work like #1 sometimes.

Ideally I would have loved to have newCachedThreadPool with a minimum - i.e. a setting which says number of threads would never go below say 20. So idle threads are killed but never allow to go below a minimum threshold.

Is there anything like this available? Or are there any better alternatives?

答:
Interesting question.

I would recommend against newCachedThreadPool. It will spawn as many threads as necessary without any upper limit. It is bad!

The approach suggested by Michael seems good. Use ThreadPoolExecutor and use a number you are comfortable with as the core pool size. Set maximum number of threads to something you wish to tolerate (or your server can handle).

Please note that there is pretty much nothing you can do once you exhaust resource (Queue is full and maximum number of threads are working). In that case, you can do one of the two things: drop new connections or apply back-pressure (don't accept new work by blocking). TPE by default throws RejectedExecutionException when it's full, but it is easy to implement Blocking behaviour. In fact, here's an open source implementation of BlockingThreadPoolExecutor.


问:
How should I behave as a developer in a project that's headed for failure?
I am a developer in a 5-member team and I believe our project is headed for disaster. I'll describe why in a moment, but my question is: how should I behave?

The deadline is in 1.5 months, and I feel no matter what we do, this project will fail. I'm of the opinion that we should just terminate the project and stop wasting our time, but politically I think it's impossible for our manager to do that.

What should I do in this case? Should I put in extra effort, or should I just take it easy? And what should I say to the manager?

Reasons this project is headed for failure:

With deadline approaching many of the must-have features are not finished

Application is unstable and very difficult to use

System is very convoluted, code very hard to understand, very difficult to change - Data model is too driven by a complex relational database (100+ tables)

Unclear leadership; the manager responds to new information with major changes

Almost no automated tests or unit test

Heavily depends on other systems, but no integration tests yet

In fact, we actually just inherited this project (along with the mess) around 1-2 months ago from another dev team under the same manager, who has worked on it for a few months.

答:
I can only reiterate what others have said, but I emphatically emphasize: Always strive for your best work and keep a paper trail. for both CYA and technical reasons.

Any fall out coming your way depends on managements' personal character; but let me tell you it's hell being on the receiving end of incompetent, lying management. But the very worst you'll leave with your self (and peer) respect intact.

Keep good notes of technical aspects of your Death March. When you get the inevitable interview question have you been on a failed project; why did it fail and what did you do to try to prevent it? Bonehead management is not an answer - even if it is the reason.


问:
What are some well known applications written in F#?
As part of a continuing quest for knowledge, I'm spending some time this week learning the basics of F# as an introduction to functional programming. I think I am understanding the construction of software under this model and some of the proposed benefits, but am still a little fuzzy on the real-world use cases.

I was hoping that a F# success stories, or at least a few applications that I'd be familiar with might make it a little clearer about when F# (or any functional programming language) would be appropriate for a project.

So back to the question, what are some well known applications that use F# or a similar functional programming language?

BTW: I am also open to hearing about some lesser-known apps, but if you mention one, please give the basics of what the app is about and why the language used was the appropriate choice.

答:
I've wondered the same thing for awhile know. I really like F# but haven't seen anything in the realm of a commercial app. What I have heard (and quite frequently) is that F# has been used a lot in the financial realm.

What decent web-frameworks exists for functional programming? has some examples of web frameworks for functional programming languages and I know http://cs.hubfs.net/blogs/tomasp/archive/2010/05/09/14050.aspx is an article how to write an ASP.Net MVC 2 Web app in F#.

As I have been searching articles on F# and a lot of examples and people's praise has come in the form of log parsers. But that is always followed up with a caveat of something along the lines of "I'm not allowed to use the language at work" (paraphrased of course). I'll try to find more examples.

I have been toying with the idea of creating a text-based MUD (Multi-User Dungeon) in F# but I never seem to have the time.


问:
design strategy pattern with null checking
When the context class can accept a null strategy, is there another way to do it without check if its null?

Is this considered a good strategy design implementation?

```<code>class MainApp{
    static void Main(){
        Context context = new Context();
        while(true){
            Strategy strategy = createConcreteStrategy(Console.ReadLine());
            context.setStrategy(strategy);
            context.run();
        }
    }
    static void createConcreteStrategy(string input){
        if( input == "strategyA" ){
            return new StrategyA();
        }
        if( input == "strategyB" ){
            return new StrategyB();
        }
        return null;
    }
}
abstract class Strategy { public abstract void doSomething(); }
class Context{
    Strategy strategy;
    ClassX x;

    public Context(){}
    public void setStrategy(Strategy strategy){
        this.strategy = strategy;
    }
    public void run(){
        if( strategy != null ){
            data = strategy.doSomething();
            x.setData(data);
        }
    }
}
</code>```

答:
There is absolutely a way to avoid checking for null here! Use the null object pattern, i.e.

```<code>class NullStrategy: Strategy {
    public void doSomething() {
    }
}
</code>```

and then the "default" case in createConcreteStrategy is return new NullStrategy() instead of return null, and  then you no longer have to check if strategy is null in run.

If you don't want to call x.setData with a null argument, then you could pass x to the strategy.  Here's one possible implementation:

```<code>class NullStrategy: Strategy {
    public void doSomething(ClassX x) {
        // don't do anything with x
    }
}

class RealStrategy: Strategy {
    public void doSomething(ClassX x) {
        var data = someOperation();
        x.setData(data);
    }
}
</code>```

Pushing an if-statement into an instance of Strategy makes sense to me in this situation.

Body:
There is absolutely a way to avoid checking for null here! Use the null object pattern, i.e.

class NullStrategy: Strategy {
    public void doSomething() {
    }
}

and then the "default" case in createConcreteStrategy is return new NullStrategy() instead of return null, and  then you no longer have to check if strategy is null in run.

If you don't want to call x.setData with a null argument, then you could pass x to the strategy.  Here's one possible implementation:

class NullStrategy: Strategy {
    public void doSomething(ClassX x) {
        // don't do anything with x
    }
}

class RealStrategy: Strategy {
    public void doSomething(ClassX x) {
        var data = someOperation();
        x.setData(data);
    }
}

Pushing an if-statement into an instance of Strategy makes sense to me in this situation.


问:
What should I do in AJAX or PHP?
Since I discovered the joys of AJAX, I tend to do all my requests to the server using AJAX. Is this a good idea?

According to you, what should I do in PHP and what should I do in AJAX?

I like to do my requests to the server with AJAX because I can use it as a kind of web service.

答:
AJAX is a technique, not a language.  You can write the server-side component of an AJAX call in PHP if you want to.  As far as PHP cares, it's just a different type of output.

As to the other question, of "what should I do with AJAX and what should be a full page reload", anything that you would let someone type in a URL for, or come directly to your site from another page for, can be a page reload.  Although if you have a robust enough AJAX implementation, you can go ahead and have all of your site's internal navigation be AJAX calls.

(And "come directly to your site from another page" also means right-clicking to open in a new tab.)

Title: What should I do in AJAX or PHP?


问:
What are the pros and cons of temporary variables vs multiple returns
Take the following examples:

```<code>public static String returnOnce() {
    String resultString = null;
    if (someCondition) {
        resultString = "condition is true";
    } else {
        resultString = "condition is false";
    }
    return resultString;
}

public static String returnMulti() {
    if (someCondition) {
        return "condition is true";
    }
    return "condition is false";
}
</code>```

Is one approach objectively better than the other, or is it just a matter of preference?  The first requires a temporary variable, but has just a single place where the method returns.  Does the decision change if the method is more complex with multiple factors that could change the result?

答:
In the days of old...

In Pascal and Algol one could really only do the first style.  This was known as structured programming.

A function in pascal and the style of programing was:

```<code>Function abs(arg:real;) : real;
Begin
  real retval;
  if retval > 0 then
    reval = arg;
  else
    retval = arg * -1;
  functionName := returnVal;
End;
</code>```

The function returned one parameter that was assigned to it at the end.  This pseudo-variable was influenced likely from Fortran which has a similar notation (but can have multiple returns).  Fortran's multiple entry (one could use the ENTRY statement to have a call jump into the middle of a function) and multiple exit points was one of the reasons that Go To Statement Considered Harmful was written and structured programming came as a reaction from).

In Algol (another influential early language), the return value of a procedure was the last expression evaluated by the procedure.  If you wanted to return something, you needed to carry it all the way to the end and then evaluate it.

This particular style/constraint of programming was often used in academia and influenced a generation of programmers and was a move to more elegant languages away from the 'goto' style code before with Fortran and assembly.

In the modern world...

The second style, if it acts as a guard statement is almost always preferable.

```<code>public static boolean returnMulti(Object arg) {
    if (!validArg) {
        return false;
    }
    more stuff;
    return true;
}
</code>```

Note the 'more stuff' that indicates processing which could be reasonably sizable.  By kicking out the invalid case early, one should be able to read more stuff more easily.

On the other hand, the only one return means that when you are walking backwards through code, there is only one spot that you need to look at.

```<code>funcA
  stuff;
  foo = funcB();
  stuff;
</code>```

Ok, so foo is the return value of funcB()...

```<code>funcB
  stuff;
  if(bar) return something;
  stuff;
  if(qux) return somethingElse;
  stuff;
  if(bletch) return anotherThing;
  stuff;
  if(blarg) return yetAnotherThing;
  stuff;
  return defaultThingy;
</code>```

At this point, you have 5 different spots where you can return from.  You don't know which one and what conditions caused the return value for funcB, it could have been any of then.  This isn't to say the above code is good code, but it isn't uncommon to see.

Using a return variable one would have code that one could find the one return statement in the function and say "it was 5 at this point" and walk backwards through the code to see the flow.

Furthermore, when you have a language with explicit resource management (malloc and free rather than garbage collection), you will find that it is easiest to do a single cleanup of the resources allocated in the function at the end rather than calling them multiple times and missing one.

As to the temproary variable... one will find in many languages that when dissasembling the code for:

```<code>func foo()
  retval = something;
  return retval;

func bar()
  return something;
</code>```

The two compile to exactly the same instructions (with a temporary variable - the compiler has to put the memory somewhere).

See also

Where did the notion of “one return only” come from?

Should a function have only one return statement?

The “Why” behind PMD's rules

Body:
In the days of old...

In Pascal and Algol one could really only do the first style.  This was known as structured programming.

A function in pascal and the style of programing was:

Function abs(arg:real;) : real;
Begin
  real retval;
  if retval > 0 then
    reval = arg;
  else
    retval = arg * -1;
  functionName := returnVal;
End;

The function returned one parameter that was assigned to it at the end.  This pseudo-variable was influenced likely from Fortran which has a similar notation (but can have multiple returns).  Fortran's multiple entry (one could use the ENTRY statement to have a call jump into the middle of a function) and multiple exit points was one of the reasons that Go To Statement Considered Harmful was written and structured programming came as a reaction from).

In Algol (another influential early language), the return value of a procedure was the last expression evaluated by the procedure.  If you wanted to return something, you needed to carry it all the way to the end and then evaluate it.

This particular style/constraint of programming was often used in academia and influenced a generation of programmers and was a move to more elegant languages away from the 'goto' style code before with Fortran and assembly.

In the modern world...

The second style, if it acts as a guard statement is almost always preferable.

public static boolean returnMulti(Object arg) {
    if (!validArg) {
        return false;
    }
    more stuff;
    return true;
}

Note the 'more stuff' that indicates processing which could be reasonably sizable.  By kicking out the invalid case early, one should be able to read more stuff more easily.

On the other hand, the only one return means that when you are walking backwards through code, there is only one spot that you need to look at.

funcA
  stuff;
  foo = funcB();
  stuff;

Ok, so foo is the return value of funcB()...

funcB
  stuff;
  if(bar) return something;
  stuff;
  if(qux) return somethingElse;
  stuff;
  if(bletch) return anotherThing;
  stuff;
  if(blarg) return yetAnotherThing;
  stuff;
  return defaultThingy;

At this point, you have 5 different spots where you can return from.  You don't know which one and what conditions caused the return value for funcB, it could have been any of then.  This isn't to say the above code is good code, but it isn't uncommon to see.

Using a return variable one would have code that one could find the one return statement in the function and say "it was 5 at this point" and walk backwards through the code to see the flow.

Furthermore, when you have a language with explicit resource management (malloc and free rather than garbage collection), you will find that it is easiest to do a single cleanup of the resources allocated in the function at the end rather than calling them multiple times and missing one.

As to the temproary variable... one will find in many languages that when dissasembling the code for:

func foo()
  retval = something;
  return retval;

func bar()
  return something;

The two compile to exactly the same instructions (with a temporary variable - the compiler has to put the memory somewhere).

See also

Where did the notion of “one return only” come from?

Should a function have only one return statement?

The “Why” behind PMD's rules


问:
How can I mirror an SVN trunk repository into a regular network folder?
Me and a small team of engineers are considering using SVN to store our electrical schematics and parts libraries; currently we just have a network folder where we put all of our files. Our company also has a separate SVN server that we have access to.

I was wondering if there was some way that we could use the SVN repository to store our files and schematics, but then somehow have the trunk SVN repository be automatically mirrored into a non-SVN network folder like we currently have.

The reason I am asking for this is because sometimes non-technical people need to access our schematic data, and we don't have enough resources to teach everyone how to use SVN. This way we could have everything under revision control, as well as allowing other people to continue accessing the data in the same way that they are used to.

答: If the SVN server is hosted with Apache, the files and folders can be accessed with normal http or https URLs. This should be as easy to use as the current network drive for those who don't want to learn or install SVN client.</p>


问:
Web applications have "the todo list." What analogous program is there for systems programming?
You can find many frameworks with an example todo list for demonstrating a small but full application in the framework.  You don't have to consider large problems like scaling or caching, but you still exercise most of the fundamentals of that framework in a todo list.

Is there an analogous application for systems-level programming?

答: Not a single one, but different areas of computing have traditions. For writing network services, the canonical functional-though-useless example is to write an echo server (it listens on a port and parrots back everything it hears). The simplest command-line utility imaginable is one that simply returns a specific exit code (Here is an astounding example of just how simple it can be made to be) - it does virtually nothing, but can still be helpful to introduce someone to the code-compile-link-execute cycle. If you count programming languages and libraries, of course there's always "Hello, world!", and almost every language has its perceived weaknesses that everyone tries to fix. For C++, it's writing a better string type;  of Perl, it is jokingly said, that every serious user has tried their hand at a better option-parsing library.


问:
GPL v 3 & Scripts
I'm not asking for legal advice; just some rough guidance.

I have a host application in Java that uses the Rhino JS engine to execute JavaScript. That JavaScript can then make calls into other Java libraries, some of which might be licensed under the GPL.

I distribute my hosting app, the JS files as source and the unmodified Java libs. I have released all of the JavaScript as open source.

Am I also required to release my Java hosting apps source?

答:
I am not a lawyer but from what I understand if you distribute code or binaries that use anything under the GPL, then yes, you need to open source it.

If you're not distributing it outside of your company, you generally don't have to do anything. So if you provide a hosting service with your Java hosting code but don't actually distribute it to others, then you can keep it private to yourself or your company.

Some people consider it a loophole in the GPL which it why the AGPL was created.

Title: GPL v 3 & Scripts


问:
Y combinator and tail call optimizations
The definition of a Y combinator in F# is

```<code>let rec y f x = f (y f) x
</code>```

f expects to have as a first argument some continuation for the recursive subproblems.
Using the y f as a continuation, we see that f will be applied to successive calls as we can develop

```<code>let y f x = f (y f) x = f (f (y f)) x = f (f (f (y f))) x etc...
</code>```

The problem is that, a priori, this scheme precludes using any tail call optimization : indeed, there might be some operation pending in the f's, in which case we can't just mutate the local stack frame associated with f.

So :

on the one end, using the Y combinator require an explicit different continuation than the function itself.

on the othe to apply TCO, we would like to have no operation pending in f and only call f itself.

Do you know of any way in which those two could be reconciled ?
Like a Y with accumulator trick, or a Y with CPS trick ?
Or an argument proving that there is no way it can be done ?

答:
I'm not completely sure about this answer, but it is the best I could come up with.

The y combinator is inherently lazy, in strict languages the laziness must be manually added through extra lambdas.

```<code>let rec y f x = f (y f) x
</code>```

Your definition looks like it requires laziness in order to terminate, or the (y f) argument would never finish evaluating and would have to evaluated whether or not f used it. TOC in a lazy context is more complicated, and furthermore the result of (y f) is repeated function composition without application with the x. I'm not sure this need take O(n) memory where n is the depth of the recursion, but I doubt you could achieve the same type of TOC as is possible with something like (switching to Haskell because I don't actually know F#)

```<code>length acc []    = acc
length acc (a:b) = length (acc+1) b
</code>```

If you aren't aware of it already, the difference between foldl and foldl' in Haskell may shead some light on the situation. foldl is written as would be done in an eager language. But instead of being TOC'd, it is actually worse than foldr because the acculator stores a potentially enormous thunk that cannot be partially evaluated. (This is related to why both foldl and foldl' do not work on infinite lists.) Thus in more recent versions of Haskell, foldl' was added which forces the evaluation of the accumulator each time the function recurs to ensure no enormous thunk is created. I am sure http://www.haskell.org/haskellwiki/Foldr_Foldl_Foldl%27 can explain this better than I.

Body:
I'm not completely sure about this answer, but it is the best I could come up with.

The y combinator is inherently lazy, in strict languages the laziness must be manually added through extra lambdas.

let rec y f x = f (y f) x

Your definition looks like it requires laziness in order to terminate, or the (y f) argument would never finish evaluating and would have to evaluated whether or not f used it. TOC in a lazy context is more complicated, and furthermore the result of (y f) is repeated function composition without application with the x. I'm not sure this need take O(n) memory where n is the depth of the recursion, but I doubt you could achieve the same type of TOC as is possible with something like (switching to Haskell because I don't actually know F#)

length acc []    = acc
length acc (a:b) = length (acc+1) b

If you aren't aware of it already, the difference between foldl and foldl' in Haskell may shead some light on the situation. foldl is written as would be done in an eager language. But instead of being TOC'd, it is actually worse than foldr because the acculator stores a potentially enormous thunk that cannot be partially evaluated. (This is related to why both foldl and foldl' do not work on infinite lists.) Thus in more recent versions of Haskell, foldl' was added which forces the evaluation of the accumulator each time the function recurs to ensure no enormous thunk is created. I am sure http://www.haskell.org/haskellwiki/Foldr_Foldl_Foldl%27 can explain this better than I.


问:
Why doesn't layered architecture translate easily to tiered architecture?
Basically, I'm trying to understand why layered and tiered are that different, and why they don't translate easily to each other.

I understand that layered could be 3 separate class files for UI, BL and DAL. Whereas tiered can be a  Project for the UI, which links to a BL project  which links to a DAL like entity framework, and then a database. So why are/aren't they easily translatable?

Hope that makes sense,
Thanks.

答:
Both concepts introduce a separation of concerns. But for layers, seperation of concerns is usually the main goal. Tiers are used for scalability and load distribution/allocation purposes, and separation of concerns is more a side effect there.

That also explains why the concepts are not easily translatable. In a layered architecture, a feature is usually implemented in the layer where it fits best semantically, and you try to avoid redundancy between layers. In tiers, you implement a feature where you have the computing ressources for it. Redundancy between tiers is common (e.g. replicate some business logic in the UI tier, but in the business logic layer, the check runs only once when data is saved, in the UI layer the check runs after each user input).


答:
I think that the answer is yes.  If you distribute this "package", you do need to release source code for your Java app framework and your Javascript under a license that is compatible with the GPL.  But if you don't distribute the package, then there is no GPL requirement to release your source code.

The AGPL-motivating issue doesn't seem to apply here.  That covers the case where someone builds (for example) a website using GPL'ed components, but doesn't distribute the server-side and therefore doesn't have to release the source code.  (In your case, you ARE distributing your framework.)

There is a caveat to the above.  If the libraries are LGPL or "GPL with Classpath exception" then non open-source code can effectively use the libraries without being "contaminated" by the "viral" GPL release requirements.  Check the licenses for the libraries you are actually using.

The bottom line is that you need to understand what the licenses yourself, make your decisions on that basis, and live with the consequences.  If you want to distribute binaries / bytecodes without releasing your source code, don't use GPL libraries.  Period.

Title: GPL v 3 & Scripts

Body:
I'm not asking for legal advice; just some rough guidance.

I have a host application in Java that uses the Rhino JS engine to execute JavaScript. That JavaScript can then make calls into other Java libraries, some of which might be licensed under the GPL.

I distribute my hosting app, the JS files as source and the unmodified Java libs. I have released all of the JavaScript as open source.

Am I also required to release my Java hosting apps source?


问:
What license is best for this: Software is open source and free to use as long as you don't charge your customers
I'm releasing an open-source jQuery plug-in that is free to use, modify and redistribute as long as you don't directly or indirectly charge your customers. Your software doesn't need to be open-source, it just need to be free. If you charge your customers, you need a commercial license.

I'm not sure about the licensing. http://www.turnjs.com/ is a plug-in that is similarly licensed and it is Non-comercial BSD license. But I can't find the definition for this license online.

Can anyone help me determining the best license for me based on my description? Thanks.

答:
This may not be directly answering your question, but it seems like you're looking for the Creative Commons Attribution-NonCommercial 3.0 Unported license. This allows for users to share and modify the work, under these conditions:

They must attribute their work to you.

They may not use it  for any commercial purposes.


问:
MorphAdorner Licensing confusion
I want to use the MorphAdorner library available free for commercial use. But it uses several other libraries that restrict commercial use (like Gate etc). Can I use this library in my application?</p>

答:
There are three licenses for sub-components of the MorphAdorner library that might restrict its use in your application.

The Gate and NGramJ libraries (contained in MorphAdorner) use the LGPL license. The LGPL effectively requires that it must be possible for a user of your application to replace those libraries (and possibly the MorphAdorner library, depending on how they are integrated into it) with different versions. Using standard dynamic linking practices should be sufficient to satisfy that requirement.

The 'Text Segmentation' part of MorphAdorner has a 'non-profit only' type of license. If you are planning to sell your application, then you either can't use MorphAdorner or you would have to strip that component out.

The XGTagger library uses the CeCILL license, which has similar restrictions as the LGPL.

In summary, you can use the MorphAdorner library as-is if you dynamically link to it and don't try to make a profit out of your application.

Title: MorphAdorner Licensing confusion


问:
What is the best way to represent quantity in stock in domain model?
A Transaction contains one or more LineItem.  One LineItem has a relation with an Item.  Every Item has a number field that represent quantity in stock.

Using this approach, every Transaction creation will need to decrease quantity in Item.  If user update a Transaction then quantity in Item will need to be adjusted.  If user delete a Transaction then quantity in Item will need to be increased.

What is the best way to implement this rule or behaviour in domain model layer? Transaction operations (like create, update, or delete) are located in data access layer.

答:
You can use publish/subscribe pattern for that.

This means that the Item object subscribes to all changes from sources affecting the stock level, such as a change in quantity in the LineItem object, or the creation or deletion of the LineItem object. The Item object then adjusts the stock accordingly.

This needs to happen within the same database transaction to preserve integrity.

I would recommend such an approach only if you have multiple publishers and subscribers, otherwise it is just overkill. For example the stock can be also influenced by running a physical inventory and create documents with correction postings. Or if you keep the value of the inventory in parallel with the stock, the value object might be a subscriber, too.

That pattern works better if you have a framework which all publishers and subscribers use. Basically the framework should make sure that any change in any object is available for subscription. Also it is good idea to model or configure the subscriptions so the subscribers can be tracked.


问:
which open source licence to use with my project?
I am working on a software project in my college.
And I want to make it open source. But I want that people to only contribute to the project.
I don't want that they should also release a project using my source with some modifications.

So what will be the best Licence to use with my project ?

答:
You can distribute the code under the Creative Commons Attribution-No Derivative Works (by-nd) license, but it will generally not be considered to be open source due to the restriction on derived projects.

If your concern is that different, possibly incompatible, versions would start to float around that claim to be the same software, you might be better of by simply requiring that derived projects don't claim to be an official, sanctioned by you, version. One way to do that is to register a trademark on your project. (See here for an example how that can work.)


答:
No "Open Source" license would prevent the creation of derivative works, it would defeat the basic purpose of open source which is "make the code public to increase the community knowledge".

You can check the definition at the "Open Source Iniative" web site.

What you look for seems more a "Work for me for free" license, I'm not sure there's one.

Title: which open source licence to use with my project?

Body:
I am working on a software project in my college.
And I want to make it open source. But I want that people to only contribute to the project.
I don't want that they should also release a project using my source with some modifications.

So what will be the best Licence to use with my project ?


问:
foreach over multiple lists at once
Are there any languages that support foreach over multiple lists at once?  Something like this:

```<code> foreach (string a in names, string b in places, string c in colors) {
      // do stuff with a, b, c
 }
</code>```

Sure, this can be done with a regular for loop:

```<code> for (int n = 0; n<max, n++) {
      a = names[n]; b = places[n]; c = colors[n];
 }
</code>```

but this loses the abstraction of foreach.

My meager google-fu only reveals people asking how to do multi-foreach in various languages that don't support it.  I'm guessing that some language uses it, I just can't figure out which one.

答:
Sure, Python can do that:

```<code>for a, b, c in zip(names, places, colors):
    pass
</code>```

zip builds a list of tuples from the iterables passed to it. Python's for loop supports "unpacking", that is to say the tuples are split into their components. It's a weak form of pattern matching.

Title: foreach over multiple lists at once

Body:
Sure, Python can do that:

for a, b, c in zip(names, places, colors):
    pass

zip builds a list of tuples from the iterables passed to it. Python's for loop supports "unpacking", that is to say the tuples are split into their components. It's a weak form of pattern matching.


答:
In C#, you can transform multiple collections into one collection of tuples, then use a foreach. There is no specific language syntax, but .NET Framework still allows you to do it.

In SQL, you can use join. I'm not sure if the "languages" you're looking for extend to SQL.

Note that in all cases, there is an ambiguity with your simple. What if colors.length < places.length? If places.length > names.length, would the remaining places be simply discarded?

Example for C#:

public static void Main(string[] args)
{
    var names = new[] { "John", "Bill", "Joel" };
    var places = new[] { 1, 2, 3 };
    var colors = new[] { Color.AliceBlue, Color.BlueViolet, Color.DarkMagenta };

    var zip = names.Zip(places, (n, p) => new { n, p }).Zip(colors, (t, c) => new { Name = t.n, Place = t.p, Color = c });

    foreach (var z in zip)
    {
        Console.WriteLine(string.Join(", ", new[] { (object)z.Name, z.Place, z.Color }));
    }

    Console.WriteLine("Press any key to continue...");
    Console.ReadKey(true);
}
```

<p>Or, using an extension method:</p>

<pre class="lang-cs prettyprint-override"><code>public static IEnumerable<Tuple<T1, T2, T3>> ZipSeveral<T1, T2, T3>(this IEnumerable<T1> first, IEnumerable<T2> second, IEnumerable<T3> third)
{
    return first.Zip(second, (a, b) => new { a, b }).Zip(third, (t, c) => Tuple.Create(t.a, t.b, c));
}
</code>```

you can reduce the code to a simple foreach:

foreach (var z in names.ZipSeveral(places, colors))
{
    Console.WriteLine(string.Join(", ", new[] { (object)z.Item1, z.Item2, z.Item3 }));
}
```

Title: foreach over multiple lists at once

Body:
Are there any languages that support foreach over multiple lists at once?  Something like this:

```<code> foreach (string a in names, string b in places, string c in colors) {
      // do stuff with a, b, c
 }
</code>```

Sure, this can be done with a regular for loop:

```<code> for (int n = 0; n<max, n++) {
      a = names[n]; b = places[n]; c = colors[n];
 }
</code>```

but this loses the abstraction of foreach.

My meager google-fu only reveals people asking how to do multi-foreach in various languages that don't support it.  I'm guessing that some language uses it, I just can't figure out which one.

Body:
In C#, you can transform multiple collections into one collection of tuples, then use a foreach. There is no specific language syntax, but .NET Framework still allows you to do it.

In SQL, you can use join. I'm not sure if the "languages" you're looking for extend to SQL.

Note that in all cases, there is an ambiguity with your simple. What if colors.length < places.length? If places.length > names.length, would the remaining places be simply discarded?

Example for C#:

public static void Main(string[] args)
{
    var names = new[] { "John", "Bill", "Joel" };
    var places = new[] { 1, 2, 3 };
    var colors = new[] { Color.AliceBlue, Color.BlueViolet, Color.DarkMagenta };

    var zip = names.Zip(places, (n, p) => new { n, p }).Zip(colors, (t, c) => new { Name = t.n, Place = t.p, Color = c });

    foreach (var z in zip)
    {
        Console.WriteLine(string.Join(", ", new[] { (object)z.Name, z.Place, z.Color }));
    }

    Console.WriteLine("Press any key to continue...");
    Console.ReadKey(true);
}

Or, using an extension method:

public static IEnumerable<Tuple<T1, T2, T3>> ZipSeveral<T1, T2, T3>(this IEnumerable<T1> first, IEnumerable<T2> second, IEnumerable<T3> third)
{
    return first.Zip(second, (a, b) => new { a, b }).Zip(third, (t, c) => Tuple.Create(t.a, t.b, c));
}

you can reduce the code to a simple foreach:

foreach (var z in names.ZipSeveral(places, colors))
{
    Console.WriteLine(string.Join(", ", new[] { (object)z.Item1, z.Item2, z.Item3 }));
}


问:
What Does "The Program Must Process Each Character Before Reading the Next One" Mean?
From the book Think Like a Programmer (emphasis mine)

The Luhn formula is a widely used system for validating identification numbers. Using the original number, double the value of every other digit. Then add the values of the individual digits together (if a doubled value now has two digits, add the digits individually). The identification number is valid if the sum is divisible by 10. Write a program that takes an identification number of arbitrary length and determines whether the number is valid under the Luhn formula. The program must process each character before reading the next one.

In a broader sense, what does it mean to process each character before reading the next one? What does this look like syntactically? What does the opposite mean and what does it look like syntactically?

Update:

For some background, here's my attempt at the problem (in JavaScript):

```<code>Array.prototype.sum = function() {
    var sum = 0,
        itemCount = this.length,
        i;

    for(i = 0; i <= itemCount - 1; i++) {
        sum += this[i];
    }

    return sum;
}

function validateNumberWithLuhnForumla(number) {
    var numbersArray = number.toString().split(''),
        numberCount = numbersArray.length,
        i = 0,
        isValid = false,
        doubledDigit,
        checksum,
        numbersToSum = [];

    for(i = 0; i <= numberCount - 1; i++) {
        if(i % 2 > 0 && i > 0) {
            doubledDigit = numbersArray[i] * 2;
            if(doubledDigit > 9) {
                numbersToSum.push(1, (doubledDigit - 10));
            } else {
                numbersToSum.push(doubledDigit);
            }
        }
    }

    checkSum = numbersToSum.sum();

    if(checkSum % 10 === 0) {
        isValid = true;
    }

    return isValid;
}
</code>```

答: It means that you're allowed to retain the value of one character in memory only until the next input operation happens. This is an idealization of the common practical constraint that an algorithm must be able to process arbitrary input without requiring arbitrary amounts of RAM. A simple practical test is: does your solution work with only a single char variable?


答: The opposite would be for example reading the whole identification number into a string, and then making multiple passes over the digits of the identification number to calculate the Luhn checksum. The question is asking you to calculate the checksum without looking back to previous digits.

Title: What Does "The Program Must Process Each Character Before Reading the Next One" Mean?

Body:
From the book Think Like a Programmer (emphasis mine)

The Luhn formula is a widely used system for validating identification numbers. Using the original number, double the value of every other digit. Then add the values of the individual digits together (if a doubled value now has two digits, add the digits individually). The identification number is valid if the sum is divisible by 10. Write a program that takes an identification number of arbitrary length and determines whether the number is valid under the Luhn formula. The program must process each character before reading the next one.

In a broader sense, what does it mean to process each character before reading the next one? What does this look like syntactically? What does the opposite mean and what does it look like syntactically?

Update:

For some background, here's my attempt at the problem (in JavaScript):

```<code>Array.prototype.sum = function() {
    var sum = 0,
        itemCount = this.length,
        i;

    for(i = 0; i <= itemCount - 1; i++) {
        sum += this[i];
    }

    return sum;
}

function validateNumberWithLuhnForumla(number) {
    var numbersArray = number.toString().split(''),
        numberCount = numbersArray.length,
        i = 0,
        isValid = false,
        doubledDigit,
        checksum,
        numbersToSum = [];

    for(i = 0; i <= numberCount - 1; i++) {
        if(i % 2 > 0 && i > 0) {
            doubledDigit = numbersArray[i] * 2;
            if(doubledDigit > 9) {
                numbersToSum.push(1, (doubledDigit - 10));
            } else {
                numbersToSum.push(doubledDigit);
            }
        }
    }

    checkSum = numbersToSum.sum();

    if(checkSum % 10 === 0) {
        isValid = true;
    }

    return isValid;
}
</code>```


问:
What is the difference between implementation and realization in Mythical Man Month?
In Fred Brook's Mythical Man Month chapter 4 (Aristocracy, Democracy, and System Design) page 49, he says:

As Blaauw points out, the total creative effort involves three distinct phase: architecture, implementation, and realization ...

implementer has plenty to do ... designing module boundaries, table structures, pass or phase breakdowns, algorithms, and all kinds of tools

...Meanwhile, on the realization level there is much to be done also. Programming has a technology, too. If the machine is a new one, much work must be done on subroutine convention, supervisory techniques, searching and sorting algorithm.

What is the difference between implementation and realization?

To me, an architecture is more related to specification descriptions or diagrams, whereas implementation is more to programming/coding, and it seems like the same as realization.

答: I believe in this case, realization is deployment and integration of final product.</p>


问:
Create a database for database tables
I'm working on a project where I have to give users the ability to build their own tables,
each user can create more than one table.

(the type of all data is string).

The user can create a table and specify what columns he wants inside it.

What is the best way to do that:

to create databases dynamically

to have a table for tables (key,value ...).

something else

Another issue is: is it better to separate my database into two, so one is for the internal use (users, accounts,....) and the other is for the tables of the users (or for the table of tables)?

答:
You should prefix the table with user name like userName_tableName pattern.
the userName will be the name of user who created the table.</p>

Title: Create a database for database tables


问:
What to do when you are faced with programming task that you have never done?
I started my career as a .NET developer 3 months ago and after a long training plan on diverse technologies, patterns and concepts the developers who were supervising me have decided that I am ready to join one of the many projects the company handles.

I am very excited to finally be able to start coding. The team I have joined is rather small for now because were starting with a new project, which is great because I get to be involved in the entire life cycle of the project. It is a web based SPA project with a backed that uses ASP.NET MVC/ASP.NET Web API and in front-end the Durandal framework and related libraries.

My problem is that after having a meeting with my colleagues and establishing the tasks and estimations for the next month I find myself in a position that I do not know if I am capable of taking on any of the tasks.

I have never done any of the created tasks and I do not know how should I proceed.

For example one of tasks created is creating a generic error handling mechanism for the entire application.

How does one usually proceed when faced with tasks that he has never done?

答:
There is no perfect solution, but some things that might help:

Break tasks down into the smallest possible units -- break them down until you have things you can do.

Restate the immediate task or problem at hand to make sure you really understand it.  Then do some analysis and repeat.

Pick the simplest task first, even if it seems too simple just to get momentum going.  Some folks prefer the hardest task so the 'hard work' is out of the way.  I have found that 'simplest task' generally works better as you are just looking to get some momentum going and I have seen 'hardest first' lead to projects stalling before they get any real momentum.

Ask for help in selecting the right task and approach to get started.

Seek out a mentor that can give you constant (ideally daily) feedback for a week or two.

Ask a lot of questions but focus on being polite to your teammates. Always ask if they have time, and pay attention to the usual verbal and non-verbal signs that they don't have time right then.

Keep a running list of issues you are encountering and then either in daily scrum or at a regular time of your choosing, go through them with others.

Don't be afraid of asking the most basic questions. Assumptions by others can be hard to challenge but if you can't proceed with what you're given you have to question again.

If you know the objective, do as much as you can until you get stuck and then post the progress and question on Stack Overflow.


答:
There are several things you can and should do to prepare for the task:

Think about the problem and draw some diagrams. Make sure that you know what the problem is that you are trying to solve.

Do research on what you are trying to do. The internet is a valuable source of information. I am not saying ask Stack Overflow -- I am saying do research on how other people have already solved a problem like yours or approached it. This what google came up with: "Exception Handling as a System Wide Concern". Personally, I always try to learn from others.

Lastly, and this might the most important, talk the other people on your team to get more clarification and direction on what to do. I always want to see new engineers come ask for guidance on projects.

Not knowing how to do something will never really end. Every day I run into problems that I have never tackled before. Having the ability to figure out how to solve new problems is extremely important. Even old problems are never totally old -- in programming, there is almost always a new twist or a request for your solution to work in a new or different way.

This is why I am an engineer; I love to figure out new stuff.

Never stop learning new things. Learning is what makes you better.

Title: What to do when you are faced with programming task that you have never done?

Body:
I started my career as a .NET developer 3 months ago and after a long training plan on diverse technologies, patterns and concepts the developers who were supervising me have decided that I am ready to join one of the many projects the company handles.

I am very excited to finally be able to start coding. The team I have joined is rather small for now because were starting with a new project, which is great because I get to be involved in the entire life cycle of the project. It is a web based SPA project with a backed that uses ASP.NET MVC/ASP.NET Web API and in front-end the Durandal framework and related libraries.

My problem is that after having a meeting with my colleagues and establishing the tasks and estimations for the next month I find myself in a position that I do not know if I am capable of taking on any of the tasks.

I have never done any of the created tasks and I do not know how should I proceed.

For example one of tasks created is creating a generic error handling mechanism for the entire application.

How does one usually proceed when faced with tasks that he has never done?


答:
I would just have one table for users and a one table for user_columns.

The whole notion of users dynamically adding tables is not one I'd tackle.

The user_columns table would have user_id as a non-unique foreign key, plus columns such as description, timestamps, etc.

That way you just add and remove rows from user_columns as needed.

Title: Create a database for database tables

Body:
I'm working on a project where I have to give users the ability to build their own tables,
each user can create more than one table.

(the type of all data is string).

The user can create a table and specify what columns he wants inside it.

What is the best way to do that:

to create databases dynamically

to have a table for tables (key,value ...).

something else

Another issue is: is it better to separate my database into two, so one is for the internal use (users, accounts,....) and the other is for the tables of the users (or for the table of tables)?