答:
First, know how the technology behind it works.

You need to know this because the knowledge behind how it works, because you're going to run into networking issues, or, as I've seen countless times, people entirely faily at understanding what server-side and client-side actually is. One of the most common newb questions I see is "How can I make JS change a variable in my ASP code?!"

Do you understand ethernet/wifi and TCP/IP to have a general idea of what's going on?

How much HTTP do you actually know?

Do you actually get HTML? Sure, you might know how tags work and nest stuff, but do you actually understand doctype and quirks mode? Do you understand that you shouldn't put paragraph tags around a list element?

Invent JavaScript (and explain it can be run server-side). ecmascript, livescript, mocascript, jsscript, node...

Learn the Window API, learn the DOM API, and learn the XHR API. If you don't know these three things you have no business writing code for the browser.

Understand your code is bigger than you, or your specific situation

Sure, you wrote something, but everyone can see it. It's all "open" source. Sure, you can obfuscate it, minifiy it, whatever... at the end of the day, if I want to see you code, it's trivial for me to defeat any methods you put in place.

You need to understand multiple browsers differences. Target the most popular ones, or the ones your market demographic has. For instance, ie6 won't render DOM table-cell elements if you appendChild rather than the DOM API methods specifically for tables. More examples exist, you need to learn them.

You need to understand how to write code around all of these issues in browsers, not your specific browser. You'll quickly learn things that work well in one browser are slow in another. You'll have to figure out how browsers work and why they're different.

For the love of Odin's beard, don't write code that permits me to do cross-site-scripting attacks on your code. If you make an ajax call to a cell and do something like cell.innerHTML = "", and an alert box shows up, you've done it wrong.

Stay the bloody hell away from DynamicDrive, w3Schools, and websites that give bad advice. You need to find comunities that give good advice. Here on Stack Overflow we have the JavaScript and Node.JS chat rooms, and we do our best to keep pushing the limits of what's "better", where as sites like w3s keep outdated data and never bother with it. You should stick with the offical spec sites such as the W3C, the Mozilla Developer Network (MDN). Ask for peer-review of your code. When you feel like you're doing something painful with your code, when you're doing a lot of cut+paste+tweak with your code, you should immediately come to a chat room and ask for guidance on writing better code.

When you come for guidance, or want to share that really cool thing you made... please, pretty please. Please, make sure you documented it, make sure your variable names make sense, make sure it's not all one-lined. You need to write clean code. If you have a pile of garbage, not only have you failed, nobody who knows how to help you will want to. Help us help you.

You want to write JavaScript-- that's cool, respect that not everyone supports JavaScript. Two reasons for this-- 1) Faster Internet for everyone (rather than "ajax all the things" which leads to a slower experience). 2) Web's more accessible to people on console-based browsers, people running no-script, mobile phones. What I'm trying to say is, your site should degrade gracefully if someone doesn't have JavaScript and at the very least, use  tags to alert them as to such.

Because of the prototype nature of JavaScript, you can make changes to how the language actually works-- which is really sweet. You see, JavaScript is evolving, we're pulling out of "ECMA Script 3", which is the older version of JS, and into "ECMA Script 5" (aka, es5). Because of prototype, we can fix the es3 language in the field to work like es5. That means, ie6, a 10 year old browser gets language feature that came out last year. Use es5-shims wherever you can, they're really cool and you need to look into it.

The western world of English speaking white kids isn't who uses the internet. Code accordingly. This means you need to understand internationalization, and writing code that deals with higher demand. 10 years ago there were less than 500 Million people on-line, today it's roughly 2 billion, and in another 10 years? Probably close to every person on the planet will have internet access, that means you need to support names that don't fit the regex of /[a-z ']/i, but include Hindi, Arabic, accents (this is an existing problem from short-sighted developers), Chinese, and others. Understand character sets, Unicode and UTF-8.

You're a programmer, not a pasta factory. Stop writing spaghetti.

Name your variables after things that make sense.

Document your code. I don't care if you're using JSDoc powered by rhino or you have a bunch of scribbles. Write documentation that helps the person who is going to use your code. Write documentation for someone who wants to improve or maintain your code. Include useful comments. Comments like "This fizzes the bizz" or ones half-English half-french aren't helpful. Describe what a function does. Describe complex sections of code.

Figure out how to limit repetition of code. Look for modular design or functional patterns. See what you can abstract. You should never end up cutting+pasting+tweaking large segments of code to do the same thing.

You need to understand the DOM API. The DOM and window objects provision for a lot of great things. This sounds like a lot of work but that's because it's a big scary acronym. A lot of you JavaScript ninjas like to write code such as . FFS DONT DO THAT. Wait for the full document to be loaded, separate your JavaScript code from the html document. This is basic OOP practices 101, just don't in-line your JS or CSS into your html document, ever. Figure out how to do it properly or find someone who knows how to show you how to do it. Again, ask questions.

the Javascript:foo("buz") is a psudeo-protocol, it's not fully supported, and if you don't in-line javascript you wouldn't be using it in the first place. I promise you from the bottom of my heart there is no reason what-so-ever on this earth or anywhere in the universe that you NEED to put your javascript inside of an HTML element. Ever. So don't do it. I won't even help people that do that any more, it's that bad.

Figure out how to write code in such a way it does't break all the time.

Global variables are one of the biggest problems. Figure out how functional programming in JavaScript works. Figure out what hoisting is. Figure out how to avoid global variables.

Use static code analysis tools. These will alert you right-away to all the little "oops" you made when writing your code. Forgot a semicolon somewhere? Oh, there it is. Have a global somewhere? Oh, there it is. Code that might throw a bunch of mystery errors when you try to run it? OH! There they are! No more screwing around and staring into a pile of code for hours trying to figure out something that's just a syntax error. (Well, hardly any, you might have done something it can't catch, but it's generally awesome).

Unit test. There's no reason not to be. There's tons of unit testing tools out there. Basically, unit testing is "Here's my function" and "I want it to output Y" "Here's some test inputs" And the test is "Did they all work?" There's many JS testing frameworks, like the popular QUnit. Take a tour through your favorite search engine and see what tickles your fancy. But use them.

Source control management, also known as version control. Git's popular, and with good reason. So is SVN and a few others. What you need to stop doing this very instant is editing production code. You need to stop renaming files main_backup_20110911.js.bak.1 You lose stuff, your directory gets messy, you can't easily "rewind" to a previous point in time. You can't see what's going on, you can't make code patches. So, just start learning GIT, it should take you an hour and you'll never go back.

Peer review. You're not that good, neither am I. I get better by asking for feedback as much as I can. That's how you should do it too.

Write JavaScript that people love

Figure out why your code is slow. Use jspref and create tests.

Stop binding events to one DOM element, it's slow, and creates serious event bubbling issues that will waste a lot of your time. Research "event delegation" in JavaScript.

STOP using innerHTML to edit the DOM. This goes back to learning what HTML is, and learning what the DOM is. HTML is data sent from the server that your browser rendering engine uses to create a bunch of programming objects that end up being a Document Object. When you use innerHTML you're asking your browser to re-render the whole thing. Thankfully, like way over 10 years ago, we created the DOM API, and it lets you "append child" or "create text node," without having to update the whole thing. innHTML is a disgrace that Microsoft invented -- if you use it, you also lose all privileges to whine about IE6 being awful because you're helping it's garbage stick around forever. Learn the DOM.

It needs to work everywhere it can. If something isn't supported, it needs to degrade gracefully so the experience doesn't suck-- you can't just slap your users in the face and crash.

Copyright and licence are important. Don't rip-off other people's hard work. If someone says "not for resale," you can't sell it. Don't be a jerk, or we'll hate your code for ripping off hard-working-people.

JS is prototypes, not classes. Stop doing that. If you don't understand how prototype works, you need to. Google it. JavaScript is not class-based, stop trying to make classes, it very rarely works out well. People try to write classical code in a prototype language and use that as a case for "why the language sucks", I could make the same case for Ruby not being able to support prototype. Learn something new and stop doing it wrong.

Focus on the basics, always.

You're wrong, and that's awesome, because you know something now. Nothing is worse than someone who won't admit to being wrong and keeps slamming bad code out the door like they're some renegade rock-star superhero ninja. They're just fools. Admit you can be wrong, admit you might be wrong, ask for help.

You don't always need jQuery. jQuery creates a lot of slow code and helps people who don't know JS to write JS. This is further a problem as JS doesn't require you know JS to write JS. Go figure. Once you understand a few of the things I mentioned above such as learning events, learning the DOM, learning about innerHTML, you'll see why jQuery can be harmful to your code. It can be used correctly in a lot of places, but often you can use a smaller library or even gasp the standard JavaScript that comes with your browser to accomplish something. You don't need jQuery to do anything, it makes it easier to write some code which is cool if you're learning but you need to start doing better and learning more -- when you know more, you'll figure out how to write better code in jQuery anyway. Check out some other JavaScript libraries and stop being so close-minded.

You don't need cut+paste+tweak, make DRY code. I've mentioned this before, but it's important here as well. You can't write quality code if your code base is a disgrace.

Don't abuse arrays/object differences, learn how to loop. Learn why you use a for (;;) and why you use a for( in ) loop. When to use a while loop. Stop nesting IFs when you can just use a switch case. Objects do not preserve order, so don't use them as an array; old Opera/FF, old MISE, sometimes Flash won't respect the order of your objects. Use an array if you want to keep an order of things, use an object if you want an object (something that doesn't have order of elements).

How decision structures can be used to your advantage, not add complexity to your code. Stop nesting IFs, figure out how Boolean logical operators work. Figure out how switch-case works.

RTFM. The best place to learn about better code is by reading the actual spec. Read the RFC specs on that part of code you're trying to use. Read the ECMAScript document. Read the W3C DOM spec. Read the W3C XHTML/HTML/HTML5 spec. Read the specs, they're good.

Focus on the long game, not a quick flash and die.

You should help the community, you should write code that will be around for a long time. Have some passion about your code and community. If you left bad knowledge somewhere, go the hell back and fix it. Bad information is really hard to purge and sticks around for ever. Do your part. Don't help w3schools make the web worse.

Don't jump in from nowhere and say "Hey I got a great idea for how to use which" drop a bunch of code that nobody can use and disappear. You contributed nothing. Don't use variables like a and chezburger.

Learn to spot the bad code and the good code, find it in your own code, make your bad code into good code.

Create something, learn something, teach something.

Broaden your horizons. You can't just write JavaScript forever --  take a sabbatical into something else that interests you, come back, share what you learnt and see if you can find a place for it in the community. Try to show the other world what value JavaScript has as well while you're out there.

You're still wrong, even when you do know everything. Use a proof to be correct, not your status/authority. You can never be right, but your proof is always correct. Don't get into pissing matches, as hard as it is to avoid sometimes. Either there's proof or there isn't. Flames help nobody.

For anyone interested, I've actually taken most of this from personal notes on a tutorial I'm href="https://github.com/0xdeadcafe/CodeGuide-0000" rel="nofollow noreferrer">nowhere done writing.

Body:
First, know how the technology behind it works.

You need to know this because the knowledge behind how it works, because you're going to run into networking issues, or, as I've seen countless times, people entirely faily at understanding what server-side and client-side actually is. One of the most common newb questions I see is "How can I make JS change a variable in my ASP code?!"

Do you understand ethernet/wifi and TCP/IP to have a general idea of what's going on?

How much HTTP do you actually know?

Do you actually get HTML? Sure, you might know how tags work and nest stuff, but do you actually understand doctype and quirks mode? Do you understand that you shouldn't put paragraph tags around a list element?

Invent JavaScript (and explain it can be run server-side). ecmascript, livescript, mocascript, jsscript, node...

Learn the Window API, learn the DOM API, and learn the XHR API. If you don't know these three things you have no business writing code for the browser.

Understand your code is bigger than you, or your specific situation

Sure, you wrote something, but everyone can see it. It's all "open" source. Sure, you can obfuscate it, minifiy it, whatever... at the end of the day, if I want to see you code, it's trivial for me to defeat any methods you put in place.

You need to understand multiple browsers differences. Target the most popular ones, or the ones your market demographic has. For instance, ie6 won't render DOM table-cell elements if you appendChild rather than the DOM API methods specifically for tables. More examples exist, you need to learn them.

You need to understand how to write code around all of these issues in browsers, not your specific browser. You'll quickly learn things that work well in one browser are slow in another. You'll have to figure out how browsers work and why they're different.

For the love of Odin's beard, don't write code that permits me to do cross-site-scripting attacks on your code. If you make an ajax call to a cell and do something like cell.innerHTML = "<script>alert("xss")</script>", and an alert box shows up, you've done it wrong.

Stay the bloody hell away from DynamicDrive, w3Schools, and websites that give bad advice. You need to find comunities that give good advice. Here on Stack Overflow we have the JavaScript and Node.JS chat rooms, and we do our best to keep pushing the limits of what's "better", where as sites like w3s keep outdated data and never bother with it. You should stick with the offical spec sites such as the W3C, the Mozilla Developer Network (MDN). Ask for peer-review of your code. When you feel like you're doing something painful with your code, when you're doing a lot of cut+paste+tweak with your code, you should immediately come to a chat room and ask for guidance on writing better code.

When you come for guidance, or want to share that really cool thing you made... please, pretty please. Please, make sure you documented it, make sure your variable names make sense, make sure it's not all one-lined. You need to write clean code. If you have a pile of garbage, not only have you failed, nobody who knows how to help you will want to. Help us help you.

You want to write JavaScript-- that's cool, respect that not everyone supports JavaScript. Two reasons for this-- 1) Faster Internet for everyone (rather than "ajax all the things" which leads to a slower experience). 2) Web's more accessible to people on console-based browsers, people running no-script, mobile phones. What I'm trying to say is, your site should degrade gracefully if someone doesn't have JavaScript and at the very least, use <noscript> tags to alert them as to such.

Because of the prototype nature of JavaScript, you can make changes to how the language actually works-- which is really sweet. You see, JavaScript is evolving, we're pulling out of "ECMA Script 3", which is the older version of JS, and into "ECMA Script 5" (aka, es5). Because of prototype, we can fix the es3 language in the field to work like es5. That means, ie6, a 10 year old browser gets language feature that came out last year. Use es5-shims wherever you can, they're really cool and you need to look into it.

The western world of English speaking white kids isn't who uses the internet. Code accordingly. This means you need to understand internationalization, and writing code that deals with higher demand. 10 years ago there were less than 500 Million people on-line, today it's roughly 2 billion, and in another 10 years? Probably close to every person on the planet will have internet access, that means you need to support names that don't fit the regex of /[a-z ']/i, but include Hindi, Arabic, accents (this is an existing problem from short-sighted developers), Chinese, and others. Understand character sets, Unicode and UTF-8.

You're a programmer, not a pasta factory. Stop writing spaghetti.

Name your variables after things that make sense.

Document your code. I don't care if you're using JSDoc powered by rhino or you have a bunch of scribbles. Write documentation that helps the person who is going to use your code. Write documentation for someone who wants to improve or maintain your code. Include useful comments. Comments like "This fizzes the bizz" or ones half-English half-french aren't helpful. Describe what a function does. Describe complex sections of code.

Figure out how to limit repetition of code. Look for modular design or functional patterns. See what you can abstract. You should never end up cutting+pasting+tweaking large segments of code to do the same thing.

You need to understand the DOM API. The DOM and window objects provision for a lot of great things. This sounds like a lot of work but that's because it's a big scary acronym. A lot of you JavaScript ninjas like to write code such as <a href="javascript:alert("foo")">. FFS DONT DO THAT. Wait for the full document to be loaded, separate your JavaScript code from the html document. This is basic OOP practices 101, just don't in-line your JS or CSS into your html document, ever. Figure out how to do it properly or find someone who knows how to show you how to do it. Again, ask questions.

the Javascript:foo("buz") is a psudeo-protocol, it's not fully supported, and if you don't in-line javascript you wouldn't be using it in the first place. I promise you from the bottom of my heart there is no reason what-so-ever on this earth or anywhere in the universe that you NEED to put your javascript inside of an HTML element. Ever. So don't do it. I won't even help people that do that any more, it's that bad.

Figure out how to write code in such a way it does't break all the time.

Global variables are one of the biggest problems. Figure out how functional programming in JavaScript works. Figure out what hoisting is. Figure out how to avoid global variables.

Use static code analysis tools. These will alert you right-away to all the little "oops" you made when writing your code. Forgot a semicolon somewhere? Oh, there it is. Have a global somewhere? Oh, there it is. Code that might throw a bunch of mystery errors when you try to run it? OH! There they are! No more screwing around and staring into a pile of code for hours trying to figure out something that's just a syntax error. (Well, hardly any, you might have done something it can't catch, but it's generally awesome).

Unit test. There's no reason not to be. There's tons of unit testing tools out there. Basically, unit testing is "Here's my function" and "I want it to output Y" "Here's some test inputs" And the test is "Did they all work?" There's many JS testing frameworks, like the popular QUnit. Take a tour through your favorite search engine and see what tickles your fancy. But use them.

Source control management, also known as version control. Git's popular, and with good reason. So is SVN and a few others. What you need to stop doing this very instant is editing production code. You need to stop renaming files main_backup_20110911.js.bak.1 You lose stuff, your directory gets messy, you can't easily "rewind" to a previous point in time. You can't see what's going on, you can't make code patches. So, just start learning GIT, it should take you an hour and you'll never go back.

Peer review. You're not that good, neither am I. I get better by asking for feedback as much as I can. That's how you should do it too.

Write JavaScript that people love

Figure out why your code is slow. Use jspref and create tests.

Stop binding events to one DOM element, it's slow, and creates serious event bubbling issues that will waste a lot of your time. Research "event delegation" in JavaScript.

STOP using innerHTML to edit the DOM. This goes back to learning what HTML is, and learning what the DOM is. HTML is data sent from the server that your browser rendering engine uses to create a bunch of programming objects that end up being a Document Object. When you use innerHTML you're asking your browser to re-render the whole thing. Thankfully, like way over 10 years ago, we created the DOM API, and it lets you "append child" or "create text node," without having to update the whole thing. innHTML is a disgrace that Microsoft invented -- if you use it, you also lose all privileges to whine about IE6 being awful because you're helping it's garbage stick around forever. Learn the DOM.

It needs to work everywhere it can. If something isn't supported, it needs to degrade gracefully so the experience doesn't suck-- you can't just slap your users in the face and crash.

Copyright and licence are important. Don't rip-off other people's hard work. If someone says "not for resale," you can't sell it. Don't be a jerk, or we'll hate your code for ripping off hard-working-people.

JS is prototypes, not classes. Stop doing that. If you don't understand how prototype works, you need to. Google it. JavaScript is not class-based, stop trying to make classes, it very rarely works out well. People try to write classical code in a prototype language and use that as a case for "why the language sucks", I could make the same case for Ruby not being able to support prototype. Learn something new and stop doing it wrong.

Focus on the basics, always.

You're wrong, and that's awesome, because you know something now. Nothing is worse than someone who won't admit to being wrong and keeps slamming bad code out the door like they're some renegade rock-star superhero ninja. They're just fools. Admit you can be wrong, admit you might be wrong, ask for help.

You don't always need jQuery. jQuery creates a lot of slow code and helps people who don't know JS to write JS. This is further a problem as JS doesn't require you know JS to write JS. Go figure. Once you understand a few of the things I mentioned above such as learning events, learning the DOM, learning about innerHTML, you'll see why jQuery can be harmful to your code. It can be used correctly in a lot of places, but often you can use a smaller library or even gasp the standard JavaScript that comes with your browser to accomplish something. You don't need jQuery to do anything, it makes it easier to write some code which is cool if you're learning but you need to start doing better and learning more -- when you know more, you'll figure out how to write better code in jQuery anyway. Check out some other JavaScript libraries and stop being so close-minded.

You don't need cut+paste+tweak, make DRY code. I've mentioned this before, but it's important here as well. You can't write quality code if your code base is a disgrace.

Don't abuse arrays/object differences, learn how to loop. Learn why you use a for (;;) and why you use a for( in ) loop. When to use a while loop. Stop nesting IFs when you can just use a switch case. Objects do not preserve order, so don't use them as an array; old Opera/FF, old MISE, sometimes Flash won't respect the order of your objects. Use an array if you want to keep an order of things, use an object if you want an object (something that doesn't have order of elements).

How decision structures can be used to your advantage, not add complexity to your code. Stop nesting IFs, figure out how Boolean logical operators work. Figure out how switch-case works.

RTFM. The best place to learn about better code is by reading the actual spec. Read the RFC specs on that part of code you're trying to use. Read the ECMAScript document. Read the W3C DOM spec. Read the W3C XHTML/HTML/HTML5 spec. Read the specs, they're good.

Focus on the long game, not a quick flash and die.

You should help the community, you should write code that will be around for a long time. Have some passion about your code and community. If you left bad knowledge somewhere, go the hell back and fix it. Bad information is really hard to purge and sticks around for ever. Do your part. Don't help w3schools make the web worse.

Don't jump in from nowhere and say "Hey I got a great idea for how to use which" drop a bunch of code that nobody can use and disappear. You contributed nothing. Don't use variables like a and chezburger.

Learn to spot the bad code and the good code, find it in your own code, make your bad code into good code.

Create something, learn something, teach something.

Broaden your horizons. You can't just write JavaScript forever --  take a sabbatical into something else that interests you, come back, share what you learnt and see if you can find a place for it in the community. Try to show the other world what value JavaScript has as well while you're out there.

You're still wrong, even when you do know everything. Use a proof to be correct, not your status/authority. You can never be right, but your proof is always correct. Don't get into pissing matches, as hard as it is to avoid sometimes. Either there's proof or there isn't. Flames help nobody.

For anyone interested, I've actually taken most of this from personal notes on a tutorial I'm nowhere done writing.


问:
How do you put different versions of your library under version control? Do you use tags? Or branches? Or another method?
I have recently started putting my code under version control (in the lab I'm working, under SVN, and my own codes in github (obviously with git)). Before using version control, I used to do something like this. I had a folder with the name of the library, inside many folders with the version number. Every time I wanted to start working on a newer version, I would make a copy of the last version, change the name to the new version and start implementing.

This however seems way redundant when the folder is put under version control. Apart from redundancy, if someone wants to get the latest version, they would be downloading all versions if they just import/clone.

Now I see many ways to doing this with version control but since I'm new to it, I don't know which would be more maintainable.

Method 1: Using tags

If I understood tags correctly, you would have your main branch, you commit whatever change you got and tag them with a version. Then, when you want to get a working copy of it, you get the one with a certain tag. (correct me if I'm wrong)

Method 2: Branching versions

In this method, the main branch would be the development branch. Every now and then that a stable version is made (let's say v1.2.0), you create a branch for that version and never commit to it. That way, if you want to download a certain version, you get the code from that branch. Although I said you never commit to it, it may be possible to do bug fixes and commit to an old version's branch to keep the old version running. For example if the current version is v2.0, but there are people who want to use v1.2, you can get another branch from v1.2, namely v1.2.1 and commit the bug fixes, or just keep the version the same as v1.2 and just commit the bug fixes.

So the branches would look like this:

```<code>                  v1.2.1  v1.2.2
                 /       /
 v1.0.0   v1.2.0---------     v2.0.0
/        /                   /
-------------------------------------- dev
</code>```

This way you have branches for every minor version update. (Note that in the graph above, v1.2.1 and v1.2.2 or created after v2.0.0 was released, so they were not part of the development between v1.2.0 and v2.0.0. Think of it as support for older versions)

Method 3: Branching development

This method is the opposite of the previous. The main branch would be the latest stable version. Whenever you are working on a new version, you create a branch (for development), work on your code and when it is stable, merge it with the main branch.

In this case, the branches would look like this:

```<code> ________  ____  ________________  _____ dev
/        \/    \/                \/
---------------------------------- latest_version
</code>```

Probably this one needs to be done in conjunction with tags right?

The question!

Anyway, my question is that based on your experience, which of these methods proves more practical? Is there a known best method out there (that possibly I didn't figure out myself)? How are these things commonly done?

答:
The three methods are not mutually exclusive, and you should combine the three to get the most out of your version control.

For my part, I would use a combination of method 1 and 3 by default, that is, develop in a feature or development branch until a feature is production-ready and then merge back into trunk. This way, trunk always represents the current state of stable, to-be-used development and can safely be linked by svn:external projects. When you release a version, tag it.

I'd only branch on demand, that is, when older versions of your library have a bug that has to be fixed. You can easily create that branch from the tag of the broken version. By not branching unnecessarily, you keep the number of branches low and have a quick overview over the bleeding edges that have to be maintained (trunk and all branches).

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Five or fewer tips to writing good JavaScript?
JavaScript has obviously become pretty indispensable; however, I'm still new to it, and I've found it's hard to fight the feeling that it seems such a mess and I don't want to deal with it right now. I'm much further in my understanding of other languages than I am with JavaScript, because I can't seem to get a handle on this fear. I get a feeling that, when I'm writing JavaScript, I'm trying to paint a portrait of Weimaraner puppies.

It usually helps me to keep a handful of the most important directives in mind that I can ask myself for each move I make. (To my mind, a handful is five or less.)

Can you list five (or fewer) questions specific to JavaScript I should ask myself for each move I make, when I'm coding JavaScript? What would they be?

Update: to clarify, I'm not asking for five things to keep in mind when learning JavaScript; I'm asking for five questions to always ask myself going forward, that everyone should alsways ask. High-level questions like: "Am I likely to repeat this somewhere else?" or "is this variable/function name specific enough (or too specific)" <== except these example questions are not peculiar to JavaScript. I'm looking for directives that are peculiar to JavaScript.

答:
I believe classes to be a quite powerful tool to structure code. There's a lot of language agnostic rules on how to design class based systems and some OO principles are actually more obviously implemented when using classes.

Therefore I suggest you have a look at CoffeeScript.

From there, I suggest you just try to gather information about how to implement SOLID, DRY, GRASP, KISS and YAGNI, and more importantly how to go about situations, where they seem to conflict (they never do, only your understanding of them or the problem at hand does). It's quite easy to find, even on stackexchange.

Please note, that these principles apply to "raw" JavaScript development just as much. However a lot of content you will find on them will illustrate them using class based languages and it might therefore be of use to program in a language, where there's not too much overhead involved in understanding them.

Personally, I think JavaScript is an extremely powerful language, but actually you will have to first deeply understand other languages, to really appreciate this fact.


问:
Do some languages make it easier to build graphically-intensive GUIs?
I made an algorithm that has a good potential use for a commercial application. I'm thinking of making a GUI, and since it's computationally expensive, I'm thinking of putting it "on the cloud" to offer the numerical part as a service. What I'm thinking is making a GUI, and then the users submit the work to the server. This GUI could be made open software (in fact, very probably will be). The GUI has a lot of graphics. Imagine something like making picks on surfaces plots, taking a look at those picks with different tools, and using numerical mathematics on those picks.

Are there languages that make this work easier? What, specifically, about them aide in creating GUIs like this?

答:
I strongly recommend Qt (especially QML)
It's got a lot of advantages compared to other GUI libraries

Cross platform

Build with QML and deploy everywhere.

Easy to learn if you already know C++

Compatible with Python (PyQt) so you can integrate with other Python libraries

Open-Source and I think it's also possible that in your case you can distribute your GUI for free and charge only for the application/algorithm that you've developed. Am not completely sure about that. If you find this is true let me know, am in the same situation.


问:
How to deal with an outsourcing company that brings your production system down?
We have a high load SAAS product and due to lack of resources the board has outsouced reporting and OLAP & Warehouse work to a 3rd Party Company. When we started working with them, they accidentally DOS'ed our production system, now they have made too many long running queries on the production databases and slowed the system down to unuseable. They are about to deliver and we have a maintainence contract with them. How do you deal with 3rd companies you can't really trust no to bring your production system down? And what do you do about it when they do? Has anyone any experience of this? (note they have a test environment set up to do everything they need to on).

I'm not looking for answers on how to prevent someone bringing down our system, I'm after what to do with the 3rd party company itself.

答:
3rd party vendors have to be held to the same standards that in-house would be. That should include qa testing, it should include performance specs that they have to meet. And it should include consequesnces for failure.

The best solution is to document the problems and ask management to fire them. That's what we did when we outsourced something and they broke production with their code fix when it was deployed (for a different client than the one they were working on even try explaining that to your clients). The board needs to know about their incompetence and fire them just as they would any other type of contractor. If they hired an airconditioning firm to come fix the broken airconditioner and they flooded the building by accident and then the airconditioning worked even worse when they were done, would they keep using them too?


问:
Real-time chat in Ruby on Rails without owning a server
I'd want to implement a Real-time chat for my Rails app but I can't really host the server which handles the sockets. I've tried Faye but it needs a server. I've also heard of pusher but it's limited to 20 users at a time on the chat and I can't really be sure they won't be more.

I've thought of IRC but I think I can't really embed it into a rails app, maybe it needs sockets...

How can I implement a real-time chat without owning a server?

答: You can't implement real-time chat without having a server capable of coordinating it in real time. Typical shared host web server setups are not suitable for this sort of thing -- they usually don't have the right sorts of things installed and typically don't have the umph to handle the traffic in any case. So typically you'll need to secure at least your own VPS especially if you care about performance and reliability.</p>


问:
Is it legal to recreate/opensource a program that you previously coded for another company
At my previous job I created a generic dashboard for automating tasks and it that turned out to be quite useful - and of course my previous employer owns all the code I wrote while I worked there. Now that I'm no longer there, is it legal for me to recreate that dashboard from memory and open source the code? If I do recreate it, the code (maybe 2k-3k lines) could be almost identical to the original since I have pretty good memory and tend to follow my usual coding style and naming conventions.

Edit: a little more background - this is a pretty generic piece of software that's used only internally by a small team (<10) within a global corporation. "The company" is not even aware of this system since it's I create it on my own initiative. It's built on python/django. And by almost identical I mean that for example the django models will have the same name/fields and views will use similar queries to return the same sets of objects.

答:
(a) Do not take legal advice from the internet (including this advice!)

(b) Being sued is a real pain in the backside, even if you win

(c) It sounds like you think there is no real risk of being sued. If so, then it probably doesn't matter whether or not you have the private law right to do this.

Whether or not it's legal, this is going to come down to how much you want to recreate this project vs how much you want to run the risk of being sued. If you have the money, then I suggest speaking with a lawyer first about whether you have the right to do this, and the cost of making litigation go away if you do.


答:
I'm making the assumption that you're using JavaScript for client-side UI development in a web-application.

1) Should this be client side or should this be server side? I know that I've gone and written serious chunks of code that really deserved to be on the serverside and vice versa. A lot of times I'll head into making an AJAX call for something that ends up just better placed in the Server code to be included on the way over. Especially things that are static in nature but change fairly regularly (list of categories for example.)

2) Is there a plugin that does this already? I use JQuery a lot and the answer is almost always YES! I'll often take plugin code that someone's written and adapt it to my needs (usually adding extra classes to things, etc.) but rarely do I ever need to start from scratch.

3) Is Javascript the right place for this? Occasionally I'll catch myself adding a whole bunch of dynamic styling to something via Javascript when it makes much more sense to use intelligent CSS.

4) Should I be using a different tool? This is something I've been grappling with lately. There are some javascript alternatives like coffee script that are handled well in my stack (Rails 3.1) and I've been considering whether or not to move much of my code there.

5) Is this Javascript code good code? Javascript is code like any other code. Is this code as good as the rest of my code? If not, why not? Is it throwaway? Am I lazy?

Title: Five or fewer tips to writing good JavaScript?

Body:
JavaScript has obviously become pretty indispensable; however, I'm still new to it, and I've found it's hard to fight the feeling that it seems such a mess and I don't want to deal with it right now. I'm much further in my understanding of other languages than I am with JavaScript, because I can't seem to get a handle on this fear. I get a feeling that, when I'm writing JavaScript, I'm trying to paint a portrait of Weimaraner puppies.

It usually helps me to keep a handful of the most important directives in mind that I can ask myself for each move I make. (To my mind, a handful is five or less.)

Can you list five (or fewer) questions specific to JavaScript I should ask myself for each move I make, when I'm coding JavaScript? What would they be?

Update: to clarify, I'm not asking for five things to keep in mind when learning JavaScript; I'm asking for five questions to always ask myself going forward, that everyone should alsways ask. High-level questions like: "Am I likely to repeat this somewhere else?" or "is this variable/function name specific enough (or too specific)" <== except these example questions are not peculiar to JavaScript. I'm looking for directives that are peculiar to JavaScript.


问:
Unicode clarification
Why is the length of the some characters e.g. the following 'ᨒ' 3 when it should be 2

ᨒ
U+1a12

1a12 means 6674

2^16 is 65536 so 6674 should take only 2 bytes and not three

答:
There are 3 encodings of unicode: UTF-8, UTF-16, UTF-32

In UTF-8 it takes 3 bytes: 0xE1 0xA8 0x92 as UTF-8 has variable length characters.

UTF-16 would take 2 bytes: 0x1A12 as UTF-16 has fixed length characters

http://en.wikipedia.org/wiki/UTF-8

http://en.wikipedia.org/wiki/UTF-16

UTF-8 character length from Wikipedia page:

```<code>Last code point Byte 1      Byte 2      Byte 3      Byte 4      Byte 5      Byte 6
 7  U+007F      0xxxxxxx
11  U+07FF      110xxxxx    10xxxxxx
16  U+FFFF      1110xxxx    10xxxxxx    10xxxxxx
21  U+1FFFFF    11110xxx    10xxxxxx    10xxxxxx    10xxxxxx
26  U+3FFFFFF   111110xx    10xxxxxx    10xxxxxx    10xxxxxx    10xxxxxx
31  U+7FFFFFFF  1111110x    10xxxxxx    10xxxxxx    10xxxxxx    10xxxxxx    10xxxxxx
</code>```

Title: Unicode clarification

Body:
There are 3 encodings of unicode: UTF-8, UTF-16, UTF-32

In UTF-8 it takes 3 bytes: 0xE1 0xA8 0x92 as UTF-8 has variable length characters.

UTF-16 would take 2 bytes: 0x1A12 as UTF-16 has fixed length characters

http://en.wikipedia.org/wiki/UTF-8

http://en.wikipedia.org/wiki/UTF-16

UTF-8 character length from Wikipedia page:

Last code point Byte 1      Byte 2      Byte 3      Byte 4      Byte 5      Byte 6
 7  U+007F      0xxxxxxx
11  U+07FF      110xxxxx    10xxxxxx
16  U+FFFF      1110xxxx    10xxxxxx    10xxxxxx
21  U+1FFFFF    11110xxx    10xxxxxx    10xxxxxx    10xxxxxx
26  U+3FFFFFF   111110xx    10xxxxxx    10xxxxxx    10xxxxxx    10xxxxxx
31  U+7FFFFFFF  1111110x    10xxxxxx    10xxxxxx    10xxxxxx    10xxxxxx    10xxxxxx


问:
There is a (social) network / website for developers share ideas and find a team for development?
Supposing I want to do some kind of project, but I want to find more people interested in that area that can develop some project with me, there is some website focused on this?

Example: "I want to develop action games for mobiles" or "Want to find web developers for a new social network focused on blah blah blah".

This already exists?

答:
Yeah, check out Github ... It a version control system but with a social factor and a developer community.

Check out the community features of github: https://github.com/features/community


答:
Check out Ohloh.

Learn what people are using and contributing to. See what's going on
  inside an open source project. Follow what your friends are coding

Title: There is a (social) network / website for developers share ideas and find a team for development?

Body:
Supposing I want to do some kind of project, but I want to find more people interested in that area that can develop some project with me, there is some website focused on this?

Example: "I want to develop action games for mobiles" or "Want to find web developers for a new social network focused on blah blah blah".

This already exists?


问:
What should a web developer know about HTTP?

Possible Duplicate:

  What should every programmer know about web development?

I've heard rumblings on this site that web developers should be familiarize themselves with HTTP.

What aspects of HTTP is it beneficial to know as a web developer, and why?

Update: This is not an exact duplicate of This is not a duplicate of "What should every programmer know about web development?"  I am asking specifically about the HTTP protocol.  I am not using HTTP to mean web development in general.

答:
Here would be my main ones:

Port numbers - This is because you may have to run sites on different ports where you may find a rude shock that some ports are commonly used for some things.  For example, 80 is the standard web port, 443 is the standard SSL port, 25 is for SMTP, etc.

HTTP Secure - This would be about security in terms of protocols commonly used by people where it helps to know a little of what is going on under the surface.

List of HTTP status codes - This can be useful just so that if you see a status code in Firebug or Fiddler you know what this or that means.

HTTP would have the more general data that could be useful though some of it may be common sense like a Request-response model and is stateless.


答:
The most important aspect of HTTP to a web developer is that it is stateless. Every web developer should know this, as it means that if you want to maintain a state for your application, you'll have to do that in your application/on your platform.

You use it in a request/response manner and every web developer should know  and understand at least the basic http commands GET and POST.

Title: What should a web developer know about HTTP?

Body:
Possible Duplicate:

  What should every programmer know about web development?

I've heard rumblings on this site that web developers should be familiarize themselves with HTTP.

What aspects of HTTP is it beneficial to know as a web developer, and why?

Update: This is not an exact duplicate of This is not a duplicate of "What should every programmer know about web development?"  I am asking specifically about the HTTP protocol.  I am not using HTTP to mean web development in general.


问:
How much time should I devote to my toolchain?
I'm a bit of a tool nut and I'll often spend as many as 6-8 hours a week finding new tools, improving my existing tools by writing plugins or adapters or playing around with new tools to see if I like them any better than the ones I have.

That's not counting that my official day job is basically tool-chain development for a large company.

Should I be spending this much time trying to improve my tool-chain? What should I be focusing on when improving it to maximize my time?

答:
Personally I'd say that unless you deal with particularly dynamic requirements, 6 - 8 hours a week is massively massively excessive.

What you need to ask yourself is how many of those hours are recovered by the efficiencies those tools offer you? If you use a tool 10 hours a week if it genuinely makes you 10% more productive then, assuming you keep a tool for a year, that's a 52 hours saving so, so long as you spent less than 52 hours on finding and selecting it then it was a good thing.

But I'm thinking that sort of saving is going to be rare. Think about the following:

What's the upskilling time? Sure you're going to be more productive eventually but for the most part that won't happen instantly and you'll be less productive to start. You need to figure in training time (zero productivity) and the bit when you're achieving less than you did, as well as the bit where you're more productive.

If you fiddle with tools a lot you're likely to swap them a lot. If this is the case then the payback time has to be a lot shorter as you probably won't have it for a year.

If you swap tools a lot you probably never become an expert in any of them. Perhaps becoming better with your existing tool is a cheaper way to productivity?

You probably work for 40 - 50 hours a week. You need to understand how much of that you spend on each task and how much it's really going to save you. If a tool allows you to do a database upgrade in half the time but they only take an hour and you do them once a month it's probably not that great.

So advice:

Look at the most time consuming tasks you carry out. What are the things that take you most time to do? The more time you spend doing something the greater the potential for savings. If you spend 10 hours a week doing something and can save 20% that's massive. Conversely if you do something rarely and or it's very quick (say half an hour) even eliminating it might not be worth the effort in doing so.

What are your pain points? Sometimes tasks cause disproportionate pain - perhaps they cause interuptions or make customers unhappy. These are things where it might be worth investing time but only if that time pays for itself in an increase in productivity greater than solving the problem or a similar increase in customer happiness.

Are you hearing really good things about something. And I mean really good things. If so then take a look, but be critical and look for credible people with solid stories and a consensus, not just people hyping something new.

Understand the difference between better and different. This is the biggest thing. Novelty is lovely but all too often it's not actually better. Programmers are the worst in the world for reimplementing something with a relatively minor change and touting it around. Different is interesting but it's not always better.

Set up a periodic review for each item in your tool chain and research it at that point. Personally I'd say more than once a year would be over the top. Somewhere around 18 months - 2 years would probably the point where things will have improved enough to justify a change.

Against all this, if you want to fiddle because you enjoy it, then by all means fiddle. Just don't kid yourself that it's productive when it's not and (as a development manager) please don't try to convince me it is unless you've been through the list above.


问:
What is it called when you set properties on object initialization?
What is it called when you set properties on object initialization?

```<code>var customer = new Customer() {RequestID = request.ID, AddressID = 5};
</code>```

Is it considered good practice?

答:
To add a bit to Falcon's good answer:

What is the name for setting properties when an object is instantiated?

It is an "object initializer". Note that the equivalent feature for collections is called a "collection initializer". That is, you can also say

```<code>x = new List<int>() { 10, 30, 20 };
</code>```

and that will be translated into

```<code>var temp = new List<int>();
temp.Add(10);
temp.Add(30);
temp.Add(20);
x = temp;
</code>```

for you. You can even mix object and collection initializers! See the C# specification section 7.6.10.3 for an example of how to use a collection initializer inside an object initializer.

Is it considered good practice?

We didn't add it to C# 3.0 because it was a bad practice!

The compelling benefit of object and collection initializers is not just that they are a much more compact, less "ceremonial" way to create and initialize an object. The compelling benefit is also that an object initializer is an expression, not a collection of statements. That means that you can use them in contexts where expressions are legal but statements are not, like:

field and local initializers

array initializers

expression lambdas

LINQ query comprehensions

and so on

Body:
To add a bit to Falcon's good answer:

What is the name for setting properties when an object is instantiated?

It is an "object initializer". Note that the equivalent feature for collections is called a "collection initializer". That is, you can also say

x = new List<int>() { 10, 30, 20 };

and that will be translated into

var temp = new List<int>();
temp.Add(10);
temp.Add(30);
temp.Add(20);
x = temp;

for you. You can even mix object and collection initializers! See the C# specification section 7.6.10.3 for an example of how to use a collection initializer inside an object initializer.

Is it considered good practice?

We didn't add it to C# 3.0 because it was a bad practice!

The compelling benefit of object and collection initializers is not just that they are a much more compact, less "ceremonial" way to create and initialize an object. The compelling benefit is also that an object initializer is an expression, not a collection of statements. That means that you can use them in contexts where expressions are legal but statements are not, like:

field and local initializers

array initializers

expression lambdas

LINQ query comprehensions

and so on


答:
I would say Everything.

HTTP is by far the most important application level protocol. The entire Web lives within HTTP, and the more we progress toward service oriented architectures -- the more of HTTP will be exploited.

Look at Google -- it's heavily HTTP based architecture. A simple search touches about 200 servers at Google and all of them communicate via HTTP.

Some years ago verbs like PUT or DELETE were virtually futile -- but now every decent RESTful service uses them.

Everybody knows caching is the best friend of scalability. How would you setup an efficient caching system without mastering HTTP caching infrastructure?

HTTP is the most well understood protocol -- there is an entire eco-system around it. You can NOT take good advantage of that if you're only moderately familiar with HTTP.

So, in my opinion, every Web developer should have a thorough understanding of HTTP.


答:
Generally as a developer you're being paid to solve problems or produce tools for other people to use to solve their problems. If you think about development as a lean process anything that doesn't add value to the product is waste and should be eliminated. Does have a cool new editor or plugin add value to your product? Probably not...so time spent on that should be eliminated.

Or not.

David Anderson has a good comment to go with this - "eliminating waste is like going for bronze [at the Olympics]". What you're actually trying to improve is cycle time (i.e. rate of delivery of value). There are lots of things in development that don't add value to a product that if you don't do them increase cycle time - daily stand-ups, testing, etc, etc. Of course eliminating waste is a good thing - but it shouldn't be your number 1 priority.

So...to answer your actual question...personally I think if you're spending 8 hours a week on tooling then it's likely to be very excessive. Sometimes though you will spot something that is a bottleneck and/or error prone and you'll be aware that there's some tooling out there that you can get, learn about, or build which will make you significantly more efficient.

Title: How much time should I devote to my toolchain?

Body:
I'm a bit of a tool nut and I'll often spend as many as 6-8 hours a week finding new tools, improving my existing tools by writing plugins or adapters or playing around with new tools to see if I like them any better than the ones I have.

That's not counting that my official day job is basically tool-chain development for a large company.

Should I be spending this much time trying to improve my tool-chain? What should I be focusing on when improving it to maximize my time?


问:
Is this a ridiculous way to structure a DB schema, or am I completely missing something?
I have done a fair bit of work with relational databases, and think I understand the basic concepts of good schema design pretty well. I recently was tasked with taking over a project where the DB was designed by a highly-paid consultant. Please let me know if my gut intinct - "WTF??!?" - is warranted, or is this guy such a genius that he's operating out of my realm?

DB in question is an in-house app used to enter requests from employees. Just looking at a small section of it, you have information on the users, and information on the request being made. I would design this like so:

User table:

```<code>UserID (primary Key, indexed, no dupes)
FirstName
LastName
Department
</code>```

Request table

```<code>RequestID (primary Key, indexed, no dupes)
<...> various data fields containing request details
UserID -- foreign key associated with User table
</code>```

Simple, right?

Consultant designed it like this (with sample data):

UsersTable

```<code>UserID  FirstName   LastName
234     John        Doe
516     Jane        Doe
123     Foo         Bar
</code>```

DepartmentsTable

```<code>DepartmentID   Name
1              Sales
2              HR
3              IT
</code>```

UserDepartmentTable

```<code>UserDepartmentID   UserID   Department
1                  234      2
2                  516      2
3                  123      1
</code>```

RequestTable

```<code>RequestID   UserID   <...>
1           516      blah
2           516      blah
3           234      blah
</code>```

The entire database is constructed like this, with every piece of data encapsulated in its own table, with numeric IDs linking everything together. Apparently the consultant had read about OLAP and wanted the 'speed of integer lookups'

He also has a large number of stored procedures to cross reference all of these tables.

Is this valid design for a small to mid-sized SQL DB?

Thanks for comments/answers...

答:
If the requirement is to have multiple departments per user, this design makes sense. The only gripe about it is the UserDepartmentTable having a surrogate key UserDepartmentID that is not needed (just make the UserId and DepartmentId a composite primary key).

If a user only ever belongs to a single department, your design makes sense (though a department lookup table would still be a good thing).


答: Makes perfect sense to me.  It's just very normalized, which imparts a lot of flexibility that you wouldn't have otherwise.  De-normalized data is a pain in the butt.</p>

Title: Is this a ridiculous way to structure a DB schema, or am I completely missing something?

Body:
I have done a fair bit of work with relational databases, and think I understand the basic concepts of good schema design pretty well. I recently was tasked with taking over a project where the DB was designed by a highly-paid consultant. Please let me know if my gut intinct - "WTF??!?" - is warranted, or is this guy such a genius that he's operating out of my realm?

DB in question is an in-house app used to enter requests from employees. Just looking at a small section of it, you have information on the users, and information on the request being made. I would design this like so:

User table:

```<code>UserID (primary Key, indexed, no dupes)
FirstName
LastName
Department
</code>```

Request table

```<code>RequestID (primary Key, indexed, no dupes)
<...> various data fields containing request details
UserID -- foreign key associated with User table
</code>```

Simple, right?

Consultant designed it like this (with sample data):

UsersTable

```<code>UserID  FirstName   LastName
234     John        Doe
516     Jane        Doe
123     Foo         Bar
</code>```

DepartmentsTable

```<code>DepartmentID   Name
1              Sales
2              HR
3              IT
</code>```

UserDepartmentTable

```<code>UserDepartmentID   UserID   Department
1                  234      2
2                  516      2
3                  123      1
</code>```

RequestTable

```<code>RequestID   UserID   <...>
1           516      blah
2           516      blah
3           234      blah
</code>```

The entire database is constructed like this, with every piece of data encapsulated in its own table, with numeric IDs linking everything together. Apparently the consultant had read about OLAP and wanted the 'speed of integer lookups'

He also has a large number of stored procedures to cross reference all of these tables.

Is this valid design for a small to mid-sized SQL DB?

Thanks for comments/answers...


答:
I don't think that either a WTF is warranted or that the guy is doing any mad genius kind of design - it's pretty standard database normalization.

The reason for the department table is that if you don't put the departments into a separate table you will have to deal with users in "Sales", "sales", "Salesmen", "Sails", and "Selling" departments, unless you do something to prevent it.  And having the extra table is (part of) the best way I know to do that.

Whether there should be a UserDepartment table is a tougher call, which of course means neither decision is way out and crazy.  On the one hand it's a pain when all your table design and logic had assumed one department per user and then that changes, on the other hand doing an extra join for no reason for years and years is a real possibility and also a pain.

I personally would agree with you that the UserDepartment table is probably overkill.  Even if it's included, the chances are that over time people will write queries that assume there is only one user per department, so you will end up with the worst of both worlds - an extra join for no reason prior to needing the table, and code not working anyway once more than one department per user becomes allowed.

EDIT - A key driver of whether the many to many relationship should be supported is if the business rules are clear.  If you have no idea how a user in multiple departments would even work there isn't much point in adding the table, since your code can't possibly correctly handle the cases where a user is in multiple departments.

Imagine that you did allow many departments per user, just in case.  You then implemented a business rule for assigning commissions, based on department.  Then multiple departments were allowed.  Fortunately, you also had the foresight to write your commission code in a way that took this into account.  Unfortunately, you added the commissions from each department for users in both.  Management wanted you to base in on the persons role for each sale.  So, how much good was having the table in advance?  What about the other tables you had "just in case" that are never needed at all?

LATER EDIT - Another reason the consultant might have wanted to add all those intermediary tables is addressed in this follow-up question, the answers to which give some reasons why refactoring a database is usually harder than refactoring code, which would tend to push you towards the "put in all the tables you might ever need" approach.


答:
Based on your statement (in a comment) that "this is not billable work time".  You've really changed the question to something other than we are likely to assume by reading the question in its current form.

I firmly believe that a good developer will continuously work to improve himself.  That improvement cam come through reading blogs and other things describing new or alternate development skill.  It could also come through the things you learn as you examine tools and/or improve them.

Spending 6-8 hours of personal time each week to:

Improve yourself as a developer = GOOD.

Fiddle around with tools and accomplishing nothing = FUN.

(You probably land somewhere between, making it "good fun"! :) )


答:
You can try out PubNub :

PubNub is considered a Web Push Engine able to push (or stream) any
  textual data in real-time data push to any types of clients across the
  Internet. PubNub solves all the complexity of pushing data in a
  scalable, secure, efficient, reliable and portable way. On the client
  side, APIs are provided so that it is very easy to build Bidirectional
  Data Push Apps (transforming your existing client or creating a new
  one from scratch). A powerful HTML5 library makes it possible to push
  data updates to Mobile Phones, Tablets and Web Pages in real-time data
  push through a zero-install client.

Title: Real-time chat in Ruby on Rails without owning a server

Body:
I'd want to implement a Real-time chat for my Rails app but I can't really host the server which handles the sockets. I've tried Faye but it needs a server. I've also heard of pusher but it's limited to 20 users at a time on the chat and I can't really be sure they won't be more.

I've thought of IRC but I think I can't really embed it into a rails app, maybe it needs sockets...

How can I implement a real-time chat without owning a server?


问:
Methodologies/tools for when developing on your own
Suppose you have to develop a medium+ sized software, fully on your own. Like if it was a personal project you want to accomplish.

What methodologies/tools would you use to define what needs to be developed, learned and have a global idea of what the system is as well in its details?

Basically to keep yourself in track and not get lost on the way.

答:
Tools:

Control Version System (even if if you the only developer in your garage or home personal P.C.): GIT, Mercurial, Tourtoise

Editor with source code highlight, even if you have an I.D.E. (Scintilla, Vim, Notepad)

Real world blackboard, whiteboard, some stuff just doesn't fit in your Designer Tools Application.

Design Tool: Rational Rose, Umbrello, (U.M.L., E-R,) Visio, or "Poor Developer's Designer Tools" like Power Point, Corel Draw, Open Office Draw

Text / Source Code Text comparison tool, e.g. WinMerge


答: In general, these questions are about risk and time value.  What is the probability that the future value of the time you are now spending on these tools will increase your productivity by at least an offsetting amount?  Sometimes this time spent pays off.  On the other hand, in the future you might look back and really wish you had done something more beneficial or useful with the time you are now spending on learning these new tools.  It's a gamble, so the answer "how much" has no generic answer.  You need to estimate your own individual odds.</p>


问:
Refactoring or upgrading databases to handle new features
Several responses to a database schema question, suggested an additional table to normalize a database for a feature that is not part of the current requirements (A UserDepartment table to allow for a many-to-many relationship between employees/users and different departments they may belong to.).

Not against normalization. Seems like when it comes to database design, there is a strong push to include features that they're 'sure' someone will want in the future. Is it so difficult to add tables/fields to the database to accomodate features that there is a tendancy to over-engineer? Wouldn't they be refactored or upgraded just like the rest of the app if needed? Redoing things is never fun, but moving data from one table to a new one can be done. Just not sure where this line of thinking will end.

Edit: There is so much of an aversion to this, I wonder how many projects end up not adding a feature that requires a drastic database change or are non-normalized approaches taken like adding a DepartmentID2 field instead of a new table. The need for multiple departments for an employee is a common domain problem. I just haven't noticed many database schemas that are littered with many-to-many relationships.

答: There is a fine line between spending lots of time over-engineering and investing a bit of your time to add just enough features to save you a considerable amount of time in the future.</p>


答:
I think the theory is that if you include a link table to support a many to many relationship between 2 tables, then even if really only many to one relationships exist in the data, everybody will write the SQL in such a way that if ever a many to many is supported everything will "just work".

In practice I have not usual found that this is true, but I suppose the SQL is closer to what it needs to be to support the many to many than it would otherwise have been.

But to get specifically to your question, there actually is a fair amount of pain converting a relationship from 1-to-many to many-to-many.  The reason is that SQL is not designed with the same kinds of encapsulation goals that objects are, and most queries use more tables on the database layer than people would be comfortable having an object in the business layer have visibility to.

Therefore a change to a many to many relationship will impact every query that involves the original 2 tables, often a much wider cascading effect than will happen on the business layer.  So people go to significant lengths to prevent this from happening.

IMHO this wouldn't be needed if we had a better language than SQL to specify the relational algebra.  If it were feasible to build up a SQL query piece by piece by objects that didn't need visibility to every table in the query this wouldn't happen.  Things like LINQ (to SQL or to Entities) attempt to solve this, but it is a very complex solution and tough to optimize (and I've been to DBA user groups where LINQ is mentioned and a collective groan goes up every time).  I dream of a database language that is universally supported with first class relational algebra functions...

In the meantime, yes, you can refactor from 1-to-many to many-to-many, but it can be a lot of work.

Title: Refactoring or upgrading databases to handle new features

Body:
Several responses to a database schema question, suggested an additional table to normalize a database for a feature that is not part of the current requirements (A UserDepartment table to allow for a many-to-many relationship between employees/users and different departments they may belong to.).

Not against normalization. Seems like when it comes to database design, there is a strong push to include features that they're 'sure' someone will want in the future. Is it so difficult to add tables/fields to the database to accomodate features that there is a tendancy to over-engineer? Wouldn't they be refactored or upgraded just like the rest of the app if needed? Redoing things is never fun, but moving data from one table to a new one can be done. Just not sure where this line of thinking will end.

Edit: There is so much of an aversion to this, I wonder how many projects end up not adding a feature that requires a drastic database change or are non-normalized approaches taken like adding a DepartmentID2 field instead of a new table. The need for multiple departments for an employee is a common domain problem. I just haven't noticed many database schemas that are littered with many-to-many relationships.


答:
Refactoring code is easy--you simply change the code and run your regression tests.

Refactoring databases is hard--you've got to move (a potentially huge amount of) data around, make sure none of it is dropped, make sure the constraints are maintained in the new schema.  And, if you have audit requirements on the data, you've got to be able to explain why it's organized differently and be able to match pre-refoctor data to post-refactor data.  Also, none of your old back-ups will match the new schema, which is yet another risk.

Scary stuff.


答: The code 6674 requires at least 13 binary bits to encode.  UTF-8 requires 5 prefix bits to indicate that a 2-byte encoded Unicode value isn't just two regular old 7-bit ASCII characters instead.  13+5 = 18, which is more than can fit in 16 bits or 2 bytes.  So it takes 3 bytes to encode (adding 2 more Unicode prefix bits).</p>

Title: Unicode clarification

Body:
Why is the length of the some characters e.g. the following 'ᨒ' 3 when it should be 2

ᨒ
U+1a12

1a12 means 6674

2^16 is 65536 so 6674 should take only 2 bytes and not three


问:
My customer wants me to record a video of how I develop his software product
Working as a freelancer, I often see strange requests from my customers, some of which can negatively affect my daily work¹, and others trying to set some sort of control. I usually encounter those things during preliminary negotiations, so it's easy enough at this stage to explain to the customer that I do care about my work and productivity and expect my customers to trust my work.

Things were much harder² on a project I just accepted, since it's only after the end of the negotiations (the contract has already been signed and did not mention anything about video tracking) and after I started to work on the project that my customer requested that I record a video of all I do on my machine when working on his project, that is, a video which will show that I move the cursor, type a character, open a file, move a window, etc.

I work in my own company, using my own PCs.

I answered to this customer that such request cannot be accepted, since:

Hundreds of hours of work on a dual-screen PC will require a large amount of disk space for the recorded videos. If I don't care about space, I do care about this customer wasting my bandwidth downloading those videos.

Recording a video can affect the overall performance and decrease my productivity (which is not actually true, since the machine is powerful enough to record this video without performance loss, but, well, it still looks like a valid argument).

I can't always remember to turn the video recording on before starting the work, and off at the end.

It may be a privacy concern. What if I switch to my mails when recording the video? What if, to open the directory with the files about this customers project, I first open the parent directory containing the list of all of my customers?

Such video cannot be a reliable source to track the cost of a project (I'm paid by the hour), since some work is done with just a pencil and a paper (which is actually true, since I do lots of draft work without using the PC).

Despite those points, the customer considers that if I don't want to record the video, it's because I have something to hide and want to lie about the real time spent on his project³.

How to explain to him that it is not usual practice for freelancers to record videos of their daily work, and that such extravagant requests must be reserved for exceptional circumstances⁴?

¹ The most frequent example is to be requested to work through Remote Desktop on a more-than-slow server which uses a more-than-slow Internet connection, or to be forced to use outdated software such as Windows Me without serious justification such as legacy support.

² In fact, I already did a lot of management and system design related work, which is essential, but usually misunderstood by customers and perceived as a waste of time and money. Observing the concerned customer, I'm pretty sure that he will refuse to pay a large amount of money for what was already done, since there is actually zero lines of code. Even if legally I can easily prove that there was a lot of work undertaken on the design level, I don't want to end my relation with this customer in a court.

³ Which is not as risky as it could be, since I gave this customer the expected and the maximum cost of the project, so the customer is sure to never be asked to pay more than the maximum amount, specified in the contract, even if the real work costs more.

⁴ One case when I effectively record on my own initiative the video of actions is when I have to do some manipulations directly on a production server of a customer, especially when it comes to security issues. Recording those steps may be a good idea to know precisely what was done, and also ensure that there were no errors in my work, or see what those errors were.

First update

Since the question attracted much more attention and had many more answers than I expected, I imagine that it can be relevant to other people, so here is an update. First, to summarize the answers and the comments, it was suggested to (ordered randomly):

Suggest other ways of tracking, as shown in Twitter Code Swarm video, or deliver a "short milestone with a simple, clear deliverable, followed by more complex milestones", etc.

Explain that video is not a reliable source and can be faked, and that it would be difficult to implement, especially for support.

Explain that video is not a reliable source since it shows only a small part of the work: a large amount of work is done without using a computer, not counting the extra hours spent thinking about a solution to a problem.

Stick with the contract; if the customer wants to change it, he must expect new negotiations and a higher price.

Do the video, "but require that the customer put [the] entire fee into an escrow account", require a lawyer to video tape all billable time, etc., in other words, "operate in an environment void of trust", requiring the customer to support the additional cost.

Search for the laws which forbid this. Several people asked in what country I live. I'm in France. Such laws exist to protect the employees of a company (there is a strict regulation about security cameras etc., but I'm pretty sure nothing forbids a freelancer to sign consciously a contract which forces him to record the screen while he works on a project.

Just do it and send the videos: the customer will "watch a few ten second snippets of activity he won't understand", then throw those videos away.

Say no. After all, it's my business, and I'm the only one to decide how to conduct it. Also, the contract is already signed, and has nothing about video tracking.

Say no. The processes and practices I employ in my company can be considered as trade secrets and are or can be classified.

Quit. If the relation starts like this, chances are it will end badly sooner or later. Also, "if he's treating you like a thief - and that is what he's suggesting - then it's just going to get worse later when XYZ feature doesn't work exactly the way he envisioned".

While all those suggestions are equally valuable, I've personally chosen to say to my customer that I accept to do the videos, but in this case, we must renegotiate the contract, keeping in mind that there will be a considerable cost, including the additional fee for copyright release. The new overall cost would be on average three times the actual cost of the project. Knowing this customer, I'm completely sure that he would never accept to pay so much, so the problem is solved.

Second update

The customer effectively declined the proposal to renegotiate the original contract, taking into account the considerable additional cost. He agreed to continue the project without video recording.

The project continued without video recording. Eventually, the customer seemed satisfied by the final result and cost, so the video recording was not mentioned again.

答:
Just to add another view, which is much easier, for your next request in line of this one:

Use a scm (like git) like you always do with your projects (right?). Hand over an export of the full repository, including the history, on delivery. This will be

cheap in terms of time (you already do it)

cheap in terms of disk space

easy to make an overview of (number of commits, dates between commits, graphs etc)

easy to look at steps in "the wrong direction"

easy for you to cover up steps in the wrong direction (merging and rebasing in git terms) but still keep the time log correct

The rest that's on my mind has already been said.


答:
You need to measure them against a known standard and when they fail to meet that standard then you should have the option to renegotiate or terminate.   Here's a link from garter that might provide some usable insight, Measuring the Performance of Outsourcing Engagements

If these decisions were dictated by management based upon a price per hour measure then your only recourse will be to illustrate to them in specific, objective, measurable, verifiable terms how much this decision is costing over and above the price per hour of the solution.   Where you have very ineffective outsourced resources you can actually have a negative return on investment, even if the price per hour for the resource was a dollar per hour:  Outsourcers cost X; our delays, downtime and opportunity costs related to the site have cost Y.   Where Y>X, get rid of the outsourcer.

Title: How to deal with an outsourcing company that brings your production system down?

Body:
We have a high load SAAS product and due to lack of resources the board has outsouced reporting and OLAP & Warehouse work to a 3rd Party Company. When we started working with them, they accidentally DOS'ed our production system, now they have made too many long running queries on the production databases and slowed the system down to unuseable. They are about to deliver and we have a maintainence contract with them. How do you deal with 3rd companies you can't really trust no to bring your production system down? And what do you do about it when they do? Has anyone any experience of this? (note they have a test environment set up to do everything they need to on).

I'm not looking for answers on how to prevent someone bringing down our system, I'm after what to do with the 3rd party company itself.


答:
Commercial reality Lessons, Subcontracting 101:

Guideline 1) Subcontractors are usually professionals who want you to succeed and will do their best to make it happen.

Rule 1) Subcontractors are in it to make money. They care as much about your business, software and systems to do enough to receive the payment of their next invoice.

Rule 2) Not all contractors are created equal.

Rule 3) If you believe any different you are setting yourself up for disappointment and failure.

Make it worth the subcontractors while not to bring it down, or conversely, not worth there while to do so.  Contractually penalty clauses are useful to remind them that they have to perform to certain standards, as is withholding payment unless / until certain criteria are met.

Technically there is absolutely nothing you can do. If you give them access to your production system, they can break it at any time, in any imaginable and unimaginable way.


答:
There are two ways to look at design of software (and probably many other things) - A tactical view or a strategic view. Each has its own advantage and drawbacks.

Even with OO software modifications is still a pain, not only the coding part is difficult, but the process of promoting a change to production in a complaint environments (given the current state of tech.) is unreal for large systems that are supposed to be working 24/7.

I follow my principle that says: "When possible, design shared software artifacts strategically" - This may sound like it goes against the YAGNI principle in some way, however, this is my opinion. This approach guarantees less re-work on the cost of complexity and resources.

In your case, the activities required to add a new junction table would include: design, design approval, changing the schema, re-writing several methods for CRUD for 3 tables (with the exception of some reads), building indexes, create GUI for the CRUD for the new table, to allow the user to select the PKs in create, update of the new table, etc. Oh, and by the way don't forget unit testing, user acceptance testing, system testing and production promotion.

If this is not enough, the real nightmare comes from information loss. If you did not have the junction table to begin with and you decided to capture the dates where the association/separation between an employee and a department occurred, you won't be able to automatically populate the date on the junction table. You got to enter those manually (if you have the data).

So, it is better to foresee this from the start.


答: As Matthew said above, refactoring/changing databases is often more involved compared to software as managing data also needs to be taken into consideration. There are techniques that can help eg ensure that you have an appropriate suite of database unit tests, decouple client applications from your base schema by using a 'DB API' - sprocs/views etc.</p>


答:
Some requirements are not clear in your question. The correct answer depends on what your customer wants - If I were you, I would ask the customer about this:

0-What is the difference between a user and an employee?

1-Assuming an employee=user, what if an employee changes departments?

2-Can a group of employees make 1 request?

3-Could an employee belong to more than one department? What about the CEO

4-Is there a subset of employees that are allowed to make requests?

5-What happens to the request when an employee record is deleted (if ever)?

6-Could you delete a request? What happens when the request is delted (make sure you don't delete the employee record by RI)

7-Can the employee make the "same" request more than one time (define the "same")

8-How to handle requests for employees when they leave the company (cancel their requests or delete the requests?)

There may be more questions, but my point is that the solution depends on exact requirements and project scope. Once that is determined the schema can be derived directly. Accordingly both solutions presented may be correct.


问:
What is the point of properties?
Here are some arguments for properties and my counter-arguments:

Easier to use than writing getter and setter methods

Getter and setter method pairs are a code smell.  Making it easier to write these is like making it easier to fail a math test by using a Scantron form and filling in all 'C's. Objects that contain only state, for persistence, shouldn't be using getters/setters and should be creating immutable objects at the time of persistence.

What is important to a consumer of an object is what it does, not how it does it.  Its behavior is what it does; its state is how it does it.  If you find yourself caring about an object's state (except for persistence, though this also breaks OO), you're simply not doing OOP and losing out on its advantages.

They give a rough indication of performance to consumers

This is something that could change in the future, for any given property.  Suppose in release 1.0, accessing PropertyX simply returns a field.  In release 1.5, if the field is null, PropertyX uses the Null Object pattern to create a new null object.  In release 2.0, the field is getting further validated by the getter method in PropertyX.

As the property gets more and more complex, the performance indication of using a property seems less and less truthful.

They're better than public fields

This is true.  But so are methods.

They represent a fundamentally different aspect of an object than a method, and all consumers of the object should care about this

Are you sure that both of the above statements are true?

They're easier to type, man

Sure, typing myObject.Length is easier than typing myObject.Length(), but couldn't that be fixed with a little syntactic sugar?

Why use methods instead of properties?

No performance guarantees.  The API will remain truthful even if the method gets more complex.  The consumer will need to profile their code if they are running in to performance issues, and not rely on word-of-API.

Less for the consumer to think about.  Does this property have a setter?  A method sure doesn't.

The consumer is thinking from a proper OOP mindset.  As a consumer of an API, I am interested in interacting with an object's behavior.  When I see properties in the API, it looks a lot like state.  In fact, if the properties do too much, they shouldn't even be properties, so really, properties in an API ARE state as they appear to consumers.

The programmer of the API will think more deeply about methods with return values, and avoid modifying the object's state in such methods, if possible.  Separation of commands from queries should be enforced wherever possible.

So I ask you, why use properties instead of methods?  Most of the points on MSDN are code smells in and of themselves, and don't belong in either properties or methods.

(These thoughts came to me after thinking about CQS.)

答:
You have almost the opposite religious viewpoint to me :)

When I moved from Delphi to Java the lack of properties was a huge affront to me.  I was used to declaring a property and either pointing it directly to a private variable or writing a (protected) getter & setter then "plumbing" them to the property. This encapsulated the property and controlled how it should be accessed in a clear unambiguous way.  You could have a read-only property that calculated the total when accessed and call it "Total" not "_getTotal()" or similar ballochs.  It also meant that you could restrict access to properties by making them protected in the abstract base class then moving them to public or published in subclasses.

To me, properties are a more natural & expressive way of setting & getting the state of the object.  Relying on unenforced coding conventions is more of a "code smell" than anything you're criticizing properties for.  Also, as others have said, coming up with a badly designed use of properties and using its failings to try & dismiss the concept of properties in general is extremely bad form.  It's possible that you've only seen bad use of properties & assume that's the way it is I suppose but you should do more research before becoming too dogmatic.

ContentLicense: CC BY-SA 2.5

Title: What is the point of properties?


答:
The general rule is if a relationship is one to one but may in future be many to many then make it a many to many.

The employee/department is a classic example. In most small companies this is effectively a one to many relationship most of the time. However there is almost always a situation where it becomes many to many -- one of your engineers moves up into management, but, is still responsible for supporting a product he developed while he was in engineering, or, one of your sales people moved to product development, but, because he has a close relationship with an important customer he is still lead salesman for that customer.

It doesn't cost much more if a one to many is implemented as a many to many -- but refactoring a database and application to support a many to many is expensive and fraught with difficulty.


答:
It may easily grow beyond the reach of your attention. Not the span, the breadth.

It's hard to consider too many elements at once.

And then... it becomes a regression rollercoaster.

Everything you do breaks previous things, and rolling  back doesn't help.

To avoid that you should aggressively test for regression.

Automatically. (You can't do that otherwise and stay sane)

Testing will add a tough strain to your energies.

If the project is all about UI... you're probably toast:

UI testing is hard.

Automated UI testing is... still hard.

Untested last minute idea for UI focused projects

  Enroll a relative with spare time and a fondness of clicking his mouse as a UI tester.

  I'm thinking "teenager" here.

Other issues:

It will take forever.

You will confront writer's block.

(It doesn't actually exists as a condition, it's a popular mislabel people attach to their lack of discipline)

If you're used to and love some kind of version control, use it.

Starting to learn one now will distract you.

Graphing out you ideas, as already pointed out, may help.

I've used Freemind, CMaps, XMind, yEd, graphviz, and… something else.

XMind is the less pointless:

very fast to insert the data into

automatic layouts

stricly trying to make you stay on topic

very good for taking notes during a lesson (I so wish I had it in college)

still hard to use while making your mind up about something you haven't clear there.

A pencil and a notebook still score pretty good on my top ten:

I scan many of my notes

I make many little explicative drawings.

(If you think with images you may never find a fulfilling brainstorming tool)

As a last resort, you can always prepare powerpoints for your own consumption :)

Title: Methodologies/tools for when developing on your own

Body:
Suppose you have to develop a medium+ sized software, fully on your own. Like if it was a personal project you want to accomplish.

What methodologies/tools would you use to define what needs to be developed, learned and have a global idea of what the system is as well in its details?

Basically to keep yourself in track and not get lost on the way.


问:
Are interfaces and method signatures copyright protected?
For example, is it copyright infringement if I write a class called Random with the exact same purpose and method signatures as Microsoft's .Net System.Random class? Does it make a difference what language it's written in? In this case I want to write a Random class for use in ActionScript, which lacks a built-in seeded PRNG class.

If anyone has good links or reference suggestions for understanding what aspects of software are protected that's great too. And yes I know this isn't the place for "real" legal advice. If anyone goes to court pointing to a public message board as precendence--shame on them.

答:
There was a similar question about database schemes: Copying a competitor's database schema? I answered there that copying the whole schema would probably be a copyright infringement, depending on the scale of the copying, appreciated by a judge.

Even if your question is similar, I will answer quite the opposite: you can copy method signatures. Why?

In fact, method signatures come from common sense.

Firstly, if we take an extreme example, Microsoft cannot copyright the name Random and sue everyone who will use the word Random in any application.

Secondly, what are you trying to do exactly? Reimplementing .NET Framework? Why? There is no need to reinvent the wheel. If you know how to make it better, more intuitive, etc., chances are you will come with better names of classes and methods, a better organization, etc. If you try to copy the structure of .NET Framework to port it to another language, then you're not a direct competitor of Microsoft, so they have no serious reasons to sue you (this being said, they will sue you if you copy the source code itself). Actually, they will even benefit from you: copying such structure to other frameworks will not only show the success of .NET Framework, but will also make it easier for .NET developers to work with other languages, and the developers from other languages to learn .NET.

Thirdly, they have more serious things to do than to sue everyone who will copy the names of the methods and classes of .NET Framework.

Now, if your intent is to copy the whole .NET Framework and to make a product which will be used by lots of developers, consult a lawyer before taking risks.

An example:

I was totally unhappy with the shaming 259 characters limitation in file paths in .NET Framework and the inability to use code transactions on file level. So I implemented my own File class with the methods which would work as expected for any path, not just the tiny short ones, and implement transactions. In the first version, I decided to clone the names of methods in File and Directory classes. Would Microsoft sue me for doing that? I doubt it.

In all cases, in the second version I came with a new syntax, new File(string fileName), which I find much more intuitive for me. Cloning names of methods is sometimes useful, but you have to have a good reason to do it.


答: I believe looking at the relationship between Mono and Dotnet answers this question. The Mono team can make use of the method definitions or public interface but they have to reimplement the internals. However the Android v Oracle case brings up a few other points that make this obvious distinction a little blurrier. In the AvO case most  of the points being taken to court are patents related the VM, the library interfaces have not been a point of contention. The only code that has been highlighted are examples where it looks like to some extend that the internals were copied.</p>

Title: Are interfaces and method signatures copyright protected?

Body:
For example, is it copyright infringement if I write a class called Random with the exact same purpose and method signatures as Microsoft's .Net System.Random class? Does it make a difference what language it's written in? In this case I want to write a Random class for use in ActionScript, which lacks a built-in seeded PRNG class.

If anyone has good links or reference suggestions for understanding what aspects of software are protected that's great too. And yes I know this isn't the place for "real" legal advice. If anyone goes to court pointing to a public message board as precendence--shame on them.