问:
Attributing credit for programming languages used
I'm working on a website and was hit with the thought of "do I need to give credit for the languages I'm using to build my website with?" I wasn't able to find any sort of licenses for HTML, CSS, or JavaScript and I'm a bit confused on the wording of PHP's license.

My question is: Do I need to specify somewhere on my website (externally or internally) that I'm using HTML, CSS, JavaScript, PHP, and MySQL (and attribute credit, linking to their licenses if they have one, etc)?

答:
IANAL ... etcetera.

This is not a licensing concern.  Most of the technologies you listed have no licensing implications whatsoever.  The others (PHP and MySQL) have open source licenses that don't require any acknowledgement to be displayed.

The answer is No.

I wasn't able to find any sort of licenses for HTML, CSS, or JavaScript ...

These are all open standards, and the copyright statements for open standards don't place any constraints on what you can do with implementations.  They only relate to the text of the standard itself.  (If you want to find them, the best place to look is in the specifications themselves.)

... and I'm a bit confused on the wording of PHP's license.

We can only help you with that it if you say what you find confusing.  (It looks pretty straightforward to me.)


问:
What should every programmer know about programming?
Please, stay on technical issues, avoid behavior, cultural, career or political issues.

答: Code Complete 2 - cover to cover</p>

ContentLicense: CC BY-SA 2.5

Body: Code Complete 2 - cover to cover


问:
Do preprocessor defines slow down build times?
I have a very large c++ project and I'm trying to decrease build times. I've been religious about forward declaring and only including files which are used. However I have many preprocessor defines which are setup in the project files (ie not in cpp or header files) so that I can keep them all in a central location for my different build configurations. Is it possible that this could increase build times? Would moving the preprocessor defines to a header file so they will only be included where needed speedup the build time?

It seems like the build time would be faster if the preprocessor didn't need to scan and replace the defines for files that don't use any of them, but I'm not sure if it's worth the effort.

答:
Unused macros that are specified on the command line of the compiler (through -D options) should not have any measurable impact on build times.
The parsing of command line arguments is insignificant compared to the time it takes to compile even a smallish source file and the compiler can't skip the preprocessing step anyway because there will invariably be some #include-s to process and some macros to expand.

ContentLicense: CC BY-SA 3.0


问:
When to write tests for a new class using BDD?
I've been practicing behaviour driven development (BDD). I understand that you have to write tests that test the behaviour of the code, and this will allow the design of your code to evolve and take shape.

When doing BDD and I find I need to refactor my code into a better design, and that refactor happens to involve extracting some code into a new class, when do I start writing tests for that new class?

Or are tests not needed for that class at all since it's a implementation detail and the behaviour of it should already be tested with the existing test coverage?

答:
I'm guessing you're refactoring because the class is violating SRP, i.e. it's got an extra feature that doesn't belong there. So, what's going to happen is that the feature is going to move from one existing class to a new class. The way I've handled this in the past is:

Check I've got atomic tests that cover that feature.

Refactor and extract the class. At this point the atomic tests become integration tests.

Refactor/move those tests, so that they're no longer integration tests on the original class, but atomic tests on the new class

Fix any existing tests on the old class that now have dependencies on the new class that need mocking.

The way I look at this is the number of features and tests in your codebase has remained the same, they've just been reorganised.


问:
OO - are large classes acceptable?
Despite many years in IT, I still struggle with OO design. One particular problem I seem to keep ending up with is large classes, often containing many hundreds of lines of code.

The OO world talks a lot about SRP, and I could argue that these large classes I end up with are each handling a single responsibility. The complex nature of the app (a scientific data processing system) means that one of these responsibilities requires an awful lot of code! E.g. a class might have a single public method Calculate(), but there could be 15-20 or more private methods to support this operation.

Where possible I will extract methods into separate classes for re-usability, but often there is little or no scope for this. Part of me says I should split these large classes up purely to improve readibility (e.g. grouping similar methods into their own classes), but the times I've done this feels like a wasted exercise - all I've really done is spread the methods around, created more class dependencies, and made things a little more difficult for other devs to find stuff.

But then I read articles where developers talk about how all their classes are small enough to fit on the screen without scrolling, and I worry that I'm doing something wrong! In a previous job, I worked on a system where it had been OO'd to the extreme, and it was common to see classes containing just one method, often with no more than one or two lines of code. Personally I found this difficult to find my way around the code-base and to debug, and for this reason (and sheer number of classes) I could argue that it becomes more difficult to maintain - not the aim of good OO design. I guess it's down to personal taste.

So, is it acceptable to have large classes, or can you suggest other ways that I could deal with them?

答:
have a single public method Calculate(), but there could be 15-20 or more private methods to support this operation.

That does not sound very "large" to me - as long as your 15-20 methods have a reasonable size. At least, not in general. However, to find out if your classes are reasonably-scoped, you will have to show them to another experienced developer and discuss it with him.

But then I read articles where developers talk about how all their classes are small enough to fit on the screen without scrolling, and I worry that I'm doing something wrong!

Don't worry: as long as your methods are small enough to fit on the screen. Okay, some people, including myself, think that's still too long. If you apply SRP and SLA ("single level of abstraction" principle, see, for example, here) to methods, they will typically become shorter than 20 lines.

The more important thing you should ask yourself is: do you suffer from maintainability problems? Do you often need days to find a specific bug because you have trouble isolating the problem due to the complexity of your code? If the answer is "yes", then your classes are probably too large. If the answer is "no", then don't worry about the size of your classes just because you "read some articles of some OO experts". Find our what works for your case.

Title: OO - are large classes acceptable?


答:
Some classes are inevitably larger than others so this wouldn't immediately set any alarm bells ringing. However, you may wish look at your class design again if any of the following are true:

You have a class that forms the whole (or large part of the) program

There are large chunks of code within the class relating to a
specific concern

Similar code is present in other classes

The same parameters with basic data types are being passed around
from method to method e.g.

DoSomethingToThis(string name, int rating, datetime when, bool flag)
  {...}

DoSomethingToThat(string name, int rating, datetime when, bool flag)
  {...}

DoSomethingToTother(string name, int rating, datetime when, bool flag)
  {...}

Depending on your implementation language there may also be other ways of breaking up the code e.g. code regions and namespaces.

Title: OO - are large classes acceptable?

Body:
Despite many years in IT, I still struggle with OO design. One particular problem I seem to keep ending up with is large classes, often containing many hundreds of lines of code.

The OO world talks a lot about SRP, and I could argue that these large classes I end up with are each handling a single responsibility. The complex nature of the app (a scientific data processing system) means that one of these responsibilities requires an awful lot of code! E.g. a class might have a single public method Calculate(), but there could be 15-20 or more private methods to support this operation.

Where possible I will extract methods into separate classes for re-usability, but often there is little or no scope for this. Part of me says I should split these large classes up purely to improve readibility (e.g. grouping similar methods into their own classes), but the times I've done this feels like a wasted exercise - all I've really done is spread the methods around, created more class dependencies, and made things a little more difficult for other devs to find stuff.

But then I read articles where developers talk about how all their classes are small enough to fit on the screen without scrolling, and I worry that I'm doing something wrong! In a previous job, I worked on a system where it had been OO'd to the extreme, and it was common to see classes containing just one method, often with no more than one or two lines of code. Personally I found this difficult to find my way around the code-base and to debug, and for this reason (and sheer number of classes) I could argue that it becomes more difficult to maintain - not the aim of good OO design. I guess it's down to personal taste.

So, is it acceptable to have large classes, or can you suggest other ways that I could deal with them?


问:
How to store / not to store passwords
I am building an web site which will allow users to aggregate the information stored in their online profiles ("data feeds") in one place.

I am wondering - what is the accepted (from a secureness point of view) way to store user name / password information in a my database?

Normally I would derive a salted-hash value from a password and would store this, but that obviously would not work in this case, as "data feeds" websites would need an actual password.

Storing the credentials it in a clear text is not an option, as it would be a huge security risk.

Not storing passwords in a database, asking users to type them in at the beginning of each session and then keeping them in a in-session memory does not seem like a viable option either, as it would be too much trouble for users to enter the same passwords many times again and again.

So far it seems that the only option is to encrypt passwords somehow, but I don't know what are the best design patters for such option.

Or perhaps there is way to deal with that problem, I haven't even considered ...

What would you recommend?

答:
As you are effectively providing a (limited) online password manager service, you could have a look at how the off-line password managers store the passwords for their users.

My napkin-design for such a feature would be to store the password in the database using a symmetric cryptographic encryption, where the key is either provided by the user or derived from a password that the user provides.
This way, the user only has to provide a single password at the start of the session, regardless of the number of data feeds that get unlocked that way.

Title: How to store / not to store passwords


答:
The general way is to use a one-way hash (plus salt, of course, and when I say "hash" here you should always mentally append "plus salt"), store the hash in the database.  Then, when the user enters a password, you hash that too (using the same hashing function) and compare hashes.

However, I would not recommend that you build your own security system.  The reason why is that security is hard, you don't know more about it than those that have already built security systems (and the fact that you're asking this question confirms it), and you shouldn't be thinking that you can do a better job than them.

Does your web server software provide a security system?  Does your OS provide a security system?  If so, and if you can, then use those instead of rolling your own.  They're tried and tested, they've been worked on by security experts, they're designed to meet requirements of security certification, and no matter what you think, you can't write a better one yourself.

If this is not an option then look to use something like OpenID, Google, whatever.  Just use something that's already been proven to work and that has the bugs (and not to mention security risks) already worked over.

Title: How to store / not to store passwords

Body:
I am building an web site which will allow users to aggregate the information stored in their online profiles ("data feeds") in one place.

I am wondering - what is the accepted (from a secureness point of view) way to store user name / password information in a my database?

Normally I would derive a salted-hash value from a password and would store this, but that obviously would not work in this case, as "data feeds" websites would need an actual password.

Storing the credentials it in a clear text is not an option, as it would be a huge security risk.

Not storing passwords in a database, asking users to type them in at the beginning of each session and then keeping them in a in-session memory does not seem like a viable option either, as it would be too much trouble for users to enter the same passwords many times again and again.

So far it seems that the only option is to encrypt passwords somehow, but I don't know what are the best design patters for such option.

Or perhaps there is way to deal with that problem, I haven't even considered ...

What would you recommend?


答:
I think what you are looking for is what is known as SSO (Single Sign On):

Source: Wikipedia

a property of access control of multiple related, but independent software systems. With this property a user logs in once and gains access to all systems without being prompted to log in again at each of them. Conversely, Single sign-off is the property whereby a single action of signing out terminates access to multiple software systems.

The challenge of implementing single sign on is that you have to provide the implementation details for each unique type of authentication mechanism that all systems seem to use.  Typically in an OOP application one would write Authentication Providers that know how to retrieve credentials and interface with outside system to where your system initiates and performs the "handshake", and then retains this trust for the remainder of the session.

A one-way hash like a salted digest won't work but you already know that.  Strong two-way encryption is necessary, but you will need a key to perform this.  Store the encrypted credentials in the database on a separate machine and lock down that servers firewall only exposing the required ports.  Keep the key on the application server in an obfuscated non-obvious way.  Keeping the key on a separate machine from the one that houses your database and encrypted credentials reduces the risk if a single machine becomes compromised.  Any additional steps you can think of that will further obfuscate this will help with security.

EDIT: User Bart Van Ingen's suggestion about the key is the ideal situation, where the user provides the key when they log in, absolving you of the responsibility of maintaining the key/keys on your own system.

Title: How to store / not to store passwords


答:
Do you write tests to maintain your code? If not, then you'll find your code will probably become much more atomic. However, I'd really focus on what 'Doc Brown' says regarding maintainibility. That's the key thing.

One large class with lots of small methods is probably easier to work with then lots of small classes each with one method. I've recently done a re-write at work taking one large God class of almost 9,000 lines of code and splitting it down. There are still classes that have almost a thousand lines of code in them. It sounds pretty dire when written down like that but at work we're finding it much easier to find and understand things. There are more classes now and more folders but it's tidier.

There is a gap between theory and practice. What looks and sounds right in theory, and usually demonstrated with a simple example, doesn't work when applied to a large real application.

Title: OO - are large classes acceptable?


答:
IANAL and all that, if you want legal advice consult a lawyer.

That said, there are three areas of law here that are of interest: Copyright, Patents, and Trademarks.

The easy one first: trademarks. Trademark law has the goal of preventing misrepresentation: when you sell something, the buyer associates your brand with certain qualities (or lack thereof); selling the thing under a competitor's brand will harm the customer (because they don't get what they think they're getting), and also the competitor (because you can leverage the brand image of your competitor's quality products to sell cheaper rip-offs). Trademark law is not about forcing people to credit anyone or anything, but rather about keeping them from "crediting" wrongly. For example, if Foobar were a trademarked programming language, it would probably be illegal for you to market one of your C++ programs as "built with Foobar"; and even if you had built it with Foobar, you'd still have to be cautious in whether or not you could advertise this fact.

Then, copyright. While the documentation and specifications of a programming languages are copyrightable, as well as the source code of a reference implementation, the language itself is not, and programming in it does not constitute a derived work. If Foobar were a programming language, and its specifications, official documentation, and reference compiler were published under extremely restrictive licenses, then you would still be free to publish your own Foobar code, and you would retain full copyright over it. And because no copyright would apply, you would be under no obligation to credit or not credit whatsoever.

Compiled binaries are trickier, because compilers usually link hard-coded snippets into your binaries, and those snippets, being part of the compiler itself, are copyrightable, which makes your binary a derived work. Whether or not you can freely distribute your binaries, then, depends on two things: are the snippets introduced by the compiler significant enough to be considered copyrightable (this is a gray area, really), and if so, what does the compiler's license say about them. In most cases, though, the compiler author explicitly allows shipping your binaries, and draws well-defined lines around those parts of the development tools / SDKs that you are allowed to redistribute (often, this part is referred to as a 'redistributable').

Libraries, of course, are a different beast: a library is typically included in a binary distribution, and as such, it becomes part of it, and the binary distribution becomes a derived work of the library, which means the library's original license governs the conditions under which you may distribute your binary. This is also the case for standard libraries that come with typical programming languages.

Running code on a server is yet another situation. Just putting your code or binaries on a web server and running it there does not constitute publishing, and as long as your code's output does not serve any significant (as in, significant enough to be copyrightable) parts of the toolchain itself, again the language implementation's copyright does not apply. Serving image files with apache, for example, does not make the HTTP responses I serve derived works of apache itself. Serving apache's own source code with apache however does. Also note that, similar to the library issue in binary distributions, responses generated by a server often contain significant portions of server-side libraries; for example, an ASP.NET application might serve widgets that render using hard-coded template code, and if that template code is significant, copyright might apply. (To my knowledge, however, the .NET license agreements explicitly disclaim copyright over such responses.)

And then there's patents. The official stance is that patents are designed to support innovation by rewarding someone who has developed a useful solution or procedure and is willing to invest money in developing it to the market by giving them exclusive rights to using this idea for a limited amount of time. In practice, however, it leads to a situation where 'vultures' go and patent everything they can get their hands on, and then sue people for applying obvious solutions to common problems. This is not a problem you'll solve with crediting though; whether you credit or not, whether it's based on your own original work and research or not, it doesn't matter at all in the face of patents: all that matters is whether someone holds a patent on whatever technique you're using, and whether they are willing to sue you over it.

So, most likely, you won't have to credit at all. Especially with open source tools, however, it is considered a nice gesture to credit the (free) tools you used anyway: it doesn't cost you much, and it helps make the tools better in the long run (free advertising == more users == more testers and more contributors == more bugs found & fixed and more features implemented == better software). So even if the license doesn't mandate crediting, or the situation is such that copyright does not apply (which is generally what you're looking at), you might still want to give credit. Not because you have to, but because it's a nice helpful thing to do.

Title: Attributing credit for programming languages used

Body:
I'm working on a website and was hit with the thought of "do I need to give credit for the languages I'm using to build my website with?" I wasn't able to find any sort of licenses for HTML, CSS, or JavaScript and I'm a bit confused on the wording of PHP's license.

My question is: Do I need to specify somewhere on my website (externally or internally) that I'm using HTML, CSS, JavaScript, PHP, and MySQL (and attribute credit, linking to their licenses if they have one, etc)?


问:
How do I reduce the number of WCF config files in a SOA?
After embracing the whole SOA thing, I've found that I'm gradually drowning in a sea of web.config and app.config files.

As an example, one system has 2 services that it interacts with. Each service has 3 config files - one for dev, one for staging and one for production. That's 6 config files. Then each application (3 different ones) that use these services needs three config files again, that's another 9. So that's 15 config files just for a relatively simple system.

How can I go about simplifying my configuration? Is there a better way of doing this? Should I try to make my config files environment agnostic? Should I investigate the whole WCF Discovery? Should I use the web.config transformation syntax?

答:
You could put the config into code instead and set different values for the environments that depend on a registry key (or something) that is set globally on each environment's servers.

Migrating the settings from the config files to code is pretty easy (at leats I started writing WCF services using all-code configuration until the architects decided that 15 config files were the way to go... I guess it was easy for them to decide that as they didn't have to manage them)


问:
What should I include in my repositiory from IDE projects
I want to add a project which in this case is created in Netbeans but this question is general for most IDE's. It's simply, what should I include in my repository. For example Netbeans creates a nbproject folder, eclipse creates a .settings folder etc. should I include these in my repository, what are the advantages/disadvantages of including or not including project specific settings. </p>

<p>In this case it's a personal project so I don't imagine that other people will start working on it, but it would be nice to add the bare minimum of project settings so the project itself will be easy to start work on different machines. </p>

答:
If it's a personal project, I say store the settings in source control. Personally, nothing kills my motivation more for a project than setting up a development environment again.

When more people are involved, I don't put these things in source control. On my team, we have a mix of IntelliJ, Sublime Text, and Eclipse being used. IDE files just add clutter, and result in pulling in commits to those files from other people for an IDE you don't use.

Also, your project shouldn't be dependent on the IDE anyway. A build server won't be booting up Eclipse to compile your product, so it should already be IDE-free. A more minor point: it eliminates personal organization within the project. For example, in IntelliJ I like to use many modules within our project. No one else using IntelliJ worries about this because we don't store the .iml (module) files.

If your team is using the same IDE then it's better, but then someone commits a bad .classpath entry because they used an absolute path. Now everyone using the IDE worries about it.

Sure, the downside is that there is more setup when someone checks out the project. I think it's worth it. We use Ivy for dependency management and have information on setup, dependencies, etc. Despite this up front cost, I think it's worth it to keep IDE settings out of source control.


问:
Does responsive web design go against the Separations Of Concerns principle?
I'm wondering how responsive design plays along with the Separations of Concern principle, in respect of how we're allowing a single implementation behave for multiple presentation devices (mobile, tablet, browser sizes etc.). Is it breaking the principle?

If I make changes to a web page that I know is behaving responsively and should work on 5 devices for example, am I not making the development extremely difficult due to possible regression that can occur from a single place in the software?

Sure it's making me write less code and work a lot faster on multiple devices, but now each one of my pages requires potentially much more thorough testing, which is the cost I could move to not using a responsive web framework and maintaining separate implementations of a page.

答:
I do not think it violates separation of concerns since the CSS uses media queries to separate the style for a particular screen size. The media queries encapsulate the code for a particular screen size.

I think, instead of thinking about responsive design as working for X number of devices, responsive design should be thought of as working for all screen sizes. Its the same web page, just styled to the screen size.


答:
How you're currently looking at responsiveness goes against the separation of concerns principle.  Your question presumes that responsiveness is a single responsibility that only belongs to one component.

I'd suggest that responsiveness is an attribute / responsibility that can be applied to multiple components.  For the sake of my example, I'm assuming a generic MVC | MVP | MVVM type pattern.

The View most certainly has a hand in the responsiveness of the application.  The UI elements and logic that you use all dictate how the View will perform.  So the View is responsible for the responsiveness of the UI elements.

The Controller also has a hand in application responsiveness.  The types of data structures and how the business logic is crafted will affect performance.  So here, the Controller | Presenter | ViewModel also have responsibility for responsiveness.  But this responsibility is over different elements than what the View is responsible for.

Finally, the Model is responsible for the data access / service calls.  There are obvious performance considerations in how the data is retrieved and presented to the middle layer.  But again, this is a different element that must also be responsive.

Responsiveness as a property is not the single responsibility of any one component.  All components must be responsible for their own crafting in order to contribute to the overall application.  A great UI and Controller can be rendered useless by seemingly interminable data requests.

As far as testing, using a tiered approach still works in your favor with respect to overall effort and responsiveness.  If you have 5 devices and wrote individual layers for each device, you would have 15 components to test.  Using the MVC* pattern allows you to remove 8 components from testing since you have a common Model and Controller.  If those two layers perform their share of the work in being responsive, then you only have to test them once.  You can then focus your remaining efforts on the 5 Views.

Title: Does responsive web design go against the Separations Of Concerns principle?

Body:
I'm wondering how responsive design plays along with the Separations of Concern principle, in respect of how we're allowing a single implementation behave for multiple presentation devices (mobile, tablet, browser sizes etc.). Is it breaking the principle?

If I make changes to a web page that I know is behaving responsively and should work on 5 devices for example, am I not making the development extremely difficult due to possible regression that can occur from a single place in the software?

Sure it's making me write less code and work a lot faster on multiple devices, but now each one of my pages requires potentially much more thorough testing, which is the cost I could move to not using a responsive web framework and maintaining separate implementations of a page.


问:
NSException in init when having a custom designated initialiser?
I have a custom View Controller that is a subclass of UIViewController that requires a data object to be set up properly. Without this object, showing the VC doesn't make any sense.
So I created a custom initialiser that requires this object to be passed as an parameter/argument.
There is also no "default" data object, so there is no point for me to override the inherited init, and implement passing this default data object internally from init to custom init.

Instead I am raising an exception that explains that you need to add an object in the designated custom initialiser instead of using the inherited init method.

However, my colleagues object that I just should return nil in the overridden standard init.
However they are not giving me any proper argument, they only tell me that this is the convention. Which is not an argument for me strictly speaking. I won't do things just because they are tradition.

Why return nil and why raising a custom exception is wrong?

答:
Convention on platforms is important. It's how you can move from one code base to another with the least effort. New code should be named and should behave as predictibly as possible.

You wouldn't just have one class in, say, a Java program that uses underscores in its method and variable names rather than camel case. I'm sure you wouldn't break that rule, but it's just a convention, too.

Convention plays an even bigger part in Cocoa when you're using ARC. Method names are used to help manage memory -- Apple took a convention and turned it into a rule.

Your exception case is similar. Most Cocoa programmers would not expect a Cocoa program to raise an exception in its init method. The convention is that it returns nil on error.

There is certainly a case for breaking rules and conventions, but you have to be careful and only do it in truely exceptional circumstances. A class with a mandatory property is a pretty common case and not one, I think, that warrants breaking the convention.


问:
Chrome's multiple process per each tabs
I am wondering what is the purpose of Chrome using multiple processes for each tabs? I asked this to C++ chat room and one responded it is a product of laziness. I personally believe this is an example of "Distributed processing" like in Erlang programming language. What exactly is it?</p>

答:
It's simply to completely separate failure of each different tab and plugin.

When one fail, whatever the way it fails, only this one will crash. The monitoring process will just report that it failed and will be able to reload it.

C++ have shared memory by default and an exception system which makes easy to crash the whole application if one part isn't working correctly. It completely solves this problem.

It also allows easier sandboxing of plugins as they have their own process so they benefit
from the same advantage: if they fail, Chrome don't.

It might also have some advantages on memory management as it's easier for the OS to allocate only for one process use of memory instead of several modules working with the same memory which basically means fragmentation and slow-down when the memory allocated gets bigger.

It's about isolating each application resources management.

Basically Chrome is designed more like a decent OS for web applications (whatever that mean).

Title: Chrome's multiple process per each tabs


问:
Building Websites: Fast Debugging Without a Browser
Is there a methodology to debug websites without a browser?

Normally I use a web browser to view a results page. The slow debugging process confuses me a little. To correct an error I need to switch to a code window (which takes some time). Then I correct the error and return to a browser window, press F5, and wait for the page to update (which could take 10 secs). It could take only 1 second if the page automatically updates after I correct my code.

I'd like a tool where I could see my code and a corresponding result page on one screen. I need a tool that updates an open page upon code changes. I would also like to edit both server and client sides (generally JavaScript), and see my changes as soon as possible, without unnecessary 'user' manipulations.

Update.

I need a tool which controls source files. It must reload a browser when any source file is changed. A good feature can be reloading with cache clear (for example if a changed file has specific extention such as .js, .css).

答: Have you tried using (eclipse) Springsource Tool Suite with maven and embedded Tomcat?  On my web projects I have a "Run configuration" with maven goals of clean tomcat7:run.  I edit my JSPs and hit refresh on the browser.  Server side java code I have to stop the server and rerun the above - takes seconds, 2-3 mouse clicks.


问:
What is the reason for using lowercase for the first word in a local variable (eg, employeeCount, firstName)
I take a good deal of criticism from other programmers due to my use of full proper casing for all my variables.  For example, your typical programmer will use employeeCount for a variable name, but I use EmployeeCount.  I use full proper casing for everything, be it a void method, return method, variable, property, or constant.  I even follow this convention in Javascript.  That last one really rustles people's jimmies.

The typical reason given as to why I shouldn't follow this "non-standard" casing convention is because full proper case should be reserved for properties and void methods.  Local variable and methods that return a value should have the first word in lowercase like int employeeCount = getEmployeeCount().

However, I don't understand why.

When I question this, it seems that I just get an arbitrary answer of that's the standard.  Whatever the answer is, it usually always boils down to That's just the way it is and I don't question it.  I just follow it..  Arbitrary answers are never good enough for me.

Ever since my early days of programming Excel 97 macros with the Office IDE, I've never needed a casing convention to tell me whether or not something is a local variable or property.  This is because I've always used a very intuitive naming convention.  For example, GetNuggetCount() clearly suggests a method that goes somewhere an gets a count of all the nuggets.  SetNuggetCount(x) suggests that you are assigning a new value to the count of nuggets.  NuggetCount all by itself suggests a property or local variable that is simply holding a value.  To that last one, one may be tempted to say, "Ah ha!  That is the question.  Property or variable?  WHICH IS IT?"  To that, I'd reply with, "Does it really matter?"

So here's the tl;dr;:  What are the objective, logical, non-arbitrary reasons to use lowercase for the first word in your variable or return method?

Edit:  For MainMa

Replace this code with the first code sample in your answer and see how well your argument holds up:

```<code>public void ComputeMetrics()
{
    const int MaxSnapshots = 20;

    var Snapshots = this.LiveMeasurements.IsEnabled ?
        this.GrabSnapshots(MaxSnapshots, this.cache) :
        this.LoadFromMemoryStorage();

    if (!Snapshots.Any())
    {
        this.Report(LogMessage.SnapshotsAreEmpty);
        return;
    }

    var MeasurementCount = Measurements.Count();
    this.Chart.Initialize((count + 1) * 2);

    foreach (var s in Snapshots)
    {
        this.Chart.AppendSnapshot(s);
    }
}
</code>```

答:
Language (with its formal aspect and conventional) is important for organizing your thoughts, it has power over your ways of thinking. So it just a pain to transit from one style to another.

Low case and upper case symbols have big semantic differences in Haskell, also they differs lightly in Scala and I've used both of them. Other languages I use make no difference between this two kinds of identifiers, but keeping thoughts in the way Haskell perceive identifiers just much easier for me than to fragment my mind for different languages.


问:
Is web session "Bad Design"? Why?
the other day I was discussing with a colleague and he came out saying that using user's session in a web application is just wrong. I replied that it could be wrong depending by the information you are storing, otherwise why should a web session service even being provided by Microsoft (we were talking about ASP.NET).

He replied to me, again, that even in MS they could easily reply me that it was bad design. And that he could show me some white-papers demonstrating that.

Unfortunately I have no opportunity to contact this guy anymore, but I would really like to understand more about his point of view. Does anyone have information/points of view about that here?

答:
I don't think he meant "Bad design" so much as "Bad practice."  Generally speaking, a web application should be as stateless as conceivably possible.  Even though, for example, you may need to know user information in order to authorize page viewing, that information could be saved on the client machine in the form of a cookie and the server simply validates the user information each and every time.

That would be ideal, but you can't always count on the client being able to save cookies.  Furthermore, it involves validating the user in a stateless fashion, which potentially involves querying information from the database for a simple page request.  Often times it's just simpler to save such information in the session.

However, once you've crossed the Rubicon, a lot of programmers are tempted to save not only authentication info in the session but many other things as well.  This is an anti-pattern and tends to make your web application heavily dependent upon state, which is precisely what was supposed to be avoided in the first place.

Some programmers would hinge on technology like Spring (if you're using Java) to untangle what would otherwise be a mess of dependencies, but I would argue that that only makes it easier to create dependencies rather than eliminate them.  Such technologies should aid your development, not make your anti-pattern less of a problem.

Therefore, a good rule of thumb is that if you can write it stateless, it is probably a better idea to do so or you risk to fall into this trap.  Obviously you're going to run into situations in which this is required, but generally speaking, you should only save information that would otherwise be difficult to reacquire.

Title: Is web session "Bad Design"? Why?


问:
What's the computational complexity of the Groovy unique() method?
Question 1

What's the computational complexity of the Groovy unique() method?

Question 2

How could I have figured it out by myself? The unique() method is defined in the class DefaultGroovyMethods. The source code can be found here: org.codehaus.groovy.runtime.DefaultGroovyMethods. Can you point me to the piece of code which illustrates the answer to question 1?

答:
As Lernkurve pointed out in the comments, the implementation given in Groovy's source code appears to be O(n^2).

public static <T> Collection<T> unique(Collection<T> self, boolean mutate) {
    List<T> answer = new ArrayList<T>();
    for (T t : self) {                    // << Outer loop over each item
        boolean duplicated = false;
        for (T t2 : answer) {             // << Inner loop over each found item
            if (coercedEquals(t, t2)) {
                duplicated = true;
                break;
            }
        }
        if (!duplicated)
            answer.add(t);
    }
    if (mutate) {
        self.clear();
        self.addAll(answer);
    }
    return mutate ? self : answer ;
}
```

The outer loop ensures that the time complexity is at least O(n), because it will grow linearly as the input list grows. Likewise, the inner loop taken by itself is O(n). For each item in the input list, it then loops over each item that it's registered into the "answer" list to see if that item is already contained. Put them together and you've got an O(n^2) function.

As I pointed out in the comments, there are a few ways you might get better performance out of this, for large sets. If you're willing to spend a bit more memory, you can use a Hash set of some kind to register whether or not an element has already been included. These generally have an O(1) lookup time to check if the current item is unique to the list.

Alternatively, sorting the input list (if it is sortable) with a good sort function (most of those included in a language's standard library will be O(n log n)) can help, assuming you don't care about the order of the "unique" output list. This way you can be sure that duplicate elements will always appear in sequence with each other, and it becomes trivial to reject them from the output.

Body:
As Lernkurve pointed out in the comments, the implementation given in Groovy's source code appears to be O(n^2).

public static <T> Collection<T> unique(Collection<T> self, boolean mutate) {
    List<T> answer = new ArrayList<T>();
    for (T t : self) {                    // << Outer loop over each item
        boolean duplicated = false;
        for (T t2 : answer) {             // << Inner loop over each found item
            if (coercedEquals(t, t2)) {
                duplicated = true;
                break;
            }
        }
        if (!duplicated)
            answer.add(t);
    }
    if (mutate) {
        self.clear();
        self.addAll(answer);
    }
    return mutate ? self : answer ;
}

The outer loop ensures that the time complexity is at least O(n), because it will grow linearly as the input list grows. Likewise, the inner loop taken by itself is O(n). For each item in the input list, it then loops over each item that it's registered into the "answer" list to see if that item is already contained. Put them together and you've got an O(n^2) function.

As I pointed out in the comments, there are a few ways you might get better performance out of this, for large sets. If you're willing to spend a bit more memory, you can use a Hash set of some kind to register whether or not an element has already been included. These generally have an O(1) lookup time to check if the current item is unique to the list.

Alternatively, sorting the input list (if it is sortable) with a good sort function (most of those included in a language's standard library will be O(n log n)) can help, assuming you don't care about the order of the "unique" output list. This way you can be sure that duplicate elements will always appear in sequence with each other, and it becomes trivial to reject them from the output.


答:
Controls and storing session state on a page are essentially a hack. Is the case of MS - a necessary one as they wanted to be able to provide a development environment where you could design pages as you can in winform environments.

MS have themselves moved towards the MVC architecture (latest version - MVC 4) which is more of a return to what the protocol actually should be - stateless.

There are situations where storing state is still handy but it should be understood that this is the exception rather than the rule.

Title: Is web session "Bad Design"? Why?

Body:
the other day I was discussing with a colleague and he came out saying that using user's session in a web application is just wrong. I replied that it could be wrong depending by the information you are storing, otherwise why should a web session service even being provided by Microsoft (we were talking about ASP.NET).

He replied to me, again, that even in MS they could easily reply me that it was bad design. And that he could show me some white-papers demonstrating that.

Unfortunately I have no opportunity to contact this guy anymore, but I would really like to understand more about his point of view. Does anyone have information/points of view about that here?


答:
I think you're confusing two different topics: 1) sessions and 2) the page model of asp.net webforms

A web session is necessary for authentication a user. Ideally a session should only be used for this purpose.  You shouldn't store user data in a session (whether it be on the server, in a cookie, or as asp.net/webforms does it: within the page itself). No one should say that a web session is bad, but rather, storing user data in a session is a bad practice.  The reasons for not storing user data on the server include the same reasons to avoid global variables.  Storing user data in cookies or in the page can introduce security issues.  Using the page model of asp.net also doesn't adhere to the stateless nature of the web. You could do a search to find out more about why webforms is a bad design.  Sessions on the other hand are a necessary part of web applications.

Title: Is web session "Bad Design"? Why?


问:
Game to decide which team member gets the window seat in a fair way
During team formation, we have a conflict where 2 developers both really want the same coveted window seat with a lush view of a creek & the woods.  What sort of game / activity can we place them in that will:

Decide who gets the seat

Provide a random (not skill based) chance of winning

Allow both team members to participate in the selection

Not be a single player game masquerading as a two player game
(drawing straws for example - the outcome is based off of the first
player's actions when there's only 2 people)

答:
Clearly, the only fair way to decide is the time honored tradition of Rock, Paper, Scissors. Most places will play a Best out of 5 format, but if you really want to see some competition you may go up to Best out of 7 or even Best out of 9.

The other option is a duel, but I doubt that you only want one living developer in the long run, so that's probably not an option.

Edit - I just wanted to point out that drawing straws is actually fair, as the first person has a 50/50 chance of picking either of the two straws, which is the exact same as the second person would have.


答:
Essentially, you want to tighten your feedback loop.

To answer your direct question, there are tons of tools or plugins to automatically refresh the browser when it detects changes in your project. There are both browser-level plugins, as well as editor integrations. For example, when I save a file in vim, I can have it automatically refresh my browser window as well as run any automated tests for that given file - all without taking my hands off the keyboard.

It's concerning that it takes 10 seconds for you to see changes. You should really be doing everything you can to speed up that feedback loop. Your local webserver takes 10 seconds to generate a file?  Fix that.

If you split your code up enough, you can adopt TDD - this means:

Splitting your code into small enough units that they can be run and tested in isolation

Mocking out any dependencies so everything is basically instant

Write tests that fail

Satisfy tests with minimal code to pass

Refactor/clean up your mess as you go

This takes your feedback loop to <1s (without blocking your workflow) whenever you change a file. This is the sort of case that TDD Is meant to help: getting feedback as fast as possible.

Even if you don't adopt testing, there are similar ways to get a tight feedback loop between browser integration, automated scripts and simplified versions of your system-under-test. Your goal is simply to minimize the steps required to ensure your code is working. The longer the delay in feedback, the higher chance of programming by coincidence.

Title: Building Websites: Fast Debugging Without a Browser

Body:
Is there a methodology to debug websites without a browser?

Normally I use a web browser to view a results page. The slow debugging process confuses me a little. To correct an error I need to switch to a code window (which takes some time). Then I correct the error and return to a browser window, press F5, and wait for the page to update (which could take 10 secs). It could take only 1 second if the page automatically updates after I correct my code.

I'd like a tool where I could see my code and a corresponding result page on one screen. I need a tool that updates an open page upon code changes. I would also like to edit both server and client sides (generally JavaScript), and see my changes as soon as possible, without unnecessary 'user' manipulations.

Update.

I need a tool which controls source files. It must reload a browser when any source file is changed. A good feature can be reloading with cache clear (for example if a changed file has specific extention such as .js, .css).


答: Each programmer should write a random number generator, keep track of who generates a random number first. When both programmers can generate a random number add them together if the resulting number is odd then the first programmer who completed the generator gets the seat, if even the second.</p>

Title: Game to decide which team member gets the window seat in a fair way

Body:
During team formation, we have a conflict where 2 developers both really want the same coveted window seat with a lush view of a creek & the woods.  What sort of game / activity can we place them in that will:

Decide who gets the seat

Provide a random (not skill based) chance of winning

Allow both team members to participate in the selection

Not be a single player game masquerading as a two player game
(drawing straws for example - the outcome is based off of the first
player's actions when there's only 2 people)


问:
C project avoiding naming conflicts
I'm struggling to find pragmatic real-world advice on function naming conventions for a medium sized C library project. My library project is separated into a few modules and submodules with their own headers, and loosely follows an OO style (all functions take a certain struct as first argument, no globals etc). It's laid our something like:

```<code>MyLib
  - Foo
    - foo.h
    - foo_internal.h
    - some_foo_action.c
    - another_foo_action.c
    - Baz
      - baz.h
      - some_baz_action.c
  - Bar
    - bar.h
    - bar_internal.h
    - some_bar_action.c
</code>```

Generally the functions are far too big to (for example) stick some_foo_action and another_foo_action in one foo.c implementation file, make most functions static, and call it a day.

I can deal with stripping my internal ("module private") symbols when building the library to avoid conflicts for my users with their client programs, but the question is how to name symbols in my library? So far I've been doing:

```<code>struct MyLibFoo;
void MyLibFooSomeAction(MyLibFoo *foo, ...);

struct MyLibBar;
void MyLibBarAnAction(MyLibBar *bar, ...);

// Submodule
struct MyLibFooBaz;
void MyLibFooBazAnotherAction(MyLibFooBaz *baz, ...);
</code>```

But I'm ending up with crazy long symbol names (much longer than the examples). If I don't prefix the names with a "fake namespace", modules' internal symbol names all clash.

Note: I don't care about camelcase/Pascal case etc, just the names themselves.

答:
The usual convention for C libraries is to use the library name as prefix for externally usable names, e.g.

```<code>struct MyLibFoo;
void MyLibAFooAction(...);
</code>```

For library-internal names that must still be accessible in multiple units of the library, there is no strict convention, but I would use a prefix of the library name and an indication that it is an internal function. For example:

```<code>struct MyLibInternalFooBaz;
void MyLibInternalFooBazAction();
</code>```

I agree that this can lead to names that are quite long and hard to type, but unfortunately that is the price we have to pay for not having a mechanism like C++ namespaces.
To reduce the length of the names, at the cost of some clarity, you can opt to use abbreviations in your names, but you have to weigh the advantages and disadvantages carefully.

Title: C project avoiding naming conflicts

Body:
The usual convention for C libraries is to use the library name as prefix for externally usable names, e.g.

struct MyLibFoo;
void MyLibAFooAction(...);

For library-internal names that must still be accessible in multiple units of the library, there is no strict convention, but I would use a prefix of the library name and an indication that it is an internal function. For example:

struct MyLibInternalFooBaz;
void MyLibInternalFooBazAction();

I agree that this can lead to names that are quite long and hard to type, but unfortunately that is the price we have to pay for not having a mechanism like C++ namespaces.
To reduce the length of the names, at the cost of some clarity, you can opt to use abbreviations in your names, but you have to weigh the advantages and disadvantages carefully.


问:
Connected components of a graph using Prolog
Given a corner x of an undirected Graph G I would like to ask for the connected component of x, but my first try does not work as desired. Here it is:

```<code>edge( a,b ).
edge( b,a ).

edge( b,c ).
edge( c,b ).

edge( c,d ).
edge( d,c ).

connected( X,X ).
connected( X,Y ) :- edge(X,Y).
connected( X,Y ) :- \+ edge(X,Y), edge( X,Z ), connected( Z,Y ).
</code>```

And here are my queries and the results:

```<code>| ?- connected(b,What).

What = b ? ;

What = a ? ;

What = c ? ;

no

| ?- connected(b,b).

true ? ;

true ? ;

true ? ;

no
</code>```

Why is corner b not connected to corner d? Why is corner b connected to itself three times? I am afraid of other problems I will get with more complex graphs. Are there any?

答:
Basically, you are using \+ too early (and you shouldn't be using it in the first place).

Trace through the execution of your query, and you'll see that the first answer comes from the first clause, and the next two from the second clause, but your third clause never succeeds. Why? Because you ask the system to prove that edge(b,Variable) is not true - but it is true, for instance via edge(b,a). The fact that your What would later be bound to another value if processing continued is irrelevant - at the moment you match it, it isn't bound, so the edge succeeds, and therefore the \+ fails and stops processing.

That is also the reason why \+ is the wrong approach here; to process arbitrary graphs, there is no way around programming unbounded recursion, and then you need to keep track of which nodes you've already tried so you don't get stuck in infinite loops. The easiest solution adds another parameter to the recursive case which does this bookkeeping.


问:
What are the pros and cons of HTML5, native and hybrid mobile app approaches?
I want to develop a mobile application. I recently read an article on Telerik Forum, which compares among three types of mobile application and I don't know which one should I select to begin with. Here is an image describing the pros and cons of different mobile design choices

To decide between these design choices, I would like to better understand the pros and cons of each architecture choice listed in the diagram.  What are the pros and cons of each architecture approach?

答:
To me when writing any consumer app, what is paramount to its success is user acceptance and perception of the app. Because of that four reasons to lean in favor of native apps, despite the additional costs associated with learning, training and losing WORA(write once run anywhere) are:

Faster App startup

Smoother scrolling

More consistence app ui that ties in more consistently with the rest of OS and apps

Faster App UI response

What you want above everything else is a great user experience that helps your app succeed in a cut throat market place. Of course there are exceptions especially lack of skillset, lack of time and budget. Sometimes apps are geared to a limited set of business users who may not care that much about these things.

It is reasons similar to these that Facebook ditched their app strategy in favor of native apps for IOS and android:

Please read:

Mark Zuckerberg: Our Biggest Mistake Was Betting Too Much On HTML5
http://techcrunch.com/2012/09/11/mark-zuckerberg-our-biggest-mistake-with-mobile-was-betting-too-much-on-html5/

Why Facebook Ditched the Mobile Web & Went Native With its New iOS App
http://readwrite.com/2012/08/23/how-facebook-ditched-the-mobile-web-went-native-with-its-new-ios-app#awesm=~o9jDrRefxdgnpS

Hope this helps.


答:
None of the above.  That's the space for the couch, the whiteboard (not covering the window of course) and the popcorn machine.  Programmers need shared space as well as private space.

I'm assuming you have more than 2 devs, & the others aren't asking for this space.


答:
Prefixing (well, affixing) is really the only option. Some patterns you'll see are <library>_<name> (e.g., OpenGL, ObjC runtime), <module/class>_<name> (e.g. parts of Linux), <library>_<module/class>_<name> (e.g., GTK+). Your scheme is perfectly reasonable.

Long names aren't necessarily bad if they are predictable. The fact that you are ending up with crazy long names and functions that are too big to stick with related functions in a single source file raises different concerns. Do you have some more concrete examples?

Title: C project avoiding naming conflicts

Body:
I'm struggling to find pragmatic real-world advice on function naming conventions for a medium sized C library project. My library project is separated into a few modules and submodules with their own headers, and loosely follows an OO style (all functions take a certain struct as first argument, no globals etc). It's laid our something like:

```<code>MyLib
  - Foo
    - foo.h
    - foo_internal.h
    - some_foo_action.c
    - another_foo_action.c
    - Baz
      - baz.h
      - some_baz_action.c
  - Bar
    - bar.h
    - bar_internal.h
    - some_bar_action.c
</code>```

Generally the functions are far too big to (for example) stick some_foo_action and another_foo_action in one foo.c implementation file, make most functions static, and call it a day.

I can deal with stripping my internal ("module private") symbols when building the library to avoid conflicts for my users with their client programs, but the question is how to name symbols in my library? So far I've been doing:

```<code>struct MyLibFoo;
void MyLibFooSomeAction(MyLibFoo *foo, ...);

struct MyLibBar;
void MyLibBarAnAction(MyLibBar *bar, ...);

// Submodule
struct MyLibFooBaz;
void MyLibFooBazAnotherAction(MyLibFooBaz *baz, ...);
</code>```

But I'm ending up with crazy long symbol names (much longer than the examples). If I don't prefix the names with a "fake namespace", modules' internal symbol names all clash.

Note: I don't care about camelcase/Pascal case etc, just the names themselves.


问:
Any tools/suggestions on how to refute code coverage quality argument
Now I know people could consider this question duplicate or asked many times, in which case I would appreciate a link to relevant questions with answer to my question.

I have been recently in disagreement with some folks about code coverage. I have a group of people who want our team to drop looking at code coverage altogether based on the argument that 100% coverage does not mean good quality tests and thus good quality code.

I have been able to push back by selling the argument that Code Coverage tells me what has not been tested for sure and help us focus on those areas.

(The above has been discussed in a similar fashion in other SO questions like this one - https://stackoverflow.com/questions/695811/pitfalls-of-code-coverage)

The argument from these folks is - then team would react by quickly creating low quality tests and thus waste time while adding no significant quality.

While I understand their point of view, I am searching for a way to make a more robust case for code coverage by introducing more robust tools/frameworks that take care of more coverage criteria (Functional, Statement,Decision, Branch, Condition, State, LCSAJ, path, jump path, entry/exit, Loop, Parameter Value etc).

What I am looking for is suggestion for a combination of such code coverage tools and practices/processes to go with them which can help me counter such arguments while feeling comfortable about my recommendation.

I would also welcome any accompanying comments/suggestions based on your experience/knowledge on how to counter such an argument, because while subjective, code coverage has helped my team be more conscious of code quality and value of testing.

Edit: To reduce any confusion about my understanding of weakness of typical code coverage, I want to point out that I am not referring to Statement Coverage(or lines of code executed) tools(there are plenty). In fact here is a good article on everything that is wrong with it: http://www.bullseye.com/statementCoverage.html

I was looking for more than just statement or line coverage, going more into multiple coverage criteria and levels.

See: http://en.wikipedia.org/wiki/Code_coverage#Coverage_criteria

The idea is that if a tool can tell us our coverage based on multiple criteria then that becomes a reasonable automated assessment of test quality. I by no means am trying to say that line coverage is a good assessment. In fact that's the premise of my question.

Edit:

Ok, maybe I projected it a bit too dramatically, but you get the point. The problem is about setting processes/policies in general across all teams in a homogeneous/consistent fashion. And the fear is general that how do you ensure quality of tests, how do you allocate guaranteed time without having any measure to it. Thus I like having a measurable feature that when backed up with appropriate processes and the right tools would allow us to improve code quality while knowing that time is not being force spent in wasteful processes.

EDIT: So far what I have from the answers:

Code reviews should cover tests to ensure quality of tests

Test First strategy helps avoid tests that are written after the fact to simply increase coverage %

Exploring alternative tools that cover test criteria other than simply Statement/Line

Analysis of covered code/number of bugs found would help appreciate the importance of coverage and make a better case

Most importantly trust the Team's input to do the right thing and fight for their beliefs

Blocks Covered/# of tests - Debatable but holds some value

Thanks for the awesome answers so far. I really appreciate them. This thread is better than hours of brainstorm with the powers that be.

答:
In my experience, code coverage is as useful as you make it. If you write good tests that cover all of your cases, then passing those tests means that you have met your requirements. In fact that's the exact idea that Test Driven Development uses. You write the tests before the code without knowing anything about the implementation (Sometimes this means another team entirely writes the tests). These tests are set up to verify that the final product does everything that your specifications says it done, and THEN you write the bare minimum code to pass those tests.

The problem here, obviously, is that if your tests aren't strong enough, you will miss edge cases or unforeseen problems and write code which doesn't truly meet your specifications. If you are truly set on using tests to verify your code, then writing good tests is an absolute necessity, or you're really wasting your time.

I wanted to edit the answer here as I realized that it didn't truly answer your question. I would look at that wiki article to see some stated benefits of TDD. It really comes down to how your organization works best, but TDD is definitely something in use in the industry.


问:
Why shouldn't I use the repository pattern with Entity Framework?
During a job interview, I was asked to explain why the repository pattern isn't a good pattern to work with ORMs like Entity Framework. Why is this the case?</p>

答: A very good reason to use the repository pattern is to allow the separation of your business logic and/or your UI from System.Data.Entity. There are numerous advantages to this, including real benefits in unit testing by allowing he use of Fakes or Mocks.

OwnerDisplayName: StringBuilder


问:
Working for free?
I came across this article Work for Free that got me thinking.

The goal of every employer is to gain
  more value from workers than the firm
  pays out in wages; otherwise, there is
  no growth, no advance, and no
  advantage for the employer.
  Conversely, the goal of every employee
  should be to contribute more to the
  firm than he or she receives in wages,
  and thereby provide a solid rationale
  for receiving raises and advancement
  in the firm.

I don't need to tell you that the
  refusenik didn't last long in this
  job.

In contrast, here is a story from last
  week. My phone rang. It was the
  employment division of a major
  university. The man on the phone was
  inquiring about the performance of a
  person who did some site work on
  Mises.org last year. I was able to
  tell him about a remarkable young man
  who swung into action during a crisis,
  and how he worked three 19-hour days,
  three days in a row, how he learned
  new software with diligence, how he
  kept his cool, how he navigated his
  way with grace and expertise amidst
  some 80 different third-party plug-ins
  and databases, how he saw his way
  around the inevitable problems, how he
  assumed responsibility for the
  results, and much more.

What I didn't tell the interviewer was
  that this person did all this without
  asking for any payment. Did that fact
  influence my report on his
  performance? I'm not entirely sure,
  but the interviewer probably sensed in
  my voice my sense of awe toward what
  this person had done for the Mises
  Institute. The interviewer told me
  that he had written down 15 different
  questions to ask me but that I had
  answered them all already in the
  course of my monologue, and that he
  was thrilled to hear all these
  specifics.

The person was offered the job. He had
  done a very wise thing; he had earned
  a devotee for life.

The harder the economic times, the
  more employers need to know what they
  are getting when they hire someone.
  The job applications pour in by the
  buckets, all padded with degrees and
  made to look as impressive as
  possible. It's all just paper. What
  matters today is what a person can do
  for a firm. The resume becomes pro
  forma but not decisive under these
  conditions. But for a former boss or
  manager to rave about you to a
  potential employer? That's worth
  everything.

What do you think? Has anyone here worked for free? If so, has it benefited you in any way? Why should(nt) you work for free (presuming you have the money from other means to keep you going)? Can you share your experience?

Me, I am taking a year out of college and haven't gotten a degree yet so that's probably why most of my job applications are getting ignored. So im thinking about working for free for the experience?

答:
There is nothing wrong with working for free, given a specific objective, of course. That's how I got my first programming job, by letting my potential employer know what I was capable of. I was lacking a degree in anything, so I could not very well simply persuade someone to hire me.

However, as with all things, so it is with this: Moderation will serve you well. It's up to you to decide whether you're obtaining experience, demonstrating your work, or slaving unnecessarily. I would propose that you work for free for a limited time, and then consider discussing your performance and your fee with your employer, if it's possible.

Title: Working for free?


答:
If you do want to avoid long prefixes, you can abbreviate library names like what Apple does in iOS and OS X:

NSString is a string from the NextStep roots of the OS

CALayer is a Core Animation layer

Title: C project avoiding naming conflicts


答:
Code coverage is certainly not proof of good unit tests, in that they are correct.

But unless they can provide a way of proving that all unit tests are good (for whatever definition of good they can come up with) then this is really a mute point.

Title: Any tools/suggestions on how to refute code coverage quality argument

Body:
Now I know people could consider this question duplicate or asked many times, in which case I would appreciate a link to relevant questions with answer to my question.

I have been recently in disagreement with some folks about code coverage. I have a group of people who want our team to drop looking at code coverage altogether based on the argument that 100% coverage does not mean good quality tests and thus good quality code.

I have been able to push back by selling the argument that Code Coverage tells me what has not been tested for sure and help us focus on those areas.

(The above has been discussed in a similar fashion in other SO questions like this one - https://stackoverflow.com/questions/695811/pitfalls-of-code-coverage)

The argument from these folks is - then team would react by quickly creating low quality tests and thus waste time while adding no significant quality.

While I understand their point of view, I am searching for a way to make a more robust case for code coverage by introducing more robust tools/frameworks that take care of more coverage criteria (Functional, Statement,Decision, Branch, Condition, State, LCSAJ, path, jump path, entry/exit, Loop, Parameter Value etc).

What I am looking for is suggestion for a combination of such code coverage tools and practices/processes to go with them which can help me counter such arguments while feeling comfortable about my recommendation.

I would also welcome any accompanying comments/suggestions based on your experience/knowledge on how to counter such an argument, because while subjective, code coverage has helped my team be more conscious of code quality and value of testing.

Edit: To reduce any confusion about my understanding of weakness of typical code coverage, I want to point out that I am not referring to Statement Coverage(or lines of code executed) tools(there are plenty). In fact here is a good article on everything that is wrong with it: http://www.bullseye.com/statementCoverage.html

I was looking for more than just statement or line coverage, going more into multiple coverage criteria and levels.

See: http://en.wikipedia.org/wiki/Code_coverage#Coverage_criteria

The idea is that if a tool can tell us our coverage based on multiple criteria then that becomes a reasonable automated assessment of test quality. I by no means am trying to say that line coverage is a good assessment. In fact that's the premise of my question.

Edit:

Ok, maybe I projected it a bit too dramatically, but you get the point. The problem is about setting processes/policies in general across all teams in a homogeneous/consistent fashion. And the fear is general that how do you ensure quality of tests, how do you allocate guaranteed time without having any measure to it. Thus I like having a measurable feature that when backed up with appropriate processes and the right tools would allow us to improve code quality while knowing that time is not being force spent in wasteful processes.

EDIT: So far what I have from the answers:

Code reviews should cover tests to ensure quality of tests

Test First strategy helps avoid tests that are written after the fact to simply increase coverage %

Exploring alternative tools that cover test criteria other than simply Statement/Line

Analysis of covered code/number of bugs found would help appreciate the importance of coverage and make a better case

Most importantly trust the Team's input to do the right thing and fight for their beliefs

Blocks Covered/# of tests - Debatable but holds some value

Thanks for the awesome answers so far. I really appreciate them. This thread is better than hours of brainstorm with the powers that be.


问:
Is C# becoming harder to read?
As C# has progressed, many language features have been added. It has come to the point where it's becoming unreadable for me.

As an example, consider the following code snip from Caliburn.Micro code here:

```<code>            container = CompositionHost.Initialize(
                   new AggregateCatalog(
                      AssemblySource.Instance.
                             Select(x => new AssemblyCatalog(x))
                               .OfType<ComposablePartCatalog>()
                )
            );
</code>```

Now, this is just a small example.

I have a number of questions:

Is this a common or known problem?

Is the C# community finding the same?

Is this an issue with the language, or is it the style used by the developer?

Are there any simple solutions to better understand others code and avoid writing code in this way?

答:
It took me a little while to understand Lambda syntax, and I'm from a mathematics and physcis background. It's a bit similar to mathematical expressions, althose they use -> instead of =>:

Maths example
f(x) := x->x+2
this reads as "Function f of x is defined as x maps on to x+2

c# example
del myDelegate = x => x +2;
this reads as "myDelegate is a function such that myDelegate (x) maps x on to x+2

The inconsistency between maths and programming doesn't really help, although I suppose -> had already been taken up in C++ as "property of" (urrgghh!)

http://en.wikipedia.org/wiki/List_of_mathematical_symbols

Title: Is C# becoming harder to read?


问:
Functional Languages that compile to Android's Dalvik VM?
I have a software problem that fits the functional approach to programming, but the target market will be on the Android OS.  I ask because there are functional languages that compile to Java's VM, but Dalvik bytecode != Java bytecode.

Alternatively, do you know if the dx utility can intelligently convert the .class files generated from functional languages like Scala?

Edit:
In order to add a bit more helpfulness to the community, and also to help me choose better, can I refine the question a bit?

Have you used any alternate languages with Dalvik?  Which ones?

What are some "gotchas" (problems) that I might run into?

Is performance acceptable?  By that, I mean the application still feels responsive to the user.

I've never done mobile phone development, but I grew up on constrained devices and I'm under no illusion that there is a cost to using non-standard languages with the platform.  I just need to know if the cost is such that I should shoe-horn my approach into default language (i.e. apply functional principles in the OOP language).

答:
Kawa is a lovely but little known variant of Scheme that has existed quietly for many years and runs on both the JVM and Dalvik, natively.  Therefore, similar to Mirah, its output includes no extra VM and only includes explicitly imported libraries.  Kawa has lots of standard macros (including some specific to Android APIs) that make for a nice clean syntax (assuming one is not averse to parentheses), and adds some tasty goodies on top of Scheme, like "promises" (lazy eval and futures in one).  The language is quite robust and well-documented, and has been actively maintained and evolving since the early days of Java.

The Java Advent Calendar summarizes Kawa's merits with some informative examples and links.


问:
Is learning C# as a first language a mistake?
I know there are similar questions on here, which I've read, but I recently read this post by Joel Spolsky:

How can I teach a bright person, with no programming experience, how to program?

And it got me thinking about my way of learning and whether it might actually be harmful in the long run.

I've dabbled with various languages but C# is my first serious one, I've read "Head First C#" and created a few projects. But after reading the post above I've found it a bit disheartening that I may be going about it all wrong, obviously I respect Joel's opinion which is what has thrown me a bit.

I've started reading "Code" as recommended in the reading list and I'm finding it pretty hard going, although enjoyable. I feel like it's taken the shine off of my "noobish hacking about" in Visual Studio.

So now I'm unsure as to what path I should take? Should I take a step back and follow Joel's advice and start reading?

I guess my main aim is just to become a good programmer, like everyone else, but I don't want to be going into bad practice by learning a .NET language when someone who's opinion I respect thinks that it is harmful.

Thoughts?

答:
It's tough on the novice, without a doubt. I've done vb, javascript, PL/SQL, T-SQL, Uniface and a bit of C# to name a few.

Someone earlier mentioned Visual Basic as where they learned about object oriented programming, and to be honest VB.NET has the most easy to understand syntax of any language I've ever seen. The best feature is that the keywords match the concepts being described closely.

e.g. Function myHandler() handles myButton.click

or
  Class Human
    Extends mammal
    implements intelligentLifeform

Seriously, for readability when you're a novice what else would you want the syntax to look like?

When you are looking for properties and methods (and distringuishing between subs and functions) it's a lot easier to read in VB.

Similarly when declaring variables

Dim myString As string - obvious which is the type and which is the instance

C# case sensitivity encourages what to me is a seriously bad habit - having the same name for class and instance with one being uppercase and one lower.

e.g.

Human human

are there seriously so few words in yuor volcabulary that you have to re-use existing ones with uppercase?

if you call human.think, it would be easy to mistake an instance for a class and think you were calling a static method at a glance. And glancing is often how we perceive code, we don;t have time to mouse over every single element to let the editor tell us what's going on.

C# might have some advantages, but it is a lot more difficult to start on - even if it saves typing. Which is why there should definitly be a place for both languages.


问:
What's with the aversion to documentation in the industry?
There seems to be an aversion to writing even the most basic documentation. Our project READMEs are relatively bare. There aren't even updated lists of dependencies in the docs.

Is there something I'm unaware of in the industry that makes programmers dislike writing documentation? I can type out paragraphs of docs if needed, so why are others so averse to it?

More importantly, how do I convince them that writing docs will save us time and frustration in the future?

答:
Documentation takes time, and I suspect a lot of developers have had too many run-ins with documentation that was worse than useless. They get the idea that not only will documenting get them trouble from their manager (the same guy who keeps cutting the QA part of the schedule), but it won't help anyone, including them.

Any half-decent bit of documentation is an investment in the future. If you don't care about the future (because you don't think beyond the next paycheck, or because you think it won't be your problem), then the thought of doing the documentation is extremely painful.


答:
There are two main factors in my experience:

Deadlines

Most companies are so date driven that QA, tech debt, and actual design are cut just so the project manager doesn't look bad or to hit some absurd over-promised client deadline. In this environment where even functional quality is cut, then a long-term investment like documentation has little chance.

Change

A relatively new best practice for developers is to de-emphasize comments. The idea is that keeping information in two places (the code [including tests] and the comments around the code) leads to a lot of overhead in keeping them in sync for little benefit. "If your code is so hard to read that you need comments, wouldn't time be better spent cleaning up the code?"

I personally won't even look at comments any more. Code can't lie.

Documentation follows the same vein. With the widespread adoption of agile, people acknowledge that requirements change regularly. With the widespread use of refactoring, the organization of code will shift pretty substantially. Why spend the time documenting all of this stuff that's bound to change? Code and tests should do a good enough job doing that.

Title: What's with the aversion to documentation in the industry?

Body:
There seems to be an aversion to writing even the most basic documentation. Our project READMEs are relatively bare. There aren't even updated lists of dependencies in the docs.

Is there something I'm unaware of in the industry that makes programmers dislike writing documentation? I can type out paragraphs of docs if needed, so why are others so averse to it?

More importantly, how do I convince them that writing docs will save us time and frustration in the future?


问:
Which are the significant algorithms for humankind in past decades?
Which world most important algorithms have contributed most to humankind in past decades?

I thought this is a good general knowledge for a developer to know about.

Update:

If possible, please keep the answer to a specific programming algorithm.

I would like to get a list of the most important ones, only one algorithm per answer.

Please consider to state why the algorithm is significant and important...

答:
Viterbi algorithm

Originally used to decode convolutional error-correcting codes, it is now used to solve a wide class of recognition problems (ranging from speech recognition to bioinformatics).
You can find it in several communication and storage devices.


答:
There are a number of factors in play here:

Well-written code is its own documentation.  All other things being equal, it is better to write clearer code that speaks for itself, rather than more documentation.  Do that, and you will need to modify less documentation when you change that code.

Writing documentation is arguably a different skill than writing code.  Some software developers are better at it than others.  Some are much better at writing code than they are writing documentation.

Documentation should only have to be written once, not twice (once in the source code, and again in the programmer's guide).  That's why we have things like XML comments and documentation generators.  Unfortunately, using such tools can be more tricky and cumbersome than just writing the documentation by hand, which is why you don't see those tools widely used.

Good documentation is time consuming, and hard to do well.  All other things being equal, there can be more value to writing new code than writing documentation for already-existing code.

When the code changes, you also have to change the documentation.  The less documentation there is, the less that has to be changed.

Nobody reads the documentation anyway, so why bother?


答:
In my experience, there's a few things to combine with code coverage to make the metric worthwhile:

Code Reviews

If you can punt bad tests back to the developer, it can help limit the number of bad tests that are providing this meaningless coverage.

Bug Tracking

If you have a bunch of code coverage on a module, but still get many/severe bugs in that area, then it might indicate a problem where that developer needs improvement with their tests.

Pragmatism

Nobody is going to get to 100% with good tests on non-trivial code. If you as the team lead look at the code coverage, but instead of saying "we need to get to N%!" you identify gaps and ask people to "improve coverage in module X" that achieves your goal without providing people an opportunity to game the system.

Blocks Covered/# of Tests

Most code coverage tools list blocks covered vs blocks not covered. Combining this with number of actual tests lets you get a metric indicating how 'broad' tests are, either indicating bad tests or coupled design. This is more useful as a delta from one sprint to another, but the idea is the same - combine code coverage with other metrics to gain more insight.


问:
Syntax-highlighting color scheme studies
Most programmers have their own personal preferences for syntax-highlighting color schemes, but I've been wondering, has anyone ever done an actual scientific study on what the best color scheme would be? I imagine such a study would look at things like the readability of the code, whether the programmer's eyes are drawn to the most important parts, etc.

Perhaps this was already done for something like the default Visual Studio theme, but I'd like to know if there are any publicly available studies out there, and what they found.

答:
As a kind of rough study, the screenshots below show 3 color themes used to syntax highlight XSLT. I've chosen XSLT as it poses a particular challenge because of the large number of language elements - and also because many developers describe it as ugly.

Solarized

Tommorow Night

Github

Observations

The number of colors used in the sample helps distinguish the different language elements, but it might prove distracting to a developer.

It helps to progress from cold to warm colors if possible, using cold colors for the more neutral parts of the language. An alternative is to shift from pastel shades to more vivid ones (hue saturation).

The background color makes a huge difference to the perception of the foreground colors.

Some adjacent foreground colors can cause bad clashes that disturb the eye, red and green in particular do not seem to go well together.

With a dark background it is easier to provide a wide range of foreground colors with sufficient contrast with each other and the background.

Lastly, external factors such as ambient light and the quality and calibration of the monitor make a huge difference.

Conclusion

It is best to use tools that provide an extensible way of setting color themes as it is unlikely that any single color theme will meet the needs of all developers, and even the same developer may frequently change their preference depending on a variety of factors.


答:
Elephant in the room: Programmers are not (necessarily) writers. Nor are they necessarily amenable to fleshing out their implementations to technical writers. Second Elephant in the room: Technical writers are generally not able to flesh out details useful for future developers (even if the developers would deign to explain them to them).

A complex system can become near inscrutable over time without proper documentation. The code becomes less valuable inversely proportionally to its scrutablility [sic]. Resolved, management hires Software Engineer who can read code and coax details from developers, pays him at a developer rate and mandates him to document and to maintain documentation. This writer can read code and will know what questions to ask and will fill in details as necessary. Just like you have a QA department, you have an internal documentation department.

The code will become more valuable, as you can licence it to a 3rd party (because he can understand it), the code can be more easily audited and improved/re-factored, you will have better code reuse even to where you can easily factor out more lightweight versions of your software, and you will be able to introduce new developers more easily into the project,  your support engineers will love working for you.

This will never happen.


问:
What is the difference between Microsoft.Web.Helpers and System.Web.Helpers?
What is the difference between Microsoft.Web.Helpers and System.Web.Helpers?

Did one take the place of the other (same thing, different version/name), or are they separate things. If so, how do they differ? What is the raison d'etre of each, and are there scenarios where you might use both of them?

答:
If I take the answer for that forum post as valid

http://forums.asp.net/t/1623534.aspx

Then Microsoft.Web.Helpers are simply experimental helpers that microsoft didn't include in the "official" ASP.NET MVC release and thus won't support. However they still put them out there so that it can benefit those that don't need full support.

EDIT

There is nothing wrong in using them, its just that you won't be able to call Microsoft tech support if they don't work. You can probably fill bug report on them and have the community answer your questions anyway. What you won't have is "Call us at midnight on Christmas Eve" support. Some organization have a real issues with unsupported components, thus the separation between the official release and this.

You can seem them as kind of compromise between MS big corporate customer that require support at all cost and  the need of a small start-up that would switch to more nimble cool new framework otherwise. Also, keeping the two separate prevent bloating in the official release. Essential stuff in System.Web, additionnal goodies in Microsoft.Web. Not everyone need Gravatar support on his website.


问:
What should every programmer know about programming?
Please, stay on technical issues, avoid behavior, cultural, career or political issues.

答: When someone asks you to build something, remember: they are also asking you to maintain it. Possibly, forever.</p>


答:
I wouldn't say that going back and covering existing code is the best route forward. I would argue that it makes sense to write covering tests for any new code you write and or any code you change.

When bugs are found, write a test that fails because of that bug and fix the bug so that the test turns green. Put in the comments of the test what bug it's written for.

The goal is to have enough confidence in your tests that you can make changes without concern for unexpected side effects. Check out Working Effectively with Legacy Code for a good summary of approaches to taming untested code.


问:
Storing data in 2 different systems/database structures
My company is an online retailer, and we use an homebrew ecommerce platform. In the last year or so, we've partnered with a accounting software vendor, as our homebrew solution was unable to produce reports as needed, or otherwise satisfy the requests of banks and investors.

We're off to a rocky start with the software, but I'm wondering if it's our approach. Currently, we store a complete set of data in the database connected to our ecommerce platform. Nightly, we send the necessary API calls to sync our entities in the accounting software (orders, POs, invoices, etc), and each morning, I've created scripts that validate that the data is correct between the two systems. This collective system has been a nightmare, as any minor chages to the ecommerce platform cascade in violent and horrible ways to system B. It's resulting in a TON of work on my part to make corrections on a daily basis.

Is there a correct way to approach this problem? Or does the problem really lie upstream, in our decision to duplicate the data between the two systems. Has anybody successfully done something similar?

It has been a non-stop fire drill for 3 months now, and any advice would be greatly appreciated.

答: Why duplicate data this day and age when you can just move to a Service Oriented Architecture? Have the accounting system put a web service on their data, then have your system call it when it needs certain pieces of data and vice-versa. Don't store the entities in your database at all. If you need to reference a record from the accounting system, store a key or a token. Then, let the service/controller layer take care of reassembling the data by making web service calls to fill in the missing pieces.</p>


问:
License: free to use but not free to modify or redistribute
I am releasing an application at no cost, but I am not granting users the right to modify or redistribute the code. How should I call this?

I initially used the term "free license", but on second thoughts I find this confusing because  free can have several meanings, and in people's mind it is often associated with open source. Is there a better terminology for my case?

答: You haven't said what form you are distributing it, but as long as you are distributing as a binary, it's pretty easy - don't give them the source code. The number of people who can be bothered to modify a binary is pretty small, and the number of those who would care what your license said anyway is probably close enough to zero that you don't care.</p>


答:
The term "freeware" (rather than the ambiguous "free software") is often used to indicate software that is free of charge but not necessarily supplied with other freedoms. However, freeware usually often carries the connotation of "free to distribute".

The adjective "gratis" is used by the FSF to unambiguously indicate "zero monetary cost". However, people not familiar with software licensing might find that wording unfamiliar, so it would be best to accompany it with an explicit description that your software is available "free of charge".

Title: License: free to use but not free to modify or redistribute

Body:
I am releasing an application at no cost, but I am not granting users the right to modify or redistribute the code. How should I call this?

I initially used the term "free license", but on second thoughts I find this confusing because  free can have several meanings, and in people's mind it is often associated with open source. Is there a better terminology for my case?


问:
Is there a kind of programs to illustrate most features and usages of different programming language?
We all know “The quick brown fox jumps over the lazy dog” used as benchmark for printing and fonts.

I wonder if there is a similar “Lazy Dog” for Programming Languages.

There are so many different programming languages, with all kinds of features and syntaxs, similar or different. The problem is: the user will be confused when using different languages at the same time.

Although plenty of differences between different languages, there must be something in common, i.e. a task or routine. If we implement the same task in different languages, and try to cover most frequently used features, then the language learning or comparison will become much more easy.

This kind of programme doesn't need to be very long, just like a tutorial but be common and abstract enough. Does it exist?

答: Any single short program would have to gloss over 90% of the language features. Most programming languages are large enough that even a half hour talk can only highlight the key distinguishing characteristics. A suite of small-ish programs is more appropriate for exposition and comparison. Rosetta Code is precisely that: A large number of problems are described, and idiomatic solutions in numerous languages are contributed (it's a wiki).


答:
The argument from these folks is - the team would react by quickly
  creating low quality tests and thus waste time while adding no
  significant quality.

This is an issue of trust, not tools.

Ask them why, if they really believe that statement, they would trust the team to write any code at all?


答:
Ok, maybe I projected it a bit too dramatically, but you get the
  point. The problem is about setting processes/policies in general
  across all teams in a homogeneous/consistent fashion.

I think that's the problem. Developers don't care (and often for excellent reasons) about consistent or global policies, and want the freedom to do what they think is right rather than comply to corporate policies.

Which is reasonable unless you prove that global processes and measures have value and a positive effect on quality and speed of development.

Usual timeline:

dev: hey, look - I added code coverage metrics to our dashboard, ain't that great?

manager: sure, let's add mandatory goals and compliance on those

dev: never mind, code coverage is stupid and useless, let's drop it


答:
MP3

Although it is a more general term than a specific algorithm, I'd mention MP3 as the aggregation of the different algorithms and techiques which work in cooperation to generate this lossy audio format.

It has surely been very significant in the "digital era".

Title: Which are the significant algorithms for humankind in past decades?

Body:
Which world most important algorithms have contributed most to humankind in past decades?

I thought this is a good general knowledge for a developer to know about.

Update:

If possible, please keep the answer to a specific programming algorithm.

I would like to get a list of the most important ones, only one algorithm per answer.

Please consider to state why the algorithm is significant and important...