答:
In my experience, I have definitely encountered several bugs that have taken weeks or even months to get to the bottom of. Some types of bugs only pop up in debug vs. release or 32bit vs 64bit modes, and others rely are multi-threading race conditions that only appear at seemingly random times. I'd say generally lack of memory safety, shared-memory concurrency, and pervasive shared mutable state are the main culprits. Large numbers of interacting components, especially third-party ones, also worsen the problem. That's why people are so religious about so-called "decoupled" and "composable" software designs - if each component works and can be tested independently, then the number of possible interactions (and thus the number of possible bugs) increases linearly with the size of the software, rather than exponentially.

One of my favorites was a bug that only appeared to some users, only in released versions of the software: occasionally when scrolling the mouse in a specific grid component, there would be a mysterious unhandled "ArithmeticOverflowException".

We figured it out months later - the developers would run/code/debug the program in 32bit mode, to provide edit-and-continue in Visual Studio. The bug would only occur in 64bit mode, and only when someone scrolled the mouse extremely fast on that particular grid...

It turned out that grid component (3rd party) was looking at a certain window message to handle scroll wheel events, and casting the 64bit integer to a 32bit one because most window messages stored nothing important in the upper 32 bits. If a user scrolled very fast, to avoid flooding the message pump with lots of individual "SCROLL" messages, Windows would "batch" the messages and use part of the upper 32bits of the message to record the number of scroll wheel clicks per batch. Casting that to a 32bit integer resulted in an overflow. Since this was in a 3rd party component, we only figured out the cause months later when doing some message-pump hackery of our own and hitting the same exception.

So that's one bug from my own experience that definitely qualifies as pesky.

Title: Pesky bugs - nonexistant?

Body:
Very short introduction (this is quite a context-heavy question):

I'm a 17 year old programmer, doing some projects, usually netting around 20 files of 200 lines each. I usually don't program very low-level, more high-level with battery included API's like Python + pygame and Lua + WoW API. Nevertheless I've written quite some code in the lower levels of the computer too (mostly C/C++).

Now, I read a lot of programmer discussion and a common returning argument is preventing pesky bugs, for example in "reusing variable names". I always nodded and thought that it was a valid argument, but just now I wondered, how valid is it?

To be honest, after thinking for a while, I figured I have no idea what they mean with pesky bugs. We all heard stories about phenomenal impossible-to-debug bugs, we all have spent useless evenings on that one annoying bug, but apart from a few cases I have never been busy with a programming-related bug for longer than a few hours.

Though on the other hand, the projects I work(ed) on aren't huge 10 million line projects like the linux kernel, and are quite simple... scripts. I have a good understanding of them (or at least my part in collaborations) and are not very error-prone.

So I'm wondering, do these pesky bugs occur exponentially more as the amount of code increases, or ...?


问:
Pesky bugs - nonexistant?
Very short introduction (this is quite a context-heavy question):

I'm a 17 year old programmer, doing some projects, usually netting around 20 files of 200 lines each. I usually don't program very low-level, more high-level with battery included API's like Python + pygame and Lua + WoW API. Nevertheless I've written quite some code in the lower levels of the computer too (mostly C/C++).

Now, I read a lot of programmer discussion and a common returning argument is preventing pesky bugs, for example in "reusing variable names". I always nodded and thought that it was a valid argument, but just now I wondered, how valid is it?

To be honest, after thinking for a while, I figured I have no idea what they mean with pesky bugs. We all heard stories about phenomenal impossible-to-debug bugs, we all have spent useless evenings on that one annoying bug, but apart from a few cases I have never been busy with a programming-related bug for longer than a few hours.

Though on the other hand, the projects I work(ed) on aren't huge 10 million line projects like the linux kernel, and are quite simple... scripts. I have a good understanding of them (or at least my part in collaborations) and are not very error-prone.

So I'm wondering, do these pesky bugs occur exponentially more as the amount of code increases, or ...?

答:
Pesky bugs do increase in occurrence when the number of lines of code goes up.

Unless you do good OOD and define plenty of abstractions (which is very possible but not practiced by everyone), increasing the amount of code will make the complexity of that code go up. Every time you modify it, you will need to remember everything you did before AND now you'll have more info to store in your head.

Increased amount of code means that certain parts of your program may not be touched for months.  In a few years from now you might even realize that some products run with code that hasn't been touched by anyone for years. But if you have to modify it, you need to remember (or figure out) how it works.

When LOC goes up, you start having more than one person on a project. Now the other person needs to remember what the original author was thinking. If you don't, maybe you'll call a function that has some bad concequences.  Try remembering something you haven't written in the first place.

As your code base increases and so does functionality of your app, you start using more third party APIs (well, you should anyway).  As more and more ends up dependent on third-party building blocks, sometimes bugs will surface because integration between your code and theirs may not always be smooth.  Maybe their side is buggy, maybe you misunderstood the documentation.

All good practices, that you've been reading about and nodding, are there to take the memory element as much as possible out of the equation. When the code is clear to read and understand.  When it flows logically and there's no hidden/secret meanings and shortcuts, there's less chance of screwing up an existing application.

To give you an example, in my first job, when I was working on the code that was creating tape archives, I found a line of code at the end of one of the functions, ReadTapeDirectory().  I knew what that method did, I worked with it before and I just assumed it was some copy/paste that someone forgot to remove.  I deleted the line and weeks later when someone went to work with tapes, we realized that all archives were completely empty.  Come to find out ReadTapeDirectory() was moving the tape position to the proper spot, and without it the entire archival process was broken.  Obviously, if a previous developer followed good practices advice that you read over and over, he would've named the function something like ResetTapePosition() and then in the spirit of DRY principle refactored ReadTapeDirectory() into smaller pieces.  As you start working with other people, you'll be amazed how many of these examples (unclear naming with easy fix; not corrupted tapes) you will run into on daily basis.

So is it that important to make sure you always use your variables once? No, it's not.  But neither are so many of other best practices (well... some are actually kinda important).  But my point is that you develop a skill of writing clear code and when you put all these things together, it makes a huge difference between readable/extendable code and a can of worms in which it takes 3 days just to add one menu item.  And at the end of the day, all the good practices in the world still don't eliminate those pesky bugs, they just minimize the chances of them happening.

ContentLicense: CC BY-SA 3.0

Title: Pesky bugs - nonexistant?


问:
PCI Compliance, FDMS and TransArmor
So, I've been tasked to work on an integration project where we will ask customers for credit card information and send it over to our integration partners, who will process the payment/cc info and process the rest of the order. So, one the tasks for  become PCI compliant. However, the partner is also looking to get PCI compliant, and they said that as part of that process, they cannot accept cc info over the internet from an external source. But then I was reading about it, and found out there is some way to become a TPA (Third Party Accepter) that can allow the passing of the credit card to the partner.

I also heard the word FDMS thrown around at the first meeting - some research led me to believe this stands for First Data Merchant Services. What I found is that First Data is a merchant processor, who actually contacts the issuing banks to check the credit cards and then collect payment. The partner wants to achieve a level of PCI compliance where they do not store credit cards, so they said when they take credit cards they will send it to FDMS using something called TransArmor, where they send the CC info to FDMS and they send back a token - and that is what they use to access the CC info.

I did my research on this, and there is a lot of information out there, and I cannot find a clear and concise place where I can read about all of this - so I have a few questions on this whole process:

Is there one place where I can read what exactly it takes to become PCI compliant?

Are there different levels of PCI compliance?

Where exactly does TPA fall into all this?

Is there an example of how TransArmor works?

答:
We are going through a similar process right now trying to meet PCI compliance.  Our situation is a little different though as we already deal with a Merchant Processor (CyberSource) and they are fining us something like $50/month for not meeting PCI compliance standards.  We are very close though.

Becoming PCI compliant is actually pretty straightforward as long as you delegate payments to a Merchant Processor like TransArmor.  They handle all of the complexity of dealing with card services, banks, storing credit card numbers, and crediting your bank account.  They are PCI compliant as well but their standards are MUCH stricter and MUCH more involved than yours will be.  In turn for doing business with them they will take a small cut of every transaction.

The most important thing you can do is make sure you do NOT store credit card numbers anywhere on your system!  Your site is external facing so SSL encryption and proper user account authentication, password hashing, and user activity logging is a given.  A user will submit credit card details through your site and your server will simply be a middle man to your payment processor.

At the server side you will call an SSL encrypted web service hosted by TransArmor that will actually store the CC details for the user and they will return a token that you can associate with the users payment on your side.  This token is low risk, and is essentially useless to a potential hacker that may have compromised your system.

Next you have to make sure that the web server(s) have highly restrictive firewall lockdown, even from sources internal to your network.  Port 443 must be available outside for web traffic and you need a port open for communication with TransArmor but thats it.  File sharing shouldn't be allowed and RDP is to be highly restricted with clearly defined users that are allowed remote access to the server (this is a fuzzy area for me and one we are still trying to figure out).

Other external factors can make you non compliant as well, (Eg. Physically insecure data center where server is hosted, anything other than WPA encrypted wireless access points ANYWHERE within your internal network, etc...)

The best answer I can give you is to start talks with TransArmor because it is in their direct interest to assist you in becoming PCI compliant and most merchant processors are extremely helpful on this front.  Most have sophisticated tools that you can run within your network and on your server to help you identify where you are non compliant and what you need to do to become compliant.  Cybersource assisted us with a checklist that we were able to step through and help identify tasks that we needed to perform to become PCI compliant.

Good luck in your project.

Title: PCI Compliance, FDMS and TransArmor


问:
Other than for legacy software, are there reasons for using COBOL?
COBOL is still (heavily?) used for financial computing. It is an old language, and AFAIK most programmers hate, or at least dislike, COBOL. This brings a question: is the only reason COBOL is still used that legacy software uses it, or does it have any real advantages over other programming languages?

Just curious.

答:
With 20 years of COBOL experience, on three different mainframes, it is my humble opinion there are few true COBOL programmers and instead there are IBM programmers, Sperry (Unisys 2200) programmers, Burroughs (Unisys MCP) programmers, and Tandem (HP NonStop) programmers.  In a showing of respect to them, I must also mention the presence of HP 3000 programmers, BULL programmers, and DEC programmers.

COBOL runs on big iron boxes, for the most part.  Perhaps the only true COBOL programmers, by my own standards, are those writing COBOL on a UNIX box.  Wow, I am going to hear about this.

Because the hardware is the central piece, most programmers who write COBOL identify themselves by the hardware on which the code they write runs.  Over the years, listening to other programmers tell me about the merits of Sperry, Burroughs, or Tandem, I have often wondered what kind of warfare would ensue if I were to round them up and place them in a room together unable to leave until they agreed upon one hardware platform for all COBOL.  I did not mention the other platforms because I have never worked on them.

I have met and talked with many IBM programmers, and they will refer to themselves as COBOL programmers.  However, if one engages them in conversation, they quickly begin referring to IBM specific procedures and tools.  Given the hardware-centric nature of COBOL, this is very understandable, for all hardware platforms.

Because COBOL is usually tied to a very expensive piece of hardware, as long as that piece of hardware runs the COBOL programs compiled on it then there is no strong desire to migrate from COBOL for migration’s sake.  However, with an aging population of COBOL programmers, migration is inevitable.

Since all of the big iron boxes running COBOL will also run Java, Java is the natural path of migration away from COBOL.  Code can be converted, particularly now in a down economy, for a rather economical price.  Once there is no COBOL, only Java, on that big expensive piece of hardware, then someone higher up in the organization is going to start wondering whether it is possible to move the Java code over to some other much less expensive piece of hardware.

IBM, Sperry, Burroughs, and Tandem programmers know this, so they will likely NEVER offer up the idea.  It would be a sacrilege for some.

ContentLicense: CC BY-SA 2.5


问:
When do you drop old technologies from your resume?
I have been reviewing several resumes we have for a new position.  I noticed that a few of them had many old programming language versions and old applications on their resume (e.g. SQL 4.2, VB5, Lotus 123, Novell).  This left their list of computer experience very long.  Do you keep it fresh?  Do you show your depth of experience even though you will never use that techology again?

When should you drop old technology on your resume?  By keeping old technology on your resume does that do any harm in getting hired?

答:
On the specific issue of harm, remember that a person reviewing a resume may only have 15-20 seconds to review your resume before deciding whether to toss it in the “No” pile or the “Maybe” pile.

If you make the “Maybe” pile, then your resume will get a longer more detailed read—perhaps a full minute.  From here, your resume will again be sorted into either the “No” pile or the “Maybe” pile.

If you make this second “Maybe” pile, then you will likely be called for an interview.

If you have something on your resume that is deemed old, it probably depends upon where it is on your resume.

If the old technology is listed say at the top of your resume, in a bulleted list of keywords, then it could be extra “fluff” reading that increases your chances of going into the “No” pile.

If the old technology is listed in the chronological portion of your resume, back when you worked for WidgetMaster Inc. in the mid 1990s, then it could actually be helpful since it shows the technology you were using in that position.  Consistent use of technology keywords under each employer can show a progression of skills.


问:
Why declare final variables inside methods?
Studying some classes of Android, I realized that most of the variables of methods
are declared as final.

Example code taken from the class android.widget.ListView:

```<code>/**
* @return Whether the list needs to show the top fading edge
*/
private boolean showingTopFadingEdge() {
    final int listTop = mScrollY + mListPadding.top;
    return (mFirstPosition > 0) || (getChildAt(0).getTop() > listTop);
}

/**
 * @return Whether the list needs to show the bottom fading edge
 */
private boolean showingBottomFadingEdge() {
    final int childCount = getChildCount();
    final int bottomOfBottomChild = getChildAt(childCount - 1).getBottom();
    final int lastVisiblePosition = mFirstPosition + childCount - 1;
    final int listBottom = mScrollY + getHeight() - mListPadding.bottom;
    return (lastVisiblePosition < mItemCount - 1)
                     || (bottomOfBottomChild < listBottom);
}
</code>```

What is the intention of using the final keyword in these cases?

答: Honestly, I don't think there would be a real reason to make a variable final in this context. I suppose they either copy and pasted the code, or they just really want to discourage anyone who adds more code to that method from making reassignments to those variables.</p>


问:
How to flag a class as under development in Java
I'm working on a internship project, but I have to leave before I can finish up everything.

I have 1 class that is not stable enough for production use. I want to mark/flag this class so that other people will not accidentally use it in production. I have already put the notice in Javadoc, but that doesn't seem enough. Some compiler error or warning would be better.

The code is organized like this:

```<code>[Package] | company.foo.bar.myproject
          |-- Class1.java
          |-- Class2.java
          |-- Class3.java <--(not stable)
</code>```

If there was a single factory class that calls those classes in public methods, I could have set the method to class3 as private. However the API is NOT exposed that way. Users will directly use those class, e.g. new Class1();, but I can't make a top-level class private. What's the best practice to deal with this situation?

答: I'd opt for making the class abstract, and commenting appropriately - that way, the code is still there for reference, but good luck to anyone who tries to instantiate it :)</p>


问:
Why should I know concurrent programming?
Concurrent programming is quite difficult to me: even looking at a basic slide seems challenging to me. It seems so abstract. </p>

<p>What are the benefits to knowing Concurrent programming concepts well? Will it help me in regular, sequential programming? I know there is a satisfaction to understanding how our programs work, but what else? </p>

答: If you do any sort of web development, concurrency comes into play, at least with most languages. For example, I use spring for web development and each new request comes in as its own thread. Therefore, if any request ends up accessing a shared object, where the state can be changed of a variable, concurrency is very much a factor and has to be taken into consideration. If its not, then the data can be edited in unpredictable ways and data corruption can result. Its not critical to know every last detail about concurrency but learning pieces at a time is important to better understand web app programming, if you are working on desktop apps, maybe its not so important unless you need to run multiple threads</p>


问:
Have objects delivered in terms of code reuse?
I have often heard it said that objects have not delivered in terms of code reuse. Do you agree? If you believe that they haven't, why not?</p>

答: Yes, they do, the ability to extend (inherit) from a super class cleary contributes to code re-use, I am not sure how anyone could argue otherwise. You can simply extend a class and override one method, while using the rest from the super class, if this isn't aiding in code re-use then I don't know what is</p>


问:
Are there any jobs in the programming field that don't require you to sit at a desk all day?
I'm new in the field of programming. I really enjoy it as a career, but I'm not sure I can handle sitting at a desk for eight hours a day. I don't mind it for short stretches of time of course, but I can't do it day in and day out.

Is there a field of programming that possibly has jobs that require less time spent at the desk?

答:
Well, at my workplace we now have two developers who stand all day while working. They raised their desks (it's the cubicle kind you can slide up and down on the wall) and they stand while working. I am serious, and I can kind of relate although I sit down while working.

Some people like to be up standing and moving around a bit more while they work, so it's up to you. No one is going to say you have to sit at a desk, but generally you do have to use a computer for much of the day, unless you're a manager; then you go sit in meetings all day.


答:
We can't know the answer for sure (unless we ask the original developers), but my guesses are:

The programmers of these methods may have felt that adding "final" better expresses the purpose of those variables.

The programmers may be using a tool that automatically add "final" where it can.

It could be an optimisation trick: I don't have the knowledge / tools to verify this myself, but would be interested to know either way.

Title: Why declare final variables inside methods?

Body:
Studying some classes of Android, I realized that most of the variables of methods
are declared as final.

Example code taken from the class android.widget.ListView:

```<code>/**
* @return Whether the list needs to show the top fading edge
*/
private boolean showingTopFadingEdge() {
    final int listTop = mScrollY + mListPadding.top;
    return (mFirstPosition > 0) || (getChildAt(0).getTop() > listTop);
}

/**
 * @return Whether the list needs to show the bottom fading edge
 */
private boolean showingBottomFadingEdge() {
    final int childCount = getChildCount();
    final int bottomOfBottomChild = getChildAt(childCount - 1).getBottom();
    final int lastVisiblePosition = mFirstPosition + childCount - 1;
    final int listBottom = mScrollY + getHeight() - mListPadding.bottom;
    return (lastVisiblePosition < mItemCount - 1)
                     || (bottomOfBottomChild < listBottom);
}
</code>```

What is the intention of using the final keyword in these cases?


答:
I would say that this is due to force of habit. The programmer that wrote this code knew as he was writing it that the values for the final variables should never be changed after assignment, and so made them final. Any attempt to assign a new value to a final variable after assignment will result in a compiler error.

As habits go, it's not a bad one to develop. At the least, making a variable final specifies the intent of the programmer at the time of writing. This is important as it might give subsequent programmers who edit the code pause for thought before they start changing how that variable is used.


问:
Why are weakly-typed languages still being actively developed?
I wonder why are weakly-typed languages still being actively developed. For example, what benefit can one draw from being able to write

```<code>$someVar = 1;
(...)  // Some piece of code
$someVar = 'SomeText';
</code>```

instead of using the much different, stongly-typed version

```<code>int someInt = 1;
(...)
string SomeString = 'SomeText';
</code>```

It is true that you need to declare an aditional variable in the second example, but does that really hurt? Shouldn't all languages strive to be strongly-typed since it enforces type-safety at compile time, thus avoiding some pitfalls in type-casting?

答:
Weak typing is more along the lines of 1 == "TRUE". This section on the wikipedia nicely illustrates the difference.

Please note that neither example from the wikipedia is statically typed, which is what you refer to in your second example.

So if the question is, why people use dynamically typed languages, then the answer is: static type systems put limitations on you. Many people simply have never worked with an expressive static type system, which leads them to the conclusion that the disadvantages of static typing outweigh the benefits.


答:
What about making a dependency that the compiler can't resolve? Just add:

import this.is.not.done.yet.do.not.use.it;

to the top.  Users won't be able to compile with it.

If you want to test out the class, simply create a package/class with that name (or use a simpler one like "experimental.danger") and you can test the new code.

Title: How to flag a class as under development in Java

Body:
I'm working on a internship project, but I have to leave before I can finish up everything.

I have 1 class that is not stable enough for production use. I want to mark/flag this class so that other people will not accidentally use it in production. I have already put the notice in Javadoc, but that doesn't seem enough. Some compiler error or warning would be better.

The code is organized like this:

```<code>[Package] | company.foo.bar.myproject
          |-- Class1.java
          |-- Class2.java
          |-- Class3.java <--(not stable)
</code>```

If there was a single factory class that calls those classes in public methods, I could have set the method to class3 as private. However the API is NOT exposed that way. Users will directly use those class, e.g. new Class1();, but I can't make a top-level class private. What's the best practice to deal with this situation?


答:
If you would excuse me, I am going to go sideways on this question.

The programming field is vast, and there are many different aspects, whatever the field.

My last two days (Thursday and Friday) were spent in a meeting room, with 6 to 12 other people depending on the current topic, while we worked out our new project.

I was sitted, but not at my desk. And I could also stand and get to the whiteboard from time to time.

Why ? Because I was not programming per se, we were discussing and planning. The discussion was heavily technical, and centered around programming, but all I had with me was a pad and a pen (and a bottle of water).

Programming does not necessarily means sitting at your desk pumping code out of your brains all day. Depending on the project / places and on your exact role, you might have more or less social interactions, and you might (or might not) travel more or get to meet customers.

For reference, I am (now) doing server programming, for internal applications.

Title: Are there any jobs in the programming field that don't require you to sit at a desk all day?

Body:
I'm new in the field of programming. I really enjoy it as a career, but I'm not sure I can handle sitting at a desk for eight hours a day. I don't mind it for short stretches of time of course, but I can't do it day in and day out.

Is there a field of programming that possibly has jobs that require less time spent at the desk?


答:
Strong / weak typing and static / dynamic typing are orthogonal.

Strong / weak is about whether the type of a value matters, functionally speaking. In a weakly-typed language, you can take two strings that happen to be filled with digits and perform integer addition on them; in a strongly-typed language, this is an error (unless you cast or convert the values to the correct types first). Strong / weak typing is not a black-and-white thing; most languages are neither 100% strict nor 100% weak.

Static / dynamic typing is about whether types bind to values or to identifiers. In a dynamically-typed language, you can assign any value to any variable, regardless of type; static typing defines a type for every identifier, and assigning from a different type is either an error, or it results in an implicit cast. Some languages take a hybrid approach, allowing for statically declared types as well as untyped identifiers ('variant'). There is also type inference, a mechanism where static typing is possible without explicitly declaring the type of everything, by having the compiler figure out the types (Haskell uses this extensively, C# exposes it through the var keyword).

Weak dynamic programming allows for a pragmatic approach; the language doesn't get in your way most of the time, but it won't step in when you're shooting yourself in the foot either. Strong static typing, by contrast, pushes the programmer to express certain expectations about values explicitly in the code, in a way that allows the compiler or interpreter to detect a class of errors. With a good type system, a programmer can define exactly what can and cannot be done to a value, and if, by accident, someone tries somethine undesired, the type system can often prevent it and show exactly where and why things go wrong.

Title: Why are weakly-typed languages still being actively developed?

Body:
I wonder why are weakly-typed languages still being actively developed. For example, what benefit can one draw from being able to write

```<code>$someVar = 1;
(...)  // Some piece of code
$someVar = 'SomeText';
</code>```

instead of using the much different, stongly-typed version

```<code>int someInt = 1;
(...)
string SomeString = 'SomeText';
</code>```

It is true that you need to declare an aditional variable in the second example, but does that really hurt? Shouldn't all languages strive to be strongly-typed since it enforces type-safety at compile time, thus avoiding some pitfalls in type-casting?


问:
Are there laws to protect us from hackers who disclose vulnerabilities prior to alerting the vendor?
Take the example of the recent ASP.NET (and Java Server Faces) vulnerability disclosure at a Hacker conference in Brazil.  It's my understanding that the poet tool was demonstrated before Microsoft was even aware of the issue.

Are there laws to protect legitimate customers from people who encite the hacker community to start hacking all the ASP.NET servers they can?  Who knows how many legitimate businesses were compromised between when the tool was demoed and the patch was applied to the server.

答:
Where would the laws apply? If the tool was demoed in Brazil, presumably it would have to be Brazilian law that is applied. So even if there was a U.S. law that protected companies, it wouldn't have helped because you can't prosecute someone in Brazil for violating a U.S. law.

You might be able to get a law like that passed in the U.S., and probably a few other countries as well (I'm sure you'd be able to get my country, Australia, to pass such as law as well, with a bit of lobbying). But good luck getting an equivalent one passed in China, Russia, or one of the many other countries where "hacking" is more prevalent anyway.


答:
Speaking as a Java developer who makes all variables final by default (and who appreciates the fact that Eclipse can do this automatically), I find it easier to reason about my program if variables are initialized once and never changed again.

For one thing, uninitialized variables are no longer any concern, because trying to use a final variable before it has been initialized will result in a compile error.  This is particularly useful for nested conditional logic, where I want to make sure that I covered all the cases:

```<code>final int result;
if (/* something */) {
  if (/* something else */) {
    result = 1;
  }
  else if (/* some other thing */) {
    result = 2;
  }
}
else {
  result = 3;
}
System.out.println(result);
</code>```

Did I cover all the cases?  (Hint: No.)  Sure enough, this code won't even compile.

One more thing: In general, any time you know that something is always true about a variable, you should try to get your language to enforce it.  We do this every day when we specify a variable's type, of course:  The language will ensure that values that are not of that type cannot be stored in that variable.  Likewise, if you know that a variable should not be reassigned because it already has the value that it should keep for the entire method, then you can get the language to enforce that restriction by declaring it final.

Lastly, there's the matter of habit.  Others have mentioned that this is a habit (+1 to Jon for that), but let me say something about why you would want this habit.  If you are declaring fields in your class and not local variables in a method, then it's possible for multiple threads to access those fields at the same time.  There are some obscure exceptions, but in general, if a field is final, then every thread that uses your class will see the same value for the variable.  Conversely, if a field is not final and multiple threads are using your class, you will need to worry about explicit synchronization  using synchronized blocks and/or classes from java.util.concurrent.  Synchronization is possible, but programming is hard enough already. ;-)  So, if you just declare everything final out of habit, then many of your fields will be final and you'll spend as little time as possible worrying about synchronization and concurrency-related bugs.

For more on this habit, check out the "Minimize Mutability" tip in Joshua Bloch's Effective Java.

Edit: @Peter Taylor has pointed out that the example above would also not compile if the final keyword is removed, which is completely correct.  When I advised in favor of keeping all local variables final, it's because I wanted to make examples like the following one impossible:

```<code>int result = 0;

// OK, time to cover all the cases!
if (/* something */) {
  if (/* something else */) {
    result = 1;
  }
  else if (/* some other thing */) {
    result = 2;
  }
  // Whoops, missed an "else" here. Too bad.
}
else {
  result = 3;
}
System.out.println(result);  // Works fine!
</code>```

Using a new variable instead of reusing an old one is how I can tell the compiler that trying to cover the complete universe of possibilities, and using final variables forces me to use a new variable instead of recycling an old one.

Another valid complaint about this example is that you should avoid complex nested conditional logic in the first place.  That's true, of course, precisely because it's hard to make sure you covered all the cases in the way that you intended.  However, sometimes complex logic can't be avoided.  When my logic is complex, I want my variables to be as simple to reason about as possible, which I can achieve by making sure my variables' values never change after they are initialized.

Body:
Speaking as a Java developer who makes all variables final by default (and who appreciates the fact that Eclipse can do this automatically), I find it easier to reason about my program if variables are initialized once and never changed again.

For one thing, uninitialized variables are no longer any concern, because trying to use a final variable before it has been initialized will result in a compile error.  This is particularly useful for nested conditional logic, where I want to make sure that I covered all the cases:

final int result;
if (/* something */) {
  if (/* something else */) {
    result = 1;
  }
  else if (/* some other thing */) {
    result = 2;
  }
}
else {
  result = 3;
}
System.out.println(result);

Did I cover all the cases?  (Hint: No.)  Sure enough, this code won't even compile.

One more thing: In general, any time you know that something is always true about a variable, you should try to get your language to enforce it.  We do this every day when we specify a variable's type, of course:  The language will ensure that values that are not of that type cannot be stored in that variable.  Likewise, if you know that a variable should not be reassigned because it already has the value that it should keep for the entire method, then you can get the language to enforce that restriction by declaring it final.

Lastly, there's the matter of habit.  Others have mentioned that this is a habit (+1 to Jon for that), but let me say something about why you would want this habit.  If you are declaring fields in your class and not local variables in a method, then it's possible for multiple threads to access those fields at the same time.  There are some obscure exceptions, but in general, if a field is final, then every thread that uses your class will see the same value for the variable.  Conversely, if a field is not final and multiple threads are using your class, you will need to worry about explicit synchronization  using synchronized blocks and/or classes from java.util.concurrent.  Synchronization is possible, but programming is hard enough already. ;-)  So, if you just declare everything final out of habit, then many of your fields will be final and you'll spend as little time as possible worrying about synchronization and concurrency-related bugs.

For more on this habit, check out the "Minimize Mutability" tip in Joshua Bloch's Effective Java.

Edit: @Peter Taylor has pointed out that the example above would also not compile if the final keyword is removed, which is completely correct.  When I advised in favor of keeping all local variables final, it's because I wanted to make examples like the following one impossible:

int result = 0;

// OK, time to cover all the cases!
if (/* something */) {
  if (/* something else */) {
    result = 1;
  }
  else if (/* some other thing */) {
    result = 2;
  }
  // Whoops, missed an "else" here. Too bad.
}
else {
  result = 3;
}
System.out.println(result);  // Works fine!

Using a new variable instead of reusing an old one is how I can tell the compiler that trying to cover the complete universe of possibilities, and using final variables forces me to use a new variable instead of recycling an old one.

Another valid complaint about this example is that you should avoid complex nested conditional logic in the first place.  That's true, of course, precisely because it's hard to make sure you covered all the cases in the way that you intended.  However, sometimes complex logic can't be avoided.  When my logic is complex, I want my variables to be as simple to reason about as possible, which I can achieve by making sure my variables' values never change after they are initialized.

ContentLicense: CC BY-SA 4.0


答:
To make silly mistakes less frequent. final makes sure that the variable always points to its first-assigned object, and any attempted changes will count as a compile-time error.

You could also ask "why explicitly declare the type of a variable?", or "why declare methods as constant in C++?". Same reason.


问:
What's the correct approach for passing data from several models into a service?
I have an AccountModel  and a page where the user can upload a file.  What I would like to have happen is when the user uploads the file. The PageController does something like the following.  this is a quick attempt just written in the question to illustrate my question.

```<code>public class PageController : Controller {
  private Service service;
      public ActionResult Upload(HttpPostedFileBase f){
         service.savefile(f,_AccountModel_whatever.currentlyloggedinuser.taxid)          }
}

public class Service
{
// abunch of validation and error checking to make sure the file is good to store
}
</code>```

Wouldn't this approach be in bad practice? Since I'm making my controller dependent on the existence of th AccountModel?  This will become a HUGE program over the next few years, and I really want to maximize the quality of the framework now.

答:
Is your AccountModel a principal of some kind?  If so, I'd really make sure to make it implement IPrincipal and follow the normal patterns.  You can then pull the principal in and cast it to get the data you need.

If its not, you can have an AccountModelId in a hidden form field.  Make your action method take an AccountModel.  A custom model binder can look for this id and retreive your model for you, if it must be read out of a database or something.

Either way, you're in a good spot to be able to unit test your controller as the AccountModel mock is easily given to the controller.


问:
random.choice in other languages
Python has a nice function in the standard library random.choice which returns a random element from a sequence. But none of the other languages I've developed in have thought to include such a feature. Do other languages provide such a feature? Why not?

答:
When choosing features for standard libraries several things have to be taken into account.

One of them is how crucial or basic a given feature is. If it won't be used on a daily basis by a substantial group of users, it likely doesn't belong in a standard library. Every feature requires time and resources to design, implement, integrate and ensure quality of. Both are limited and have to be shared between all such would-be features. Finally, even assuming resources would be available, the bigger picture has to be taken into account. Standard libraries generally aim to provide a relatively minimal set of generic tools. Adding superfluous features causes a library to bloat, making it harder to use and maintain.

Standard library designers have to weigh all those qualities against each other. In case of this particular feature, some have made a decision for it, some against.

Even when the standard library doesn't provide this feature right of the bat, it can easily be implemented with little code. In typical cases it all boils down to choosing a random index in an array or sorting a collection using a random comparison function and returning the first/last element. It comes as no surprise that almost every language provides a random number generator and some generic sort function in its standard library.

A classic post by Eric Lippert that somewhat touches on the subject.

Title: random.choice in other languages


问:
How can I get my startup working with Agile development?
In our startup, we've worked until now using the traditional waterfall model, but we want to try our next project using Agile Methodology.

We are pretty much alien to the entire Agile process, so considering this, what is the best way to understand Agile (resources and a practical handbook can be of help), decide on a specific methodology (Scrum, etc), and start it in our next project?

答:
We are pretty much alien to the entire Agile process, so considering
  this, what is the best way to understand Agile (resources and a
  practical handbook can be of help), decide on a specific methodology
  (Scrum, etc), and start it in our next project?

Of course, do what everyone else here has said and start reading/learning.

Beyond that, don't pick your "next project", pick a project that will succeed using agile methods.
To succeed, the project must be small in scope, have low risk, high customer value and is achievable.  The team should be small, co-located and willing to embrace change.  You must also have automated processes (especially build & test) in place.

Once you have those things, set the team up to succeed by: have an excited customer committed to partner with the team for continuous feedback and open communication.  Make sure the product owner is willing and able to articulate what the customers need and prioritize what should be worked on first and what should be worked on next.  Then have the team deliver a build weekly to the customer/PO for their acceptance and feedback.

What I described above is only part of what you will need to know but it's the essential parts that will lead to continued and sustainable success.

OwnerDisplayName: andy


问:
Scrum taskboard with QA stage
I've been reading this article by Mike Cohn about Scrum task boards.

One query I have is how this fits into a workflow where there is QA stage performed by testers who aren't developers.

It seems that many tasks could not easily be QA'd in isolation.

A practical alternative could be that the "To Verify" process should be carried out by another developer in the team, and then to have an additional stage after DONE to QA the whole story (probably after deployment to a stage/test environment).

Does this seem right?

答:
A practical alternative could be that the "To Verify" process should
  be carried out by another developer in the team, and then to have an
  additional stage after DONE to QA the whole story (probably after
  deployment to a stage/test environment).

Does this seem right?

I assume you are suggesting to redefine DONE as "Each story is done" and add a new column called "Product Ready To Release".  If the team is not already delivering a potentially releasable build each sprint then your suggestion makes a lot of sense and is in fact commonly used in Kanban boards.

So, what happens when the product is NOT ready to release?  In that situation, consider:

Creating work items to address each bug

Identify which story or stories caused that bug

Undo the "done" state of those stories that were actually "not done"

Add the bugs to the backlog for prioritization

Discuss the root cause in the retrospective

Also, developers are notorious for developing up to the last minute of each iteration.  This makes it difficult for the "is it ready to release" non-development team members to do their job.  Kanban also helps here by suggesting that agile teams feature-box iterations instead of time-boxing them.  However, if it makes more sense for your product to time-box iterations, then you could agree as a team not to accept new stories in the next iteration until you can show the customer that the product is at a releasable level.  Of course, you will need to articulate to the PO why the team is not able to accept new work.

Title: Scrum taskboard with QA stage


问:
Which database should I use to manage relationship?
I need 2 capabilities:

calculating mutual friends distinguishing between different types of edges, (e.g. FRIEND, ENEMY and other)

getting relationships distinguishing between different types of edges as over

My problem is speed: If I use a database as MySQL, I can get thousands of relationships in few moments, but if I need to calculate mutual friends, it costs a lot for my server, doesn't it?

I've about 100,000 accounts on my site, and I want to introduce a relationship system, but obviously I have to decide the right way to develop it. Do you have any idea?

答:
You can use a graph database like Neo4j.

...an open-source, high-performance, enterprise-grade NOSQL graph database.

Neo4j is a robust (fully ACID) transactional property graph database. Due to its graph data model, Neo4j is highly agile and blazing fast. For connected data operations, Neo4j runs a thousand times faster than relational databases....

They are good for relations between users in e.g. a social network site.


问:
Is Entity Framework the way to go for our situation?
A little overview about what my group does ...

I work in a development team in a fairly large insurance company.  My group's responsibility consists mostly of building applications for our employees.  Stuff like tracking systems, scheduling applications, contact directories, etc.

Of course we have a decent amount of "shared data" that all applications usually reference.  Stuff like states, employees, and a slew of elements that pertain to our particular business (agents, lines of business, rating companies, etc).  Currently, we have a set of common code that all the applications can leverage to retrieve most of that common data.

Most requests that we get in require either tweaks to the current database objects or creation of many new database objects.  Our group is fairly small, but we still probably have 3-4 sets of database changes going through our Change Management System at any one given time and, depending on priority, some newer changes can leap-frog others on their way to production.

I understand all the benefits EFL brings but I also have a few concerns given our setup:
Since there is the element of shared data, it seems like it'd make sense to have one Data Model for our entire database (which contains all the objects for all the different applications).  Is that a safe assumption?  Or is it possible to build separate Data Models and have them interact with each other?

In the end, we want one class that is called "Employee" and we want that to be able to constant through any application so it seems like we either need to make one mega Data Model so that applications A-Z all have access to the Employee data and all reference the Employee class.  Unless the class can sit in a GAC DLL and then each Data Model can reference .... or, like I asked, separate Data Models can interact with each other.

Then ... if we do go with one mega data model, how difficult would it be to have different individuals making separate changes to that unified data model and then moving it up through a change management system?

I can see the benefits of using such a technology in a silo-ed application ... especially one with minimal maintenance ... but I'm having a hard time envisioning whether the time savings would still be there on a large scale with tons of different data model maintenance happening ... all at the same time.

Any advice given would be greatly appreciated.

答:
As far as versioning goes, I'll tell you that you already have this problem in a different form, though you might not know it.  You have one database, but you have multiple projects accessing the data, correct?  Essentially what's happening now is that since you are (probably) using SQL to access your database in each of your applications your project still compiles no matter what changes you've made to the database.  Any truly breaking changes happen at runtime.

By adding an entity data model, you merely shift this break in your application to one that happens at compile-time.  I guess my question back at you is "how are you versioning your database changes?"  I would suggest you create a single entity data model, package it into an assembly, and make changes to it as you make changes to your database.  Use branching and merging in your source control provider to manage how these changes actually happen in your development workflow.  The newer versions of the Entity Framework are a lot better nowadays for managing merges than they used to be.


答:
Checkout any new breed of NoSQL Databases. eg. MongoDB, CounchDB, Redis. Even Tokyo Cabinet or Kyoto Cabinet is worth exploring depending on respond time you are looking for.

Basically MySQL or any relational database would employ joins which will be costly !! Consider duplicating the data at the time of storing, so that you don't have to join at the time of query !! Your data need not be in perfect normalized form.

Also important aspect that you have not specified here is how much transactional this operation need to be ! Do you want the integrity of the data to be maintained every second to second or every minute to minute ? Is eventual integrity ok ?

Title: Which database should I use to manage relationship?

Body:
I need 2 capabilities:

calculating mutual friends distinguishing between different types of edges, (e.g. FRIEND, ENEMY and other)

getting relationships distinguishing between different types of edges as over

My problem is speed: If I use a database as MySQL, I can get thousands of relationships in few moments, but if I need to calculate mutual friends, it costs a lot for my server, doesn't it?

I've about 100,000 accounts on my site, and I want to introduce a relationship system, but obviously I have to decide the right way to develop it. Do you have any idea?


问:
Pesky bugs - nonexistant?
Very short introduction (this is quite a context-heavy question):

I'm a 17 year old programmer, doing some projects, usually netting around 20 files of 200 lines each. I usually don't program very low-level, more high-level with battery included API's like Python + pygame and Lua + WoW API. Nevertheless I've written quite some code in the lower levels of the computer too (mostly C/C++).

Now, I read a lot of programmer discussion and a common returning argument is preventing pesky bugs, for example in "reusing variable names". I always nodded and thought that it was a valid argument, but just now I wondered, how valid is it?

To be honest, after thinking for a while, I figured I have no idea what they mean with pesky bugs. We all heard stories about phenomenal impossible-to-debug bugs, we all have spent useless evenings on that one annoying bug, but apart from a few cases I have never been busy with a programming-related bug for longer than a few hours.

Though on the other hand, the projects I work(ed) on aren't huge 10 million line projects like the linux kernel, and are quite simple... scripts. I have a good understanding of them (or at least my part in collaborations) and are not very error-prone.

So I'm wondering, do these pesky bugs occur exponentially more as the amount of code increases, or ...?

答: I would say it's not so much the size of the code as the number of programmers working on it.  Code I recently wrote myself is almost always fairly easy to debug.  It's interactions between code you wrote and code you didn't that cause the most issues.  That's why so many best practices are focused on making your code simple and robust so other programmers (or yourself a year from now) won't accidentally misuse it.  </p>

Title: Pesky bugs - nonexistant?


问:
Can a Code Review help in learning the code-flow and/or technology of a large code-base?
I'm new to VC++, and so am not very familiar with COM, ActiveX, IDL etc. When I mentioned this to my tech-lead, he assigned me the task of doing the code review of files he felt were important, in terms of the code that I'll soon be working with.

The actual code-base is approx. 10000 files.

I'm a bit skeptical that doing a code review can help in understanding VC++ (I've already worked with C++ on Linux extensively for 2 years and have plenty of experience in Actionscript, Processing and many other languages).

Since the code yet has to be built and run on my system (I'd prefer putting breakpoints and finding the code-flow), my tech-lead gave me the code review work. Is there a better way?

答:
This is a good scenario--it looks like you are being granted an opportunity to learn--be grateful that you are not being asked to code anything straightaway.

Advice:

Establish what version of DirectX you are working against.

Determine what parts of the system use "managed" or "unmanaged code".

Become familiar with the concepts of COM programming, especially with .NET interoperation with COM objects.

Use Visio or other diagramming tools to reverse engineer the code into diagrams, such as Sequence Diagrams. Some versions of Visual Studio provide this functionality.

If using .NET, a good exercise in understanding the build order is to analyse the *.*proj files--these can be built at the command line using msbuild.exe, but it is even easier to configure the build commands using NAnt to call msbuild.exe, like this:

```<code><exec program="${framework::get-framework-directory(framework::get-target-framework())}\msbuild.exe" commandline="${solution.file} /t:Rebuild /p:Configuration=${build.configuration} /p:TrackFileAccess=${build.trackfileaccess} /v:detailed" workingdir="."/>
</code>```

Figuring out how to build the system without having to depend on the Visual Studio user interface will help you to become more deeply familiar with the system's dependencies, and will likely impress your team lead.

Body:
This is a good scenario--it looks like you are being granted an opportunity to learn--be grateful that you are not being asked to code anything straightaway.

Advice:

Establish what version of DirectX you are working against.

Determine what parts of the system use "managed" or "unmanaged code".

Become familiar with the concepts of COM programming, especially with .NET interoperation with COM objects.

Use Visio or other diagramming tools to reverse engineer the code into diagrams, such as Sequence Diagrams. Some versions of Visual Studio provide this functionality.

If using .NET, a good exercise in understanding the build order is to analyse the *.*proj files--these can be built at the command line using msbuild.exe, but it is even easier to configure the build commands using NAnt to call msbuild.exe, like this:

<exec program="${framework::get-framework-directory(framework::get-target-framework())}\msbuild.exe" commandline="${solution.file} /t:Rebuild /p:Configuration=${build.configuration} /p:TrackFileAccess=${build.trackfileaccess} /v:detailed" workingdir="."/>

Figuring out how to build the system without having to depend on the Visual Studio user interface will help you to become more deeply familiar with the system's dependencies, and will likely impress your team lead.


问:
Why use services (REST/SOAP) instead of a library?
Let's say you're looking at breaking up your applications into services.  Are there any good reasons to adopt a SOA approach vs. just creating a library API that can be loaded by the applications that need it.</p>

答:
The difference may be subtle between both. For example in .NET world, you may have an application which would feel like monolithic to an end user and which will work on a same machine, but inside, would be separated into a bunch of WCF services. You may also have architectures where libraries are not strongly linked (addins/plugins) and are just following a protocol when talking to each other.

If we avoid talking about those intermediary cases, and deal only with strongly linked API library vs. a separate REST service, then you may want to consider following points:

A library API is called on the same machine. Services can be hosted anywhere and be called from anywhere. If you're counting hosting the application on multiple machines for performance/scalability/security reasons, chances are you'll need to use services.

The situation is similar when it goes to using one service by an application deployed on several machines. For example if you're doing an application for a bank doing some financial computations, one way is to deploy the whole large application to every desktop, and be forced to do large-size updates to every client every time; another approach would be to host computation part on servers, and deploy to the desktops only a lightweight app with just a UI and a bunch of calls to those servers.

If you're hosting a REST service, anyone can use it: a Mac user, a person who uses Linux, etc. If you've created a C# library with Visual Studio and you distribute it as a DLL, forget about users (customers?) who don't have Windows.


问:
Alternativates to HTML Help
We currently use a system called AsciiDoc which allows us to create documentation in a simple text markup. From that we can generate multiple output formats. We only make use of the pdf output and chm output formats.

I was wondering if there was an alternative to chm? What I am looking for is something that can be used off-line (this is important because quite a few of our users are in very remote places) with our software. It should have an index (it can be as simple as an html page with hyperlinked terms), it should be searchable and it should have a mechanism that allows specific entries to be called up from the code (similar to context sensitive help).

The two things that are against PDF in this case is:

Context sensitive help isn't an option

Generally the document is rather large

PDF is more suitable to printed documentation than context sensitive help

What I would like is to use html. The only problem with html is that I can't seem to figure out how to automatically provide a keyword search (other than the browsers ctrl+f functionality - I would like something more apparent). I also can't seem to find a method to automatically generate a hyperlinked index of key words. Context sensitive help would be simple because of the section tags - I could simply pass the url of the page and section that I am interested into the default browser and that page should load up to the correct section.

My requirements sound an awful lot like chm - they do. I modeled my requirements off chm. The only reason I don't like chm is because of the way the code interacts with it using mapids and such. I would much rather use store a plain text list (that is automatically generated for me) that my code can use to access the context sensitive portion of the documentation.

I am envisioning a script that would go through the html output files and generate an index page that simply contains a list of keywords that it found. obviously there should be word exclusion mechanism to ignore words like: the, it, is, etc.. This part would be relatively easy to write. The second part would need a script of some sort to put together a database of keywords and their location within the html text. I think this would be the tricky part along with providing the search mechanism within the browser.

Any ideas on alternatives would be appreciated. I would love to use a wiki or set of static html pages hosted on a webserver somewhere, but we have a critical offline usage requirement. Simply placing the html on the local drive doesn't provide us with the search requirements that we need.

EDIT:

I design software that is used by the mining industry. A lot of mines are very remote and do not have access to the internet in any meaningful way. There is nothing wrong with pdf or html or chm (except that it is getting old). If I could display a pdf file at the correct location (i.e. context sensitive help) I would use it. I am almost tempted to write my own - basically it would be a portable wiki. Speaking of that, if you suggest portable wiki - you have to think of the end user which may have no experience in using such tools. It has to be dead simple. That was the beauty of chm, it is a pain to work with but the end users like it.

答:
CHM itself is getting old, and Microsoft has also moved on to newer things: http://msdn.microsoft.com/en-us/library/bb164608(v=vs.80).aspx

But if you really want to avoid converting your help to an existing system, and are looking how to provide a search and keyword-lookup on static help files, here are two idea's:

add a small localhost-only HTTP server to the project to serve a website with the documentation. Problems are when or how to start/stop this HTTP server and/or keep it running. An alternative would be implementing a custom URL scheme, but this would tie you to one browser and is a lot more work (and I can tell)

write a JavaScript search engine. JavaScript in any browser is getting pretty fast and performant these days. A keyword index could be easily stored on JSON, and I have run regular expressons on local files with pretty good results.

Title: Alternativates to HTML Help


答: Another advantage of services is that when you update the service, it is immediately deployed to all consumers of the service. So if you fixed a bug, or performance issue, everyone gets the benefit as soon as the updated service goes live, instead of having to distribute an update that people may choose to ignore.</p>

Title: Why use services (REST/SOAP) instead of a library?

Body: Let's say you're looking at breaking up your applications into services.  Are there any good reasons to adopt a SOA approach vs. just creating a library API that can be loaded by the applications that need it.</p>


问:
Multi sourced search in WPF app
If I’m using the MVVM pattern – this one for my WPF application

And my project requires a search function on different sources – say clients, accountants, cases.

What would be the best way to go about it so that I only have one search view and the search results shown in the ListView are ‘dynamic’ in that they could be result for clients or accountants or cases

Should I have a base search view model and specific view models for clients, accountants, cases that then somehow set as the datacontext for the search view

Or

try to build the grid dynamically in a code behind for the search and then somehow get the data back into the view model without the search view knowing about the view model.

For clarification

The searches are separate and will not need to be combined, I would only every return results for clients or accountants or cases.

答:
I would build a grid for each search type case. e.g.

SEARCH RESULTS

Accounting

result 1
result 2
result 3

Cases

result 1
result 2
result 3

etc.

Title: Multi sourced search in WPF app


问:
How can I convince management to deal with technical debt?
This is a question that I often ask myself when working with developers. I've worked at four companies so far and I've become aware of a lack of attention to keeping code clean and dealing with technical debt that hinders future progress in a software app. For example, the first company I worked for had written a database from scratch rather than use something like MySQL and that created hell for the team when refactoring or extending the application. I've always tried to be honest and clear with my manager when he discusses projections, but management doesn't seem interested in fixing what's already there and it's horrible to see the impact it has on team morale.

What are your thoughts on the best way to tackle this problem?
What I've seen is people packing up and leaving. The company then becomes a revolving door with developers coming in and out and making the code worse. How do you communicate this to management to get them interested in sorting out technical debt?

答:
You should just stop complaining about it.

Here's why:

They never plan to use the software longer than a year

it's just waste of time tweaking it if their plan is to dump it afterwards

there's some real problems that need fixing now

programmers just need to learn to deal with maintainance, even if it's not always fun

complaining that you know better what needs to be done is arrogant - someone else makes the decision, and you should be happy about it

They anyway trust you to write good code

So best way forward is:

When they give you new task, try to implement it as well as possible in the given time

Write it perfectly the first time. If you need to change it afterwards, you made a mistake the first time and any change is always going to wrong direction - and it's a learning opportunity for programmers when you make mistakes.

Don't ask extra time for it, you wont get it, there are deadlines you know.


问:
Integration of routes that are not resources in an MVC REST style application
I would like to keep my application relatively REST-pure for the sake of consistency, but I'm struggling philosophically with the relatively few views (maybe just one) that I'll need to build that don't relate to resources directly, and therefore do not fit into a REST style.

As an example, take the home page.  Ruby on rails seems to bail on their otherwise RESTful approach for this very basic need of all web sites.  The home page appears special:

You can get it, but a get at the resource level is supposed to give you a collection of elements.  I can imagine this being the list of routes maybe, but that seems a stretch, and doesn't address anything else.

Getting the home page by id doesn't seem to make a whole lot of sense - what's the element of a home collection?  Again, maybe routes, but a get on a route would do what?  Redirect?  This feels odd.

You can't delete it (arguably you could allow this for administrators)

Adding a second one doesn't make sense except possibly if the elements were routes

Updating it might make sense for administrators, but AFAIK REST doesn't describe updates on the resource directly, only elements of the resource (this article explicitly says "UNUSED" for PUTS on the resource)

Is the "right" thing to do just to special case these types of things?  At the end of the day, I can wrap my head around most of applications being gathered around resources...I can't think of another good example other than a home page, but since that's the start of an application, I think it warrants some thought.

答:
A homepage is still a resource, a slightly anachronistic one. When the web was new a convention arose that GET requests to the server root '/' would be answered with a default document, usually 'index.html', otherwise known as the home page.

Doing PUT on a resource is exactly how you would update it. It doesn't generally make sense to PUT a collection (which is the 'unused' one in the article). But a home page isn't a collection so there's no special case there.


答: A SOA approach allows the various services to be hosted and maintained separately. In addition to code, deploying a particular service may require a lot of special configuration (passwords, ports, certificates, etc). Consuming a REST service has a finite amount of complexity that can be clearly documented and easily understood. It's also more secure because it means you don't need to grant access to DBs or other resources to clients.</p>


问:
Algorithm analysis refresher help
I haven't touched algorithm complexity stuff in quite a while, so I am trying to do a refresher.

I am trying to figure out the number of steps in the following for loop.

```<code>for(i = 0; i < n; i++){
  //code
  for(j = i + 1; j < n; j++){
     //code
  }
}
</code>```

The inner loop will be executed    times

I mean t times for each value of j.
Right?

In the worst case tj will be equal to n-i. Since it will run for n-(i+1)-1 times.

Well is my approach on this analysis correct?

答:
The inner code will be executed (n-1)*(n/2) times.

Looking at the first few iterations and the end conditions helps give a general pattern

When i=0, the inner code will go from 1 to n - (n-1 times)

When i=1, the inner code will go from 2 to n - (n-2 times)

.

.

When i=n-2, the inner code will go from (n-1) to n - (n-(n-1))

So (n-1) + (n-2) + ... + (n-(n-1)) = (n-1)*(n/2)

Title: Algorithm analysis refresher help


问:
Learning Python from Beginner to Advanced level
I have some problems in my hand and would like to resolve them by myself (rather than hiring some professional, obviously due to cash problem!):

build a really good website (planning to set-up my own start-up).

build some good software (preferrably with exe installation files) on many mathematical and statistical techniques.

To accomplish those tasks, is it worth to learn Python in advance level? I have advanced programming experiences with R and Matlab and VBA (and some sort of C), however not anything on Python.

Be very grateful if experts put some guidance here.

Thanks for your time.

答:
Well, although Python is popular here, there and everywhere you don't actually need it but build a website. As far as (2.) goes, if you already know MATLAB and are experienced in it, I see no advantages of going down the Python path for that. MATLAB is more than a capable software package for that purpose. You can build .exe files with it as well.

However, if you really wish to start learning Python, this might be a good place to check out: Learning Python the Hard Way (although there is really a mass of other tutorials as well. Just try searching on this site alone for "python tutorial" or "python book").


问:
How to create an extendable web application?
How would you implement an extendable web application? What I'm thinking about is a web application similar to Jenkins or Hudson which provides plug-in support. While it's obvious to me how  plug-ins can be located and loaded, I don't know how they can be integrated within the overall architecture. I'm especially uncertain about the following points.

How can a plug-in change the view, e.g. add input elements to a form?

My first idea would be that a plug-in can register partials / fragments for a certain form.

Example:
Newsletter plug-in which registers a typical newsletter checkbox fragment which will be rendered in the user registration view.

How can a plug-in react to incoming requests?

Again, a direct approach would be to provide listeners for certain requests or actions, e.g. POST request to /user.

How could a plug-in persist data?

I'm assuming this is a situation where NoSQL data storage solutions would be superior to relational databases.

I would appreciate any comments, ideas and experiences (maybe there is even a design pattern) that you have regarding extendable web applications.

答:
Your question contains almost all the answers. You're right in the ballpark: it's all plug-ins and their extension points to set the context and make them do the things you want. There are numerou ways to design plug-in systems. For starters:

http://people.clarkson.edu/~dhou/courses/EE564-s07/plugin.pdf

http://blogs.atlassian.com/developer/2011/03/plugin_architecture_episode_i.html

Here is a trivial example to illustrate how a rudimentary plugin-aware system would work:

```<code>public interface Plugin {

  void setEntityManager(EntityManager manager); // this is very course grained and liberal! A plugin would have access to whatever Entity Manager the container gives it. A plugin would then have a carte blanche to do whatever it needs: create, drop, insert, select, delete.

  View renderView(ViewContext context); // a plugin would render or return a view (whatever it is, could be a string in the simplest case) based on the context that the container passed to the plugin

  Action readEvent(Event event); // a plugin performs some Action based on an event as notified by a container

}

public class PluginContainer {

  private List<Plugin> plugins = new ArrayList<Plugin>();

  public void registerPlugins() {
    // loop through plugin descriptors obtained by your preferred mechanism
    // like introspecting libraries (JARs) in a configurable location

    // for each descriptor, load a Plugin dynamically and "register" it with a container
    Plugin p = ClassLoader.getSystemClassLoader().loadClass("com.my.PluginA").newInstance();
    p.setEntityManager(entityManager);
    plugins.add(p);
  }

  public void readEvent(AppEvent appEvent) {
    Event e = this.constructPluginSpecificEventFromAppEvent(); // optional
    for (Plugin p : this.plugins) {
      p.readEvent(e); // disregarding Action here
    }
  }
}

public class Application {

  private PluginContainer pContainer;

  private void buttonClicked(AppEvent appEvent) {
    this.showCoolDialog("Thank you for clicking a button!");
    // now let my plugins handle this
    // they can do whatever they want for this event
    // since they have access to EntityManager, they can work with a persistence storage as well
    this.pcContainer.readEvent(appEvent);
  }

}
</code>```

Body:
Your question contains almost all the answers. You're right in the ballpark: it's all plug-ins and their extension points to set the context and make them do the things you want. There are numerou ways to design plug-in systems. For starters:

http://people.clarkson.edu/~dhou/courses/EE564-s07/plugin.pdf

http://blogs.atlassian.com/developer/2011/03/plugin_architecture_episode_i.html

Here is a trivial example to illustrate how a rudimentary plugin-aware system would work:

public interface Plugin {

  void setEntityManager(EntityManager manager); // this is very course grained and liberal! A plugin would have access to whatever Entity Manager the container gives it. A plugin would then have a carte blanche to do whatever it needs: create, drop, insert, select, delete.

  View renderView(ViewContext context); // a plugin would render or return a view (whatever it is, could be a string in the simplest case) based on the context that the container passed to the plugin

  Action readEvent(Event event); // a plugin performs some Action based on an event as notified by a container

}

public class PluginContainer {

  private List<Plugin> plugins = new ArrayList<Plugin>();

  public void registerPlugins() {
    // loop through plugin descriptors obtained by your preferred mechanism
    // like introspecting libraries (JARs) in a configurable location

    // for each descriptor, load a Plugin dynamically and "register" it with a container
    Plugin p = ClassLoader.getSystemClassLoader().loadClass("com.my.PluginA").newInstance();
    p.setEntityManager(entityManager);
    plugins.add(p);
  }

  public void readEvent(AppEvent appEvent) {
    Event e = this.constructPluginSpecificEventFromAppEvent(); // optional
    for (Plugin p : this.plugins) {
      p.readEvent(e); // disregarding Action here
    }
  }
}

public class Application {

  private PluginContainer pContainer;

  private void buttonClicked(AppEvent appEvent) {
    this.showCoolDialog("Thank you for clicking a button!");
    // now let my plugins handle this
    // they can do whatever they want for this event
    // since they have access to EntityManager, they can work with a persistence storage as well
    this.pcContainer.readEvent(appEvent);
  }

}


问:
How do you avoid disrupting the flow of work when the Product Owner asks for a release?
My team has been using Scrum for years with a goal to deliver a potentially releasable build each sprint.  We recently started using a Kanban board moving away from time-boxed delivery to feature-boxed delivery.  So far, this seems to better fit the teams natural way of working.  With feature-boxed delivery, stories are pulled from the backlog when an individual feels they are comfortably ready to begin working on it.

The teams average story lead time is three weeks.  So, theoretically, at the moment the product owner asks for a release, the team should be able to deliver it three weeks later.

When the PO sets the "stop development" trigger, individuals who have time are supposed to start helping with stories already underway to begin clearing out the board.  The people freed up first are typically the "front-end" folks... Those more skilled at analysis and development.  They are typically asked to help with back-end work, like system testing.

The teams work flow, or cadence changes each time the stop trigger is set.  What do you do to minimize this change and keep the team working as efficiently as possible?  How do you avoid the disruption caused by the Product Owner asking for a release?

答:
The way you describe it preparing for a release is a significant interruption of your workflow which appears to work otherwise.

As we had a similar demand placed on our team we introduced the following solution. It has mainly to do with branch management in your version control system. The concept is known to me as "No Junk In The Trunk". It basically means that you have a branch that is 'clean' in that it contains only work that has successfully passed Quality Assurance (QA). Using Subversion this branch may be called 'trunk' hence the name. Of course this works with other version control systems as well, e.g. GIT.

When we start work on a new feature then we create a feature branch. This feature branch is updated with a merge from trunk at least once a day to keep the difference to a minimum. All testing, quality assurance, sign-off by various parties is entirely done on the feature branch. Once the feature is complete it is then merged back into 'trunk' followed by a quick integration testing focusing on where the new feature integrates with what is already there.

When we release we create release branches out of 'trunk'. Since 'trunk' is 'clean' we can pretty much release at any time. Since releases do not depend on wiping out all stories from the Kanban board we can prepare a release at any time without interrupting the regular development workflow.

This process works very well for us. Creating the release branch takes about 10 seconds as it is fully automated. The most significant item on the release branch is reviewing the release notes by a native English speaker. This is unfortunately a manual process and it takes about one or two hours depending on the amount of new features and bug fixes in the new release.

As always you may have factors in your environment that may make other solutions to the challenge a better option.


问:
What are the typical naming conventions for OO C public and private functions?
Short Question

Is there a typical way to name 'public' and 'private' members of an OO C project?

Background

I fully understand that public and private members do not really exist in the C language.  However, like most C programmers, I still treat members as public or private to maintain the OO design.  In addition to the typical OO methods I have found my self following a pattern (see example below) that makes it easier for me to distinguish which methods are meant for the outside world vs the private members that may have fewer checks / are more efficient etc... Does a standard or best practice exist for such a thing or is my example below a good way to approach this?

Example Header

```<code>#ifndef _MODULE_X_H_
#define _MODULE_X_H_

bool MOD_X_get_variable_x(void);
void MOD_X_set_variable_x(bool);

#endif /* _MODULE_X_H_ */
</code>```

Example Source

```<code>// Module Identifier: MOD_X
#include "module_x.h"

// Private prototypes
static void mod_x_do_something_cool(void);
static void mod_x_do_something_else_cool(void);

// Private Variables
static bool var_x;

// Public Functions - Note the upper case module identifier
bool MOD_X_get_variable_x(void)      {return var_x;}
void MOD_X_set_variable_x(bool input){var_x = input;}

// Private Functions  - Note the lower case module identifier
void mod_x_do_something_cool(void){
     // Some incredibly cool sub routine
}

void mod_x_do_something_else_cool(void){
     // Another incredibly cool sub routine
}
</code>```

答:
Usually the convention is to not put the private functions in the header at all.

Since you normally put implementation of one object wholly in one source, the private function can usually be just file-static. In that case you'd usually skip the prefix to save some typing (the symbol won't be visible outside of that compilation unit).

If you for some reason need to make the function available to some other class, but otherwise still private, than you name it just like any other method, but put it in a separate "-private" header.

The same applies to the definition of the type too. If possible, you only forward-declare the structure as incomplete type in the header and define it either in the source or in the "-private" header. You need the definition to inherit the class, so you'd treat the extra header as protected rather than private stuff than.

Probably the biggest piece of object-oriented code in C is the Gnome platform. You can most easily see the convention on the GObject library, that provides the lowest level base classes. It it roughly what I describe above and is used throughout Gnome.


答:
Building a good website isn't just about knowing python. You need css, html and JavaScript skills to make it really good. There is also significant skill in ux design that isn't related to any language.

While all of these things are nice to have they will take time to learn. Its your call if paying someone else is worth it, we don't really have enough info to make the call. If its not a skill you would need going forward then pay somone else to do it

If your doing mathmatical/statistical programs then you can't really beat R, the whole language was designed with that in mind. You might want to learn a little C# or similar  to make a nice GUI wrapper. That really depends on how much your clients value looks though. Don't switch from R for the guts.

Title: Learning Python from Beginner to Advanced level

Body:
I have some problems in my hand and would like to resolve them by myself (rather than hiring some professional, obviously due to cash problem!):

build a really good website (planning to set-up my own start-up).

build some good software (preferrably with exe installation files) on many mathematical and statistical techniques.

To accomplish those tasks, is it worth to learn Python in advance level? I have advanced programming experiences with R and Matlab and VBA (and some sort of C), however not anything on Python.

Be very grateful if experts put some guidance here.

Thanks for your time.


答:
If you're dealing with non-technical managers, it would help if you can cast your discussion into terms they understand.  If you can construct a realistic case for a positive ROI on the work spent to pay down the technical debt, you might get somewhere.  That exercise will depend on your circumstances, but an example might be something like this:

Analyze how much time developers are forced to spend helping Support with production issues, then make the case that fixing crufty old code would A. reduce the number of support issues, B. make it easier for Support to resolve issues without escalating to Development, and C. reduce the time Development spends on production issues when they do arise.  Put it in terms of dollars saved by not having developers tied up doing support work.  Also point out that every hour a developer spends doing support is a "double whammy" because not only are you paying a developer to do support, but you're burning the opportunity cost of what that developer could be doing (adding new features, etc.)

Yeah, some of the numbers will be voodoo / smoke-and-mirrors... that's OK, the dirty secret of management is that they know that the majority of the numbers they sling around are total B.S.  Just as long as you give them something seemingly concrete to work with, so they can get it in their heads, you have a fighting chance.

Title: How can I convince management to deal with technical debt?

Body:
This is a question that I often ask myself when working with developers. I've worked at four companies so far and I've become aware of a lack of attention to keeping code clean and dealing with technical debt that hinders future progress in a software app. For example, the first company I worked for had written a database from scratch rather than use something like MySQL and that created hell for the team when refactoring or extending the application. I've always tried to be honest and clear with my manager when he discusses projections, but management doesn't seem interested in fixing what's already there and it's horrible to see the impact it has on team morale.

What are your thoughts on the best way to tackle this problem?
What I've seen is people packing up and leaving. The company then becomes a revolving door with developers coming in and out and making the code worse. How do you communicate this to management to get them interested in sorting out technical debt?


问:
Why are weakly-typed languages still being actively developed?
I wonder why are weakly-typed languages still being actively developed. For example, what benefit can one draw from being able to write

```<code>$someVar = 1;
(...)  // Some piece of code
$someVar = 'SomeText';
</code>```

instead of using the much different, stongly-typed version

```<code>int someInt = 1;
(...)
string SomeString = 'SomeText';
</code>```

It is true that you need to declare an aditional variable in the second example, but does that really hurt? Shouldn't all languages strive to be strongly-typed since it enforces type-safety at compile time, thus avoiding some pitfalls in type-casting?

答: Weakly-types languages are still being developed because people use them and like them. If you don't like weak typing, don't use weakly-typed languages. Declaring that something is The One True Way and that Everybody Should Do It The One True Way ignores the complicatedness of the world.</p>


问:
Is there a canonical book on functional design specifications?
I have seen and read quite a few books about software design (using UML, etc.), and others about user experience, GUIs, etc. but I'm looking for books that describe the process that happens before all of that.

I'm looking for the pre-development stuff. How to develop a cohesive and comprehensive plan for what the application is functionally supposed to do, leading to flow-charts and a functional specification, etc. So I guess my question is in two parts:

Is there a book out there that's the de-facto standard for describing best practices, design methodologies, and other helpful information about functional requirements analysis? What about that book makes it special?

答:
When it comes to requirements specifications, my go-to books are Karl Wieger's Software Requirements and More About Software Requirements. Together, these books discuss the majority of the topics needed for requirements engineering, from defining stakeholders and requirements to establishing a vision and scope to capturing and prioritizing requirements.

Software Requirements tends to focus more on specifications and requirements engineering techniques. More About Software Requirements discusses other methods of capturing requirements, such as use cases and determining the detail needed in the documents that are used to capture requirements.


答:
Shouldn't all languages strive to be strongly-typed since it enforces
  type-safety at compile time, thus avoiding some pitfalls in
  type-casting?

Not necessarily. Learning Objective-C: A Primer addresses that question directly in the context of Objective-C:

Weakly typed variables are used frequently for things such as
  collection classes, where the exact type of the objects in a
  collection may be unknown. If you are used to using strongly typed
  languages, you might think that the use of weakly typed variables
  would cause problems, but they actually provide tremendous flexibility
  and allow for much greater dynamism in Objective-C programs.