答:
I would not worry about having this many parameters in a query.  There is no restriction on number of parameters, only total length of the URL (as mentioned by others).  Long queries with lots of parameters are commonly used by big-name websites.  For example, it is easy to construct a 15 parameter query in Google Maps.

As long as GET makes sense for your case, and you don't have to worry about the character limit, I would use it.

Interestingly, Google Maps also doesn't worry about breaking the 2000 character limit.  Here is the URL it generated for my tour of places with long names in the Philadelphia area:

https://local.google.com/maps?saddr=Philadelphia+International+Airport,+Essington+Avenue,+Philadelphia,+PA,+United+States&daddr=Philadelphia+Archery+%26+Gun+Club,+Ellsworth+Street,+Philadelphia,+PA,+United+States+to:Philadelphia+Museum+of+Art,+Benjamin+Franklin+Parkway,+Philadelphia,+PA,+United+States+to:Northeast+Philadelphia,+Philadelphia,+PA,+United+States+to:Philadelphia+International+Airport,+Essington+Avenue,+Philadelphia,+PA,+United+States+to:Philadelphia+Airport+Florist,+MacDade+Boulevard,+Philadelphia,+PA,+United+States+to:Philadelphia+Museum+of+Art,+Benjamin+Franklin+Parkway,+Philadelphia,+PA,+United+States+to:Philadelphia+Family+Court,+South+11th+Street,+Philadelphia,+PA,+United+States+to:Philadelphia+Museum+of+Art,+Benjamin+Franklin+Parkway,+Philadelphia,+PA,+United+States+to:Erawan+Thai+Cuisine,+South+23rd+Street,+Philadelphia,+PA,+United+States+to:Four+Points+by+Sheraton+Philadelphia+City+Center,+Race+Street,+Philadelphia,+PA,+United+States+to:Philadelphia+Museum+of+Art,+Benjamin+Franklin+Parkway,+Philadelphia,+PA,+United+States+to:Philadelphia+International+Airport,+Essington+Avenue,+Philadelphia,+PA,+United+States+to:Philadelphia+Streets+Department,+Arch+Street,+Philadelphia,+PA,+United+States+to:Oak+Lane%2F+East+Oak+Lane,+Philadelphia,+PA,+United+States+to:Philadelphia+International+Airport,+Essington+Avenue,+Philadelphia,+PA,+United+States&hl=en&sll=40.283716,-77.036133&sspn=3.582578,6.773071&geocode=FZxxYAIdUcqD-yHY0zdGlBUuPikvg6lgZsTGiTHY0zdGlBUuPg%3BFeBcYQIdzSyF-yGcj_mKAfhviSnVvLzvHsbGiTGcj_mKAfhviQ%3BFS3UYQIdhNSE-yHTwCkDIXYoiyn_kKhF5sXGiTHTwCkDIXYoiw%3BFRVmYwIdt4yH-ykvmB-AjLPGiTH60vEMkAhnrA%3BFZxxYAIdUcqD-yHY0zdGlBUuPikvg6lgZsTGiTHY0zdGlBUuPg%3BFaKWYAIdt8iD-yFsINr-eokAkSmfV6fdfcPGiTFsINr-eokAkQ%3BFS3UYQIdhNSE-yHTwCkDIXYoiyn_kKhF5sXGiTHTwCkDIXYoiw%3BFeeZYQIdsCuF-yEClZG3nPycxilx2ebjKMbGiTEClZG3nPycxg%3BFS3UYQIdhNSE-yHTwCkDIXYoiyn_kKhF5sXGiTHTwCkDIXYoiw%3BFYGdYQIdRN-E-yFe7_1dh5lMoCmBMp8cSMbGiTFe7_1dh5lMoA%3BFSCuYQId9imF-yF-Sw5cubLO2il5juueK8bGiTF-Sw5cubLO2g%3BFS3UYQIdhNSE-yHTwCkDIXYoiyn_kKhF5sXGiTHTwCkDIXYoiw%3BFZxxYAIdUcqD-yHY0zdGlBUuPikvg6lgZsTGiTHY0zdGlBUuPg%3BFWipYQIdwwqF-yH_vQ3XcJYw_Snrjd4cMsbGiTH_vQ3XcJYw_Q%3BFTInYwIdNKKF-yk9j724FbfGiTFK_xFG6xNTDQ%3BFZxxYAIdUcqD-yHY0zdGlBUuPikvg6lgZsTGiTHY0zdGlBUuPg&oq=phil&dirflg=ht&doflg=ptk&mra=ls&t=m&z=12

This URL also works in recent versions of Internet Explorer, so perhaps this limit no longer exists.  The information about the IE limit, linked above, goes back to a source from 2006, so the limit might have been gone for a long time.

Update: after further testing, I discovered that Chrome (!) chokes on this long URL.  So maybe you should worry about it!

Body:
I would not worry about having this many parameters in a query.  There is no restriction on number of parameters, only total length of the URL (as mentioned by others).  Long queries with lots of parameters are commonly used by big-name websites.  For example, it is easy to construct a 15 parameter query in Google Maps.

As long as GET makes sense for your case, and you don't have to worry about the character limit, I would use it.

Interestingly, Google Maps also doesn't worry about breaking the 2000 character limit.  Here is the URL it generated for my tour of places with long names in the Philadelphia area:

<a href="https://local.google.com/maps?saddr=Philadelphia+International+Airport,+Essington+Avenue,+Philadelphia,+PA,+United+States&daddr=Philadelphia+Archery+%26+Gun+Club,+Ellsworth+Street,+Philadelphia,+PA,+United+States+to:Philadelphia+Museum+of+Art,+Benjamin+Franklin+Parkway,+Philadelphia,+PA,+United+States+to:Northeast+Philadelphia,+Philadelphia,+PA,+United+States+to:Philadelphia+International+Airport,+Essington+Avenue,+Philadelphia,+PA,+United+States+to:Philadelphia+Airport+Florist,+MacDade+Boulevard,+Philadelphia,+PA,+United+States+to:Philadelphia+Museum+of+Art,+Benjamin+Franklin+Parkway,+Philadelphia,+PA,+United+States+to:Philadelphia+Family+Court,+South+11th+Street,+Philadelphia,+PA,+United+States+to:Philadelphia+Museum+of+Art,+Benjamin+Franklin+Parkway,+Philadelphia,+PA,+United+States+to:Erawan+Thai+Cuisine,+South+23rd+Street,+Philadelphia,+PA,+United+States+to:Four+Points+by+Sheraton+Philadelphia+City+Center,+Race+Street,+Philadelphia,+PA,+United+States+to:Philadelphia+Museum+of+Art,+Benjamin+Franklin+Parkway,+Philadelphia,+PA,+United+States+to:Philadelphia+International+Airport,+Essington+Avenue,+Philadelphia,+PA,+United+States+to:Philadelphia+Streets+Department,+Arch+Street,+Philadelphia,+PA,+United+States+to:Oak+Lane%2F+East+Oak+Lane,+Philadelphia,+PA,+United+States+to:Philadelphia+International+Airport,+Essington+Avenue,+Philadelphia,+PA,+United+States&hl=en&sll=40.283716,-77.036133&sspn=3.582578,6.773071&geocode=FZxxYAIdUcqD-yHY0zdGlBUuPikvg6lgZsTGiTHY0zdGlBUuPg%3BFeBcYQIdzSyF-yGcj_mKAfhviSnVvLzvHsbGiTGcj_mKAfhviQ%3BFS3UYQIdhNSE-yHTwCkDIXYoiyn_kKhF5sXGiTHTwCkDIXYoiw%3BFRVmYwIdt4yH-ykvmB-AjLPGiTH60vEMkAhnrA%3BFZxxYAIdUcqD-yHY0zdGlBUuPikvg6lgZsTGiTHY0zdGlBUuPg%3BFaKWYAIdt8iD-yFsINr-eokAkSmfV6fdfcPGiTFsINr-eokAkQ%3BFS3UYQIdhNSE-yHTwCkDIXYoiyn_kKhF5sXGiTHTwCkDIXYoiw%3BFeeZYQIdsCuF-yEClZG3nPycxilx2ebjKMbGiTEClZG3nPycxg%3BFS3UYQIdhNSE-yHTwCkDIXYoiyn_kKhF5sXGiTHTwCkDIXYoiw%3BFYGdYQIdRN-E-yFe7_1dh5lMoCmBMp8cSMbGiTFe7_1dh5lMoA%3BFSCuYQId9imF-yF-Sw5cubLO2il5juueK8bGiTF-Sw5cubLO2g%3BFS3UYQIdhNSE-yHTwCkDIXYoiyn_kKhF5sXGiTHTwCkDIXYoiw%3BFZxxYAIdUcqD-yHY0zdGlBUuPikvg6lgZsTGiTHY0zdGlBUuPg%3BFWipYQIdwwqF-yH_vQ3XcJYw_Snrjd4cMsbGiTH_vQ3XcJYw_Q%3BFTInYwIdNKKF-yk9j724FbfGiTFK_xFG6xNTDQ%3BFZxxYAIdUcqD-yHY0zdGlBUuPikvg6lgZsTGiTHY0zdGlBUuPg&oq=phil&dirflg=ht&doflg=ptk&mra=ls&t=m&z=12" rel="nofollow">https://local.google.com/maps?saddr=Philadelphia+International+Airport,+Essington+Avenue,+Philadelphia,+PA,+United+States&daddr=Philadelphia+Archery+%26+Gun+Club,+Ellsworth+Street,+Philadelphia,+PA,+United+States+to:Philadelphia+Museum+of+Art,+Benjamin+Franklin+Parkway,+Philadelphia,+PA,+United+States+to:Northeast+Philadelphia,+Philadelphia,+PA,+United+States+to:Philadelphia+International+Airport,+Essington+Avenue,+Philadelphia,+PA,+United+States+to:Philadelphia+Airport+Florist,+MacDade+Boulevard,+Philadelphia,+PA,+United+States+to:Philadelphia+Museum+of+Art,+Benjamin+Franklin+Parkway,+Philadelphia,+PA,+United+States+to:Philadelphia+Family+Court,+South+11th+Street,+Philadelphia,+PA,+United+States+to:Philadelphia+Museum+of+Art,+Benjamin+Franklin+Parkway,+Philadelphia,+PA,+United+States+to:Erawan+Thai+Cuisine,+South+23rd+Street,+Philadelphia,+PA,+United+States+to:Four+Points+by+Sheraton+Philadelphia+City+Center,+Race+Street,+Philadelphia,+PA,+United+States+to:Philadelphia+Museum+of+Art,+Benjamin+Franklin+Parkway,+Philadelphia,+PA,+United+States+to:Philadelphia+International+Airport,+Essington+Avenue,+Philadelphia,+PA,+United+States+to:Philadelphia+Streets+Department,+Arch+Street,+Philadelphia,+PA,+United+States+to:Oak+Lane%2F+East+Oak+Lane,+Philadelphia,+PA,+United+States+to:Philadelphia+International+Airport,+Essington+Avenue,+Philadelphia,+PA,+United+States&hl=en&sll=40.283716,-77.036133&sspn=3.582578,6.773071&geocode=FZxxYAIdUcqD-yHY0zdGlBUuPikvg6lgZsTGiTHY0zdGlBUuPg%3BFeBcYQIdzSyF-yGcj_mKAfhviSnVvLzvHsbGiTGcj_mKAfhviQ%3BFS3UYQIdhNSE-yHTwCkDIXYoiyn_kKhF5sXGiTHTwCkDIXYoiw%3BFRVmYwIdt4yH-ykvmB-AjLPGiTH60vEMkAhnrA%3BFZxxYAIdUcqD-yHY0zdGlBUuPikvg6lgZsTGiTHY0zdGlBUuPg%3BFaKWYAIdt8iD-yFsINr-eokAkSmfV6fdfcPGiTFsINr-eokAkQ%3BFS3UYQIdhNSE-yHTwCkDIXYoiyn_kKhF5sXGiTHTwCkDIXYoiw%3BFeeZYQIdsCuF-yEClZG3nPycxilx2ebjKMbGiTEClZG3nPycxg%3BFS3UYQIdhNSE-yHTwCkDIXYoiyn_kKhF5sXGiTHTwCkDIXYoiw%3BFYGdYQIdRN-E-yFe7_1dh5lMoCmBMp8cSMbGiTFe7_1dh5lMoA%3BFSCuYQId9imF-yF-Sw5cubLO2il5juueK8bGiTF-Sw5cubLO2g%3BFS3UYQIdhNSE-yHTwCkDIXYoiyn_kKhF5sXGiTHTwCkDIXYoiw%3BFZxxYAIdUcqD-yHY0zdGlBUuPikvg6lgZsTGiTHY0zdGlBUuPg%3BFWipYQIdwwqF-yH_vQ3XcJYw_Snrjd4cMsbGiTH_vQ3XcJYw_Q%3BFTInYwIdNKKF-yk9j724FbfGiTFK_xFG6xNTDQ%3BFZxxYAIdUcqD-yHY0zdGlBUuPikvg6lgZsTGiTHY0zdGlBUuPg&oq=phil&dirflg=ht&doflg=ptk&mra=ls&t=m&z=12

This URL also works in recent versions of Internet Explorer, so perhaps this limit no longer exists.  The information about the IE limit, linked above, goes back to a source from 2006, so the limit might have been gone for a long time.

Update: after further testing, I discovered that Chrome (!) chokes on this long URL.  So maybe you should worry about it!


问:
Is what someone publishes on the Internet fair game when considering them for employment as a programmer?
(Originally posted on Stack Overflow but closed there and more relevant for here)

So we first interviewed a guy for a technical role and he was pretty good. Before the second interview we googled him and found his MySpace page which could, to put it mildly, be regarded as inappropriate.  Just to be clear there was no doubt that it was his page (name, photos, matching biographical information and so on).

The content was entirely personal and in no way related to his professional abilities or attitude.

Is it fair to consider this when thinking about whether to offer them a job?

In most situations my response would be what goes on in someone's private life is their own doing. However for anyone technical who professes (implicitly or explicitly) to understand the Internet and the possibilities it offers, is posting things in a way which can so obviously be discovered a significant error of judgement?

EDIT: Clarification - essentially it was a fairly graphic commentary on porn (but of, shall we say, a non-academic nature).  I'm actually more interested in the general concept than the specific incident as it's something we're likely to see more in the future as people put more and more of themselves on-line.

My concerns are not primarily about him and how he feels about such things (he's white, straight, male and about the last possible victim of discrimination on the planet in that sense), more how it reflects on the company that a very simple search (basically his name) returns these things and that clients may also do it.  We work in a relatively conservative industry.

答:
In a perfect world, only if it relates to programming like SO posts.

For non-programming behaviors, you have to decide if it will impact their job performance. Someone who likes to party is not necessarily a problem, but when they post "I was so ripped I had to call off work for 3 days." you may want to see if they have changed. It is fair to ask a recent college graduate if they are going to be able to make the adjustment to the real world and get their priorities straight.

I'm amazed at some of the responses that seem overly-concerned with others fitting in. If you can't work with other people who are not like you, you and/or your company have a problem. This is beyond the illegal (in some countries) practice of bias towards race/creed, gender, and religion. Don't hire a gun collector for fear they may bring one to the office if they become disgruntled. How silly would it be to not hire a tri-athlete because they may go for a run and show up to work sweaty and smelly in front of clients. You have to know whether or not the candidate can differentiate what is appropriate at work and what isn't.

Being concerned with whether or not an employee can show some discretion is important. Many have mentioned the likely hood of getting caught. Asking someone to wear a disguise when they go to an adult club, is a little creepy.

ContentLicense: CC BY-SA 2.5


问:
UDP order of packets with direct connection
If i have two systems (A and B) running on LAN(INTRANET) which are directly connected. There are no routers in the middle. In this case, if system A sends a few UDP packets every few milliseconds to system B:

Is it possible that system B receives the packets in a different order?

Please note that I'm not asking whether to use TCP or UDP. I'm interested in whether the above scenario will have packets out of order - I'm aware that UDP packets are not guaranteed to arrive in order.

答:
Though order or arrival is not guarranted by the specification, in your context I see no device that could reorder the packets or destroy them (provided that no other network traffic is present).

Just in case, you can build up a test that you run during a couple of hours and that sends packets with an incrementing sequence number in the body and that fails as soon as the sequence number of a received packet does not match the number of packets received so far.

ContentLicense: CC BY-SA 3.0


问:
Querystring Advanced Search where there are about 20 search fields
I am creating an advanced search page where there are about 20 search fields for a user to filter their search. My question deals with the query string, Is it standard web development practice to have say 20 parameters in a querystring?

The search results display large tables of data. Is there an alternative that still uses HTTP GET(querystring), if it is not standard? I would like the users to be able to bookmark their searches.

答:
Standard practice would generally be to allow the parameters to all be in the query string.  However, you find that the browser limit is being exceeded, you do need to figure out an alternative system.

A possible solution would be:

use HTTP POST body to submit the arbitrarily lengthed data

cache these search parameters, and generate a unique ID for it

issue a browser redirect of the form http://[your_query_url]?query_id=[generated_id]

now, just make sure that you [your_query_url] can translate the ID into the query using the cache to seamlessly generate the response

To the user, this will be a seamless search, and they now will have a bookmark-able page.  Depending on other real world requirements that you may have, this could be optimized to some extent to meet your needs, but it is a simple starting point that gets around browser limitations.


答:
Yes it is possible.

This could be hardware and driver dependent, and might be very different depending on what other types of packets are being sent over the line at the same time.

How are internal packet buffers handling the incoming send requests? You can't know. It could be using parallel buffers that fill up in odd ways. Since the spec doesn't have a guarantee, there would be no reason for the implementer to bother keeping things in sync (esp. considering the speed gains with lack of overhead).

A windows box might decide to send a NTP time update request and a network share scan, and then while in the middle of that, dropbox could make a request for local folders. Now any data in buffers are suspect.

You could send millions of packets and not experience this issue. But it is a possibility.  The chances of it happen may be small, but it will happen.

The only real way to guarantee that these aren't going to cause problems is if you are running your own OS and have explicit knowledge on how the hardware performs and have the driver source code and the UDP api's source code.

Title: UDP order of packets with direct connection

Body:
If i have two systems (A and B) running on LAN(INTRANET) which are directly connected. There are no routers in the middle. In this case, if system A sends a few UDP packets every few milliseconds to system B:

Is it possible that system B receives the packets in a different order?

Please note that I'm not asking whether to use TCP or UDP. I'm interested in whether the above scenario will have packets out of order - I'm aware that UDP packets are not guaranteed to arrive in order.


问:
Changing a server centric site to a more JS centric one
First of all, I'm not really a Javascript guy, but more towards PHP.

However, I want to move to the next level, that is taking load off the server and let the client do the processing. Hopefully to be a more JS guy.

My first thought is to request of data off the server, and it just returns key-values which the client will generate the HTML and puck in the values.

There are 3 problems generally:

I find it so much easier to generate the HTML in PHP cause data exchange between the server and HTML is fluid. Unlike returning data in JSON, which I then have to select the DOM that I want, and put in the values eg. $('.personRecord').html(data['name']).

I also find looping through arrays and generating HTML easier than JS?

I find myself using so much of jQuery selector to select the element I'm interested to manipulate and I'm not sure if that's the correct practice (going forward to be a JS ninja). But I'm doing it cause it sure saves lots of characters.

In order to select the elements easily, I tend to give them unique class names as identifier. Again, I'm not sure if that's what a JS Ninja will do.

Going forward (web trend), I would like to know if I should try to put more work to JS?

Also, any ideas or thoughts on how I can overcome my 3 problems stated above?

Is it a sin to return formatted HTML as part of a JSON value? Or should HTML be generated in JS and only read values off the returned JSON when it needs?

Putting frameworks aside (I know there's Backbone, Angular, Can.JS and many more) does anyone really do raw JS scripting? I mean, it is possible but seems extremely wordy.

Lastly, please advice how one would convert a server centric site to a JS centric one?

If what I wrote doesn't make any sense, hopefully you can point some JS centric sites, and explain what approach they are using as an example. Sites that are full featured (say..maybe facebook, twitter, stackoverflow) and not just a TODO web app.

答:
jQuery is a fantastic DOM manipulation tool. What I have found though is that it is helpful to pair it with a good JavaScript templating tool (Knockout.js is one of my favorites because of the declarative data binding-like workflow it uses) precisely to do as little low-level manipulation as is possible. That said, jQuery has fantastic array looping with .each().

The selector is the correct practice for retrieving DOM bits to manipulate. However, I would refer back to #1 for how to avoid doing repetitive manipulations.

CSS classes should be applied to groups or things that may potentially become groups. If you really need to refer to an item directly, use an ID. It is typically preferred to group things with classes and seldom think in terms of manipulating some precise element.

Raw JavaScript (without even jQuery, Prototype JS or MooTools) can be written and can be used to manipulate the DOM. This is seldom done in practice because of the DOM implementation incompatibilities that a good framework will hide for you. If you write raw JavaScript you will quickly find that you are spending a good deal of valuable development time rediscoving oddball JavaScript/DOM incompatibilities.

As for how to perform such a conversion, there are two angles to consider: project management and technological. From the first perspective, you probably do not want to do some wholesale conversion. Rather, convert individual pieces as you fix bugs or augment their functionality.

The question lacks enough detail to provide a good technical answer. Moving towards an MVC-like architecture might be helpful. I have found web services, even very small ones, extremely helpful as they allow me to serve up fairly "dumb" pages (even if they are presented by something less-than-dumb like ASP.NET) and have the JS call off to the service to fill in data and perform operations.

Finally, you may want to step back and ask yourself why you are trying to make this transition. Better performance? Better user experience? What problem does it solve? There may be other solutions to your immediate problem.

Bear in mind that client-side scripting is no panacea. There are trade-offs. You need to be even more careful in your handling of data scrubbing and validation (which you should be doing anyway) and ensure that both your client and server side code can gracefully recover from errors presented by the other.


问:
Am I handling my exceptions in a sensible manner?
I'm still restructuring the code I have been given to update on my current work project, and I've come to the point where I'm looking at how the code handles an 'exceptional' input, that doesn't conform to the business logic.

In essence, the code stitches together various different excel spreadsheets, tarts them up and lets the user 'download' them to their workspace for later analysis.

This is what I have set in the code:

If the code ends up (anywhere) trying to, for instance, import an empty spreadsheet into the final work book (something that should never happen, under the business logic) then write out to a LinkedList variable (ErrorList) in a static class (MyVariables) like so, the error:

```<code>MyVariables.ErrorList.add("My Specific Error Text");
</code>```

Then I throw an exception like so:

```<code>throw new PICNICException();
</code>```

Then in the frame that called the trail of methods, the exception is finally caught and I can write, something like this:

```<code>catch(PICNICException Pe){
    JOption.showMessageDialog(This, MyVariables.ErrorList.getLast(), "Title Relevant to what Code is Doing", JOption.ERROR_DIALOG)
   Pe.printStackTrace();
}
</code>```

I have feel I have to do this as, I have no way to pop up the Message Dialog (which is the desired behaviour on erroring) from within the method that's thrown this exception. Without completely refactoring the entire code base, and making a singleton that can be accessed anywhere to handle these message dialogues, I don't see any other way of doing this.

I can't help but feel this is a gigantic hack, and there is a better method for doing this.

Am I handling my exceptions in the best possible manner, given my situation? What would the best practice be?

答:
Throwing exceptions is not bad, throwing exceptions for a non exceptional situation is considered poor but this sounds like you're throwing the exception for an exceptional reason so I think it's fine.

Things I'd keep in mind though:

Throw a specific exception

Log information before the exception is thrown

Call out in the documentation that this method can throw the exception

Other than that, we shouldn't try to avoid exceptions in all cases - they do come in very useful, we just shouldn't be using them for standard control flow.


问:
Why don't languages use explicit fall-through on switch statements?
I was reading Why do we have to use break in switch?, and it led me to wonder why implicit fall-through is allowed in some languages (such as PHP and JavaScript), while there is no support (AFAIK) for explicit fall-through.

It's not like a new keyword would need to be created, as continue would be perfectly appropriate, and would solve any issues of ambiguity for whether the author meant for a case to fall through.

The currently supported form is:

```<code>switch (s) {
    case 1:
        ...
        break;
    case 2:
        ... //ambiguous, was break forgotten?
    case 3:
        ...
        break;
    default:
        ...
        break;
}
</code>```

Whereas it would make sense for it to be written as:

```<code>switch (s) {
    case 1:
        ...
        break;
    case 2:
        ...
        continue; //unambiguous, the author was explicit
    case 3:
        ...
        break;
    default:
        ...
        break;
}
</code>```

For purposes of this question lets ignore the issue of whether or not fall-throughs are a good coding style.

Are there any languages that exist that allow fall-through and have made it explicit?

Are there any historical reasons that switch allows for implicit fall-through instead of explicit?

答:
Go allows explicit fallthrough using the fallthrough keyword (break is implicit, but may be explicit):

```<code>switch val {
case 1: // breaks
case 2:
    fallthrough
case 3:
    goto
case 4, 5, 6: // equivalent to defining individual cases with explicit fallthough
    break // unnecessary
default:
}
</code>```

Here's the relevant bit from effective go and the language spec.

I don't think you can use goto to go to a specific case, but you can make a label inside the case and use a goto like normal.

As a bonus, Go lets you use binary expressions, strings, or types in a switch as case statements.

Body:
Go allows explicit fallthrough using the fallthrough keyword (break is implicit, but may be explicit):

switch val {
case 1: // breaks
case 2:
    fallthrough
case 3:
    goto
case 4, 5, 6: // equivalent to defining individual cases with explicit fallthough
    break // unnecessary
default:
}

Here's the relevant bit from effective go and the language spec.

I don't think you can use goto to go to a specific case, but you can make a label inside the case and use a goto like normal.

As a bonus, Go lets you use binary expressions, strings, or types in a switch as case statements.


问:
Map of functions vs switch statement
I'm working on a project that processes requests, and there are two components to the request: the command and the parameters. The handler for each command is very simple (< 10 lines, often < 5). There are at least 20 commands, and likely will have more than 50.

I've come up with a couple of solutions:

one big switch/if-else on commands

map of commands to functions

map of commands to static classes/singletons

Each command does a little error checking, and the only bit that can be abstracted out is checking for the number of parameters, which is defined for each command.

What would be the best solution to this problem, and why? I'm also open to any design patterns I may have missed.

I've come up with the following pro/con list for each:

switch

pros

keeps all commands in one function; since they're simple, this makes it a visual lookup table

don't need to clutter up source with tons of small functions/classes that will only get used in one place

cons

very long

hard to add commands programmatically (need to chain using default case)

map commands -> function

pros

small, bite-size chunks

can add/remove commands programmatically

cons

if done in-line, same visually as switch

if not done in-line, lots of functions only used in one place

map commands -> static class/singleton

pros

can use polymorphism to handle simple error checking (only like 3 lines, but still)

similar benefits to map -> function solution

cons

lots of very small classes will clutter project

implementation not all in the same place, so it's not as easy to scan implementations

Extra notes:

I'm writing this in Go, but I don't think the solution is language-specific. I'm looking for a more general solution because I may need to do something very similar in other languages.

A command is a string, but I can easily map this to a number if convenient. The function signature is something like:

```<code>Reply Command(List<String> params)
</code>```

Go has top-level functions, and other platforms I'm considering also have top-level functions, hence the difference between the second and third options.

答:
How do you select your commands / functions?

If there's some "clever" way of selecting the correct function then that's the way to go - means that you can add new support (perhaps in an external library) without modifying the core logic.

Also, testing individual functions is easier in isolation than an enormous switch statement.

Finally, only being used in one place - you might find that once you get to 50 that different bits of different functions can be reused?

Title: Map of functions vs switch statement


问:
Suggested Web Application Framework and Database for Enterprise, “Big-Data” App?
I have a web application that I have been developing for a small group within my company over the past few years, using Pipeline Pilot (plus jQuery and Python scripting) for web development and back-end computation, and Oracle 10g for my RDBMS. Users upload experimental genomic data, which is parsed into a database, and made available for querying, transformation, and reporting.

Experimental data sets are large and have many layers of metadata.  A given experimental data record might have a foreign key relationship with a table that describes this data point's assay. Assays can cover multiple genes, which can have multiple transcript, which can have multiple mutations, which can affect multiple signaling pathways, etc.  Users need to approach this data from any point in those layers in the metadata. Since all data sets for a given data type can run over a billion rows, this results in some large, dynamic queries that are hard to predict.

New data sets are added on a weekly basis (~1GB per set).  Experimental data is never updated, but the associated metadata can be updated weekly for a few records and yearly for most others.  For every data set insert the system sees, there will be between 10 and 100 selects run against it and associated data.  It is okay for updates and inserts to run slow, so long as queries run quick and are as up-to-date as possible.

The application continues to grow in size and scope and is already starting to run slower than I like.  I am worried that we have about outgrown Pipeline Pilot, and perhaps Oracle (as the sole database). Would a NoSQL database or an OLAP system be appropriate here? What web application frameworks work well with systems like this? I'd like the solution to be something scalable, portable and supportable X-years down the road.

Here is the current state of the application:

Web Server/Data Processing: Pipeline Pilot on Windows Server + IIS

Database: Oracle 10g, ~1TB of data, ~180 tables with several billion-plus row tables

Network Storage: Isilon, ~50TB of low-priority raw data

答:
There are two ways to scale - up (bigger/better/faster boxes) and out (more boxes).  Up is good to a point, but no one is making off the shelf petaflop boxes yet.  Out takes more work, but if you have removed the bottlenecks there's no significant limit on how many boxes can be run in parallel.

Based on your comments it sounds like you have some bottlenecks to remove so you're clusterable etc.

As for whether or not you've outgrown Pipeline Pilot, that's a question that the vendor can best answer.


答:
Your use of exceptions seems entirely appropriate here.

The code encounters a situation that should never occur and that it can't reasonably handle locally. That sounds like the kind of situation that exceptions were meant for.

However, I have also some points of critique:

Your exception name does not seem to indicate what kind of problem the code encountered (I would have expected something along the lines of EmptyWorkbookException).  This means that it will later be harder to implement different error handling for different problems (for example, one error requires a 'Critical' messagebox, while another requires a 'Warning' messagebox)

Instead of using the separate variable ErrorList, it is better to either generate the user-visible message at the point where you display it (and thus also know what language to use), or to put it in the exception object itself.
The first option is generally preferred for end-user visible text, so you don't have to bother with localisation all over the place. The second option should be used to carry information in general from the throw site to the catch site.

Title: Am I handling my exceptions in a sensible manner?

Body:
I'm still restructuring the code I have been given to update on my current work project, and I've come to the point where I'm looking at how the code handles an 'exceptional' input, that doesn't conform to the business logic.

In essence, the code stitches together various different excel spreadsheets, tarts them up and lets the user 'download' them to their workspace for later analysis.

This is what I have set in the code:

If the code ends up (anywhere) trying to, for instance, import an empty spreadsheet into the final work book (something that should never happen, under the business logic) then write out to a LinkedList variable (ErrorList) in a static class (MyVariables) like so, the error:

```<code>MyVariables.ErrorList.add("My Specific Error Text");
</code>```

Then I throw an exception like so:

```<code>throw new PICNICException();
</code>```

Then in the frame that called the trail of methods, the exception is finally caught and I can write, something like this:

```<code>catch(PICNICException Pe){
    JOption.showMessageDialog(This, MyVariables.ErrorList.getLast(), "Title Relevant to what Code is Doing", JOption.ERROR_DIALOG)
   Pe.printStackTrace();
}
</code>```

I have feel I have to do this as, I have no way to pop up the Message Dialog (which is the desired behaviour on erroring) from within the method that's thrown this exception. Without completely refactoring the entire code base, and making a singleton that can be accessed anywhere to handle these message dialogues, I don't see any other way of doing this.

I can't help but feel this is a gigantic hack, and there is a better method for doing this.

Am I handling my exceptions in the best possible manner, given my situation? What would the best practice be?


答:
In this case I would remove the ErrorList and include some kind of key long with the exception e.g. :

```<code>throw new PICINCException(ErrorKey.EMPTY_SPREADSHEET);
</code>```

The error key then maps into a set of messages with specific error messages for your GUI.
This has some advantages over the current solution:

All your error messages are in a single place which makes them easy to update.

If you're ever likely to localise the app (it sounds unlikely but you would be surprised) it would be easier to do user specific locales.

With proper naming it should be obvious to anyone reading the code what is going on with reduced exposure ("I see an ErrorKey enum so that must map to the error messages").

It reduces the boiler-plate around adding to the ErrorList then throwing the exception, what happens if I forget to add to the ErrorList then I throw an Exception?

Body:
In this case I would remove the ErrorList and include some kind of key long with the exception e.g. :

throw new PICINCException(ErrorKey.EMPTY_SPREADSHEET);

The error key then maps into a set of messages with specific error messages for your GUI.
This has some advantages over the current solution:

All your error messages are in a single place which makes them easy to update.

If you're ever likely to localise the app (it sounds unlikely but you would be surprised) it would be easier to do user specific locales.

With proper naming it should be obvious to anyone reading the code what is going on with reduced exposure ("I see an ErrorKey enum so that must map to the error messages").

It reduces the boiler-plate around adding to the ErrorList then throwing the exception, what happens if I forget to add to the ErrorList then I throw an Exception?


问:
Idiomatic Javascript code architecture
I am writing a node.js application which I am breaking down into modules, the issue is I am not sure how to organise my code in an idiomatic Javascript way.

Currently each of my modules exposes a set of functions that are intended to be called directly. All state is modified by the module with the gameId being the first parameter :

```<code>//snip
    var gameId = gameModule.createGame();
    // Return the gameId down to a remote client
    client.send(gameId);
}
// When a remote client wants to add a player
    gameModule.addPlayer(gameId, "Player 1");
}
</code>```

An alternative approach would be to actually use objects e.g. :

```<code>//snip
var game = new gameModule.Game();
// Return the gameId down to a remote client
client.send(game.getId());
}
//snip
// When a remote client wants to add a player
var gameToModify = gameModule.getGame(gameId);
gameToModify.addPlayer("Player 1");
gameModule.saveGame(gameToModify);
</code>```

My question is to any Javascript programmers (or regular ones) is which of the two above alternatives looks easiest to work with / most natural?

答:
The problem with the first code is that by hiding the Game object you prevent all direct actions on this object, as each of them involve to use the gameId to look, inside the library, for the object. This will have an impact of performances if you do small actions. And you might be tempted to write too much code to avoid those too small actions.

Without hesitation, in your specific case, the second version is cleaner.

I would, by the way, complete the logic by enabling

```<code>gameToModify.save();
</code>```

Title: Idiomatic Javascript code architecture

Body:
The problem with the first code is that by hiding the Game object you prevent all direct actions on this object, as each of them involve to use the gameId to look, inside the library, for the object. This will have an impact of performances if you do small actions. And you might be tempted to write too much code to avoid those too small actions.

Without hesitation, in your specific case, the second version is cleaner.

I would, by the way, complete the logic by enabling

gameToModify.save();


答:
I've never used go, as a c# programmer I would probably go down the following line, hopefully this architecture will fit what you are doing.

I would create a small class/object for each with the main function to execute, each one should know its string representation. This gives you plugability which it sounds like you want as the number of functions will increase. Note that I wouldn't use statics unless you really need to, they don't give much of an advantage.

I would then have a factory which knows how to discover these classes at run time altering them to be loaded from different assembles etc. this means you don't need them all in the same project.

Thus also makes it more modular for testing and should make code nice and small, which is easier to maintain later.

Title: Map of functions vs switch statement

Body:
I'm working on a project that processes requests, and there are two components to the request: the command and the parameters. The handler for each command is very simple (< 10 lines, often < 5). There are at least 20 commands, and likely will have more than 50.

I've come up with a couple of solutions:

one big switch/if-else on commands

map of commands to functions

map of commands to static classes/singletons

Each command does a little error checking, and the only bit that can be abstracted out is checking for the number of parameters, which is defined for each command.

What would be the best solution to this problem, and why? I'm also open to any design patterns I may have missed.

I've come up with the following pro/con list for each:

switch

pros

keeps all commands in one function; since they're simple, this makes it a visual lookup table

don't need to clutter up source with tons of small functions/classes that will only get used in one place

cons

very long

hard to add commands programmatically (need to chain using default case)

map commands -> function

pros

small, bite-size chunks

can add/remove commands programmatically

cons

if done in-line, same visually as switch

if not done in-line, lots of functions only used in one place

map commands -> static class/singleton

pros

can use polymorphism to handle simple error checking (only like 3 lines, but still)

similar benefits to map -> function solution

cons

lots of very small classes will clutter project

implementation not all in the same place, so it's not as easy to scan implementations

Extra notes:

I'm writing this in Go, but I don't think the solution is language-specific. I'm looking for a more general solution because I may need to do something very similar in other languages.

A command is a string, but I can easily map this to a number if convenient. The function signature is something like:

```<code>Reply Command(List<String> params)
</code>```

Go has top-level functions, and other platforms I'm considering also have top-level functions, hence the difference between the second and third options.


答: Your problem lends very nicely to the Command design pattern. So basically you will have a base Command interface and then there would be multiple CommandImpl classes that would implement that interface. The interface essentially needs to just have a a single method doCommand(Args args). You can have the arguments passed in via an instance of Args class. This way you leverage the power of polymorphism instead of clunky if/else statements. Also this design is easily extensible.

Title: Map of functions vs switch statement


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答:
I worked in a project were the chief architect demand to write (way too) explicit code. One of the worst examples I found in the code (and he happily approved) was the following.

```<code>private string DoSomething( bool verbose )
{
    if ( verbose ) { return someString; }
    else if ( !verbose ) { return otherString; }
    else { return string.Empty; }
}
</code>```

Even ReSharper told you this is wrong!

Body:
I worked in a project were the chief architect demand to write (way too) explicit code. One of the worst examples I found in the code (and he happily approved) was the following.

private string DoSomething( bool verbose )
{
    if ( verbose ) { return someString; }
    else if ( !verbose ) { return otherString; }
    else { return string.Empty; }
}

Even ReSharper told you this is wrong!

OwnerDisplayName: Jax


问:
How to learn/become capable of thinking out of the box?
In every problem solving there's always people who think differently, who come with a 6th option when only 5 were suggested by others, who think "out of the box". Please tell how one can achieve such ability? And what it takes to achieve it?</p>

答:
Be Bold

Are you prepared to suggest outlandish ideas in front of others?

Are you prepared to be wrong?

Know the Box

When you understand what constrains your current thinking you can move beyond it.

Break your Mindset

Change Perspective

Think of someone who has a different perspective and guess what how they see the problem.

Get up and walk around.

Change Language

Think of the problem as:

Pipes with water flowing through them

A series of gates with gatekeepers who demand payment

A battle from StarTrek

Change Representation

Draw a picture

Express the problem in a single sentence

Start at the Other End

Try working backwards from the goal.

Are you solving the right problem?

Change Size

What if you only had to solve the problem for one user?

What if you had to make one 10 times as big?

Do Something. Anything

Try switching if off and then on again.

Make a cup of tea.

Ask Someone Else

Have you tried Googling it?

Ask a 6-year old.


问:
How do I take responsibility for my code when colleague makes unnecessary improvements without notice?
One of my teammates is a jack of all trades in our IT shop and I respect his insight.

However, sometimes he reviews my code (he's second in command to our team leader, so that's expected) without a heads up. So sometimes he reviews my changes before they complete the end goal and makes changes right away... and has even broken my work once.

Other times, he has made unnecessary improvements to some of my code that is 3+ months old.

This annoys me for a few reasons:

I am not always given a chance to fix my mistakes

He has not taken the time to ask me what I was trying to accomplish when he is confused, which could affect his testing or changes

I don't always think his code is readable

Deadlines are not an issue and his current workload doesn't require any work in my projects other than reviewing my code changes.

Anyways, I have told him in the past to please keep me posted if he sees something in my work that he wants to change so that I could take ownership of my code (maybe I should have said "shortcomings") and he's not been responsive.

I fear that I may come off as aggressive when I ask him to explain his changes to me.

He's just a quiet person who keeps to himself, but his actions continue. I don't want to banish him from making code changes (not like I could), because we are a team--but I want to do my part to help our team.

Added clarifications:

We share 1 development branch. I do not wait until all my changes complete a single task because I risk losing some significant work--so I make sure my changes build and do not break anything.

My concern is that my teammate doesn't explain the reason or purpose behind his changes. I don't think he should need my blessing, but if we disagree on an approach I thought it would be best to discuss the pros and cons and make a decision once we both understand what is going on.

I have not discussed this with our team lead yet as I would prefer to resolve personal disagreements without getting management involved unless it is necessary. Since my concern seemed more of personal issue than a threat to our work, I chose to not bother the team lead. I am working on code review process ideas--to help promote the benefits of more organized code reviews without making it all about my pet peeves.

答:
I think most developers find themselves in this position at some point, and I hope that every developer who's felt victimized realizes how frustrating it will be when he or she becomes the senior and feels compelled to clean up code written by juniors.

For me, avoiding conflict in this situation comes down to two things:

Courtesy. Talking to someone about his/her code allows a dev to know that you're interested and you can discuss it as grown up professionals.

Forget about "code ownership" - the team owns the code. Other people wanting to make the changes is a good thing. If a senior dev makes changes that are "unreadable" or worse, then back them out. You don't need to be aggressive, just let an editor know that his/her changes didn't work, and you're more than happy to discuss your reversion.

Remember, team ownership of code is great and it cuts both ways. If you see something that doesn't make sense in someone else's code, then fix it. Being overly possessive and inadequately communicative is a surefire way to a create a poisonous development environment.

OwnerDisplayName: Jesslyn

OwnerDisplayName: Michael


答:
Not that this will solve the whole situation, but you might try adding more comments to your source code.

If code is not complete, it could be marked as such.

If the purpose of a block of code is not self-documenting, then you should document it.

All and all, try to make lemonade instead wasting time sucking on lemons.
As Michael said, in general, teammates aren't out to make you look bad. Try to learn from your mistakes and apply them to future revisions.

If you believe that his changes are having a negative impact, please voice this (diplomatically). If it were me, I would simply ask why specific changes were done and see if you can defend your original changes. Your senior co-workers are human too. It's quite possible that he missed something and/or is unaware of any negative impact he is providing.

Title: How do I take responsibility for my code when colleague makes unnecessary improvements without notice?

Body:
One of my teammates is a jack of all trades in our IT shop and I respect his insight.

However, sometimes he reviews my code (he's second in command to our team leader, so that's expected) without a heads up. So sometimes he reviews my changes before they complete the end goal and makes changes right away... and has even broken my work once.

Other times, he has made unnecessary improvements to some of my code that is 3+ months old.

This annoys me for a few reasons:

I am not always given a chance to fix my mistakes

He has not taken the time to ask me what I was trying to accomplish when he is confused, which could affect his testing or changes

I don't always think his code is readable

Deadlines are not an issue and his current workload doesn't require any work in my projects other than reviewing my code changes.

Anyways, I have told him in the past to please keep me posted if he sees something in my work that he wants to change so that I could take ownership of my code (maybe I should have said "shortcomings") and he's not been responsive.

I fear that I may come off as aggressive when I ask him to explain his changes to me.

He's just a quiet person who keeps to himself, but his actions continue. I don't want to banish him from making code changes (not like I could), because we are a team--but I want to do my part to help our team.

Added clarifications:

We share 1 development branch. I do not wait until all my changes complete a single task because I risk losing some significant work--so I make sure my changes build and do not break anything.

My concern is that my teammate doesn't explain the reason or purpose behind his changes. I don't think he should need my blessing, but if we disagree on an approach I thought it would be best to discuss the pros and cons and make a decision once we both understand what is going on.

I have not discussed this with our team lead yet as I would prefer to resolve personal disagreements without getting management involved unless it is necessary. Since my concern seemed more of personal issue than a threat to our work, I chose to not bother the team lead. I am working on code review process ideas--to help promote the benefits of more organized code reviews without making it all about my pet peeves.


答:
This is a great fit for a map (2nd or 3rd proposed solution).  I've used it dozens of times, and it's simple and effective.  I don't really distinguish between these solutions; the important point is that there is a map with function names as the keys.

The major advantage of the map approach, in my opinion, is that the table is data.  This means that it can be passed around, augmented, or otherwise modified at runtime; it's also easy to code additional functions which interpret the map in new, exciting ways.  This wouldn't be possible with the case/switch solution.

I haven't really experienced the cons that you mention, but I would like to mention an additional drawback:  dispatching is easy if only the string name matters, but if you need to take additional information into account in order to decide which function to execute, it's a lot less clean.

Perhaps I've just never run into a hard enough problem, but I see little value in both the command pattern and encoding the dispatch as a class hierarchy, as others have mentioned.  The core of the problem is mapping requests to functions; a map is simple, obvious, and easy to test.  A class hierarchy requires more code and design, increases the coupling between that code, and may force you to make more decisions upfront that you will later be likely to need to change.  I don't think the command pattern applies at all.

Title: Map of functions vs switch statement


问:
Agile: When to re-factor and when to extend while accruing technical debt?
Consider the following scenario.

You currently have a feature set A you wish to extend to include feature set B. In the near feature there's a high possibility that you wish to extend this even further to include feature set C.

Option 1) Cost to extend A -> B is minimal, but high maintenance
costs.

Option 2) Cost to refactor A and B to make more logical sense is
moderate, but low  maintenance costs.

Extending to include feature set C:

Cost to extend refactored(A & B) -> C is minimal, again low
maintenance costs.

Cost to extend A,B -> C is high, (both to refactor and extend).

Assuming the inclusion of feature set C is beyond the scope of the current sprint, how do you go about choosing an option?

How does this change if the addition of feature set C is several (2 or more) sprints out?

答: The longer you keep the debt the higher the accumulated interest. It's almost always better to pay off now.</p>


问:
Best language or tool for automating tedious manual tasks
We all have tasks that come up from time to time that we think we'd be better off scripting or automating than doing manually.

Obviously some tools or languages are better for this than others - no-one (in their right mind) is doing a one off job of cross referencing a bunch of text lists their PM has just given them in assembler for instance.

What one tool or language would you recommend for the sort of general quick and dirty jobs you get asked to do where time (rather than elegance) is of the essence?

Background: I'm a former programmer, now development manager PM, looking to learn a new language for fun.  If I'm going to learn something for fun I'd like it to be useful and this sort of use case is the most likely to come up.

答:
Perl

Perl is pretty much my definition of quick and dirty.

Perl is infinitely flexible which is a strength and weakness.  It doesn't force structure on you, but it's there if you want it.  It has libraries for everything.  It's been used extensively for 20 years; there's tons of code out there to work with.


问:
Architecting related products for different markets: MEF?
Hopefully, this question is not too open-ended...

I have been tasked with taking a 3 year old application (.NET 4.0, WPF, WCF, EF 4, SQL 2008) that was designed for a very specific market X and "re-purposing" it for a another very specific market Y.

To further complicate things, the company has also mentioned a third market Z, but that may be a year+ down the road. But it’s definitely coming.

The deadline for getting the application Y ready for market is aggressive. It might be negotiable, but just assume it’s a matter of 2-3 months.

I have been working at the company for a while, and I was very intimately involved with the initial creation of application X, and I am still involved with the maintenance.

The new “application” Y is interesting because there is some “overlap” between the features required for X and Y.

For example, let A, B, C, D, and E be features and let ‘ (prime) denote an enhancement to a feature. All of the following scenarios are valid:

```<code>---X---|---Y---  …  ---Z--- (down the road)
   A   |   A
   B   |   B’
   C’  |   C
       |   D
   E   |
</code>```

Some features can be merged from X to Y as-is (A). Some features from X must be enhanced before they can be merged into Y (B). Some features in X will not be in Y at all (E), and Y will contain features that are not in X (D). You get the idea.

Here are my questions:

(1) In the eyes of upper management, they ultimately see 3 different applications - one for each market: X, Y, Z. Moreover, they see 3 different copies of the same feature A that will need to go into each application. As discussed, there may be some enhancements that will make it to select products, but at the core, they are nearly identical.

Sometimes I'm guilty for finding excuses to use the latest programming trends, BUT I think there's a strong business case here for utilizing the Managed Extensibility Framework (MEF). Why have 3 different physical applications (and hence 3 code bases) when it could really be one “next generation” application with plug-able features through something like MEF? There are several benefits that something like MEF could bring to the table.

Does an extensibility solution like MEF seem valid in a case like this?

(2) Given the limited time to get application Y to market...

(a) Should I go with a conservative approach and simply give management what they’re asking for, i.e. make a deep copy of X and modify it for Y? Perhaps there will be time after Y goes to market to develop a more ideal and extensible solution? My past experience with this company has seen demos become fully-fledged products within no time – if you get my drift ;)

It could very well be more difficult to modify X code to make it work for Y rather than it would be to create Y from scratch and import X features.

(b) Leaving X alone for now, should I create Y with MEF in mind. Features from X can easily be imported into Y. If this is done properly, Z should be easy to implement. It will probably be a risky undertaking to go back and address X to fit into this framework since it's so widely used, but it could be done on the side with no specific deadline.

I have to pitch this to upper management. Any advice or thoughts?

答:
Some thoughts:

Upper management very likely doesn't know or care what MEF is.  If asked, they'd likely want to know that it will get them a solution sooner and cheaper than otherwise.  That's a tough promise to keep if you are still learning the framework.

Do you really want to be learning a new framework at the same time you're implementing Y with "an aggressive deadline"?

Regarding Z in a year - what if "definitely coming" turns into "maybe someday?" or "never"?

My recommendation would be to implement your choice (2)(a) - give the folks who sign your paycheck what they ask for.  Copy X into Y and revise.  Naturally, this isn't an ongoing pattern.

Learn MEF on the side with no specific deadline.  That way you're not risking your deadlines and you can afford to make mistakes as you climb the learning curve.

If/when Z becomes a real project, you'll be in a good position to implement it with 'known technology' and probably refactor the other two into a more general solution.


问:
Is there a better way to model a many-to-many relationship on the same table with Entity Framework?

The context

We're building a web application using Entity Framework 5.0. One of the requirements is that it should be possible for the administrators to link related products so that when someone browses to a product we can render a list "You might also like these products:".

Since a product can be linked to many products we need a many-to-many relationship for this.

The table in the database could look something like this:

```<code> _________________________
| LinkedProducts          |
|-------------------------|
| ProductId1 | ProductId2 |
|------------|------------|
|     1      |     2      |
|------------|------------|
|     1      |     3      |
|------------|------------|
|     2      |     4      |
|------------|------------|
</code>```

An additional requirement is that the linking should be bidirectional. This means that with the sample data from the table above, when you browse to product 2, you should get product 1 and 4 in the list. So for a given ProductId, you should be able to get its linked products from column ProductId1 and ProductId2.

What I've come up with

The product entity:

```<code>public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Product> References { get; set; }
    public virtual ICollection<Product> ReferencedBy { get; set; }

    public Product()
    {
        References = new List<Product>();
        ReferencedBy = new List<Product>();
    }
}
</code>```

The product mapping:

```<code>public class ProductMapping : EntityTypeConfiguration<Product>
{
    public ProductMapping()
    {
        HasKey(t => t.ProductId);

        Property(t => t.Name).IsRequired().HasMaxLength(150);

        ToTable("Products");
        Property(t => t.ProductId).HasColumnName("ProductId");
        Property(t => t.Name).HasColumnName("Name");

        HasMany(x => x.References).WithMany(x => x.ReferencedBy).Map(map =>
            {
                map.ToTable("LinkedProducts");
                map.MapLeftKey("ProductId1");
                map.MapRightKey("ProductId2");
            });
    }
}
</code>```

This all works. To display the list of linked products for a certain product, I can just get the union of References and ReferencedBy:

```<code>var product = db.Find(2);
var linkedProducts = product.References.Union(product.ReferencedBy);
</code>```

The problem

As I said, this works, but I don't really like it and I was wondering if there is a better way to deal with a situation like this when working with Entity Framework.

The solution

I liked Ryathal's suggestion to add two records to the database when linking products. So, when linking product 1 to product 2, I now insert two records: { 1, 2 } and { 2, 1 }.

This also allows me to remove the ReferencedBy collection in the Product class so that only one collections remains: References.

To link to products:

```<code>product1.References.Add(product2);
product2.References.Add(product1);
</code>```

To remove the link between products:

```<code>product1.References.Remove(product2);
product2.References.Remove(product1);
</code>```

Here is my new Product class with the mapping:

```<code>public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Product> References { get; set; }

    public Product()
    {
        References = new List<Product>();
    }
}
</code>```

The product mapping:

```<code>public class ProductMapping : EntityTypeConfiguration<Product>
{
    public ProductMapping()
    {
        HasKey(t => t.ProductId);

        Property(t => t.Name).IsRequired().HasMaxLength(150);

        ToTable("Products");
        Property(t => t.ProductId).HasColumnName("ProductId");
        Property(t => t.Name).HasColumnName("Name");

        HasMany(x => x.References).WithMany().Map(map =>
            {
                map.ToTable("LinkedProducts");
                map.MapLeftKey("ProductId1");
                map.MapRightKey("ProductId2");
            });
    }
}
</code>```

答:
I have always felt weird for creating explicit entities for my many-to-many tables. EF tries to associate many-to-many tables with some parent table. However, this usually wasn't "good enough". Either it didn't make sense for properties to appear in the parent entity or my many-to-many tables were entities in their own right.

I was constantly fighting EF, having to removing associations every time I updated my model based on the database. However, I think it was worth it.

This might be a case where you making the ProductaMapping table an explicit entity is good design.


答:
What is it about the process that makes you want to take responsibility for "your code" ?  Do you have the sole responsibility to keep certain features working?  Did the lead say "Michael, I want you to take responsibility for ..." ?  Or is your responsibility implicit, in that the lead and the rest of the team look to you every time certain features are broken?

Either way, if you have the responsibility, then you need authority over the code.  The next time the other fellow makes unilateral changes and the lead comes back to you to fix them, you should sit down with the lead and ask to have your authority and responsibility aligned.


问:
How to time the sprints in Scrum to allocate time for TDD?
We have sprints of 4 weeks duration. What I have been doing is 3 weeks dev time and 1 week of pure manual/automated testing, stabilization and shipment assurance testing.

How to manage TDD within dev time? In my previous experience writing tests and getting 80% coverage requires round about 50% of the development time. Following the same we would get only 1 and a half week of development which is not enough.

My actual problem is how to allocate time for TDD? I want to make TDD a mandatory but with these it becomes really difficult for me. Do you think this is correct approach we are using or are we missing something and alter our approach to Scrum?

答:
The idea behind TDD is that, while it consumes time itself, it reduces time required in other areas. You should be writing your code faster, and not spending as much time on bug-fixing and manual testing, so you can reduce these aspects accordingly.

Therefore, your statement (emphasis mine):

Following the same we would get only [x time for] development which is not enough.

is not necessarily true.

Whether this is what you acheive in practice is up to you to determine, but that's the theory :)

OwnerDisplayName: Haris

OwnerDisplayName: RB.


答:
The idea behind TDD is that creating the tests is part of the development. You shouldn't really calculate it as development + unit test, the better way to view it is development = functionality + unit tests, where creating the unit tests is not a separate activity. While your developers are working on the functionality, they are also creating the unit tests.

Likewise your task board shouldn't have a separate task for "Create Unit Tests" - the unit tests should be implemented alongside the functionality, there really shouldn't be any separation.

It shouldn't be like 1.5 weeks of development and then 1.5 weeks of unit tests. Instead, you want to have 3 weeks of development and end up with the functionality in a fully tested state. If your Definition of Done specifies that every piece of functionality is unit tested, then there really shouldn't be any separation between getting the functionality implemented and the unit tests done.

As for your other question regarding the integration of QA: We have QA resources as part of the team, testing each feature as it becomes available, with a daily (or nightly) full regression test. If a feature's implementation is done on day 3 of the Sprint, our QA will start testing it on this day - ideally they have developed the test scripts at the same time as the developer implemented the feature.

Both need to work hand in hand and with a lot of collaboration. There's lots of communication between the developers and QA in the team. "Hey, feature A is now ready, you can start testing it." and "I found the following issue in my test for feature B, can you please fix this?" We have this back and forth all the time during the Sprint, with the goal that everything is tested and working at the end.

Combine that with a full regression test run every night, where the results are published, and you can pretty much develop up to the last day of the Sprint. Testing should happen at all stages of the Sprint, not just the last couple of days.

Title: How to time the sprints in Scrum to allocate time for TDD?

Body:
We have sprints of 4 weeks duration. What I have been doing is 3 weeks dev time and 1 week of pure manual/automated testing, stabilization and shipment assurance testing.

How to manage TDD within dev time? In my previous experience writing tests and getting 80% coverage requires round about 50% of the development time. Following the same we would get only 1 and a half week of development which is not enough.

My actual problem is how to allocate time for TDD? I want to make TDD a mandatory but with these it becomes really difficult for me. Do you think this is correct approach we are using or are we missing something and alter our approach to Scrum?

OwnerDisplayName: nwinkler


答:
If you are just beginning working in Scrum, 4 weeks is quite a long duration for your sprints.  Shorter sprints allow you to fail early and often (not a bad thing) and so by inspection and adapting you can improve your processes a lot quicker.  It also allows you to be more reactive to change.

In my previous experience writing tests and getting 80% coverage requires round about 50% of the development time

In TDD, development time IS development + unit testing time.  You're not getting 2 weeks development + 1 weeks testing, you're getting 3 weeks high quality development.  Since such a large percentage of the cost of developing software is maintenance, quality should be of high importance and should be built into both your definition of done, and acceptance criteria for stories.

1 week of pure manual/automated testing, stabilization and shipment assurance testing

nwinkler answered this well above, so I won't re-iterate what he's said.  What you're doing is essentially mini-waterfall in every sprint!  Create stabilization / shipment assurance tasks (or whatever) in your sprint backlog for each story you're testing if necessary.  Obviously, if you have tester roles in your organisation, they should be on your scrum team if they are not already

OwnerDisplayName: tohalloran


答:
The GUI guys in my organization like TestComplete for automation in Windows.

For CLI scripting, about 90% Perl and 10% Bash

I've been working on rolling together some Common  Lisp routines to help with scripting, but it's not as easily native to that task as Perl.

Title: Best language or tool for automating tedious manual tasks

Body:
We all have tasks that come up from time to time that we think we'd be better off scripting or automating than doing manually.

Obviously some tools or languages are better for this than others - no-one (in their right mind) is doing a one off job of cross referencing a bunch of text lists their PM has just given them in assembler for instance.

What one tool or language would you recommend for the sort of general quick and dirty jobs you get asked to do where time (rather than elegance) is of the essence?

Background: I'm a former programmer, now development manager PM, looking to learn a new language for fun.  If I'm going to learn something for fun I'd like it to be useful and this sort of use case is the most likely to come up.


问:
Why would one bother marking up properly and semantically?

Note that I (try) to mark up as semantically as possible because I like they way it looks and feels, but not because I'm aware of any other stunning advantages. The point of my question is to be able to educate others

Well, I've seen a lot of articles and tutorials which often state "Let's mark this up in the most semantic possible way".

But a strange thought came to me, why?

Why would one need (or want) to bother with the specific elements which convey the correct semantic meaning? Specifically, I'm referring to the new HTML5 elements, such as <time>, <output>, or <address>. Especially, if the page "works" (it renders nicely in all browsers).

Why would I want to use elements like <time> or <address>, where nothing at all (or at the worst case, a generic ) works just as nicely?

I'm asking this because I'm seeing a multitude of (very popular) websites (this one included) which does not follow these so-called best practices.

答:
I run a small web consulting company, and our current approach is to not use the new HTML5 tags because we're trying to balance many factors. In this case, the balance is between usability, usability, and SEO:

SEO: What other answers here said - it might help a little bit for SEO, although based on my experience the more obvious an SEO strategy is, the less likely it is to help.

Usability #1: It's reasonable to assume that HTML5 tags confer some sort of usability advantage. For blind users it's certain that whatever fallback their accessible browser provides them is going to be better than anything I'm going to be able to provide. For your typical user it's a lot more debatable. Maybe using an unskinned media player your browser provides is easier for you to use than the less familiar widget I'd otherwise put in there. Or maybe your browser's default is crap (like the way Chrome Windows's default MP3 player just stops working periodically).

Usability #2: Old IE. Old IE requires a bunch of HTML5 shims that bloat the page in order for any of these tags to work. You have to add some script to the head tags that calls CreateElement() in a loop across all the HTML5 tags you're using. If you're not going to go around combing each page for the tags you have in use, that means every HTML5 tag.  This needs to run on every single page, inline, meaning no caching. And bad news: old IE is the slowest to execute Javascript, so it creates a nice little lurch while it loads. Then you've got to barrel in a bunch of old IE-only Javascript and CSS, and often Flash, to make all the newer unsupported elements render correctly. You can feature detect before deciding to load the old IE code, but then you're making old IE users wait until enough scripts have loaded to do that feature detect before even starting to request all the stuff that makes those tags work. You could browser detect and only send the old IE stuff to users with those browsers, but that can make caching tough or impossible depending on your platform. Delivering different code to different users also means testing is more complicated - ever have an asynchrony bug? How about one that only occurs on a specific browser? And only in production? Sign me up. So, you're probably just going to send that bloat to everyone.

Until IE8 dies, the value in these newer HTML5 tags just isn't high enough for the performance problems they bring. We're yet to work with an audience where it's even close to dead*, but someday.

*Our most recent metrics show IE8 at 6% for the site with the fewest IE8 visitors, and 24% with the most IE8 visitors. Far, far from dead.


问:
Are there any problems with implementing custom HTTP methods?
We have a URL in the following format

/instance/{instanceType}/{instanceId}

You can call it with the standard HTTP methods: POST, GET, DELETE, PUT. However, there are a few more actions that we take on it such as "Save as draft" or "Curate"

We thought we could just use custom HTTP methods like: DRAFT, VALIDATE, CURATE

I think this is acceptable since the standards say

"The set of common methods for HTTP/1.1 is defined below. Although this set can be expanded, additional methods cannot be assumed to share the same semantics for separately extended clients and servers."

And tools like WebDav create some of their own extensions.

Are there problems someone has run into with custom methods? I'm thinking of proxy servers and firewalls but any other areas of concern are welcome. Should I stay on the safe side and just have a URL parameter like action=validate|curate|draft?

答:
One of the fundamental constraints of HTTP and the central design feature of REST is a uniform interface provided by (among other things) a small, fixed set of methods that apply universally to all resources. The uniform interface constraint has a number of upsides and downsides. I'm quoting from Fielding liberally here.

A uniform interface:

is simpler.

decouples implementations from the services that they provide.

allows a layered architecture, including things like HTTP load balancers (nginx) and caches (varnish).

On the other hand, a uniform interface:

degrades efficiency, because information is transferred in a standardized form rather than one which is specific to an application's needs.

The tradeoffs are "designed for the common case of the Web" and have allowed a large ecosystem to be built which provides solutions to many of the common problems in web architectures. Adhering to a uniform interface will allow your system to benefit from this ecosystem while breaking it will make it that difficult. You might want to use a load balancer like nginx but now you can only use a load balancer that understands DRAFT and CURATE. You might want to use an HTTP cache layer like Varnish but now you can only use an HTTP cache layer that understands DRAFT and CURATE. You might want to ask someone for help troubleshooting a server failure but no one else knows the semantics for a CURATE request. It may be difficult to change your preferred client or server libraries to understand and correctly implement the new methods. And so on.

The correct* way to represent this is as a state transformation on the resource (or related resources). You don't DRAFT a post, you transform its draft state to true or you create a draft resource that contains the changes and links to previous draft versions. You don't CURATE a post, you transform its curated state to true or create a curation resource that links the post with the user that curated it.

* Correct in that it most closely follows the REST architectural principles.


答:
Everyone implicitely 'owns their own code', regardless of the politics, legalistics, or economics - it's the 'nature of things' - you naturally feel a personal connection to your own work.

If your co-worker is engaging in the behavior that you described and remains unresponsive when you ask for a heads up, that co-worker is discourteous, to say the least, and may be trying to undermine you (to say the worst...) - does NOT sound like a team player.

A good co-worker would touch base with you and point out the problem with your code to you - and let you fix/change it, or respond appropriately. I am very grateful that even when I was a newbee, my mentors always pointed out to me what I was doing wrong, explained why and let (or made) me fix it. That made me a better programmer and everyone benefited. And that's what I have always done when reviewing work done by others. Then you, (or whoever) actually learns something from your 'jack of all trades', and the code and the team all get better, including your teacher: Teaching helps understanding.

If it's at all possible, I would discuss the matter in private with the Team Leader. Based on your description of the situation, a good team leader will take your side - a bad one won't.... Obviously this requires caution - you will have to judge that for yourself.


答:
You and most of the answerers approach this as a communication issue between two colleagues, but I don't really think it is. What you describe sounds more like a horribly broken code review process than anything else.

First, you mention that your colleague is second in command and it's expected that he'll review your code. That's just wrong. By definition, peer code reviews are not hierarchical, and they are certainly not just about finding defects. They can also provide learning experiences (for everyone involved), an opportunity for social interaction, and prove a valuable tool for building collective code ownership. You should also review his code from time to time, learn from him and correct him when he's wrong (no one gets it right every time).

Furthermore, you mention that your colleague makes changes right away. That's also wrong, but of course you already know it; you wouldn't have asked this question if his gung ho approach wasn't a problem. However I think you are looking for a solution in the wrong place. To be perfectly honest, your colleague reminds me a bit of... me, and what worked for me in similar situations was a well-defined and solid review process and a set of awesome tools. You don't really want to stop your colleague from reviewing your code, and asking him to stop and talk to you before every little change is not really going to work. It might, for a while, but he'll soon reach a point where it will just get too annoying and you'll be back where you started, or worse: he'll just stop reviewing your code.

A key to a resolution here might be a peer code review tool. I usually avoid product recommendations, but for code reviews Atlassian's Crucible is really a life saver. What it does may seem very simple, and it is, but that doesn't mean it's not amazingly awesome. It hooks up to your repository and gives you the opportunity to review individual changesets, files or group of files. You don't get to change any code, instead you comment on everything that doesn't feel quite right. And if you absolutely must change someone else's code, you can simply leave a comment with the changeset explaining your changes. The introductory video at Crucible's product page is worth watching if you want more details. Crucible's pricing is not for everyone, but there are numerous freely available peer review tools. One I've worked with and enjoyed is Review Board and I'm sure you'll find a lot of others with a simple Google search.

Whatever tool you choose, it will completely change your process. No need to stop, get off your chair, interrupt the other person and discuss the changes; all you need to do is set some time off every week and go through the comments (once a week is just a suggestion. You know your schedule and daily routine better than I do). More importantly the core reviews are stored in a database somewhere and you can retrieve them at any time. They aren't ephemeral discussions around the water cooler. My favourite use case for old reviews is when introducing a new team member to our codebase. It's always nice when I can walk someone new through the codebase pointing out where exactly we were stuck, where we had differing opinions, etc.

Moving on, you mention that you don't always find this colleague's code readable. That lets me know that you don't have a common set of coding standards, and that's a bad thing. Again you may approach this as a people problem or you can approach this as a process problem, and again I would strongly suggest the latter. Get your team together and adopt a common coding style and set of standards as soon as possible. It doesn't really matter if you chose a set of standards that's common in your development ecosystem or you come up with your own. What really matters is for your standards to be consistent and that you stick to them. Lots and lots of tools out there can help you, but that's a whole different discussion. Just to get you started, a very simple thing to do is having a pre-commit hook run some kind of style formatter on your code. You can continue writing your code however you like and let the tool "fix it" automagically before anyone else sees it.

Lastly you mention in a comment that management does not believe individual dev branches are necessary. Well, there's a reason we call them "dev branches" and not "management branches." I'll stop here as there's no reason for the rant that's forming in my head to get out.

All that said, know that I don't doubt your colleague is (a bit) at fault here. That's not my point, my point is that your whole development process is also at fault, and that's something that's easier to fix. Arm yourself with the proper tools, explore the numerous formal and informal processes and pick those that fit your team. Soon you'll reach a point where you'll realize that most of your "people problems" don't exist anymore. And please don't listen to anyone (including yourself) that brings forth the "we're a small team, we don't need all that" excuse. A team of competent developers can set up the necessary tools in less than a week, automate everything that can be automated, and never look back again.

PS. "Code ownership" is a nebulous term, constantly debated, and it means different things to different people. You can find a brilliant collection of most of the differing (and sometimes antithetical) opinions on C2.


问:
What's the best practice for naming uploaded images?
Suppose I have a form in my web application where users can upload a profile picture.

I've got few requirements about file size, dimensions etc, but when the user uploads the image, how should I name them on my system? I suppose it would need to be consistent and also unique.

Maybe a GUID?

```<code>a5c627bedc3c44b7ae7c06a44fb3fcf8.jpg
</code>```

A timestamp?

```<code>129899740140465735.jpg
</code>```

A hash? Ex: md5

```<code>b1a9acaf295cf14ffbc5b6538294562c.jpg
</code>```

Is there a standard or recommended way to do this?

答:
You don't want to stress applications (such as Explorer) and make it crash when you open the directory. Whilst it is unlikely you are going to stress the actual file system, you need to take this into account if you're going to be storing thousands of files.

If you're expecting to store thousands of files my suggestion is to partition into folders. For example upload\silo001, upload\silo002, etc. You can either balance your files or wait until a folder hits a certain number of files and then create another.

With regards to naming, I always name a file with a GUID because it is globally unique. I do pull the extension from the upload and set the extension of the file to match, but the actual name is set from a new Guid.

If you're doing this in conjunction with a RDBMS and have several categories, i.e. products, categories, etc you could have upload\products, upload\categories, and so on, and you could use the row ID as the filename.

In terms of best practices, I too have looked in the past and not found anything. I came up with the above while discussing with some of my developers.


答:
Using MEF does not magically turn your application into a collection of composable components.

The code first has to be structured to have sufficiently loose coupling between the different parts, which probably requires quite a bit of refactoring. Sometimes it's almost a rewrite if you didn't care for loose coupling before.

Once your codebase is structured to support composing features, the technology you use for composing does not have that much impact. It's only there to create objects and wire them up to each other. MEF isn't necessarily the only choice for composing "components". A dependency injection container like Autofac also does that (with better features for composition of "components" within a single codebase, but no dynamic loading of plugins).

So i'd suggest to learn about the requirements for composability on your codebase first (i think Dependency Injection in .NET is a good book on that - it also covers MEF), pay special attention to them while creating new features and slowly refactor exisiting features. Once you can compose the most important parts you can pick a technology for doing so.

Title: Architecting related products for different markets: MEF?

Body:
Hopefully, this question is not too open-ended...

I have been tasked with taking a 3 year old application (.NET 4.0, WPF, WCF, EF 4, SQL 2008) that was designed for a very specific market X and "re-purposing" it for a another very specific market Y.

To further complicate things, the company has also mentioned a third market Z, but that may be a year+ down the road. But it’s definitely coming.

The deadline for getting the application Y ready for market is aggressive. It might be negotiable, but just assume it’s a matter of 2-3 months.

I have been working at the company for a while, and I was very intimately involved with the initial creation of application X, and I am still involved with the maintenance.

The new “application” Y is interesting because there is some “overlap” between the features required for X and Y.

For example, let A, B, C, D, and E be features and let ‘ (prime) denote an enhancement to a feature. All of the following scenarios are valid:

```<code>---X---|---Y---  …  ---Z--- (down the road)
   A   |   A
   B   |   B’
   C’  |   C
       |   D
   E   |
</code>```

Some features can be merged from X to Y as-is (A). Some features from X must be enhanced before they can be merged into Y (B). Some features in X will not be in Y at all (E), and Y will contain features that are not in X (D). You get the idea.

Here are my questions:

(1) In the eyes of upper management, they ultimately see 3 different applications - one for each market: X, Y, Z. Moreover, they see 3 different copies of the same feature A that will need to go into each application. As discussed, there may be some enhancements that will make it to select products, but at the core, they are nearly identical.

Sometimes I'm guilty for finding excuses to use the latest programming trends, BUT I think there's a strong business case here for utilizing the Managed Extensibility Framework (MEF). Why have 3 different physical applications (and hence 3 code bases) when it could really be one “next generation” application with plug-able features through something like MEF? There are several benefits that something like MEF could bring to the table.

Does an extensibility solution like MEF seem valid in a case like this?

(2) Given the limited time to get application Y to market...

(a) Should I go with a conservative approach and simply give management what they’re asking for, i.e. make a deep copy of X and modify it for Y? Perhaps there will be time after Y goes to market to develop a more ideal and extensible solution? My past experience with this company has seen demos become fully-fledged products within no time – if you get my drift ;)

It could very well be more difficult to modify X code to make it work for Y rather than it would be to create Y from scratch and import X features.

(b) Leaving X alone for now, should I create Y with MEF in mind. Features from X can easily be imported into Y. If this is done properly, Z should be easy to implement. It will probably be a risky undertaking to go back and address X to fit into this framework since it's so widely used, but it could be done on the side with no specific deadline.

I have to pitch this to upper management. Any advice or thoughts?


答:
You should try to meet two goals: Uniqueness, and usefulness.

Using a GUID guarantees uniqueness, but one day the files may become detached from their original source, and then you will be in trouble.

My typical solution is to embed crucial information into the filename, such as the userID (if it belongs to a user) or the date and time uploaded (if this is significant), or the filename used when uploading it.

This may really save your skin one day, when the information embedded in the filename allows you to, for example, recover from a bug, or the accidental deletion of records. If all you have is GUIDs, and you lose the catalogue, you will have a heck of a job cleaning that up.

For example, if a file "My Holiday: Florida 23.jpg" is uploaded, by userID 98765, on 2013/04/04 at 12:51:23 I would name it something like this, adding a random string ad8a7dsf9:

20130404125123-ad8a7dsf9-98765-my-holiday-florida-23.jpg

Uniqueness is ensured by the date and time, and random string (provided it is properly random from /dev/urandom or CryptGenRandom.

If the file is ever detached, you can identify the user, the date and time, and the title.

Everything is folded to lower case and anything non-alphanumeric is removed and replaced by dashes, which makes the filename easy to handle using simple tools (e.g. no spaces which can confuse badly written scripts, no colons or other characters which are forbidden on some filesystems, and so on).

Title: What's the best practice for naming uploaded images?

Body:
Suppose I have a form in my web application where users can upload a profile picture.

I've got few requirements about file size, dimensions etc, but when the user uploads the image, how should I name them on my system? I suppose it would need to be consistent and also unique.

Maybe a GUID?

```<code>a5c627bedc3c44b7ae7c06a44fb3fcf8.jpg
</code>```

A timestamp?

```<code>129899740140465735.jpg
</code>```

A hash? Ex: md5

```<code>b1a9acaf295cf14ffbc5b6538294562c.jpg
</code>```

Is there a standard or recommended way to do this?


问:
What are the licencing requirements for publishing and distributing an ASP.net application
I  started developing websites using PHP. I have read many times that PHP is free and open source which is an advantage over ASP.net.

However, due to my current job requirements, I had to switch to ASP.net which is pretty good. Now after developing few applications, I am wondering how can I publish them for free. As PHP is free and opensource, it was never an issue for me.

What's bothering me is this.

Suppose I developed a web application using Visual Studio Express (or Professional version or any other version)

Do I need any special permission/license from Microsoft to host my application on Internet

If I create a desktop application and want to distribute it for free on internet, is any license required.

If no, then what are microsoft licenses all about and how is PHP free and ASP is not free

Thanks!

答:
You are not authorized to distribute (as well as sell, decompile, etc.) Visual Studio itself. This doesn't apply to applications you create with Visual Studio. Those can be licensed under very permissive licenses, like Microsoft Public License (MS-PL), BSD, etc.

The same is true for ASP.NET (note that .NET Framework source code is available from Microsoft publicly, but is copyrighted).

ASP.NET MVC is licensed under Apache License 2.0, so it's a different stuff.

If no, then what are microsoft licenses all about and how is PHP free and ASP is not free

Politics.

If you want a more serious answer:

PHP is said free because you can easily setup a free LAMP stack without paying anything to anyone,

ASP.NET (because you're talking about ASP.NET, not ASP, are you?) reasonably requires Windows, which is a copyrighted, closed-source application. Proponents of Microsoft would say that Mono exists, but there are no well-known cases of easy industrial-scale deployment of web applications with Mono on Linux.

Free, here, is not about licenses, but about how much do you pay for software in order to deploy a web application to a server. This doesn't take in account neither the cost of hardware, nor the salary of a DBA.


问:
Logging to database: Log first or action first?
Long story short, I'm working on a web-based frontend that interacts with a database, and one of the functions is that every action on a particular table gets logged to keep a full history of all changes to that table.

An earlier attempt at using triggers in postgreSQL to handle the logging automatically ran afoul of a couple of other requirements of software that will use said database as a backend, so I'm back to manually creating the log entries and saving them.

My question is, what's best practice? Creating and storing the log first, then making the change, or making the change first, then storing the log? I realize that it's essentially a moot point because I'm wrapping the entire process into a transaction anyway, but I'm suddenly wondering if there are arguments in favor of either methods.

答: Begin a transaction, make your changes, log the changes, then commit the transaction. If the changes fail, you are not logging them, and if the logging fails, you should probably roll back the transaction (depending on how important logging is in your system).</p>


答:
I'd recommend to use just md5 or anything conceptually equivalent.
By renaming files by digest of it contents you are not only granting uniqueness (always cache images for as long as possible, and with content-based renaming, well, with proper one, you can cache images practically forever).

Also, not a big deal, but nevertheless it is not a pure hypothetical case when different users upload exactly same image. Just out of the box you'll have a small data storage optimization.

As for anything else proposed: as for me, I am a strong opponent of keeping any kind of auxiliary information in a file name. When I was much younger (and a bit slimmer :), I've been a Perl developer and had a dubious habit to store as much of auxiliary info in file name as common sense allowed me, since Perl string pattern features are awesome. And I've came up to conclusion that, talking of web development, it is always better choice to keep data associated with file separately from the file name.

Keep in mind that nowadays, when mobile interfaces are dominating, actual file name is a less important thing that it was 5, 10 years ago. But even if this will be crucial in context of your application, you can always involve some old school magic with with involving Content-Disposition: attachment; filename="pretty_file_name.jpg" HTTP header, constructing any relevant file name you wish. Also, modern browsers are paving way to new HTML5 attribute, download. I don't believe that actually seeing "human readable" image name is a thing you should think about in majority of cases.

UPD: A modification can be made in order not to have too many files in one directory - just take first 3 letter and create dir.


答:
A log is traditionally something that records what has already happened (think ships' log), so "act first log after" is the norm.

Although it makes little difference in your scenario (as you're using transactions) that best practice is to do things the way that most developers would expect unless you have good reason not to (principle of least surprise).

Title: Logging to database: Log first or action first?

Body:
Long story short, I'm working on a web-based frontend that interacts with a database, and one of the functions is that every action on a particular table gets logged to keep a full history of all changes to that table.

An earlier attempt at using triggers in postgreSQL to handle the logging automatically ran afoul of a couple of other requirements of software that will use said database as a backend, so I'm back to manually creating the log entries and saving them.

My question is, what's best practice? Creating and storing the log first, then making the change, or making the change first, then storing the log? I realize that it's essentially a moot point because I'm wrapping the entire process into a transaction anyway, but I'm suddenly wondering if there are arguments in favor of either methods.


问:
Why do books say, "the compiler allocates space for variables in memory"?
Why do books say,  "the compiler allocates space  for variables in memory". Isn't it the executable which does that? I mean, for example, if I write the following program,

```<code>#include <iostream>
using namespace std;

int main()
{
   int foo;
   return 0;
}
</code>```

and compile it, and get an executable (let it be program.exe), now, if I run program.exe, this executable file will itself command to allocate some space for the variable foo. Won't  it ? Please explain why books keep on saying, "the compiler will do this...do that".

答:
You are right that the compiler as such is gone when your program actually runs. And if it runs on a different machine, the compiler isn't even available anymore.

I guess this is to make a clear distinction between memory actually allocated by your own code. The compiler will insert some code in your program that does the memory allocation (like using new, malloc or similar commands).

So books use "the compiler does this or that" often to say the compiler added some code that is not explicitly mentioned in your code files. True enough that this isn't exactly what's going on. From this point of view a lot of things mentioned in tutorials would be wrong but would need rather elaborate explanations.