答:
As someone already mentioned in the comments you could use a simple message queue.  When a message is sent all you do is add it to the queue.  You then have an asynchronously running "Listener" or "Consumer" which simply processes every message retrieved from the queue one at a time.  Even though the server is multi-threaded the Listener/Consumer can be single threaded (though you have the option of using multiple when order is not important).

Edit: As pointed out by one of the comments below this will only work if processing prior to adding to the queue is instantaneous.  The idea behind the separation is also to move all your logic and processing to the Listener/Consumer and not keep it in the multi-threaded portion of your code.

Title: How to preserve order of incoming requests on a multithreaded server

Body:
I want to write a multithreaded server application which is able to process requests in a multithreaded fashion while keeping up execution order of incoming requests of the same client.

For example if client A sends a message M1 and then a message M2 the muiltithreaded server must process these requests in exactly the same order, first M1 and then M2. However, there is no guarantee that threads that process these incoming requests do process these messages in the same order.

For example, thread T1 consumes message M1, thread T2 consumes message M2 and completes processing the message and is able to accept further messages before T1 has finished it's job.

After a message has been processed the result will be passed to some other process for further processing (of which only one exists in the whole computation), this process will schedule sending a response to the client.

These mutliple threads do only exist for the purpose of preprocessing data for some other process. This particular problem sounds like a problem with pipeline characteristics, first M1, then M2, then M3, etc. However, I wanted to parallalize as much as possible to achieve a higher number of communication cycles between the server and the clients.

What architecture / pattern / technique is well suited for such a task?


问:
How should we draw the release burndown chart?
I have been in various Agile projects and seen many release burndown chart styles. Most of them were handled manually since somehow all the tools that I have run across don't produce really useful burndown charts.

In reality, we may not be dealing with all stories estimated and we just keep burning down. Many times, the scope is added during the release.

Currently, I am dealing with these problems with the burndown chart and have questions about the following things:

How do we represent added scope in the release burndown chart?

How do we deal with unestimated stories in release burndown chart
assuming that there is high probability that we will do it but we
just do not have time to estimate them yet?

How do you project the end of the release?

The burndown chart below is from the fictional case study in the appendix of classic Mike Cohn's Estimating and Planing book.

答:
I have been in various Agile projects and seen many release burndown
  chart styles. Most of them were handled manually since somehow all the tools that I have run across don't produce really useful burndown charts.

A number of tracking systems do produce reasonable burndown charts.  Redmine for example has a plugin that will present various charts. Similarly Jira has a burndown chart, too.

In reality, we may not be dealing with all stories estimated and we
  just keep burning down. Many times, the scope is added during the
  release.

The key here is to separate the "all stories" from the "target release".  Not all the stories are in scope for a given release.

Looking at Redmine's roadmap for itself one can see a distinction between things worked on for the next release and things candidate for a future release.

Currently, I am dealing with these problems with the burndown chart
  and have questions about the following things:

How do we represent added scope in the release burndown chart?

How do we deal with unestimated stories in release burndown chart assuming that there are high probability that we will do it but we
  just do not have time to estimate them yet?

How do you project the end of the release?

Part of the burndown chart is the visibility of velocity of the project.  Having a jagged peak approach to the burndown chart means that the added scope messes up the velocity when examined as a straight line on the chart (and to an extent, may also confuse the projected target).

Instead, consider dropping the floor for increased scope and raising the floor for reduced scope.  An example of this can be seen in

Where the drop in the blue line shows an increase of scope.

For unestimated stories, there are two options - either do an estimate and refine it later (this is a valid and appropriate estimation technique known as the cone of uncertainty)

( From http://www.construx.com/Page.aspx?cid=1648 )

Or estimate them at 0 initially and regard them as increases in scope.

The end of the release is when the remaining work intercepts the scope.

A chart that I like is known as the Earned Value Chart.  Its an "up" style chart rather than a "down" style.  The numbers are percents so that both the cost (the total hours used / total hours allocated) and the scope (as a percent of estimates done to total initial estimates) are on the same scale.

(from http://www.agilekiwi.com/earnedvalue/agile-charts/ )

In this example it can be seen that the hours used so far are more than originally budgeted and that the amount done so far is less than the ideal.  This project is in trouble.

In this model scope increases are shown as recalculations of the percents.

(From http://www.agilekiwi.com/earnedvalue/charting-change/ )

The release can be extrapolated out from the percent complete.

(Also from http://www.agilekiwi.com/earnedvalue/agile-charts/ )

The realm of understanding this chart is known as Earned Value Management - there is a significant amount of work done in understanding these charts in a number of industries.

I strongly recommend reading the Agile Wiki charting change series - Charting Change and  Agile Charts - my linking of the images glosses over a fair bit of the material on the site.

ContentLicense: CC BY-SA 3.0


问:
How do you debug without an IDE?
Every time I look for an IDE (currently i'm tinkering with Go), I find a thread full of people recommending Vi, Emacs, Notepad++ etc.

I've never done any development outside of an IDE; I guess I've been spoiled. How do you debug without an IDE? Are you limited to just logging?

答:
By using a debugger.  For the most part, this is also what an IDE does behind the scenes -- it just wraps the experience in a GUI.

On Unix, one of the most commonly used debuggers is GNU gdb, which has largely supplanted the earlier Unix debuggers such as dbx.

To get an idea of what debugging looks like / feels like from the command line, you can look at the gdb manual.

As in other areas, using a debugger from the command line requires learning a syntax and a set of commands, but brings with it a lot of flexibility and scriptability.  On the other hand, if you are already comfortable working in an editor such as vim or emacs, you may find that your favorite editor has a plug in for your favorite debugger.

Title: How do you debug without an IDE?


问:
What is use of universal character names in identifiers in C++
The C++ standard (I noticed it in the new one, but it did already exist in C++03) specifies universal character names, written as \uNNNN and \UNNNNNNNN and representing the characters with unicode codepoints NNNN/NNNNNNNN. This is useful with string literals, especially since explicitly UTF-8, UTF-16 and UCS-4 string literals are also defined. However, the universal character literals are also allowed in identifiers. What is the motivation behind that?

The syntax is obviously totally unreadable, the identifiers may be mangled for the linker and it's not like there was any standard function to retrieve symbols by name anyway. So why would anybody actually use an identifier with universal character literals in it?

Edit: Since it actually existed in C++03 already, additional question would be whether you actually saw a code that used it?

答: C++ requires that actual extended characters appearing literally in source behave identically with Universal Character Names. Allowing Universal Character Names in identifiers permits programmers to use extended characters in identifiers.</p>


问:
Readability of || statements
On HTML5 Boilerplate they use this code for jQuery:

```<code><script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-...
</code>```

What's more readable:

```<code>if (!window.jQuery) document.write(...);
</code>```

or

```<code>window.jQuery || document.write(...);
</code>```

答: As with others I think the if version is more readable, I certainly wouldn't want to see logic like that strewn about a program. Having said that I think there is one idiomatic usage which is common in Perl that I personally rather like: when checking for a fatal return value, e.g. open(filename) || die. It seems to me this is a clear, compact way of expressing it that keeps the unlikely check out of the main logic of the code.

Title: Readability of || statements


问:
should F12's request headers show session id as cookie?
I'm trying to educate myself on potential web attacks.  I just found a site (which will rename anonymous) where it shows me what looks to be like the php session id inside the cookies section of the request header.
My immediate reaction was "wow, that's bad"... but then i couldn't really come up with a scenario as to how someone could use this to mess up the site.
But maybe its because I'm a newbie to this stuff.
But assuming that I got someone else's session id... I'd have to hack the site with their session id before it expires right?

So my question is, how real is this threat?
And is this common, where web developers store session ids in cookies, thereby making it visible in F12?
Sorry for the remedial questions.
I read the article:
Why do popular websites store very complicated session-related data in cookies -- and what does it all mean?

And i get that sometimes, you want to use cookies to move data off server to client... but I think I need more clarification on how serious a security breach this is.

答: This SO question indicates it's not really an issue so long as you are using random numbers for your session ids and take a few other precautions like encrypting the communication channel.</p>


问:
What "version naming convention" do you use?
Are different version naming conventions suited to different projects? What do you use and why?

Personally, I prefer a build number in hexadecimal (e.g 11BCF), this should be incremented very regularly. And then for customers a simple 3 digit version number, i.e. 1.1.3.

```<code>1.2.3 (11BCF) <- Build number, should correspond with a revision in source control
^ ^ ^
| | |
| | +--- Minor bugs, spelling mistakes, etc.
| +----- Minor features, major bug fixes, etc.
+------- Major version, UX changes, file format changes, etc.
</code>```

答:
We use Major.Minor.Build#.YYMMDD[suffix], as we usually only do one production build on any particular day (but use a b/c/d suffix if there's more than one) and the YYMMDD gives users/customers/management an indication of the age of the build, where 6.3.1389 does not.

Major numbers increase with significant product features (paid-for).

Minor numbers increase with fixes/improvements (free update).

Build always increases; not all builds ship, so it's not a linear progression.

ContentLicense: CC BY-SA 2.5


问:
Realtime (almost) bidrectional communication in Java
I will explain the context of the problem first. For a University project I'm going to implement an Android application. The Android application (and others) will be able to send data to a remote source, that remote source will also be able to send messages to the Android applications. For example the messages may be "apply configuration x", "what is your status". I want the remote source to be able to send these messages to:

Reduce overhead. I don't want the Android devices sending data when its not necessary. This uses data and power.

So that I can scale it, for example version 1 might allow you to check what value x is on the Android applications, version 2 might let you check what y is etc.

I have looked at implementing this using Sockets in Java. Having the Android application talk to the remote source is easy. I configure the router (port forward) and everything is OK. The problem is having the remote source to talk to the Android application. They may be using public WiFi hotspots, have their 3G on etc, I wouldn't be able to address the device directly via sockets right?

The approach to solving the problem is not that common I believe, which makes me believe I'm trying to do something that shouldn't be done. Can anyone shed some light on this and offer me some guidance?

Many thanks.

答:
As you say, typically it is very difficult or impossible to establish a socket connection originating at a central server and attempting to connect to mobile devices. Instead, what you can do is originate the connection at the mobile device, connect to the central server, and leave the socket open waiting for a command from the central server. Of course the first thing your Android code would do on connection is identify itself to the central server, so the central server knows who it is talking to.

Fortunately, Google has already done this for you in Google Cloud Messaging for Android:

Google Cloud Messaging for Android (GCM) is a service that allows you to send data from your server to your users' Android-powered device. This could be a lightweight message telling your app there is new data to be fetched from the server (for instance, a movie uploaded by a friend), or it could be a message containing up to 4kb of payload data (so apps like instant messaging can consume the message directly).


答:
Some people use gdb at the command line, or a plugin.  There are also standalone GUI front ends to gdb, like DDD.  Depending on your language, there are language-specific standalone debugger GUIs, like Winpdb for python, or jswat for java.  Because these projects focus only on debugging, they are often superior to integrated debuggers.

The other dirty little secret about IDEs is all of them worth their salt let you specify a custom editor, so you can use parts of the IDE for certain tasks, but use a decent editor for editing.  It's not uncommon to only fire up an IDE to use its debugger, especially if that's what your colleagues all use.

Title: How do you debug without an IDE?

Body:
Every time I look for an IDE (currently i'm tinkering with Go), I find a thread full of people recommending Vi, Emacs, Notepad++ etc.

I've never done any development outside of an IDE; I guess I've been spoiled. How do you debug without an IDE? Are you limited to just logging?


答:
I think you're confusing connection with communication.  Your application can open communications with the server using TCP or UDP and just sit there without sending
any data.  A bidirectional pipe is open, and can be used to send messages initiated
at either end of the connection.</p>

Title: Realtime (almost) bidrectional communication in Java

Body:
I will explain the context of the problem first. For a University project I'm going to implement an Android application. The Android application (and others) will be able to send data to a remote source, that remote source will also be able to send messages to the Android applications. For example the messages may be "apply configuration x", "what is your status". I want the remote source to be able to send these messages to:

Reduce overhead. I don't want the Android devices sending data when its not necessary. This uses data and power.

So that I can scale it, for example version 1 might allow you to check what value x is on the Android applications, version 2 might let you check what y is etc.

I have looked at implementing this using Sockets in Java. Having the Android application talk to the remote source is easy. I configure the router (port forward) and everything is OK. The problem is having the remote source to talk to the Android application. They may be using public WiFi hotspots, have their 3G on etc, I wouldn't be able to address the device directly via sockets right?

The approach to solving the problem is not that common I believe, which makes me believe I'm trying to do something that shouldn't be done. Can anyone shed some light on this and offer me some guidance?

Many thanks.


问:
Refactoring: Two big chunks within a function
I am designing an API which mostly involves refactoring the original code.

So Right now I have a method which has two big chunks which are seperated by an If-else condition, which in my opinion is not exactly the best idea.

The code looks like

```<code>do_something():
     if (isTrue):
         #Large block of statements.
     else:
         #another large block of statements.
</code>```

The reason I have them both under a single function is because both the chunks do the same thing but with some slight variations, which introduces the ugly if-else block.

I wanted to know what would be the best idea to refactor this code in a better way, if it is possible to do that using OOP, that would be even better.

I am not going with the obvious defining two methods way because at the moment both the chunks are doing the same thing.

答: The obvious way is a good way to start.  Once you have methods a and b defined, you can extract their commonality into c - at which point maybe you can re-inline a and b into the original method.</p>


问:
How to manage releases with multiple features at different states?
We have a branching structure of:

multiple dev branches for each major new feature

Main branch, merged into from a dev branch once a feature is ready for testing

Release branch, merged into from Main once a feature is ready for production

We often have new features completed at around the same time that end up in Main, with some of the same source code changed. Then Feature A may be declared ready for production and need to be deployed, while Feature B requires more work.

Once changes are incorporated in Main, particularly with multiple revisions to Feature A and B, their identity as separate features is lost. It then becomes risky and difficult to promote just one of them to production. We use TFS and I don't know if this is one of its limitations.

What is the best way to resolve this? Should we be using a different branching strategy, or would a DVCS fix it?

答:
Don't merge to main (or trunk) for testing. Trunk should always "ready-to-go" code, meaning it may not have all functionality, but will not be broken code.

Think of trunk as code you can release at any time.

Test your branches, and when they pass, merge to trunk, immediately do an integration test and then tag and deploy when ready. If the new code fails the integration, then revert, merge changes from trunk into branch and then fix the problem. Once the branch works, rinse and repeat.

You will not lose your history because you can always traverse backwards through the logs (assuming you're using something sane; CVS/VSS are not sane).


问:
What are some things you have read that inspired and guided you as a programmer?
For example, being a beginner, I find a lot of inspiration and direction from reading this post by Bryan Woods.</p>

答:
I found You and Your Research to be very valuable advice. This was a lecture by Hamming to his colleagues at Bell Labs.

What Bode was saying was this: "Knowledge and productivity are like compound interest." Given two people of approximately the same ability and one person who works ten percent more than the other, the latter will more than twice outproduce the former. The more you know, the more you learn; the more you learn, the more you can do; the more you can do, the more the opportunity - it is very much like compound interest. I don't want to give you a rate, but it is a very high rate. Given two people with exactly the same ability, the one person who manages day in and day out to get in one more hour of thinking will be tremendously more productive over a lifetime. I took Bode's remark to heart; I spent a good deal more of my time for some years trying to work a bit harder and I found, in fact, I could get more work done. I don't like to say it in front of my wife, but I did sort of neglect her sometimes; I needed to study. You have to neglect things if you intend to get what you want done.


答:
You could model your "if" condition as two different classes.  I'm assuming there are 3 differences between your "large blocks of statements."  You might call one OneWay and the other AnotherWay.

```<code>Class OneWay(ParentWay):
    myWay(a, b, c):
        #Large block of statements.

Class AnotherWay(ParentWay):
    myWay(a, b, c):
         #another large block of statements.
</code>```

So here's how you'd use these two classes

```<code>do_something(someWay):
    someWay.myWay(a, b, c)
</code>```

Now it will do the right thing based on what type of class it's passed.  This kind of turns things inside out.

I'm not saying one way is better than the other, but it depends on the situation.  Certainly if your entire method is one big if/else statement and the if-block and else-blocks are nearly identical, then some kind of refactoring is probably called for.

A simpler and possibly better solution is this:

```<code>do_true_thing():
     #Large block of statements.

do_false_thing():
     #another large block of statements.
</code>```

So instead of passing a true/false, the client calls an appropriate method.  You would use better names.  In general, I don't like to have booleans in method signatures, unless it's really obvious what they mean.  When you get a method like do_stuff(isTrue, isReallyTrue) I have a hard time remembering what the parameters mean.

Using either of these techniques, you may still want to break the large blocks up into different procedures the way @CarlManaster suggested.

Pardon my pseudocode, I really don't know Python, but the concepts should still apply.

Title: Refactoring: Two big chunks within a function

Body:
I am designing an API which mostly involves refactoring the original code.

So Right now I have a method which has two big chunks which are seperated by an If-else condition, which in my opinion is not exactly the best idea.

The code looks like

```<code>do_something():
     if (isTrue):
         #Large block of statements.
     else:
         #another large block of statements.
</code>```

The reason I have them both under a single function is because both the chunks do the same thing but with some slight variations, which introduces the ugly if-else block.

I wanted to know what would be the best idea to refactor this code in a better way, if it is possible to do that using OOP, that would be even better.

I am not going with the obvious defining two methods way because at the moment both the chunks are doing the same thing.

Body:
You could model your "if" condition as two different classes.  I'm assuming there are 3 differences between your "large blocks of statements."  You might call one OneWay and the other AnotherWay.

Class OneWay(ParentWay):
    myWay(a, b, c):
        #Large block of statements.

Class AnotherWay(ParentWay):
    myWay(a, b, c):
         #another large block of statements.

So here's how you'd use these two classes

do_something(someWay):
    someWay.myWay(a, b, c)

Now it will do the right thing based on what type of class it's passed.  This kind of turns things inside out.

I'm not saying one way is better than the other, but it depends on the situation.  Certainly if your entire method is one big if/else statement and the if-block and else-blocks are nearly identical, then some kind of refactoring is probably called for.

A simpler and possibly better solution is this:

do_true_thing():
     #Large block of statements.

do_false_thing():
     #another large block of statements.

So instead of passing a true/false, the client calls an appropriate method.  You would use better names.  In general, I don't like to have booleans in method signatures, unless it's really obvious what they mean.  When you get a method like do_stuff(isTrue, isReallyTrue) I have a hard time remembering what the parameters mean.

Using either of these techniques, you may still want to break the large blocks up into different procedures the way @CarlManaster suggested.

Pardon my pseudocode, I really don't know Python, but the concepts should still apply.


问:
How do I evaluate an IDE?
I don't want to know which IDE is best, because that's subjective. I'd like to know how to evaluate an IDE. I'm primarily a vim user, and realistically happy there, but occasionally look at languages that have powerful IDE's and I consider using them.

The problem I run into is that they mostly seem the same to me. Certainly any of them will work, but when trying to decide which IDE to invest time in how do I decide?

What features should I be testing to see if I like the way A or B works better? Obviously some IDE's are specifically tailored to a language, but given a choice between say Netbeans, Eclipse, and Intellij IDEA, how would I decide? as a novice they seem the same.

When evaluating I generally try the editor, a few configuration options, file browser. I think my colleagues all basically the same as me and don't use IDE. I also doubt I'd end up using the IDE for work, because Perl shop, and I'm happy with vim for that, I'm simply trying to figure out how to use them in the context of languages that aren't day job and have solid IDE support.

答: As a developer, I consider whichever one helps me get the job done the quickest with the least frustration.  Also, one that is popular because I know I can find support for just about anything via google if that is the case.  As a fellow vim'er I tend to choose ones with vim plugins (e.g. eclipse and visual studio both have vim plugins).  Then it's the best of both worlds :)</p>

Title: How do I evaluate an IDE?


答:
I used a debugger for several years while I was writing graphics drivers.  I had a second computer that ran the debugger against the first one (because the screen in the primary computer wouldn't work when the graphics driver was broken).  It was critical to be able to stop the code and step to the point where I hung the hardware so I'd know what was happening.

For purely software problems, I find that thinking about the problem and testing the system to learn more about the problem is much more useful than stepping through code line by line.  With print statements, I have a list of everything that happened at the command line or log file that I can look at and reconstruct what happened, going backwards and forwards more easily than I ever could with a debugger.

The hardest bugs are usually solved by understanding the problem away from the computer.  Sometimes with a piece of paper or whiteboard, and sometimes the answer reveals itself while I'm doing something else.  The trickiest bugs are solved by looking carefully at the code like playing Where's Waldo.  All the rest seem easiest with print statements, or logging statements.

Different people have different styles, and different styles are better for different tasks.  Print statements are not necessarily a step down from a debugger.  Depending on what you are doing, they can even be better.  Especially in a language that doesn't have a native debugger (does Go?).

Title: How do you debug without an IDE?


答:
You need to have someone who pushes changes from Main to each sub-branch regularly. Do the testing on the dev branches individually. Once one feature has been approved for release its changes must be merged into the other feature branches via Main. Then push to Release.

Releasing should be done on a FCFS basis unless there are dependencies.

Having different features modify the same code may result in your merge tool failing and a headache for some poor soul.

Title: How to manage releases with multiple features at different states?

Body:
We have a branching structure of:

multiple dev branches for each major new feature

Main branch, merged into from a dev branch once a feature is ready for testing

Release branch, merged into from Main once a feature is ready for production

We often have new features completed at around the same time that end up in Main, with some of the same source code changed. Then Feature A may be declared ready for production and need to be deployed, while Feature B requires more work.

Once changes are incorporated in Main, particularly with multiple revisions to Feature A and B, their identity as separate features is lost. It then becomes risky and difficult to promote just one of them to production. We use TFS and I don't know if this is one of its limitations.

What is the best way to resolve this? Should we be using a different branching strategy, or would a DVCS fix it?


答: jimwise answered the question quite well, but I thought I should add that, should you choose to work without a full IDE, the Microsoft provided command line debugger for Windows is called CDB. CDB comes with several other tools, including WinDBG which is the GUI equivalent, when you download the Windows SDK.</p>

Title: How do you debug without an IDE?


问:
How do you compress ASCII strings into fewer bytes?
I'm working with an embedded device with a unique protocol that sends messages to other devices and I'm making an application that parses the sent packets. Each packet carries 8 bytes. The protocol is defined as where first byte is header and remaining 7 bytes is the data.

They are trying to pass a particular ID string but the ID string is 8 characters long (ASCII) so it won't fit in 7 bytes.

What my colleague told me is that they're going to turn the 8 ascii bytes of original string into integer (decimal) and send me 4 bytes of it. They told me I should be able to get the original string from the 4 bytes. I'm having a hard time wrapping my head around on this.

So if you have an ID string like "IO123456", that's 0x49 0x4f 0x31 0x32 0x33 0x34 0x35 0x36 in ASCII.. How on earth can you compress that in 4 bytes by turning it into an integer and I can get the original string from it? Am I missing something or is my colleague mistaken? I understand this is a really bizzare question but this seriously does not make any sense to me.

答: Is the ID always in the form: IO123456? What your colleague could mean is that he only sends the numeric part, which fits easily in 4 bytes omitting the "IO" part.</p>


答:
Possibly by converting '0123456' to a long integer.

But this would only work for numeric IDs.

Another possible scheme would be to convert your 7  to 6 bit ECMA-1 encoding which would give you a Six byte string but you would be limited to the character set to numbers upper case letters and a limited set of punctuation characters.

Title: How do you compress ASCII strings into fewer bytes?

Body:
I'm working with an embedded device with a unique protocol that sends messages to other devices and I'm making an application that parses the sent packets. Each packet carries 8 bytes. The protocol is defined as where first byte is header and remaining 7 bytes is the data.

They are trying to pass a particular ID string but the ID string is 8 characters long (ASCII) so it won't fit in 7 bytes.

What my colleague told me is that they're going to turn the 8 ascii bytes of original string into integer (decimal) and send me 4 bytes of it. They told me I should be able to get the original string from the 4 bytes. I'm having a hard time wrapping my head around on this.

So if you have an ID string like "IO123456", that's 0x49 0x4f 0x31 0x32 0x33 0x34 0x35 0x36 in ASCII.. How on earth can you compress that in 4 bytes by turning it into an integer and I can get the original string from it? Am I missing something or is my colleague mistaken? I understand this is a really bizzare question but this seriously does not make any sense to me.


问:
Is initializing a char[] with a string literal bad practice?
I was reading a thread titled "strlen vs sizeof" on CodeGuru, and one of the replies states that  "it's anyways [sic] bad practice to initialie [sic] a char array with a string literal."

Is this true, or is that just his (albeit an "elite member") opinion?

Here is the original question:

```<code>#include <stdio.h>
#include<string.h>
main()
{
    char string[] = "october";
    strcpy(string, "september");

    printf("the size of %s is %d and the length is %d\n\n", string, sizeof(string), strlen(string));
    return 0;
}
</code>```

right. the size should be the length plus 1 yes?

this is the output

the size of september is 8 and the length is 9

size should be 10 surely. its like its calculating the sizeof string before it is changed by strcpy but the length after.

Is there something wrong with my syntax or what?

Here is the reply:

It's anyways bad practice to initialie a char array with a string literal. So always do one of the following:

```<code>const char string1[] = "october";
char string2[20]; strcpy(string2, "september");
</code>```

答:
Never is really long time, but you should avoid initialization char[] to string, because, "string" is const char*, and you are assigning it to char*.
So if you pass this char[] to method who changes data you can have interesting behavior.

As commend said I mixed a bit char[] with char*, that is not good as they differs a bit.

There's nothing wrong about assigning data to char array, but as intention of using this array is to use it as 'string' (char *), it is easy to forget that you should not modify this array.


答:
Try them out!

You mentioned that you're a vim user. Assuming that you don't want to give up your superpowers, you'll probably want to see which IDEs have better vim modes.

Think about if you want an IDE that works with many languages, or multiple which are fantastic at the language they specialize in.

It's all a matter of opinion.

Title: How do I evaluate an IDE?

Body:
I don't want to know which IDE is best, because that's subjective. I'd like to know how to evaluate an IDE. I'm primarily a vim user, and realistically happy there, but occasionally look at languages that have powerful IDE's and I consider using them.

The problem I run into is that they mostly seem the same to me. Certainly any of them will work, but when trying to decide which IDE to invest time in how do I decide?

What features should I be testing to see if I like the way A or B works better? Obviously some IDE's are specifically tailored to a language, but given a choice between say Netbeans, Eclipse, and Intellij IDEA, how would I decide? as a novice they seem the same.

When evaluating I generally try the editor, a few configuration options, file browser. I think my colleagues all basically the same as me and don't use IDE. I also doubt I'd end up using the IDE for work, because Perl shop, and I'm happy with vim for that, I'm simply trying to figure out how to use them in the context of languages that aren't day job and have solid IDE support.


答:
First things first, are there automated tests around this code already?  Assuming not, is there a way you can write an automated test around this code to make sure you don't break it when you refactor it?  You'll probably save time in the long run if you do this first.

After you've got that, I'd do what @CarlManaster. Extract them into two methods and piece by piece extract the parts they've got in common into a single method that they both share.  It may help if you've got a way to compare the two methods with a diff tool.  I use intellij-idea and it makes this pretty easy to do.


答:
There's not much point in defining evaluation criteria. Even if you define some, you will have to play with the IDE to decide if it satisfies them, but then again by playing with the IDE you will encounter things you like or dislike about it anyway, regardless of whether you established criteria or not.

My algorithm is: I choose the defacto standard for the language/SDK I'm using and just wait and see. If I encounter too much problems I'll consider switching to an IDE which is promised (by advertisement or word of mouth) to not have these specific issues.

As others have mentioned, since you're a vim user, one easy thing you can do is look at available vim emulation plugins.

Title: How do I evaluate an IDE?


问:
How can I avoid mistakes using the same variable name again?
This isn't a rare case and occurs with me often and I spent countless time trying to debug the code.

Latest example, this PHP code where I used $email for the parameter and for object as well.

```<code>private function _mail( $email )
{
    if( filter_var( $email, FILTER_VALIDATE_EMAIL ) ):
        $email = new Zend_Mail();
        $email->setSubject( $this->request->post('subject') )
            ->setBodyHtml( $this->request->post('message') )
            ->setFrom( $this->request->post('from') )
            ->addTo( $email )
            ->send();
        unset($email);
    endif;
}
</code>```

It was throwing an error, strtr() expects parameter 1 to be an string object given and it was really frustrating to browse through zend libraries to see what obscure string statement was throwing this error.

How to avoid such mistakes?

答:
My IDE does that for me.
Eclipse has "templates" for code-autocomplete (STRG+Space)
I told my Eclipse to always add a prefix to method parameters.

For example your method:

private function _mail( $recipient )

would automatically be auto-completed with $pRecipient.

Short Rule:
Always prefix method parameters, to avoid variable clashes inside the method body.

sidenote: think about using interfaces instead ob objects as method parameters.


答:
If you don't want to start with the obvious thing, you can also start with identifying small, common portions in block A and B and refactor each portion to a separate method which is then called from A as well as from B. Ideally, this will lead you to new blocks A and B only containing non-common functionality.

But then moving those functionality to separate methods will most probably still be a good idea, and the final result will be the same as if you did it the other way round.

To my experience, extracting small, common functions from A and B first has the advantage that you can deal with small methods which are quite often easier to understand, so the chance of introducing errors is smaller. Doing this step-by-step reduces also the size of the blocks A and B, and increases their readability, so afterwards the refactoring of A and B to methods gets easier.


问:
How do you interview someone with more experience than you?
The company I'm working for is looking to hire a senior developer with more experience than me, and they expect me to do the technical part of the interview. I've only been programming a few years and am not sure I have the knowledge needed to evaluate the coding skills of someone who has greater understanding/experience than I do.

Can anyone recommend some technical interview questions to ask that are a good means for evaluating higher-level programming skills, but still be ones I can understand?

I would say I'm past the jr. programmer level, but nowhere near senior. Most of what I've done is built small apps (web and desktop), some of them fairly complicated, but all of them have been meant to be used by no more then a handful of users. I feel I have a decent understanding of most programming concepts and am capable of learning/teaching myself just about anything, however I lack experience. As my boss is fond of telling me, "You don't know what you don't know".

In particular, things we'd like the person we hire to have experience with (that I don't have) is: Multi-tier development, multi-user environment, large-scale application development, two-way messaging, shared sessions, and Multi-threading/BackgroundWorkers.

UPDATE:

In response to Thor's comment below, we hired someone a few months ago and I think it has been working out great. I am learning a lot, not just about coding but also about things like design patterns, software architecture, documentation, and how other larger programming teams get stuff done. Its not always easy having someone come in and point out better ways to do things you have done, but if you can swallow your pride and be willing to try out new things you can learn a lot.

The interview process went better than I expected. I started asking questions about things I was familiar with, then asked some questions about some things I was struggling with. Whenever the interviewee said something I didn't understand, I'd ask them to explain it to me and then write it down so I could look it up later on. Overall, I felt I was able to get a pretty good idea of the applicant's skill level, intelligence, and what they'd be like to work with.

答:
I've had to do this several times.  I learned to do it in a step-wise process.

Start out with the same questions I give to the college grads.  I did this because the position I was doing the technical interview for was a programming position where we expected the developer to be hands on in the code, and I wanted to make sure the candidates could program.  With only one exception none of the candidates could - they were worse than any of the college grads.  All of them had been in managerial positions far too long.

For the candidate who passed a basic coding competency test, I had some more general "how would you handle X scenario" kinds of questions.  If you are doing web services in your project, for example, think of an interesting web services question and ask the candidate how he would solve it.  I wouldn't recommend that this be something you are currently working on directly, mostly because of the issue of intellectual property and company proprietary data.  Don't give that stuff out!

Spend time asking the candidate about stuff on his or her resume.  This is important.  You can find out about his or her best and worst team experiences, experiences as a supervisor, and so on.  Try to get a feel of the person's working style to see if he or she fits into your team.

My biggest issue when interviewing senior candidates was that they often got very nervous to be interviewed by a junior person, especially those who couldn't handle my basic coding tests.  Try hard to seem non-threatening in any skills you show throughout the interview - focus it on them, even if they can't answer your questions well.  Try and skew the interview to questions they can answer if they fail on the basics.


答:
Let's say Alice is using Bob's web application (running on Bob's server). HTTP does not have a concept of a session, so each page that Alice loads exists in isolation. The session cookie is something Bob sends back to Alice's browser when she logs on so that he can keep track of all the requests coming from Alice.

Therefore, the session cookie announced to Bob "this request comes from Alice". Bob implicitly trusts this. When he sees the cookie, he knows he is talking with Alice.

Where does this go wrong? When someone else than Alice can see the cookie.

Suppose Alice is sitting on an unencrypted wifi network. Mallory is sitting on the same network and sees the traffic between Alice and Bob. Suppose the traffic is unencrypted (HTTP instead of HTTPS). Now Mallory sees the HTTP cookie that Alice sends to Bob. Mallory can use their technical knowhow to send a request to Bob with Alice's cookie embedded in it, and Bob will respond to Mallory thinking that he is responding to Alice. This is what tools like Firesheep automate, but really anyone can do this sort of attack on any site accessed over HTTP on an open network.

Now, circling back to your question, this explains the common practices with session cookies:

Never put the session id in the URL. Otherwise Alice might send a link to Mallory via IM or some other channel that includes her session id. Mallory has her session id, so he can pretend to be her.

Always use HTTPS to prevent eavesdropping over Wifi. If the network traffic can be intercepted, and the cookie can be heard, Mallory can use it to pretend to be Alice.

If an application is used over HTTP, then the session can be intercepted by someone listening in on the network traffic, and the application is open for attack. How likely this is depends on whether someone decides to target the app and can find unsecured networks where the app is being used. Therefore, for unpopular web apps the risk is low, but for popular web apps the risk is very high. This is why facebook moved to HTTPS by default, and why Yahoo Mail now has the option to enable it.

There is no risk in F12, because there is no harm to Alice knowing her own cookie. There is only a risk if Mallory can see her screen and copy the cookie for his private uses.

Title: should F12's request headers show session id as cookie?

Body:
I'm trying to educate myself on potential web attacks.  I just found a site (which will rename anonymous) where it shows me what looks to be like the php session id inside the cookies section of the request header.
My immediate reaction was "wow, that's bad"... but then i couldn't really come up with a scenario as to how someone could use this to mess up the site.
But maybe its because I'm a newbie to this stuff.
But assuming that I got someone else's session id... I'd have to hack the site with their session id before it expires right?

So my question is, how real is this threat?
And is this common, where web developers store session ids in cookies, thereby making it visible in F12?
Sorry for the remedial questions.
I read the article:
Why do popular websites store very complicated session-related data in cookies -- and what does it all mean?

And i get that sometimes, you want to use cookies to move data off server to client... but I think I need more clarification on how serious a security breach this is.


答:
If the first two characters are not constant (but are always letters) and the remaining six characters are always numbers, a string like "IO123456" can be packed into 5 bytes by converting the numbers into binary-coded decimal (BCD) format:

```<code>IO123456 -> 0x49 0x4f 0x31 0x32 0x33 0x34 0x35 0x36
             |    |      \   /     \   /     \   /
            0x49 0x4f     0x12      0x34      0x56
</code>```

If there is a limited set of possible identifiers (the first two letters), you can encode these into a number and send that instead (as long as there are no more than 256 combinations), e.g.:

```<code>IO -> 0x00
RD -> 0x01
WT -> 0x02
   ...
AB -> 0x10
   ...
ZZ -> 0xff
</code>```

so that the original string is packed into 4 bytes without any loss of information:

```<code>IO123456 -> 0x49 0x4f 0x31 0x32 0x33 0x34 0x35 0x36
              \    /     \   /     \   /     \   /
               0x00       0x12      0x34      0x56
</code>```

Of course this process can also be reversed to get the original ID string.

Body:
If the first two characters are not constant (but are always letters) and the remaining six characters are always numbers, a string like "IO123456" can be packed into 5 bytes by converting the numbers into binary-coded decimal (BCD) format:

IO123456 -> 0x49 0x4f 0x31 0x32 0x33 0x34 0x35 0x36
             |    |      \   /     \   /     \   /
            0x49 0x4f     0x12      0x34      0x56

If there is a limited set of possible identifiers (the first two letters), you can encode these into a number and send that instead (as long as there are no more than 256 combinations), e.g.:

IO -> 0x00
RD -> 0x01
WT -> 0x02
   ...
AB -> 0x10
   ...
ZZ -> 0xff

so that the original string is packed into 4 bytes without any loss of information:

IO123456 -> 0x49 0x4f 0x31 0x32 0x33 0x34 0x35 0x36
              \    /     \   /     \   /     \   /
               0x00       0x12      0x34      0x56

Of course this process can also be reversed to get the original ID string.

ContentLicense: CC BY-SA 4.0


答:
If the string can be any sequence of characters:

If you can be sure your strings don't use the most-significant bit in each byte, you can chop each one down to seven bits and use bitwise operations to shift the remaining 56 bits into the 56 bits you have available.

If the strings are only letters and digits, come up with a 6-bit representation of just that set and make a 48-bit string of your identifier.

If the format is always two letters followed by a string of digits:

Leave the first two bytes alone and encode the number into a six-byte integer.  IO123456 becomes 0x49 0x4f 0x01E240.

Leave the first two bytes alone and pack the digits as binary-coded decimal.  IO123456 becomes 0x49 0x4f 0x12 0x34 0x56.


答:
you could move the 2 blocks into seperate functions then use a simple dispatcher:

```<code>def do_something():
    function_1() if isTrue else function_2()
</code>```

This will prevent haivng 2 "ugly" blocks of code

It is it a bad idea to treat functions as "bags of code" - if the code does differentoncerns then seperate them.

It will make the code more readable and pythonic - future you and maintainers will thanks you

Body:
you could move the 2 blocks into seperate functions then use a simple dispatcher:

def do_something():
    function_1() if isTrue else function_2()

This will prevent haivng 2 "ugly" blocks of code

It is it a bad idea to treat functions as "bags of code" - if the code does differentoncerns then seperate them.

It will make the code more readable and pythonic - future you and maintainers will thanks you


问:
How would I make a suggestion for a change to the SQL standard
If I wanted to make a suggestion to a change to how the UPDATE statement works in SQL, how would I go about it?

Is there a website for the next standard?

I googled, but just kept getting the Wikipedia page.

答:
Well that standards are controlled by ANSI, so I would suggest you start there.

http://www.ansi.org/

Although as already said getting it in to the standards is unlikely, as mentioned from others there are ways of doing this already if you want to be explicit and more importantly your change wouldn't be backwards compatible.


答:
There are a couple of means to do this.

Petition ISO

Persuade your favorite DB vendor

Make the change yourself

Petition ISO

You can petition your request to the appropriate committee(s) at ISO.  The Wikipedia article you linked provides the ISO specification numbers and therefore which committees.

Be forewarned that you'll probably need to volunteer on the committee(s) and / or put in a lot of work to champion this change.  Having indirectly worked with standards committees before, I can assure you that nothing is straightforward and nothing occurs unless the change has a champion.

Persuade your favorite DB vendor

The DB vendors such as IBM, Microsoft, and Oracle are not obligated to code their databases against the SQL standard.  Last I checked, none of them complied completely with the latest SQL standard anyway.  If you have sufficient clout with the vendors, you may be able to persuade them to implement the change you are requesting.  I would start with your local sales representative in this case.

All of the major DB vendors are (or should be) involved in the standardization process.  If you can convince one of them to make the change for you, then they should be able to champion the change at the next evolution of the standard.

Make the change yourself

All that having been said, you're more than welcome to pull a copy of the source for your favorite open source DBMS and make the change yourself.  While this will likely require the most amount of effort on your part, it also has the best odds of actually seeing the light of day.  Even if the project maintainers reject your enhancement, you can always run your version of the database and have the change you have requested.

If your change is adopted by the project and it proves popular, it could eventually find its way into the next version of the standard.

Title: How would I make a suggestion for a change to the SQL standard

Body:
If I wanted to make a suggestion to a change to how the UPDATE statement works in SQL, how would I go about it?

Is there a website for the next standard?

I googled, but just kept getting the Wikipedia page.


问:
Cyclomatic complexity with two IFs - why it is 3?
I have read an article with following example:

```<code>void func()
{
if (condition1)
a = a + 1;
if (condition2)
a = a - 1;
}
</code>```

It says the CC is 3 as there are three possible paths. How come? Why not 4? I Would expect TRUE,TRUE; FALSE,FALSE; TRUE, FALSE and FALSE, TRUE.

Does not matter what the statements are. CC=Ifs-EndPoints+2. It is always 3 for 2 IFs and one ending..

答:
TRUE,TRUE has the same outcome as FALSE,FALSE.</p>

```<code>//TRUE,TRUE
void func()
{
    a = 1;

    if (condition1)
        a = a + 1; // a == 2
    if (condition2)
        a = a - 1; // a == 1

    // a == 1
}

//FALSE,FALSE
void func()
{
    a = 1;

    if (condition1)
        a = a + 1; // a == 1
    if (condition2)
        a = a - 1; // a == 1

    // a == 1
}

//TRUE, FALSE
void func()
{
    a = 1;

    if (condition1)
        a = a + 1; // a == 2
    if (condition2)
        a = a - 1; // a == 2

    // a == 2
}

//FALSE, TRUE
void func()
{
    a = 1;

    if (condition1)
        a = a + 1; // a == 1
    if (condition2)
        a = a - 1; // a == 0

    // a = 0
}
</code>```

Body:
TRUE,TRUE has the same outcome as FALSE,FALSE.

//TRUE,TRUE
void func()
{
    a = 1;

    if (condition1)
        a = a + 1; // a == 2
    if (condition2)
        a = a - 1; // a == 1

    // a == 1
}

//FALSE,FALSE
void func()
{
    a = 1;

    if (condition1)
        a = a + 1; // a == 1
    if (condition2)
        a = a - 1; // a == 1

    // a == 1
}

//TRUE, FALSE
void func()
{
    a = 1;

    if (condition1)
        a = a + 1; // a == 2
    if (condition2)
        a = a - 1; // a == 2

    // a == 2
}

//FALSE, TRUE
void func()
{
    a = 1;

    if (condition1)
        a = a + 1; // a == 1
    if (condition2)
        a = a - 1; // a == 0

    // a = 0
}


问:
Programming languages classification / taxonomy
Is there a rigorous way to classify programming languages ?

If so, can the various "dimensions" be quantified ? (degree of purity)

For instance, I just went on the Shade language website (I am not affiliated with it in any way) and saw :

"semi-functional" -> But how much is that language semi-functional ? -> quantification need

"full type checking" -> So type checking can be partial -> can be quantified too ?

Objectif model / no object model...

答:
You can find a lot of information here:

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

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

I am not going to rewrite the Wikipedia here, just a few simple explanations, so you may better understand what the Wikipedia articles are trying to say.

One thing is how the programs are constructed. Sometimes it is about the programmer's style, but the programming language or the library can make styles easier, harder, or impossible. Multiple styles can be used in the same program.

imperative programming -- "first do this, then do this, then do that". You always write what is supposed to happen next. Even if there are more choices, e.g. based on the user's input, it is always: you ask about the input when you want to ask, then you choose what happens next based on the answer you received. This programming style is nice for short non-interactive programs; but with large programs it becomes very difficult to read and maintain. Also this is how the computer works on the hardware level (all other programming languages have to be compiled or interpreted to this), therefore this is what many programming languages use.

event-based programming -- you are not doing the whole program, but rather some part of it, which must fit into a given framework. The framework tells you "now this happened", and you are supposed to react on the event. You don't decide what happens later. The framework calls you when your reaction is needed, and you only react to that. (For example, if you make a computer game, you react on "game started", "mouse clicked", "key pressed", "screen needs to be displayed" and "game is quitting" events. You can remember e.g. the coordinates of your spaceship; the reaction to pressing a key would be changing the coordinate, and the reaction to screen needing to be display would be drawing the spaceship on the current coordinates.)

object-oriented programming -- you split the program into many smaller parts, and you describe each part separately; from inside: what data it contains, and from outside: what actions it can do. (For example, your object Spaceship has data: x coordinate, y coordinate, number of lives. It can: move up, move down, move left, move right, return the number of lives, remove one life.) The important part is polymorphism, which means that multiple objects can have the same interface, i.e. can do the same kind of action. (E.g. Spaceship, Missile, and Asteroid all have coordinates, and can paint themselves on a screen.) So a part of program can treat all of them in a unique way. (E.g. a gravity field could influence the coordinates of all MovableObjects without having to know their details.)

aspect-oriented programming -- another way to split the program into smaller pieces, but this time the pieces represent the functionality of the program. (Sorry, I don't know much about this.)

functional programming -- most natural for mathematical calculations. You define what "f(x)" means and what "g(x, y)" means, and then you ask program to calculate "g(f(3), f(5))". Each function depends only on its input data, nothing else; e.g. the function "f(x)" can only use the value of "x", so if you call "f(7)" twice, you get the same result. Also the function "f(x)" cannot modify the value of "x". If you want to make a program where data change in time, you have to somehow include the time or other events as parameters of the functions. (For example, the position of spaceship in time T+1 could be described as a function of position of the spaceship in time T and the state of keyboard buttons.) These limitations give the advantage of avoiding come bugs and making concurrent programming (multiple processors or even computers running parts of the same program) much easier.

Another thing is how you use the data. Do you use only input and output values of the functions, or can you also store the values in variables a access them randomly? If you specify a value, can you change it later? If you have multiple types of data (e.g. texts, numbers, coordinates, spaceship description), can any kind of data go to any kind of a variable, or do you have to specify which variable contains which kind of data? -- Typically, the more freedom you have here, the more opportunities you have to make bugs.

But I guess that to understand this fully, one has to become familiar with a few programming languages representing the various styles, see the advantages and disadvantages of each, and also how each language can try to overcome its specific problems. Some languages give you more choices. (For example in Java you can write imperative, event-based, object-oriented and even kind-of-functional programs. The language itself is object-oriented, some objects use events, and there is nothing preventing you to put all your code in one function. If you use immutable objects and avoid side effects, you get some advantages of functional programming.)


问:
Dealing with Feature Intersections
I have recently witnessed more and more problems similar to the ones explained in this article on feature intersections. Another term for it would be product lines, though I tend to attribute these to actually different products, whereas I usually encounter these problems in the form of possible product configurations.

The basic idea of this type of problem is simple: You add a feature to a product, but somehow things get complicated due to a combination of other existing features. Eventually, QA finds a problem with a rare combination of features that no one thought of before and what should have been a simple bugfix may even turn into requiring major design changes.

The dimensions of this feature intersection problem are of a mind-blowing complexity. Let's say the current software version has N features and you add one new feature. Let's also simplify things by saying that each of the features can turned on or off only, then you already have 2^(N+1) possible feature combinations to consider. Due to a lack of better wording / search terms, I refer to the existence of these combinations as feature intersection problem. (Bonus points for an answer including reference(s) for a more established term.)

Now the question I struggle with is how to deal with this complexity problem on each level of the development process. For obvious cost reasons, it is impractical up to the point of being utopian, to want to address each combination individually. After all, we try to stay away from exponential complexity algorithms for a good reason, but to turn the very development process itself into an exponentially sized monster is bound to lead to utter failure.

So how do you get the best result in a systematic fashion that does not explode any budgets and is complete in a decent, useful, and professionally acceptable way.

Specification: When you specify a new feature - how do you ensure that it plays well with all the other children?

I can see that one could systematically examine each existing feature in combination with the new feature - but that would be in isolation of the other features. Given the complex nature of some features, this isolated view is often already so involved that it needs a structured approach all in itself, let alone the 2^(N-1) factor caused by the other features that one willingly ignored.

Implementation: When you implement a feature - how do you ensure your code interacts / intersects properly in all cases.

Again, I am wondering about the sheer complexity. I know of various techniques to reduce the error potential of two intersecting features, but none that would scale in any reasonable fashion. I do assume though, that a good strategy during the specification should keep the problem at bay during implementation.

Verification: When you test a feature - how do you deal with the fact, that you can only test a fraction of this feature intersection space?

It is tough enough to know that testing a single feature in isolation
guarantees nothing anywhere near error-free code, but when you reduce
that to a fraction of 2^-N it seems like hundreds of tests are not
even covering a single drop of water in all oceans combined. Even worse, the most   problematic errors are those that stem from the intersection of features, which one might not expect to lead to any problems - but how do you test for these if you don't expect such a strong intersection?

While I would like to hear how others deal with this problem, I am primarily interested in literature or articles analyzing the topic in greater depth. So if you personally follow a certain strategy it would be nice to include corresponding sources in your answer.

答:
This won't be the best answer by any means, but I've been thinking on some things which intersect with points in your question so I thought I'd mention them:

Structural Support

From the little I've seen, when features are buggy and/or don't mesh well with others it is largely due to poor support provided by the core structure/framework of the program for managing/coordinating them. Spending more time fleshing out and rounding out the core, I think, should ease the addition of new features.

One thing I've found to be common in the applications where I work is that the structure of a program was set up to handle one of a kind of object or process but a lot of the extensions we've done or want to do have to do with handling many of a kind. If this were taken into account more at the outset of the application's design, then it would have helped adding these features later.

This becomes quite critical when adding support for multiple X's which involve threaded/asynchronous/event-driven code because that stuff can go bad quite quickly -- I've had the joy of debugging a number of issues related to this.

It's probably difficult to justify this kind of effort up front though, especially for prototypes or one-off projects -- even though some of those prototypes or one-offs go on to be used again or as (the basis of) the final system, meaning the expenditure would have been worth it in the long run.

Design

When designing a program's core, starting out with a top-down approach can help turn things into manageable chunks and lets you wrap your head around the problem domain; after that I think a bottom-up approach should be used -- this will help make things smaller, more flexible, and better for adding on to later. (As mentioned in the link, doing things this way makes for smaller implementations of the features, which means fewer conflicts/bugs.)

If you focus on the core building blocks of the system and make sure they all interact well, then anything built using them will also probably behave well and should integrate better with the rest of the system.

When a new feature is added, I think a similar route could be taken in designing it as was taken designing the rest of the framework: decomposing it then going bottom-up. If you can reuse any of the original blocks from the framework in implementing the feature then that would definitely be helpful; once you're done you can add any new blocks you get from the feature to those already in the core framework, testing them with the original set of blocks -- that way they'll compatible with the rest of the system and usable by future features as well.

Simplify!

I've been taking a minimalist stance on design of late, starting with simplifying the problem, then simplifying the solution. If time can be made for a second, simplifying design iteration on a project then I could see that being very helpful when adding things later on.

Anyway, that's my 2c.

Title: Dealing with Feature Intersections


答:
If your article "says the CC is 3 as there are three possible paths" then the article is missing some of the detail. The wikipedia definition of cyclomatic complexity defines it in terms of the number of nodes and edges in the graph of the function: M = E − N + 2P.

This is the graph of your function:

```<code>    (+)
     |
    (if)
     |\
     | (stmt)
     |/
    (if)
     |\
     | (stmt)
     |/
    (*)
</code>```

E = 7, N = 6, P = 1 so M = 7 - 6 + 2*1 = 3.

Title: Cyclomatic complexity with two IFs - why it is 3?

Body:
I have read an article with following example:

```<code>void func()
{
if (condition1)
a = a + 1;
if (condition2)
a = a - 1;
}
</code>```

It says the CC is 3 as there are three possible paths. How come? Why not 4? I Would expect TRUE,TRUE; FALSE,FALSE; TRUE, FALSE and FALSE, TRUE.

Does not matter what the statements are. CC=Ifs-EndPoints+2. It is always 3 for 2 IFs and one ending..

Body:
If your article "says the CC is 3 as there are three possible paths" then the article is missing some of the detail. The wikipedia definition of cyclomatic complexity defines it in terms of the number of nodes and edges in the graph of the function: M = E − N + 2P.

This is the graph of your function:

    (+)
     |
    (if)
     |\
     | (stmt)
     |/
    (if)
     |\
     | (stmt)
     |/
    (*)

E = 7, N = 6, P = 1 so M = 7 - 6 + 2*1 = 3.


问:
How much time a week do you spend on extracurricular programming?
Background: I'm a microsoft DBA/IT type person by day, an iOS and Mac developer by night. I have one app in the App Store and another one in the works. I try to spend as much time as possible working on my two apps, but with a new daughter and other (non computer) hobbies, I find it hard to spend more than a few hours every week programming.

I'm wondering how this compares to other developers. I see a lot of apps out there written by single developers who don't do iOS development as their main job. Are they spending 4 hours a night working on their projects, or do they just plug away for a year or two before releasing anything?

答:
For me it really goes in streaks.  I have a lot of hobbies, one of which is extracurricular programming.  Like most hobbies, I get into it for a while, then lose interest for a while, then come back to it later when I'm sick of all my other hobbies.

When I'm on a hardcore hacking streak, I'll go a few weeks where I spend 4-5 hours a night and a good portion of my weekends programming just for fun, in addition to the programming I do at work.  During these times, programming is constantly on my mind.  Then I temporarily burn out and give it a rest for a few months.  During this time, I spend some time on another hobby and for a while, and do almost no recreational programming.  I maybe spend an hour or two a week on bug fixes for my existing projects.

I find it very hard to just consistently spend a few hours a week because to write really good hobby project code, I need to be thinking about it all the time.  On the other hand, such effort is unsustainable in the long run.  The result is this extreme bimodality.


问:
How to maintain lots of different variations for deployment, using Git for development
Although there are many similar questions here regarding using GIT for maintaining different versions, none seem to answer my specific case.

I'm OK with how to use GIT to do my development, using different branches to do hot fixes, versioning etc.

However, I am making a commercial application that needs to track various modules and configurations for DIFFERENT clients. And I do NOT wish the client to have access to a module or code they haven't paid for. Yet I would like to use GIT to deploy on their server, or to be able to deploy directly on the client server using ssh/rsync, or even on my server in a unique directory, then zip up the source files using a standard process.

Let me give you an example:

Client A:

Deploy basic application

Deploy Module A (e.g. forum) only

Deploy Client A specific theme with Client A specific logo

Client B:

Deploy basic application

Deploy Module A (e.g. forum)

Deploy Module B (e.g. faq system)

Deploy Client B specific theme with Client B specific logo

Development Server:

Contains basic application

Contains Module A (e.g. forum)

Contains Module B (e.g. faq system)

Contains Client A and Client B themes with all logos

Contains Development Notes which must NOT be visible to client

Contains build files used with Phing - these must NOT be available to clients

It's very important to understand that GIT on the development server contains proprietary data for Client A and Client B. Therefore Client A must never see my development notes, my Phing build files, Module B (faq system) or code/data/images for Client B.

I do not need to keep variations of a module or the basic application for individual clients. Everything is standard across the system, and it's only the deployment configuration/variation for each client which is unique.

I am happy to use GIT Submodules to keep some parts separate, if that helps.

Note that all my code is in PHP and I am happy to deploy solutions using PHP, Perl, Python or scripting, but I don't want to use Java on the destination server. Ideally I would like to avoid Ruby solutions, if possible. I have access to SSH on the client server and can use rsync over SSH as well, but I need to be able to execute a script on the client server to clean caches etc after an update.

My development machine is Windows - yes, unfortunate, but true. If I cannot achieve what I need on Windows then I will run CentOS/Fedora in VMWare.

This is not a multi-server deployment requiring simultaneous updating across a server farm, although it would be nice to be able push out updates of the application to all the various clients on a schedule or using a single command/procedure rather than having to do it manually for each one. I would also need to be able to push client specific updates to individual clients as and when required (for instance HTML or logo updates).

So, can I use GIT for deployment, or at least track the various configurations using branches? Or is it simply going to be too messy?

Can I hide Client B from Client A, including in commit history, in a particular branch, to make sure someone proficient with GIT at the client's organization cannot retrieve code they mustn't see (and this is a contractual requirement of the project)? If so, how do I do this in GIT?

If not, how can I best manage a build process that allows me to deploy client specific configurations? Note that initially I will be managing around 20 different clients, and this might grow to 100 or more different configurations as each one will include their own HTML and logos, and a variation based on a potentially unique selection of 15-20 modules.

I am happy to maintain a hundred different XML configuration files if that's what it takes. I am aware of Capistrano, but from reading about it, it doesn't seem that suitable for my specific case. If you feel otherwise, please do feel free to state so.

答:
This is not a Git-specific answer, but it should work regardless of the VCS system you use.

I would start with several different repositories

One for each client, containing the client-specific files and a configuration file stating which options the client has purchased

One or more repositories with the development code

Then I would use a make_release script (written in your favourite scripting language) that does the following:

Given the name of the client, checkout that client's repository to a temporary location

Based on the purchased options, checkout or copy (from an existing checkout) the application and modules to the same location

Remove all files/directories that are not relevant for the client (especially those that contain data meant for the VCS system)

Package the release in a convenient format (e.g. zip or tar.gz)

Then deployment should be as simple as copying the release to the client's server, unpacking it and running whatever scripts that are needed to finish the installation/upgrade.


问:
Can someone else patent my open-sourced algorithm?
I've written a recursive search algorithm to find the boundaries of a voxel data structure in order to render it more efficiently. I've looked around, and either it's such a simple and obvious technique that nobody's bothered to patent it, or it's novel and nobody's done it this way before.

It's openly "published" on GitHub and protected under the GPL. I'd like to show it to others, to see if it can be improved, however...

I fear that although I've written and published it, someone may attempt to patent the same idea.

Am I safe, protected by the banners of open source software, or must I attempt to protect myself like the big guns and patent trolls do?

It's my belief that software patents are evil, and that in order for the best software to be written, many eyes need to see it. I'm worried this may be a rather naïve viewpoint on how software is written, though, and I'm curious as to what others think.

答:
Having read @akton's answer, it is important to recognize how software patents are playing out at the moment.

While it shouldn't happen, a lot of bad software-related patents get issued in the United States.  Patents with overly broad or indefinite claims, patents that where there is clear prior art, and patents that are blatantly obvious.  The problem is that the US Patent Office is not diligent enough, and the appeals court is too patent-holder friendly, and jury trials are a lottery because most jurors are technically clueless.

So how is this relevant to the Question?

Well the problem is that publishing your algorithm as source code on Github won't prevent someone from applying for a patent on it.  It is then up to the patent examiner assigned to the application decide whether to grant the patent.  The chances are that the examiner won't find your work for various reasons:

Searching for algorithms is hard.

Reading through reams of source code to try to understand an algorithm takes a lot of time.

Deciding that two algorithms are similar is hard, especially if one is couched in language that is designed to obfuscate rather than reveal.

Patent examiners don't have lots of time to spend on each patent.

So if the examiner then decides that the patent is sufficiently novel relative to the (other) prior art presented / found, and so on, the patent could get issued ... despite your prior art.

What can you do about this?  Not a lot!  However, it is still better if you do publish the algorithm, etc.  Because if you don't, there won't be the evidence of prior art to help get the bad patent overturned.


问:
How to implement a hybrid role-based access control model?
I am writing an enterprise web-forms-frontend application for in-house use. It has Direct access control (DAC) masquerading as Role-based access control (RBAC).

For anonymization purposes, let's call the main unit of information stored in my application a Document, and the roles in the company a Boss, a Grunt and a C-level executive. There are also Externals (e.g. somebody working for a business partner of ours). The general guideline is that everybody but externals should be able to read all documents, C-level execs can write everything, Bosses can write the Documents belonging to their own department, and Grunts can only write Documents personally assigned to them. Fairly standard thus far.

But what users actually want is that they can make arbitrary exceptions to the above. They want that any person in the system can be granted write access to any Document, and that Externals can be granted Read access to any document. (Actually, it is more complicated than that, with more roles and finer granularity of permissions, including management of who can propagate which permission to others, but the above description illustrates the core of the problem well enough). So what I have is basically permissions on a personal level, and the roles are only a convenient way of having default settings for the personal-level permissions when a user or a Document is added to the system, instead of having somebody fill out a whole row or column in an access control matrix by hand.

Now I have already designed a Permissions table in my database, which has a User FK, Document FK and columns for the different types of permissions. What I am not sure is what I should save in the table.

Alternative 1: I save all permissions in this table (pure DAC) and have the logic tier mimic a RBAC. E.g. when a new Boss is added, a row for each Document in the system is added to the DB, with Read permissions for all documents and Write for the Documents of her department.

Alternative 2: I save the deviations from the role guidelines only. So when a new Boss is added, nothing is written to the permissions table. But when an executive gives a Boss the rights to write to a Document from a different department, then a single row is added to reflect that information.

I am not sure which alternative would be better. The first one feels closer to textbook implementation, and if a principle has made it into a textbook, then there is normally good reason to use it. But in my case, it also hurts the DRY principle - after all, if the information that a C-level exec can write to Document X is derivable from his role, writing a row with this information in the DB is redundant.

What are the advantages and disadvantages of each approach in terms of a) application performance and b) complexity of implementation? What headaches can I expect from each?

Keep in mind that 1) I don't plan to implement a full logic tier. The whole application is practically a convenient CRUD frontend to a database, so I will be doing DB queries for each page view instead of keeping a collection of Document objects in memory. (I know the advantages of a MVC pattern, but it was decided that it will be overkill for this project). 2) I am programming this in ASP .NET 4.5, so the closer I stay to roles, the more I can let the framework do the heavy lifting for me. 3) I have thought of implementing groups orthogonal to the roles to manage access, but it doesn't make sense in my case.

答:
User permissions

If you had full permissions information for each user entry in your database, you'd have the advantage of simplicity.  You want to know the permissions of user X, load permissions for user X.  The advantage is in the work you'd have to do.  It's also true that it would use more database space, but I consider that a minor disadvantage that isn't really worth mentioning.

If your client was happy micromanaging the permissions of each individual user, this is ideal.  You yourself do not have to manage the permissions, and at the same time, you allow full control to your client.

The problem comes in when the client starts complaining about having too many users to change.  The sensible solution at this point is to give users group permissions, but modifying your current model in order to allow for groups is somewhat of a nightmare.  Not to mention that updating the permissions of a group means batch updating all users with that group.  It quickly becomes unmanageable and there is no easy way to switch permissions model.

Role permissions

I would advise you to use a role-based system.  Instead of holding all permissions for every user, have a user record point to a permissions group or NULL.  If it is NULL, have a default (undeletable) permission group that a user will inherit from if none is specified.  Clients modify a permission group directly (including the default permissions group) or the permission group that a user points to, but they remain separate entities.  In this way, they have all the individual control they had before, creating permission groups for single users if they desire it, but they can also make blanket permissions and simply assign users to it.

You could argue that it is slower to load, but if you make a point to cache permissions, it will only be slow in the first load.  The only true disadvantage to this approach is that it is a little trickier to implement with respect to the first approach, but considering the headaches you'd have trying to implement the second approach after already having used the first approach makes it worthwhile in my humble opinion.


问:
How do you debug without an IDE?
Every time I look for an IDE (currently i'm tinkering with Go), I find a thread full of people recommending Vi, Emacs, Notepad++ etc.

I've never done any development outside of an IDE; I guess I've been spoiled. How do you debug without an IDE? Are you limited to just logging?

答:
There's no reason why you can't use the debugger in an IDE alongside a standalone text editor. I used to use !Zap to edit, JBuilder to debug on another machine, and a fileserver in the basement. Traditionally debuggers were standalone programs without dragging along an IDE, and that works too.

It is worth noticing that comprehensive testing displaces debugging. It is worthwhile considering a reported bug to be a bug in your testing rather than in your code.

There's also printf. It can be useful to create a large amount of "logging" and search through it, rather than stopping for every line. I find particularly useful if you can modify library classes that you wouldn't be able to modify in production, for instance using -Xbootclasspath/p: to hack Java library classes.

Title: How do you debug without an IDE?


问:
Building dedicated codepad in PHP
I am author of growing framework, which is focused around User Interface building in PHP. Essential requirements for the up-coming website redesign is ability to run code examples. I am willing to extend this option to add-on authors which would mean other people will be able to execute code on my server.

Please suggest how to securely set up the environment which would allow me execute 3rd party PHP code built on my framework. I'd like to hear ideas from someone who have had experience with building sandboxed solutions.

答:
I don't have experience in sandboxing environments, but here are my 2 cents:

I worked on Google App Engine, both Java and Python, and GAE have their own sandboxed environment. Speaking of allowing users to run code, pranks/evil users might either try to abuse your server programmatically or can do illegal transactions(via http calls) from your server. I also do not have much knowledge in PHP, so pardon me for any bad assumptions.

Abusing your server:

CPU: They could write a never ending for-loop that just consumes your CPU. They could write code with high CPU usage.

Memory: They could write code creating objects in memory and not freeing them.

What Google does:

They have a 30 second limit to process the request, after 30 seconds, they kill the thread.

They mention in TOS that they can take down the app if it is consuming higher CPU. Perhaps they have automated triggers that show apps not using CPU efficiently.

What you could do:

Limit the code execution time, say 10 or 15 seconds(or even lesser) depending on your use cases.

As the program runs, record the CPU stats of each program execution(with user name) and flag those users who are running inefficient code frequently and issue a warning/ban them.

I'm guessing you'd start each user submitted code in a new process, limit the memory of that program, say 32 MB. Choose the number depending on the need.

Illegal network activity:

They could send email/hit servers to scrape data. It is illegal to scrape content of several sites.

If doing HTTP requests is out of scope in your context, figure out a way to disable any HTTP request code. If you NEED to provide this functionality, then I guess you will have to monitor the bandwidth consumed by each user running their programs. Any one using beyond a few KB(since they don't download media like browsers do) is questionable. I can think of another alternative for this case, which I think is feasible. I will discuss it anyway - The solution requires Javascript: from the submitted code, filter out the HTTP requests, perform the HTTP requests from the code submitter's browser itself(using JavaScript, of course), once you get the response, submit the code and the response to your server for processing. Eliminates your server out of the external HTTP requests equation. However, you will really need to block network requests from the process on your server side also.

Hope this helps.

PS: For some reason, I believe this question belongs on Stackoverflow. Have your tried there?

Title: Building dedicated codepad in PHP


答: Some languages offer a REPL - that is, you can write and execute code line by line as you write it, which can be a first step in verifying a piece of code.  Many of these also offer debugging facilities.  The GHC for Haskell comes with GHCi which can be used to interactively debug a program in the command line, similar to how an IDE would do.</p>

Title: How do you debug without an IDE?


问:
Application protocols and state machines: designing a complicated server
I'm designing and prototyping a server that has the following characteristics:

during the daemon's initialization it spawns nine "manager" servers, each of which solves one part of the overall problem.

after initialization, the daemon accepts connections from clients, forking a "slave" server for each which connects to the managers and then accepts requests from the client, farms them out to the managers, assembles the results, and sends them back to the client, ad infinitum.

the daemon, the managers, and the slaves all should have the ability to concurrently accept "control" connections from a terminal, and receive and process commands (e.g. queries for performance stats).

the concurrency of each process's socket I/O is being managed by select().

The problem I'm having is the complexity of the coding.   For one thing, each program has at least two phases - initialization and main loop - in which it is variously establishing a connection to its parent, or accepting a connections from its children, or sending and asynchronously awaiting data from its children, and so on.  At various points I don't want, say, to accept a client connection while I'm initializing, or I do want to accept control sessions even in the midst of regular processing.  Not to mention managing the protocol of each such connection.

Given enough time, I could probably massage all of this into a reasonably well-factored set of subroutine calls.  But I remember having heard of an entirely different approach to this sort of problem, involving libevent, callbacks, and finite state machines.

What I'm hoping is that someone reading this might say "Why, yes!  That's a perfect example of where event callbacks and FSMs are far superior to looping on select()s - and a great introductory article about this is ..." or "here's what it's all about in a nutshell."  (Or, possibly, "that's not what libevent is intended for, at all.")

答:
There are no silver bullets in design or architecture.  ( Sorry )

It sounds like you're still at the beginnings of the Design phase and I think you need to focus more on the "divide and conquer" aspects of mapping out your application.  Rushing into the lower level details before you have a comprehensive design means you may miss otherwise "obvious" opportunities for particular techniques.  Comprehensive doesn't mean final it just means that you've got all of the major components and their interactions laid out in a general form.  In other words, you've got to know where you're trying to go before you can get there.

Once you've mapped out the major requirements of your daemon, managers, and processors (slaves) then you should start examining what requirements / functions are allowed at what stages.  This will lead into your state definitions, and those states should help refine the scope of the program.

You should also be able to identify the common components based upon the functions and requirements.  Combined with the state definitions from before, you can determine when common components can be called and with what parameters.  Again, this should help scope down the size of your program.

It's at this point that you can consider queues, callbacks, etc... based upon what your design calls for the program to be doing.  Prototype some and then come back and refine the design.


答:
Not nearly enough...

Belatedly - its hard to quantify, it can't be a hard number because there are too many other variables but it should be sufficient to have a measurable achievement every week and I'm certainly not doing that.

Title: How much time a week do you spend on extracurricular programming?

Body:
Background: I'm a microsoft DBA/IT type person by day, an iOS and Mac developer by night. I have one app in the App Store and another one in the works. I try to spend as much time as possible working on my two apps, but with a new daughter and other (non computer) hobbies, I find it hard to spend more than a few hours every week programming.

I'm wondering how this compares to other developers. I see a lot of apps out there written by single developers who don't do iOS development as their main job. Are they spending 4 hours a night working on their projects, or do they just plug away for a year or two before releasing anything?


问:
Can notes/to-dos in code comments sent to code-reviews result in an effective refactoring process?
I want to start/improve a culture of collective code ownership at my company but at a geographically distributed level... I'd say there is some current collective code-ownership mentality, but only at single geographical sites.

This is a follow-up to this question: What is the politically correct way of refactoring other's code?

I'm just wondering if submitting *just code comments* for code reviews (we have ReviewBoard, possibly upgrading to Crucible) could actually be an effective mechanism to get the conversation started on improving code, without having others feel territorial about their code.

For example, if I add:

```<code>//ToDo: Refactor this code and that code because of reasons X and Y
</code>```

Then, submit it for code review, and it gets accepted... it could be considered as an agreement (which I think is sometimes harder to get with new code up front). At the same time, the author (and others) might have an easier time digesting and accepting the proposal; rejecting a proposal because it might break things will not longer be a valid reason and therefore the fear of making a change is lost... and at the same time, do not invest 10 hours optimizing something that no one thinks it is worth it and opposes to it just out of fear.

This is all conjecture, but I'm feeling something like this (submitting refactoring notes in code comments at the code-review process) would work. Has anyone done something like this in practice?, if so, what have been the results?

答:
I have experienced, that comments alone will change nothing. If the programmers do not talk at all - except through code-commentary - something is wrong. Just adding a //Todo now and then will not solve you problem, it might even make them worse. For example if someone feels offended.

If you find something that is worth refactoring (and you're sure you totally understand the piece of code AND the impact on the existing program, then just do it.
If you do not think you have an absolute understanding of the code (this might be the reason you want to refactor in the first place), try to make contact with the initial developer. Involve him in the process, discuss what you can do, and i'm sure he will be a valuable partner through the whole process of refactoring.


问:
Temporary variables vs line length requirements
I've been reading Martin Fowler's Refactoring. It is generally excellent but one of Fowler's recommendations seems to be causing a little trouble.

Fowler recommends that you replace temporary variables with a query, so instead of this:

```<code>double getPrice() {
    final int basePrice = _quantity * _itemPrice;
    final double discountFactor;
    if (basePrice > 1000) discountFactor = 0.95;
    else discountFactor = 0.98;
    return basePrice * discountFactor;
}
</code>```

you pull out into a helper method:

```<code>double basePrice() {
    return _quantity * _itemPrice;
}

double getPrice() {
    final double discountFactor;
    if (basePrice() > 1000) discountFactor = 0.95;
    else discountFactor = 0.98;
    return basePrice() * discountFactor;
}
</code>```

In general I agree except that one reason I use temporary variables is when a line is too long. For example:

```<code>$host = 'https://api.twilio.com';
$uri = "$host/2010-04-01/Accounts/$accountSid/Usage/Records/AllTime";
$response = Api::makeRequest($uri);
</code>```

If I tried inlining that, the line would go longer than 80 characters.

Alternately I end up with chains of code, which are themselves not that much easier to read:

```<code>$params = MustacheOptions::build(self::flattenParams($bagcheck->getParams()));
</code>```

What are some strategies for reconciling the two?

答:
I think, the best argument for using helper methods instead of temporary variables is the human readability. If you, as a human, have more trouble reading the helper-method-chain than the temporary varialbe, i see no reason why you should extract them.

(please correct me if i'm wrong)


问:
What are some famous one-liner or two-liner programs and equations?
I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

```<code>#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}
</code>```

60 characters exactly!

Thanks so much for your wisdom!

答:
Duff's Device:

```<code>void send(short *to, short *from, int count)
{
    int n = (count +7 ) / 8;

    switch (count % 8) {
    case 0: do {    *to = *from++;
    case 7:         *to = *from++;
    case 6:         *to = *from++;
    case 5:         *to = *from++;
    case 4:         *to = *from++;
    case 3:         *to = *from++;
    case 2:         *to = *from++;
    case 1:         *to = *from++;
        } while(--n > 0);
    }
}
</code>```

Tom Duff unrolled a memory-mapped port write into one of the most bizarre C constructs the world has seen.

Body:
Duff's Device:

void send(short *to, short *from, int count)
{
    int n = (count +7 ) / 8;

    switch (count % 8) {
    case 0: do {    *to = *from++;
    case 7:         *to = *from++;
    case 6:         *to = *from++;
    case 5:         *to = *from++;
    case 4:         *to = *from++;
    case 3:         *to = *from++;
    case 2:         *to = *from++;
    case 1:         *to = *from++;
        } while(--n > 0);
    }
}

Tom Duff unrolled a memory-mapped port write into one of the most bizarre C constructs the world has seen.