问:
TDD and test automation in applications heavily dependent on databases and user input
Recently I have been reading online about eXtreme programming and agile practices. I wish to adapt them. However most of my code is all in PHP which is the normal CRUD type web applications. Moreover I user web framework like CodeIgniter, which also abstracts a lot of the core features.

To sum up, how can I implement the test driven development into applications which are heavily dependent on databases and user input, particularly in the test automation part?

I would now ask this question targeting my current project

I am working on an college forum web application. It has the basic social network features and also includes XMPP server on its stack. The following components constitute my application stack:

Apache web server  with mod_php enabled.

PHP as a back-end language.(CodeIgniter framework)

MySql database.

Openfire server for XMPP.

HTML, CSS, jQuery and Strophe(for XMPP) on front end, and

A Python middleware for XMPP.

Currently I am working without any testing or build cycle. I use SVN as the version control system. And I wish to include TDD and CI into the development process. I already have some code in the project. What strategies and best practices should I adopt for implementing TDD and CI in this kind of project?

PS: We are a team of three people working on a self project as such we dont have any other person who influences the design(apart from the end users).

This is what I did to start implementing

I refactored the login function which was taking the username and password passed from the front end and then applies sanity checks, checks for valid username, then for valid password, If yes it sets the session cookie and redirects the user to a page based on his role.

I broke the above function into three one to take username and password and check if they are correct, another to set the cookies and the last one that takes the values from front end and applies sanity checks, calls the other two functions and then redirects.

I could write test for only the first function. Is that enough?

答:
PHPUnit will help with testing your application.

Usually, people write unit tests to test the singularity of their business rules, the actual methods that have business logic. That would be the unitary part of your tests.

You can mock the database, or write functional or integration tests to test the features on a more wider space.

PHPUnit helps you with that as well.


问:
How much help should I give during technical interviews?
I'm asked to perform or sit in during many technical interviews. We ask logic questions and simple programming problems that the interviewee is expected to be able to solve on paper. (I would rather they have access to a keyboard, but that is a problem for another time.) Sometimes I sense that people do know how to approach a problem, but they are hung up by nervousness or some second-guessing of the question (they aren't intended to be trick questions).

I've never heard my boss give any help or hints. He just thanks the interviewee for the response (no matter how good or bad it is) and moves on to the next question or problem. But I know something about the rabbit hole that defeat and nerves can lead you down, and how it disables your mind, and I can't help wondering if providing a little help now and then would ultimately help us end up with more capable programmers instead of more failed interviews.

Should I provide hints and assistance for befuddled interviewees (and if so, how far should I go while still being fair to the more prepared candidates)?

答:
For "senior people", I offer short, open ended questions and pay more attention to the questions they ask than the answer. I find senior people who listen, communicate, use active listening, clarify, then provide solutions are the type I like.

For "line engineers", I have used the technique for programming tests where you give an applicant a computer and a problem and a few hours, then you come back. In that situation, we asked the applicant in advance what OS and tools they preferred (also an interesting part of a programmer's expertise). When they were finished, as a group we asked them to present the solution and why it was better than other solutions - a code review. All skills I expect from an experienced engineer on day 1.

Importantly, the entire interviewing team had taken an afternoon to do the same test, so we knew the test was fair. We spent an hour examining each persons' approach like we would with an interviewee, which gave us a sense of different approaches.

This second technique found us some of the best "unsung" programmers (lousy resume, lousy interview skills) I've ever found.

ContentLicense: CC BY-SA 3.0


问:
JIT compiler for C, C++, and the likes
Is there any just-in-time compiler out there for compiled languages, such as C and C++? (The first names that come to mind are Clang and LLVM! But I don't think they currently support it.)

Explanation:

I think the software could benefit from runtime profiling feedback and aggressively optimized recompilation of hotspots at runtime, even for compiled-to-machine languages like C and C++.

Profile-guided optimization does a similar job, but with the difference a JIT would be more flexible in different environments. In PGO you run your binary prior to releasing it. After you released it, it would use no environment/input feedbacks collected at runtime. So if the input pattern is changed, it is probe to performance penalty. But JIT works well even in that conditions.

However I think it is controversial wether the JIT compiling performance benefit outweights its own overhead.

答:
Yes, there are JIT compilers for C++. From a pure performance perspective, I think Profile Guided Optimization (PGO) is still superior.

However, that does not mean that JIT compilation is not yet used in practice. For example, Apple uses LLVM as a JIT for their OpenGL pipeline. That is a domain where you have significantly more information at runtime, which can be used to remove a lot of dead code.

Another interesting application of JIT is Cling, an interactive C++ interpreter based on LLVM and Clang:
https://root.cern.ch/cling

Here is a sample session:

```<code>[cling]$ #include <iostream>
[cling]$ std::cout << "Hallo, world!" << std::endl;
Hallo, world!
[cling]$ 3 + 5
(int const) 8
[cling]$ int x = 3; x++
(int) 3
(int const) 3
[cling]$ x
(int) 4
</code>```

It is no toy project but it is actually used in CERN, for example, to develop the code for the Large Hadron Collider.

Title: JIT compiler for C, C++, and the likes

Body:
Yes, there are JIT compilers for C++. From a pure performance perspective, I think Profile Guided Optimization (PGO) is still superior.

However, that does not mean that JIT compilation is not yet used in practice. For example, Apple uses LLVM as a JIT for their OpenGL pipeline. That is a domain where you have significantly more information at runtime, which can be used to remove a lot of dead code.

Another interesting application of JIT is Cling, an interactive C++ interpreter based on LLVM and Clang:
https://root.cern.ch/cling

Here is a sample session:

[cling]$ #include <iostream>
[cling]$ std::cout << "Hallo, world!" << std::endl;
Hallo, world!
[cling]$ 3 + 5
(int const) 8
[cling]$ int x = 3; x++
(int) 3
(int const) 3
[cling]$ x
(int) 4

It is no toy project but it is actually used in CERN, for example, to develop the code for the Large Hadron Collider.


问:
Algorithm to find if a set can be recreated
I'm finding it hard to solve the problem and was hoping that someone could help me with the solution or at least give me a search term to use for problems like this one.

The generalized problem: I have a set of numbers (e.g. [1,2,3]) and a an array of sets (e.g. [1,4,5],[4,2,3],[6,7,8],[2],[1,3]). What I need to do is to find if I can create the first set from the others by taking 1 or 0 elements from them (e.g. taking 1 from the first, 2 from the second and 3 from the last). Order of the elements doesn't matter in any of the sets.

答:
Here's an approach that should be "ok" time complexity wise (but maybe still not optimal). The idea is to first build an index of values in the array of sets, then go through the set of numbers to see if they can be found in the index.

Definitions

Using the problem's description,

let S be the set you are looking to rebuild

let X be the array of sets, where X[i] is the i'th set in X

let v=X[i,j] be the j'th value in set X[i]

To solve the problem efficiently,

let H be a map with entries h(v,XI), where v is a value in X, and XI is a list of indexes i into X where this value was found.

let R be the map of values corresponding to S, with entries r(i,v) where v is the value in set X[i], and i is the set where this value was taken from to rebuild S

Algorithm

Build the map H by reading through all sets in X. For each new value v=X[i,j], insert a corresponding entry h(v,XI) into H to remember in which set (the i'th set in X) this value was found. For values already in H, add i into the corresponding entries' XI.

Iterate over all values in S. For each value, look it up in H. If one is not found, abort since S cannot be rebuilt.

For each value in S, if the value exists in H, iterate over XI of the corresponding entry h(v,XI) to retrieve the indices i.

For each i in XI, try to add in R a new entry r(i,v), if and only if R does not contain another entry for the same i. If an entry for i exists already, it means that another value has already been read from the corresponding set in X, and another set i must be considered.

Repeat step 4 until a new entry could be added to R, or until there are no more i left. In the latter case abort as the set S cannot be rebuilt. *)

The values v in the entries of R should now correspond to S.

*) actually, before aborting in step 5, there could be some permutation of sets in X that would still work. For this to work, the algorithm would have to restart step 4 by trying another combination of sets in X.

Disclaimer: I did not implement the algorithm or test it.


问:
DB schema for packaging products/services together under a single price/offer
I’m trying to “conceive” the business logic of this website that has many activities, that the users can build their “combo” and get discounts depending on their choices and how long they are willing to pay for their plan (1, 3, 6 and 12 month plans).

I’m having a hard time trying to come up with a solution, while keeping the database normalized and with proper relations, without having to resort to JSON-encoded data in the database fields. The system must stay generic enough to fit many businesses types that relies on plans/activities. I need to know how to structure my tables.

Scenario: For example, in case of a gym, will have bodybuilding, yoga, boxing, body pump. If the person choose bodybuilding and boxing, they will have a discount. If they add yoga, boxing and bodybuilding will keep the discount but will add the yoga without any discount to the price. If the person decides to pay 12 months upfront, they will get a bigger discount.

Bodybuilding + Body Pump

Bodybuilding..$70 | 28% discount
Body Pump.....$70 |
Total........$100

1 month  - $100 / month
3 months - $ 91 / month
6 months - $ 75 / month
```

<p>Bodybuilding + Body Pump + Yoga</p>

<pre class="lang-none prettyprint-override"><code>Bodybuilding..$70 | 28% discount
Body pump.....$70 |
Yoga..........$90 | No discount
Total........$190

1 month  - $190 / month
3 months - $171 / month
6 months - $158 / month
</code>```

I’ll be using PHP and MYSQL but that doesn’t matter much, only the RDBMS part.

Edit for clarification: What I really looking for is a database schema for packaging products (or in this case services) together under a single price/offer. Each product must also exist in the system as a standalone product.

I still need the ability to report on sales (and profit) by product even if that product was sold as part of a package.

I would need the ability to report on package performance.

答:
At a Minimum You need:

A Promo Header Table - Holds exactly what you get with the
Promotion (Free item, free shipping, $$ off)

A Promo-Requirements Tables (I to meany to Promo's, Hold all the
requirement if the promo) Each record is one Requirement,
Requirements can be "must be and item of Brand X" or must be SKU
1234, or order total must be >50$ (When i did this is had a row type
flag that told me what kid if Requirement it was.)

A module that is good a checking if an order meets a promotion's
Requirements.

Unfortunately, I can't give you an exact ERD, because the promo conditions vary so much from business to business, so it's up to you make it as complex or simple as you need.
For example, do you need Promos by SKU?, By Category, by subcategory?, by brand?, do you need to exclude certain SKUs?, brands? Category's? shipping locations?

Lastly make sure you make this thing easy to maintain and adjust, because just when you think you covered all your bases the business team will come up with some new crazier promo the no customer on earth will understand how to use.

EDIT:
*Now that I better understand your question here what you need:*

Package Header Table and a Line Items Table, The Package Name and Description is stored on the header, The Lines hold the Items (including the Item prices when sold as part of that package).

You need a way to adding a Package to order. When that is done add then each item in the package as a regular line item but have a extra fields to specifies that the item is part of a Package and the PackageID.

It is then up to you to decide how you want to code the order Print out, Either just print a package total, so the customer doesn't know the line item prices, or print it normally but add with the package description.


答:
This can be solved by computing a matching from elements in your base set, to the other sets. This is essentially checking for Hall's condition.

That is, build a bipartite graph G=(A,B,E), with A being the base set, and B being the other sets. There is an edge from x in A to some y in B if x is in y. Now compute a maximum matching (there are several algorithms for this) and you're good to go. If no matching exists, then you cannot recreate the set.

Title: Algorithm to find if a set can be recreated

Body:
I'm finding it hard to solve the problem and was hoping that someone could help me with the solution or at least give me a search term to use for problems like this one.

The generalized problem: I have a set of numbers (e.g. [1,2,3]) and a an array of sets (e.g. [1,4,5],[4,2,3],[6,7,8],[2],[1,3]). What I need to do is to find if I can create the first set from the others by taking 1 or 0 elements from them (e.g. taking 1 from the first, 2 from the second and 3 from the last). Order of the elements doesn't matter in any of the sets.


问:
Memory management for fast message passing between threads in C++
Suppose there are two threads, which communicate by asynchronously sending data messages to each other. Each thread has some kind of message queue.

My question is very low level: What can be expected to be the most efficient way to manage the memory? I can think of several solutions:

Sender creates the object via new. Receiver calls delete.

Memory pooling (to transfer the memory back to the sender)

Garbage collection (e.g., Boehm GC)

(if the objects are small enough) copy by value to avoid heap allocation completely

1) is the most obvious solution, so I'll use it for a prototype. Chances are that it is already good enough. But independent of my specific problem, I wonder which technique is most promising if you are optimizing for performance.

I would expect pooling to be theoretically the best, especially because you can use extra knowledge about the flow of information between the threads. However, I fear that it is also the most difficult to get right. Lots of tuning... :-(

Garbage collection should be quite easy to add afterwards (after solution 1), and I would expect it to perform very well. So, I guess that it is the most practical solution if 1) turns out to be too inefficient.

If the objects are small and simple, copy by value might be the fastest. However, I fear that it forces unnecessary limitations on the implementation of the supported messages, so I want to avoid it.

答:
It is going to depend on how you implement the queues.

If you go with an array (round robin style) you need to set an upper bound on size for solution 4. If you go with a linked queue, you need allocated objects.

Then, resource pooling can be done easily when you just replace the new and delete with AllocMessage<T> and freeMessage<T>. My suggestion would be to limit the amount of potential sizes T can have and round up when allocating concrete messages.

Straight up garbage collection can work but that might cause long pauses when it needs to collect a large part, and will (I think) perform a bit worse than new/delete.


问:
Alternate string formatting options in C++?
I'm looking at optimizing some string formatting code that's hit a lot in our code. We had been using ostringstream, and I converted the code to use sprintf (actually Microsoft's more secure sprintf_s). I've traded type safety for run-time performance. But I've debugged enough sprintf related weird crashes to know that sprintf has its own serious flaws that the compile time checking of ostringstream catch. But ostringstream is more than an order-of-magnitude slower then sprintf by my measure, and that's not tolerable in this code. I'm also not thrilled with the readability of C++ stream string formatting, but this may be entirely subjective.

So unfortunately when formatting strings in C++ I've got several "standard" options that are suboptimal:

sprintf -- fast, but not type safe. Can have insidious bugs when the wrong format string is not used.

ostringstream -- slow, but type safe. IMO Ugly, too verbose, and difficult to read.

boost::format -- a little more readable then ostringstream IMO, but in my performance benchmarks appears to be even slower then ostringstream, so this is out.

To summarize, I'm not really satisfied with the "standard" options. I'd like something that takes both performance and type safety seriously. What other string formatting options are out there for C++?

答:
I recommend this formatting library which I wrote recently. Here is an incomplete list of its features:

Format string syntax similar to the one used by str.format in Python.

Type safety and support for user-defined types.

High speed: performance of the current implementation is close to that of glibc's (s)printf and better than performance of IOStreams. See Speed tests.

It's a new library, but it already supports almost all of the formatting options of printf (with different syntax), in addition to that it supports positional arguments, center alignment, custom fill character and user-defined types.

Update: now it also provides a safe printf implementation


问:
How did Python become popular as a scripting language?
I looked at it in my field of work, which is film and pretty much every software we use comes with python as a scripting language: http://en.wikipedia.org/wiki/List_of_Python_software That made me assume it's the most popular.

How did Python become popular as a scripting language? Especially as an embedded language into standalone applications.

What's the reason for this? There are others like Lua, Ruby, etc. but yet it looks like Python came on top.

If it's because of a particular thing or just a matter of getting out there at the right time?

答:
In most cases, behind a successful language is a powerful sponsor.  AT&T gave us C and C++, Microsoft created the .NET family, Java came from Sun, and even though they didn't invent it, Apple is almost completely responsible for the recent popularity of Objective-C.  (Though that's a borderline case, since pretty much nobody outside the OSX/iOS ecosystem is using Objective-C for anything.)

Python is the same way.  It was around for a long time, but it was a fairly obscure language until it found institutional favor at Google.  They decided they liked it so much that they ended up hiring Guido Van Rossum! And now Python's a really big language.


问:
Designing entities to be self-manageable
Although this is a gamedev project, the question is about general OOP practices, so I believe it goes here. Here's the problem:
(note: I will call any equivalent of real-world physical objects "entities" from now on; e.g. a rock in the game is an entity)

A specific class:

```<code>class Character
{
public/private CharacterInventory Inventory;
public/private CharacterStats Stats;
public/private CharacterEquipment Equipment;
}
</code>```

Inventory functionality is self-contained in the CharacterInventory class. Same goes for stats. My aim is to make each character in my game a self-manageable entity. What do I mean by this? To put it plainly, I want to design the base Character class so that in the end I get an object that reacts in its entirety even when the smallest change occurs, in any of its components. To make things clearer, here's an example: when an item that changes the strength of the character gets equipped, the CharacterEquipment component of Character gets updated. At the same time, the Character will call the Stats object to change the strength attribute.

I've thought about doing this using events. Character subscribes to Equipment's OnEquip event, and in its handler, tells the Stats component do do its job. I believe this is an elegant enough solution; my issue however lies somewhere else.

I've got two ways in which I can update the character's inventory. First, by making the inventory (and any other component) private and providing a public method inside of Character, that does the work of calling the appropriate update method in the inventory.
Like so:

```<code>Character chara = new Character();
chara.AddItemToInventory(SomeItem);
</code>```

The 2nd way is by making the components public and accessing them like:

```<code>Character chara = new Character();
chara.Inventory.AddItem(SomeItem);
</code>```

To me, both ways seem roughly equivalent in terms of readability. But the 2nd way seems like it's breaking the whole "self-manageable" idea. Basically, I'm invading the "private" space of the character. By going with the 2nd way, I can hook to the inventory events from some other place, but then again, this breaks the main idea even further.
However, going the 1st way, I get the impression of writing duplicated code; even though it's not! I think the impression is given to me by the fact that Character.AddItemToInventory(...) and CharacterInventory.AddItem(...) share enough naming similarities to suggest duplicated code.

To be sincere, I'd go the first way, even though it seems to me like an extra layer of code. Then again, to make the character a self-manageable object, an extra layer of security is essential.
But I'd like to hear from people more experienced than me. Are there any advantages to the 2nd way? Any severe disadvantages? I just can't get over the impression that I'm writing extra, unnecessary code.

答:
There is no problem making 2nd option "self-contained" too. Simply include callback/event in CharacterInventory that gets called/raised when item is added and subscribe to it within a character class. This way, you get same behavior as 1st option, you dont need to re-implement the public interface AND you keep the implementation details hidden.

I don't see how it breaks the idea of "self-contained". Especially if you use callback methods, instead of events. I think this might be better option.


问:
How can I hide confidential data in my open source project?
I have an open source project that uploads files to DropBox among several file hosts. Right now I am screen scraping for DropBox. To use their API, I have to hardcode a SECRET KEY provided by them to me for OAuth authentication. But I'm afraid that the key won't be secret if it is visible plainly for anyone to see.

It is 'possible' for someone malicious to use my key to upload a virus to a user's account (who already allowed access to my app) that will spread to their pc (if they had desktop sync enabled) and to others' pc (if they had shared folders) and so on. :O

I found this unanswered question that has the same problem as mine.

But I would like to know generally how one would hide confidential data in an open source project.

I have one idea.

Have a placeholder in the source code like "<SECRET KEY HERE>" and fill it only when building binary for release? (yuck!)

Any decent idea?

答:
The easiest way is to simply not publish confidential data. Some options:

Use a placeholder like in the question.

Use a header file especially for the key, don't commit it to source control, and only privately distribute it to trusted parties.

I've used the second option for open source development because it means you don't have to worry about filling in the details just before build, or having one change to remember not to commit.


答:
The basic idea is that you do NOT check-in confidential values in the code or in the compiled binary. Especially if the project is open source you really shouldn't. There are several configuration strategies you can take in order to do so:

Placeholders in code (hardcoded values)

Placeholders in code - as was suggested - which is most sane and easiest to do in dynamic programming languages as the code is easy to change (without needing to compile). I've seen a lot of open source projects do this such as MediaWiki with it's LocalSettings.php.

The downside with this strategy is that the key is hardcoded. So if the program is distributed as a binary then having the key hard-coded does not make it particularly maintainable.

Configuration Text Files

You can also do this by implementing configuration text files, i.e. the program/application searches for a configuration file and reads values from it. You can check-in a sample configuration with placeholders but have the actual configuration local in your machine.

In your case you can create a key.conf text file with the actual key, let the program use that file and let it be ignored by version control. You can, for being helpful, check in a key.conf.example text file with a bogus key and check that-in. Make sure your program/application makes an helpful error message
for the user to add the actual key in the correct file.

Some programming languages have APIs that provide this automatically for you, such as:

Java's Properties API, Preferences API, Apache Commons Configuration API

C#/VB.NET apps does this with App.Config files accessible through the ConfigurationManager .NET API

NodeJS apps have a convention of package.json or putting configuration values in json-files, and with the file modules API the files are easy to parse and use as they're basically JavaScript object literals.

If your application is a database app, then consider putting the key or other configuration variables in the database. It is the same as the configuration text file above but you put all configuration variables such as the key in a database table instead.

Through preferences view or a Back Office app

If the program is a window or a web application with views then you can also let the application create the configuration file, through a preferences view of sorts. That way you don't need to check in an example config file as suggested above.

MediaWiki solved this similarly by auto-generating the LocalSettings.php file in an initial installation process.

Admittedly this is not an option for programs that solely run as background processes, services or daemons. However that's why you create seperate GUI projects for these to create a point-of-entry for administration and preferences settings, in web apps usually called a Back Office application.

Title: How can I hide confidential data in my open source project?

Body:
I have an open source project that uploads files to DropBox among several file hosts. Right now I am screen scraping for DropBox. To use their API, I have to hardcode a SECRET KEY provided by them to me for OAuth authentication. But I'm afraid that the key won't be secret if it is visible plainly for anyone to see.

It is 'possible' for someone malicious to use my key to upload a virus to a user's account (who already allowed access to my app) that will spread to their pc (if they had desktop sync enabled) and to others' pc (if they had shared folders) and so on. :O

I found this unanswered question that has the same problem as mine.

But I would like to know generally how one would hide confidential data in an open source project.

I have one idea.

Have a placeholder in the source code like "<SECRET KEY HERE>" and fill it only when building binary for release? (yuck!)

Any decent idea?


问:
Is the 80 character limit still relevant in times of widescreen monitors?
on a widescreen monitor one can easily see more than 80 characters at a time, without scrollbars. even linus torvalds sees the 80 character limit as outdated.

so, is the 80 character limit still relevant in times of widescreen monitors?

答:
Yes, there are reasons to limit code line length:

Although our screens have gotten wide, sometimes you need to print out your code. If only for this reason.

Diff-viewers often display lines with a vertical split - this becomes harder if the lines are as long as a wide screen would allow.

Having said that, 80 is a bit too little. But, still, some limitation is probably a good idea as a design principle.

I would say that extra long lines shouldn't be disallowed, because occasionally they are necessary. But if most functions are only viewable on a 30" screen then the code has some issues.

ContentLicense: CC BY-SA 2.5


问:
Performance: recursion vs. iteration in Javascript
I have read recently some articles (e.g. http://dailyjs.com/2012/09/14/functional-programming/) about the functional aspects of Javascript and the relationship between Scheme and Javascript (the latter was influenced by the first, which is a functional language, while the O-O aspects are inherited from Self which is a prototyping-based language).

However my question is more specific: I was wondering if there are metrics about the performance of recursion vs. iteration in Javascript.

I know that in some languages (where by design iteration performs better) the difference is minimal because the interpreter / compiler converts recursion into iteration, however I guess that probably this is not the case of Javascript since it is, at least partially, a functional language.

答:
As per request by the OP I'll chip in (without making a fool of myself, hopefully :P)

I think we're all agreed that recursion is just a more elegant way of coding. If done well it can make for more maintainable code, which is IMHO just as important (if not more) that shaving off 0.0001ms.

As far as the argument that JS does not perform Tail-call optimization is concerned: that's not entirely true anymore, using ECMA5's strict mode enables TCO. It was something I wasn't too happy about a while back, but at least I now know why arguments.callee throws errors in strict mode. I know the link above links to a bug report, but the bug is set to WONTFIX. Besides, standard TCO is coming: ECMA6 (December 2013).

Instinctively, and sticking to the functional nature of JS, I'd say that recursion is the more efficient coding style 99.99% of the time. However, Florian Margaine has a point when he says that the bottleneck is likely to be found elsewhere. If you're manipulating the DOM, you're probably best focussing on writing your code as maintainable as possible. The DOM API is what it is: slow.

I think it's nigh on impossible to offer a definitive answer as to which is the faster option. Lately, a lot of jspref's I've seen show that Chrome's V8 engine is ridiculously fast at some tasks, which run 4x slower on FF's SpiderMonkey and vice versa. Modern JS engines have all sorts of tricks up their sleeves to optimize your code. I'm no expert, but I do feel that V8, for example, is highly optimized for closures (and recursion), whereas MS's JScript engine is not. SpiderMonkey often performs better when the DOM is involved...

In short: I'd say which technique will be more performant is, as always in JS, nigh on impossible to predict.


问:
Having error codes option in C++ library for performance
I have written an open source and cross-platform C++ File Library which have exception and error codes. Exceptions can be disabled when the program is running. In that case, the user have to check the error codes. Of course, when exception throwing is enabled, error code won't be returned because exception is thrown before the called function returns.

Currently, exceptions still could be thrown when disabled (bug). I'll fix that soon. Someone comment to me that it is considered bad design to have both exception and error codes. I agree with him and I am about to remove the error codes and have library throw custom derived exceptions with more error information.

But I hesitate. I like to have this hybrid approach for performance reasons. This is what I am thinking of doing: keeping exception throwing and error codes but exception throwing is disabled through macro at compile time instead of runtime.

If user define the following in a common config file

```<code>#define ELMAX_EXCEPTION 1
</code>```

The follow code

```<code>int Write(std::wstring str) ELMAX_THROW_OR_NOT;
</code>```

would expand to either of the 2.

```<code>// under C++11 compiler
int Write(std::wstring str) noexcept;

// under C++98 compiler
int Write(std::wstring str) throw();
</code>```

If ELMAX_EXCEPTION is not defined or is zero, the macro would expand to nothing.

```<code>int Write(std::wstring) ;
</code>```

The reason I want to do this, is for library user who wants the performance gain of not having the compiler generating the stack unwinding code (for exception) and compiler can better optimize such functions. My C++ file library is using C file API and the only thing which could throw exception is new keyword, which I intend to add nothrow. The UTF-8 code can also throw exceptions (need to be changed too)

```<code>char *parr = new (nothrow) char[num];

if(parr==NULL)
    // handle it either through error code or throw exception (if enabled)
</code>```

Please kindly advise if I should have a pure exception approach or a hybrid approach (as mentioned), for my library errors?

答:
If you have good use cases for both, consider splitting your library into two or three classes:

The core, which contains the code that does the work and is able to return enough information on failure to produce an error code or an exception.

A wrapper class that calls the core's methods and throws exceptions on failure.  The trade-off here is that exceptions thrown won't show exactly where in the core class a failure occurred.  This may not be an issue depending on the complexity of the core's methods.

A wrapper class that calls the core's methods and returns error codes on failure.  If appropriate, the core class could be used directly, eliminating the need to have a non-throwing wrapper.

Whatever you do, don't change the library's behavior using the preprocessor.  Doing so will change the method prototypes:

```<code>class Foo {
  #ifdef NO_EXCEPTIONS
    StatusType bar() { ... }
  #else
    void bar() { ... }
  #endif
};
</code>```

The first time a class expecting the exception-throwing behavior #includes another's header that has the NO_EXCEPTIONS macro set, you'll have uncompilable code because there will be code present that expects Foo to be prototyped two different ways.

Body:
If you have good use cases for both, consider splitting your library into two or three classes:

The core, which contains the code that does the work and is able to return enough information on failure to produce an error code or an exception.

A wrapper class that calls the core's methods and throws exceptions on failure.  The trade-off here is that exceptions thrown won't show exactly where in the core class a failure occurred.  This may not be an issue depending on the complexity of the core's methods.

A wrapper class that calls the core's methods and returns error codes on failure.  If appropriate, the core class could be used directly, eliminating the need to have a non-throwing wrapper.

Whatever you do, don't change the library's behavior using the preprocessor.  Doing so will change the method prototypes:

class Foo {
  #ifdef NO_EXCEPTIONS
    StatusType bar() { ... }
  #else
    void bar() { ... }
  #endif
};

The first time a class expecting the exception-throwing behavior #includes another's header that has the NO_EXCEPTIONS macro set, you'll have uncompilable code because there will be code present that expects Foo to be prototyped two different ways.


答:
The choice between exceptions and error codes should not be a global one, but rather based on how exceptional the error condition is with a normal usage of the library.

Error codes should be used for situations that are erroneous but that can easily occur with a normal usage of the library. For example, failure to open a file or failure to read an integer at the current position.

Exceptions should be used to report serious problems that should not occur with normal usage of the library and that the immediate caller is unlikely to be able to recover from. Examples of these are memory exhaustion or hard errors reported by the underlying filesystem (e.g. disk full).

And for I/O libraries, you can also consider using a delayed error reporting mechanism. Instead of having each function return an error code (which has to be checked by the caller), the error code is stored internally. Subsequent calls do nothing if they determine an earlier call resulted in an error and the user of the library has to check (at a convenient point) if an error has occurred in the preceding set of calls. This is the default mode of operation for the standard C++ I/O streams.

Title: Having error codes option in C++ library for performance

Body:
I have written an open source and cross-platform C++ File Library which have exception and error codes. Exceptions can be disabled when the program is running. In that case, the user have to check the error codes. Of course, when exception throwing is enabled, error code won't be returned because exception is thrown before the called function returns.

Currently, exceptions still could be thrown when disabled (bug). I'll fix that soon. Someone comment to me that it is considered bad design to have both exception and error codes. I agree with him and I am about to remove the error codes and have library throw custom derived exceptions with more error information.

But I hesitate. I like to have this hybrid approach for performance reasons. This is what I am thinking of doing: keeping exception throwing and error codes but exception throwing is disabled through macro at compile time instead of runtime.

If user define the following in a common config file

```<code>#define ELMAX_EXCEPTION 1
</code>```

The follow code

```<code>int Write(std::wstring str) ELMAX_THROW_OR_NOT;
</code>```

would expand to either of the 2.

```<code>// under C++11 compiler
int Write(std::wstring str) noexcept;

// under C++98 compiler
int Write(std::wstring str) throw();
</code>```

If ELMAX_EXCEPTION is not defined or is zero, the macro would expand to nothing.

```<code>int Write(std::wstring) ;
</code>```

The reason I want to do this, is for library user who wants the performance gain of not having the compiler generating the stack unwinding code (for exception) and compiler can better optimize such functions. My C++ file library is using C file API and the only thing which could throw exception is new keyword, which I intend to add nothrow. The UTF-8 code can also throw exceptions (need to be changed too)

```<code>char *parr = new (nothrow) char[num];

if(parr==NULL)
    // handle it either through error code or throw exception (if enabled)
</code>```

Please kindly advise if I should have a pure exception approach or a hybrid approach (as mentioned), for my library errors?


答:
Its up to you, but error codes are easier to document and handle within a library like this.
Exceptions can be a performance killer, if you're using them for all possible errors then you might end up with them being used for program flow - and that is very bad.
In addition, I'd be worried that someone is calling your library from an app that has exception handling turned off.

Generally speaking, if you're writing a completely sealed-off component, you shouldn't be throwing exceptions outside it unless they are definitely documented as things to expect. No-one wants to know about the internals of your component so all exceptions you throw internally should be caught and then (where applicable) presented to the user as a defined error case. In most cases, returning this information as an error code is the simplest, easiest and safest approach.

The reason here is that you can throw whatever exception you like, or the system can do so for you, and the user of your component can do nothing with it. At least with error codes, you're not going to let unhandled exceptions propagate through to the user.

You must not allow exceptions to return from your component if they're "normal" errors. People say that exceptions should be for exceptional situations and they're right - once you start returning "end of file" exceptions, the user will have to wrap every last one of your method calls in an try block - which makes for really messy code. If you use exceptions, the user should be able to call your functions and never put a try block anywhere, if nothing goes wrong there won't be a problem. If you can't achieve this then the user's code will have to be littered with exception handlers for all the cases where he thinks you might throw one.

A hybrid approach can work though, error codes for most things with exceptions for all unexpected problems, but if you're doing that, you might as well stick with just error codes at the boundaries of your library.


问:
Why aren't user-defined operators more common?
One feature I miss in from functional languages is the idea that operators are just functions, so adding a custom operator is often as simple as adding a function. Many procedural languages allow operator overloads, so in some sense operators are still functions (this is very true in D where the operator is passed as a string in a template parameter).

It seems that where operator overloading is allowed, it is often trivial to add additional, custom operators. I found this blog post, which argues that custom operators don't work nicely with infix notation because of precedence rules, but the author gives several solutions to this problem.

I looked around and couldn't find any procedural languages that support custom operators in the language. There are hacks (such as macros in C++), but that's hardly the same as language support.

Since this feature is pretty trivial to implement, why isn't it more common?

I understand that it can lead to some ugly code, but that hasn't stopped language designers in the past from adding useful features that can be easily abused (macros, ternary operator, unsafe pointers).

Actual use cases:

Implement missing operators (e.g. Lua doesn't have bitwise operators)

Mimic D's ~ (array concatenation)

DSLs

Use | as Unix pipe-style syntax sugar (using coroutines/generators)

I'm also interested in languages that do allow custom operators, but I'm more interested in why it has been excluded. I thought about forking a scripting language to add user-defined operators, but stopped myself when I realized that I haven't seen it anywhere, so there's probably a good reason why language designers smarter than me haven't allowed it.

答:
Since this feature is pretty trivial to implement, why isn't it more common?

Your premise is wrong. It’s not “pretty trivial to implement”. In fact, it brings a bag of problems.

Let’s have a look at the suggested “solutions” in the post:

No precedence. The author himself says “Not using precedence rules is simply not an option.”

Semantic aware parsing. Like the article says, this would require the compiler to have a lot of semantic knowledge. The article doesn’t actually offer a solution for this and let me tell you, this simply isn’t trivial. Compilers are designed as a trade-off between power and complexity. In particular, the author mentions a pre-parsing step to collect the relevant information, but pre-parsing is inefficient and compilers strive very hard to minimise parsing passes.

No custom infix operators. Well, that’s not a solution.

Hybrid solution. This solution carries many (but not all) of the disadvantages of semantic aware parsing. In particular, since the compiler has to treat unknown tokens as potentially representing custom operators, it often cannot produce meaningful error messages. It also may require the definition of said operator to proceed with parsing (to collect type information etc.), once again necessitating an additional parsing pass.

All in all, this is an expensive feature to implement, both in terms of parser complexity and in terms of performance, and it’s not clear that it would bring a lot of benefits. Sure, there are some benefits to the ability of defining new operators but even those are contentious (just look at the other answers arguing that having new operators isn’t a good thing).


答:
If someone has the source code (or byte code that can be reverse engineered) then they WILL be able to get the secret key by running the code in a debugger, and putting a break point at the point where you send the key.

You can make it a little harder by supplying a precompiled C library that talks to drop box, with the key encoded in that, but there are still plenty of ways in which keys will leak out (i'm thinking strings for example).

The only safe way that I can think of doing this, is to provide a web service that does the posting to drop box. That way the secret key remains on your server under your control.  The hosting and bandwidth costs mean that this solution is less than ideal for a free application, but the added bonus is that your server can authenticate the clients properly before relaying their files being sent to dropbox.


答:
If its in C++, just use one of the smart pointers - unique_ptr would work well for you, as it won't delete the underlying object until no-one has a handle on it. You pass the ptr object to the receiver by value and never need to worry about which thread should delete it (in cases where the receiver doesn't receive the object).

You'd still need to handle locking between the threads but performance will be good as no memory gets copied (only the ptr object itself, which is tiny).

Allocating memory on the heap isn't the fastest thing ever, so pooling is used to make this much faster. You just grab the next block from a pre-sized heap in a pool, so just use an existing library for this.

Title: Memory management for fast message passing between threads in C++

Body:
Suppose there are two threads, which communicate by asynchronously sending data messages to each other. Each thread has some kind of message queue.

My question is very low level: What can be expected to be the most efficient way to manage the memory? I can think of several solutions:

Sender creates the object via new. Receiver calls delete.

Memory pooling (to transfer the memory back to the sender)

Garbage collection (e.g., Boehm GC)

(if the objects are small enough) copy by value to avoid heap allocation completely

1) is the most obvious solution, so I'll use it for a prototype. Chances are that it is already good enough. But independent of my specific problem, I wonder which technique is most promising if you are optimizing for performance.

I would expect pooling to be theoretically the best, especially because you can use extra knowledge about the flow of information between the threads. However, I fear that it is also the most difficult to get right. Lots of tuning... :-(

Garbage collection should be quite easy to add afterwards (after solution 1), and I would expect it to perform very well. So, I guess that it is the most practical solution if 1) turns out to be too inefficient.

If the objects are small and simple, copy by value might be the fastest. However, I fear that it forces unnecessary limitations on the implementation of the supported messages, so I want to avoid it.


答:
The cost of throwing an exception is negligible compared to writing to a disk. In addition, return codes are more expensive, not less. Finally, nobody is going to care how fast your library is when they can't make their program have the correct semantics because their teammate who just joined the company forgot to check a return code.

The only safe return code is the one that the user can safely ignore.


问:
Azure website that talks to third party services
I have website that crawls data from many third party services when user browse to webpage. This can be really slow because I hit third party server and process returned data before showing it to user. I am hosting website on Azure (shared mode). I am thinking to improve my implementation. Here is what I am thinking...

Run a service that crawls data from third party services, process it and then store it in database. when user browse to my site, my site pulls data from database and display them to user.

But above solution is not clear to me. Should I have normal service or wcf service? If wcf service then should website talk to database or wcf service (that can access data from database)? If normal service then how can I deploy on Azure?

答:
You could first send the website without the 3rd party data to the client, and then make the client request the data of each 3rd party site using an XmlHttpRequest to your server.

That way you could display a "loading" placeholder animation for each external service which hasn't loaded yet. When some of the external services take longer to load, the user could already see the data from those which have already responded.


答:
Technical difficulties to handle precedence and complex parsing set aside, I think there are a few aspects of what a programming language is that has to be considered.

Operators are typically short logical constructs that are well defined and documented in the core language (compare, assign..). They are also typically hard to understand without documentation (compare a^b with xor(a,b) for instance). There are a rather limited number of operators that actually might make sense in normal programming (>,<, =,+ etc..).

My idea is that it's better to stick to a set of well defined operators in a language - then allow operator overloading of those operators (given a soft recommendation that the operators should do the same thing, but with a custom data type).

Your use cases of ~ and | would actually be possible with simple operator overloading (C#,C++, etc.). DSL is a valid usage area, but probably one of the only valid areas (from my point of view). I, however, think that there are better tools to create new languages within. Executing a true DSL language within another language is not that difficult by using any of those compiler-compilers tools. Same goes for the "extend LUA argument". A language is most likely defined primarily to solve problems in a specific way, not to be a foundation for sub-languages (exceptions exists).

Title: Why aren't user-defined operators more common?

Body:
One feature I miss in from functional languages is the idea that operators are just functions, so adding a custom operator is often as simple as adding a function. Many procedural languages allow operator overloads, so in some sense operators are still functions (this is very true in D where the operator is passed as a string in a template parameter).

It seems that where operator overloading is allowed, it is often trivial to add additional, custom operators. I found this blog post, which argues that custom operators don't work nicely with infix notation because of precedence rules, but the author gives several solutions to this problem.

I looked around and couldn't find any procedural languages that support custom operators in the language. There are hacks (such as macros in C++), but that's hardly the same as language support.

Since this feature is pretty trivial to implement, why isn't it more common?

I understand that it can lead to some ugly code, but that hasn't stopped language designers in the past from adding useful features that can be easily abused (macros, ternary operator, unsafe pointers).

Actual use cases:

Implement missing operators (e.g. Lua doesn't have bitwise operators)

Mimic D's ~ (array concatenation)

DSLs

Use | as Unix pipe-style syntax sugar (using coroutines/generators)

I'm also interested in languages that do allow custom operators, but I'm more interested in why it has been excluded. I thought about forking a scripting language to add user-defined operators, but stopped myself when I realized that I haven't seen it anywhere, so there's probably a good reason why language designers smarter than me haven't allowed it.


问:
Unit Testing DatabaseOpenHelper class in Android
I've written several unit tests for an already existing DatabaseOpenHelper class. I covered the creation scenario and migration from old schema to new one. Unfortunately, I don't feel that my tests are good. For example, for DB creation I check that SQLiteDatabase. execSQL() was called three times (we have three tables so far) and check that query string is in set of specified SQL strings.

The issue so far - if someone changes order of columns the test will fail. Probably this is OK.

But what are other ways of SQL schema unit testing? Or don't you have unit tests for that, and rely only on the integration one?

答:
Instead of verifying that

colum1 is name,

colum2 is birthday,

colum3 is ....

i would just test if these colums exist after upgrade.

To do this I would create an integration test that

starts with a databasefile which has old database  version,

run the updater and then

execute a sql-select for every table with a all fields.

Example:

select name, birthday, telefonnumber from customer

select orderid, orderdate, customerid from order

Test-Success means there is no database-exception for unknown table or field.

[Update 2.2.2013]
Unittesting the DatabaseOpenHelper (Unittest=Testing in isolation) would requre to test without a real database and verifying that the database update script is valid or at least contain all neccessary fields/tables. In my opinion this is to much work. Integration testing with a real database is much easier.


答:
Since this feature is pretty trivial to implement, why isn't it more common?

It isn't trivial to implement (unless trivially implemented). It also doesn't get you very much, even if implemented ideally: the readability gains from terseness are offset by the readability losses from unfamiliarity and opacity.
In short, it's uncommon because it's not usually worth the developers' or the users' time.

That said, I can think of three languages that do it, and they do it in different ways:

Racket, a scheme, when it isn't being all S-expression-y allows and expects you to write a what amounts to parser for any syntax you want to extend (and provides useful hooks to make this tractable).

Haskell, a purely function programming language, allows defining any operator that consists solely of punctuation, and allows you to provide a fixity level (10 available) and an associativity. Ternary etc. operators can be created out of binary operators and higher order functions.

Agda, a dependently typed programming language, is extremely flexible with operators (paper here) allowing both if-then and if-then-else to be defined as operators in the same program, but its lexer, parser, and evaluator are all strongly coupled as a result.


答:
We do not use user-defined operators for the same reason we do not use user-defined words. No one would call their function "sworp". The only way to convey your thought to other person is to use shared language. And that means both words and signs (operators) must be known to the society for whom you are writing your code.

Therefore the operators you see in use in programming languages are the ones we've been taught in school (arithmetic) or the ones that have been established in programming community, like say boolean operators.


问:
The idea of functionN in Scala / Functionaljava
From brain driven development

It turns out, that every Function you’ll ever define in Scala, will
  become an instance of an Implementation which will feature a certain
  Function Trait.

There is a whole bunch of that Function Traits, ranging from Function1 up to
  Function22.

Since Functions are Objects in Scala and Scala is a statically typed
  language, it has to provide an appropriate type for every Function
  which comes with a different number of arguments. If you define a
  Function with two arguments, the compiler picks Function2 as the
  underlying type.

Also, from Michael Froh's blog

You need to make FunctionN classes for each number of parameters that
  you want? Yes, but you define the classes once and then you use them
  forever, or ideally they're already defined in a library (e.g.
  Functional Java defines classes F, F2, ..., F8, and the Scala standard
  library defines classes Function1, ..., Function22)

So we have a list of function traits (Scala), and a list of interfaces (Functional-java) to enable us to have first class funtions.

I am trying to understand exactly why this is the case. I know, in Java for example, when I write a method say,

```<code>public int add(int a, int b){
    return a + b;
}
</code>```

That I cannot go ahead and write

```<code>add(3,4,5);
</code>```

( error would be something like : method add cannot be applied to give types )

We simply have to define an interface/trait for functions with different parameters, because of static typing?

答:
One does have to implement functions as first-class objects in Scala somehow, no? When the programmer e.g. assigns a function literal to a variable, that variable must get some value at runtime that represents the function in a type-safe way. The implementers of Scala have chosen to do it the way the FunctionN traits work. So, all the syntax for functions in Scala is essentially just syntactic sugar for that implementation. Each function of e.g. some type (A, B C) => D becomes an object that has type Function3[A,B,C,D] at runtime and thus, among other things, implements a method apply(p1: A, p2: B, p3: C): D.
Applying the function is syntactic sugar for calling the apply method etc.
Also, this is how Java can interoperate with Scala functions.


问:
Design Parts DB
I'm developing a tool that handles (electrical) parts. The parts can be created, viewed, modified, deleted, grouped and so on...

In order to make this question useful for future visitors I like to keep this question universal since managing parts in a DB is very common no matter what parts are in the DB (CDs, cars, food, students, ...).

I am thinking of 3 different DB designs:

Using a parts table and derived tables for specialized part attributes.

```<code>Parts      (id, part_type_id, name)
PartTypes  (id, name)
Wires      (id, part_id, lenght, diameter, material)
Contacts   (id, part_id, description, picture)
</code>```

Using only specialized part tables.

```<code>Wires      (id, name, lenght, diameter, material)
Contacts   (id, name, description, picture)
</code>```

Using a Parts-, PartTypes-, ValueTypes- and PartValues table that contain all values.

```<code>PartTypes  (id, name)
ValueTypes (id, part_type_id, name)
Parts      (id, part_type_id, name)
PartValues (part_id, value_type_id, value)
</code>```

Which one to prefer and why? Or is there a better one?

I am concerned about the DB queries. I don't want the queries become overly slow or complicated.

Update

The number of types in the DB are pretty much given and static since they rest on a international standard and will be enhanced seldomly.

答:
With NOSQL DB database (like MongoDB for example) you will just need one set named "Parts".
Each part in that set is so called document - record with variable set of fields:

```<code>{
   "_id": ObjectId("4efa8d2b7d284dea1"),
   "partType": "wire",
   "length": 102.5,
   "diameter": 1.5,
   "material": "silver"
},
{
   "_id": ObjectId("4efa8d2b7d284sjsq23d"),
   "partType": "contact",
   "description": "something",
   "picture": Binary(...)
},
</code>```

I think that this is the most natural data storage for the task you describe.

Title: Design Parts DB

Body:
With NOSQL DB database (like MongoDB for example) you will just need one set named "Parts".
Each part in that set is so called document - record with variable set of fields:

{
   "_id": ObjectId("4efa8d2b7d284dea1"),
   "partType": "wire",
   "length": 102.5,
   "diameter": 1.5,
   "material": "silver"
},
{
   "_id": ObjectId("4efa8d2b7d284sjsq23d"),
   "partType": "contact",
   "description": "something",
   "picture": Binary(...)
},

I think that this is the most natural data storage for the task you describe.


答:
You're fighting against two things here:

Why do operators exist in languages in the first place?

What is the virtue of operators over functions/methods?

In most languages, operators are not really implemented as simple functions. They might have some function scaffolding, but the compiler/runtime is explicitly aware of their semantic meaning and how to translate them efficiently in to machine code. This is much more true even as compared to built-in functions (which is why most implementations also don't include all the function call overhead in their implementation). Most operators are higher level abstractions on primitive instructions found in CPUs (which is partly why most operators are arithmetic, boolean, or bitwise). You could model them as "special" functions (call them "primitives" or "builtins" or "native" or whatever), but to do that generically requires a very robust set of semantics for defining such special functions. The alternative is to have built-in operators that semantically look like user defined operators, but which otherwise invoke special paths in the compiler. That runs afoul of the answer to the second question...

Aside from the machine translation issue I mentioned above, at a syntactical level operators aren't really different from functions. They're distinguishing characteristics tend to be that they are terse and symbolic, which hints at a significant additional characteristic they must have to be useful: they must have broadly understood meaning/semantics to developers. Short symbols don't convey much meaning unless it is short hand for a set of semantics that are already understood. That makes user defined operators inherently unhelpful, as by their very nature they aren't so broadly understood. They make as much sense as one or two letter function names.

C++'s operator overloads provides fertile ground for examining this. Most operator overload "abuse" comes in the form of overloads that break some of the semantic contract that is broadly understood (a classic example is an overload of operator+ such that a + b != b + a, or where + modifies either of its operands).

If you look at Smalltalk, which does allow operator overloading and user defined operators, you can see how a language might go about doing it, and how useful it would be. In Smalltalk, operators are merely methods with different syntactical properties (namely, they are encoded as infix binary). The language uses "primitive methods" for special accelerated operators and methods. You find that few if any user defined operators are created, and when they are, they tend not to get used as much as the author probably intended for them to be used. Even the equivalent of an operator overload is rare, because it is mostly a net loss to define a new function as an operator instead of a method, as the latter allows for an expression of the semantics of the function.


答:
I would start with a data/object model allowing inheritance, and then use a standard object-relational mapping. This way you get a base class Parts and sub-classes like Wires, Contacts etc. Now, if you apply a "map-each-class-to-own-table" strategy, you get option 1, which is the most "normalized" solution and should be the canonical strategy if you don't have any more information about the queries you expect.

Option 2 is what you get when applying a "map-each-concrete-class-to-own-table" approach. This can avoid "joins" and may perform better for some kind if queries (especially queries for just one "part type"), on the other hand it makes generic handling with all parts harder and slower. Avoid this if you don't have any special reasons for it.

Option 3 is what you need only if you want the user to change the number of part types at run time - if you don't expect that requirement, option 3 will be a perfect example for over-engineering things.

Title: Design Parts DB

Body:
I'm developing a tool that handles (electrical) parts. The parts can be created, viewed, modified, deleted, grouped and so on...

In order to make this question useful for future visitors I like to keep this question universal since managing parts in a DB is very common no matter what parts are in the DB (CDs, cars, food, students, ...).

I am thinking of 3 different DB designs:

Using a parts table and derived tables for specialized part attributes.

```<code>Parts      (id, part_type_id, name)
PartTypes  (id, name)
Wires      (id, part_id, lenght, diameter, material)
Contacts   (id, part_id, description, picture)
</code>```

Using only specialized part tables.

```<code>Wires      (id, name, lenght, diameter, material)
Contacts   (id, name, description, picture)
</code>```

Using a Parts-, PartTypes-, ValueTypes- and PartValues table that contain all values.

```<code>PartTypes  (id, name)
ValueTypes (id, part_type_id, name)
Parts      (id, part_type_id, name)
PartValues (part_id, value_type_id, value)
</code>```

Which one to prefer and why? Or is there a better one?

I am concerned about the DB queries. I don't want the queries become overly slow or complicated.

Update

The number of types in the DB are pretty much given and static since they rest on a international standard and will be enhanced seldomly.


问:
Would it be better to have extra checks, or would it be a waste of time?
In your opinion, do you think it is a waste of time to make checks that you know there is no possible way of it being there/not being there, or would you just put it there just in case there is a bug or something?  For example, below checks to see if a button is visible, then music is playing, but there is no way for that button to be shown without the music playing:</p>

```<code>if (buttonVisible)
    if ([music playing] == true) //is always true if the button is visible
        [music stopPlaying];
</code>```

答:
What if:

Some other application manipulates the window and renders the button visible while the music is not playing?

A thread stops the music and is about to hide the button when you check the visibility of a button?

Some other developer modifies the code, without knowing the relationship between the visibility of the button and the music state?

You modify the code since the requirements changed and instead of hiding the button, you were required to only disable it?

You replace the button by some other control?

In other words:

You shouldn't check for a condition if “there is no possible way of it being true/false”. For example the if block in the following code is redundant and should be removed:

```<code>assert(input > 0);
var i = input * 2;
if (i > 0)
{
    // Do something useful.
}
</code>```

You should check for a condition in a case like the one you illustrated, since there is no strict and reliable relation between the visibility of a button and the state of the music.

Note that in your code, what you should omit is the first if. Since you simply want to stop the music (and for a reason, you can't just call music stopPlaying if the music is not playing), the only check you should do is if ([music playing]). That the button is visible or not doesn't matter. You don't care whether it is visible or not, enabled or not, or even if it exists.

For example something like:

```<code>if ([button visible])
    if ([music playing])
        [music stopPlaying]
        [button hide]
</code>```

could be rewritten as:

```<code>if ([music playing])
    [music stopPlaying]
    [button hide]
</code>```

if the visibility of the button relies on the state of the music. Data binding, if supported by your language/framework, is even better:

```<code>[button visibility=(bind:music state)]

// Later in code:

if ([music playing])
    [music stopPlaying] // The button is hidden automatically
</code>```

Body:
What if:

Some other application manipulates the window and renders the button visible while the music is not playing?

A thread stops the music and is about to hide the button when you check the visibility of a button?

Some other developer modifies the code, without knowing the relationship between the visibility of the button and the music state?

You modify the code since the requirements changed and instead of hiding the button, you were required to only disable it?

You replace the button by some other control?

In other words:

You shouldn't check for a condition if “there is no possible way of it being true/false”. For example the if block in the following code is redundant and should be removed:

assert(input > 0);
var i = input * 2;
if (i > 0)
{
    // Do something useful.
}

You should check for a condition in a case like the one you illustrated, since there is no strict and reliable relation between the visibility of a button and the state of the music.

Note that in your code, what you should omit is the first if. Since you simply want to stop the music (and for a reason, you can't just call music stopPlaying if the music is not playing), the only check you should do is if ([music playing]). That the button is visible or not doesn't matter. You don't care whether it is visible or not, enabled or not, or even if it exists.

For example something like:

if ([button visible])
    if ([music playing])
        [music stopPlaying]
        [button hide]

could be rewritten as:

if ([music playing])
    [music stopPlaying]
    [button hide]

if the visibility of the button relies on the state of the music. Data binding, if supported by your language/framework, is even better:

[button visibility=(bind:music state)]

// Later in code:

if ([music playing])
    [music stopPlaying] // The button is hidden automatically


问:
Are there any programming languages that follow a minimalist development approach?
I find it that when languages are considered the same as commercial software, there is always a constant need to add new features to justify new releases.

Can there be or are there languages where version 1.0 is the final version? Of course bug fixes are exempt from this, but the feature set always remains the same?

This way every feature in the language fits together nicely and not seem like they are bolted on after the fact with obsolete features still around because of backwards compatibility.

I assume some academic languages are like this? But are there commercially successful languages that follows this idea? The accompanying library is also free to get new features too, but the language always remains constant.

One example I can give is, one of my favourite languages C#, which I use pretty often, more and more features are being added every release. To take advantages of these, I have to drop actual tasks in hand, and spend considerable time learning these instead of being able to pick up trivial concepts and combine those myself to solve more complex problems with ease.

So I guess I am looking for a minimalist approach where everything is consistent, makes sense, and is as orthogonal as possible.

答:
Although Lisp was mentioned, The most minimalistic language I know is scheme. I had a hard time understanding it in university courses where I had to. But it changed my way of thinking about programming, and It is very minimal. As minimal as its whole syntax are Parentheses () and spaces.

The only change in the language was the decision to convert the primitives like +, define (and some others) to built-ins. Meaning they are available on launch, but can be re-defined during run-time.


问:
How to understand and debug legacy software?

Possible Duplicate:

  I’ve inherited 200K lines of spaghetti code — what now?

Not long ago my company placed me in a team that deals with some of the most complex bugs that are in production. The thing is that almost all of these bugs are in legacy applications I am having a really difficult time understanding and debugging, and these are some of the reasons:

Bad software design

Lots of code duplication

Misleading comments

Bad names

No documentation at all

The creators of the software no longer work in the company

Really big classes and methods, very badly programmed

Bugs are very badly documented and the operations team makes very poorly documented reports on the issues that occur.

It is very time consuming and frustrating. As a TDD and ATDD developer,  I try by starting writing tests to triangulate and pinpoint the problem, but there are so many things that need to be mocked that it is very difficult. Also the business analysts don't provide criteria for this software since they don't even know it themselves. The only thing they say is that it needs to be fixed.

I thought that maybe here I could find somebody with experience in legacy software that could give me some advice on how to deal with bugs in an environment like this. I feel I am doing software archeology when working with this. Also it is very stressful and this big amount of frustration makes me feel useless and unproductive since it takes weeks sometimes to fix bugs. I always worked green field development and this is the first time I am doing production support. I would really appreciate some advice.

答:
You have hit the nail on the head - What you have complained about is the definition of "Legacy software". Working on this class of software requires a different mindset to Green-fields work. Your stress is a result of you measuring your progress against unrealistic measures.

Don't try to put todays ideology on yesterdays work. If it was not designed around TDD and UT, then retro-fitting Test driven methodology is a major, expensive and difficult undertaking. As you are finding - shoehorning todays silver bullets into yesterdays failed silver bullets is far from the ideal way to work. If carefully though through, with clear understanding of goals and benefits, it can be worth while.  However, it quickly devolves into negative returns. Go for the "low hanging fruit" and develop tests only if it clear they will be used many times and find many defects.

The best approach is to remove unrealistic expectations. Productivity will be low, code hard to analyze and faults hard to fix. Unexpected side effects of changes are likely, and as you have found, regression testing non-existent- Maintaining Legacy code is slow and hard - thats why so many developers run off to Green Fields projects. I can be rewarding, but only if you reset your expectations.

When you start work on a defect, start by staying focused on three things - What the code does now, not introducing unexpected side effects and what it should do when fixed. You may find that "code duplication" is better than "unexpected side effects"..... Without decent tests and requirements, introducing regression is often the biggest sin of all.

Always strive to leave the code in a better state than you found it, but be careful not to change its behavior except where required.


答:
This is always a frequent area of debate at user groups and conferences I attend. The best advice I've ever heard is this:

For new, well tested code, the tests are the source of all truth. For untested, legacy code, the codebase is the source of all truth. When adding a new feature, write solid unit tests. When addressing an existing module or fixing a defect, test as best you can, to avoid regression. Take your time, keep calm, and carry on.

That's clearly a paraphrase of a few well-honed perspectives, but the core is this: the codebase is clearly 'broken', but the functionality isn't and that's what users care about. But if it becomes completely unmaintainable, and you have an idea about how to re-implement functionality quickly and sanely, it might be time to bring up the possibility of the dreaded 'big rewrite'.

I admit that I'm in the camp that says the big rewrite is never a good idea, until it is. You, your team, and your customers will have to discuss and negotiate if or when that time has come. Best of luck, it's a terrible situation with no one correct solution. I should know, I've been there before a few times.

Title: How to understand and debug legacy software?

Body:
Possible Duplicate:

  I’ve inherited 200K lines of spaghetti code — what now?

Not long ago my company placed me in a team that deals with some of the most complex bugs that are in production. The thing is that almost all of these bugs are in legacy applications I am having a really difficult time understanding and debugging, and these are some of the reasons:

Bad software design

Lots of code duplication

Misleading comments

Bad names

No documentation at all

The creators of the software no longer work in the company

Really big classes and methods, very badly programmed

Bugs are very badly documented and the operations team makes very poorly documented reports on the issues that occur.

It is very time consuming and frustrating. As a TDD and ATDD developer,  I try by starting writing tests to triangulate and pinpoint the problem, but there are so many things that need to be mocked that it is very difficult. Also the business analysts don't provide criteria for this software since they don't even know it themselves. The only thing they say is that it needs to be fixed.

I thought that maybe here I could find somebody with experience in legacy software that could give me some advice on how to deal with bugs in an environment like this. I feel I am doing software archeology when working with this. Also it is very stressful and this big amount of frustration makes me feel useless and unproductive since it takes weeks sometimes to fix bugs. I always worked green field development and this is the first time I am doing production support. I would really appreciate some advice.


答:
Learning how to read and understand other people's code is a huge part of being a programmer. Some of the code you read will be your own. It can be dangerous to modify code when you don't fully understand how it fits into the whole. Introducing unit tests and running them as part of some kind of automatic build system will help you keep the code they cover from changing behavior, but this means (especially with legacy code) that you have to understand how the code you're changing is used by the system.

It can be tempting to throw away code that seems to be too complex (or crufty, whatever that means) and rewrite it yourself. (Everyone wants to be the architect). The danger in throwing away old code and rewriting it from scratch is that you're also throwing away knowledge gained by time and hard experience that will usually be difficult to regain except by repeating the same mistakes and fixing the same bugs the original developers did over time.

Introducing TDD into (or on top of) a legacy system can be tricky. Be prepared to fix bugs in these tests as you will inevitably find inconsistencies in the code itself. Remember that your tests are not infallible. As you come to better understand the existing system, you will have to improve/fix them.


问:
Will Java still be relevant in 5 years?
Will Java have the same importance it had in the past, or it will be less relevant than nowadays?</p>

答:
If it's bound to some industry (i.e. banking; mobile platforms; etc.) it's like asking "Will Internet Explorer still be relevant in 5 years.." 5 years ago. Today there are many companies that have IE-specific internal websites that can't be rewritten from scratch. So it's not "relevant" but "unavoidable".

To come to your question-- no, it's not relevant as a driving force for innovation; but yes, it's relevant because many industries will require java applications to be maintained for many years to come.

Title: Will Java still be relevant in 5 years?


问:
Setting up Clojure Project And Sub Projects
This is primarily a lein question about setting up a major project and its sub-projects, and is not intended to be a discussion question. Instead, I am interested in either a pointer to documentation or to a Clojure/lein best practices link.

I have a municipal property assessments application that splits two master flies into different subset files, depending on whether a billing transfer is taking place or we want to batch update new accounts, rather than making our assessment department enter new accounts once in their system and then again in the tax collection system.

My application is going to be large enough, that I can see a common library lein project with support functions, like splitting apart the files, and then individual lein projects that use the common library.

Should the lein projects be set up at the same level and support included through the project.clj/core.clj files?

Is there an advantage to creating lein new projects underneath a major project?

Is there a problem with combing all functions in one project?

I can probably make my one core.clj contain all flavors of the program, but coming from a C/C++ and Python background, I would prefer to have a lot of little projects.

答:
If you reasonably believe that parts of your project would be valuable as shared libraries, I would build separate projects for them with lein new.

At the same time, Clojure is all about simplicity, so you can always create the components in separate namespaces, and pull out pieces as libs on an as-needed basis (really, you should be doing this anyhow, in order to keep your components as decoupled as possible).

Once you have your separate pieces, you have a couple of options. If you want to make them public/open-source, you can upload them to Clojars. If they're private, in-house libs, you can set up a maven server internally, or while you're in early development, just use lein-localrepo to have them accessible to your build process when you include them in your project.clj.

This is one of those times for hammock-driven development; think carefully about which modules you think will be reusable before you start, and create those as separate libs. But for many cases, that level of reusability is a YAGNI feature, so my usual approach is to just put common functionality in a common namespace, and extract it out asa library on an ad hoc basis. It's both pragmatic, and avoids the pain of having to maintain too many discrete software entities unnecessarily.


答:
This is slow work.  Be patient.  Your colleagues are probably the best source of information available.  As you gain knowledge, add comments so the next guy won't have to relearn what you already know.

This work is not a lot of fun, and doesn't do much to advance a career, so you should be paid more than you would get for new development.  I would probably not take on work of this type as a salaried employee.  I would want to get contractor rates including overtime for the many "emergencies" that are sure to arise.


问:
Hash function classification
On the internet, I've come across this question:

Classify the Hashing Functions based on the various methods by which the key value is found.

with answers like

Direct method

Subtraction method

Modulo-Division method

Digit-Extraction method

Mid-Square method

Folding method

Pseudo-random method

which I find strange. I think I know a lot about hashing, but this is plain gibberish to me, could anybody explain?

答:
They are methods of turning a hashcode into an index of the array that contains the values. Let's say you have a hashcode of 0x12345678. A very large number and you're unlikely to have an array of this size. If you do you can just do

```<code>Value = array[0x12345678];
</code>```

And be done (direct method).

If you don't then you have a figure out a way to turn this value into one that fits the array size while trying to avoid too many collisions. The terms used are probably known by other names too, but for example you could just mask off the higher bits of the hashcode

```<code>Value = array[hashcode & 0xffff];
</code>```

Or mod the hashcode against the array size

```<code>Value = array[hashcode % array.size()]; // modulo division
</code>```

Etc etc

Edit: this link may help

Title: Hash function classification

Body:
They are methods of turning a hashcode into an index of the array that contains the values. Let's say you have a hashcode of 0x12345678. A very large number and you're unlikely to have an array of this size. If you do you can just do

Value = array[0x12345678];

And be done (direct method).

If you don't then you have a figure out a way to turn this value into one that fits the array size while trying to avoid too many collisions. The terms used are probably known by other names too, but for example you could just mask off the higher bits of the hashcode

Value = array[hashcode & 0xffff];

Or mod the hashcode against the array size

Value = array[hashcode % array.size()]; // modulo division

Etc etc

Edit: this link may help


问:
Ruby but not Rails on my Resume
I have listed Ruby as a skill on my resume becuase I've been programming in Ruby for 5 years while I work on my Ph.D. thesis. I've mostly been using it to implement natural language processing algorithms.

I'm starting to look for a job, and I posted my resume to a few sites (as an extra bonus when applying to certain on-target jobs). Now I get recruiters calling me to offer me Ruby on Rails jobs. The problem is that I've never learned Rails. It was never relevant to what I'm doing for my Ph.D.

How do you recommend handling this situation to avoid wasting my time and theirs? (And learning Rails probably isn't an option until I finish my thesis.) Can my resume be adjusted to make this clearer? Should it be adjusted? Should I just politely tell them on the phone that I don't know Rails?

By the way, the relevant part of my resume simply says:

Skills:

Programming Languages:  C, C++, Java, Scala, Ruby, LaTeX

Databases: MySQL, XML, XPath

and lists a few other skill areas that couldn't possibly be confused with a Rails developer.

答:
I would leave it as is and just list Ruby.

I would also spend 1 hour boning up and if you know Ruby well, there's not that much to know.

It's Model-View-Controller.

The models represent database tables through the rails ORM, mapping models and attributes to tables.

Functionality such as authentication can be done through 'gems'.

html is created through 'ERB' templates.

Low cost hosting solutions exist, e.g. Heroku.

Title: Ruby but not Rails on my Resume


答: There is an approach that I found quite useful while working with situation similar to what you have described. Usually legacy code written in very monolithic and obscure way. But there's an interesting approach to start working with legacy code: approval tests. I'll recommend you to start with recording of golden copy and make sure that captured information contains values meaningful to your business. Next step, show that golden copy to business analyst. Usually, that are able not only to understand this representation, but also tell you what is wrong with those numbers, otherwise what are business analysts for? So now, you have both current result of program executing, commented by analyst, so you could safely start refactoring and bug fixing in your legacy code.


问:
Data decoding initialization/Constructor error handling
I have a set of loadable data decoders for a specific type of data and a stream to read containing data. Now I want the program to select the correct decoder in a reliable way so I want to use a trial-and-error algorithm. It seems resonable to create a decoder and connect it to the stream using a constructor:

```<code>// C++ code
// codecs is an array of structs containing function pointers loaded from a dll
FileIn src("foo.wav");
for(size_t i=0; i<N_CODECS; ++i)
    {
    try
        {
        WaveIn wavein(codecs[i],src);
        //Process data
        return;
        }
    catch(...) //Swallow error. It's likly that another codec works. But if it were another error??
        {
        src.reset();
        }
    }
//no codec found (definitly an error)
</code>```

Here, there is probably no true error before we have tried all codecs in the list. The reason to try-catch here is that it is not possible to get return code from the ctor. Would it be better to use zombie objects in this case?

EDIT: What the constructor does, is the following

```<code>WaveIn::WaveIn(Vtable& vt, FileIn& src):m_vt(vt)
    {
    m_handle=m_vt.create(src);
    if(m_handle==NULL) //Resources allocated in DLL were released in this case.
         {throw "Bad file";}
    }
</code>```

The dtor:

```<code>WaveIn::~WaveIn()
    {
    m_vt.destroy(m_handle);
    }
</code>```

答: Many programmers see throwing exceptions to control flow as a code smell, because Exceptions (in Java, c and C++) are like non-local goto statements that are hard to understand and the chances for memory leaks are high. </p>


问:
Why must the burden of proof rest with the caller and not the method of the class that is being called?
Michael Perry states in his Pluralsight course on Provable Code (transcript subscription only) that:

[T]he burden of proof rests with the caller

In a code contract, why must the burden of proof rest with the caller and not the method of the class that is being called? Is this a preferred convention or does it have a more solid basis? At the moment it just like a dogma to me as the class being called could make its own safety checks, which would reduce calling code duplication.

答:
I'd say that "burden of proof" is the wrong way to think about it. A class with a calling contract can and should validate that the contract is kept by callers. But when it's not, all it can do is produce an error/exception.

The point of the contract is to state clearly  what the calling code must do to produce a correctly working program, so that there are no errors/exceptions. When a code contract is not kept, that's a programming error. Making the contract explicit helps you to avoid the error.

If you're serious about code contracts, you want a language where they are enforced by the compiler as much as possible.


问:
How to document a dual open source license?
If a project is dual-licensed GPL & BSD, should there be one LICENSE file with the text of both licenses? Or two separate files, one for each license?

And I think I should put a copyright/license comment at the top of each source file. How should that comment indicate the dual-licensed status of the project?

答:
To make it immediately clear that the project uses a dual licence, I would recommend to have two licence files, LICENCE.GPL and LICENCE.BSD.

Also, if your files currently have no copyright notices, they can not be legally distributed under either of those licences, because both require that a copyright notice is present in all source files (in addition to other notices required by GPL).


答: As to languages that do support such overloading: Scala does, actually in a much cleaner and better way can C++. Most characters can be used in function names, so you can define operators like !+*=++ , if you like. There is built-in support for infix (for all functions taking one argument). I think you can define the associativity of such functions, too. You can't however, define the precedence (only with ugly tricks, see here).</p>


问:
Is programming in Python faster than in C, C++ or Java?
There's a widespread belief among programmers that the more dynamic and loosely typed the language, the more productive the programmer will be in it. Guido van Rossum wrote about programming productivity using python in 1998 and searching around the web I still see people referencing this exact claim:

Syntactically, Python code looks like executable pseudo code. Program development using Python is 5-10 times faster than using C/C++, and 3-5 times faster than using Java. In many cases, a prototype of an application can be written in Python without writing any C/C++/Java code. Often, the prototype is sufficiently functional and performs well enough to be delivered as the final product, saving considerable development time. Other times, the prototype can be translated in part or in whole to C++ or Java -- Python's object-oriented nature makes the translation a straightforward process.

Has this issue been properly scientifically evaluated? If not for python then perhaps for sibling scripting languages like ruby, perl or php?

I'm not looking for rationalizations, analogies, or explanations why it could potentially be hard to answer, unless it's the opinion of researchers or experts that has taken the time to look into the issue.

I initially asked this question over at skeptics.SE, and someone suggested I should ask it here too.

答:
Last time I used Java (a while ago admittedly) it took a screen full of code to open and write to a file. Compare that to a couple of lines in Python or Perl, and you can guess which one is faster.

Obviously languages all have their own strengths and weaknesses, but for most tasks Python will be faster to write.


答:
That's because it's the caller the one that passes the parameters.

The caller can pass wrong parameters, hence it must check the exceptions thrown by the callee (or err codes).

Title: Why must the burden of proof rest with the caller and not the method of the class that is being called?

Body:
Michael Perry states in his Pluralsight course on Provable Code (transcript subscription only) that:

[T]he burden of proof rests with the caller

In a code contract, why must the burden of proof rest with the caller and not the method of the class that is being called? Is this a preferred convention or does it have a more solid basis? At the moment it just like a dogma to me as the class being called could make its own safety checks, which would reduce calling code duplication.


问:
How did Python become popular as a scripting language?
I looked at it in my field of work, which is film and pretty much every software we use comes with python as a scripting language: http://en.wikipedia.org/wiki/List_of_Python_software That made me assume it's the most popular.

How did Python become popular as a scripting language? Especially as an embedded language into standalone applications.

What's the reason for this? There are others like Lua, Ruby, etc. but yet it looks like Python came on top.

If it's because of a particular thing or just a matter of getting out there at the right time?

答:
Popularity of any language is difficult to measure. There is not a clear indicator that makes one language better than the other. The reason is that there is no language that is the most suitable for everything.

Some languages are more specialized for certain tasks even though they may be used for other tasks (Perl excels in string processing, PHP is famous a web serverside language, Fortran was popular for number crunching, ...).

The age of the language also influences popularity. Say, Fortran would not be that popular for number crunching if it was not one of the oldest (usefull) programming languages.

I like Python, but I would not dare to do an ultimate comparison with other languages. Anyway, I like its clean syntax, readability, brevity, pragmatism, pseudo-code look.

In my opinion, the languages could be compared only in pairs -- i.e. one language vs. the other. And it should be done by people who have intimate knowledge of both.


问:
Can I use a GPL licensed piece of JavaScript on a commercial website?
I'm looking at plupload for some upload features on a website I'm developing. Now plupload is GNU GPLv2 licensed and that implies that all derivative software should also be GPL licensed (right?). Therefore I run the plupload through my minifier, the single minified js file will violate the license, and upon request, I must make all the sources of my page available (right?).

I'm curious about:

can I use the plupload API without having to open source my code?

does the license exclude minified code somehow?

See also: https://stackoverflow.com/questions/3213767/minified-javascript-and-bsd-license

答:
Disclaimer: IANAL

Short answers:

yes, you can use plupload without open sourcing your code

no, minifying is not excluded by the license

Rationale based on my understanding to the GNU GPL 2.0 license is this:

as long as your code is not a derivative work of the GPL'ed work, you are fine. In this case, your code does not extend, modify or otherwise depend on plupload other than using it over well published interfaces, so it can hardly be argued to derive form it. Please note this interpretation is debated and untested in court (as per comment by @apsillers).

minifying the GPL'ed work is fine, as the minified version is really a binary (executable) version of the source code. This is permitted.

you have to offer to provide the GPL'ed code, that is plupload, on request to anyone using your website.

BTW: To be on the safe side, you may want to consider buying one of their commercial license. And no, I am not in any way affiliated to plupload.

** Updates

noted emphasis on GPL 2.0

added link to further information on derivate work interpretation


答:
Yes, you may use GPL licensed javascript on a commercial page. You simply have to meet the distribution requirements. The license does not exclude using minified code, but you will have to make the non-minified version available as well. The easiest way to do this would be to include a comment with a link to the non-minified sources hosted on your site at the top of the minified code.

If you modify the GPL code in any way, your modifications will have to be GPL as well, so they should be included in the non-minified sources that you provide.

Title: Can I use a GPL licensed piece of JavaScript on a commercial website?

Body:
I'm looking at plupload for some upload features on a website I'm developing. Now plupload is GNU GPLv2 licensed and that implies that all derivative software should also be GPL licensed (right?). Therefore I run the plupload through my minifier, the single minified js file will violate the license, and upon request, I must make all the sources of my page available (right?).

I'm curious about:

can I use the plupload API without having to open source my code?

does the license exclude minified code somehow?

See also: https://stackoverflow.com/questions/3213767/minified-javascript-and-bsd-license