答:
I'm a CS researcher myself. The best way to leverage research papers is to find the most recent publication on your desired topic and then look at the related work section to see previous research in the area. If you find that some papers are referenced very often, then it's probably a canonical work that you should read. Google Scholar also helps here because it will track how many other papers cite a particular paper.

Another resource is ACM Computing Surveys, where each article has a complete survey of a given field. Extremely handy for academic research.

Communications of the ACM and IEEE Computer are general-audience monthly magazines with research topics written by laymen, and the related work section of each article is usually very good.

If you can find a really good, recent book on a given topic, that would be preferrable because the whole book is written by one author (or just a few co-authors), so the writing style is presumably more uniform. Books are presumably written more for laymen and are better to understand.

Title: research papers vs books


问:
Why do certain sites prevent spaces in passwords?
It seems less common with newer websites, but many websites I need an account on (like for paying bills, etc.) prevent me from creating a password with spaces in it.  This only makes things more difficult to remember, and I am aware of no database or programming restrictions on spaces in passwords, encrypted or (heaven forbid) otherwise.  Why, then, is the spacebar so commonly discriminated against when it comes to signing up for a site?</p>

答:
It's done for the same reason that many sites don't allow hyphens, apostrophes, or non-ASCII letters in names, even though these are very common practices even just within the U.S. and it requires more work to disallow these characters than to simply allow them.

It's also done for the same reason many sites' word filters won't let you use words like "cocky", "retardant" or even "accumulate" (though many common racial slurs are perfectly alright).

It's because a lot of developers are apparently completely lacking in common sense, or at least have a very limited imagination when considering possible user inputs and scenarios. A small percentage of them may be working off of false information (that excluding non-alphanumeric characters is somehow a standard practice, or that the hashing algorithm or storage method can't handle spaces or special characters). Others may simply be lazy—they're worried about charset issues, so they simply restrict inputs to a minimal character space. And then there may be those who are exercising overzealous input validation/sanitation because of paranoia due to a lack of understanding of real threats.

OwnerDisplayName: beanland

ContentLicense: CC BY-SA 3.0


问:
Should one use pseudocode before actual coding?
Pseudocode helps us understand tasks in a language-agnostic manner. Is it best practice or suggested approach to have pseudocode creation as part of the development lifecycle? For instance:

Identify and split the coding tasks

Write pseudocode

Get it approved [by PL or TL]

Start Coding based on Pseudocode

Is this a suggested approach? Is it practiced in the industry?

答:
Writing pseudocode before coding is certainly better than just coding without planning, but it's far from being a best practice. Test-driven development is an improvement.

Even better is to analyze the problem domain and design solutions using techniques like user stories, use cases, CRC cards, diagramming, as espoused by methodologies such as Cleanroom, RUP, Lean, Kanban, Agile, etc.

Thoroughly understanding the nature of the problem and the components you use to implement the solution is the principle behind best practices.

ContentLicense: CC BY-SA 2.5


问:
Debug multiprocessing in Python
What are some good practices in debugging multiprocessing programs in Python?</p>

答:
True multiprocessing Python programs (as opposed to multi-threaded Python programs which have to deal with the dreaded GIL) are no different from those in any other language. They all have the same basic challenges:

Task assignment and result reporting. Even if they are mostly working on independent datasets, they normally have to go back to the master thread to report results and get new data to work on. This can be a choke point.

Race conditions. Processes are trying to use a one-at-a-time resource and they need to use mutex (or something similar) to keep from stepping all over each other's data. Failure to protect these kinds of resources can lead to really, really painful debug sessions.

Sequentiality. Sometimes you are trying to make something parallel that isn't. The various processes end up waiting for each other to do something and the end result is that you have, for all intents and purposes, taken a sequential program, made it parallel, and it still ends up executing in linear time (or worse).

Although there are development methods that try to avoid each of these problems, at the end of the day you really need to think about what you are doing. I recommend heavy stress testing — far beyond anything you think might happen in real life — so that you have a good chance of hitting those Windows of Opportunity and blowing up in development as opposed to in the middle of a major demo or during production.

We used to use microsecond-timestamped log files and then created a color-coded log viewing app so we could try to visualize what was happening between N process running on M processors. We also tried (and mostly succeeded) in creating a system that would drive off the log files to recreate the context of the crash.

But the best tool is good design and really wicked, nasty people who try to blow your app out of the water. (Hi, dbell!)

Title: Debug multiprocessing in Python


问:
Need help understanding reference operator(C++) in specific functions
In the current semester at the university we are working on OOP with C++.

I would like to understand the difference between a pointer and a reference operator.

The differences that I understand are:

1. Cannot change the object that the reference variable is binded to

2. we can use the reference variables to refer to the binded object without having to type the & operator (in contrast with the pointers where we would write *pi = 5;)

Also,does a reference variable contain the address of the object that is binded to?

In example:

```<code>int i;
int &ri = i;
</code>```

Here ri contains the address of i?

And the reason why when overloading ++ operator in this example of enumeration we are using the dereference or reference(*) operators before the name of the function.

答:
A reference serves one purpose: to act as an alias for an existing variable:

```<code>int i;
int &ri = i;
</code>```

In this example, the addresses of i and ri are identical (&i == &ri). The two names refer to the very same location in memory. Thus one of the useful applications of references is to provide an alias for a long name that it would be wasteful to retype:

```<code>const Location& p = irresponsibly_long_object_name.retrieve_location();
</code>```

When you pass a function parameter by reference, it has the same effect:

```<code>void increment(int& parameter) { ++parameter; }

int main(int argc, char** argv) {
    int variable = 0;
    increment(variable);
}
</code>```

Here, parameter serves merely as an alias of variable, just as though it were defined as int& parameter = variable. Modifying parameter inside increment() is indistinguishable from modifying variable in main(). Furthermore—and this is quite useful—variable does not need to be copied; so if it were of a large type such as std::list<int>, then passing it by reference would be much more efficient. That’s the main point of const references.

For the purpose of function parameters of reference type, the sanest course of action for a compiler is to use a pointer internally, as if you had written:

```<code>void increment(int* parameter) { ++*parameter; }

int main(int argc, char** argv) {
    int variable = 0;
    increment(&variable);
}
</code>```

This is an interesting detail, and well worthwhile to remember. While it is not essential to your understanding of references, recognising this equivalence allows you to think of pointers merely as explicit references. Likewise, references are implicit pointers.

Body:
A reference serves one purpose: to act as an alias for an existing variable:

int i;
int &ri = i;

In this example, the addresses of i and ri are identical (&i == &ri). The two names refer to the very same location in memory. Thus one of the useful applications of references is to provide an alias for a long name that it would be wasteful to retype:

const Location& p = irresponsibly_long_object_name.retrieve_location();

When you pass a function parameter by reference, it has the same effect:

void increment(int& parameter) { ++parameter; }

int main(int argc, char** argv) {
    int variable = 0;
    increment(variable);
}

Here, parameter serves merely as an alias of variable, just as though it were defined as int& parameter = variable. Modifying parameter inside increment() is indistinguishable from modifying variable in main(). Furthermore—and this is quite useful—variable does not need to be copied; so if it were of a large type such as std::list<int>, then passing it by reference would be much more efficient. That’s the main point of const references.

For the purpose of function parameters of reference type, the sanest course of action for a compiler is to use a pointer internally, as if you had written:

void increment(int* parameter) { ++*parameter; }

int main(int argc, char** argv) {
    int variable = 0;
    increment(&variable);
}

This is an interesting detail, and well worthwhile to remember. While it is not essential to your understanding of references, recognising this equivalence allows you to think of pointers merely as explicit references. Likewise, references are implicit pointers.


问:
Why does everybody write to-do comments in capital letters?
I'm doing the same. When there is something "to-do" in my code, I write //TODO .... But I'm curious to know when this started and if there is a reason for writing "to-dos" in all capital letters?

答:
It calls attention to the fact that there exists a todo.

It is important that it be obvious all the time that someone needs to come back to the code. The particulars only need to be known by the person coming back to address whatever the issue is.


问:
What's an Elegant and OOP way to create a tree from arrays and render it as a nested UL
I have a series of arrays which represent file system paths, so each next value is actually a directory deeper, for example:

```<code>var a1 = ["Desktop", "Pictures", "Summer 2011"];
</code>```

is the equivalent of

```<code>Desktop
|-Pictures
  |-Summer 2011
</code>```

I'm trying to find an elegant way to:

Flatten/merge all the different arrays I have to come up with one object/dictionary/multi-dimensional-array.

Parse the result and render a nested UL (html list) to the page which represents the hierarchy correctly.

Write what I already have in a more 'OOP way'..

I already have a working version:

```<code><!DOCTYPE html>
<html>
    <head></head>
    <body onload="init()">
        <ul id="tree"></ul>
        <script>
            var a = [ "Desktop", "Folder1",  "InnerFolder1" ];
            var b = [ "Desktop", "Folder1",  "Inner 2" ];
            var c = [ "Documents", "Folder 2", "InnerFolder1", "even deepper" ];
            var d = [ "Something Else", "Folder1",  "Inner 2" ];

            var all = [a, b, c, d];
            var Tree = {};
            var ul = document.getElementById("tree");

            function init(){
                for ( var i = 0; i < all.length; i++ ){
                    addToTree(Tree, all[i] );
                }
                createList(Tree, ul);
            }

            //function from http://stackoverflow.com/questions/3663096/how-to-convert-array-to-tree
            function addToTree(tree, array) {
                for (var i = 0, length = array.length; i < length; i++) {
                    tree = tree[ array[i] ] = tree[ array[i] ] || {};
                }
            }

            function createList( obj, _pushTo  ){
                for ( attr in obj ){
                    var _doIHaveChildren = function ( ){
                        for(var prop in obj[attr]) {
                            if (obj[attr].hasOwnProperty(prop)) {
                                return true;
                            }
                        }
                        return false;
                    }
                    var li = document.createElement("li");
                    li.id = attr.toString();
                    li.innerHTML = attr.toString();
                    if ( Tree.hasOwnProperty(attr) ){
                        ul.appendChild(li);
                    } else {
                        _pushTo.appendChild(li);
                    }
                    if ( _doIHaveChildren() === true ){
                        var ul2 = document.createElement("ul");
                        li.appendChild(ul2);
                    }
                    createList( obj[attr], ul2 );
                }
            }
        </script>
    </body>
</html>
</code>```

Thanks!

EDIT:
I'm starting from strings which represent the paths i.e. "Desktop/Pictures/Summer 2011" which are broken to arrays.

答:
In a simple OO way - i would define all the vars -  a, b, c, and d   itself as a tree.

```<code>a_tree = new tree(a);
</code>```

and same for all others.
After that i would have have a merge tree command

```<code>a_tree.merge_tree(b);
a_tree.merge_tree(c);
</code>```

This is just another way to do things. Typically merge_tree should be recursive process.

I think to judge which method has more significant different at all, when you scale up the tree to a large size.

Body:
In a simple OO way - i would define all the vars -  a, b, c, and d   itself as a tree.

a_tree = new tree(a);

and same for all others.
After that i would have have a merge tree command

a_tree.merge_tree(b);
a_tree.merge_tree(c);

This is just another way to do things. Typically merge_tree should be recursive process.

I think to judge which method has more significant different at all, when you scale up the tree to a large size.


答: I'm going to disagree with the previous answers and say no, but with a caveat: you can get rid of psuedocode only if you're feverishly devoted to refactoring your code to deal with issues that crop up. Psuedocode is, at its essence, a way of defining your code before you define your code; it's an unnecessary abstraction in many circumstances, and since your code will never be perfect the first time (and likely, not follow the psuedocode's design to completion), it seems extraneous to me.</p>

Title: Should one use pseudocode before actual coding?

Body:
Pseudocode helps us understand tasks in a language-agnostic manner. Is it best practice or suggested approach to have pseudocode creation as part of the development lifecycle? For instance:

Identify and split the coding tasks

Write pseudocode

Get it approved [by PL or TL]

Start Coding based on Pseudocode

Is this a suggested approach? Is it practiced in the industry?


答:
There are a huge amount of stupidities when it comes to passwords in websites.

Some have purely technical reasons (valid or not, that's another question, but nearly all of them are not):

Your password must be four characters length and have only digits.

(By limiting a password to 0001 .. 9999 range, you can simply store them as a number, plaintext, in the database)

Other are explained by some erroneous thoughts that they will make passwords more secure:

Your password must start with a capital letter and end with a digit.

(By doing this the developer, or the manager, assumed that this will actually force the users to choose a safe password, while the rule as "Your password must contain min. 6 characters and contain at least one capital letter, lowercase letter and a digit" will magically fail to do it)

Other, finally, are explained by the fact that passwords are stored plaintext, and there are some ambiguities about how they are stored, processed or retrieved, and there are no time to unit test them.

Your password contains an invalid character é.

or,

Your password y$₯46¥*A'xD<7&฿=ᴙcN&sF5_Ở!d contains some invalid characters. Use characters from Latin alphabet and digits only.

or,

Your password cannot contain whitespace characters.

In all three cases, the developer was just insure that passwords like this will be stored correctly.

In the first case, what if é will be transformed into %C3%A9 when sent? Or what if the database will store é incorrectly?

In the second case, what if PHP (why PHP?) cannot deal with unicode, and does something terrible when receiving a password like this? What if < character causes trouble? What if & character is interpreted as a separator in an URL (assuming that for some reason, the password is being sent through GET instead of POST)? What if ' is interpreted by the database, because, guess what, we have no idea what SQL Injection is and how to avoid it? Or what if ' is transformed into \'?

In the third case, what if PHP (again?) trims whitespace in some cases and not in others? What if the administrators (who have surprisingly the access to users passwords in plaintext) are lost because they see only one whitespace, while the user have set three consecutive whitespaces?

In all three cases, those ambiguities are easily solved through testing, especially unit testing. But in a huge amount of projects, there is no testing at all, and no time to test (but still plenty of time to debug later).

This means that whether the developer tries to think about the possible consequences of allowing spaces, or unicode characters, or just any character outside ASCII 48..57 ∪ 65..90 ∪ 97..122 (digits, lowercase letters, uppercase letters), the easiest way, when testing is not possible, is to just forbid them.

In my opinion, this is the sole reason to forbid spaces. Yannis Rizos gave another reason related to UX. While being a plausible reason in theory, it doesn't work at all in practice: websites made by people who actually care about UX don't fix stupid password rules. Instead, websites where whitespace is actually forbidden are in most part done by people who never heard about UX. This is especially true since forbidding any character is really annoying from UX point of view, as any password-related restriction, including the useful ones, as the minimum number of characters.

Title: Why do certain sites prevent spaces in passwords?

Body: It seems less common with newer websites, but many websites I need an account on (like for paying bills, etc.) prevent me from creating a password with spaces in it.  This only makes things more difficult to remember, and I am aware of no database or programming restrictions on spaces in passwords, encrypted or (heaven forbid) otherwise.  Why, then, is the spacebar so commonly discriminated against when it comes to signing up for a site?</p>


问:
What machine learning algorithm[s?] would be applicable here?
I have documents that contain an arbitrary amount of key/value fields. The value can be a primitive or a list.

Completed documents all have an associated state (such as passed, failed, halted, etc.).

Using completed documents as training data in a machine learning algorithm, my goal is to pass the system an incomplete document and determine the probable outcome. Is it more likely that the incomplete document I'm currently looking at will pass, fail or halt?

The identifying information I'm looking to compare here consists mostly of unique keys. So a document could look something like:

```<code>id: 1
keys_of_type_x: [x1, x2, x3, ..]
keys_of_type_y: [y1, y2, y3, ..]
key_z: "sample text field"
etc.
</code>```

I am not necessarily looking for a concrete answer, but more for a push in the right direction with information regarding what algorithm is best suited for this sort of multi-value based classification.

答:
First, try to flatten all nested features into one large set of features and create a mapping from the text to a real number, using something like Naive bayes.

Then replace incomplete information with some kind of normalized data and apply Logistic regression with "1 versus all" classification. An alternative would be to use a decision tree based approach like Random Forest as it tends to work better with incomplete information, since you will be taking only a random subset of features.


问:
Why is there both a short-circuit OR as well as unshort-circuited variation of that operator in C#?
Periodically, I wonder about this:

The short-circuit OR would always return the same value that the unshort-circuited OR operator would?

I expect that the short-circuit OR would always evaluate more quickly. So, was the unshort-circuited OR operator included in the C# language for consistency?

What have I missed?

答: if the right-hand clause of the operator have side-effect, and the programmer intended that he want both side effect to happen before checking their return value.</p>


答:
This is correct, the short-circuit OR operator (||) will always return the same value as the non-short-circuit OR operator (|). (*)

However, if the first operand is true, the short-circuit operator will not cause evaluation of the second operand, while the non-short-circuit operator will always cause evaluation of both operands. This can have an impact on performance, and sometimes in side-effects.

So, there is a use for both: if you care for performance, and the evaluation of the second operand does not produce any side effects, (or if you do not care about them,) then by all means use the short-circuit operator. But if for some reason you need the side-effects of the second operand, then you should use the non-short-circuit operator.

An example where you should use the non-short-circuit operator:

```<code>if( write_customer_to_database() != SUCCESS |
    write_supplier_to_database() != SUCCESS |
    write_order_to_database() != SUCCESS )
{
    transaction_rollback();
}
</code>```

(*) Except for some really perverted scenario where the evaluation of the first operand to false causes by side-effect the the second operand to evaluate to true instead of false.

Title: Why is there both a short-circuit OR as well as unshort-circuited variation of that operator in C#?

Body:
Periodically, I wonder about this:

The short-circuit OR would always return the same value that the unshort-circuited OR operator would?

I expect that the short-circuit OR would always evaluate more quickly. So, was the unshort-circuited OR operator included in the C# language for consistency?

What have I missed?

Body:
This is correct, the short-circuit OR operator (||) will always return the same value as the non-short-circuit OR operator (|). (*)

However, if the first operand is true, the short-circuit operator will not cause evaluation of the second operand, while the non-short-circuit operator will always cause evaluation of both operands. This can have an impact on performance, and sometimes in side-effects.

So, there is a use for both: if you care for performance, and the evaluation of the second operand does not produce any side effects, (or if you do not care about them,) then by all means use the short-circuit operator. But if for some reason you need the side-effects of the second operand, then you should use the non-short-circuit operator.

An example where you should use the non-short-circuit operator:

if( write_customer_to_database() != SUCCESS |
    write_supplier_to_database() != SUCCESS |
    write_order_to_database() != SUCCESS )
{
    transaction_rollback();
}

(*) Except for some really perverted scenario where the evaluation of the first operand to false causes by side-effect the the second operand to evaluate to true instead of false.

ContentLicense: CC BY-SA 4.0


答:
Both operands were meant for different things, coming from C which didn't have a boolean type. The short-circuit version || only works with booleans, while the non-short circuit version | works with integral types, performing a bitwise or. It just happened to work as a non-short circuit logical operation for booleans which are represented by a single bit, being 0 or 1.

http://en.wikibooks.org/wiki/C_Sharp_Programming/Operators#Logical


答:
| (the bitwise-or) must be non-short-circuit for types like int. That is because in almost all cases you need to calculate both sides of an | expression to calculate the correct result. For example, what is the result of 7 | f(x) ?

If f(x) is not evaluated, you cannot tell.

Furthermore it would be inconsistent to make this operator short-circuit for bool, when it is non-short-circuit for int. By the way, I think I have never used | for logical comparisons intentionally, finding it is very inconvenient to speak of | as a logical operator.

|| however is for logical comparisons, where short-circuit evaluation works fine.

The same is valid even for C and C++, where the origin of those operators is.


答: You need to model a class node that has a variable a and that can points to itself and then you can use DFS to search the tree. In your example you use an adjacent list which isn't really object oriented style. The root of the tree is a special case where the variable a is a magic number. </p>

Title: What's an Elegant and OOP way to create a tree from arrays and render it as a nested UL

Body:
I have a series of arrays which represent file system paths, so each next value is actually a directory deeper, for example:

```<code>var a1 = ["Desktop", "Pictures", "Summer 2011"];
</code>```

is the equivalent of

```<code>Desktop
|-Pictures
  |-Summer 2011
</code>```

I'm trying to find an elegant way to:

Flatten/merge all the different arrays I have to come up with one object/dictionary/multi-dimensional-array.

Parse the result and render a nested UL (html list) to the page which represents the hierarchy correctly.

Write what I already have in a more 'OOP way'..

I already have a working version:

```<code><!DOCTYPE html>
<html>
    <head></head>
    <body onload="init()">
        <ul id="tree"></ul>
        <script>
            var a = [ "Desktop", "Folder1",  "InnerFolder1" ];
            var b = [ "Desktop", "Folder1",  "Inner 2" ];
            var c = [ "Documents", "Folder 2", "InnerFolder1", "even deepper" ];
            var d = [ "Something Else", "Folder1",  "Inner 2" ];

            var all = [a, b, c, d];
            var Tree = {};
            var ul = document.getElementById("tree");

            function init(){
                for ( var i = 0; i < all.length; i++ ){
                    addToTree(Tree, all[i] );
                }
                createList(Tree, ul);
            }

            //function from http://stackoverflow.com/questions/3663096/how-to-convert-array-to-tree
            function addToTree(tree, array) {
                for (var i = 0, length = array.length; i < length; i++) {
                    tree = tree[ array[i] ] = tree[ array[i] ] || {};
                }
            }

            function createList( obj, _pushTo  ){
                for ( attr in obj ){
                    var _doIHaveChildren = function ( ){
                        for(var prop in obj[attr]) {
                            if (obj[attr].hasOwnProperty(prop)) {
                                return true;
                            }
                        }
                        return false;
                    }
                    var li = document.createElement("li");
                    li.id = attr.toString();
                    li.innerHTML = attr.toString();
                    if ( Tree.hasOwnProperty(attr) ){
                        ul.appendChild(li);
                    } else {
                        _pushTo.appendChild(li);
                    }
                    if ( _doIHaveChildren() === true ){
                        var ul2 = document.createElement("ul");
                        li.appendChild(ul2);
                    }
                    createList( obj[attr], ul2 );
                }
            }
        </script>
    </body>
</html>
</code>```

Thanks!

EDIT:
I'm starting from strings which represent the paths i.e. "Desktop/Pictures/Summer 2011" which are broken to arrays.


问:
Is recursive forking considered an anti-pattern?
I'm starting to tinker with process forking, just to get a feel for it. I thought I'd write an example where work is distributed among child processes and the results handed back to the parent; this way, it could be run in parallel on several processors.

In my first attempt, I'm forking in a loop, which means that each time through, all the existing processes (the original, children, grandchildren, etc) produce another fork.

This is causing me problems (memory consumption, rapid growth of the number of processes, keeping track of the pipes to hand data back up the chain, etc), and I'm wondering if I've stumbled on an anti-pattern. I could simply fork N children directly from the parent.

I realize that it's common to fork and exec multiple times; for instance, terminal forks a shell, and the shell forks an editor. But is it considered bad practice to fork "recursively" when the children are all of the same type?

答: If you want to distribute multiple processes the goal is to minimize proccessing time. You need to define what do you want to minimize. Usually it is a nearest neighbor or a geometry function or 2d function f(x)=y. A recursion isn't such a function but you can look into a gray code for example to traverse a function f(x)=y. It can help you to difference between the left and the right bit.</p>


问:
What visualization method would you recommend for event driven programs?
What visualization method would you recommend for event driven programs? Are there industry standard diagrams, such as flowcharts?</p>

答: If you want to visualize a chain of events, an UML sequence diagram might be something you can start with. If you are looking, however, for a general approach to model event based programs, where the order of events is intentionally left out, then Flow Design may be the right thing for you.</p>


答:
The flow of an event driven program cannot easily be represented by a flow chart as it is very much dependent on outside things happening and flow charts just are not geared to that.

One way to visualize the flow of an event driven program is to use the good ol' conversation design diagrams (which I learned when programming mainframes). In these diagrams, you have a symbols representing screens. In the center is the screen under analysis or design. At the top will be the screens from which application logic can lead to the central screen. At the bottom will be screens that you can go to from the central screen.

Of course back in my mainframe days, we didn't have to deal with on-screen interactions like dropping down a menu (though for the top menu we had different diagrams) or opening up/filling out a details section on the same screen depending on the current selection in a list.

To address interactions like those, you could define a "screen" per screen state, but that would mean that the number of screen would grow to unmanageable proportions pretty quickly. Mock ups are probably a better solution here. They are perfectly suited to communicate the design of a screen without getting lost in all kinds of itty-bitty details. They also allow for annotations and other ways to indicate on-screen interactions. And using arrows and labels with the name of a following or preceding screen, transitions to other screens can be indicated thus giving a feel for the major navigation within the app.

Balsamiq ( http://www.balsamiq.com ) is a mock up tool that you can try out online and also use on your desktop. Check it out to see whether it would help in what you are trying to do.

Body: What visualization method would you recommend for event driven programs? Are there industry standard diagrams, such as flowcharts?</p>


答:
The answer is History

We seem to forget that the basis of a lot this comes from a time when storage was not effectively free (on disk or in memory) when our ability to manage all these things was somewhat less than it is now and equally the ability of automated systems to attempt to crack same was also somewhat less.

There are lots of rants about passwords based on what we know now and what we can do now but the simple fact is that we're often dealing with a combination of legacy thinking and legacy systems.

Should there be restrictions in new systems now? I would hope not - far less reason now


答:
Uncontrolled forking is definitely an anti-pattern. As you have discovered, it is relatively easy to consume all available resources, and then continue to consume them to the point where everything grinds to a complete standstill.

Just ask the Sorcerer's apprentice.

Like any problem involving recursion, you have to clearly understand your terminating condition. If your algorithm potentially never terminates, recursion is completely unsuitable since you have no control of how deep your stack can become.

Of course, some tasks may "discover" other tasks, so it may also never be possible to launch everything directly from the parent process.

One strategy often used to simplify a solution is to create some kind of task manager process, and have it consume a queue of pending tasks. The master task, or any children, can add tasks to the queue as they find them. The task manager then forks as many processes as it needs to in order to process the tasks.

In this way, the task manager can keep a count of the total number of running processes, and only fork a new process if it thinks it necessary and the hardware can cope with it.

There is a risk of blocking with this, of course: some task needs the result of another task before it can continue, yet that other task is in the queue and will never be run because all the currently executing tasks are blocking waiting for tasks that haven't been started yet...

You can fix this by having separate tasks whose job is to consume results, and managing these through a separate task manager. That way, the calculations can never become completely blocked: something is always going to be making progress.

Title: Is recursive forking considered an anti-pattern?

Body:
I'm starting to tinker with process forking, just to get a feel for it. I thought I'd write an example where work is distributed among child processes and the results handed back to the parent; this way, it could be run in parallel on several processors.

In my first attempt, I'm forking in a loop, which means that each time through, all the existing processes (the original, children, grandchildren, etc) produce another fork.

This is causing me problems (memory consumption, rapid growth of the number of processes, keeping track of the pipes to hand data back up the chain, etc), and I'm wondering if I've stumbled on an anti-pattern. I could simply fork N children directly from the parent.

I realize that it's common to fork and exec multiple times; for instance, terminal forks a shell, and the shell forks an editor. But is it considered bad practice to fork "recursively" when the children are all of the same type?


答:
There would be 2 reasons to use the non-shortcircuit variant:

keeping side effects (but that's clearer to code with a temporary variable)

thwart timing attacks by avoiding the fork in the short circuit (this may even improve the runtime efficiency if the second operand is a variable but that is a micro-optimization the compiler may make anyway)


问:
Cross "Machine" Code?
Some languages (mostly ones made in the last 2 decades or so) can now not only run (after some compilation step or directly) on several platforms, but also can be compiled to run on several virtual machines.

For example, take Scala. Pure Scala code can be either interpreted , compiled to run on the JVM (Java Virtual Machine) or can be compiled to run using the .NET Framework.

The benefits of platform-independence put aside, what exactly are the benefits of writing code that can compile on several virtual machines and runtimes?

答:
It is simpler to write the intermediate compilers - one to the bytecode/IL (whatever) from your source, and one from bytecode/IL (whatever) to native code.

It also allows you to create new languages and target the bytecode or write new bytecode to a new processor and automatically have a new platform available.

See this blog post by Eric Lippert (one of the C# compiler and specification writers) on the subject.

Title: Cross "Machine" Code?


问:
How common are "bandage" fixes?
Imagine the following scenario:

You've detected that your (or someone else's) program has a bug - a function produces the wrong result when given a particular input. You examine the code and can't find anything wrong: it just seem to bog out when given this input.

You can now do one of two things: you either examine the code further until you've found the actual cause; or you slap on a bandage by adding an if statement checking if the input is this particular input - if it is, return the expected value.

To me, applying the bandage would be completely unacceptable. If the code is behaving unexpectingly on this input, what other input that you've missed will it react strangely to? It just doesn't seem like a fix at all - you're just shoveling the problem under the rug.

As I wouldn't even consider doing this, I'm surprised at how often the professors and books keep reminding us about how applying "bandage" fixes is not a good idea. So this makes me wonder: just how common are these kinds of "fixes"?

答:
There are cases where that kind of fix is really OK and probably the ideal (as far as the amount of time it takes to debug is concerned).

Imagine a scenario where you've got 20 DLLs which are supposed to act as some sort of modules for your main executable, but also require some information from the main executable to run.

If you ever want to use those DLL's outside of the main executable, you will need to fudge some return values from the main executable because. A.) It doesn't exist in this context and B.) You don't want it to exist in this context.

That being said, you better put some compiler directives in your code to make sure you're running completely different code when you're fudging the results vs when you're getting the real results.

Instead of putting an if inside someone else's function,  I'd put an {$ifdef} around the function - that way no one confuses it with something that ought to be there.

Title: How common are "bandage" fixes?


问:
Form screenshot for legal proof of clicking one of the checkboxes?
We got a request from one of our customers, and since I've never encountered such a request before, I don't even know where to start looking.

Our customer is a network of colleges, and we're building them a site. On that site, among other things, will be a form which potential applicants can fill out in order to get more info about the studies in one of the colleges. After a user fills out this form - including giving their email and/or phone number - the relevant college then contacts them with the relevant info.

Now, for legal reasons, the client is asking that this form also have a checkbox that the potential applicant checks to indicate that they agree to get promotional material from these colleges. That's of course no problem. But here comes the weird part of the request:

The details of each filled out form have to be be saved in a reliable method. Apparently, saving the form values in a database - a column indicating if the user agreed or didn't agree - isn't enough, because a DB could be changed after the users has sent the form. Our client claims that other college portals create a screenshot of the filled-out form, and save it somewhere in a dedicated folder, in a manner that is easily found, such as giving the file a name that includes the user's name, and the date and time.

My question is as follows: have you heard of using screenshots as a method of proving a user has actually filled out a form? Are there other methods that are are considered reliable?

答: As everyone noted, the technical and legal merit of the feature request is nonexistent. That said, there's the option if allowing a user to manually take and upload a screenshot as a form attachment. </p>


问:
where can I find an overview of known "multithreading systems architectures" design patterns?
Using C#, I have been doing multithreaded development for about 5 years, and consider myself quite proficient (I wrote my own lock-free queue and task parallel framework before Microsoft made TPF).

However, I find it incredibly difficult to find information on practical multithreaded system design patterns anywhere. There are some good resources on low-level algorithms and collections, but not much on system design.

So to the question, anyone know where this information can be found?

答:
Threading in C#, by Joe Albahari is a good starting point.

Please consider the book .NET Multithreading too.


问:
Learning Django by example
When I first started learning Android, I found a fantastic series of YouTube videos by Marakana that stepped through building a Twitter clone. It walked me through all the steps and thus explained to me the basics, common libraries, best practices, resources, etc. Looking over an expert's shoulder while building a practical app was the absolute best learning method for me. More than anything else, it provided me with a skeleton I could build on. From there I could continue researching and know which questions to ask.

I'm now looking for something similar with Django. Of course I checked out the official tutorial, and The Django Book. The former flexes some Django muscles, but doesn't walk through a full app. The latter is certainly better, but the app it builds is very basic and by the time it reaches the more advanced subjects the tutorial breaks down and its back to short code snippets and documentation-like explanations.

Checking out Amazon isn't terribly encouraging. The latest general Django book was released almost two-and-half years ago and only covers v1.0. To be fair, I understand that this is probably because the online documentation is excellent, but again, I'm looking for a walk-through. I did experience a spark of excitement when I came across Practical Django Projects, which sounds like exactly what I was looking for. However, some of the reviews make claims of some egregious problems--no source code, many errors and no errata, totally apathetic author and unresponsive publisher, etc.

And so I'm left at square one and need your advice. Is there a place where I can sit on a giant's shoulder and be walked through a realistic Django project from start to finish? Preferably using a more recent version of the framework.

答:
It is a good idea to work through the official Django tutorials at djangoproject.com. These are written by some of the core developers and raise important issues regarding Python/Django/DB versions and syntax evolution. But, yes, the Polls app created in the process is rudimentary, so here are my recommendations to useful Django tutorials which involve app creation:

13 series of screencasts creating a Django web app:
http://showmedo.com/videotutorials/series?name=PPN7NA155

Django by Example: code walkthroughs for several useful apps
http://www.lightbird.net/dbe/

lastly, I would like to suggest you give Practical Django Projects a second chance. The second edition of the book has been published and the book is available on author, James Bennett's bitbucket repository. (i'm a new user so can't post more than 2 hyperlinks - kindly google)

Title: Learning Django by example


答: In addition to what Oded said, it is a lot easier to write programs that dynamically produce code at runtime: all you have to do is emit bytecode, (or CIL, or "cross machine code", or whatever you call it,) which has a reduced, and at the same time relatively high-level, instruction set.</p>

Title: Cross "Machine" Code?

Body:
Some languages (mostly ones made in the last 2 decades or so) can now not only run (after some compilation step or directly) on several platforms, but also can be compiled to run on several virtual machines.

For example, take Scala. Pure Scala code can be either interpreted , compiled to run on the JVM (Java Virtual Machine) or can be compiled to run using the .NET Framework.

The benefits of platform-independence put aside, what exactly are the benefits of writing code that can compile on several virtual machines and runtimes?


问:
TDD with limited resources
I work in a large company, but on a just two man team developing desktop LOB applications.  I have been researching TDD for quite a while now, and although it is easy to realize its benefits for larger applications, I am having a hard time trying to justify the time to begin using TDD on the scale of our applications.

I understand its advantages in automating testing, improving maintainability, etc., but on our scale, writing even basic unit tests for all of our components could easily double development time.  Since we are already undermanned with extreme deadlines, I am not sure what direction to take.  While other practices such as agile iterative development make perfect since, I am kind of torn over the productivity trade-offs of TDD on a small team.

Are the advantages of TDD worth the extra development time on small teams with very tight schedules?

答:
Here's where I think Behavior Driven Development shows immediate gains, but I'm not sure that test driven development does.

In behavior driven development you approach your tickets in a different way: you sit down with the business person and work with them to define the behaviors that this chunk of functionality should have. I describe this in an entry on my blog, (the post title: Writing Behaviors).

Sitting down with the business person or whomever will help you and them to better understand what the system needs to do for everyone to be happy with that piece of functionality. What it needs to do to be able to be accepted by the QA process you have in place.

Defining testing criteria, then writing those testing criteria into your automated test suite, should reduce the amount of back and forth you get: someone claiming the functionality is broken, because you missed something (either because you legitimately missed something, or because they never told you about it).

It also may help other's perception of your team: if you sit down and define what needs to be done in the system, you could go from, "idiots who overengineer everything and spend time on things we didn't ask for", to, "smart folk who are coming up with useful features".

TL; DR: Behavior Driven Development may show improvements quickly because it's "customer" focused. Test Driven Development, to me, seems to be about testing internals of the codebase that "nobody" cares about and gives less obvious business benefits. (Behavior Driven Development has the immediate, in your face, change: the engineers are suddenly having a lot more face time with the "customer" or business analyst to try to get this right - which should be seen as a good thing. "Oh, they're having a meeting about Feature X, which means there's progress on that front!")

Title: TDD with limited resources


答: UML Sequence diagrams are probably the most universial tool to use. Flow charts are only suitable for the flow through event processing, not for the event triggers themselves. </p>

Title: What visualization method would you recommend for event driven programs?


答:
Parallel Programming with Microsoft .NET: Design Patterns for Decomposition and Coordination on Multicore Architectures

This is a book, I recommend wholeheartedly.

It is:

New - published last year. Means you are not reading somewhat outdated practices.

Short - about 200+ pages, dense with information. These days there is too much to read and too little time to read 1000+ pages books.

Easy to read - not only it is very well written but it introduces hard to grasps concepts in really simple to read way.

Intended to teach - each chapter gives exercises to do. I know it is always beneficial to do these, but rarely do. This book gives very compelling and interesting tasks. Surprisingly I did most of them and enjoyed doing them.

Title: where can I find an overview of known "multithreading systems architectures" design patterns?

Body:
Using C#, I have been doing multithreaded development for about 5 years, and consider myself quite proficient (I wrote my own lock-free queue and task parallel framework before Microsoft made TPF).

However, I find it incredibly difficult to find information on practical multithreaded system design patterns anywhere. There are some good resources on low-level algorithms and collections, but not much on system design.

So to the question, anyone know where this information can be found?


问:
What are the consequences of having unnecessary references and usings?
I'm a bit of a neat freak and tend to keep my projects by cleaning references and usings in each class to keep only what's actually used.

What other argument could I make (besides calming my OCD nerve) of keeping to the essentials? I'm thinking mostly system references, any reference to custom work will bring its lot of backward compatibility issues. Is the release footprint bigger? Compile time longer?

答:
using statements are simply for the compiler to be able to fully reference classes, etc.  Extra using statements will have no appreciable effect on compilation time.

Also, the runtime won't load a referenced assembly until it is actually needed, so again I don't believe there are any negative consequences of unneeded references.

If you use a tool like Reflector, finding and removing these unnecessary bits can be mostly automated, so I'd say it's wasteful to spend much time at all on these activities.  For example, an hour or two of manually removing unneeded using statements more than pays for a Reflector license - and it comes with many other productivity enhancing features.


答:
Intellisense will be a heck of a lot more useful to you if you keep using at a minimum, and that is a great advantage.

Other than that, I do not think there is any gain. So maybe the C# compiler will work faster by, say, 1%; so what.

Title: What are the consequences of having unnecessary references and usings?

Body:
I'm a bit of a neat freak and tend to keep my projects by cleaning references and usings in each class to keep only what's actually used.

What other argument could I make (besides calming my OCD nerve) of keeping to the essentials? I'm thinking mostly system references, any reference to custom work will bring its lot of backward compatibility issues. Is the release footprint bigger? Compile time longer?


答:
Since it is virtually trivial to accomplish this in Visual Studio (simple right click), why not do it?

This is consistent with Occam's Razor, it is just plain good engineering.

As to the consequences of not doing it, consider what happens if some other developer tries to open your project and it contains an (unused) reference to a library that he/she does not have on his/her computer. Now that poor developer needs to figure out why that unresolved reference exists and what to do about it.

If you prefer, consider it in terms of the golden rule. Would you want to take over development on a project that had lots of references to libraries that you did not have on your computer and that you had no idea why they are there?


问:
Will Java still be relevant in 5 years?
Will Java have the same importance it had in the past, or it will be less relevant than nowadays?</p>

答:
Two answers:

1)Android

2)Blackberry

Seriously though, on the desktop, it may be in decline, but it powers the two competitors to iPhone.

Also, last year, I helped a bunch of people with Java homework for school. Point being, java is still taught in colleges.

Edit:

As of October 2011, BlackBerry seems to be in decline. Android is still going strong.

Title: Will Java still be relevant in 5 years?


答:
In addition to the above, I guess it was not yet mentioned here that, each reference requires a component either within the .NET framework or an external DLL. If the reference is made to an external DLL, you will need to have that when (and where) your run the software.

Edit - As per valid comment by phoog below:
The application would still run if the DLL is not used and is not required to be shipped with the application just because it was added to references. To take care of un-used references in the code, you may want to look at: Removing unused references.


问:
Should I plan ahead, or figure out programs as I'm writing them?
I was thinking today about Paul Graham's book "Hackers and Painters." More specifically, these two paragraphs:

"I was taught in college that one ought to figure out a program
  completely on paper before even going near a computer. I found that I
  did not program this way. I found that I liked to program sitting in
  front of a computer, not a piece of paper. Worse still, instead of
  patiently writing out a complete program and assuring myself it was
  correct, I tended to just spew out code that was hopelessly broken,
  and gradually beat it into shape. Debugging was a kind of final pass
  where you caught typos and oversights... [It] seemed like programming
  consisted of debugging.

... As far as I can tell, the way they taught me to program in college
  was all wrong. You should figure out programs as you're writing them,
  just as writers and painters and architects do."

That's how it's taught in my college and I'm pretty sure most other colleges as well. You figure out what your program will do, and then you figure out how to do it, then you type and debug. Sometimes you make a basic version and add functionality, but the idea is that you think through and then type.

This sort of reminds of that chapter in Feynman's book called "He Solves Radios By Thinking!" where he paced around thinking of how the radio could be broken, and then fixes it. To me, that's what programming is about - thinking and then finding a solution.

Is this the prevalent approach to coding? If so, why don't more people just hack away and put a program together without having a preconceived idea of what it's going to look like?

What are the advantages and disadvantages of think & type vs. spew & beat?

答:
I think the workflow is very individual for each programmer. Use the method that works best for you.

Me, personally, usually start with a blank paper and a pencil (or a very large whiteboard if I have one). I'm first drawing class diagrams and relations. Then I refine it until I have a basic structure. I also make the state machines at this stage.
At this point no code has been written or thought of, only classes and relations.

Now this is only a lose sketch and while I start to program my classes I will run into more design questions. I then go back to my whiteboard (or paper) and break down the new problems, sometimes meaning ripping up some of the original design.

This is also similar to how Agile design works (note SIMILAR to all of you that will complain about this). There is a whole science on how to track the project progress using this method, because the number of new tasks will accelerate in the beginning and should fade to the end of the project.

The idea is to iterate code and design. We used this process in my former company (with 130 developers) and it works great. We also used Doxygen to produce class and relation diagrams from code. This was a quick way to get a good overview of the actually coded design, to spot flaws and missing relations.

If this works for you or not, I can't tell. You have to try and see what works best for you.


问:
File system layout for multiple build targets
I am seeking some ideas for how to build and install software with some parameters. These including target OS, target platform CPU details, debugging variant, etc.
Some parts of the install are shared, such as documentation and many platform independent files, others are not, such as 64 and 32 bit libraries when these are separated and not together in a multi-arch library.

On big networked platforms one often has multiple computers sharing some large server space, so there is actually cause to have even Windows and Unix binaries on the same disk.

My product has already fixed an install philosophy of $INSTALL_ROOT/genericname/version/ so that multiple versions can coexist.

The question is: how to manage the layout of all the other stuff?

答:
Use a build tool which allows different source and target directories.  For each platform have a separate target directory into which the platform specific files are generated.

Builds may run faster if you use a common build directory for non-platform specific files.


答:
Given that when a package is installed in a system - there is only 1 system at hand. i.e. OS, CPU/Arch, 32/64 bits variables are fixed for that system target.

In this context, usually i would NOT make separate folder like

 $INSTALL_ROOT/package//<64-32bit>/versions/

Rather, i would define it as part of the naming. Look at it for example the RPM file naming convention:

 name-version-release.architecture.rpm

It does include the distribution version number as like like fc8 or fc11 etc.

Debian follows a similar naming convention but probably the packages have some internal directory layout. (Sorry donno details here!)

Title: File system layout for multiple build targets

Body:
I am seeking some ideas for how to build and install software with some parameters. These including target OS, target platform CPU details, debugging variant, etc.
Some parts of the install are shared, such as documentation and many platform independent files, others are not, such as 64 and 32 bit libraries when these are separated and not together in a multi-arch library.

On big networked platforms one often has multiple computers sharing some large server space, so there is actually cause to have even Windows and Unix binaries on the same disk.

My product has already fixed an install philosophy of $INSTALL_ROOT/genericname/version/ so that multiple versions can coexist.

The question is: how to manage the layout of all the other stuff?


问:
Is the "exposer (hack) pattern" a newly identified pattern or does it have another name?
EDITED FOR CLARIFICATION

In the past, I have seen a whole manner of resolutions and fudges. Some really stand out. One particular resolution that I initially thought of as a fudge possibly deserves a category of its own.

It could be considered a hack or a pattern, as a design pattern is just a piece of reusable code. So, it still conforms to the definition: http://en.wikipedia.org/wiki/Software_design_pattern

It possibly already has a name but I have not seen it in the literature. I was wondering if anyone knows another name for what I labelled the "exposer (hack) pattern".

I have included an example of it below. This code is used to expose data that is not available to a data source. Instead, the results are not generated until a data bind method is called. Unfortunately, these results are not stored anywhere in the data source after execution. This is due to an oversight (or bad design) in the third party API. So, the results are passed a repeater to store locally, before returning these out as a populated PageDataCollection:

```<code>public static PageDataCollection Search(this SearchDataSource searchDataSource)
{
            PageDataCollection results = new PageDataCollection();

            //This is a dummy repeater whose only purpose is to provide a way of
            //iterating over the search results
            Repeater dummy = new Repeater();

            dummy.ItemDataBound += delegate(Object sender, RepeaterItemEventArgs e)
            {
                if (e != null && e.Item != null && e.Item.DataItem != null)
                {
                    PageData pageData = e.Item.DataItem as PageData;

                    if (pageData != null)
                    {
                        results.Add(pageData);
                    }
                }
            };

            dummy.DataSource = searchDataSource;

            dummy.DataBind();

            return results;
        }
</code>```

答:
I don't know of an applicable anti pattern. I would just says its an arse backward way of coding. If you're writing code like that, you're either using the wrong classes or don't understand the correct implementation of those classes.

Edit from your comments (I didn't get that from the question) it seems you're coding like this to get around the limitations of a 3rd party API. The most appropriate term is a "hack". Hacks should be avoided where possible but clearly documented when they can't be avoided.


答:
I wouldn't want it known as a pattern because it really is not a pattern to recommend in general.

From you comment to Tom Squires' answer I understand that it is to expose stuff in classes of which you are not the author. And you need some way to get at stuff not exposed by the authors of those classes.

I use TProtectedSomeClass = class(TSomeClass) (Delphi) to get access to protected members of a class in libraries I don't control (even if I have the source). It is known as the "protected hack".

What you are doing feels like hacking as well and I think that if you name the pattern it would be good to have "hack" in the name of it. "Hacker" sounds nice and short. :-)

Title: Is the "exposer (hack) pattern" a newly identified pattern or does it have another name?

Body:
EDITED FOR CLARIFICATION

In the past, I have seen a whole manner of resolutions and fudges. Some really stand out. One particular resolution that I initially thought of as a fudge possibly deserves a category of its own.

It could be considered a hack or a pattern, as a design pattern is just a piece of reusable code. So, it still conforms to the definition: http://en.wikipedia.org/wiki/Software_design_pattern

It possibly already has a name but I have not seen it in the literature. I was wondering if anyone knows another name for what I labelled the "exposer (hack) pattern".

I have included an example of it below. This code is used to expose data that is not available to a data source. Instead, the results are not generated until a data bind method is called. Unfortunately, these results are not stored anywhere in the data source after execution. This is due to an oversight (or bad design) in the third party API. So, the results are passed a repeater to store locally, before returning these out as a populated PageDataCollection:

```<code>public static PageDataCollection Search(this SearchDataSource searchDataSource)
{
            PageDataCollection results = new PageDataCollection();

            //This is a dummy repeater whose only purpose is to provide a way of
            //iterating over the search results
            Repeater dummy = new Repeater();

            dummy.ItemDataBound += delegate(Object sender, RepeaterItemEventArgs e)
            {
                if (e != null && e.Item != null && e.Item.DataItem != null)
                {
                    PageData pageData = e.Item.DataItem as PageData;

                    if (pageData != null)
                    {
                        results.Add(pageData);
                    }
                }
            };

            dummy.DataSource = searchDataSource;

            dummy.DataBind();

            return results;
        }
</code>```


问:
Separating a "wad of stuff" utility project into individual components with "optional" dependencies
Over the years of using C#/.NET for a bunch of in-house projects, we've had one library grow organically into one huge wad of stuff. It's called "Util", and I'm sure many of you have seen one of these beasts in your careers.

Many parts of this library are very much standalone, and could be split up into separate projects (which we'd like to open-source). But there is one major problem that needs to be solved before these can be released as separate libraries. Basically, there are lots and lots of cases of what I might call "optional dependencies" between these libraries.

To explain this better, consider some of the modules that are good candidates to become stand-alone libraries. CommandLineParser is for parsing command lines. XmlClassify is for serializing classes to XML. PostBuildCheck performs checks on the compiled assembly and reports a compilation error if they fail. ConsoleColoredString is a library for colored string literals. Lingo is for translating user interfaces.

Each of those libraries can be used completely stand-alone, but if they are used together then there are useful extra features to be had. For example, both CommandLineParser and XmlClassify expose post-build checking functionality, which requires PostBuildCheck. Similarly, the CommandLineParser allows option documentation to be provided using the colored string literals, requiring ConsoleColoredString, and it supports translatable documentation via Lingo.

So the key distinction is that these are optional features. One can use a command line parser with plain, uncolored strings, without translating the documentation or performing any post-build checks. Or one could make the documentation translatable but still uncolored. Or both colored and translatable. Etc.

Looking through this "Util" library, I see that almost all potentially separable libraries have such optional features that tie them to other libraries. If I were to actually require those libraries as dependencies then this wad of stuff isn't really untangled at all: you'd still basically require all the libraries if you want to use just one.

Are there any established approaches to managing such optional dependencies in .NET?

答:
I thought I'd post the most viable option we've come up with so far, to see what the thoughts are.

Basically, we'd separate each component into a library with zero references; all the code that requires a reference will be placed into an #if/#endif block with the appropriate name. For example, the code in CommandLineParser that handles ConsoleColoredStrings would be placed into #if HAS_CONSOLE_COLORED_STRING.

Any solution that wishes to include just the CommandLineParser can easily do so, since there are no further dependencies. However, if the solution also includes the ConsoleColoredString project, the programmer now has the option to:

add a reference in CommandLineParser to ConsoleColoredString

add the HAS_CONSOLE_COLORED_STRING define to the CommandLineParser project file.

This would make the relevant functionality available.

There are several issues with this:

This is a source-only solution; every consumer of the library must include it as a source code; they can't just include a binary (but this isn't an absolute requirement for us).

The library project file of the library gets a couple of solution-specific edits, and it's not exactly obvious how this change is committed to SCM.

Rather un-pretty, but still, this is the closest we've come up with.

One further idea we considered was using project configurations rather than requiring the user to edit the library project file. But this is absolutely unworkable in VS2010 because it adds all project configurations to the solution unwantedly.


问:
Why is #include <iostream.h> bad?
I was reading another thread where a guy asked about C++ books for beginners, and one of the programmers answering wrote this:

Some warnings: avoid all books that present an "hello world" stating with

```<code>#include <iostream.h>
</code>```

I opened my C++ book and sure enough it included the iostream header like the example above.

Why is that bad? What other pointers should I keep in mind when learning C++?

Background: I am proficient with C and I'll start to learn C++ this next semester.

答:
The header iostream.h is a non-standard header and does not exist on all platforms. As a matter of fact it does not exist on my system (using g++ and the GNU libstdc++). So any code using it would simply not compile on my system.

The iostream.h header used to be common before C++ was first standardized in 1998. But since the 98 standard used <iostream> instead of <iostream.h>, the latter has fallen out of favor (being non-standard and all) and is no longer supported on all platforms. Code that uses it should be considered non-standard legacy code and is not portable. Books that teach it should be considered outdated and avoided.

Title: Why is #include <iostream.h> bad?


答:
Given your reference to problematic 3rd party API you can't just get rid of, your workaround looks pretty close to Escape Hatch:

Context: You are in a paradigm (e.g. language, runtime environment, scribble on back of envelope) and you need to express or
  do some thing which does not fit.

Problem: You are being restricted by your current tool set.

Forces: You may not be able to ditch your current tool for various reasons: technical, legal, political or legacy code...

By the way if you've got a lot of issues of that kind, consider arranging an Anticorruption Layer:

If your application needs to deal with a database or another application whose model is undesirable or inapplicable to the model you want within your own application, use an AnticorruptionLayer to translate to/from that model and yours.


问:
Python productivity VS Java Productivity
Over on SO I came across a question regarding which platform, Java or Python is best for developing on Google AppEngine. Many people were boasting of the increased productivity gained from using Python over Java. One thing I would say about the Python vs Java productivity argument, is Java has excellent IDE's to speed up development whereas Python is really lacking in this area because of its dynamic nature.

So even though I prefer to use Python as a language, I don't believe it gives quite the productivity boost compared to Java especially when using a new framework. Obviously if it were Java vs Python and the only editor you could use was VIM then Python would give you a huge productivity boost but when IDE's are brought into the equation its not as clear cut.

I think Java's merits are often solely evaluated on a language level and often on out dated assumptions but Java has many benefits external to the language itself, e.g the JVM (often criticized but offers huge potential), excellent IDE's and tools, huge numbers of third party libraries, platforms etc..

Question: Does Python, or related dynamic languages, really give the huge productivity boosts often talked about (with consideration given to using new frameworks and working with medium to large applications)?

答:
Here are my 2 cents. In my experience Python is good for small to middle-sized
projects whereas for larger projects I am more productive with Java.

In general, I can use a dynamically typed language like Python (or PHP) for
smaller projects: it is not too complex, you want to get it done fast and
there is not too much that can go wrong. In this case, I find that Python
can be more practical to use.

However, when I have to develop a larger piece of software, I prefer a
statically typed language like Java because I prefer the compiler to perform
as many checks as possible for me. My experience is that in larger projects
I have to spend more time fixing bugs with Python than with Java, so I do not
bother if it takes a bit more to write the code in Java because this will
save time later.


答:
Just dropping my 2 cents. I don't think there is a correlation between ".h" and the quality of a book. This is a minor syntax issue. Back in the day it was actually the correct sytnax.

Is it possible to have a great book with iostream.h? yes

Is it possible to have a terrible book with iostream? yes

I would rely on online user reviews (and my own review after reading) to judge the quality of a book.

Title: Why is #include <iostream.h> bad?

Body:
I was reading another thread where a guy asked about C++ books for beginners, and one of the programmers answering wrote this:

Some warnings: avoid all books that present an "hello world" stating with

```<code>#include <iostream.h>
</code>```

I opened my C++ book and sure enough it included the iostream header like the example above.

Why is that bad? What other pointers should I keep in mind when learning C++?

Background: I am proficient with C and I'll start to learn C++ this next semester.


问:
Are design patterns independent of programming languages?
I have been recently working on Objective C and came across use of Delegate pattern.

I had seen most of the common patterns theoretically in Java, thanks to the Head First book.

But at times looking at differences in Dynamic and scripting languages I get confused about need of certain design patterns.

For example lets take example of Adapter pattern.

It already has two implementations : Object adapter[java] and Class Adapter[C++].
depending on whether the language has supports for Multiple inheritance or not.

But with dynamic languages like Objective-C, duck-typing is possible and also we have methods like respondsToSelector to check if an object actually supports a method or not.
So why do we have protocols here even if we need to use a delegate pattern ?

If we can assume anything to be anything.in a dynamic language, do we need concept of abstract class or interface at all to implement few patterns ?

they more look like tools for statically typed languages to give dynamic behavior.

specially I dont understand the need for abstract keyword in PHP.

Can anyone point out some important details, I am relatively new to this.

答:
We all know that, specially in programming, there's more than one way to skin a cat. Modern languages are very powerful and flexible these days, and in some cases offer ways around some patterns.

Patterns and the abstract keyword in PHP any many other OO languages is more about structure and integrity. The abstract keyword, for example, gives the programmer instructions as to how to write an extension class.  Look at this example: http://php.net/manual/en/language.oop5.abstract.php#example-181

Right off the bat I know:

I can't use AbstractClass by itself. I must write another class that extends it.

I already have the printOut() method available to me, so I don't have to re-write it.

Whatever I do, I must write my own protected getValue() and prefixvalue($prefix) methods.

As long as I follow these requirements, I know it's going to work. When someone else wants to extend this class, they'll know what to do.

OwnerDisplayName: Amogh Talpallikar

OwnerDisplayName: Ayman Safadi


答:
If I understand your question correctly, the answer boils down to this:

TLDR

The reason for having things like abstract classes and interfaces/protocols in a dynamic language like Objective-C are mainly simplicity and cleanliness of code.

The longer version

As cool as duck-typing is, it's actually a huge hassle if you cannot make any assumptions on the type of an object:

every respondsToSelector: line in your code messes it up. It adds noise that obfuscates what you are actually trying to accomplish for little to no benefit.

Besides, it's shit-work.

So if you provide an API contract by loosing some dynamism, using a more statically typed model it's almost always a win:

Replacing multiple respondsToSelector: methods with a single conformsToProtocol: is a win.

Having a succinct and clear listing of the necessary methods in the protocol definition is a win. (Writing that definition in and of itself is shit-work as well, but it keeps you from doing more shit-work in a number of places, so that's tolerable.)

Based on that, having the compiler warn you if you omitted implementing any one of those methods is a huge win.

And: Not having to write a single respondsToSelector: or conformsToProtocol: message at all, because the compiler can now warn and tell you where you messed up, is the biggest win of all.

If you can go further than that by providing a common foundation of actual implementation, creating an abstract class might be an even bigger win (probably not so useful in the context of delegation...) — after all, repeating yourself in implementation is the worst case of shit-work, as every change will result in more shit-work to keep things consistent.

So yes, dynamism is a cool and useful thing to have, as it allows you to pull off all kinds of fun tricks. But in practice, getting rid of some of that (where appropriate) can make your life much easier and keep you from doing shit-work — like writing respondsToSelector:.

Title: Are design patterns independent of programming languages?

Body:
I have been recently working on Objective C and came across use of Delegate pattern.

I had seen most of the common patterns theoretically in Java, thanks to the Head First book.

But at times looking at differences in Dynamic and scripting languages I get confused about need of certain design patterns.

For example lets take example of Adapter pattern.

It already has two implementations : Object adapter[java] and Class Adapter[C++].
depending on whether the language has supports for Multiple inheritance or not.

But with dynamic languages like Objective-C, duck-typing is possible and also we have methods like respondsToSelector to check if an object actually supports a method or not.
So why do we have protocols here even if we need to use a delegate pattern ?

If we can assume anything to be anything.in a dynamic language, do we need concept of abstract class or interface at all to implement few patterns ?

they more look like tools for statically typed languages to give dynamic behavior.

specially I dont understand the need for abstract keyword in PHP.

Can anyone point out some important details, I am relatively new to this.

OwnerDisplayName: danyowdee


问:
How to treat "The field is never used" warnings?

Warning   1 The field 'MCS_SPS_School.Fees.DiscountAmt.rtvalue' is assigned but its value is never used   G:\Jagadeeswaran\Nov 17\MCS-SPS School\MCS-SPS School\Fees\DiscountAmt.cs

Warning   2 The field 'MCS_SPS_School.Fees.DiscountAmt.dt' is never used  G:\Jagadeeswaran\Nov 17\MCS-SPS School\MCS-SPS School\Fees\DiscountAmt.cs

This type of warning is still in my project. But the project runs safely.

Now what I do for this warnings, to fix or Ignore?

Is any dangerous if ignore that, performance wise or other?

答:
The warning means exactly that - you have declared fields in your classes that you never use.

Warning 1 means that your DiscountAmt.cs file has fields named rtvalue and dt that are declared but not referenced anywhere.

These fields take some space for each instance of the class, even though they are never used - best practice is to delete such fields.

There is another issue to do with warnings - if you don't fix these, you end up with many warnings. Some of these warnings are important, but you will never notice them because you have many other warnings that these get lost in the noise. A good practice is to have 0 warnings and 0 errors.


答:
Always fix warnings and hints. They point to issues that can pose problems later on.

Even if this warning seems unimportant, when you start ignoring "unimportant" hints and warnings, you will soon be drowned in them  and then you won't spot the ones that are in fact very important and do cause bugs if unaddressed.

Any development team serious about code quality will have a zero hints and warnings policy in place. Our build server will continue a build when some projects produce hints and warnings, but our QA department will be all over us if we allow these to propagate from "work" branches into the main development branch. And issues in work branches won't be "resolved" (accepted for integration into the main development branch) by them until all hints and warnings are gone and all unit tests succeed.

Title: How to treat "The field is never used" warnings?

Body:
Warning   1 The field 'MCS_SPS_School.Fees.DiscountAmt.rtvalue' is assigned but its value is never used   G:\Jagadeeswaran\Nov 17\MCS-SPS School\MCS-SPS School\Fees\DiscountAmt.cs

Warning   2 The field 'MCS_SPS_School.Fees.DiscountAmt.dt' is never used  G:\Jagadeeswaran\Nov 17\MCS-SPS School\MCS-SPS School\Fees\DiscountAmt.cs

This type of warning is still in my project. But the project runs safely.

Now what I do for this warnings, to fix or Ignore?

Is any dangerous if ignore that, performance wise or other?


答:
It's not directly a safety problem, but it might be an indirect one.  That's why it's a warning.  The compiler is telling you that you've declared something but you aren't actually doing anything with it, which most likely means that your code is incomplete: you started building something and didn't finish it.  This could cause bugs further down the line.

The best way to fix this warning is to either finish writing whatever was supposed to use this value, or delete it.


答:
if you are delaying the fix for this item until later stage of the project you can turn of the warning message by using the #pragma warning disable see link:
Pragma warning

otherwise remove the item if you are not using it until it is needed :)


答:
You could make use of interfaces declared in an additional library.

Try to resolve a contract (class via interface) using a dependency injection (MEF, Unity etc). If not found, set it to return a null instance.

Then check if the instance is null, in which case you don't do the extra functionalities.

This is especially easy to do with MEF, since it's the textbook use for it.

It would allow you to compile the libraries, at the cost of splitting them into n + 1 dlls.

HTH.

Title: Separating a "wad of stuff" utility project into individual components with "optional" dependencies

Body:
Over the years of using C#/.NET for a bunch of in-house projects, we've had one library grow organically into one huge wad of stuff. It's called "Util", and I'm sure many of you have seen one of these beasts in your careers.

Many parts of this library are very much standalone, and could be split up into separate projects (which we'd like to open-source). But there is one major problem that needs to be solved before these can be released as separate libraries. Basically, there are lots and lots of cases of what I might call "optional dependencies" between these libraries.

To explain this better, consider some of the modules that are good candidates to become stand-alone libraries. CommandLineParser is for parsing command lines. XmlClassify is for serializing classes to XML. PostBuildCheck performs checks on the compiled assembly and reports a compilation error if they fail. ConsoleColoredString is a library for colored string literals. Lingo is for translating user interfaces.

Each of those libraries can be used completely stand-alone, but if they are used together then there are useful extra features to be had. For example, both CommandLineParser and XmlClassify expose post-build checking functionality, which requires PostBuildCheck. Similarly, the CommandLineParser allows option documentation to be provided using the colored string literals, requiring ConsoleColoredString, and it supports translatable documentation via Lingo.

So the key distinction is that these are optional features. One can use a command line parser with plain, uncolored strings, without translating the documentation or performing any post-build checks. Or one could make the documentation translatable but still uncolored. Or both colored and translatable. Etc.

Looking through this "Util" library, I see that almost all potentially separable libraries have such optional features that tie them to other libraries. If I were to actually require those libraries as dependencies then this wad of stuff isn't really untangled at all: you'd still basically require all the libraries if you want to use just one.

Are there any established approaches to managing such optional dependencies in .NET?


问:
I need some counter-points to counter the argument of why NOT to use M-V-P
I whipped up a demo on Friday before the holiday weekend of using the Model-View-Presenter pattern (the "Passive View" version, I believe) that I want to show to my co-workers this week as an example of how to architect our WebForms application moving forward and get maintainable, clean code.  We currently keep almost all logic outside of some data access routines in the code-behind files.

I know immediately one of the points raised will be that it's faster/easier to just use code-behind rather than create a separate class library for the views and presenters, and having to create a separate view per page (that at least can get hairy as we have well over a hundred pages, although at this point I'm talking about future development and not retrofitting the rest of the code).  The argument will be that it's much faster to get a task done by doing something like this:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    DataSet ds = Customer.Get(Request.QueryString["custid"]);
    if (ds.Tables[0].Rows.Count > 0)
    {
       txtFirstName.Text = ds.Tables[0].Rows[0]["fname"].ToString();
       // other properties here..
    }
}
</code>```

than this:

```<code>// CustomerDetails.aspx
private CustomerDetailsPresenter _presenter;

protected void Page_Load(object sender, EventArgs e)
{
    long customerId = Convert.ToInt64(Request.QueryString["custid"]);
    _presenter = new CustomerDetailsPresenter(this);
    _presenter.Init(customerId);
}

// CustomerDetailsPresenter.cs
class CustomerDetailsPresenter
{
    private ICustomerDetailsView _view;

    // ctor here...

    public void Init(long customerId);
    {
        // get customer somehow, via ORM or DataSet or whatever...
        _view.FirstName = firstName; // some string, whether from dataset or ORM
    }
}
</code>```

What counter-arguments can I use to show the benefit of using the MVP pattern?  Specifically ways it would improve the speed and efficiency of getting things done.  Just saying "it's cleaner" or "you can properly abstract the code" isn't enough because code quality has never been a big issue, just speed (and now that mentality is biting us in the rear).

NOTE: This is for new features to an existing brownfield/legacy application, not for a new site (I would chose MVC for a brand new site).  New pages that have to interact with the application as a whole, radical changes to old pages, and the like is what we normally do and what I'm talking about using MVP for.

答: Trivially, all you have to do is introduce the case of multiple pages. In this case, it will be significantly easier to refactor and test the CustomerDetailsPresenter than six dozen copies of it's source code in six dozen pages.</p>


答:
No. This is why I think the Design Patterns book is a load of crud. The thesis of the book is that some things just can't be automated: design patterns.

For example the most famous, the Visitor Pattern .. err .. in an decent language that's a fold (accumulate in C++ STL).

What's actually discovered in the book isn't Design Patterns, but Language Deficiencies.

If there's a pattern, its the goal of language designers to be able to automate it. Almost all type theory research is centered on making polymorphic type systems more expressive.


答:
I know immediately one of the points raised will be that it's faster/easier to just use code-behind rather than create a separate class library for the views and presenters

This argument can be raised for plenty of things.

It's faster to start writing code, instead of spending more of the 50% of the time gathering requirements, designing the architecture of the future project, etc.

It's faster to not enforcing style guidelines.

It's faster to write code, instead of writing code and unit tests.

In all cases, the argument is invalid for large projects. You spend less time if you avoid writing unit tests, then you spend much more time debugging, understanding bug reports from your customer, etc.

If the project is really small, don't use MVP. Code-behind solution will be faster in all cases, with no drawbacks. If you are about to start a large-scale website with thousands of lines of code, not using MVP because it will be faster at the beginning is not a valid argument.

Title: I need some counter-points to counter the argument of why NOT to use M-V-P

Body:
I whipped up a demo on Friday before the holiday weekend of using the Model-View-Presenter pattern (the "Passive View" version, I believe) that I want to show to my co-workers this week as an example of how to architect our WebForms application moving forward and get maintainable, clean code.  We currently keep almost all logic outside of some data access routines in the code-behind files.

I know immediately one of the points raised will be that it's faster/easier to just use code-behind rather than create a separate class library for the views and presenters, and having to create a separate view per page (that at least can get hairy as we have well over a hundred pages, although at this point I'm talking about future development and not retrofitting the rest of the code).  The argument will be that it's much faster to get a task done by doing something like this:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    DataSet ds = Customer.Get(Request.QueryString["custid"]);
    if (ds.Tables[0].Rows.Count > 0)
    {
       txtFirstName.Text = ds.Tables[0].Rows[0]["fname"].ToString();
       // other properties here..
    }
}
</code>```

than this:

```<code>// CustomerDetails.aspx
private CustomerDetailsPresenter _presenter;

protected void Page_Load(object sender, EventArgs e)
{
    long customerId = Convert.ToInt64(Request.QueryString["custid"]);
    _presenter = new CustomerDetailsPresenter(this);
    _presenter.Init(customerId);
}

// CustomerDetailsPresenter.cs
class CustomerDetailsPresenter
{
    private ICustomerDetailsView _view;

    // ctor here...

    public void Init(long customerId);
    {
        // get customer somehow, via ORM or DataSet or whatever...
        _view.FirstName = firstName; // some string, whether from dataset or ORM
    }
}
</code>```

What counter-arguments can I use to show the benefit of using the MVP pattern?  Specifically ways it would improve the speed and efficiency of getting things done.  Just saying "it's cleaner" or "you can properly abstract the code" isn't enough because code quality has never been a big issue, just speed (and now that mentality is biting us in the rear).

NOTE: This is for new features to an existing brownfield/legacy application, not for a new site (I would chose MVC for a brand new site).  New pages that have to interact with the application as a whole, radical changes to old pages, and the like is what we normally do and what I'm talking about using MVP for.


答:
Yes.  This is why the Design Patterns books are very important.  The theses in all of these books is that some things can't be automated: good design.

What's actually discovered in the book has nothing to do with Language Deficiencies, but are patterns of good design.  Some of those patterns are filled by language features.  Some of those patterns are not filled by language features.

Good design is independent of language.

There are an unlimited number of distinct design patterns.  A language designer can't anticipate or fill all of them.

So why do we have protocols here even if we need to use a delegate pattern ?

Because protocols are a language implementation of a good design pattern.

do we need concept of abstract class or interface at all to implement few patterns ?

A formal abstract class is always useful, even in duck-typed languages.

A formal interface is an implementation, used by some languages.  The design pattern (even in duck typed languages) still exists.


答:
If I were one of your co workers I wouldn't be against the idea using MVP or MVC. But I would question the way you want to achieve it. The way you propose it is much harder than adding MVC 3.0 to the site. MVC and WebForms can be used on the same website. There is almost no argument why to do it in some manual way like you want to do it.

If you are using MVC you have better arguments against it is faster the old way because it does not take more time implementing with MVC. The amount of code you have to write is almost the same.


答:
Patterns are a way to solve common problems, it has nothing to do with speed or efficiency. More precisely problems that the languaje itself can handle as it is. If you want speed, code the critical parts in another language, perl is very fast, because in the end you can buy just more servers, cpu or ram, but if the code is a mess or hard to extend it's useless.
You won't find good arguments against a certain pattern because they are language independant. The only thing i can tell you for sure is that mixing a pattern with legacy code will make it hard to understand to another programmer.</p>


答:
I'll chime in with my two cents as well.

Writing out a full program on paper before you start is a "CS 101" exercise that works for Hello World.
But spewing out code without taking the time to think about what you want to achieve is a waste of time as well.

Between these two extremes, you have the full range o software methodologies, from hard Waterfall (expansive set of specifications, pretty much one output at the end) to agile ("light" specs with very fast turnaround between releases and constant "customer" dialogue).

In any case, you need to know what you are building before you can start, whatever the methodology. This will help frame the program's architecture. Waterfall will put an emphasis on having the whole system architectured before you start coding, so that you know what you will end up with.
Agile will put an emphasis on "spec the minimum functionnality to be achieved for the next iteration", and will admonish you to be prepared to re-arcitecture constantly (by creating suitable test suites and the like so that you can actually carry out such work).

Note that NO methodology will tell you to just start coding without a thought, and indeed, you should have a pretty good idea of what you are trying to do (be it the whole thing with Waterfall, or a smaller area with Agile). You do improvise somewhat in "HOW" you do something, not in "WHAT" you are trying to do.

I can draw a parallel with what you learn when taking acting lessons. One big part is "improv". When starting an improvisation, you need to come in with as little set in stone as you can, and be prepared to abandon your idea if someone takes the scene in another direction. You need great listening skills, and need to accept the others' propositions. The main thing is to come on stage with a character a situation, maybe a feeling you want to convey, and potentially an ending towards which you want to take the scene. But the furthest away the idea is in the scene, the more likely it is that you will end up somewhere else. In the end, it's a very "Agile" way of thinking, which might be what you are struggling with here.

Now, if you are talking at the "let's write code" level (specs, stories or whatever are available), then it's up to you. Some people do write pseudocode, some write comments before the actual code (in a "fill in the blank fashion) and some start by writing tests (see Test Driven Development). In any case, the goal is to frame your idea so that you achieve what you set out to do in your particular method.
At that level, most people do some thinking before they write the actual code. But going so far as to write down the code before hand on paper seems overkill to me...

Title: Should I plan ahead, or figure out programs as I'm writing them?

Body:
I was thinking today about Paul Graham's book "Hackers and Painters." More specifically, these two paragraphs:

"I was taught in college that one ought to figure out a program
  completely on paper before even going near a computer. I found that I
  did not program this way. I found that I liked to program sitting in
  front of a computer, not a piece of paper. Worse still, instead of
  patiently writing out a complete program and assuring myself it was
  correct, I tended to just spew out code that was hopelessly broken,
  and gradually beat it into shape. Debugging was a kind of final pass
  where you caught typos and oversights... [It] seemed like programming
  consisted of debugging.

... As far as I can tell, the way they taught me to program in college
  was all wrong. You should figure out programs as you're writing them,
  just as writers and painters and architects do."

That's how it's taught in my college and I'm pretty sure most other colleges as well. You figure out what your program will do, and then you figure out how to do it, then you type and debug. Sometimes you make a basic version and add functionality, but the idea is that you think through and then type.

This sort of reminds of that chapter in Feynman's book called "He Solves Radios By Thinking!" where he paced around thinking of how the radio could be broken, and then fixes it. To me, that's what programming is about - thinking and then finding a solution.

Is this the prevalent approach to coding? If so, why don't more people just hack away and put a program together without having a preconceived idea of what it's going to look like?

What are the advantages and disadvantages of think & type vs. spew & beat?


问:
research papers vs books
For studying advanced topics, what's the better and nearer to complete approach? Can books cover what's in research papers, journals or those ACM transactions, or Springer's LNCS? Or reading research papers is indispensable for getting advanced? If we can't depend on books for information, how can a learner know of what he is missing in a specific topic, since research papers cover a specific (very specific) topic which cannot be found in a collected manner of the whole topic as books do. Is there a place (may be wikipedia) which could help finding the way through a topic? Rephrasing my question, do research papers offer new information which may not be found in books or are they clever applications of the information found in books?</p>

答:
There are a lot of useless papers, and a lot of great papers. Use the books to learn the fundamentals, and fill in your knowledge where you need to understand papers.

Blog posts, lambda the ultimate, and cstheory.stackexchange are also great resources.

Basically: use everything you can get your hands on that is relevant.

Title: research papers vs books