答:
It depends on what code   is in the include file.

Did you try putting the #include for <stdio.h> inside main()? Depending on how the standard library is implemented on your system it may not even compile. Header files can contain not only function declarations, but function definitions. Standard C doesn't support nested functions.

If your header file contains function and variable declarations, putting them inside the body of main() limits their scope.

If the header file only contains preprocessor macros it might work, but you'll annoy all other C programmers by gratuitously moving the include somewhere unexpected. Coding standards are particularly important in C because C has so few safeguards to keep you from screwing up.

Title: Is it bad to place "include directive" within main function?

Body:
It is always said that the include directives should be placed at the beginning of a script. The main reason is to make the functions available throughout the script. Regardless of this fact, is it bad to place an include directive within the main function where it is needed?

For example,

```<code>#include <stdio.h>
int main() {
#include <mysql.h>
}
</code>```

Instead of

```<code>#include <mysql.h>
#include <stdio.h>
int main() {
}
</code>```

I was unable to find any different in performance or compiled file size, but it is difficult to judge about this fact based on simple scripts. I wonder if it has any effect or drawback, or any reason to avoid this non-standard approach.


问:
Is it bad to place "include directive" within main function?
It is always said that the include directives should be placed at the beginning of a script. The main reason is to make the functions available throughout the script. Regardless of this fact, is it bad to place an include directive within the main function where it is needed?

For example,

```<code>#include <stdio.h>
int main() {
#include <mysql.h>
}
</code>```

Instead of

```<code>#include <mysql.h>
#include <stdio.h>
int main() {
}
</code>```

I was unable to find any different in performance or compiled file size, but it is difficult to judge about this fact based on simple scripts. I wonder if it has any effect or drawback, or any reason to avoid this non-standard approach.

答:
Its really very very bad!

The reason is that many C header files include lot of macro stuff like:--

```<code> #if !defined(MYSTUFF_INCLUDED)          /* File not yet included? */
   #define MYSTUFF_INCLUDED                /* Show file now included */
   int variable1;
   int variable2;
 #endif
</code>```

macro variables have a "file" scope whereas any variables defined within will have function scope if you include the "#INCLUDE" within a function.

So

```<code>    #include <stdio.h>
    int main() {
        #include <mysql.h>
        call doSql();
     }
     int doSql () {
        #include <mysql.h>
        .....
     }
</code>```

Will not compile as the macro variable MYSQL is already defined and the second INCLUDE will not define anything.

ContentLicense: CC BY-SA 3.0

Body:
Its really very very bad!

The reason is that many C header files include lot of macro stuff like:--

 #if !defined(MYSTUFF_INCLUDED)          /* File not yet included? */
   #define MYSTUFF_INCLUDED                /* Show file now included */
   int variable1;
   int variable2;
 #endif

macro variables have a "file" scope whereas any variables defined within will have function scope if you include the "#INCLUDE" within a function.

So

    #include <stdio.h>
    int main() {
        #include <mysql.h>
        call doSql();
     }
     int doSql () {
        #include <mysql.h>
        .....
     }

Will not compile as the macro variable MYSQL is already defined and the second INCLUDE will not define anything.


问:
session persisting problem after system restart
Is there a way to prevent session id restore on startup/restart of user's system?

We are using a asp.net app and I am able to login and access the site. For the first time session id is created and stored in cookies.

Problem:

But if I restart my system without signing out, the session is still alive.

How can I prevent this? from server side.

I can try to delete cookies but it is not practical, as each user will have different preferences.

答:
I assume we are talking about a web application over HTTP, which is stateless by nature. I'm not sure this is doable. How would a server know that your client has restarted?

Alternative is to make session time-out really short (1 minute) and refresh it every 30 seconds through AJAX calls.


问:
What do I call people who extend my class in base class documentation?
Been calling them "implementers", but it seems weird to me.

```<code>/// <summary>
/// Implementers should implement this.  Derp
/// </summary>
protected abstract void InternalExecute();
</code>```

A point of clarification, I'm interested in what to call the people who create child classes, not the child classes themselves.

"Hey, you there" not "that thing there."

答:
I usually say children, child classes or inheritors.

Its not that important; people are going to understand what you mean by Implementers anyway.

ContentLicense: CC BY-SA 2.5


问:
How do I implement code obfuscation for native code?
I'm interested in doing code obfuscation (native code, to make it clear what I mean by "native code": the actual machine code in x86/x64/arm executable files - PE, ELF, Macho and etc, not the sources) as a part of a build process. I can think of several ways of doing it:

Writing a compiler plugin, that would get internal representation after all optimization phases, transform it and then send it to compiler's back-end. In this case, could you advise me some compilers that support plugins like that? Programming language doesn't really matter, but I would like to try out something other than C/C++ (I know that both GCC and Clang support plugins, but I could never get it working properly on Windows).

Dump internal representation after all optimization phases to file, parse and process it with my obfuscation tool and pass it back to the compiler. I couldn't find how to do it with GCC (I successfully dumped different internal representations, but I couldn't find how to make compiler generate code from it). And I know that Clang is able to generate LLVM bitcode, that can be processed and compiled with LLVM compiler, but again I couldn't make it work properly on Windows. Do you know any compiler that allows doing such things?

Currently I'm doing obfuscation by preprocessing sources, it works, but it takes too long to do it for a large code base. So I'm looking for alternative ways of doing it, and I want to read your opinions on what is the best way to do native code obfuscation.

PS Please bear in mind that I'm asking a concrete question. I'm not asking whether I need obfuscation on not. Obfuscation is done for a reason and I have a reason to do it. I'm not asking how to perform actual native code obfuscation or about algorithms of code obfuscation. I know how to do it and how to break it.

I'm asking about native code compilers that either have good support for plugins or can dump and recompile some low level internal representation like AST (abstract syntax tree), RTL (register transfer language), three-address code or something else.

答:
You seem to be confused.

Code obfuscation is a (weak) method of protecting your source code from being understood by others if they get their hands on it. It can be a superficial barrier to amateur when variable names, formatting etc. are distorted to be "unreadable", but the attackers you should worry about - hackers and crackers - aren't fazed by such cosmetic changes. They will just normalize the code automatically and read it with little difficulty.

Obfuscating native code makes even less sense. There are only so many ways you can add two numbers, and if your program needs additions, it will have to use one of them. Assembler code is never printed in anything but normalized one-op-per-line format, and it rarely uses long, meaningful identifiers in the first place. In other words, obfuscated native code looks just like normal native code. (And yes, professional software thieves can read machine code like they read the newspaper.) While it is possible to make the actual operations performed by the program more obscure and needlessly complicated, this carries a heavy risk of introducing errors and inefficiency. Is this really worth the perceived additional safety against code thieves?

In short, I suggest you reconsider what exactly your threat model is and what measures make sense to defend yourself.


问:
How to assure users that website and passwords are secure
On reliable websites I always see claims such as "All data is encrypted" or "All passwords are encrypted using 128bit encryption" and etc. However I have never come across a claim such as "All passwords are hashed."

On my website, I will be storing all user passwords in a database after using SHA-512 (most likely) hashing with a random salt. I want to add a snipet assuring users that their passwords are secure so they will not be deterred from using my website because it requires a password. I want users to feel secure but I do not think everyone knows what hashing is.

MY QUESTION:
Is it okay to provide a message saying that "All passwords are encrypted and secure" since I do not think that the average user will know what the difference between hashing and encryption is, and will more likely feel secure just because they see the comfort word "encryption"? Or is there an alternative message I should provide?

On a side note, I am new to encryption and password hashing and I was wondering if this would be safe enough for now as I launch my site. I do not want to tell users it is secure if it is not. Any information would be greatly appreciated. Thanks.

答:
It really depends on the context of your specific website.

For example, if this is a consumer website, odds are that most of them will only care about their passwords (maybe), financial/health information (depending), and their private information such as pictures (hahaha, yeah right...).

If this is a business application, then the level of security of the entire site is relevant, not just passwords. Likewise, it depends on who your target users are - highly technical / not so technical, etc.

All this context greatly defines what you should be communicating, and what level of assurance is required.

For example, for non-technical consumers, it is sufficient to have some generic, simple comments, such as:

This site is built using state-of-the-art security techniques. Your password is always encrypted, and we will never ever send your pictures to the NSA.

(And, as others have said, you are better off not even having passwords at all, use some standard like OpenId or OAuth.)

For highly technical businesses, you would want to have a full page of technical and procedural details, such as:

We have implemented a full SDL (secure development lifecycle) throughout our development and deployment process.

  ...

  Our security architecture is ... This gives the benefits of...

  We ensure secure coding such as ... by... We perform these and those tests.

  Our cryptography includes these algorithms... and ...
  We are compliant with whichever industry regulation you need, and certified for...

  Our security is verified by this independent 3rd party consultant.

  ...

  For more details, and to review our policies or to arrange an independent audit, please discuss with the marketing department.

Of course, you don't want to be giving away too much detailed information, it should be more about the process than the passwords themselves... And of course it should go without saying that the reality should actually comply with whatever you write there, whichever context you are dealing with.

As one of the answers alluded to, most users don't care, wouldn't understand whatever you tell them, and would still sign up anyway, even if you say that you DO send user data to the NSA.

This is not for them.

They would be just as happy not having any passwords, just let me pick my username from the list and log me in automatically.

Obviously this is for the small percentage that care - you should be enabling the smart users to do what's right, to give them the information they need, and grant them the education they might ask for.

If you don't, when that goes wrong, the other 98% will suddenly wake up and get angry.

("Sure, I knew that I don't need a password to see my pictures, but I didnt think that anybody else could also see them!!")


问:
Can I remove all-caps and shorten the disclaimer on my License?
I am using the MIT License for a particular piece of code. Now, this license has a big disclaimer in all-caps:

```<code>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF...
...
</code>```

I've seen a normally capitalised disclaimer on the zlib license (notice that it is above the license text), and even software with no disclaimer at all (which implies, i take it, that there is indeed a guarantee?), but i'd like some sourced advice by a trusted party. I just haven't found any.

GNU's License notice for other files comes with this disclaimer:

This file is offered as-is,
  without any warranty.

Short and simple.

My question therefore: Are there any trusted sources indicating that a short rather than long, and a normally spelled rather than capitalised disclaimer (or even one or the other) are safely usable in all of the jurisdictions I should be concerned with?

For the purposes of this question, the software is released in the European Union, should it make any difference.

答:
The disclaimer is there to protect you as the original author. Otherwise there might be implied warranties by law you would need to fulfill when passing along the software work.

As you can imagine in technical systems, this can be complex and that is why you really want to exclude the warranty. This is also what entry-level or more advanced literature on the topic suggests.

As society increasingly relies on software to perform critical functions in everything from manufacturing to life support systems, the risk that an error in a software program will lead to economic loss, property damage, or personal injury increases. Prudent software developers will be cognizant of these risks and will take steps to minimize their exposure to this type of liability. Determining how far a software developer should go in this effort requires balancing the degree of exposure to software product liability against the adverse impact, if any, of the steps required to limit this exposure on the software vendor's ability to market and sell its software.

(from: IV. Conclusion - Software Product Liability: Understanding And Minimizing The Risks (By Lawrence B. Levy and Suzanne Y. Bell) )

As you are probably giving your software away under very liberal free software terms, you better consult a lawyer before changing an established and widely accepted license text (yes that can do a difference and if I read @Tim Posts Lawyers feedback right, this is also what his lawyer meant. You can find that as well within comments/publications by other lawyers also especially about free software licenses).

However, this disclaimer is no carte-blanche for everything. In Germany for example you couldn't reduce liability by such a warranty disclaimer easily by just adding it below the terms.

Because full warranty for a software as required by law would have put too many liabilities on the original author - who actually most often doesn't earn a cent - this has been better clarified for Free Software as there are now some sentences in German law to make this more clear (and to allow warranty disclaiming to a certain degree). This didn't put the world as we knew it before topside-down, but just saying that things aren't as easy as they seem on first sight and in a critical area it's perhaps better to stay with a critical mass of users of the same terms to effectively fight back in case it's necessary.

You can find these kind of implications also in the terms of the GPL 3 which is a modern license with international use in mind:

Sections 15. is a Disclaimer of Warranty and 16. is a Limitation of Liability:

17. Interpretation of Sections 15 and 16.

If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.

(from: GNU General Public License - Version 3, 29 June 2007 )

This is only possible if you stick to the accepted practices which includes not to change the accepted Free Software license texts including the warranty disclaimers beneath them for (more or less) personal reason.

However, the MIT license text you relate to in your question does not have a requirement to retain the warranty disclaimer.

Which probably can make sense because in some cases of contracting a licensing of the software or a work based on it might require you to remove this really broad disclaimer and negotiate more precise terms here.

However it's perhaps not a good idea to remove it because of that, the OSI FAQ has the topic of different warranty as well (not specifically, see below) and the wording suggests a warranty sold separately which probably makes indeed much more sense:

Some companies may sell you a warranty separately, for a fee, but that is not part of the open source license, it's just your private contract with that company.

(from: Can I restrict how people use an Open Source licensed program? - OSI FAQ )

So changing and removing it does not seem to be permitted and it does not look like you would loose any rights of re-use, however what you actually do here is to destroy the text and offer warranty for too many users as you are actually willing to care about.

Further text-analysis by others might not easily identify the original license this was obtained from adding one more step/point to follow over while clarifying the license of a work (for a third-party using that work). Then other users might be puzzled and what not. Therefore keep this transparent is the best suggestion I can give.

And do that for a reason. Just formatting purposes because it does not please your taste? Well, it's a free world so you can do whatever you want, but this is also for giving something to others so keep in mind that this can make others live a bit more complicated. Just decide what is important for you and which risks you are willing to take.

And if you have legal questions, well, better ask somebody who is able to answer those to you in a legally binding manner (not saying that lawyers will do always, but chances are higher you will be more educated later on from the legal viewpoint :)). But I guess you know the deal.

IANA/YLJASD


问:
How do you stay focused at work?
Sometimes, the things I have to do for my job are interesting and engaging.  Sometimes, they aren't.  Occasionally, they really aren't.

Do you have any particular strategies or tricks for dealing with those dull stretches when your brain would rather be doing anything other than what you're supposed to be doing, particularly when the Internet and its boundless opportunities for interesting Slack beckon?

答: I find that getting up from my desk for a short walk (2-4 minutes every hour or so) clears my mind and lets me get back in the groove. Note that this needs to be scheduled and disciplined, otherwise it becomes mere avoidance and anything boring or difficult will result in me wandering aimlessly for a bit and not getting anything done.</p>

Title: How do you stay focused at work?


问:
Should one write Big Oh complexity in the documentation of algorithms?
When writing or using an algorithm, should the Big Oh complexity be mentioned?</p>

答:
If you can back it up with real analysis, then yes, absolutely.

@Casebash test != analysis.  If it should always be documented then just start throwing

 // this algorithm is O(n!)
on every function.

I've worked with people who would say things like 'This function is O(1) because there are no loops', and then I would point to the call $(someHugeList).each(function(//...


答: subclasses or classes that extend ThisInterfaceor classes that implement InternalExecute

Title: What do I call people who extend my class in base class documentation?

Body:
Been calling them "implementers", but it seems weird to me.

```<code>/// <summary>
/// Implementers should implement this.  Derp
/// </summary>
protected abstract void InternalExecute();
</code>```

A point of clarification, I'm interested in what to call the people who create child classes, not the child classes themselves.

"Hey, you there" not "that thing there."


答:
Consider the possible things that may be found in a header file.

Preprocessor macros. These will be available from the #include until the end of the .c file that includes the header. Preprocessor macros are not concerned about C block scope (braces), so even though the header is inside a function, the macros will still be available after the end of the block.

Declarations of types, variables and functions. Their scope will be the block where the #include directive is located. That's usually fine. However, it works only once. Almost all include files contain header guards, so that if the file is included more than once (which often happens due to headers requiring other headers) its content is only processed once. So if you #include the same header in multiple functions, the declarations will only be available the first time.

Definitions of functions (or variables, but that's extremely rare in headers). Headers sometime contain small static functions which the compiler can inline. These will cause the compilation to fail if the #include directive is inside the function, because (barring some compiler extensions) you can't define a function inside another function.

So it's not just a matter of style: #include inside a function often plain doesn't work.

You can put an #include directive anywhere at file scope (i.e. outside a function) with no major technical ill effects. The entities that it defines would only be available below the #include line. That's mostly a matter of style, but it's unusual and pointless so it will confuse maintainers. It can also lead to confusing errors if you define a variable or function of the same name as something declared in a header, because then any mismatch will be reported in the header (or in a header included in a header included … included in that header), possibly using weird implementation-specific syntax, rather than in your code.

So yes, it's bad. Group all your #include directives near the top of the file, with nothing other than comments and the occasional #pragma or #define if instructed by your implementation's documentation.


问:
Is a well written documentation a good enough reason for learning a programming language?
I am learning Python currently which wasn't part of my college curriculum. I was asked in an interview why I chose Python and I replied that it is easy to learn and the documentation is very well written. The interviewer didn't reply whether it was a good enough reason. He looked convinced but I cannot be sure.

Is a well written documentation along with ease of learning a good enough reason for choosing a scripting language? Or should I have elaborated more about the availability of Python libraries and bigger user base of Python?

Just a note. Python wasn't required for the job. The company worked on Ruby-on-rails. Python was in my resume and I think the interviewer just wanted to know what considerations I made as a fresher while choosing a programming language.

答:
Yes, why not? The more languages you learn, the easier it is to learn the next language. Many programming concepts can be learned in a variety of languages. So you might as well start with the one that has the best materials available for learning.

Also most tasks can be accomplished in a variety of languages. Usually, after a while, you'll master the core language concepts and tools, but you'll learn most libraries as needed. It is an argument in favor of a language if the libraries are well-documented so that you can quickly get up to speed on a particular application domain.


问:
Zero-knowledge code hosting?
In light of recent revelations about widespread government monitoring of data stored by online service providers, zero-knowledge services are all the rage now.

A zero-knowledge service is one where all data is stored encrypted with a key that is not stored on the server. Encryption and decryption happens entirely on the client side, and the server never sees either plaintext data or the key. As a result, the service provider is unable to decrypt and provide the data to a third party, even if it wanted to.

To give an example: SpiderOak can be viewed as a zero-knowledge version of Dropbox.

As programmers, we rely heavily on, and trust some of our most sensitive data - our code - to a particular class of online service providers: code hosting providers (like Bitbucket, Assembla, and so on). I am of course talking about private repositories here - the concept of zero-knowledge does not make sense for public repositories.

My questions are:

Are there any technological barriers to creating a zero-knowledge code hosting service? For example, is there something about the network protocols used by popular version control systems like SVN, Mercurial, or Git that would make it difficult (or impossible) to implement a scheme where the data being communicated between the client and the server is encrypted with a key the server does not know?

Are there any zero-knowledge code hosting services in existence today?

答:
I don't think there are any barriers - consider SVN, what gets sent to the server for storage is the delta between what the previous and current version of your code - so you change 1 line, just that line gets sent to the server. The server then 'blindly' stores it without doing any inspection of the data itself. If you encrypted the delta and sent that instead, there would be no impact on the server, in fact you wouldn't even need to modify the server at all.

There are other bits that might matter, such as meta data properties that are not easily encryptable - such as mime type - but others could be encrypted, eg comments in the history log, just as long as you know you have to decrypt them on the client to view. I'm not sure if the directory structure would be visible, I think it would not be visible due to the way SVN stores directories, but its possible I'm wrong. This might not matter to you if the contents are secure however.

This would mean you couldn't have a web site with the various code view features, no server-side repository browser or log viewer. No code diffs, no online code review tools.

Something like this already exists, to a point, Mozy stores your data encrypted with your private key (you can use their own, and they make noises about "if you lose your own key, too bad, we can't restore your data for you", but that's more targeted at the common user). Mozy also stores a history of your files, so you can retrieve previous versions. Where it falls down is that upload is on a regular basis, not checkin when you want, and I believe it discards old versions when you run out of storage space. But the concept is there, they could modify it to provide secure source control using their existing system.

Title: Zero-knowledge code hosting?


答:
Have a look at Stuxnet for a starting point.  I realize you didn't imply or ask about malware technique, but it's the only example I can think of that will meet your requirements. Regardless of the political intent for Stuxnet, the technical structure is quite interesting.

Symantec's analysis provides a really good introduction to the structure of that malware. There's quite a few additional analyses available that go deeper into the code.

The heart of Stuxnet consists of a large .dll file that contains many different exports and resources. In addition to the large .dll file, Stuxnet also contains two encrypted configuration blocks.

  The dropper component of Stuxnet is a wrapper program that contains all of the above components stored inside itself in a section name “stub”. This stub section is integral to the working of Stuxnet. When the threat is executed, the wrapper extracts the .dll file from the stub section, maps it into memory as a module, and calls one of the exports.

And I think the generalized approach would work for you.  You'll have a stub or wrapper that hosts your application.  Each separable component is encrypted and packed within the wrapper. An attacker would then need to decrypt the packed component(s) before they could read the machine code it contains.

For additional obfuscation, use separate encryption keys for each component.  Keep in mind that an attacker will still have access to the keys since you have to include them for the wrapper to decrypt the components. However, if you are distributing based upon a licensing model then you don't have to distribute all the keys. Likewise, you could setup keys on a per-client distribution so if a copy of your code escapes to the wild, you could potentially track down the source of the escape.

Alternatively, take a look at what mainframe programmers of old used to do with code that would overwrite itself.

A conditional would jump to another location which would insert instructions in the area that just executed.  The code then jumps back to the beginning of the modified area. It was "useful" when hotfix patches needed to be applied to a system.  It was also frequently perilous to the application's health, so be cautious with this technique.

The obfuscation comes into play because the program has to run and write over the existing instructions before the "actual" program can operate.  I don't think this would scale for a larger project

Title: How do I implement code obfuscation for native code?

Body:
I'm interested in doing code obfuscation (native code, to make it clear what I mean by "native code": the actual machine code in x86/x64/arm executable files - PE, ELF, Macho and etc, not the sources) as a part of a build process. I can think of several ways of doing it:

Writing a compiler plugin, that would get internal representation after all optimization phases, transform it and then send it to compiler's back-end. In this case, could you advise me some compilers that support plugins like that? Programming language doesn't really matter, but I would like to try out something other than C/C++ (I know that both GCC and Clang support plugins, but I could never get it working properly on Windows).

Dump internal representation after all optimization phases to file, parse and process it with my obfuscation tool and pass it back to the compiler. I couldn't find how to do it with GCC (I successfully dumped different internal representations, but I couldn't find how to make compiler generate code from it). And I know that Clang is able to generate LLVM bitcode, that can be processed and compiled with LLVM compiler, but again I couldn't make it work properly on Windows. Do you know any compiler that allows doing such things?

Currently I'm doing obfuscation by preprocessing sources, it works, but it takes too long to do it for a large code base. So I'm looking for alternative ways of doing it, and I want to read your opinions on what is the best way to do native code obfuscation.

PS Please bear in mind that I'm asking a concrete question. I'm not asking whether I need obfuscation on not. Obfuscation is done for a reason and I have a reason to do it. I'm not asking how to perform actual native code obfuscation or about algorithms of code obfuscation. I know how to do it and how to break it.

I'm asking about native code compilers that either have good support for plugins or can dump and recompile some low level internal representation like AST (abstract syntax tree), RTL (register transfer language), three-address code or something else.


问:
Do unit tests sometimes break encapsulation?
I very often hear the following: "If you want to test private methods, you'd better put that in another class and expose it."

While sometimes that's the case and we have a hiding concept inside our class, other times you end up with classes that have the same attributes (or, worst, every attribute of one class become a argument on a method in the other class) and exposes functionality that is, in fact, implementation detail.

Specially on TDD, when you refactor a class with public methods out of a previous tested class, that class is now part of your interface, but has no tests to it (since you refactored it, and is a implementation detail).

Now, I may be not finding an obvious better answer, but if my answer is the "correct", that means that sometimes writting unit tests can break encapsulation, and divide the same responsibility into different classes.

A simple example would be testing a setter method when a getter is not actually needed for anything in the real code.

Please when aswering don't provide simple answers to specific cases I may have written. Rather, try to explain more of the generic case and theoretical approach. And this is neither language specific.

Thanks in advance.

EDIT: The answer given by Matthew Flynn was really insightful, but didn't quite answer the question. Although he made the fair point that you either don't test private methods or extract them because they really are other concern and responsibility (or at least that was what I could understand from his answer), I think there are situations where unit testing private methods is useful. My primary example is when you have a class that has one responsibility but the output (or input) that it gives (takes) is just too complex. For example, a hashing function. There's no good way to break a hashing function apart and maintain cohesion and encapsulation. However, testing a hashing function can be really tough, since you would need to calculate by hand (you can't use code calculation to test code calculation!) the hashing, and test multiple cases where the hash changes. In that way (and this may be a question worth of its own topic) I think private method testing is the best way to handle it. Now, I'm not sure if I should ask another question, or ask it here, but are there any better way to test such complex output (input)?

OBS: Please, if you think I should ask another question on that topic, leave a comment. :)

EDIT2: I accepted an answer as my correct because it made me think and decide my course of action, although it didn't answered my question completely. But for those who face the same problem as I do (one cohesive class that will change together, but is still too hard to test by itself), I'll tell what I did and why. I decided that the output of that class is simply too hard to a computer to test correctly, so I didn't test it. I could have used a framework to test it's private methods (which would be the best idea, I think), but I didn't want to get to that point. If you are wondering what it is that is cohesive and respects SRP, and still is too hard to a computer to test, I'll give some examples: heightmap generation, hashing functions, procedural music generation (you can test some units, but the highest level unit is simply too subjective).

答:
First of all, not code, but class behavior is what is tested. Code is just a way to make the class work as expected, but code isn't required at all :) It would be actually better to make your class work without writing code (OFF TOPIC).

Public methods call private methods, so testing public methods should always be enough. When using TDD, you should write tests before the implementation, so it's impossible to test private methods.

As for health-critical software and stuff like that, hitting 100% path coverage by testing private methods will not ensure that tested software works correctly in 100% of cases. You can be sure only after testing all possible input data on all possible object states. Doing this for only public methods should cover all paths in private methods.

ContentLicense: CC BY-SA 4.0


问:
Version Control for One Man Dev Team?
I recently began work at a small company as a lone software developer. Before I came no true documentation/version control/etc. was in place. The best they have is Microsoft Word documents and Excel spreadsheets to keep track of everything the engineering team produces.

Personally, among other things, I'd like to institute version control for my own sake, but they're extremely hesitant about it.

My question, is version control sane for a lone developer? What are some of the benefits of version control to a lone developer? Also, what are some of the benefits to, say, a 2-3 man team? And, being that it is a private company, would Github or a private Git server be best?

答:
I ran across a similar issue working as a contractor. The IT team had no backup and no idea how to institute something. Rather than regale them with possible doomsday scenarios, I set up a git repository on the machine on which I was working.

When it came time for me to leave, I instructed one of the team members how to access the repo and pointed them to the online doc "Git in a Nutshell". Then I left. I don't know if they continued to use it. However, for the time I was there, all my work was backed up.

Title: Version Control for One Man Dev Team?


问:
Using WPF rather than WinRT for Windows 8 Pro tablet app: good or bad idea?
Our business is considering writing a line of business application for tablets to enable road warriors and executives access our data.
This will be primarily used for dashboards, reports and some form filling input: quite typical scenario.

Our other apps being built in .Net (WinForms) with lots of related class libraries DLLs (for data access layer, business logic, etc), it seems natural to want to use Windows 8 for this.

I am a rather put off by Windows RT as it doesn't implement the whole .Net Framework and seems quite limitating, so we are rather considering the Windows 8 Pro tablets than WinRT ones.
However, we want a smooth and pleasant tablet experience and I don't think WinForms would be great for this as not built for touch support.

My question is would WPF be good for this? I see there are UI vendors selling touch controls kits but I wonder whether the "touch" experience in WPF is equivalent to the one found WinRT/Metro apps?

Probably this could be answered by playing around with the tablet but I unfortunately do not have one at the moment and can't get the budget to buy one until I have settled this.

答:
I think the answer to your question relies on the purpose, size and specifications of your app.

One "hidden" specification that you have (if I didn't get it wrong) is that you want to reuse as much as possible from your WinForm project or have more or less the same structure as the other WinForm apps. In the comments you said that you are currently accessing the DB from the application using Entity Framework.

Reuse some DLL's in WinRT is not possible, since some .NET classes are not allowed in WinRT, and Entity Framework (which is based on ADO.NET) is not compatible. So the data layer would need to change slightly.

If you chose this way and you need to refactor the data layer acess, my recommendation, if possible, is to use an API (WebAPI or WCF for example) to handle with the Data, so the WinRT app can focus on the presentation layer to be fast and responsive.

If that amount of work "is not affordable", I think the WPF application would be the best option since this kind of apps can handle more heavy work just as WinForms and you could reuse many assemblies. The structure of the app could be very similar, only changing the presentation layer, and YES you could have a very similar touch experience as in WinRT apps.

Depending on the time you can spend and the marketing point of view you should make your decision.

In my opinion a WinRT app can be very saleable and fancy, but in your scenario could take too much time if the infrastucture behind is not ready to support it. The presentation layer will need to be redone anyway since you cannot reuse much from WinForms, maybe the final decision should be taken after evaluating the cost of having a new data infrastucture.


问:
how to reduce communication time in distributed teams
We have 10 distributed teams in our company and we are developing 3 huge web applications. A lot of time of our developers is spent with writing emails.

We are using scrum and for that we had a daily stand-up meeting, but other questions regarding product features, design issues are always communicated via email?

Is there a method or techniques available to reduce the time which is used to communicate!

答:
Is there a method or techniques available to reduce the time which is used to communicate!

Actually, our project have 3 distributed teams 2 located in oversea countries. The teams are using Agile scrum methodology. The method of communication that our company currently uses, might be called : team lead communications through video calls (Lync and Skype).

Because of the time differences, (9 and 7 hours) from US Eastern time, there is no way to have daily stand-up meeting for entire team (22 devs). However, it is managed by 3 team leads, through their communication in Skype.

Basically, each team works on their dedicated new development modules, bug fixes, data patches , etc. However, overall design, responsibilities and progress is daily discussed on high level between key developers.

Note: Above does not mean to abandon email communications, rather just to reduce them asap. As a solution, live video communications reduce the amount of emails and misunderstandings, and eliminates need to sent each specific problem to all Dev teams.


答: Descendants? (need couple more chars)</p>

Body: Descendants? (need couple more chars)


问:
How could we rewrite the 'No Evil' license to make it 'free'?
I did not find the lawyers' SE site, so I thought it best to post here.

```<code>/*
 * ...subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * The Software shall be used for Good, not Evil.
 *
 * THE SOFTWARE IS PROVIDED "AS IS"...
 */
</code>```

This is the 'non-free', Crockford, No-Evil, MIT-style, license. This license is considered non-free because of this phrase: "The Software shall be used for Good, not Evil."

How could we rewrite this to become a 'free' license, while retaining the original spirit of the sentence?

答:
The way to rewrite this license to be more free, would be to remove that stupid sentence. Stick to the standard widely adopted MIT license.

This particular license has caused all kinds of headaches for downstream developers building upon Douglas Crockford's work, and now means his low level library is having to be carefully picked out and replaced throughout the ecosystem. A huge waste of effort.

The "legal definition of evil" aspect of this is problematic obviously, but really this is part of a more general problem of "license proliferation". If people keep making up new licenses just for fun, then more wasted effort will always occur. So to your question, how to rewrite this license to create a new license with a similar meaning? I say...

DON'T! For goodness sake. Pick an existing license. There are already too many to choose from.


问:
Generally speaking can a Javascript-based application (iUI) be deployed without a webserver?
Suppose I have a Javascript based application written in iUI or Kendo UI.  Can it be packaged in such a way they can run locally without a webserver?

I have a few web applications, that with some rework and HTML5 LocalStorage, can possibly work offline (in an airplane or subway).

My mobile development experience is limited to Blackberry Playbook, which I only did so I can get a free one a few years ago.  That platform supports "mobile applications" based on HTML, and an additional out-of-band packaging set of tasks.

Question

Are other platforms (iPhone, Android, etc) similar in that I can simply package an iUI based application so that it can run offline or on a webserver?

答:
Beside phonegap and co. you can also just build a plain HTML5/JS/CSS3 web application that runs in modern browsers like iOS Mobile Safari.

You can set up a cache manifest in your webapplication / website and specify HTML, Javascript, Images, etc. to store locally in the browsers cache. The webapplication / -site then can be run locally (after it is initially downloaded) even without network connection. For our webapps this worked great on iOS devices. Users can also pin the webapplication to their iOS home-screen which is a basic feature for all iOS'es. Some meta tags can customize icon's used on the home-screen etc.

General information about cache manifests can be found here: http://en.wikipedia.org/wiki/Cache_manifest_in_HTML5

We also wrote a article on how we did it with some advanced version checking where on the server HTTP authentication is used for restricting user who have access to the app here:
http://encodo.com/en/blogs.php?entry_id=313

I think it is a quite good alternative to packager's like phonegap etc. Might worth some thoughts.


问:
In Objective C, what English words can I conceptually associate to the symbols?
I'm learning Objective C (from a C# background) and am having difficulty understanding the unusual method signatures and am looking for a shortcut to make the learning curve less steep.

When reading Objective C code, what English words or phrases can I associate with the symbols?

For example, calling a method looks like this:

```<code>  @implementation Calculator

  -(int) add:(int)a and:(int)b {
  }
  @end
</code>```

I would write this code:

```<code>Calculator *calculator = [[Calculator alloc] init]];
int sum = [calculator add:10 and:20];
</code>```

So far in my learning cheat sheet I wrote: "[" means "do" .  What other word associations are there for symbols in Objective C?

答:
So far in my learning cheat sheet I wrote: "[" means "do"

I wouldn't think of it that way. Instead, try to remember that a method call looks like this:

```<code>[target message]
</code>```

The brackets enclose a pair where the first item is the object that you're sending the message to, and the second is the message that you're sending. It doesn't take any longer to get used to brackets used like that than to learn that {and } enclose a group of statements in C-like languages. If you try to translate the brackets to some other meaning you might just make the whole idea more complicated. If you need a way to "say" the brackets as you read them, think of them as "start method call" and "end method call".

As for the messages themselves, it may help to remember that the name of a method includes all its parts. In your example, the method is:

```<code>add:and:
</code>```

I know it's surprising that the parameters are inserted between parts of the method name, but once you get past the surprise you'll find that it's very nice to use the method name to remind you of which parameter is which.

Body:
So far in my learning cheat sheet I wrote: "[" means "do"

I wouldn't think of it that way. Instead, try to remember that a method call looks like this:

[target message]

The brackets enclose a pair where the first item is the object that you're sending the message to, and the second is the message that you're sending. It doesn't take any longer to get used to brackets used like that than to learn that {and } enclose a group of statements in C-like languages. If you try to translate the brackets to some other meaning you might just make the whole idea more complicated. If you need a way to "say" the brackets as you read them, think of them as "start method call" and "end method call".

As for the messages themselves, it may help to remember that the name of a method includes all its parts. In your example, the method is:

add:and:

I know it's surprising that the parameters are inserted between parts of the method name, but once you get past the surprise you'll find that it's very nice to use the method name to remind you of which parameter is which.


答:
Not particularly fluent in Objective-C, but [calculator add:10 and:20]; means as much as "send a message to calculator to add 10 and 20".

From what I remember Objective-C emphasizes that a method call is actually sending a message to an object, sometimes with a payload (the arguments to a method call as it were), which is a bit different than how you would think about it in C#.

Title: In Objective C, what English words can I conceptually associate to the symbols?

Body:
I'm learning Objective C (from a C# background) and am having difficulty understanding the unusual method signatures and am looking for a shortcut to make the learning curve less steep.

When reading Objective C code, what English words or phrases can I associate with the symbols?

For example, calling a method looks like this:

```<code>  @implementation Calculator

  -(int) add:(int)a and:(int)b {
  }
  @end
</code>```

I would write this code:

```<code>Calculator *calculator = [[Calculator alloc] init]];
int sum = [calculator add:10 and:20];
</code>```

So far in my learning cheat sheet I wrote: "[" means "do" .  What other word associations are there for symbols in Objective C?


答:
I wouldn't try to equate it to anything in English. Without reading the brackets you can read it in plain English: Calculator add 10 and 20. [] are used for containment/grouping.

Basic Example:

I would first start by translating the syntax to a programming language you already know.

And I would first start by learning an example without named parameters:

[calculator reset]; means: calculator.reset();

Nesting:

[[container calculatorInstance] reset]]; means container.calculatorInstance().reset();

So the first item after the [ is an object (or class). After the space is a method being called on the object (or class).

So a set of brakets [] could be thought of as object.method() and if you were to take that value and call a method on it you would have an outer set of [].

```<code>[[something returnAValue] actOnThatValue];
</code>```

is the same as

```<code>something.returnAValue().actOnThatValue();
</code>```

Body:
I wouldn't try to equate it to anything in English. Without reading the brackets you can read it in plain English: Calculator add 10 and 20. [] are used for containment/grouping.

Basic Example:

I would first start by translating the syntax to a programming language you already know.

And I would first start by learning an example without named parameters:

[calculator reset]; means: calculator.reset();

Nesting:

[[container calculatorInstance] reset]]; means container.calculatorInstance().reset();

So the first item after the [ is an object (or class). After the space is a method being called on the object (or class).

So a set of brakets [] could be thought of as object.method() and if you were to take that value and call a method on it you would have an outer set of [].

[[something returnAValue] actOnThatValue];

is the same as

something.returnAValue().actOnThatValue();


问:
How to loosely couple modules in service oriented architecture
We're developing a total solution, and we've chosen service-oriented architecture to loosen subsystems. However, now we have a problem.

When customer orders something, Order Subsystem is responsible to get that order, and register it. However, there are some other modules which are responsible too, in order registration process, and each module should do something on it:

Customer Accounting module should check customer's balance, and prevent order registration if there is not enough money in customer's account.

Asset Management module should increase/decrease customer's assets

Rule Engine should apply some business rules dynamically on it (like preventing a specific customer, or notifying an operator, etc.)

CRM should view customer's history, and give good customers some discount

...

Right now, we're doing it this way:

```<code>public void RegisterOrder(Order order)
{
    RuleEngineService.ApplyBusinessRules(order);
    // some code here
    CrmService.GiveDiscountIfApplicable(order);
    // some code here
    CustomerAccountingService.CheckBalance(order);
    // some code here
    AssetManagementService.ChangeAssetCount(order);
    // some code here
}
</code>```

This means that if we add another subsystem (module) that needs to do something on order, we have to recompile the code of our OMS (Order Management System) to support it. Also we're coupled to some extent to other subsystems here, and if one of them fail, this registration process fails.

One way of making this piece of code dynamic and loosely coupled is to use interfaces or contracts, like:

```<code>public void RegisterOrder(Order order)
{
   // Finding a list of all IOrderProcessors.
   // Looping over each, calling orderProcessor.Process(order);
}
</code>```

However, it has two problems:

We can't use interfaces over SOAP and HTTP (we don't have access to other subsystems' DLL files)

Those need to run in a specified order (rule engine the first one)

What should we do here? What are the known patterns and practices?

答:
Take a look at the Pub-Sub pattern as it's well suited for providing that decoupling you're looking for.  The observer pattern may have some applicability in your case as well.

In essence, the "main" application that handles the request will push a message to a queue that the other systems will pick up and handle as they need to.  You'll need to define a standard interface or contract for the message format, but that's what will gain you the decoupling you're looking for.  Adding and removing applications is as simple as adding and removing subscribers.

Another added benefit is a supporting system can go offline, and when it comes back it will pick up where it left off in the message queue.

If you have atomic transactions, you'll need to extend the pattern a little bit.  Reply messages on another queue are one means of accomplishing that.  Presumably you already have some logic in place to handle that transaction state, so you would just need to modify it to react to reply messages instead.


问:
Cross border data obfuscation and how to deal with it?
I am currently facing a situation where I will need to obfuscate data for legal reasons (these are countrywide rules and not specific to me)

I will still need to work with teams outside this area who will still need to access applications/databases for testing/deployment and so on, however the data must be fully obfuscated.

What are your experiences of this scenario?

e.g. Who owns what stage of the process, what access do the various parties have, how strong is the encryption, how do updates occur

答:
I don't know if there are any best practices for this sort of thing.  But if I were given this task I think I'd identify what correlations yield the most data and then try to randomize those correlations.

The problem with a piece of data is not the data itself.  It's the correlations that can be made.  Any obfuscation scheme would do best to concentrate on randomizing those correlations so thoroughly that they couldn't be extracted again.  One correlation that's independent of other pieces of data is the overall rarity of a piece of data, and that correlation should also be obscured.

For example, identify a rarity cutoff for first and last names, then replace all first and last names below that rarity cutoff with others that are just as rare, but picked from a random list of baby names or something along those lines.  I might also copy some names from one place to another to change the frequencies at which they occur.  For example, change all "John"s to "Avercrombie"s, and all "Hilda"s to "Mary"s.

Then I would start randomly swapping the first names with other first names in the tables.  I would do the same (but independently) for last names.  I would also start scrambling important relationships.  For example, with a Netflix style database, the list of movies people rented.  I would randomly move movies from one person's list to another until all the lists were hopelessly scrambled.  Of course, if what you want is to be able to refine a prediction algorithm with 'anonymized' data, that would make the data useless, so you will have to exercise judgment in what data you did this with.


问:
Architecture for REST consumer
Are there any good samples of web applications that consume restful web services?

I am developing a webapp with spring, and have come to the point of reading lists of elements and element details from a RESTful JSON api. I started developing as though I was using a database, creating services, model elements plus DAOS, but now I'm stuck on how to do a proper design here.

Should model objects hold a fromJson/toJson method and encapsulate themselves the serialization info? What should DAO objects do? Where should I keep WS specific info (urls, api keys, item names, etc.)?

Any good opensource apps would be nice.

答:
I have a personal project, MultiBit Merchant, which is released under MIT license. It is arranged as a platform that provides a REST API to a number of downstream clients, one of which is the MultiBit Store. It behaves as a simple e-commerce platform.

It's in early development and has some background documentation that is worth reading to get a good grip on the design decisions - there are numerous further articles covering REST, HAL and more.

The technologies involved are Maven, Java, Dropwizard, Spring, Hibernate, JAX-RS, JDBC, OpenID, HMAC and so on. Design patterns include services, DAOs, DTOs (with JSON HAL representation) within a Hexagonal architecture.

When I get the chance I will move away from Hibernate to MongoDB which will greatly simplify things.

If you're looking for a reasonable sized project that covers a lot of ground it may be of some use. If you want to copy great chunks of the code and alter them for your own purposes you may find the Simple Scaffolding class helpful.

Title: Architecture for REST consumer


问:
Does an Open Source license exist that allows me to retain rights to revoke usage of software/source at any time, for any reason, and without warning?
Does an Open Source license exist that allows me to retain rights to revoke usage of software/source at any time, for any reason, and without warning?

I want to allow others to use my software and source code for free but at the same time, I want the ability to revoke rights to usage if I don't agree with the ways that the software and/or source is being used.

答:
That would not be an Open Source license by the definition of the Open Source Initiative:

5. No Discrimination Against Persons or Groups

The license must not discriminate against any person or group of persons.

Rationale: In order to get the maximum benefit from the process, the maximum diversity of persons and groups should be equally eligible to contribute to open sources. Therefore we forbid any open-source license from locking anybody out of the process.

Some countries, including the United States, have export restrictions for certain types of software. An OSD-conformant license may warn licensees of applicable restrictions and remind them that they are obliged to obey the law; however, it may not incorporate such restrictions itself.

6. No Discrimination Against Fields of Endeavor

The license must not restrict anyone from making use of the program in a specific field of endeavor. For example, it may not restrict the program from being used in a business, or from being used for genetic research.

Rationale: The major intention of this clause is to prohibit license traps that prevent open source from being used commercially. We want commercial users to join our community, not feel excluded from it.


问:
What do I call people who extend my class in base class documentation?
Been calling them "implementers", but it seems weird to me.

```<code>/// <summary>
/// Implementers should implement this.  Derp
/// </summary>
protected abstract void InternalExecute();
</code>```

A point of clarification, I'm interested in what to call the people who create child classes, not the child classes themselves.

"Hey, you there" not "that thing there."

答: You can call them extenders or subclassers.</p>


问:
Breaking down a complex story at project start
I'm trying to get to grips with agile project management (with Pivotal Tracker) but keep finding myself running into walls when trying to define the first few stories of a project. Take for example this very simple story:

"A user should be able to tag a product"

Assuming I've already defined "product" elsewhere, this story would possibly involve writing a polymorphic tagging system under the hood, on completion of that system id be able to finally add the ability to tag a product.

My problem is with the amount of work hidden in this story. I can define tasks to get the story done but stories as a whole are supposed to be 1-2 days work? I don't feel right about the story just revealing the tip of the iceberg but that's the only part that relates to the User.

How do you overcome this kind of thing? What are the best practices?

UPDATE 25/08 Thanks to everyone for your guidance, I've taken all advice onboard on how to define stories. I am now switching to Jira Grasshopper which has better support for tasks within stories (assignment, estimates etc) and tracking of development tasks once the sprint has began.

答:
Stories are not supposed to be, "1-2 days work". Under Scrum stories are normally estimated using Story Points, a relative sizing system. If you use planning poker stories are given a points value - the time that story takes to implement depends on the velocity that your team has established.

If you feel the story is hiding complexity (you could call it an Epic story), you should break it up into smaller stories. Make sure that the new stories follow the INVEST criteria.

But you may be overengineering this; the XP principle of YAGNI applies here.  To be explicit you should not implement a, "polymorphic tagging system under the hood", unless you really need it. Even then, it should be designed by improving the existing system, that you have developed with a good suite of tests.

If you're certain you do need this complex tagging system, you should call out the complexity in separate stories. Mike Cohn describes the approach to design as, "Intentional, yet emergent"

OwnerDisplayName: matthewrk


答:
If you need your stories to be 1 to 2 days of developer work each, perhaps you should break each story into specific user tasks that are 1 to 2 days of developer work.

Consider the following "user story:"

A user should be able to receive an invoice from a purchased product.

Think about what's involved just in the database design, in giving the user this capability.  You need a customer table, an invoice header table, and an invoice line items table, and we haven't even talked about accepting payments yet.

In reality, user stories are not this simple.  Complete user stories include a walkthrough of the user steps involved:

User puts product in cart

User specifies quantity

User specifies shipping type

and so on.  In short, you need to break down your user stories into finer detail.

Title: Breaking down a complex story at project start

Body:
I'm trying to get to grips with agile project management (with Pivotal Tracker) but keep finding myself running into walls when trying to define the first few stories of a project. Take for example this very simple story:

"A user should be able to tag a product"

Assuming I've already defined "product" elsewhere, this story would possibly involve writing a polymorphic tagging system under the hood, on completion of that system id be able to finally add the ability to tag a product.

My problem is with the amount of work hidden in this story. I can define tasks to get the story done but stories as a whole are supposed to be 1-2 days work? I don't feel right about the story just revealing the tip of the iceberg but that's the only part that relates to the User.

How do you overcome this kind of thing? What are the best practices?

UPDATE 25/08 Thanks to everyone for your guidance, I've taken all advice onboard on how to define stories. I am now switching to Jira Grasshopper which has better support for tasks within stories (assignment, estimates etc) and tracking of development tasks once the sprint has began.


答:
If you can revoke someone else's use at any time for any reason, they don't have a license, they just have nominal permission.

A simple statement like what you had in the question is enough, though you may want to specify exactly how quickly they should stop using your code if asked.

Body:
Does an Open Source license exist that allows me to retain rights to revoke usage of software/source at any time, for any reason, and without warning?

I want to allow others to use my software and source code for free but at the same time, I want the ability to revoke rights to usage if I don't agree with the ways that the software and/or source is being used.


答:
If you don't want it to be used in certain situations why not spell it out in the license up front?

A license is a contract, whatever terms and conditions you spell out go as long as they are legal in contract law, no slavery, racism or other protected class discrimination.

As an example of other projects that do this here is a project (GPU grid processing for gnutella) that put a no military use clause in their license.

http://gpu.sourceforge.net/

GPU is a Gnutella client that allows users to share CPU-resources... (which is under GPL and targets only peaceful goals btw).

http://archive09.linux.com/articles/56426 -  an interview with the devs where it gives a bit of their license:

Tiziano Mengotti and Rene Tegel are the lead developers on the GPU project. Mengotti is the driving force behind the license "patch," which says "the program and its derivative work will neither be modified or executed to harm any human being nor through inaction permit any human being to be harmed."

Title: Does an Open Source license exist that allows me to retain rights to revoke usage of software/source at any time, for any reason, and without warning?


问:
How would you evaluate object oriented design skills?
what kind of insights or questions would lead you to determine a person's OOAD skills.</p>

答: Don't give a vocabulary quiz.    "Define Inheritance"  or "name 3 features of OO design" are questions that won't tell you anything about the skills of the individual, only how long since he/she last read a textbook.   I've met several great programmers who use these skills every day, but would choke if asked to give the formal definition.


问:
High traffic chat - how to check if there is new message and show it for all users
I already had question about this but obviously it was not accepted very well, apparently too long when it's actually more information so you could have given me better answer.

Ok, I will be much clearer now. Best possible logic to develop scalable chat in terms of stability, storing/reading messages on chat, updating chat on new message for all users etc.? I have most of this developed, the logic I think I miss is --> check if there is new message and show it for all users. I have this implemented but it crashes the site due to its traffic of 300k-400k people, so that's my main question.

The chat is PHP based and uses Pusher (www.pusher.com) for instant messaging but it lacks what I need because it's more like a websocket.

I'm using hardcoded files to keep messages (want to avoid database as much as possible). It's a no extension type of file, I'm sure you know. I'm getting crash with

```<code>$fp = fopen(..., "w"); // pretend ... is the path and filename
fwrite($fp, $msg); //hardcode the message
fclose($fp);
</code>```

where $msg is the message itself. I'm having 1 file per message. I show last 150 messages = 150 file accesses and reads, yeah it's too much I guess. I have better logic now which I'm pursuing and that is 1 file with last 50-100 messages at all time. Sure it should be much better.

How does it crash, that's the trickiest part because everything seems ordinary, believe me it is difficult to determine what exactly crashes the site, but in like 5 minutes when I try to open the site it's gone, then I put the old content without chat and is back online again.

I'm having jquery post every 1 second to check if there is new message. I'm using timestamp in a special file where I keep the time last message was sent and if ((time() - time in file) <= 2) = reload last 150 messages including the last one. Too much input/output, write/read or however to say it I think is what crashes the site.

答:
First of all, could you provide me with some clarification: are you coding a chat room (one-to-many) or individual (one-to-one) chats?

There are a couple of obvious flaws in your current system's design that I would like to point out.  First, I'll start out with a brief analysis and then explain what is wrong with it and what you can do to fix it.  Obviously if you want to run a successful project you should start from step one and get your hands dirty with systems analysis and design.

Problem

Website receives a high volume of traffic and eventually crashes.

Requirements

Sustain high volume of web traffic

Display previous 150 messages

Secure communication pathway between clients

Problem Analysis

Right away it is obvious that your site is crashing because the code that opens the file is being called hundreds of thousands of times per second.  Opening files and writing to them is very memory intensive.

The FILE Probem: Files do not handle concurrency very well at all.  In fact, they're terrible with concurrency.  Think about it like this, essentially you've opened the same file with notepad with hundreds of thousands of open windows/processes and you're changing the content in all of them simultaneously.  When you try to solve a problem with this type of solution you end up with non-deterministic results.  Basically, it is impossible to predict what data will be in the file.

Fortunately, there is a way to get deterministic results while still using files if you lock them properly.  Unfortunately, this is not a solution to your problem.  In your case, only one person would be able to send a message at a time.  Surely that is NOT the solution you want!

Wait... there IS a solution:

You CAN USE a Database!

Databases are particularly good at solving this sort of concurrency issue!  Depending on what database/engine you use your table may lock or only a single record might lock.  In you case, I would suggest a free database like MySQL and a record-locking engine like InnoDB.  If you're not a database rookie, you might want to look into MariaDB as well, it is a fork of the MySQL project by the original developer and is a binary drop in.

Basically, there is no way around it using a database for this type of solution.  In fact, databases are very powerful and you can program procedures with them.  From your query you can choose to select only 150 messages and then order them by most recent very easily.  All users will be able to send messages at the same time with a record-locking database engine like InnoDB.

I would like to additionally point out that I would be a little troubled to find out what the code for the rest of the application looks like.  It is very easy to write PHP code that looks fine but performs terribly.  I'm not sure if you're familiar with asymptotic analysis or unit testing but I highly suggest that you thoroughly test your code before pushing it to production.  Given the size of your userbase you should be concerned about code optimization and runtime.  If your application/problem/solution was properly analyzed, designed, implemented, tested, and debugged you would have a much better handle on your problem.

It is also very easy to write code in PHP that is insecure.  I would like to advise you to test your code thoroughly (try to break it) when writing modules that interact with the database.  Poorly coded web applications can be very easy to exploit and given your user base of 300-400k I wouldn't doubt it if Cindy Lou Who suddenly decided to give it her own security audit.  If a white hat hacker discovers the flaw in your system they will likely encourage you to fix it.  If a black hat hacker discovers the flaw they will likely use it to spread malware and steal information.


问:
Shared hosting for a PHP application
I was reading Essential PHP Security and chapter 8 talks about problems with hosting your PHP app in a shared hosting environment.

Some of the problems he mentions are:

- Exposed source code and File system browsing.

a web server must be able to read the source code in order to execute it. Since the web server is shared a PHP script written by another developer on the server can read arbitrary files. An attacker can also create a script that browses the file system.

- Exposed session data and Session injection.

By default, PHP stores session data in /tmp which is writable by all users, so Apache has permission to write session data there. A simple script can allow other users to read, add, modify, or delete sessions.

It's like everything is exposed and vulnerable if I used shared hosting this way.

My questions:

Considering the book was published 8 years ago, are they problems still occurring or were they mitigated somehow in the last few years?

Why would one opt for shared hosting if it going to cause these huge security concerns?

I understand that shared hosting is cheap, but there must be a safer alternative to it and cheaper than dedicated hosting?

In case a customer ask me to develop an application that will be hosted on a shared hosting, is there a full proof way to develop a secure application or is it just a recipe for disaster?

答:
Partial answer:

2)  Because it's the cheapest available option; and for people who either don't know about the risks or don't care because they don't feel anything they have is worth the extra cost to secure it there's no reason not to.

3)  Virtual Private Servers (VPS) sit between shared and dedicated hosting in price.  What you get is a VM to install your own web/db/etc servers on.  At the low end I've seen them for as little as $10/month which is not much more than a cheap shared account.  For that price you're getting a very minimal amount of resources on a server with a large number of other VPSes running on it; but the same is true of any low cost shared hosting.  At higher prices you can get larger shares of server resources and more support until you're blurring the line between a large VPS and a low end dedicated server (ex atom, celeron, etc).

4)  Even a dedicated server isn't full proof in that it could be hacked; but I can't give you any specific advise in hardening a shared account.

Title: Shared hosting for a PHP application


答:
1) Considering the book was published 8 years ago, are they problems still occurring or were they mitigated somehow in the last few years?

File system browsing can be disabled by suitably competent hosting services.  I know the couple of shared hosting accounts I still have do not let you browse files outside of your own directory.  Also, leaked session data is a non issue - put that in a database where it belongs.

2) Why would one opt for shared hosting if it going to cause these huge security concerns?

Historical context - 8 years ago VPS hosting was just getting ramped up.  The two primary options were shared hosting and didicated machines.  And obviously dedicated machines were much more expensive than shared hosting.  So... a lot of people went with shared hosting.

3) I understand that shared hosting is cheap, but there must be a safer alternative to it and cheaper than dedicated hosting?

No, 8 years ago there really wasnt.  Not at that particular price point.  VPS hosting now is much cheaper, and thats basically taken over.

4) In case a customer ask me to develop an application that will be hosted on a shared hosting, is there a full proof way to develop a secure application or is it just a recipe for disaster?

No.  There is no 'fool proof' way to do this on shared hosting, ... or dedicated hosting.  I would, though, recommend VPS hosting over shared hosting.  This puts the responsibility on the developer to secure the machine, but also allows the developer to install any needed software and extensions.

Shared hosting can be fine.  While there are theoretical problems, consider too that the people setting up the machines are likely much more competent at securing them than your average PHP hack would be.  And in all honesty, if there's a security problem, its far, far more likely to be due to a flaw in PHP code than server setup.

Title: Shared hosting for a PHP application

Body:
I was reading Essential PHP Security and chapter 8 talks about problems with hosting your PHP app in a shared hosting environment.

Some of the problems he mentions are:

- Exposed source code and File system browsing.

a web server must be able to read the source code in order to execute it. Since the web server is shared a PHP script written by another developer on the server can read arbitrary files. An attacker can also create a script that browses the file system.

- Exposed session data and Session injection.

By default, PHP stores session data in /tmp which is writable by all users, so Apache has permission to write session data there. A simple script can allow other users to read, add, modify, or delete sessions.

It's like everything is exposed and vulnerable if I used shared hosting this way.

My questions:

Considering the book was published 8 years ago, are they problems still occurring or were they mitigated somehow in the last few years?

Why would one opt for shared hosting if it going to cause these huge security concerns?

I understand that shared hosting is cheap, but there must be a safer alternative to it and cheaper than dedicated hosting?

In case a customer ask me to develop an application that will be hosted on a shared hosting, is there a full proof way to develop a secure application or is it just a recipe for disaster?


问:
How to handle divide by zero in a language that doesn't support exceptions?
I'm in the middle of developing a new programming language to solve some business requirements, and this language is targeted at novice users. So there is no support for exception handling in the language, and I wouldn't expect them to use it even if I added it.

I've reached the point where I have to implement the divide operator, and I'm wondering how to best handle a divide by zero error?

I seem to have only three possible ways to handle this case.

Ignore the error and produce 0 as the result. Logging a warning if possible.

Add NaN as a possible value for numbers, but that raises questions about how to handle NaN values in other areas of the language.

Terminate the execution of the program and report to the user a severe error occurred.

Option #1 seems the only reasonable solution. Option #3 is not practical as this language will be used to run logic as a nightly cron.

What are my alternatives to handling a divide by zero error, and what are the risks with going with option #1.

答:
It seems like a bad idea to me to run important tasks (ie; "nightly cron")
in an environment where errors are ignored.   It's a terrible idea to make this
a feature.  This rules out options 1 and 2.

Option 3 is the only acceptable solution.  Exceptions don't have to be part of the language, but they are part of reality.  Your termination message ought to be as specific and informative as possible about the error.


答: It may depend on where you live (the jurisdiction). Here's a 2003 article "Problems in Open Source Licensing" by Jeremy Malcolm, an Australian IT lawyer, who gives his opinion that under Australian law, any free license can be revoked arbitrarily: GPL, BSD, MIT, anything. Precisely because the licensee has not paid for it or exchanged anything of value for it.


问:
Selecting an appropriate design for Month/Date Selection
I have a requirement what seemingly looks very simple (and perhaps strange) but some minor details are giving me troubles. Perhaps I'm overthinking this.

I'm building a scheduler application (on WPF) for an embedded device that runs everyday. The scheduler controls when the device can be turned on and off. For example, the embedded device can be scheduled to shut off every weekends and on any holidays, such as July 4th.

So I went ahead and designed my datastructure to hold a datetime collection for holidays. Firstly, I don't need to store the time but apparently in C#, there's no other appropriate class that holds just dates. Second, I also don't need to store years but then I have no way of knowing whether it is a leap year or not. (For example, I can schedule the device to be shut off on every February 29th, but that date may not be available on a particular year.)

I also need a way for the users to select a month/date. As far as I know, there's no appropriate UI control available to handle my problem. I think I need to look for something like this (Below is photoshopped from a standard calendar control):

What datastructure/design would you use to handle problems like this? What's a good UI design to have users intuitively select a month/date?

答:
I'm currently trying to solve the same problem and decided to model the UI and functionality on the Outlook calendar appointments 'occurrence' feature, simplified a bit. This partially abstracts the selection of repeated events away from a calendar control and covers most scenarios. No point in reinventing the wheel.

The data model is a simple class with type of recurrence(week or month) a day of week flags enum, day of month, recurrence frequency, end date/max number of recurrences.

The tricky bit is processing the recurrence rules (work in progress).


问:
How much functional programming expertise can programmers be expected to have?
I'm coding in a non-functional language with functional mechanisms (C# to be specific, but you could substitute, say C++ and use function pointers, or what have you) on a small team.  It's my habit to use functional techniques -- passing delegates (objects representing functions) as arguments, using closures, occasional anonymous functions, etc -- and I try to document this better than I think a reasonable programmer would need them documented.  Looking at code I see online and on Stack Exchange communities, I think my style is pretty normal among C# developers.

Our team, however, isn't sophisticated in these techniques and I end up having to explain (and defend) myself -- my high level of documentation is actually used as evidence by them that I shouldn't code the way I do for the sake of readability.

Now, given the make-up of my team, I understand that I might just give up the good fight here and code to their standards, understanding its better for the team.  Does anyone have successful experience using empirical studies, accreditation criteria or best practices lists published by respectable sources that suggest that programmers today have more experience in these functional programming idioms, and that, therefore, we don't need to shy away from them for purposes of maintainability?

答:
I would expect any professional C# or web developer in 2013 to be familiar with anonymous functions, closure basics, and the concept of passing methods around. .NET 3.5 has been out for years now, and should be pervasive.

I would expect most professional developers (of any sort) to understand other tangential concepts to functional programming like immutability and pure functions, and how these apply to program design. These concepts too have been around in mainstream programming for ages (and more prevalently in the past 5 or so).

That said, I would not be surprised if more than half of applicable professional developers were completely oblivious to these concepts - and you are largely correct that you should conform to what is best for the team, just like they're largely correct that high levels of documentation is a smell towards unreadable code.

So conform for now and work at training people up, likely through some combination of explicit training and gradual use of more complicated functional structures (where appropriate).


答:
In C#, functional programming is a proper tool when you have to navigate through collections. In those cases, functional programming makes the code much shorter and helps focusing on the problem instead of its implementation, while reducing the risk of making mistakes.

You can hardly be accountable of reducing the codebase and the margin for errors by using a proper tool.

The issue you have with your colleagues, I have it in the company I'm currently working in. Most programmers there don't know very well neither C#, nor programming in general, which makes me a not so popular person, given that my colleagues have a hard time understanding the code which uses parallel programming, functional paradigms, code contracts and other features of .NET Framework.

One of the rules each developer should follow is that their code should be understandable in a given context. This conflicts with the fact that one shouldn't be forced to reduce code quality just because he works with unskilled people.

There are two solutions:

Teach your colleagues functional programming and other things you know and they don't, trying to increase their level at yours. This is what I've chosen in my case and what I would suggest to anyone.

Pros: the quality of the codebase will only increase, and you may appreciate better to work with more skilled colleagues.

Cons: many programmers don't want to learn things. They work for money, and they don't care about their work. Trying to teach them anything would be an extremely difficult task and one should be ready to receive heavy resistance.

Start writing crappy code written for beginners. Given that this may be disastrous for the motivation, this solution should be taken only when working with people who are unable and/or unwilling to learn and in a circumstance when you can quit soon.

Pros: this can enhance relations with coworkers if they don't want to learn things and don't want to make effort reading your code.

Cons: this will decrease the quality of the codebase. Working on badly done projects which would inevitably fail is not very motivating.

Finally, should programmers know functional programming? It depends. It would be mandatory for any person who works daily with C# to know what are anonymous types and lambda expressions and how to use them in C#; on the other hand, I wouldn't say that the same person who don't know what a monad is should be treated as an incompetent.

The difference is that anonymous types and lambda expressions are the inherent part of C# nowadays, while the term monad doesn't exist in C# world.

On the other hand, I'm expecting a developer to be familiar to functional programming concepts like monads, even if this developer never used them. This is because developers are expected not only to write code in a given language, but have enough general culture and curiosity beyond the tools they use daily.

Title: How much functional programming expertise can programmers be expected to have?

Body:
I'm coding in a non-functional language with functional mechanisms (C# to be specific, but you could substitute, say C++ and use function pointers, or what have you) on a small team.  It's my habit to use functional techniques -- passing delegates (objects representing functions) as arguments, using closures, occasional anonymous functions, etc -- and I try to document this better than I think a reasonable programmer would need them documented.  Looking at code I see online and on Stack Exchange communities, I think my style is pretty normal among C# developers.

Our team, however, isn't sophisticated in these techniques and I end up having to explain (and defend) myself -- my high level of documentation is actually used as evidence by them that I shouldn't code the way I do for the sake of readability.

Now, given the make-up of my team, I understand that I might just give up the good fight here and code to their standards, understanding its better for the team.  Does anyone have successful experience using empirical studies, accreditation criteria or best practices lists published by respectable sources that suggest that programmers today have more experience in these functional programming idioms, and that, therefore, we don't need to shy away from them for purposes of maintainability?


问:
When should I write integration tests?
According to rules of TDD unit tests are written before production code, but what about Integration tests that exercises interaction between concrete (non mocks) wired objects?

Should they be written before unit tests or after production code just to test the "wiring" ?

Note that I'm not talking about Acceptance or functional tests but Lower level integration tests.

答:
Unit tests test discrete blocks of code within your project.

Integration tests test how your code interfaces with other code: in other words, they test the interface of your code.

Write unit tests when developing code behind an interface.

Write integration tests when developing the interface or any code that implements the interface.

This means that you will sometimes write integration tests very late in a project, because the majority of the work is behind the interface: for example, a compiler, a particular webservice that implements several layers of logic or .. something that involves a lot of internal logic.

However, if you're implementing a set of REST services or refactoring the data model and adding support for XA transactions, then you're going to start developing integration tests almost immediately, because most of your work is centered around the interface, whether it's the REST API or how the program uses the data model.

Title: When should I write integration tests?


问:
Is it legal to imitate how an API looks?
I want to make an open-source graph thing which looks and behaves very similarly to Google Visualization API, but it would be based on Flot. Is this legal, or must I not imitate Google Visualization API?</p>

答: GNU has a long history of making work alikes for libraries.  When BSD was sued for copyright it was over implementation copying and not interface copying (reimplementing the Unix interface was considered a valid resolution). Then as whatsisname points out in the comments Oracle lost when they sued Google for API copyright. Work alikes have a long history of being legal.  So it should be ok.  Though as always I am not a lawyer and this is not legal advice. </p>


问:
Why one would commit changes to version control every three minutes?
The frequency of commits depend on two factors:

the developer himself: some developers tend to commit often, others may spend hours without committing,

the current work: the same developer may have to commit very frequently when effectuating risky refactoring operations or similar tasks, and quite rarely when working on other parts of the codebase.

From what I observed, beginners tend to commit one or two times per day on average. Developers with a few years experience are probably committing once per hour on average. Committing every fifteen minutes is probably the best thing to do, but I've rarely seen this commit frequency.

Question:

I've spotted in Google Closure Library logs that it has commits nearly every three minutes from the same developer.

What are the benefits of such high frequency?

Are there consequences on the way the code is written?

Is it related to the fact that at Google, codebase is compiled and tested on servers and so one should commit the code to see if it compiles and passes all the unit and integration tests?

答:
You must make sure your code can be compiled and correctly run before you commit your code.Otherwise your co-workers's work will be interrupted by you!
   I think that someone commits very frequently is not so good.
   You should commit after you have finished and tested a function.
   You should commit at least once everyday.</p>


问:
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?

答:
My way to study  large code project is as the following:

make the project,and use it.

use IDE to open the project.For example:Eclipse or Codelite.Then use IDE to index all source code of the project.

Use IDE to generate class diagram if the language of the project support this function.

Find the main method.Main method is an entry of program.And main method is also a good entry to explore the project.

Find the core data-structs and functions of the program.Take a look at the implementation.

Modify some code of the project.Make it and use it.Watch whether it correctly works!
You will be encouraged by modify the program.

After you have understood the main flow of the program and the implementation of the core system,you can explore the other modules of the program.

Now you have understood  the large code project!Please enjoy it!

Title: How do you dive into large code bases?


问:
Use case notation for login
When a login is needed in a system to perfom any action. How do you express that in a Use Case Diagram?

I have a system that will allow employees to perform sells. They must be logged in, but once they are, it is not necesary to log again until the session ends (typical login).

I do not know how can I express that that login is compulsory, but only once.

答:
From your requirement, you mention this

They must be logged in,

In order to perform sells (one use case), they MUST also login (one use case). I believe this login use case will be reuse everywhere other than sells module. Thus I would like to suggest to use <<include>>. Below is the text on the <<include>> usage extract from this link.

An e-commerce application that
  provides customers with the option of checking the status of their
  orders. This behavior is modeled with a base use case called
  CheckOrderStatus that has an inclusion use case called LogIn. The
  LogIn use case is a separate inclusion use case because it contains
  behaviors that several other use cases in the system use. An include
  relationship points from the CheckOrderStatus use case to the LogIn
  use case to indicate that the CheckOrderStatus use case always
  includes the behaviors in the LogIn use case.

Title: Use case notation for login


问:
How to loosely couple modules in service oriented architecture
We're developing a total solution, and we've chosen service-oriented architecture to loosen subsystems. However, now we have a problem.

When customer orders something, Order Subsystem is responsible to get that order, and register it. However, there are some other modules which are responsible too, in order registration process, and each module should do something on it:

Customer Accounting module should check customer's balance, and prevent order registration if there is not enough money in customer's account.

Asset Management module should increase/decrease customer's assets

Rule Engine should apply some business rules dynamically on it (like preventing a specific customer, or notifying an operator, etc.)

CRM should view customer's history, and give good customers some discount

...

Right now, we're doing it this way:

```<code>public void RegisterOrder(Order order)
{
    RuleEngineService.ApplyBusinessRules(order);
    // some code here
    CrmService.GiveDiscountIfApplicable(order);
    // some code here
    CustomerAccountingService.CheckBalance(order);
    // some code here
    AssetManagementService.ChangeAssetCount(order);
    // some code here
}
</code>```

This means that if we add another subsystem (module) that needs to do something on order, we have to recompile the code of our OMS (Order Management System) to support it. Also we're coupled to some extent to other subsystems here, and if one of them fail, this registration process fails.

One way of making this piece of code dynamic and loosely coupled is to use interfaces or contracts, like:

```<code>public void RegisterOrder(Order order)
{
   // Finding a list of all IOrderProcessors.
   // Looping over each, calling orderProcessor.Process(order);
}
</code>```

However, it has two problems:

We can't use interfaces over SOAP and HTTP (we don't have access to other subsystems' DLL files)

Those need to run in a specified order (rule engine the first one)

What should we do here? What are the known patterns and practices?

答:
There are some way to solve your problems:

As above ,use Message queue to loose all modules.You can use Pub/Sub model to loose requester and responser. MQ is a async architecture.

Use SOA.SOA is a architecture that use SOAP and XML to export service.Every service supply a SOAP and xml segment. The registerOrder service can be implemented with a xml that combine some xml segment that supplied by other services.
SOA is a xml file.You can easy edit it. SOA is a sync architecture.Sync architecture maybe have performance problem when request flood in.

Use workflow(BPM).You can use some workflow engine to organize your bussiness logic.Workflow is also a XML file.You can easy edit it. I suggest that you use JBPM as your workflow engine.
Workflow generally use a database recorder to track a workflow instance.So a workflow instance can be alive forever.
If you have atomic transactions,you only need set some process in workflow.When workflow has finished,your  atomic transactions always be consistency.

Workflow is also a async architecture.

I suggest that you use workflow(for example JBPM) to combine your services.As far as know,most of order system use workflow engine.