问:
Java: How to make local fields & parameters final without having a 'final' keyword on each declaration
By default, I want all my local variables and method parameters to be final. Unfortunately, the Java language designers chose a different default: variables&parameters are by default non-final, and final variables&parameters need to be declared with the final keyword. So I need to add lots of finals. (And obviously I don't do this manually, but have my IDE add them for me.)

So I end up with source code where every default case is marked, whereas exceptions to my preferred default are barely visible. For readability, I would like it to be the other way round, i.e. only non-final local variables and parameters should be marked/highlighted/annotated/...

Is this possible?

I'm open to solutions that integrate at different levels, e.g. folding within the editor, style checkers, build steps, etc...

答: I think you need to read about the purpose of final and stop misusing it.  http://en.wikipedia.org/wiki/Final_%28Java%29   The whole point of final is if you want to make a member of a class public (yet constant) rather than hide it behind a getter, Or if you want to put a method in a class and make it impossible to override, Or if you want to make a class unextendable.  Using final for a slew of variables in a local function is a total abuse of the language (and is not going to give you some magical performance boost like you think since they still have to go onto the function stack!).  What would make sense to do is create a class that holds all your final variables and just reference it in your local functions, or make final global variables.  And as for adding the final keyword, just start all the variables with fnx_variablename and use search and replace to turn fnx_variablename to final fn_variablename; you should use some kind of convention to show they are final after all.


问:
Is it possible to develop a web application entirely in Javascript today (client and server) including a RESTful API exposing PostgreSQL data?
Where I work we have over a dozen internal SW systems that we have developed in-house using a variety of technologies, frameworks, and languages. Those include various from Microsoft (ASP.NET Web Forms, WebAPI, WinForms, SharePoint, Office Automation, Win8 Native Apps, SQL Server, SSRS) and others not from Microsoft (plain-old JS/HTML/CSS, PHP, Lithium, PostgreSQL, MySQL). Our SW dev team has grown and shrunk again to where it's just me and one other dev now. I love trying shiny new tech and taking advantage of different tools to get things done, which partly explains the huge span of different technologies we've chosen over the years, but we're suffering from the "jack of all trades, master of none" syndrome.

Now we've been told that the company is expecting significant new growth and that the two of us will need to produce a number of new applications over the next year. I'm ready to consolidate our skill sets and tool sets so that we can master the tools and focus more on the business problems we will face without having the slowdown of context switching between technologies. The two of us have been doing a lot of "plain old" JS/HTML5/CSS3 development recently and I would like to focus on that technology set moving forward.

We will be primarily using PostgreSQL as our data store on the back end (possibly augmenting with some NoSQL for very specific uses, and probably needing to find an advanced full-text search tool to integrate in). Our primary user interfaces will be a combination of traditional web apps and Single Page Apps (50%-50% mix), but there is the hope for native mobile apps down the line. Therefore I would like to expose our business data via a RESTful API so that it's easy to consume by various clients. And the most important factor in all of this is that I want to be able to code exclusively in Javascript from front to back (with the exception of writing SQL as necessary for the DB layer, and HTML5/CSS3 for the presentation).

This leaves me with the following questions:

Is it possible today to code all these layers/components exclusively in Javascript without resorting, for example, to PHP on the server, or C# for the RESTful API (i.e., WebAPI)?

Is node.js required to make this a reality, or can I use a non-node web server and still achieve the "Javascript-only" ideal? (related...would node.js just make more sense in a JS-only paradigm?)

Are there any frameworks for building JS-only RESTful APIs that can talk to PostgreSQL?

Are there any advanced full-text search tools (such as Lucene) that allow you to program against them with a JS-only approach?

答: There are tools like Wakanda that allow you to author an entire client/server application in Javascript.  PostgreSQL integration is possible, but a lot of these new-generation tools are NoSQL solutions. </p>

ContentLicense: CC BY-SA 3.0


问:
Developing Python on Windows and deploying to Linux
I have a client who would prefer to host their application on Linux. However, my coworkers and I have very little experience with Linux. This is a short project with a low budget, so making choices that save time and money are not just desired, they're a must. We are also heavy on continuous integration and automation, much of which we already have figured out in Windows and can reuse from previous projects. That said, having the development team learn Linux and rebuild our automation so we can develop on the same environment to which we intend to deploy is most likely not a viable option. (For a larger project, perhaps, but not this one.) The team is familiar enough with Python that writing the application in Python is a viable option (even though most of our development is done in .NET), although we would need to figure out a good packaging mechanism that can run on Windows and be pushed to a Linux box. I don't anticipate needing any libraries unavailable on Windows. Most likely, we will only need psycopg and sqlalchemy in terms of libraries with native components.

All this makes the notion of having developers create the application on Windows, deploying to a Linux testing environment, and then pushing to production after thorough testing seem like a fairly attractive option, but I'm skeptical about it. Linux and Windows are very different operating systems, and I'm concerned about gotchas that could creep up and make life very difficult. Are there any real concerns with doing this (beyond the typical file path differences and other common things easily solved by good coding practices)? I think that a lot of shared hosting providers host on Linux, and I can't imagine everyone using them has developed on Linux for the past umpteen years. Is this done more commonly than I'm aware?

答:
Don't know about python, but I've moved Java applications from Windows to Linux and vice-versa.  Java makes the "write once, run anywhere" claim which may not be 100% true, but with very little work I was able to make it true enough (basically everything works great on Linux, a few issues on Windows).

I'll use W and L for Windows and Linux:

W: files and folders are case insensitive.  L: case sensitive.  Test file name capitalization carefully on Linux because Windows hides these issues.

Windows has a more granular file permissions system, that lets you use intersections of various groups and permissions.  Linux has a simpler system of one group and one user per file or folder.  Plus an execute-bit.  Well, there are some other little things like setting the execute bit on a folder makes the permissions cascade the way they do in Windows vs. being set to the user and group that created each file the way they do by default in Linux.  These issues mostly come into play when zipping and unzipping files, for instance during an install.

W: drives are mounted in the root folder as letters.  L: Drives are mounted anywhere as anything.  A single file can appear multiple places in your file system (symlinks).

Folder separator: W: \ L: /

Path separator: W: ; L: :

End of line in a text file: W: \r\n  L: \n

Default character set: W: ISO-8859-1  L: UTF-8

You need to know which Linux distribution you are targeting.  Two areas of difference are how System V init scripts are handled and how super-user tasks are performed (sudo vs su).  Also you mentioned an install script.  Apt and Yum are popular, but you need to work with the tool that your distribution uses.  Use yum on RedHat, apt on Debian, etc.

This is why you need a Linux machine for testing, whether virtual or physical.  It must use the same exact distribution you are targeting.  Have someone set up a dual-boot on an old server or something.  I also strongly recommend cygwin for every developer.  The file permissions aren't quite the same as Linux, and you can set it to case sensitive (though it's more useful case insensitive on Windows) but it makes a pretty reasonable test bed.

It doesn't hurt you to know both (Windows and Linux) and once you do, you can make an informed choice about what works best for you.  I was a Windows-only developer for the first 10 years of my career.  I've been almost purely Linux for the last 4-6 years, so some of my Windows information might be old.  I still run Windows in a virtual machine to do testing on Internet Explorer.

One thing you will get used to quickly on Linux is that you can solve most problems by Googling the error message.  90% of command line tools tell you how they work if you type "man ."  If you really need it, most source code is easily available, depending on the distribution.  When I solve a problem in Linux, I feel like I learned something about how computers really work.  In Windows, I feel like I just keep blindly trying stuff until something works.  When I find the solution, I'm lucky to remember everything I tried, no less know what it all means.

So I'd encourage you to spend some of your own time learning Linux and this job might be a way to get paid for some portion of that learning.  But don't mistake temptation for opportunity.  If the time frame is truly short, or money is tight, you may have to say that you have to deploy to what you know (Windows) or not take the job.


问:
What exactly makes code "clean"?
I am an intern at a small software company, doing typical grunt work. Many tasks that the actual developers are doing are above my head however I finally got to see some real "action" and write some code myself. I will admit the task was perhaps a bit too difficult for me but I managed and my coded worked in the end. When my mentor was doing code-review he had said to me "Man, this part is ugly." When I said, "Why? Is something wrong with it?" he replied, "No, the code works, but it's just not clean code." The concept of of clean code is one I have run across a few times before, especially now since that I get to hang around professional developers. But what exactly is it that makes code "clean"? In other words what is the criteria?

I have heard in formal mathematics, a "beautiful" proof, is one that is ideally as clear and as short as possible and uses creative techniques. Many people know that in literature, "good" literature is one that can express feelings effortlessly and elegantly to the extent that one can "feel" it. But one can't "feel" code (at least I can't) and I think most would agree that short code is not necessarily the best (as it could be very inefficient) or even that the most efficient way is always preferred (as it could be very long and complex). So, what is it! Please, try to enlighten me to just what exactly makes code "clean".

答:
In my estimation, clean code has the following characteristics:

It is clear and easy to understand,

It is loosely coupled,

It has relatively low cyclomatic complexity,

It has a sensible, flexible architecture,

It is easily discoverable,

It is well-designed and

It is testable.

Note that these are all subjective, although principles like SOLID and practices like TDD can go a long way towards achieving these goals.  Also note that, as with most software dynamics, they're not necessarily mutually compatible; there are always tradeoffs.

Also note that I didn't mention performance at all, because code that is highly performing is often the opposite of clean.

Title: What exactly makes code "clean"?


答:
My answer is not as constructive as Robert Harvey's answer. But I can add some options which I am using during development. Considering performance issues some of them should avoid or remove when publishing in real world.

Use comments in your code. Maybe several supervisors may have to look upon your work after your coding.

Use meaningful words for variables, functions, and methods. Not just a, b, c, etc.

Avoid using several whitespaces between code. It's annoying.

Lines of code should be in a sequence. It makes code more readable.

Title: What exactly makes code "clean"?

Body:
I am an intern at a small software company, doing typical grunt work. Many tasks that the actual developers are doing are above my head however I finally got to see some real "action" and write some code myself. I will admit the task was perhaps a bit too difficult for me but I managed and my coded worked in the end. When my mentor was doing code-review he had said to me "Man, this part is ugly." When I said, "Why? Is something wrong with it?" he replied, "No, the code works, but it's just not clean code." The concept of of clean code is one I have run across a few times before, especially now since that I get to hang around professional developers. But what exactly is it that makes code "clean"? In other words what is the criteria?

I have heard in formal mathematics, a "beautiful" proof, is one that is ideally as clear and as short as possible and uses creative techniques. Many people know that in literature, "good" literature is one that can express feelings effortlessly and elegantly to the extent that one can "feel" it. But one can't "feel" code (at least I can't) and I think most would agree that short code is not necessarily the best (as it could be very inefficient) or even that the most efficient way is always preferred (as it could be very long and complex). So, what is it! Please, try to enlighten me to just what exactly makes code "clean".


答:
Python code

As soon as your application is a well-behaved egg, or a set of eggs, and you can easily deploy it into a virtualenv using pip or easy_install, you should be fine on any platform.

Things to pay attention to:

Native-code dependencies. You might depend on some eggs that include these (like psycopg); make sure that such an egg is equally supported on Windows and Linux.

File paths. Make sure you don't use a hard-coded "\" anywhere; always use path.sep, path.join, etc.

File names. Unix filesystems are case-sensitive, so 'Foo' and 'foo' are different files. Make sure you preserve the case of file names.

App servers

Most probably you're writing a web app. Part of it is usually non-Python: the web server, DB server(s), etc. Things may be not as cross-platform: for instance, there's a Windows version of nginx, but not of uwsgi.

Bite the bullet

While you may do all of your development, unit testing, and part of integration testing, on Windows, there's no way around deploying your app on Linux.

Install Linux in a VirtualBox, or use a VPS (Amazon AWS, DigitalOcean, etc). Try to mimic the target deployment environment of your customer as closely as possible.

Install non-Python components, like the web server, memcached, or anything else platform-specific, on that machine. Ask your customer to configure these things for you if they have strong opinions about that. You can keep Postgres and other platform-independent things where you like.

Deploy regularly on the Linux machine. Usually it's just ssh linux-machine, pip -U install <your-eggs>, and, for example, sudo service uwsgi restart. You don't have to be expert sysadmins to cope with that. But if you learn some Linux lore along the way, be sure that it will be useful in the future.

Title: Developing Python on Windows and deploying to Linux

Body:
I have a client who would prefer to host their application on Linux. However, my coworkers and I have very little experience with Linux. This is a short project with a low budget, so making choices that save time and money are not just desired, they're a must. We are also heavy on continuous integration and automation, much of which we already have figured out in Windows and can reuse from previous projects. That said, having the development team learn Linux and rebuild our automation so we can develop on the same environment to which we intend to deploy is most likely not a viable option. (For a larger project, perhaps, but not this one.) The team is familiar enough with Python that writing the application in Python is a viable option (even though most of our development is done in .NET), although we would need to figure out a good packaging mechanism that can run on Windows and be pushed to a Linux box. I don't anticipate needing any libraries unavailable on Windows. Most likely, we will only need psycopg and sqlalchemy in terms of libraries with native components.

All this makes the notion of having developers create the application on Windows, deploying to a Linux testing environment, and then pushing to production after thorough testing seem like a fairly attractive option, but I'm skeptical about it. Linux and Windows are very different operating systems, and I'm concerned about gotchas that could creep up and make life very difficult. Are there any real concerns with doing this (beyond the typical file path differences and other common things easily solved by good coding practices)? I think that a lot of shared hosting providers host on Linux, and I can't imagine everyone using them has developed on Linux for the past umpteen years. Is this done more commonly than I'm aware?


问:
Is the development of CLI apps considered "backward"?
I am a DBA fledgling with a lot of experience in programming.

I have developed several CLI, non interactive apps that solve some daily repetitive tasks or eliminate the human error from more complex albeit not so daily tasks. These tools are now part of our tool box.

I find CLI apps are great because you can include them in an automated workflow.

Also the Unix philosophy of doing a single thing but doing it well, and letting the output of a process be the input of another, is a great way of building a set of tools than would consolidate into an strategic advantage.

My boss recently commented that developing CLI tools is "backward", or constitutes a "regression".

I told him I disagreed, because most CLI tools that exist now are not legacy but live projects with improved versions being released all the time.

Is this kind of development considered "backwards" in the market?

Does it look bad on a rèsumè?

I also considered all solutions whether they are web or desktop, should have command line, non-interactive options. Some people consider this a waste of programming resources.

Is this goal a worthy one in a software project?

I also think that for a web or desktop app, having an alternate CLI interface is a great way of demonstrating that the business logic is completely decoupled from the GUI.

答:
The GUI and CLI both have their place.  The GUI is great for allowing a user to perform certain canned operations quickly.  The CLI is for when you want to do things the GUI doesn't allow you to do.  The CLI is usually more powerful and harder to use.

A good CLI tool allows the user to do things the person who wrote the tool never thought of.  One example is the UNIX 'find' command.  This command:

```<code>find . -type f -name xyzzy\* -maxdepth 5 -mtime +3 -exec rm {} \;
</code>```

finds files under the current directory (but limited to 5 levels down) that have a name starting 'xyzzy' and were modified more than 3 days ago and then delete them (note: untested code).  And that's a moderately simple usage.  You can use a file manager to do that sort of thing, but it will take longer and is error prone.  Of course, being more powerful means the CLI can be more easily misused and create problems for yourself!

A good developer might write a CLI tool in such a way that it also has a GUI allowing a limited set of operations to be performed.  The user can start with the GUI and learn the complexities of the CLI later.

A good (long and biased (?)) read on the CLI/GUI tradeoff is at:

```<code>http://www.cryptonomicon.com/beginning.html
</code>```

Body:
The GUI and CLI both have their place.  The GUI is great for allowing a user to perform certain canned operations quickly.  The CLI is for when you want to do things the GUI doesn't allow you to do.  The CLI is usually more powerful and harder to use.

A good CLI tool allows the user to do things the person who wrote the tool never thought of.  One example is the UNIX 'find' command.  This command:

find . -type f -name xyzzy\* -maxdepth 5 -mtime +3 -exec rm {} \;

finds files under the current directory (but limited to 5 levels down) that have a name starting 'xyzzy' and were modified more than 3 days ago and then delete them (note: untested code).  And that's a moderately simple usage.  You can use a file manager to do that sort of thing, but it will take longer and is error prone.  Of course, being more powerful means the CLI can be more easily misused and create problems for yourself!

A good developer might write a CLI tool in such a way that it also has a GUI allowing a limited set of operations to be performed.  The user can start with the GUI and learn the complexities of the CLI later.

A good (long and biased (?)) read on the CLI/GUI tradeoff is at:

http://www.cryptonomicon.com/beginning.html


答:
I think Robert Harvey has a great answer but I'd like to expand on what I believe is the most important part:

It is clear and easy to understand

A lot goes into writing good code. But later on we'll find that we spend as much or more time reading code then we do writing it. Writing clear, easy to understand code is critically important to the concept of clean code because ultimately it makes all that time we spend reading easier and less time consuming.

It should be well formatted. Pick standards and be consistent. Look around at other style guides in the language of your choice. Pick what works best for you or your team, document it and be consistent.

Class names, member names, variable names should be expressive and descriptive of what they're doing. Avoid meaningless names. Naming really is one of the hardest things to get right in programming and often will be specific to the domain that you're working in.

Keep it short. The guy/girl reading your code doesn't want to read a novel. They want to understand how functionality works or how you solved a problem. Make that clear to them. Abstract small pieces of functionality into expressive methods and build a short, descriptive "story" for them on how the bigger piece works.

A lot of things goes into writing clean code. But, in my opinion, making it clear and easy to understand is the single most important thing you can do.

Also read Robert Martin's book.

Title: What exactly makes code "clean"?


问:
The rationale behind Falsy values
I'm wondering what the arguments for/against Falsy values are. On what principles would you decide to add or exclude them from a language? Are there any problems you could see them causing off-hand?

For users of languages that support Falsy values:

Where specifically have you used them to your advantage?

Where have you had unpleasant run-ins with them?

Are there any rules or finer points in your language/project/team about where it's appropriate or inappropriate to use them?

For users of other languages:

Have you ever seen a situation where you've thought "I wish I could use a Falsy value here"?

I'm tagging the question haskell and python because AFAIK those two represent opposite ends of the spectrum (Haskell demanding Bools when you use if, and Python treating None and some "empty" values as Falsy), but feel free to talk about your experience from other languages. Just mention where on the spectrum they stand.

答:
In Python it's more of a something vs nothing concept, and it's incredibly convenient, plus much more readable, to have one's custom classes set to show as nothing (False) if they don't have a meaningful value when used in boolean tests.

Nearly all my own classes support it (lot's of container-type classes).

Title: The rationale behind Falsy values


问:
Is knowing .NET only enough for a successful career in IT industry?

Possible Duplicate:

  Is it better to specialize in a single field I like, or expand into other fields to broaden my horizons?

Recently, I don’t know from where I got a thought in my mind that, “is knowing .NET development environment enough for a successful career in IT industry”. Should I be learning more languages too or will .NET suffice me for next 10-15 years.

By successful career I mean earning decent living and having good growth opportunities.

答:
Technology keeps evolving during the time. Setting the career goals based on only one development environment can be risky. I believe 10 to 15 years is too long time to envisage state of any technology.<br>
We should be open to work on any development environment in our software development career. Of course, we may have our favorites and we may have more expertise over language than other  but knowing other development environment will help.  Let us say, If you become manager of the team which is developing software under different environments, at least you will be in position to guide and understand the internals of the ongoing project. </p>

ContentLicense: CC BY-SA 2.5

Body:
Technology keeps evolving during the time. Setting the career goals based on only one development environment can be risky. I believe 10 to 15 years is too long time to envisage state of any technology.

We should be open to work on any development environment in our software development career. Of course, we may have our favorites and we may have more expertise over language than other  but knowing other development environment will help.  Let us say, If you become manager of the team which is developing software under different environments, at least you will be in position to guide and understand the internals of the ongoing project.


问:
What's the best way to create a static utility class in python? Is using metaclasses code smell?
Ok so I need to create a bunch of utility classes in python. Normally I would just use a simple module for this but I need to be able to inherit in order to share common code between them. The common code needs to reference the state of the module using it so simple imports wouldn't work well. I don't like singletons, and classes that use the classmethod decorator do not have proper support for python properties.

One pattern I see used a lot is creating an internal python class prefixed with an underscore and creating a single instance which is then explicitly imported or set as the  module itself. This is also used by fabric to create a common environment object (fabric.api.env).

I've realized another way to accomplish this would be with metaclasses. For example:

```<code>#util.py
class MetaFooBase(type):
    @property
    def file_path(cls):
        raise NotImplementedError

    def inherited_method(cls):
        print cls.file_path

#foo.py
from util import *
import env

class MetaFoo(MetaFooBase):
    @property
    def file_path(cls):
        return env.base_path + "relative/path"

    def another_class_method(cls):
        pass

class Foo(object): __metaclass__ = MetaFoo

#client.py
from foo import Foo

file_path = Foo.file_path
</code>```

I like this approach better than the first pattern for a few reasons:

First, instantiating Foo would be meaningless as it has no attributes or methods, which insures this class acts like a true single interface utility, unlike the first pattern which relies on the underscore convention to dissuade client code from creating more instances of the internal class.

Second, sub-classing MetaFoo in a different module wouldn't be as awkward because I wouldn't be importing a class with an underscore which is inherently going against its private naming convention.

Third, this seems to be the closest approximation to a static class that exists in python, as all the meta code applies only to the class and not to its instances. This is shown by the common convention of using cls instead of self in the class methods. As well, the base class inherits from type instead of object which would prevent users from trying to use it as a base for other non-static classes. It's implementation as a static class is also apparent when using it by the naming convention Foo, as opposed to foo, which denotes a static class method is being used.

As much as I think this is a good fit, I feel that others might feel its not pythonic because its not a sanctioned use for metaclasses which should be avoided 99% of the time. I also find most python devs tend to shy away from metaclasses which might affect code reuse/maintainability. Is this code considered code smell in the python community? I ask because I'm creating a pypi package, and would like to do everything I can to increase adoption.

答: Metaclasses are a powerful tool.  Most of the time they are not needed, but it looks like you have solid reasons for doing so.  I do not see your use of metaclasses, or lack thereof, affecting your package's adoption on PyPI.</p>


问:
How to convince team members of the existence of a "mandelbug"
We are developing an application; it includes a library developed by another coder, this library communicates with server via multiple network connections, and this involves multiple threads working together. The server side code is quite complicated, and we don't have access to the source code.

Recently I've discovered a mandelbug making application crash sometimes. I could reproduce it once and got a stack trace, so I opened a bug report. The bug itself is easy to fix (uncaught web exception in one of background threads, that makes CLR terminate the program).

The problem is that developer is refusing to fix the bug, because "he is not convinced it exists". Unfortunately for me the boss is siding with him and says this bug cannot be fixed unless I make a "solid test case" to prove existence of the bug, and to make unit test verifying that it's gone. What is basically impossible due to a nature of the bug.

Any advice?

答:
If possible, may be spend some time to check if this defect can be reproduced  by putting some sleep or block  in your application code. But do not spend too much time. As this issue is due to multi-theading (and also as you observed), it's occurrence will be rare.

My advice is not to sweat over this too much. Continue your work. Whenever you come across this crash,  update your bug report  with the stack trace, saying that this is repeat occurrence, and changing the owner to library developer. Let the management/lead decide whether to fix or not depending on it's frequency.

Also try to understand the developer's mentality. You said "uncaught web exception". The developer at this stage may not be entirely sure what will be other effects of catching this. So he/she may be is reluctant to touch the code.


答:
For a bug such as this, automated fuzz testing (also called random testing) might be helpful in trying to reproduce it. This automates the process of finding the bug by randomizing a fixed set of parameters (or inputs) into the thing you're testing. Each test run, parameters are recorded to a log file, including time stamps, etc. so that when the crash occurs you can (theoretically) just replay back the test, using the same parameters, to reproduce it.

Since its automated, the test process can run many tests in a short period of time. Often it can be left to run overnight, and in the morning you can check a log file to see if it reproduced the crash.

Title: How to convince team members of the existence of a "mandelbug"

Body:
We are developing an application; it includes a library developed by another coder, this library communicates with server via multiple network connections, and this involves multiple threads working together. The server side code is quite complicated, and we don't have access to the source code.

Recently I've discovered a mandelbug making application crash sometimes. I could reproduce it once and got a stack trace, so I opened a bug report. The bug itself is easy to fix (uncaught web exception in one of background threads, that makes CLR terminate the program).

The problem is that developer is refusing to fix the bug, because "he is not convinced it exists". Unfortunately for me the boss is siding with him and says this bug cannot be fixed unless I make a "solid test case" to prove existence of the bug, and to make unit test verifying that it's gone. What is basically impossible due to a nature of the bug.

Any advice?


问:
Which benchmarking software would you use to evaluate the performance of your development rig?
I have been tasked with evaluating a new PC for our dev team that is spec'd only slightly better than our current models.

Could anyone recommend appropriate benchmarking software that would be useful to emulate typical development tasks?

答:
Make sure your new boxes come with SSD drive - developers use their hard drives most (compilation, file search, file copy) and it's the slowest part in the computer.

Get a good SSD and you can cut compilation time in half easily.


答:
I'll add a short answer on the importance of clean code, because it was only tangentially evoked in other answers.

"Clean code" is important, because during the total life of the product, or product line, you have maybe spent some weeks to write that module, but it will "live" for years or decades in your code base.

So maybe typically:

Time spent writing code: 10%

Time spent maintaining code: 90%

By writing clean code, you are easing the work of people who are going to have to review and update it in five years. And in some cases, that person will be you!

(I have already found myself wondering "Would wrote that code?" and by checking in the version control system, it was actually me a few years before...)

Title: What exactly makes code "clean"?


答:
So, from your more or less clarifying comments, I got it this way:

You are sure there is only a simple additional exception handling missing, and you know already which code line in the lib is problematic and how the lib could be fixed.

Why then don't you just add the few missing lines of code to the lib by yourself, ask the team kindly to test the lib with that changes? Make sure it is a low-risk change, easy to understand by the dev who is responsible for the lib. The worst thing that could happen is that someone has to revert that change in your VCS if your fix causes some new unexpected behaviour.

Most people are easier to convince when the work is already done. Also, they react better on "here is an improved solution", opposed to "this code is wrong, fix it somehow".

EDIT: when the dev still refuses to add that change, best option is trying to make the problematic code work inside an isolated test harness where you simulate the network error. Working effectively with legacy code describes a lot of techniques on how to tackle such kind of problems. For example, you could create a test version of the library, including only the problematic modules and functions, and create a "mock environment" around it where you can simulate the "network exception" under controlled conditions. That may seem to be too much effort at first glance, but once you have such an environment, you can add a lot of additional tests to it (and I guess that will make sense, since when the author of the lib refuses to add missing exception handling in one place, one should expect more bugs of that kind).


答:
As per me (and for most others) it fully depends on the readability of the code.

If I can read the code and understand it, it is clean or else it is not clean. Good naming and other things are of course important. But then unfortunately readability mainly depends upon a person's technical understanding in data structure or the programming language.

A simple example: Imagine that I wrote a program in C++. I was fascinated by the new features added in the C++11 standard, and I wrote my program using functional programming. So all the loops and iterations over the containers, I replaced by accumulate (reduce, fold), transform (map), any (filter), currying, etc.

Now this program is clean and concise for anyone who knows the concepts and the language features. Unfortunately those who are new or do not even heard about functional programming, are going to struggle. They will say that the code unnecessarily use the confused APIs, and complex to understand. These things can be done using loops, which is more clear and clean. They are still right as where they stand, but the code is actually better. Hence the readability and cleanness depends upon the individual.

Title: What exactly makes code "clean"?


答:
Yes, you can is the short answer.

You need Node.js for the server side. On top of that, you can build whatever you can imagine. That will cover your first 2 questions.

You should check the expressjs framework.

You can find PostgreSQL connectors for node.js such as this one (I haven't tried it). Have in mind that, as Daniel already told you, the latest trend is towards NoSQL solutions so you can find a lot more in that direction (with MongoDB and CouchDB being more famous). You can have a look here.

About the full-text search tools, I've no idea. But since Lucene has SOLR to expose lucene over http, you could make the requests from your server side javascript. This is how they use it with PHP (links: stackoverflow, lucenetutorial).

Finally, have in mind that you can also have native C/C++ node.js modules and code in your projects. That can come handy when you face any node.js limitation.

Title: Is it possible to develop a web application entirely in Javascript today (client and server) including a RESTful API exposing PostgreSQL data?

Body:
Where I work we have over a dozen internal SW systems that we have developed in-house using a variety of technologies, frameworks, and languages. Those include various from Microsoft (ASP.NET Web Forms, WebAPI, WinForms, SharePoint, Office Automation, Win8 Native Apps, SQL Server, SSRS) and others not from Microsoft (plain-old JS/HTML/CSS, PHP, Lithium, PostgreSQL, MySQL). Our SW dev team has grown and shrunk again to where it's just me and one other dev now. I love trying shiny new tech and taking advantage of different tools to get things done, which partly explains the huge span of different technologies we've chosen over the years, but we're suffering from the "jack of all trades, master of none" syndrome.

Now we've been told that the company is expecting significant new growth and that the two of us will need to produce a number of new applications over the next year. I'm ready to consolidate our skill sets and tool sets so that we can master the tools and focus more on the business problems we will face without having the slowdown of context switching between technologies. The two of us have been doing a lot of "plain old" JS/HTML5/CSS3 development recently and I would like to focus on that technology set moving forward.

We will be primarily using PostgreSQL as our data store on the back end (possibly augmenting with some NoSQL for very specific uses, and probably needing to find an advanced full-text search tool to integrate in). Our primary user interfaces will be a combination of traditional web apps and Single Page Apps (50%-50% mix), but there is the hope for native mobile apps down the line. Therefore I would like to expose our business data via a RESTful API so that it's easy to consume by various clients. And the most important factor in all of this is that I want to be able to code exclusively in Javascript from front to back (with the exception of writing SQL as necessary for the DB layer, and HTML5/CSS3 for the presentation).

This leaves me with the following questions:

Is it possible today to code all these layers/components exclusively in Javascript without resorting, for example, to PHP on the server, or C# for the RESTful API (i.e., WebAPI)?

Is node.js required to make this a reality, or can I use a non-node web server and still achieve the "Javascript-only" ideal? (related...would node.js just make more sense in a JS-only paradigm?)

Are there any frameworks for building JS-only RESTful APIs that can talk to PostgreSQL?

Are there any advanced full-text search tools (such as Lucene) that allow you to program against them with a JS-only approach?


问:
Should Cross browser testing be explicitly mentioned in the scope of a project?
I do freelance web development and front end dev is not my strongest point. This question came to me in my recent fixed bid project.

Nowadays we use Jquery and Bootstrap and these take care of lots of cross browser stuff. Still, there are lots of errors in different browsers. It requires testing tools and a whole lot of other things to worry about.

Should it be explicitly mentioned that the resulting site should be tested for cross browser compatibility in a contract? Or

Does it come by default in the scope of the project?

How can we estimate hours spent in cross browser compatibility?

Edit: Some great answers here. But how should a scenario be handled when no browser discussions happened at all at the time of signing contract?

答:
A working approach is to classify the browsers as the BBC did in BBC Browser Support Standards.

I use these classes:

```<code>+ supported (≥5%)
o partially supported (≥2%)
- not supported
● tested by me
</code>```

The customer gets a chart with browsers, versions and marketshare, with each entry marked according to the legend above. I test only with the newest version of each of the three market leading browsers.

Supported browsers are those with a market share of at least 5%. For these, I guarantee functional and visual compliance to the client's specifications. Any deviation is considered to be a bug, I have to fix.

Partially sopported browsers are those with a market share between 2% and 5%. I guarantee only functional compliance. Any functional deviation is a bug, everything else a change request.

Unsupported browsers are what the name says - not supported. Anything the customer wants me to do in this area is a change request, he has to pay for.

Body:
A working approach is to classify the browsers as the BBC did in BBC Browser Support Standards.

I use these classes:

+ supported (≥5%)
o partially supported (≥2%)
- not supported
● tested by me

The customer gets a chart with browsers, versions and marketshare, with each entry marked according to the legend above. I test only with the newest version of each of the three market leading browsers.

Supported browsers are those with a market share of at least 5%. For these, I guarantee functional and visual compliance to the client's specifications. Any deviation is considered to be a bug, I have to fix.

Partially sopported browsers are those with a market share between 2% and 5%. I guarantee only functional compliance. Any functional deviation is a bug, everything else a change request.

Unsupported browsers are what the name says - not supported. Anything the customer wants me to do in this area is a change request, he has to pay for.


问:
What can I use to keep track of the status of 60 programs, some of which are obsolete?
I've taken a software development role in an engineering company(all software developed is for internal use only). The company has about 60 individual programs from past developers.  The problem is that all past developers are gone and no one knows why about half of the software was built, who uses it, or even what some of it does.  We use SVN, but no past developers wrote comments or did any sort of documentation.

Assuming I figure all of this out, is there some program/system/method that could be used to keep track of all this information?  The company is leaning toward Excel, I'm assuming there's something better.  Would it just be better to write up documentation in a Word Doc and commit it to svn so it's right next to the code?

答:
What you are referring to for managing a 'portfolio' of applications is either Project Portfolio Management (PPM) and/or Application Lifecycle Management (ALM). There are numerous tools from low-cost simple management to high-end management.

Do yourself and your organization a favor by NOT trying to put a band-aid on the problem with file based solutions. A few PPM tools I've implemented for clients include:

AtTask - Low tier, SaaS available, straightforward and limited configurability

Planview - High tier, SaaS available, ultimate configurability

Clarity - Mid tier, SaaS unknown, limited configurability


问:
How to create an Intelligent Agent
I am currently doing my Honours in Computer Science and taking Artificial Intelligence as a subject. As part of completing the subject I have to develop my own basic intelligent agent.

I have yet to wrap my head around what I actually have to do for this project. I am not the most technically gifted programmer and I have no idea of what to do or where to start

Could someone please point me in the right direction as to where to start learning how to develop an Intelligent Agent as well as any possible idea's of what to actually do for a project? The requirement for the project are very vague as we were not told how technical or big the project should be. (Hopefully not too big as I have another 8 subjects who require projects as well).

Any VB.net references would be appreciated as well. (I know it's not the best language to develop an IA with, but due to my time constraints this is the programming language I 'feel' most comfortable with).

答:
The other answers have explained the "intelligent" part.

Now, about the agent :

You first need an environment, or world, in which your agent lives. In practice, it's an object or a function looping endlessly. It has two main tasks :

The execution of every agent

Agents have a main function containing all steps needed to take a decision based on informations. That's the actual "intelligent" part. This function needs to run on every world step as long as your agent is active.

Computing perceptions and sending them to the agents

Perceptions are all informations your agent needs to take a decision. For exemple, an intelligence trying to do facial recognition might get a portion of pixels to analyze, and return its guess ("looks like Bruce !").

The environment will then display all data from all agents, which would be your result.

Title: How to create an Intelligent Agent


答:
Therefore I would like to expose our business data via a RESTful API
  so that it's easy to consume by...

..hackers, TFTFY. :)

I would really not try to make the DB 'easily consumable' by directly giving access to its tables. I would however, secure the DB with stored procedures that are the only interface to the DB (which is sort-of the same principle you're advocating only the API is a sproc one rather than a REST one) and then I would provide a set of services to provide an intermediary layer between the clients and the DB. These services can provide a REST API.

Not only do you improve security (if the clients don't have access to the DB, they can't abuse it) but you can provide a more logical set of APIs to clients without them having to know what the DB contains.

As for javascript everywhere, Node.JS is the thing you want. To get a beautiful tutorial, see the Node Beginner Book. Then grab a js library to make working with the system easier like express or restify.


答:
If you are wondering what all these means practically, well for a change from academic programming, you would need to have meaningful variables and function names firstly.

Secondly, your codes needs to be organised such that it is easy to follow. That is you need to understand code separation (understand why people likes MVCs), you need to put functional things in models and in view have only things which will be used for the frontend and Controller to plug them all in. So that if a person comes to read your code these separation will actually help them focus on the bit they want for quick update etc.

Thirdly, you also need to be organised at modular level, you shouldn't have functions for example ticketing algorithm in some other module like payroll or accounts etc. You should also design modules in a way that if you can easily remove the module and the system should still work without its functionalities (also that means you can easily plug in modules as well).

Finally, also a good practise I think to keep helper functions separate from all modules so that they can be called from anywhere.

I should also have a look at different design patterns and learn how to use them as they do help your codes to be more organised and manageable.

Title: What exactly makes code "clean"?


答:
Redmine.

Create a project for each of your projects, hook each one up to the SVN section that contains the code and go from there. Each project will gain a bugtracker and a wiki and a way to track changes and information about each project as you determine what that info is. Additionally, you can see the code that comprises the projects and tie it to bugs or documents.

The 2nd bonus is you get a very good project management tool for free.

Title: What can I use to keep track of the status of 60 programs, some of which are obsolete?

Body:
I've taken a software development role in an engineering company(all software developed is for internal use only). The company has about 60 individual programs from past developers.  The problem is that all past developers are gone and no one knows why about half of the software was built, who uses it, or even what some of it does.  We use SVN, but no past developers wrote comments or did any sort of documentation.

Assuming I figure all of this out, is there some program/system/method that could be used to keep track of all this information?  The company is leaning toward Excel, I'm assuming there's something better.  Would it just be better to write up documentation in a Word Doc and commit it to svn so it's right next to the code?


答:
The Devil's Advocate suggests another path.

The other developer has stated, flatly, that there is no bug there.

Can you come up with a way to stress the hell out of his allegedly-nonexistent bug, and cause it to crash a lot more frequently?


答:
Additionally to other answers, there can be actual ways to feel about code. By feel, I mean instinctively interact with code.

First, the formatting of the code itself can be easier for people to read and understand using some basic principles that help us read the code. Gestalt Principles can help anything be more quickly and easily understood by humans (applied heavily in data visualization). Using these principles for simple things like aligning comments, placing spaces and blank lines in the right place all help people read code more easily at an instinctive level.

A lot of my coding conventions and formatting is based on making it easier to read first at a subconscious level.

Which feels more readable?

```<code>int x; //This is an x
string foo; //Foo here
MyObject baz; //Instance of MyObject

int x;        //This is an x
string foo;   //Foo here
MyObject baz; //Instance of MyObject
</code>```

EDIT

To Michael's comment about having a long declaration. Our minds are forgiving, so the laws don't have to be followed exactly.

```<code>int x;        //This is an x
string foo;   //Foo here
MyObject baz; //Instance of MyObject
MyTypeWithSomeAwfullyLongName bar;
long UUID;    //The Law can be broken and still help
</code>```

The Law of Proximity should mean most people like the second version better. It's the same reason we have columns and tables to organize data.

Another example, based on the Law of Symmetry

```<code>function fooBarLongMethodName() {
    return null;
}

function fooBarLongMethodName()
{
    return null;
}
</code>```

The law of symmetry states that the mind perceives objects as being
  symmetrical and forming around a center point. It is perceptually
  pleasing to divide objects into an even number of symmetrical parts.

So it is more pleasing for the mind to see the symmetry in the second example, being able to see both the open and close braces in line.

These examples should instinctively make reading code easier. But there are also learned patterns that it takes time for you to take advantage of, these are based on the Law of Past Experience.

So secondly, understanding the intent of certain code, and knowing when it's being used incorrectly (especially without having to investigate or know much about previous code). This article talks about naming variables so that you can see from the names when they're are being used incorrectly.  Once this pattern of naming and use have become habitual, it's possible to recognize an issue with the code by site and without having to investigate much of the other code.

Finally, these lead into a larger idea of Code Smells. The idea that certain patterns that emerge in code can commonly signal an issue somewhere in the code. This sometimes shows up as a sentiment "This unit testing code is ugly, why is it even necessary?" and the answer to that question is maybe "Oh, you're using Singletons for everything.".  This is the hardest to teach or learn and probably only comes with experience.

So I hope this helps expand on the other answers as to why or how people can consider code 'beautiful', 'good', or 'ugly'

Title: What exactly makes code "clean"?

Body:
Additionally to other answers, there can be actual ways to feel about code. By feel, I mean instinctively interact with code.

First, the formatting of the code itself can be easier for people to read and understand using some basic principles that help us read the code. Gestalt Principles can help anything be more quickly and easily understood by humans (applied heavily in data visualization). Using these principles for simple things like aligning comments, placing spaces and blank lines in the right place all help people read code more easily at an instinctive level.

A lot of my coding conventions and formatting is based on making it easier to read first at a subconscious level.

Which feels more readable?

int x; //This is an x
string foo; //Foo here
MyObject baz; //Instance of MyObject

int x;        //This is an x
string foo;   //Foo here
MyObject baz; //Instance of MyObject

EDIT

To Michael's comment about having a long declaration. Our minds are forgiving, so the laws don't have to be followed exactly.

int x;        //This is an x
string foo;   //Foo here
MyObject baz; //Instance of MyObject
MyTypeWithSomeAwfullyLongName bar;
long UUID;    //The Law can be broken and still help

The Law of Proximity should mean most people like the second version better. It's the same reason we have columns and tables to organize data.

Another example, based on the Law of Symmetry

function fooBarLongMethodName() {
    return null;
}

function fooBarLongMethodName()
{
    return null;
}

The law of symmetry states that the mind perceives objects as being
  symmetrical and forming around a center point. It is perceptually
  pleasing to divide objects into an even number of symmetrical parts.

So it is more pleasing for the mind to see the symmetry in the second example, being able to see both the open and close braces in line.

These examples should instinctively make reading code easier. But there are also learned patterns that it takes time for you to take advantage of, these are based on the Law of Past Experience.

So secondly, understanding the intent of certain code, and knowing when it's being used incorrectly (especially without having to investigate or know much about previous code). This article talks about naming variables so that you can see from the names when they're are being used incorrectly.  Once this pattern of naming and use have become habitual, it's possible to recognize an issue with the code by site and without having to investigate much of the other code.

Finally, these lead into a larger idea of Code Smells. The idea that certain patterns that emerge in code can commonly signal an issue somewhere in the code. This sometimes shows up as a sentiment "This unit testing code is ugly, why is it even necessary?" and the answer to that question is maybe "Oh, you're using Singletons for everything.".  This is the hardest to teach or learn and probably only comes with experience.

So I hope this helps expand on the other answers as to why or how people can consider code 'beautiful', 'good', or 'ugly'


问:
Programming with voice recogition software
I used Dragon Naturally Speaking very briefly a few years ago and was thinking if it would be a viable solution for programming?

I was thinking more so if you break your arm or something that would be a major hinderance to programming.

This same question on SO but was never answered.

答:
Here's a link to a video from a Python Convention where Tavis Rudd explains how he customized Dragon Naturally Speaking using their Python plugin structure to create a vocabulary suited towards programming and editing in Emacs, vim and the terminal. An inspiring glimpse at the possibilities of voice recognition in the domain of programming and development.

Using Python to Code by Voice

Two years ago I developed a case of Emacs Pinkie (RSI) so severe my hands went numb and I could no longer type or work. Desperate, I tried voice recognition. At first programming with it was painfully slow but, as I couldn't type, I persevered. After several months of vocab tweaking and duct-tape coding in Python and Emacs Lisp, I had a system that enabled me to code faster and more efficiently by voice than I ever had by hand.

In a fast-paced live demo, I will create a small system using Python, plus a few other languages for good measure, and deploy it without touching the keyboard. The demo gods will make a scheduled appearance. I hope to convince you that voice recognition is no longer a crutch for the disabled or limited to plain prose. It's now a highly effective tool that could benefit all programmers...


答:
Based on Joe's answer where the Problem is that you can not go back and forth:

You can use eye tracking additionally to solve this issue.

Programming languages can be readable. Smalltalk is quite readable.

```<code>10 timesRepeat: [
    Transcript show:'hello'.
    Transcript cr.
].
</code>```

Imagine a programming language that is optimized for speaking. It can be done.

If I had asked my customers what they wanted they would have said a
  faster horse. - Henry Ford

In these terms: A spoken text input may not be it. But a speech controlled environment with programmable traits would be a step further.

Title: Programming with voice recogition software

Body:
I used Dragon Naturally Speaking very briefly a few years ago and was thinking if it would be a viable solution for programming?

I was thinking more so if you break your arm or something that would be a major hinderance to programming.

This same question on SO but was never answered.

Body:
Based on Joe's answer where the Problem is that you can not go back and forth:

You can use eye tracking additionally to solve this issue.

Programming languages can be readable. Smalltalk is quite readable.

10 timesRepeat: [
    Transcript show:'hello'.
    Transcript cr.
].

Imagine a programming language that is optimized for speaking. It can be done.

If I had asked my customers what they wanted they would have said a
  faster horse. - Henry Ford

In these terms: A spoken text input may not be it. But a speech controlled environment with programmable traits would be a step further.


答:
If you want to be stuck in the same place forever, then know .NET and forget everything else.

Because technology moves, as do development environments and languages, the developers need to move as well.

Example (though I am a bit of an oddball), in 25 years I've actively used APL, BASIC (more varieties than I can remember), Fortran (several variants), C, C++, Pascal, Delphi, Ada, and a bunch more I can't even remember.

These have all been for large and complex projects. Then some of these were on operating systems (Windows, unix[es], linux, other strange proprietary OS's, IBM MVS/TSO, etc). And some have been on the bare-metal hardware (lots of embedded stuff), some had RTOS environment, some didn't.

The point I'm making here is - if you learn new things and move in new directions as the needs arise you will be more knowledgeable and more employable.

The danger of learning one thing only is that obsolescence creeps up on you. There are not so many jobs these days for Fortran programmers - or buggy-whip makers :)

Title: Is knowing .NET only enough for a successful career in IT industry?

Body:
Possible Duplicate:

  Is it better to specialize in a single field I like, or expand into other fields to broaden my horizons?

Recently, I don’t know from where I got a thought in my mind that, “is knowing .NET development environment enough for a successful career in IT industry”. Should I be learning more languages too or will .NET suffice me for next 10-15 years.

By successful career I mean earning decent living and having good growth opportunities.


答:
Redmine allows you to configure a hierarchy of projects, and each project has its own separate wiki. The wiki formatting is very simple, so you don't have to go crazy on it. Most wikis we create are just a single page, with links to outside references, a few paragraphs whining about poor code, and then some notes on important @todos.

It also supports source code integration, and there is syntax for linking directly to the code from the wiki, provided by a plugin.


答: You may already read (or not) about S.O.L.I.D. patterns. But I expect such question requires more specific answer. Please take a look at Doom 3 Source code review. Even you are not familiar with the game development you still can understand the code. In my opinion, it is an example of the Clean code.</p>

Title: What exactly makes code "clean"?


问:
Phonetic programming language?
Many of us coders, programmers and developers struggle with repetitive stress injuries, carpal tunnel, etc.

I've been curious about introducing voice control into my workflow in order to save myself some stress.

This has led me to my current question: Would it be possible or practical to implement a programming language (or superset of an existing language) which was primarily phonetic, and hence well suited to programming by voice?

答:
A phonetic programming language is certainly possible, SKI combinators give you a Turing complete language, and I don't think there can be any doubt that 'S', 'K' and 'I' are phonetic. With a restricted language like this there is even room to replace open and close brackets with something phonetic, maybe 'C' and 'D'. Of course actually using Turing tar pit languages is not something most people want to do.

The more interesting point is, is it practical to develop this way, with a 'real' phonetic language, as far as I know this is somewhat unknown.

Title: Phonetic programming language?


答:
I noticed several answers here touch on style/layout, i.e. cosmetics of code. I think that there is a distinction to be drawn between code that is clean and code that is tidy. Ideally you have both, but the first is more important.

As an analogy I might decide to tidy up my kitchen (stack the dishes away, rearrange, sort jars in the cupboards, etc.). The same with code - you can align the text, format, whitespace, naming conventions, breakdown into smaller files, etc.

None of that will mean your code will be clean - and when I cook later/compile my code I might still get a bug (stomach bug/segmentation fault, my analogy is holding well...)

You can kill bugs of course (boiling water, soap/a patch, a hack), but it is much better to avoid them entirely - that is to have clean code. So you design your kitchen to your needs, plenty of space, clear worktops/have a separate meat vs. vegetable chopping board, etc./nicely factored design, single responsibility principle, KISS, YAGNI, etc.
The analogy breaks down, because I need my kitchen to be tidy before I can cook. Whereas you don't need tidy code to have it compile and work, as long as the design is clean.

It just means it takes a little longer for the average developer to navigate your kitchen/code and work out where everything is, but at least that is possible, but it is not possible for them to see a swathe of salmonella and E-coli on a kitchen surface. They can only trust that there isn't because you've got several obvious bottles of antibacterial spray in the cupboard under the sink where they would normally expect to find it/you designed your code in the canonical way for the problem it solves.

Now (an unadulterated opinion): inexperienced developers (it doesn't matter what their seniority is) get distracted by tidiness when they should be more concerned about dirt.

Title: What exactly makes code "clean"?


问:
What is the best/most standard way to measure server load?
I'm a bit green to web applications although I am in the final phases of developing one for a client. I'm using Django with Gunicorn/Nginx on an AWS m1.medium. The database (MongoDB) is on a separate instance. The client is paranoid about scaling and so I threw together a crude monitoring server which has the ability to spin up new AWS instances, install the app code and load balance (I know, I know, I could have used ELB. I said I was green, and it was fun writing it anyway).

The question is, I don't really know what metrics I should be aware of. How will I know when my app server is under 'high load'? CPU? RAM? Request latency? All of the above?

Any guidance in this area would be appreciated.

答:
High load is too high when either software is unstable, or users start to notice latencies, whichever comes first. You should know your usage pattern, and build load tests based on it.
Pick the bottleneck factor (cpu, ram, io) and fire up instances at 80% of the peak value, to handle spikes. Also you start/shutdown them before busiest/most idle times of the day.


答:
A simple solution to solve puntuation and complex structure issues would be to phonetize a stack-based language such as Postscript.

The vocal editor could implement multiple modes, like vi: insert mode for saying the program and command mode for navigating and functions such as copy-paste, text search...

Title: Phonetic programming language?

Body:
Many of us coders, programmers and developers struggle with repetitive stress injuries, carpal tunnel, etc.

I've been curious about introducing voice control into my workflow in order to save myself some stress.

This has led me to my current question: Would it be possible or practical to implement a programming language (or superset of an existing language) which was primarily phonetic, and hence well suited to programming by voice?


问:
IDE Generated Code
Many IDEs have the ability to spit out automatically written pieces of code. For example, it might generate a getter/setter pair for you. I wonder whether it isn't an attempt to work around some flaws in the language. If your IDE can figure out what the code should be without your help, why can't the compiler?

Are there cases where this is a really good idea? What kind of code generation does your IDE provide? Would the same thing be better provided as a feature of the language?

答:
When I code in Ruby, I use vim, and I feel good. I mean, I don't want or need any kind of autocompletion / code generation.

On the other side, when, I code in Java, I use Eclipse (or Netbeans) and I could not work without it. I need to easily generate the getters/setters, the big try/catch block, I'm happy if the IDE can help me with the for each loop.

I wonder whether it isn't an attempt to work around some flaws in the language

Ruby getter + setter + variable for my_var:

```<code>attr_accessor :my_var
</code>```

Java getter + setter + variable for myVar:

```<code>private String myVar;
public String getMyVar() {
  return myVar;
}
public void setMyVar(String value) {
  myVar = value;
}
</code>```

Yes, in Java, I need to generate that code...

So... Is it an attempt to work around some flaws in the language ? I'm tempted to answer YES, but I might be too much biased...

Title: IDE Generated Code

Body:
When I code in Ruby, I use vim, and I feel good. I mean, I don't want or need any kind of autocompletion / code generation.

On the other side, when, I code in Java, I use Eclipse (or Netbeans) and I could not work without it. I need to easily generate the getters/setters, the big try/catch block, I'm happy if the IDE can help me with the for each loop.

I wonder whether it isn't an attempt to work around some flaws in the language

Ruby getter + setter + variable for my_var:

attr_accessor :my_var

Java getter + setter + variable for myVar:

private String myVar;
public String getMyVar() {
  return myVar;
}
public void setMyVar(String value) {
  myVar = value;
}

Yes, in Java, I need to generate that code...

So... Is it an attempt to work around some flaws in the language ? I'm tempted to answer YES, but I might be too much biased...


答:
I don't think there is a strong need for a programming language specialized for this.

However there is a need for alternative input methods for current programming languages.

Here's a presentation by Tavis Rudd about writing code using voice recognition.
http://www.youtube.com/watch?v=8SkdfdXWYaI

He wrote python which might be easier to write this way than c for instance, so your mileage may vary depending on your preferred programming language.

Title: Phonetic programming language?


答:
Would it be possible or practical to implement a programming language (..) which was primarily phonetic

Possible: probably.

Practical: probably not, your vocal chords would suffer even faster under the stress then you would get carpal tunnel.

Title: Phonetic programming language?


问:
Proper Price Markup Formula
Ok, so this is not the most advanced programming question - and it kind of borders on e-commerce, but it has specifically come up twice in my career - which is only 10 years old, so I figured I would ask it.

Question: I want to markup a price 10% from its original cost for a website, which is the proper way to do it:

NP = (P * 1.1)

or

NP = (P / 90) * 100

Where P is the original Price and NP is the New Price?

Background:
I am a web developer. I have worked on several e-commerce sites in my time. A few years back, I was building a freelance site for a tool shop. The guy had been in business for years and was moving into online sales. I wrote a script that took his core inventory list, cycled through it and automatically marked up the price 10% before inserting into the Database. I used formula #1. When he reviewed it he said the price was too low and to use formula #2.

Using formula #1, a 15 dollar product is now equal to 16.5, using two it is $16.66.

His logic was that 15 is 90% of $16.66 and thus 16.66 a 10% markup, by which 16.5 is only about a 9% markup.

Flash forward a  few years to today and and I hit the same problem. My company has a massive list of inventory that gets marked up and down in a number of ways. Our old DBA was marking up the price for distributors 10%. He was using formula 1. Our new DBA rewrote a stored procedure and started using formula two.

A few people flipped out and started saying that the distributor prices were way too high and that the old formula was correct. We sell large quantities of relatively low-cost items, the fear is that our distributors would balk at the cost.

Logically it seemed that formula #1 was the proper way to markup, but the experienced business owner told me the other way was. Now I am hearing people say the opposite.

EDIT: My Using the original 15 example. It has always seemed  to me that 15 is actually a 10% markdown of 16.66 where as 16.5 is the proper 10% markup of 15.

答:
The proper way to increase something by 10% is to multiply by 1.1.  Formula 2 is based of the misguided assumption that a 10% increase followed by a 10% decrease should yield the original number.  That's not how it works.  You would need to multiply by the inverse fraction.

```<code>Ex: Given NP = 1.1 * P
Applying a 10% discount gives .9 * NP => .9 * 1.1 * P = .99 * P
</code>```

To make it easier to see, use 50% instead of 10%.  If I have a $10 product and I increase the price by 50% its new price becomes $15.  If I then apply a 50% discount the price becomes $7.50.

To get back to the original price I need to apply a 33% discount.

```<code>NP = 1.5 * P
Apply 33% discount => NP * (1/1.5) => NP * .67 => 1.5 * P * .67 => P
</code>```

Title: Proper Price Markup Formula

Body:
The proper way to increase something by 10% is to multiply by 1.1.  Formula 2 is based of the misguided assumption that a 10% increase followed by a 10% decrease should yield the original number.  That's not how it works.  You would need to multiply by the inverse fraction.

Ex: Given NP = 1.1 * P
Applying a 10% discount gives .9 * NP => .9 * 1.1 * P = .99 * P

To make it easier to see, use 50% instead of 10%.  If I have a $10 product and I increase the price by 50% its new price becomes $15.  If I then apply a 50% discount the price becomes $7.50.

To get back to the original price I need to apply a 33% discount.

NP = 1.5 * P
Apply 33% discount => NP * (1/1.5) => NP * .67 => 1.5 * P * .67 => P


答:
Formula one adds a percentage of the cost price.

Formula two says that the cost price should be a percentage of the sales price.

The idea between them is totally different. It's not about the calculation but how you work with pricing. So there is no wrong or right. It is just different.

The new DBA did it wrong because he changed the business rules without commitment as it seems. That's the only error.

Title: Proper Price Markup Formula

Body:
Ok, so this is not the most advanced programming question - and it kind of borders on e-commerce, but it has specifically come up twice in my career - which is only 10 years old, so I figured I would ask it.

Question: I want to markup a price 10% from its original cost for a website, which is the proper way to do it:

NP = (P * 1.1)

or

NP = (P / 90) * 100

Where P is the original Price and NP is the New Price?

Background:
I am a web developer. I have worked on several e-commerce sites in my time. A few years back, I was building a freelance site for a tool shop. The guy had been in business for years and was moving into online sales. I wrote a script that took his core inventory list, cycled through it and automatically marked up the price 10% before inserting into the Database. I used formula #1. When he reviewed it he said the price was too low and to use formula #2.

Using formula #1, a 15 dollar product is now equal to 16.5, using two it is $16.66.

His logic was that 15 is 90% of $16.66 and thus 16.66 a 10% markup, by which 16.5 is only about a 9% markup.

Flash forward a  few years to today and and I hit the same problem. My company has a massive list of inventory that gets marked up and down in a number of ways. Our old DBA was marking up the price for distributors 10%. He was using formula 1. Our new DBA rewrote a stored procedure and started using formula two.

A few people flipped out and started saying that the distributor prices were way too high and that the old formula was correct. We sell large quantities of relatively low-cost items, the fear is that our distributors would balk at the cost.

Logically it seemed that formula #1 was the proper way to markup, but the experienced business owner told me the other way was. Now I am hearing people say the opposite.

EDIT: My Using the original 15 example. It has always seemed  to me that 15 is actually a 10% markdown of 16.66 where as 16.5 is the proper 10% markup of 15.


答:
My math background tells me formula #1
My background dealing with business guys: whatever your boss or the sales person can get away with and still keep customers happy. Which could be #2 but anything really.

And it's also about how you word the requirements:
For instance: 10% of the price, is our markup. Then it's a clear #2.

Title: Proper Price Markup Formula


问:
How do I collect a list of rss feeds?
I am developing a rss reader where users search and follow blogs. But, how will I collect and store the feeds of thousands of blogs?

Manual process of adding individual feeds is painful. Is there an easier way to add or import site feeds?

答:
Blekko has an API that provides the RSS link and other relevant details for any site.

Example : http://blekko.com/ws/cnn+/json

Change cnn to any other topic or site name.

Title: How do I collect a list of rss feeds?


问:
Making Simple IF Statements Shorter
If we assume we have this little snippet of code:

```<code>string str = "checked";
bool test1;

if (str == "checked")
{
    test1 = true;
}
else
{
    test1 = false;
}
</code>```

Is it bad practice to change a simple statement like this to the following?:

```<code>bool test2 = (str == "checked");
</code>```

Because they work exactly the same, and work as required, so I can't imagine how it would be. However, as a young, inexperienced programmer I am not aware of whether such a thing is frowned upon or not. Can anyone tell me, if this is NOT ok, why not?

The following test program:

```<code>using System;

public class Test
{

    public static void Main()
    {
        string str = "checked";

        bool test1;

        if (str == "checked")
        {
            test1 = true;
        }
        else
        {
            test1 = false;
        }

        bool test2 = (str == "checked");

        bool test3 = (str != "checked");

        Console.WriteLine(test1.ToString());
        Console.WriteLine(test2.ToString());
        Console.WriteLine(test3.ToString());
    }
}
</code>```

Outputs:

```<code>True
True
False
</code>```

Any insight etc is appreciated.

答:
I would be very annoyed at someone who used the long form when the statement is that simple.

It hints that the one who wrote it either doesn't understand boolean data types, or doesn't realize == is independent of if.

Title: Making Simple IF Statements Shorter


答:
Is it bad practice to change a simple statement like this to the following?:

```<code>bool test2 = (str == "checked");
</code>```

No, it's good practice. To me, the longer code:

```<code>if (str == "checked")
{
    test1 = true;
}
else
{
    test1 = false;
}
</code>```

indicates that the programmer doesn't understand Boolean expressions.  The shorter form is much clearer.  Similarly, don't write:

```<code>if (boolean-expression) {
    return true;
} else {
    return false;
}
</code>```

Just write return boolean-expression;

Title: Making Simple IF Statements Shorter

Body:
If we assume we have this little snippet of code:

```<code>string str = "checked";
bool test1;

if (str == "checked")
{
    test1 = true;
}
else
{
    test1 = false;
}
</code>```

Is it bad practice to change a simple statement like this to the following?:

```<code>bool test2 = (str == "checked");
</code>```

Because they work exactly the same, and work as required, so I can't imagine how it would be. However, as a young, inexperienced programmer I am not aware of whether such a thing is frowned upon or not. Can anyone tell me, if this is NOT ok, why not?

The following test program:

```<code>using System;

public class Test
{

    public static void Main()
    {
        string str = "checked";

        bool test1;

        if (str == "checked")
        {
            test1 = true;
        }
        else
        {
            test1 = false;
        }

        bool test2 = (str == "checked");

        bool test3 = (str != "checked");

        Console.WriteLine(test1.ToString());
        Console.WriteLine(test2.ToString());
        Console.WriteLine(test3.ToString());
    }
}
</code>```

Outputs:

```<code>True
True
False
</code>```

Any insight etc is appreciated.

Body:
Is it bad practice to change a simple statement like this to the following?:

bool test2 = (str == "checked");

No, it's good practice. To me, the longer code:

if (str == "checked")
{
    test1 = true;
}
else
{
    test1 = false;
}

indicates that the programmer doesn't understand Boolean expressions.  The shorter form is much clearer.  Similarly, don't write:

if (boolean-expression) {
    return true;
} else {
    return false;
}

Just write return boolean-expression;


问:
How do people develop emulators?
I hope this is right area on Stack Exchange to ask this question.  People out there have built emulators for every game console but I don't understand how they do it. I consider myself (and have the professional title of) a senior level developer in several languages including Javascript but I don't have the faintest idea about how to begin writing an emulator in Javascript. How do they figure out how to read the ROMs and emulate the game?</p>

答:
I guess you've never had the pleasure of a college course where you had to self-assemble and disassemble your own code, or design a CPU.  It's tedious, but actually not that difficult.

Take the Microchip PIC instruction set as an example, which I chose because it is very simple, only 35 instructions.  If you look at the "14-bit instruction word" column in the table on page 3, those are the bits that actually get written to flash, what is mostly used today instead of ROM.  Each instruction has a unique fixed prefix.  ADDWF has a prefix of 00 0111, for example.

An emulator just has to check the value from the ROM against all the instruction prefixes until it finds a match, then parse the rest of the instruction.  For ADDWF, the d bit becomes the d argument, and the f bits become the f argument.  Then you just use those arguments to do an add in Javascript, something like:

```<code>addwf = function(f, d) {
  if (d == 0)
     w = w + registers[f]
  else
     registers[f] = w + registers[f]
}
</code>```

Of course, there are also carry bits and such to set, but that's the basic idea to emulating a CPU.  For a game console, you also have to emulate the IO, but there are technical specification documents around the internet to help you know how to do that.  For example, writing an 0x0000ff to a certain memory location might turn a specific pixel blue.  Your emulator then just has to detect writes to that emulated memory location from your emulated CPU and translate it into whatever Javascript commands turn a pixel blue.

That's a gross oversimplification.  It takes a considerable amount of optimization work to make an emulation fast enough to handle the desired frame rate of a game, but those are the basic principles.

Title: How do people develop emulators?

Body:
I guess you've never had the pleasure of a college course where you had to self-assemble and disassemble your own code, or design a CPU.  It's tedious, but actually not that difficult.

Take the Microchip PIC instruction set as an example, which I chose because it is very simple, only 35 instructions.  If you look at the "14-bit instruction word" column in the table on page 3, those are the bits that actually get written to flash, what is mostly used today instead of ROM.  Each instruction has a unique fixed prefix.  ADDWF has a prefix of 00 0111, for example.

An emulator just has to check the value from the ROM against all the instruction prefixes until it finds a match, then parse the rest of the instruction.  For ADDWF, the d bit becomes the d argument, and the f bits become the f argument.  Then you just use those arguments to do an add in Javascript, something like:

addwf = function(f, d) {
  if (d == 0)
     w = w + registers[f]
  else
     registers[f] = w + registers[f]
}

Of course, there are also carry bits and such to set, but that's the basic idea to emulating a CPU.  For a game console, you also have to emulate the IO, but there are technical specification documents around the internet to help you know how to do that.  For example, writing an 0x0000ff to a certain memory location might turn a specific pixel blue.  Your emulator then just has to detect writes to that emulated memory location from your emulated CPU and translate it into whatever Javascript commands turn a pixel blue.

That's a gross oversimplification.  It takes a considerable amount of optimization work to make an emulation fast enough to handle the desired frame rate of a game, but those are the basic principles.


问:
In API design, when to use/avoid ad hoc polymorphism?
Sue is designing a JavaScript library, Magician.js. Its linchpin is a function which pulls a Rabbit out of the argument passed.

She knows its users may want to pull a rabbit out of a String, a Number, a Function, perhaps even a HTMLElement. With that in mind, she could design her API like so:

The strict interface

```<code>Magician.pullRabbitOutOfString = function(str) //...
Magician.pullRabbitOutOfHTMLElement = function(htmlEl) //...
</code>```

Each function in the above example would know how to handle the argument of the type specified in the function name/parameter name.

Or, she could design it like so:

The "ad hoc" interface

```<code>Magician.pullRabbit = function(anything) //...
</code>```

pullRabbit would have to account for the variety of different expected types that the anything argument could be, as well as (of course) an unexpected type:

```<code>Magician.pullRabbit = function(anything) {
  if (anything === undefined) {
    return new Rabbit(); // out of thin air
  } else if (isString(anything)) {
    // more
  } else if (isNumber(anything)) {
    // more
  }
  // etc.
};
</code>```

The former (strict) seems more explicit, perhaps safer, and perhaps more performant -- as there are little or no overheads for type checking or type conversion. But the latter (ad hoc) feels simpler looking at it from the outside, in that it "just works" with whatever argument the API consumer finds convenient to pass to it.

For the answer to this question, I'd like to see specific pros and cons to either approach (or to a different approach altogether, if neither is ideal), that Sue should know which approach to take when designing her library's API.

答:
This (to me) is an interesting and complicated question to answer.  I actually like this question so I will do my best to answer.  If you do any research at all into standards for javascript programming, you will find as many "right" ways of doing it as there are people touting the "right" way of doing it.

But since you're looking for an opinion as to which way is better.  Here goes nothing.

I personally would prefer the "adhoc" design approach.  Coming from an c++/C# background, this is more my style of development.  You can create the one pullRabbit request and have that one request type check the argument passed in and do something.  This means you dont have to worry about what type of argument is being passed in at any one time.  If you use the strict approach, you would still need to check which type the variable is but instead you would do that before you make the method call.  So in the end the question is, do you want to check the type before you make the call or after.

I hope this helps, please feel free to ask more questions in relation to this answer, I will do my best to clarify my position.


答:
Some pros and cons

Pros for polymorphic:

A smaller polymorphic interface is easier to read. I only have to remember one method.

It goes with the way the language is meant to be used - Duck typing.

If it's clear which objects I want to pull a rabbit out of, there shouldn't be ambiguity anyway.

Doing a lot of type checking is considered bad even in static languages like Java, where having plenty of type checks for the type of the object makes ugly code, should the magician really need to differentiate between the type of objects he's pulling a rabbit out of?

Pros for ad-hoc:

It's less explicit, can I pull a string out of a Cat instance? Would that just work? if not, what is the behavior? If I don't limit the type here, I have to do so in the documentation, or in the tests which might make a worse contract.

You have all the handling of pulling a rabbit in one place, the Magician (some might consider this a con)

Modern JS optimizers differenciate between monomorphic (works on only one type) and polymorphic functions. They know how to optimize the monomorphic ones much better so the pullRabbitOutOfString version is likely to be much faster in engines like V8. See this video for more information. Edit: I wrote a perf myself, it turns out that in practice, this is not always the case.

Some alternative solutions:

In my opinion, this sort of design isn't very 'Java-Scripty' to begin with. JavaScript is a different language with different idioms from languages like C#, Java or Python. These idioms originate in years of developers trying to understand the language's weak and strong parts, what I'd do is try to stick with these idioms.

There are two nice solutions I can think of:

Elevating objects, making objects "pullable", making them conform to an interface on run-time, then having the Magician work on pullable objects.

Using the strategy pattern, teaching the Magician dynamically how to handle different type of objects.

Solution 1: Elevating Objects

One common solution to this problem, is to 'elevate' objects with the ability to have rabbits pulled out of them.

That is, have a function that takes some type of object, and adds pulling out of a hat for it. Something like:

```<code>function makePullable(obj){
   obj.pullOfHat = function(){
       return new Rabbit(obj.toString());
   }
}
</code>```

I can make such makePullable functions for other objects, I could create a makePullableString, etc. I'm defining the conversion on each type. However, after I elevated my objects, I have no type to use them in a generic way. An interface in JavaScript is determined by a duck typing, if it has a pullOfHat method I can pull it with the Magician's method.

Then Magician could do:

```<code>Magician.pullRabbit = function(pullable) {
    var rabbit = obj.pullOfHat();
    return {rabbit:rabbit,text:"Tada, I pulled a rabbit out of "+pullable};
}
</code>```

Elevating objects, using some sort of mixin pattern seems like the more JS thing to do.
(Note this is problematic with value types in the language which are string, number, null, undefined and boolean, but they're all box-able)

Here is an example of what such code might look like

Solution 2: Strategy Pattern

When discussing this question in the JS chat room in StackOverflow my friend phenomnomnominal suggested the use of the Strategy pattern.

This would allow you to add the abilities to pull rabbits out of various objects at run time, and would create very JavaScript'y code. A  magician can learn how to pull objects of different types out of hats, and it pulls them based on that knowledge.

Here is how this might look in CoffeeScript:

```<code>class Magician
  constructor: ()-> # A new Magician can't pull anything
     @pullFunctions = {}

  pullRabbit: (obj) -> # Pull a rabbit, handler based on type
    func = pullFunctions[obj.constructor.name]
    if func? then func(obj) else "Don't know how to pull that out of my hat!"

  learnToPull: (obj, handler) -> # Learns to pull a rabbit out of a type
    pullFunctions[obj.constructor.name] = handler
</code>```

You can see the equivalent JS code here.

This way, you benefit from both worlds, the action of how to pull isn't tightly coupled to either the objects, or the Magician and I think this makes for a very nice solution.

Usage would be something like:

```<code>var m = new Magician();//create a new Magician
//Teach the Magician
m.learnToPull("",function(){
   return "Pulled a rabbit out of a string";
});
m.learnToPull({},function(){
   return "Pulled a rabbit out of a Object";
});

m.pullRabbit(" Str");
</code>```

Title: In API design, when to use/avoid ad hoc polymorphism?

Body:
Sue is designing a JavaScript library, Magician.js. Its linchpin is a function which pulls a Rabbit out of the argument passed.

She knows its users may want to pull a rabbit out of a String, a Number, a Function, perhaps even a HTMLElement. With that in mind, she could design her API like so:

The strict interface

```<code>Magician.pullRabbitOutOfString = function(str) //...
Magician.pullRabbitOutOfHTMLElement = function(htmlEl) //...
</code>```

Each function in the above example would know how to handle the argument of the type specified in the function name/parameter name.

Or, she could design it like so:

The "ad hoc" interface

```<code>Magician.pullRabbit = function(anything) //...
</code>```

pullRabbit would have to account for the variety of different expected types that the anything argument could be, as well as (of course) an unexpected type:

```<code>Magician.pullRabbit = function(anything) {
  if (anything === undefined) {
    return new Rabbit(); // out of thin air
  } else if (isString(anything)) {
    // more
  } else if (isNumber(anything)) {
    // more
  }
  // etc.
};
</code>```

The former (strict) seems more explicit, perhaps safer, and perhaps more performant -- as there are little or no overheads for type checking or type conversion. But the latter (ad hoc) feels simpler looking at it from the outside, in that it "just works" with whatever argument the API consumer finds convenient to pass to it.

For the answer to this question, I'd like to see specific pros and cons to either approach (or to a different approach altogether, if neither is ideal), that Sue should know which approach to take when designing her library's API.

Body:
Some pros and cons

Pros for polymorphic:

A smaller polymorphic interface is easier to read. I only have to remember one method.

It goes with the way the language is meant to be used - Duck typing.

If it's clear which objects I want to pull a rabbit out of, there shouldn't be ambiguity anyway.

Doing a lot of type checking is considered bad even in static languages like Java, where having plenty of type checks for the type of the object makes ugly code, should the magician really need to differentiate between the type of objects he's pulling a rabbit out of?

Pros for ad-hoc:

It's less explicit, can I pull a string out of a Cat instance? Would that just work? if not, what is the behavior? If I don't limit the type here, I have to do so in the documentation, or in the tests which might make a worse contract.

You have all the handling of pulling a rabbit in one place, the Magician (some might consider this a con)

Modern JS optimizers differenciate between monomorphic (works on only one type) and polymorphic functions. They know how to optimize the monomorphic ones much better so the pullRabbitOutOfString version is likely to be much faster in engines like V8. See this video for more information. Edit: I wrote a perf myself, it turns out that in practice, this is not always the case.

Some alternative solutions:

In my opinion, this sort of design isn't very 'Java-Scripty' to begin with. JavaScript is a different language with different idioms from languages like C#, Java or Python. These idioms originate in years of developers trying to understand the language's weak and strong parts, what I'd do is try to stick with these idioms.

There are two nice solutions I can think of:

Elevating objects, making objects "pullable", making them conform to an interface on run-time, then having the Magician work on pullable objects.

Using the strategy pattern, teaching the Magician dynamically how to handle different type of objects.

Solution 1: Elevating Objects

One common solution to this problem, is to 'elevate' objects with the ability to have rabbits pulled out of them.

That is, have a function that takes some type of object, and adds pulling out of a hat for it. Something like:

function makePullable(obj){
   obj.pullOfHat = function(){
       return new Rabbit(obj.toString());
   }
}

I can make such makePullable functions for other objects, I could create a makePullableString, etc. I'm defining the conversion on each type. However, after I elevated my objects, I have no type to use them in a generic way. An interface in JavaScript is determined by a duck typing, if it has a pullOfHat method I can pull it with the Magician's method.

Then Magician could do:

Magician.pullRabbit = function(pullable) {
    var rabbit = obj.pullOfHat();
    return {rabbit:rabbit,text:"Tada, I pulled a rabbit out of "+pullable};
}

Elevating objects, using some sort of mixin pattern seems like the more JS thing to do.
(Note this is problematic with value types in the language which are string, number, null, undefined and boolean, but they're all box-able)

Here is an example of what such code might look like

Solution 2: Strategy Pattern

When discussing this question in the JS chat room in StackOverflow my friend phenomnomnominal suggested the use of the Strategy pattern.

This would allow you to add the abilities to pull rabbits out of various objects at run time, and would create very JavaScript'y code. A  magician can learn how to pull objects of different types out of hats, and it pulls them based on that knowledge.

Here is how this might look in CoffeeScript:

class Magician
  constructor: ()-> # A new Magician can't pull anything
     @pullFunctions = {}

  pullRabbit: (obj) -> # Pull a rabbit, handler based on type
    func = pullFunctions[obj.constructor.name]
    if func? then func(obj) else "Don't know how to pull that out of my hat!"

  learnToPull: (obj, handler) -> # Learns to pull a rabbit out of a type
    pullFunctions[obj.constructor.name] = handler

You can see the equivalent JS code here.

This way, you benefit from both worlds, the action of how to pull isn't tightly coupled to either the objects, or the Magician and I think this makes for a very nice solution.

Usage would be something like:

var m = new Magician();//create a new Magician
//Teach the Magician
m.learnToPull("",function(){
   return "Pulled a rabbit out of a string";
});
m.learnToPull({},function(){
   return "Pulled a rabbit out of a Object";
});

m.pullRabbit(" Str");


答:
The problem is that you're trying to implement a type of polymorphism that doesn't exist in JavaScript - JavaScript is almost universally best treated as a duck-typed language, even though it does support some type faculties.

To create the best API, the answer is that you should implement both. It's a bit more typing, but will save a lot of work in the long run for users of your API.

pullRabbit should just be an arbiter method that checks types and calls the proper function associated with that object type (e.g. pullRabbitOutOfHtmlElement).

That way, while prototyping users can use pullRabbit, but if they notice a slowdown they can implement the type checking on their end (in likely a faster way) and just call pullRabbitOutOfHtmlElement directly.