问:
Which are the alternatives to using a stack to represent function call semantics?
We all know and love that function calls are usually implemented using the stack; there are frames, return addresses, parameters, the whole lot.

However, the stack is an implementation detail: calling conventions may do different things (i.e. x86 fastcall uses (some) registers, MIPS and followers use register windows, and so on) and optimizations can do even other things (inlining, frame pointer omission, tail-call optimization..).

Sure, the presence of convenient stack instruction on many machines (VMs like JVM and the CLR, but also real machines like x86 with their PUSH/POP etc.) make it convenient to use it for function calls, but in some cases it is possible to program in a way in which a call stack is not needed (I am thinking about Continuation Passing Style here, or Actors in a message passing system)

So, I was beginning to wonder: is it possible to implement function call semantics without a stack, or better, using a different data structure (a queue, perhaps, or an associative map?)

Of course, I understand that a stack is very convenient (there is a reason why it is ubiquitous) but I recently bumped into an implementation that made me wonder..

Do any of you know if it has ever been done in any language/machine/virtual machine, and if so which are the striking differences and shortcomings?

EDIT:
My gut feelings are that different sub-computation approaches can use different data structures.
For example, lambda calculus is not stack based (the idea of function application is captured by reductions) but I was looking at a real language/machine/example. That's why I am asking...

答:
It's not possible to implement function call semantics without using some sort of stack. It's only possible to play word games (e.g. use a different name for it, like "FILO return buffer").

It is possible to use something that doesn't implement function call semantics (e.g. continuation passing style, actors), and then build function call semantics on top of it; but this means adding some sort of data structure to track where control is passed when the function returns, and that data structure would be a type of stack (or a stack with a different name/description).

Imagine you have many functions that can all call each other. At run-time, each function must know where to return to when the function exits. If first calls second then you have:

```<code>second returns to somewhere in first
</code>```

Then, if second calls third you have:

```<code>third returns to somewhere in second
second returns to somewhere in first
</code>```

Then, if third calls fourth you have:

```<code>fourth returns to somewhere in third
third returns to somewhere in second
second returns to somewhere in first
</code>```

As each function is called, more "where to return" information must be stored somewhere.

If a function returns, then its "where to return" information is used and is no longer needed. For example, if fourth returns back to somewhere in third then the amount of "where to return to" information would become:

```<code>third returns to somewhere in second
second returns to somewhere in first
</code>```

Basically; "function call semantics" implies that:

you must have "where to return" information

the amount of information grows as functions are called and is reduced when functions return

the first piece of "where to return" information stored will be the last piece of "where to return" information discarded

This describes a FILO/LIFO buffer or a stack.

If you attempt to use a type of tree, then every node in the tree will never have more than one child. Note: a node with multiple children can only happen if a function calls 2 or more functions at the same time, which requires some sort of concurrency (e.g. threads, fork(), etc) and it would not be "function call semantics". If every node in the tree will never have more than one child; then that "tree" would only be used as a FILO/LIFO buffer or a stack; and because it's only used as a FILO/LIFO buffer or a stack it's fair to claim that the "tree" is a stack (and the only difference is word games and/or implementation details).

The same applies to any other data structure that could conceivably used to implement "function call semantics" - it will be used as a stack (and the only difference is word games and/or implementation details); unless it breaks "function call semantics". Note: I would provide examples for other data structures if I could, but I can't think of any other structure that is slightly plausible.

Of course how a stack is implemented is an implementation detail. It could be an area of memory (where you keep track of a "current stack top"), it could be some sort of linked list (where you keep track of "current entry in list"), or it could be implemented in some other way. It also doesn't matter if hardware has built-in support or not.

Note: If only one invocation of any procedure may be active at any moment; then you can statically allocate space for "where to return to" information. This is still a stack (e.g. a linked list of statically allocated entries used in a FILO/LIFO way).

Also note that there are some things that do not follow "function call semantics". These things include "potentially very different semantics" (e.g. continuation passing, actor model); and also includes common extensions to "function call semantics" like concurrency (threads, fibres, whatever), setjmp/longjmp, exception handling, etc.

Body:
It's not possible to implement function call semantics without using some sort of stack. It's only possible to play word games (e.g. use a different name for it, like "FILO return buffer").

It is possible to use something that doesn't implement function call semantics (e.g. continuation passing style, actors), and then build function call semantics on top of it; but this means adding some sort of data structure to track where control is passed when the function returns, and that data structure would be a type of stack (or a stack with a different name/description).

Imagine you have many functions that can all call each other. At run-time, each function must know where to return to when the function exits. If first calls second then you have:

second returns to somewhere in first

Then, if second calls third you have:

third returns to somewhere in second
second returns to somewhere in first

Then, if third calls fourth you have:

fourth returns to somewhere in third
third returns to somewhere in second
second returns to somewhere in first

As each function is called, more "where to return" information must be stored somewhere.

If a function returns, then its "where to return" information is used and is no longer needed. For example, if fourth returns back to somewhere in third then the amount of "where to return to" information would become:

third returns to somewhere in second
second returns to somewhere in first

Basically; "function call semantics" implies that:

you must have "where to return" information

the amount of information grows as functions are called and is reduced when functions return

the first piece of "where to return" information stored will be the last piece of "where to return" information discarded

This describes a FILO/LIFO buffer or a stack.

If you attempt to use a type of tree, then every node in the tree will never have more than one child. Note: a node with multiple children can only happen if a function calls 2 or more functions at the same time, which requires some sort of concurrency (e.g. threads, fork(), etc) and it would not be "function call semantics". If every node in the tree will never have more than one child; then that "tree" would only be used as a FILO/LIFO buffer or a stack; and because it's only used as a FILO/LIFO buffer or a stack it's fair to claim that the "tree" is a stack (and the only difference is word games and/or implementation details).

The same applies to any other data structure that could conceivably used to implement "function call semantics" - it will be used as a stack (and the only difference is word games and/or implementation details); unless it breaks "function call semantics". Note: I would provide examples for other data structures if I could, but I can't think of any other structure that is slightly plausible.

Of course how a stack is implemented is an implementation detail. It could be an area of memory (where you keep track of a "current stack top"), it could be some sort of linked list (where you keep track of "current entry in list"), or it could be implemented in some other way. It also doesn't matter if hardware has built-in support or not.

Note: If only one invocation of any procedure may be active at any moment; then you can statically allocate space for "where to return to" information. This is still a stack (e.g. a linked list of statically allocated entries used in a FILO/LIFO way).

Also note that there are some things that do not follow "function call semantics". These things include "potentially very different semantics" (e.g. continuation passing, actor model); and also includes common extensions to "function call semantics" like concurrency (threads, fibres, whatever), setjmp/longjmp, exception handling, etc.


问:
How easy is it to hack JavaScript (in a browser)?
My question has to do with JavaScript security.

Imagine an authentication system where you're using a JavaScript framework like Backbone or AngularJS, and you need secure endpoints. That's not a problem, as the server always has the last word and will check if you're authorized to do what you want.

But what if you need a little security without involving the server? Is that possible?

For example, say you've got a client-side routing system and you want a concrete route to be protected for logged-in users. So you ping the server asking if you're allowed to visit protected routes and you go on. The problem is that when you ping the server, you store the response in a variable, so the next time you go to a private route, it will check that if you're already logged in (no ping to the server), and depending on the response it will go or not.

How easy is for a user to modify that variable and get access?

My security (and JavaScript) knowledge isn't great. But if a variable is not in global scope and is in the private part of a module pattern which only have getters but not setters, even in that case, can you hack the thing out?

答:
It's simple: any security mechanism that relies on the client to do only what you tell it to do can be compromised when an attacker has control over the client.

You can have security checks on the client, but only to effectively act as a "cache" (to avoid making an expensive round-trip to the server if the client already knows that the answer will be "no").

If you want to keep information from a set of users, make sure that those users' client never gets to that information. If you send that "secret data" together with instructions "but please don't display it," it'll become trivial to disable the code that checks that request.

As you see, this answer doesn't really mention any JavaScript/Browser specifics. That's because this concept is the same, no matter what your client is. It doesn't really matter it's a fat client (traditional client/server app), an old-school web application, or a single-page-app with extensive client-side JavaScript.

Once your data leaves the server, you must assume that an attacker has full access to it.

ContentLicense: CC BY-SA 3.0


问:
Tic tac toe class diagram
I'm in a software engineering class and I want to practice some skills on the most basic case possible : tic tac toe. I know this is overkill but I want to do it in "proper" OOP.

I designed a class diagram for it but there is one point where I don't clearly see what would be the best design decision.

("Joueur" means "Player", "PlancheDeJeu" means "Game board")

Given this diagram, according to the Expert, Low coupling and Strong cohesion design patterns (sorry if those are not the correct english terms, I am translating) the score should be kept by the user class (Joueur). However, since there is no direct relation between Joueur and Système I don't exactly know how the game could display the score in a clean way. In this diagram, Système would have to ask the PlancheDeJeu object about the score and it would itself have to get it from Joueur. This seems wrong. I am trying to think of how to design an intermediary object that would link Joueur and Système but I can't come up with a good idea.

What would be the best way to go here ?

Thanks !

答:
First one should clarify what is meant by score. If that means "the number of wins, losses and remis outcomes in all previous games", then it should be clear that the score cannot belong to a game board, because the lifetime of a gameboard should be just one game. So the score is a personal property of each player, meaning it is correctly placed there.

This picture gets even clearer if you think of having more than two players, all of them having a Tic Tac Toe tournament. And indeed, since you have to manage the existing players somewhere (independently from the game board), I guess you should add the players to the system in form of a relationship.

I am trying to think of how to design an intermediary object that would link Joueur and Système

Why not just creating a 1:n association between System and Player? That should be sufficient. There must be a place in the program where players and the empty game board will be created, a place where the actual two players are picked (among all players), and a place where they get the current game board assigned. These are tasks typically done by a different ("higher level") object, maybe the "System" object in your model.

Title: Tic tac toe class diagram


答:
Please read Joachim's answer before reading this one. He covers the general reasons behind client-side vulnerability. Now, for a suggestion how you might get around this problem...

A secure scheme for client-server communication without having to authenticate with the server manually on every request:

You're still letting the server have the last say, and the server still has to validate everything the client says, but it happens transparently.

Assume the HTTPS protocol to prevent man-in-the-middle attacks (MITMA).

The client handshakes with the server for the first time, and the server generates a public key for the client and keeps a private one using an asymmetric encryption scheme. The client stores the server's "public" key in the local storage, encrypted with a secure password you don't save anywhere.

The client is now offline. The client wants to perform trusted actions. The client enters his password and grabs the server's public key.

The client now performs actions based on its knowledge of that data, and the client encrypts every action it performs with the server's public key for that client.

When the client is online, client sends its client ID and all actions the client performed are sent to the server encrypted with the server's public key.

The server decrypts the actions, and if they are in correct format it trusts that they originated in the client.

Note:

You can't store the client's password anywhere, otherwise an attacker would be able to fetch the key and sign the actions as its own. The security of this scheme relies solely on the integrity of the key the server generates for the client. The client would still need to be authenticated with the server when asking for that key.

You're still in fact relying on the server for security and not the client. Every action the client performs you must validate on the server.

It's possible to run external scripts in web workers. Keep in mind every JSONP request you have is now a much bigger security issue. You need to protect the key at all costs. Once you lose it, an attacker can impersonate the user.

This meets your demand that 'no ping to the server' is performed. An attacker can't simply imitate an HTTP request with forged data if they don't know the key.

Joachim's answer is still correct. You're still, in fact, performing all authentication on the server. The only thing you saved here is the need for password validation with the server every time. You now need only to involve the server when you want to commit, or pull updated data. All we did here is save a trusted key on the client side and have the client re-validate it.

This is a pretty common scheme for single page applications (for example, with AngularJS).

I call the server's public key "public" because of what that means in schemes like RSA, but it is in fact sensitive information in the scheme and should be safeguarded.

I wouldn't keep the password anywhere in memory. I'd make the user submit his/her 'offline' password every time he/she starts running offline code.

Don't roll your own cryptography - use a known library like Stanford's for authentication.

Take this advice as is. Before you roll this sort of authentication in a real world business-critical application consult a security expert. This is a serious issue that is both painful and easy to get wrong.

It's critical that no other scripts have access to the page. This means you only allow external scripts with web workers. You can't trust any other external scripts that might intercept your password when the user enters it.

Use a prompt and not an inline password field if you're not completely sure and don't defer its execution (that is, it shouldn't live to a point where events have access to it but only in sync code). And don't actually store the password in a variable -- again, this only works if you trust the user's computer isn't compromised (although that's all true for validating against a server too).

I'd like to add again that we still don't trust the client. You can't trust the client alone, and I think Joachim's answer nails it. We only gained the convenience of not having to ping the server before starting to work.

Related material:

Certificates vs username+password.

Why can't we do security via client side?

Don't roll your own crypto.

Related discussion about making JS secure for crypto operations

Title: How easy is it to hack JavaScript (in a browser)?

Body:
My question has to do with JavaScript security.

Imagine an authentication system where you're using a JavaScript framework like Backbone or AngularJS, and you need secure endpoints. That's not a problem, as the server always has the last word and will check if you're authorized to do what you want.

But what if you need a little security without involving the server? Is that possible?

For example, say you've got a client-side routing system and you want a concrete route to be protected for logged-in users. So you ping the server asking if you're allowed to visit protected routes and you go on. The problem is that when you ping the server, you store the response in a variable, so the next time you go to a private route, it will check that if you're already logged in (no ping to the server), and depending on the response it will go or not.

How easy is for a user to modify that variable and get access?

My security (and JavaScript) knowledge isn't great. But if a variable is not in global scope and is in the private part of a module pattern which only have getters but not setters, even in that case, can you hack the thing out?


答: There is a saying in the gaming community: "The client is in the hands of the enemy". Any code that is running outside of a secured area like the server is vulnerable. In the most basic scenario, vulnerable to not being run in the first place. It's the client's decision to actually run your "security code" and the user may just "opt out". While with native code you have at least an automatic obfuscation into assembly and an additional layer of protection by the fact that an attacker needs to be a good programmer to manipulate that, JS comes normally unobfucated and as plain text. All you need to stage an attack are primitive tools like a proxy server and a text editor. The attacker will still need a certain level of education concerning programming, but it's way easier to modify a script using any texteditor than injecting code into an executable.


答:
Score is derived data from the accumulation of game outcomes. The result of the game should be stored on the "Game Board" object. From there you could take a couple approaches.

1) You could keep a set of all games played in the "System" and provide a public method "score(Player)" which would calculate the score for all games that "Player" has completed. This option seems like it fits the needs of your system in order to display the data.

or

2) The Player keeps track of all games they have completed and can respond to "score" appropriately.

It looks like you may be missing a class though.

Player - A participant in a Tic Tac Toe game
Game (Board) - A stateful object that receives player input (moves) and determines win/lose/draw
System - Displays data to a User(?), Instantiates new Games(?), Creates new Players(?).

System feels pretty nebulous to me. It seems like there should be a Controller of some sort which can start new games and keep reference to them for analysis of the outcome. Introducing this object would give the System the ability to focus on Displaying data rather than having the mixed responsibility of keeping track of players, games and whatever else to display the data requested.

Using the Controller, it would provide the method score(Player).

Title: Tic tac toe class diagram

Body:
I'm in a software engineering class and I want to practice some skills on the most basic case possible : tic tac toe. I know this is overkill but I want to do it in "proper" OOP.

I designed a class diagram for it but there is one point where I don't clearly see what would be the best design decision.

("Joueur" means "Player", "PlancheDeJeu" means "Game board")

Given this diagram, according to the Expert, Low coupling and Strong cohesion design patterns (sorry if those are not the correct english terms, I am translating) the score should be kept by the user class (Joueur). However, since there is no direct relation between Joueur and Système I don't exactly know how the game could display the score in a clean way. In this diagram, Système would have to ask the PlancheDeJeu object about the score and it would itself have to get it from Joueur. This seems wrong. I am trying to think of how to design an intermediary object that would link Joueur and Système but I can't come up with a good idea.

What would be the best way to go here ?

Thanks !


问:
How is dependency injection not just moving the complexity into a separate class?
I've been looking into using the Typhoon framework for dependency injection this week. I get that separating the construction of objects is beneficial for replacing arbitrary components with mocks during unit testing, and so far I have seen benefits from this alone.

But I cannot help but think that where before I had a humongous view controller class that had tens of header imports, I now have a humongous factory class that has tens of header imports. Am I supposed to avoid having a massive factory class?

答:
Dependency Injection simply helps define how one object knows about another dependent object. It is not going to help you reduce the overall complexity of the system. If you needed tens of import before DI, you will still need tens of imports after. The difference is that these imports will be in a location (class) that makes more sense (factory, builder, etc).

By allowing dependencies to be provided through a constructor or method you allow yourself the flexibility to supply a different, yet still valid, dependent object to your class and increase cohesion of said class by removing concerns.

There are several principles that are similar and are often used together: Dependency Injection (DI), Inversion of Control (IoC), and the Dependency Inversion Principle (DIP)

From this article
http://martinfowler.com/articles/dipInTheWild.html

DI is about wiring, IoC is about direction, and DIP is about shape


答:
Depending on the language, it may not be necessary to use a call stack.  Call stacks are only necessary in languages that allow recursion or mutual recursion.  If the language does not allow recursion, then only one invocation of any procedure may be active at any moment, and local variables for that procedure may be statically allocated.  Such languages do have to make provision for context changes, for interrupt handling, but this still does not require a stack.

Refer to FORTRAN IV (and earlier) and early versions of COBOL for examples of languages that do not require call stacks.

Refer to the Control Data 6600 (and earlier Control Data machines) for an example of a highly-successful early supercomputer that did not provide direct hardware support for call stacks.  Refer to the PDP-8 for an example of a very successful early minicomputer that did not support call stacks.

As far as I know, the Burroughs B5000 stack machines were the first machines with hardware call stacks.  The B5000 machines were designed from the ground up to run ALGOL, which required recursion.  They also had one of the first descriptor-based architectures, which laid groundwork for capability architectures.

As far as I know, it was the PDP-6 (which grew into the DEC-10) that popularized call stack hardware, when the hacker community at MIT took delivery of one and discovered that the PUSHJ (Push Return Address and Jump) operation allowed the decimal print routine to be reduced from 50 instructions to 10.

The most basic function call semantics in a language that allow recursion require capabilities that match nicely with a stack.  If that's all you need, then a basic stack is a good, simple match.  If you need more than that, then your data structure has to do more.

The best example of needing more that I have encountered is the "continuation", the ability to suspend a computation in the middle, save it as a frozen bubble of state, and fire it off again later, possibly many times.  Continuations became popular in the Scheme dialect of LISP, as a way to implement, among other things, error exits.  Continuations require the ability to snapshot the current execution environment, and reproduce it later, and a stack is somewhat inconvenient for that.

Abelson & Sussman's "Structure and Interpretation of Computer Programs" goes into some detail on continuations.

Title: Which are the alternatives to using a stack to represent function call semantics?

Body:
We all know and love that function calls are usually implemented using the stack; there are frames, return addresses, parameters, the whole lot.

However, the stack is an implementation detail: calling conventions may do different things (i.e. x86 fastcall uses (some) registers, MIPS and followers use register windows, and so on) and optimizations can do even other things (inlining, frame pointer omission, tail-call optimization..).

Sure, the presence of convenient stack instruction on many machines (VMs like JVM and the CLR, but also real machines like x86 with their PUSH/POP etc.) make it convenient to use it for function calls, but in some cases it is possible to program in a way in which a call stack is not needed (I am thinking about Continuation Passing Style here, or Actors in a message passing system)

So, I was beginning to wonder: is it possible to implement function call semantics without a stack, or better, using a different data structure (a queue, perhaps, or an associative map?)

Of course, I understand that a stack is very convenient (there is a reason why it is ubiquitous) but I recently bumped into an implementation that made me wonder..

Do any of you know if it has ever been done in any language/machine/virtual machine, and if so which are the striking differences and shortcomings?

EDIT:
My gut feelings are that different sub-computation approaches can use different data structures.
For example, lambda calculus is not stack based (the idea of function application is captured by reductions) but I was looking at a real language/machine/example. That's why I am asking...


问:
Programming Style in Large Scale C++ Applications
Recently I've been browsing source code of large applications written in C++ to learn a bit but I couldn't help but notice that most if not all use a lot of IFDEFs and class-less functions (where they could have been class members/methods).

An example is Qt Creator IDE source code:

http://qt.gitorious.org/qt-creator/qt-creator/blobs/master/src/app/main.cpp

If you notice, it has a bunch of functions around the main() function; one of them, for example, is:

```<code>static inline void toHtml(QString &t)
</code>```

the above method is defined outside while I think it could have been part of some utility class maybe.

Also, I think IFDEFs make the programs messy (again my opinion).

My question is: is it just an accepted practice in C++ world to mix procedural and OO code like that?

答:
While I agree with others that the question is subjective, the two examples you give are viewed very differently by the C++ community:

#ifdef sparkled around C++ code is a bad practice. System-dependent code is best kept isolated in separate files and handled by the build system. Otherwise you get the mess that you saw in the cpp file you sent a link to.

Free functions in C++ are a good thing. Instead of giving lengthy explanation here, I suggest reading Scott Meyer's classic text on the topic: How Non-Member Functions Improve Encapsulation


答:
Dependency injection does not reduce complexity, but it increases manitainability through separation of concerns and reduced coupling.

But I cannot help but think that where before I had a humongous view controller class that had tens of header imports, I now have a humongous factory class that has tens of header imports. Am I supposed to avoid having a massive factory class?

You're supposed to avoid "humongous" classes, period. So let's say you split up the view controller into smaller, more maintainable classes. Now all of them are responsible to get hold of their dependencies. DI helps you to move this dependency management from all of those classes into a factory/configuration class which is only responsible for dependency management - see Single Responsibility Principle. And while it will certainly be much less "humongous" than the original view controller, if it gets too big you always have the option to split it into smaller dependency-management classes that are responsible for different parts of the application.

Title: How is dependency injection not just moving the complexity into a separate class?

Body:
I've been looking into using the Typhoon framework for dependency injection this week. I get that separating the construction of objects is beneficial for replacing arbitrary components with mocks during unit testing, and so far I have seen benefits from this alone.

But I cannot help but think that where before I had a humongous view controller class that had tens of header imports, I now have a humongous factory class that has tens of header imports. Am I supposed to avoid having a massive factory class?


问:
Why do many PHP Devs hate using isset() and/or any of PHP's similarly defensive functions like empty()?
Over on stackoverflow, I see this issue crop up all the time:

E_NOTICE ?== E_DEBUG, avoiding isset() and @ with more sophisticated error_handler

How to set PHP not to check undefind index for $_GET when E_NOTICE is on?

How to stop PHP from logging PHP Notice errors

How do I turn off such PHP 5.3 Notices ?

Even Pekka (who offers a lot of solid PHP advice) has bumped against the dreaded E_NOTICE monster and hoped for a better solution than using isset(): isset() and empty() make code ugly

Personally, I use isset() and empty() in many places to manage the flow of my applications.  For example:

```<code>public function do_something($optional_parameter = NULL) {
    if (!empty($optional_parameter)) {
        // do optional stuff with the contents of $optional_parameter
    }
    // do mandatory stuff
}
</code>```

Even a simple snippet like this:

```<code>if (!isset($_REQUEST['form_var'])) {
    // something's missing, do something about it.
}
</code>```

seems very logical to me.  It doesn't look like bloat, it looks like stable code.  But a lot of developers fire up their applications with E_NOTICE's enabled, discover a lot of frustrating "uninitialized array index" notices, and then grimace at the prospect of checking for defined variables and "littering" their code with isset().

I assume other languages handle things differently.  Speaking from experience, JavaScript isn't as polite as PHP.  An undefined variable will typically halt the execution of the script.  Also, (speaking from inexperience) I'm sure languages like C/C++ would simply refuse to compile.

So, are PHP devs just lazy?  (not talking about you, Pekka, I know you were refactoring an old application.)  Or do other languages handle undefined variables more gracefully than requiring the programmer to first check if they are defined?

(I know there are other E_NOTICE messages besides undefined variables, but those seem to be the ones that cause the most chagrin)

Addendum

From the answers so far, I'm not the only one who thinks isset() is not code bloat.  So, I'm wondering now, are there issues with programmers in other languages that echo this one?  Or is this solely a PHP culture issue?

答:
I code to E_STRICT and nothing else.

Using empty and isset checks does not make your code ugly, it makes your code more verbose. In my mind what is the absolute worst thing that can happen from using them? I type a few more characters.

Verses the consequences of not using them, at the very least warnings.

ContentLicense: CC BY-SA 2.5


问:
How can I translate my android app help and keep it up to date?
My Android application is almost done and I spend much time creating a set of very precise help pages in HTML that I display using WebViews. I am now ready for the next step, which is i18n.

Translating my app is no problem, the strings.xml is not that long and I can easily ask friends to translate it. My problem is about these help pages.

When I'll update my app, I'll probably have to update the help pages as well. I saw that it wasn't that simple, even with one language.

I need your opinion on how to perform such a massive work (which is not at all my job as a developer). Do I need to:

Manually update every language help page when I update the app, which means asking all of my translators to provide a new version of their work each time I change anything.

Provide help only in a default language (probably English, even though the default language is French. French people would still have the French help ;-D).

Google-translate the help pages, even if it "not well English is". I don't know any way to do it automatically.

Do something else, which you probably thought of long ago.

Thanks for your answers, tips and tricks.

答:
There isn't a convenient way to support internationalization and the associated translation that's required. As you noted, automatic translations leave a lot to be desired.

The easiest way around the translation problem is to simply avoid it.  As applicable, consider the following:

Avoid changes that impact the help files

Only provide translations on major version updates

Only document the critical stuff so there's less to translate

Consider providing video tutorials through your website

You do have a bit of a conundrum with considering English to be the default language for the help doc but then having French as the default language for the application.  If you do not write French fluently enough to provide the help documentation, then slap a Désolé, je n'écris pas français... message at the beginning of your help doc and explain that updates to help will lag the application updates.  For that matter, having that message at the beginning of all of your help docs would be beneficial.  Then ask your users to pay for your app so you can pay your friends for translating.


问:
Is writing software easier than reading and understanding it from scratch?
Me and a friend of mine were discussing yesterday about differences between writing a large C++ software and understanding it as a new recruit.

Is it possible that since a software gets done one line at a time and this process resembles how we (humans) learn things and build a thing on top of another one, writing a large software is actually easier than reading it and understanding what it does (stepping through the code helps but you need to remember multiple classes/source files together you don't even know what they've been written for, multithreaded code adds malus points)?

This sounds weird at first but after we thought a bit it seemed reasonable

答:
It's an interesting question, but I would tend to lean towards the side of it being easier to read and understand than it is to create it.

If you are a veteran, seasoned programmer, then you are likely to read through code and go "Yeah, good choice, check, oh, I might have done X instead of Y", etc. You may modify or tweak, but that would save immense time over writing from scratch (Unless there are reasons for doing so).

If you are a newer programmer, then "you don't know what you don't know", and so you are going to have to invent/learn all the little things, and very likely you are going to have some inefficiencies in the code. You will likely develop a greater understanding of the language, however.

But in both of those cases, it's going to be easier to read the code and go from there than it is to write it completely from scratch.


答:
The person writing the piece of software will almost always have the best understanding of the program simply due knowing the logic and his/her thinking process while writing it.

I don't think that writing code can at all be compared to reading code in terms of ease of understanding. On one hand, simply writing software provides greater understanding of that specific piece of software due to knowledge of the context associated with each section of code, library used, etc. However, reading code that others have written can be difficult to understand in terms of the actual piece of software, but in terms of understanding the language it can provide insight into new ways of doing things or uses of a library that you might not have considered using, which can lead to making your life writing code easier.

In terms of build knowledge, I think reading code and writing code are very connected and in many ways build on each other. Experience writing code provides ease of understanding others code, and reading code allows you to have an easier time writing code (through new logic concepts, library use, etc).

Title: Is writing software easier than reading and understanding it from scratch?

Body:
Me and a friend of mine were discussing yesterday about differences between writing a large C++ software and understanding it as a new recruit.

Is it possible that since a software gets done one line at a time and this process resembles how we (humans) learn things and build a thing on top of another one, writing a large software is actually easier than reading it and understanding what it does (stepping through the code helps but you need to remember multiple classes/source files together you don't even know what they've been written for, multithreaded code adds malus points)?

This sounds weird at first but after we thought a bit it seemed reasonable


答:
This is something that I've personally felt to be self-evident, but I've never been entirely sure that it holds for the programming populace as a whole. For example, I've known some very talented coders who rather than read documentation, can happily pick through other people's code and comprehend it as if it were their own.

This leads to the question: does this matter?

If you're reading the code, then chances are you're making a change rather than rewriting it. Even if you are rewriting it, you're likely to be writing this in a new language/version and so you may not necessarily craft the code in the same way. The point I'm making is that it isn't always necessary to understand all of the code all of the time.

All this being true, newer development methodologies e.g. BDD do recognise that it is important for the business logic to be clear from the code rather than the code simply being a means to drive the machine. This of course is nothing new - the concept has been around since Donald Knuth's seminal work: Literate Programming.


答:
Based on my experience, I would rank the following activities in order from easiest to hardest.

Reading good code

Writing bad code

Writing good code

Reading bad code

The above ranking leads to 2 conclusions

While it is easier to write code than reading bad code, it is easier to read good code than write your own code

Writing bad code is easier than writing good code, but writing bad code sets you up for reading bad code, which is the hardest thing of all. Especially since bad code is read more than it is written.

Of course, good code and bad code are broad generalizations. I recommend Code Complete and Clean Code for more details about good code.


答:
I'm into StMotorSpark's answer, just adding:

It depends on so many factors it can't be a yes or no question, for instance:

Is the existing code well documented and well written or does it look like a spaghetti without any sense or comments?

Is it a tiny app with very rare situations that cost you endless time to find out how to solution, or a larger but simple app?

etc.


答:
This question appeals to a False Consensus. http://en.wikipedia.org/wiki/False-consensus_effect

Different people learn and absorb information differently. It's akin to auditory learners, visual learners and kinestetic learners. For some, reading code is easier, for others, creating code is easier. For me, it is the latter. For others on my team, it is the former. I don't believe finding some kind of consensus or majority is useful. It is better to understand how your brain absorbs and learns information and use that knowledge to make yourself better and to learn to accept others who are different.


问:
How to copyright personal code
I am writing a program using VBA because its readily available, the code will be available to Cracks even though I password protect it. I knew this when I chose VBA because portability is more important than protection. My question relates to copyright, I put copyright and my name in the code and on the spread sheet to indicate it is my program but is this enough when people start copying the code?
Do you have a strong legal version which I could place in my code?</p>

答:
Copyright is Implicit

If it's personal, it's already copyrighted.

And something like what Matthew Foscarini gave you in his comment would do just fine to really make it clear:

Copyright 2013, Tony Royden, All rights reserved.

If it's you say you release copyright that it's not.

Licensing Isn't

On the other hand, that just tells people you're the rightful owner of some stuff. Doesn't tell them what they can or can't do with it. That comes with licensing terms, which are up to you to define. They can range from "do whatever the hell you want with it as long as I can't be held responsible for it" to a "you damn kids get off my lawn, that's my stuff!". Or the GPL, but it's more verbose and complex to read and get.

Big Fat Caveat: There's No Universal Copyright Law

There are not that many universal laws of any kind, for that matter. This will vary from country to country. This is usually the accepted logic online though, as we mostly talk about US Copyright Laws and laws from countries that adhere to the Berne Convention defining some international copyright agreements.

Your mileage may vary, ask a lawyer.

(Of course, IANAL and stuff...)

Title: How to copyright personal code

ContentLicense: CC BY-SA 4.0


答:
In the US, if you created it, you already have a copyright on your work. There's a difference between owning a copyright and registering a copyright. So yes, for some purposes it's enough to put your copyright notice on your work and call it a day. If you think you might ever need to enforce your copyright, though, you may want to also register your work with the US Copyright Office.

Start by reading about copyright at the US Copyright Office's FAQ. If you decide that you want to register your copyright, there's a step-by-step guide on wikihow.com that will help. It basically walks you through the registration process.

Title: How to copyright personal code

Body:
I am writing a program using VBA because its readily available, the code will be available to Cracks even though I password protect it. I knew this when I chose VBA because portability is more important than protection. My question relates to copyright, I put copyright and my name in the code and on the spread sheet to indicate it is my program but is this enough when people start copying the code?
Do you have a strong legal version which I could place in my code?</p>


答:
Most programmers find it easier to understand code they wrote themselves compared to code other people wrote.  This is due both to the line-by-line learning you mentioned, as well as just a matter of individual style and talent.  That's why so much wheel reinvention happens.

However, that's the view of the trees.  The forest view is that it's much easier to read code than to write it from scratch.  For example, is it easier to write a new word processor from scratch, or to learn an existing code base well enough to make improvements?

When you start reading the code, you can think of a bazillion ways to make the code easier for yourself to read.  You spend the first while just tracing code around, trying to figure out the lay of the land, sometimes in an architecture completely anathema to how you would like to do it.  But even in really large code bases, you'll spend maybe 40-80 hours spinning your wheels, compared to the hundreds of thousands of man hours already invested in creating that application.


答:
differences between writing a large C++ software and understanding it as a new recruit

This isn't the same thing as the difference between reading and writing software. When you're new to a project (and especially when you're new to a company) you have a lot more to learn than just what the code does. Understanding why the code does what it does often requires an understanding of how the business works and how the project relates to the rest of the organization. In short, reading code without the benefit of background knowledge is a slower, more difficult task than reading code when you fully understand the context in which the code works.

There is a difference between writing brand new code on a greenfield project and reading and modifying existing code, but I wouldn't say that one is necessarily easier than the other, just different. When you're creating something new, you don't have to worry about how to make your code work with what's already there, but you do have to worry about making your project sufficiently extensible and adaptable that it'll remain useful into the future. When you're working on an existing project, you can often use what's already there as a guide, but you must first understand what's there.

As a "new recruit" it's usually better to work on an existing project specifically because it helps you to learn all the things you don't know: how the business works, how the various projects work together, coding standards and practices, and even (especially) what could be improved.


问:
How to write a HTTP server?
As the title says, I would like to write a HTTP server. My question is this, how do I do this? I know this sounds VERY general and too "high level", but there is a method to my madness. An answer to this question should be, I believe, language agnostic; meaning, no matter what language I use (e.g., C, C++, Java, etc.) the answer should be the same. I have a general idea of how this is supposed to work:

Open a socket on port 80.

Wait for a client to make a request.

Read the request (i.e., this person wants page "contact-us.html").

Find and read "contact-us.html".

Send an html header, then send the content of "contact-us.html"

Done

Like I said, I believe this is the process, but I am not 100% sure. This leads me to the heart of my question. How or where does a person find out this information?

What if I didn't want to write just an HTTP server, what if I wanted to write an FTP server, a chat server, an image viewer, etc.? How does a person find out the exact steps/process needed to create a working HTTP server?

A co-worker told me about the html header, so I would have NEVER know this without him. He also said something about handing off each request to a new thread. Is there some big book of how things work? Is there some manual of what it takes to be an HTTP server?

I tried googling "how does a HTTP server work", but the only answers I could find were geared towards your average Joe, and not towards a person wanting to program a HTTP server.

答:
Use the RFC2616, Luke!

You read the RFC 2616 on HTTP/1.1, and you go for it.

That was actually a project in my 3rd year in engineering school, and that's pretty much the project description.

Tools

Your tools are:

basic networking stuff (socket management, binding, understand addresses),

good understanding of I/O streams,

a lot patience to get some shady parts of the RFC (mime-types are fun).

Fun Considerations

Things to consider for extra fun:

plug-in architecture to add CGI / mod support,

configuration files for, well, many things,

lots of experimentation on how to optimize transfers,

lots of experimentation to see how to manage load in terms of CPU and memory, and to pick a dispatch model (big fat even loop, single accept dispatch, multi-thread, multi-process, etc...).

Have fun. It's a very cool thing to look at.

Other (Simpler) Suggestions

FTP client/server (mostly RFC959 but there are older versions and also some extensions)

IRC client/server (mostly RFC1459, but there are extensions)

They're way easier to tackle first, and their RFCs are a lot easier to digest (well, the IRC one has some odd parts, but the FTP one is pretty clear).

Language Choice

Of course, some implementation details will be highly dependant on the language and stack you use to implement it. I approached all that in C, but I'm sure it can be fun just as well in other languages (ok, maybe not as much fun, but still fun).

Title: How to write a HTTP server?


答:
Each of the protocols used on the internet is specified in one or more public documents called RFCs. All the current RFCs can be found at http://www.rfc-editor.org/, which also has a decent search function.

The HTTP protocol (version 1.1), for example, is specified in RFC2616 and the FTP protocol is specified in RFC959.

As specification go, the RFCs are, in my opinion, very well readable.

Title: How to write a HTTP server?

Body:
As the title says, I would like to write a HTTP server. My question is this, how do I do this? I know this sounds VERY general and too "high level", but there is a method to my madness. An answer to this question should be, I believe, language agnostic; meaning, no matter what language I use (e.g., C, C++, Java, etc.) the answer should be the same. I have a general idea of how this is supposed to work:

Open a socket on port 80.

Wait for a client to make a request.

Read the request (i.e., this person wants page "contact-us.html").

Find and read "contact-us.html".

Send an html header, then send the content of "contact-us.html"

Done

Like I said, I believe this is the process, but I am not 100% sure. This leads me to the heart of my question. How or where does a person find out this information?

What if I didn't want to write just an HTTP server, what if I wanted to write an FTP server, a chat server, an image viewer, etc.? How does a person find out the exact steps/process needed to create a working HTTP server?

A co-worker told me about the html header, so I would have NEVER know this without him. He also said something about handing off each request to a new thread. Is there some big book of how things work? Is there some manual of what it takes to be an HTTP server?

I tried googling "how does a HTTP server work", but the only answers I could find were geared towards your average Joe, and not towards a person wanting to program a HTTP server.


问:
Reason for placing function type and method name on different lines in C
I just started at a company and one of the style comments at my first code review was that the return type and method name should be on different lines. For example, this

```<code>void foo() {
}
</code>```

should be this

```<code>void
foo() {
}
</code>```

I've always used the first style, and I was wondering if there is any reason other than personal preference why people use the second style? I don't think the first one hurts readability at all. Is one more common than the other with C programmers and large open source projects?

答:
was wondering if there is any reason other than personal preference
  why people use the second style?

That's a style that was popular back in the early days of C, so the reason may just be that that's how they've done it for a very long time, they've got a lot of code that looks like that, and that's what everyone is used to. Not so much personal preference as corporate momentum.

Another reason is that function names always start in the first column. Return types vary in length and can be somewhat complex -- putting the type on its own line makes the function name easier to find.

If the company has a set style, they may also have a coding standards document. Ask for it. It may explain the reason(s) for this choice, and having a copy will help you avoid similar issues in future reviews.


问:
Can I use a LGPL licensed library for my web project
I am looking to use a javascript libray licensed under the LGPL license v3.

From what I have read so far, I understand that

If I do not make any modifications to the library, I can use the library without any restrictions.

But if I modify the library, I need to make the modified version available to the end users and also enable them to link the library dynamically.

Since I am using javascript, my code is anyways open to the end user. Also the user can dynamically link to library through the debug console.

So my question is, do I need to do anything explicitly since javascript is already open to users ?

Also, are there any other restrictions that apply which I may have missed out ?

Note: I found other answers that describe LGPL with respect to any application. But I am looking for an answer that describes how LGPL applies to javascript specifically.

答:
The status of GPL in combination with web-projects is a bit murky.

The basic principles of the LGPL are

People that you distribute a LGPL-library to must be given the possibility to obtain the source code of the exact version of the library that you distribute.

People that have obtained a copy of your program must have the possibility to use your program in combination with modified versions of the LGPL-libraries that your program uses

The problem with Javascript is that, to my knowledge, it is legally unclear if using a Javascript library in a (public) website counts as distribution of that library and if it does, if that implies that users must have the possibility to exercise their freedoms on that website (which would become very impractical).


答:
I first met this style on like 19th year working with C&C++. Was pretty much baffled on how could someone invent this evil thing.

The only (potentially) positive point I could find is that you can find the funciton definition using grep ^FuncName. Might be relevant factor decade+ ago in some real tool hating communities...  At the place I saw it was applied to C++ and class member funcitons, that kill even this attribute.

Guess my opinion. :)

Title: Reason for placing function type and method name on different lines in C

Body:
I just started at a company and one of the style comments at my first code review was that the return type and method name should be on different lines. For example, this

```<code>void foo() {
}
</code>```

should be this

```<code>void
foo() {
}
</code>```

I've always used the first style, and I was wondering if there is any reason other than personal preference why people use the second style? I don't think the first one hurts readability at all. Is one more common than the other with C programmers and large open source projects?


问:
Is it an appropriate use of #define to make typing repeated code easier?
Is there any view on whether using the #define to define full lines of code for simplifying coding is good or bad programming practice? For example, if I needed to print a bunch of words together, I'd get annoyed typing

```<code><< " " <<
</code>```

To insert a space between words in a cout statement. I could just do

```<code>#define pSpace << " " <<
</code>```

and type

```<code>cout << word1 pSpace word2 << endl;
</code>```

To me this neither adds or subtracts from the clarity of the code and makes typing slightly easier. There are other cases that I can think of where typing will be much easier, usually for debugging.

Any thoughts on this?

EDIT: Thanks for all the great answers! This question just came to me after doing a lot of repetitive typing, but I never thought there would be other, less confusing macros to use. For those who don't want to read all the answers, the best alternative is to use the macros of your IDE to reduce repetitive typing.

答:
No, you're not allowed to use macros to save typing.

However you are allowed, even required to use them to separate non-changing part of code from changing ones, and reduce redundancy.  For the latter you must think alternatives and pick macro only if better tools don't work. (For practice macro is quite at the end of the line, so having it implies last resort...)

To reduce typing most editors have macros, even intelligent code snippets.


问:
Gradual approaches to dependency injection
I'm working on making my classes unit-testable, using dependency injection. But some of these classes have a lot of clients, and I'm not ready to refactor all of them to start passing in the dependencies yet. So I'm trying to do it gradually; keeping the default dependencies for now, but allowing them to be overridden for testing.

One approach I'm conisdering is just moving all the "new" calls into their own methods, e.g.:

```<code>public MyObject createMyObject(args) {
  return new MyObject(args);
}
</code>```

Then in my unit tests, I can just subclass this class, and override the create functions, so they create fake objects instead.

Is this a good approach? Are there any disadvantages?

More generally, is it okay to have hard-coded dependencies, as long as you can replace them for testing? I know the preferred approach is to explicitly require them in the constructor, and I'd like to get there eventually. But I'm wondering if this is a good first step.

One disadvantage that just occurred to me: if you have real subclasses that you need to test, you can't reuse the test subclass you wrote for the parent class. You'll have to create a test subclass for each real subclass, and it will have to override same the create functions.

答:
When I am faced with this type of problem I will identify each dependency of my class-to-test and create a protected constructor that will allow me to pass them in. This is effectively the same as creating a setter for each, but I prefer declaring dependencies in my constructors so that I don't forget to instantiate them in the future.

So my new unit testable class will have 2 constructors:

```<code>public MyClass() {
  this(new Client1(), new Client2());
}

public MyClass(Client1 client1, Client2 client2) {
  this.client1 = client1;
  this.client2 = client2;
}
</code>```

Body:
When I am faced with this type of problem I will identify each dependency of my class-to-test and create a protected constructor that will allow me to pass them in. This is effectively the same as creating a setter for each, but I prefer declaring dependencies in my constructors so that I don't forget to instantiate them in the future.

So my new unit testable class will have 2 constructors:

public MyClass() {
  this(new Client1(), new Client2());
}

public MyClass(Client1 client1, Client2 client2) {
  this.client1 = client1;
  this.client2 = client2;
}


问:
Why was strict parsing not chosen for HTML?
I have often wondered why strict parsing was not chosen when creating HTML. For most of the Internet history, browsers have accepted any kind of markup and tried their best to parse it. The process degrades performance, permits people to write gibberish, and makes it difficult discontinue obsolete features.

Is there a specific reason why HTML is not strictly parsed?

答:
HTML authors and authoring tools produce crappy markup. Browsers do their best with it for competitive reasons: a browsers that fails to render most of web pages in any reasonable way will be rejected by users, who won’t care the least about whose fault it is.

It’s rather different from what programming language implementations do. Compilers and interpreters work on code that can be assumed to be written by a programmer, whereas everyone and his brother can write HTML with minimal training, or without. HTML markup is code, in a sense, but it’s data rather than programming language instructions, and the (good) tradition in software is to be tolerant with data.

XHTML in principle imposes strict (XML) parsing rules, so that an XHTML document served with an XML content type will be displayed only if it is well-formed in the XML sense – otherwise, only the first error is communicated to the user. This never became popular in web authoring – almost all of the “XHTML” around is served as text/html and processed as traditional tag soup in a very liberal way, just with some new eccentricities .


答:
Because making best guesses is the right thing to do, from a browser-maker's perspective. Consider the situation: ideally, the HTML you receive is completely correct and to spec. That's great. But the interesting part is what happens when the HTML is not correct; since we're dealing with input from a source that we have no influence on, really, we have to be prepared for this. Now when that happens, what could we do? We have two options: a) fail, and b) make a best effort to recover from the error. If we fail, the user has nothing but a useless error message, and there is nothing they can do about it, because they don't control the server. If we make a best effort, the user has at least what we could make of the page, and often the guess is mostly right.

The only real problem with this is when you need the error messages, which is typically in a development situation - you want to make sure the HTML you generate is correct, and since "works in browser X" is not equivalent to "correct", we can't simply run it through a browser and see if it works: we can't tell the difference between correct HTML and incorrect HTML that the browser has fixed for you. This is a solvable problem though; there are browser plugins that report standards violations, there's the W3C validator, and lots of other similar tools.

Title: Why was strict parsing not chosen for HTML?

Body:
I have often wondered why strict parsing was not chosen when creating HTML. For most of the Internet history, browsers have accepted any kind of markup and tried their best to parse it. The process degrades performance, permits people to write gibberish, and makes it difficult discontinue obsolete features.

Is there a specific reason why HTML is not strictly parsed?


问:
Versioning Javascript Files in a Web App
I am currently building a Web application using a LAMP stack that relies on Javascript on the front end. As the app grows and expands, I naturally plan to expand and change the javascript files. I'm concerned that many of our users' computers will cache the files (which I usually want) but I want to be proactive to make sure that new files are grabbed when I update.

The obvious answer seems to version the javascript files throughout the application so that edit.js become edit.0.3.6.js and can be updated whenever the file changes so a new version is downloaded.

I think that this is the most fail-proof method, but I question if there is an easy way to manage these versioning changes automatically. We use Github to version control all our files.

答:
Another way to version javascript, CSS and other such files (say background images), is to add a parameter on the URL that they link to - for example edit.js?ver=1.

When the version changes, you update the parameter - ver=2. This ensures that it will be re-fetched.

An added bonus is that you can easily search for ?ver= in your source code and possibly do a global replace.


问:
Should a software company have a dedicated team for research and/or utility libraries?
I work in a company that does web applications for various banks and some smaller e-shops
We employ about 20 developers and have 4-5 projects in development at any one time.
Our development teams don't interact much and a lot of the same problems are done in varied ways(good to bad).

I was wondering if it would be a good idea for a company to have a team of programmers that do research on current frameworks and continually improve a common library of functions and a common framework to build current and future projects much faster and more efficiently.

How large should a team like this be?

Also should it have permanent members that train others or should it rotate people?

Update: I was thinking about a common project that people can work on for fun that might spark some interest. It seems that when people have job pressures the solutions they come up with are not the best.

答: How much time are you going to spend on debating whether or not using the framework is going to be a benefit in all cases? Does a project get delayed by waiting for the framework to be upgraded? At some point the usage of the framework has to be required in order to justify its existence.</p>


答:
This is partially a historic remnant of the browser war

IE and netscape were competing to take over the market and kept releasing new features that kept becoming more and more "awesome", and were force to accept the pages designed for the other browser.

This means that browser accept and ignore unknown tags silently, after the committees started getting involved ... well you have a committee designing stuff and as a result a lot of different versions (with some ambiguously worded specs) where browser want to support most of them, and creating a separate parser for each version would be enormous bloat. So it is (relatively) easier to use a single parser with different modes.

For another part netscape and IE wanted html to be accessible for the common man (as was the fad those days) which means trying to do what the user wanted to be done instead of what he said to do and tripping over every dangling tag.

Making the problem worse is that there are also several "tutorial" sites teaching the wrong thing and thinking they are right because what they teach works.

Ultimately this means that if you now create a browser with only strict html parsing 99% of the sites out there will just not work.


问:
Which are the alternatives to using a stack to represent function call semantics?
We all know and love that function calls are usually implemented using the stack; there are frames, return addresses, parameters, the whole lot.

However, the stack is an implementation detail: calling conventions may do different things (i.e. x86 fastcall uses (some) registers, MIPS and followers use register windows, and so on) and optimizations can do even other things (inlining, frame pointer omission, tail-call optimization..).

Sure, the presence of convenient stack instruction on many machines (VMs like JVM and the CLR, but also real machines like x86 with their PUSH/POP etc.) make it convenient to use it for function calls, but in some cases it is possible to program in a way in which a call stack is not needed (I am thinking about Continuation Passing Style here, or Actors in a message passing system)

So, I was beginning to wonder: is it possible to implement function call semantics without a stack, or better, using a different data structure (a queue, perhaps, or an associative map?)

Of course, I understand that a stack is very convenient (there is a reason why it is ubiquitous) but I recently bumped into an implementation that made me wonder..

Do any of you know if it has ever been done in any language/machine/virtual machine, and if so which are the striking differences and shortcomings?

EDIT:
My gut feelings are that different sub-computation approaches can use different data structures.
For example, lambda calculus is not stack based (the idea of function application is captured by reductions) but I was looking at a real language/machine/example. That's why I am asking...

答:
The toy concatenative language XY uses a call-queue and a data stack for execution.

Every computation step simply involves dequing the next word to be executed and in the case of builtins, feeding it's internal function the data stack and call-queue as arguments, or with userdefs, pushing the words composing it to the front of the queue.

So if we have a function to double the top element:

```<code>; double dup + ;
// defines 'double' to be composed of 'dup' followed by '+'
// dup duplicates the top element of the data stack
// + pops the top two elements and push their sum
</code>```

Then the composing functions + and dup have the following stack/queue typ signatures:

```<code>// X is arbitraty stack, Y is arbitrary queue, ^ is concatenation
+      [X^a^b Y] -> [X^(a + b) Y]
dup    [X^a Y] -> [X^a^a Y]
</code>```

And paradoxically, double will look like this:

```<code>double [X Y] -> [X dup^+^Y]
</code>```

So in a sense, XY is stackless.

Body:
The toy concatenative language XY uses a call-queue and a data stack for execution.

Every computation step simply involves dequing the next word to be executed and in the case of builtins, feeding it's internal function the data stack and call-queue as arguments, or with userdefs, pushing the words composing it to the front of the queue.

So if we have a function to double the top element:

; double dup + ;
// defines 'double' to be composed of 'dup' followed by '+'
// dup duplicates the top element of the data stack
// + pops the top two elements and push their sum

Then the composing functions + and dup have the following stack/queue typ signatures:

// X is arbitraty stack, Y is arbitrary queue, ^ is concatenation
+      [X^a^b Y] -> [X^(a + b) Y]
dup    [X^a Y] -> [X^a^a Y]

And paradoxically, double will look like this:

double [X Y] -> [X dup^+^Y]

So in a sense, XY is stackless.


问:
Should I use webKit or is there a better technology to make a browser in Windows
I create web applications most in RoR and PHP. About a year ago a company wanted to use my app but in a stand alone browser window in Linux, so I wrote one in python using webkit, locked it down to just accessing the target web app, easily done.

Now what options do I have to do the same for Windows?

I want basic browser functionality such as going back and forward pages and to stop the script from loading. It will have to run stand alone or maybe install via .exe file. Sorry for my ignorance on this but I very rarely enter a Windows Environment.

答:
You have pretty much the same options, actually. WebKit is cross-platform, as are other browser engines.

Also, I'd think that quite a lot of general purpose mainstream programming languages would already provide a "WebView" component that should be good enough for most use cases.

For instance, Java has had this capability for quite a long while. Though I'd expect it wasn't rocket fast for the time and would scream for its mommy with the amount of JS that's now present in most web-apps; but surely that must have improved as well over time.

Android has such a WebView, that pretty much allows to invoke the Android Browser (not sure what happens now that newer versions have switched to Chrome for Android, actually; I don't know if that view now relies on a stripped view of the legacy browser or or the mobile Chrome one).

.NET has a similar capability to invoke the same components as the ones used by IE.

And so on.

But if your thing is done with Python and WebKit and some graphic toolkit, I'd be surprised if you can't get it to run on Windows as well.


问:
Which Open Source License to choose for an ASP.NET MVC 3 OpenId StarterKit?
I've built a ASP.NET MVC 3 (RC at the moment) site that uses OpenID login system. I was still learning about OpenID while implementing this so I commented the code heavily. The result is a site that let's users login/register with OpenID, add other OpenIDs to their account and also remove them. This little project can be then used as a starting point for any new project that would use OpenID login system. It can also be used as a resource for people to learn OpenID with.

I decided to release this project as open source. This will be my first open source project and I need to decided what license to use. I want people to be able to use this for any purpose they wish for. They can learn from it, use it for commercial or non-commercial projects and make their own forks of the code. It would also be nice for others to be able to contribute back to the project with stuff like bug fixes on sites like GitHub. But I'd like to be the copyright owner of the code that is under my control. For example the code that is in my GitHub repository (I'll call this the main code base). I've heard that for this I need to get every contributor, that adds code to this code base, to give me the copyright for their contribution. How exactly does this work?

I also use other licensed (mostly open source) resources in my projects. Here's their list and their licenses:

DotNetOpenAuth (Ms-PL)

T4MVC (part of MvcContrib which is licesned using Apache License 2.0)

ASP.NET MVC (Ms-PL)

ADO.NET Entity Framework CTP4 (I couldn't find a license)

I of course want to use the main code base for any type of projects I want. Commercial, non-commercial, open source, ...

So I have some very important questions here:

Which license should I use? I think GPL or LGPL is not suitable here. I was looking at Apache 2, New BSD, MIT and Ms-PL. Ms-PL seems to be a good fit as, but I'm not sure.

What restrictions and/or obligations do I have towards the resources I use in this project? I think I read somewhere that I have to add -LICENSE.txt for Ms-PL resources. Is that true? How does this work for Apache 2 and other licenses? What do I have to do if I modify any of these resources' code and then use that in my project?

I'd also really like a "as-is" clause in the license, so people can't sue me if something goes wrong while they're using my code.

Do I need to add anything to my files to make clear what the license is? If so, how do I format that?

Also one last thing. If I decide to make a Visual Studio template out of this samples how do I license that?

答:
Since you're using MS-PL and Apache 2.0 components, you're restricted by the MS-PL license and the Apache 2.0 license.  This means you can't use the GPL anyway, since it's incompatible with MS-PL, and version 2 of the GPL is also incompatible with Apache 2.0.  Given that, I would suggest releasing your parts either under MS-PL, Apache 2.0, or a BSD-style, so you're not adding requirements.

You can read the licenses to see what you have to do.  They aren't long.  With MS-PL, you can do pretty much everything as long as everything's released under MS-PL and you include the entire license (which isn't long).  With Apache 2.0, it's pretty much the same, except that you need to include any NOTICE file.  You do have to include all attributions, etc., and that's pretty standard across OS licenses.

You really can't add to the licenses.  You are free to put any disclaimers you want.  You can put them in a NOTICE file, which under Apache 2.0 requires them to be preserved.

You should list which files are under which licenses, and you do have to include full copies of MS-PL and Apache 2.0 in the package.

Be careful about ADO.NET Entity Framework CTP4, as you say you can't find a license.  If you can't find a license, ordinary copyright law applies, and you can't legally use it.  You may want to write to whoever owns that code, and see what license they use.

As far as copyright ownership goes, you can never retract open source licenses for the versions you release under them, but if you own all applicable copyrights you can relicense as you wish.  Some companies, like MySQL AB, released what they had under the GPL, and would sell other licenses for money, so that (say) another company could use MySQL as a part of their commercially sold product without having to release under the GPL.

Since you're using components owned by other people, you really can't do that with the entire project, but you could with your portions.

To do that, you'd have to get everybody who contributes to fill out a copyright assignment form, along with some proof that they do own the copyright (and, for example, that it doesn't count as work for hire for an employer).  This does tend to diminish user contributions, so you may want to skip it entirely.  You might want to look at what the Gnu project does, since they do want complete copyright, and emulate them.


问:
How does the operating system regain control when multitasking?
I get how multiple processes can run on a single core by interleaving the processing. What I don't understand is how the operating system ensures that the program releases the processor after a certain amount of time. If only one program can run at a time, and the os allows a process to run, what's to prevent that process from never giving the processor back?</p>

答: interrupt from a outside clock with the timeout set at the start of a process' timeslot, which immediately goes back to the OS</p>


答: As @rachet_freak says, there are hardware timers that fire interrupts that can switch execution to the kernel when your processes' timeslice is up. In addition, whenever you call an OS service, say allocating memory, reading from the keyboard, writing to a disk, etc. the OS code can decide that your process needs to wait, and activate another process.</p>

Title: How does the operating system regain control when multitasking?

Body: I get how multiple processes can run on a single core by interleaving the processing. What I don't understand is how the operating system ensures that the program releases the processor after a certain amount of time. If only one program can run at a time, and the os allows a process to run, what's to prevent that process from never giving the processor back?</p>


问:
What source control do I need for a large project in an average company?
I know Git is great for open source projects. But I was wondering: for a company with 20 programmers working on a 1 year project, which source control system is desirable? From what I heard Git uses pulling; wouldn't it be less than desirable to need to go through someone else to get your changes in the main trunk? Especially when everyone is working at the same time?

That's just of an example I was wondering about. I know how to use SVN but even at my last job we didn't use it on our projects, since everything was done in PHP and those were typically standalone 1 week projects. I just had SVN for my local code and didn't need to use it with others.

So what are good source controls, and specifically why is it good for this?

答: Use whatever your team is comfortable with. All Version Control systems do roughly the same thing in similar ways; there's no reason to re-invent the wheel because "it might work better". If your team isn't comfortable with anything, then pick the option that has the easiest integration with your team's standard IDE.</p>


问:
Why do javascript implementations parse numbers this way?
According to the ECMAScript spec the integer part of a decimal number should be either zero or start with a non-zero digit. A hexadecimal value should start with 0x.

Javascript, in the major browsers, extends EMCAScript to include octal numbers. These are determined by having a sequence of digits (from 0 to 7 inclusive) start with a zero.

Given these facts, my naive implementation of a javascript interpreter would probably parse integers a bit like this:

```<code>if first_char in [1-9] then
    parse_input_as_decimal()
else if first_char is 0 then
    if second_char is 'x' then
        parse_input_as_hexadecimal()
    else if second_char in [1-7] then
        parse_input_as_octal()
    else
        parse_input_as_zero()
</code>```

However the web browsers seem to act slightly weird in that if a number beginning with zero contains the digits 8 or 9 then it reads it as a valid decimal. This can lead to oddities, especially when using a decimal point or exponent. Some examples:

```<code>011 // is octal
0011 // is octal
019 // is decimal
0091 // is decimal
011.0 // throws an error
019.0 // is decimal
011e5 // throws an error
019e5 // is decimal
</code>```

My question is why do they behave like this? Is it just some quirk of history? Or is there a good reason? Is it written in some spec somewhere? Will this ever change?

I know this is a bit arcane and few people use octals in javascript these days, but I'm curious.

答: Quirk:'strict mode' gets rid of this behavior, I think it was a non standard behavior that a couple browsers implemented but I'm not 100% (about it being non-standard, I am sure about it being removed from strict JavaScript)</p>


问:
Can you close branches in Git?
In Mercurial you can close a branch like this: hg commit --close-branch, this means the the branch will not be listed anymore but will still exist, and can still be listed if you use hg branches --closed

I have learned that in Git generally branches are not kept, they disappear, specially when doing fast-forward merges.

So my question is: can you keep branches in git but in a way that you don't list them anymore?

Edit: Some additional context: In Mercurial branches are metadata, so each commit always knows it's branch. In Mercurial if you want to delete a branch, you strip the base branch revision. You can also rebase and end up with the same result as with Git. Mercurial Bookmarks are pointers, so they have the exact same behavior than a Git Branch.

答:
If you just want to merge a branch while still keeping a record of it's existence, you could always tell git not to fast-forward the merge using git merge --no-ff this will create a new commit with two parents, and a commit message along the lines of "Merged [branch_name] into master"

Since git allows you to check out any commit and make a branch from it, you could always look for the merge commit and re-create the branch if you need it. As others have stated, using git tag can make finding these easier.

If you're not merging the branch, then you need to get more creative. MY first idea would be to add a new remote called archive, and push the branches you're tired at looking at into it.

```<code>$ git init --bare ../archive.git
$ git remote add archive ../archive.git
$ git push archive feature_branch
$ git branch -D feature_branch
$ git branch -r
    origin/master
    archive/feature_branch
</code>```

this thread suggests using git update-ref to move the branch somewhere git won't look for it, but that's messing a bit too much with the git internals for my liking.

Title: Can you close branches in Git?

Body:
If you just want to merge a branch while still keeping a record of it's existence, you could always tell git not to fast-forward the merge using git merge --no-ff this will create a new commit with two parents, and a commit message along the lines of "Merged [branch_name] into master"

Since git allows you to check out any commit and make a branch from it, you could always look for the merge commit and re-create the branch if you need it. As others have stated, using git tag can make finding these easier.

If you're not merging the branch, then you need to get more creative. MY first idea would be to add a new remote called archive, and push the branches you're tired at looking at into it.

$ git init --bare ../archive.git
$ git remote add archive ../archive.git
$ git push archive feature_branch
$ git branch -D feature_branch
$ git branch -r
    origin/master
    archive/feature_branch

this thread suggests using git update-ref to move the branch somewhere git won't look for it, but that's messing a bit too much with the git internals for my liking.


答:
In general, the approaches can be classified (conceptually) into two types:

Preemptive multi-tasking.

Cooperative multi-tasking.

The details for both can be found in the question which Charles E. Grant has commented on your question.

There is a further classification under cooperative multi-tasking:

The applications needs to periodically call back an OS function, to allow the OS to perform its work, without benefit to the application itself. Typically this is termed  yielding.

The application may request some services from the OS by making an OS call, such as opening/reading/writing a chunk of a file, or reading from a port or network. The OS could take this opportunity to perform additional work of its own.


答: The reason is simple: At the time of the first graphical browsers, NCSA Mosiac and later Netscape Navigator, almost all HTML was written by hand.  The browser authors (Netscape was built by ex-Mosaic folks) recognized quickly that refusing to render incorrect HTML would be held against them by the users, and voila!


问:
DDD and filtering
I am developing an app in ddd maner. So I have a complex domain model. Suppose I have a Fare object and Airline. Each Airline should contain several or much more Fares.

My UI should represent Model (only small part of complex model) as a list of Airline, when the user select the Airline, I must show the list of Fares. User can filtering the Fares (by travel time, cost, etc.).

What is the appropriate place for filtering Fares and Airlines?

I am assuming that I should do it in ViewModel. Like: My domain model has wrapped with Service Layer -> UI works with ViewModel -> ViewModel obtain data from Service Layer filtering it and create DTO objects for UI. Or I'm wrong?

答:
If there is a substantial amount of data to filter, then consider passing the "filter" query up through the stack so that it is a database query. This will minimize the amount of data passing between your database (assuming you have one) and your code.

On the other hand, if you need to filter data that are already in memory, and your code is all in a single process, then you can do so at any point: you are only passing pointers after all. But if you are considering refactoring your service layer into an actual service, running separately from the UI code, then you want the filtering to be in the service layer so that you can again minimize the data traffic between layer boundaries.

Title: DDD and filtering


问:
How do you dive into large code bases?
What tools and techniques do you use for exploring and learning an unknown code base?

I am thinking of tools like grep, ctags, unit-tests, functional test, class-diagram generators, call graphs, code metrics like sloccount, and so on. I'd be interested in your experiences, the helpers you used or wrote yourself and the size of the code base with which you worked.

I realize that becoming acquainted with a code base is a process that happens over time, and familiarity can mean anything from "I'm able to summarize the code" to "I can refactor and shrink it to 30% of the size". But how to even begin?

答:
I wrote a fairly lengthy post on this topic. Here is an excerpt

I thought about this problem for a quite while. I decided to write up my own personal solution as a general process. The steps I have documented are as follows:

Create Vocabulary Sheet

Learn the Application

Browse Available Documentation

Make Assumptions

Locate Third Party Libraries

Analyze Code

This process is written in the context of a large desktop application, but the general techniques are still applicable to web applications, and smaller modules.

taken from: A Process For Learning A New Codebase

Title: How do you dive into large code bases?


问:
Prototyping vs. Clean Code at the early stages
I'm planning to work/start on a few personal projects that could end up as my daily job. It made me think, which way should I start?

Just prototype—write just working basic code that could cost me tons of time optimizing and refactoring for easy expansion.

Write clean, optimized and documented code from the very beginning, keeping in mind that if after some time it won't be cost-effective, it will be dropped.

Update: Combining YAGNI with sunpech and M.Sameer answers makes perfect sense to me :) thank you everyone for help.

答:
Both are good. Both I like. They don't contradict each other.

I like to prototype. Prototyping is developing my creativity skills. I'm testing many possible solutions. Doing it quick gives me a possibility to test a lot of possible ways to solve problem.

I like to write clean, good tested code. It develops my core skills. I usually choose one of the prototypes, and either improve it, or rewrite from scratch.

But you should never mistake the prototype from the production code. Prototype should never go into production. It should be always marked as prototype. At best do all prototyping in your own branch.


问:
Over thinking development
I've been working as an app developer for a year and a half now (not long I know), and I've just been given my first big project.

Needless to say it didn't go very smoothly, so I sought advice from a senior programmer involved in the project about how to approach it.

He said that I had drastically been over thinking the task at hand, and that because I had never tackled a project of this scale before I'd been spending too much time over thinking design patterns. In his wise words, he told me "F*ck the future, build for now".

Is this a trend programmers typically follow when going about a project like this? For example, if you were asked to do a proof of concept model, is it a typical trend just to mash a workable example out as soon as possible?

Edit: In light of the debate this has sparked, I'd like to mention that this situation is fairly extreme: we have very tight deadlines due to factors beyond our control (i.e. the market we're aiming for will lose interest if we don't show them something) and his advice proved to be very effective for this particular task.

答:
Show me your code and I will tell you who you are

Your code is your visit card. If you write messy code, what tell you about yourself to the other people? Just think of that. Every time we find in office a really bad fragment of code, we ask ourselves, who have written it and how on hell was he passed through the university?

You are becoming what you code

Your code is your program for life.

A programmer writing bad code is like a ballet dancer dancing in striptease club

Some people don't care dancing in striptease club. But if they are tallented dancers, they are wasting their skills. If you are poor dancer but have nice legs, you can strip for many.

Finally, you should read Gogol's novelle 'The Portrait', and you should be warned by the story of the main character. You friend is similar to the man from the portrait. He is luring you with money, but you'll pay the high price for it.

Title: Over thinking development


问:
Should I use different projects for building different layers in a 3-layer model?
I am creating a new project from scratch and have decided to use a 3-layer model.

I am using:

the 1st layer for business entities,

the 2nd layer for business logic,

and the 3rd layer for data logic layer.

Do I need to create different projects for these different layers or do I need to create different folders in one project?

What are the pros and cons of both approaches?

答:
I would most definitely create 3 separate projects for each layer you hope to create.
By using separate projects it makes your solution much more discoverable and maintainable.

To read a bit more on when to divide up projects see this answer

In the solution that you create you can make solution folders that nicely segregate the projects into more manageable areas.

You can have solution folders that are named after each layer you want to create.

Business Entity

Business Logic

Data Logic Layer


答: A colleague of mine enthusiastically endorses repeated prototyping, with the caveat that one must have enough discipline to throw each prototype away and write again from scratch - and not only that, ensure that one isn't influenced by the implementation details decided on last time round, as what one then ends up doing is writing the same prototype in a trivially different style several times. He semi-seriously suggested that if you were really attached to some brilliant piece of code that you couldn't possibly discard, that you should print it out, delete the source control repository, and post the printout to yourself - it'll be gone long enough that it can't infiltrate the next iteration.

Title: Prototyping vs. Clean Code at the early stages

Body:
I'm planning to work/start on a few personal projects that could end up as my daily job. It made me think, which way should I start?

Just prototype—write just working basic code that could cost me tons of time optimizing and refactoring for easy expansion.

Write clean, optimized and documented code from the very beginning, keeping in mind that if after some time it won't be cost-effective, it will be dropped.

Update: Combining YAGNI with sunpech and M.Sameer answers makes perfect sense to me :) thank you everyone for help.


答:
It's generally a good idea to separate the aspects of your product in separate components and extract them to independent modules as much as possible (or projects, if you want).

However, it's not necessarily as easy to do in all languages, as the level of tooling at hand may vary greatly and a lower-tech solution might be a good compromise between a decent design and pulling your hait out for hours to make your build comply to an ideal architecture.

Considering your added the C# tag, which I left as I think that helps to assume the tooling you have, though it really isn't relevant to the language, I'd indeed recommended to separate your project in 3 projects as part of a single solution.

Title: Should I use different projects for building different layers in a 3-layer model?

Body:
I am creating a new project from scratch and have decided to use a 3-layer model.

I am using:

the 1st layer for business entities,

the 2nd layer for business logic,

and the 3rd layer for data logic layer.

Do I need to create different projects for these different layers or do I need to create different folders in one project?

What are the pros and cons of both approaches?


问:
Testing From A Developer's Perspective
I have a book which mentions:

"There are many types of testing, including unit testing, integration testing, functional testing, system testing, performance testing, and acceptance testing".

It is often noted that many developers carry out unit-testing only, or no testing at all. From the types of testing above, which ones are to be conducted by the developer? What are the responsibilities of a developer when it comes to testing?

答:
All Languages Support All Kinds of Testing

The way you formulated your original question, I think you were approaching testing the wrong way and make too big a distinction between kinds of progammers and their roles, and making assumptions on the link between a language and the testing taught.

All languages allow for all kinds of testing. They may have built a more in-grained culture around testing, and may provide more tooling, and have some language features that facilitate it. And it's true that if you were to conduct a literature review, mainstream books about testing may have been appearing around Java's introduction and rise to fame, and relying on it to illustrate their points.

But all languages allow for testing of all kinds.

What's Your Responsibility?

So, now, to try to answer your original questions:

What other testing does a Java Developer do from a Java Developer's Perspective?

and

As I have already mentioned every Java Developer carrys out Unit Testing.
  From the 1's I have described above, which 1's are done from a Java Developer's Perspective?

All the ones you've listed afterwards in your answer:

Unit Test

Integration Testing

Regression Testing

Performance Testing

...

Of course, depending on your company some of the tests may not necessarly need to be performed by you. For instance, accpetance testing or performance testing are quite often left to other teams.

Plus, some testing may be done as "black-box testing", in which case it may even be best than you don't know the internals (or you may not have a choice to know at all), and in that situation it is of course less relevant for the original developers to be part of that testing effort. But they can still add their input, and they are likely to approach the problem in ways others may not have thought of.

However, I'd strongly recommend that developers, of any kind, participate in all testing efforts themselves or by directly working with whoever performs the testing in close-knit relationship.

It's a Matter of Culture/Philosophy, not of Technology

Most of the times, software shops host separate testing and development teams do it for the wrong reasons, or because they are kind of pushed into it (or feel lile they're pushed into it) by the development lifecycle and their methodology.

It's not a fatality and can be changed.

Also, some testing can sometimes be done on top of existing efforts by non-developers. It's best to even advise your clients to perform their own acceptance testing and performance to validate your results. And you definitely should press them hard to get involved in that, so you can make sure they know what they want, and that you know what they will expect from your deliverables!

A final note: testing is only relevant if you know what to test and how to interpret the metrics and results they deliver.

Title: Testing From A Developer's Perspective