答:
One way is to give them alternative commands. I rarely use git merge; instead, I use the bash functions below. If you're running on Windows (and not using Cygwin), I suppose you could create batch files to do the same thing.

```<code>function branch
{
    if [ $# == 0 ] ; then
        git branch | grep '^\*' | sed -e 's/.* //' ;
    elif git branch | grep -q " $1\$" ; then
        git checkout $1
    else
        git checkout master
        git checkout -b $1
    fi ;
}

function push
{
    src=`branch`
    if [ $# == 0 ] ; then
        git push origin ${src} ;
    elif [ $# == 1 ] ; then
        git push $1 ${src} ;
    else
        git push $1 ${src}:${2} ;
    fi ;
}

function pull
{
    if [ $# == 0 ] ; then
        src=`branch` ;
        git pull origin ${src} ;
    elif [ $# == 1 ] ; then
        branch $1
        git pull origin $1 ;
    else
        echo "usage: pull [BRANCH]" ;
    fi ;
}
</code>```

Title: How can I prevent users from merging origin/X into Y in git?

Body:
Is it possible to force git to only merge remote tracking branches into the corresponding local branch? E.g. assume origin/X tracks X on origin and corresponds to local X and the same for origin/Y and Y. I want to prevent users to do git checkout Y; git merge origin/X. Is it possible? How?

Edit:

To make it clear: The workflow is not the problem. People try to merge the wrong branches because they forgot to checkout the correct branch before merging. It is not about "offenders" or pushing to the central repo. It's just people forgetting at which branch they are. The last "incident" was literally:

"I should commit and push real quick before I leave.

git add .

git commit -am 'Feature Y'

git push origin

Whoops, whats that. It tells me to merge branch origin/X first. OK whatevs.

git merge origin/X

Whoops, whats that now. Lots of merge conflicts. What have I done. I better call somebody..."

The user was working in branch Y and did not understand what the git push origin was saying. It told it that origin/X needed merging and that's what he did, because he wanted to "push real quick". In the case above branch X was one commit ahead of the local X, so pushing all branches yielded the "needs merging" error.

I adjusted the "workflow" now to always push a branch explicitly, e.g. git push origin Y instead of just git push origin, but that's not curing the problem. It should (usually) not be allowed without a warning to merge origin/X with Y. For merging feature branches X and Y can be merged.

Body:
One way is to give them alternative commands. I rarely use git merge; instead, I use the bash functions below. If you're running on Windows (and not using Cygwin), I suppose you could create batch files to do the same thing.

function branch
{
    if [ $# == 0 ] ; then
        git branch | grep '^\*' | sed -e 's/.* //' ;
    elif git branch | grep -q " $1\$" ; then
        git checkout $1
    else
        git checkout master
        git checkout -b $1
    fi ;
}

function push
{
    src=`branch`
    if [ $# == 0 ] ; then
        git push origin ${src} ;
    elif [ $# == 1 ] ; then
        git push $1 ${src} ;
    else
        git push $1 ${src}:${2} ;
    fi ;
}

function pull
{
    if [ $# == 0 ] ; then
        src=`branch` ;
        git pull origin ${src} ;
    elif [ $# == 1 ] ; then
        branch $1
        git pull origin $1 ;
    else
        echo "usage: pull [BRANCH]" ;
    fi ;
}


问:
Is it wise to be going back and forth between two programming languages?
I have been writing quite a lot of PHP for nearly two years. Now I am doing .NET (mainly c#) development. However, sometimes I go back and do some php.

My main question is, is it wise for me to continue doing this or should I continue development in C#? Would this harm me in the long run (mind you my main goal is not to be a jack o all trades) or is it a good practice to be doing?

答:
It has always been the case for people to program using more than one language. When people were using Assembly, they have to lean a new Assembly language every time they changed architectures.

When people where doing COBOL or Fortran, they also typically did RPG and/or JCL.

In Unix, people would work with C, sed, awk, shell script and just about everything in the Unix kitchen sink (almost every command line tool in Unix is its own, very specialzided DSL.)

In DOS, people would be programming in Turbo Pascal or C in addition to batch scripts. Later when Windows came, it was VB or something like PowerBuilder coupled with SQL and possibly batch installation scripts.

Nowadays, it is a de-facto that people "work" with more than two languages any given day (and by "work" I mean do actual day-to-day coding or have working knowledge). Java or C# or VB mixed with JavaScript and SQL at the very least. Then other languages come into play for batch/job scripting and the like. Then, for each language, you have a framework that itself implements an internal DSL, a mini-language in its own right.

So, it is not just beneficial to work with more than  one language, but it is necessary. There is no way to build a modern, complex system with a single language (and by "build" I don't mean just code some crap that compiles, but to build something with a decent design.)

Heck, I'll go out of a limb and say that I would expect kids in college to be proficient in two or more languages if they are serious about being in this profession.

So, regarding your question:

My main question is, is it wise for me to continue doing this or
  should I continue development in C#? Would this harm me in the long
  run (mind you my main goal is not to be a jack o all trades) or is it
  a good practice to be doing?

So, short answer, no, using or switching between languages won't give you the cooties. Knowing more than one language won't make you a jack of all trades, and there is no way for a developer to become an expert by being unable to use more than one language.

ContentLicense: CC BY-SA 3.0


问:
What happens between sprints?
I'm working on a project loosely following the scrum model. We're doing two week sprints. Something I'm not clear on (and don't have a book to consult) is exactly what is supposed to happen between sprints: there should be some "wrap" process, where the product gets built and delivered, but:

how long does this typically take?

should the whole team be involved?

does it strictly have to finish before developers start working on the next sprint items?

is this when code review and testing take place?

There are three developers, adding up to about 1 FTE. So the sprints are indeed very short.

答:
... and when is the estimation? planning?

Stories should be really easy to have no time between sprints.

And I don't know what kind of test are you talking but developers will make unit and integrations test, nothing more.

I was working in a project with sometimes 2 o 3 days between sprints and it feels right. Now I am working on a project where there is no time and its all fuzzy. The last time of the sprint we have production deployment and that takes some time of my last sprint day.

Title: What happens between sprints?


问:
Web application without libraries | Relation to job postings
I have an application built without any libraries using PHP, JavaScript, HTML5, CSS, and mySQL that will support major modern browsers - IE, Safari, FF, Opera, and Chrome.

One thing I've noticed is that most web jobs 90%+ ask for library experience of some sort.

About 10 % do not... they focus more on the language then language-libraries.

Why this lean toward libraries? I can understand that you don't want to have to re-write AES encryption algorithms and PHd level math things like that, but so much web development does not have any high level math at all.

What is the difference between jobs that focus on library use vs. jobs that focus on language?

答:
Ninety percent of all software applications that are being written by software developers earning a paycheck are line-of-business CRUD applications... unspectacular software that models business processes.  These are domains where the process of developing software is already very well-understood, and libraries have emerged as a way to speed up the development of mundane, repetitive elements such as database access, data validation and the like.

Consequently, most employers expect developers with current knowledge of programming practices to know and understand these "tools of the trade," since it costs a lot of time, effort and money to reproduce that which has already been adequately created by someone else.

As to the other ten percent of software applications (those involving research or specialized domains such as aerospace), there is still a significant demand for custom code, as the problems posed by such environments do not always lend themselves well to the stitching together of generalized libraries.


问:
Preferring Python over C for Algorithmic Programming
I've been studying a bit of algorithms and have been looking at sites like SPOJ.pl TopCoder etc. I've seen that programmers prefer C or C++ usually for most algorithmic programming contests.

Now I've been having some trouble lately. I know both a bit of C and Python and when trying to write a code I seem to prefer Python over C for most algorithms. Everytime I sit down to write a code in C I give up after about 15 minutes because I find it too cumbersome and tend to move over to python. Passing matrices Pointers and so on seem to be useless time wasted that I could actually be utilizing to think about the algorithm itself.

Now I know and have heard from a lot of people that C is a very important language and is the bread and butter of a lot of programmers out there.

What I wanted to know was whether this approach of mine has any drawbacks/consequences/Disadvantages etc.

This is not a Python vs C debate; This a question about how this specific practice of preferring python over C because of the ease of use will affect me or any other programmer/computer Scientist in the long run.

I'd love to hear from people who've used these languages in the industry/and or to develop large software/libraries etc.

答:
Researchers whose primary interest is not programming prefer higher level languages such as Python, because they can code a solution more readily in such languages than, say, C.  Python is particularly well suited to this because it is more "prototyping" oriented, it is "batteries included," and it integrates with numerical libraries such as NumPy and SciPy.

If a researcher needs better performance, they will typically hand over the algorithm they created in Python to a Software Engineer, who will find ways to optimize it (up to, and including, recoding in C).


问:
What tools do you use to manage requests from users?
I'm drowning in user emails and I'd like to implement a better way to manage all these requests I get and put them in a queue where those people on a team, as well as users, have access to them and can make common notes. I'm thinking about some sort of task management tool that would allow multiple tasks to be created under a project where emails, comments, ideas, etc. could be dropped/entered and easily accessible.

I need something that all parties can be involved in - users, managers, team leaders, developers. I'm looking for a tool that can allow:

Users to just drag/drop an email to submit a request for maintenance or enhancement.

Developers to just see their queue and the weighted priority of each task/project.

A team of developers to see what everyone is working on in real-time.

Management to keep a a log of time spent on each task.

I I am starting to look in more of a Agile/Scrum direction for solving this problem. I found list of scrum agile sofware project management open source tools. Since I am limited on time, has anyone used these? Which one should I test to see if it will meet my needs? TeamPulse is a good direction, but think it is a little too bloated. I need something simple for all parties.

答:
Trac.

Users can have accounts to submit tickets, view their status, and see any documentation you add as a support wiki. You can also give users a section of the wiki they can edit so they can document shared practices.

Tickets can be assigned to particular components, so developers can quickly see tickets that affect their part of the code in addition to being able to see their "queue" of tickets assigned to them.

Tickets can be assigned to releases or milestones, which is one way in which managers can see the overall "health" or "pulse" of the project. The custom reporting allows managers to view other metrics they may be interested in.

Trac integrates well with subversion, but I'm not certain about other SCM systems.

The price is right.

ContentLicense: CC BY-SA 2.5


答:
Everytime I sit down to write a code in C I give up after about 15 minutes because I find it too cumbersome and tend to move over to python.

This productivity gain is the common reason that C and C++ jobs have decreased substantially.

This a question about how this specific practice of preferring python over C because of the ease of use will affect me or any other programmer/computer Scientist in the long run.

There are two core parts to this. The first is algortihmic programming. It really doesn't matter what language you use to express the algorithm. Working with the algorithm itself and fitting the right ones into the right problems are the key parts, so there's no real issue there.

The second part is productivity gains. Using things that make you more productive over time is a good habit, and something that will do nothing but benefit you during your career. Being able to express the algorithms in different languages is very helpful, but that helpfulness sits more about what idioms the languages use not necessarily what those languages are.

In short, don't worry about it. What you use to express the algorithm is far less important than being able to express it at all.

Title: Preferring Python over C for Algorithmic Programming

Body:
I've been studying a bit of algorithms and have been looking at sites like SPOJ.pl TopCoder etc. I've seen that programmers prefer C or C++ usually for most algorithmic programming contests.

Now I've been having some trouble lately. I know both a bit of C and Python and when trying to write a code I seem to prefer Python over C for most algorithms. Everytime I sit down to write a code in C I give up after about 15 minutes because I find it too cumbersome and tend to move over to python. Passing matrices Pointers and so on seem to be useless time wasted that I could actually be utilizing to think about the algorithm itself.

Now I know and have heard from a lot of people that C is a very important language and is the bread and butter of a lot of programmers out there.

What I wanted to know was whether this approach of mine has any drawbacks/consequences/Disadvantages etc.

This is not a Python vs C debate; This a question about how this specific practice of preferring python over C because of the ease of use will affect me or any other programmer/computer Scientist in the long run.

I'd love to hear from people who've used these languages in the industry/and or to develop large software/libraries etc.


问:
JavaScript vs third party libraries
I program in Java and it doesn't make sense to me to think about learning a Java library or a framework without knowing the actual language the thing is built with. Same goes for C. I always avoided JavaScript simply because I wasn't interested in the client side of things but that has changed now.

I'm confused as to how and why do people avoid learning JavaScript and instead jump right ahead with a library like JQuery ?
How can I program without knowing the features of JS, what is a prototype based language, functions as first class citizens, OOP, closures, etc.

Also, are most of the things today in the client-side world built with the help of third party libraries?

答:
When we used to develop in JavaScript we had to write three version of the same function in order to make the function works in IE, Safari and Firefox.

JQuery take care of this problem (not perfect but better than doing it from scratch) and let you focus on the function itself.

Title: JavaScript vs third party libraries


答:
The more you have to compare to in reference to your primary language(s), the better you'll understand the design tradeoffs that went into making it particularly strong or weak at certain things and take advantage/compensate for those things. Master at least one but don't worry about being a jack of many others. That only looks good.

It's better to ask how resumes with only one language listed from "senior" developers look. The answer to that question is: "Not very interested in what they do for a living."

Title: Is it wise to be going back and forth between two programming languages?

Body:
I have been writing quite a lot of PHP for nearly two years. Now I am doing .NET (mainly c#) development. However, sometimes I go back and do some php.

My main question is, is it wise for me to continue doing this or should I continue development in C#? Would this harm me in the long run (mind you my main goal is not to be a jack o all trades) or is it a good practice to be doing?


答:
Bear in mind SPOJ.pl, the ACM competition and all similar competitions are focused on producing working code fast that is going to be thrown away right after the competition. TopCoder does this, but to a smaller extent (code there is at least properly organized at the OO-design level).

However, in the real world of programming almost every shortcut you'd take in algorithmic programming competitions is an anti-pattern. Only if you take this in mind, can you make any sort of comparison. Let's take your example: passing a multidimensional array between different functions. In a competition environment, the best approach would be to simply declare the array global to save the time figuring the proper call details (e.g. should I pass the size, or can it be determined?). In real-life programming, I'd do the exact opposite.

So, to your question, are there any complex consequences of choosing Python over C for algorithms, I'd say no. If you're only interested in the algorithm, you will do the same thing in Python and C. Implementing it in a functional language might bring forward some differences, but the algorithm is still the same.

Virtually the only thing you've gained by implementing the algorithm in C is more control over the execution and a guarantee you're using just lower-level abstractions. This isn't a small thing, since in Python much of the complexity is hidden. But if the problem is not trivial in the higher-level abstractions, then you've only possibly lost execution speed, and in most cases, you're not really trying to make the program as fast as you can, you're simply learning.

As already suggested, you can always swap a Python implementation with a C implementation if Python turns out to be too slow. But this will happen probably 2-3 times in a huge project, so starting in C might be a waste of time, unless it's your language of choice (and you've indicated it's not).


答:
As a longtime member of TopCoder and an occasional user of SPOJ I can tell you that a major reason for preferring C/C++ over other languages in competitions is its raw speed. When your program execution is timed, there is an enormous pressure to pick the "fastest" language you can get, because it gives you more slack in terms of coding your algorithm. My progression in TC went from Java to C# to C++.

However, this situation is more common in competitions than in day-to-day development: although writing optimal code is universally important, the relative importance of finishing your code as soon as you can and making it as maintainable as possible usually trumps saving a few hundred CPU cycles. If you are more comfortable coding something in Python, it is very often a preferred solution.

Moreover, Python offers high-level capabilities that are not available in C++. Building them out is often very expensive, and sometimes even impossible (for example, consider building reflection or self-modifying code in C++). In cases like that relying on a higher-level language may prove to be an optimal solution as well.


问:
Is there much thought towards internal diagnosis testing within an enterprise application?
Imagine a discussion between four people - one a developer, one a manager, one a tester and one a deployment/operations type.

The Manager is very angry as a system has fallen over after a new version of code was deployed into production. He is looking to point fingers.

Operations person pleads ignorance - they followed the deployment steps exactly.

Tester pleads ignorance - they have functionally tested code and it worked fine in test environment.

Development person pleads ignorance - they provided good code, and claim that the system badly configured.

This situation may seem familiar to some. There's always an excuse, some mistake made along the chain - from design to deployment - that allows a system to be upgraded but doesn't work as intended.

What are the pros and cons of diagnosis testing - tests run built into the application (perhaps through a command line API or something) that would allow a system to check it's internal connections (database, middleware, filesystem etc) and confirm that everything it expects to work is correct?

This is rather than relying on an external monitoring system that may not be configured in the same fashion as the application? (new release, different properties, looking at the wrong database etc)

An example :

I'm writing a class that interacts with a database. Within this class, I create a method that interacts with the database without affecting it, say a simple select query.

In the constructor of this class, I pass to an observer a test based on the arguments passed into the constructor. This observer can be called to run all the tests it has at any time so as to test for the validity of the connection - even while the system is actually running.

答:
What are the pros and cons of diagnosis testing - tests run built into the application (perhaps through a command line API or something) that would allow a system to check it's internal connections (database, middleware, filesystem etc) and confirm that everything it expects to work is correct?

Pros

It allows the deployment people to run the tests rather than you waiting until off hours to smoke test the app.

It gives you one more hurdle to clear before the boss is pissed.

Cons

It's more maintenance.

It's another exposed endpoint to input, which has its own security concerns.

It's unnecessary.

Okay, I threw this last one in here. In my experience ...

If your test environment followed best practices and mirrored production, this wouldn't be an issue.

If someone smoke tested the deployment to production, this wouldn't be an issue.

If you could write the tests to properly verify that stuff, why aren't you doing it in code already and including the cause of the failure in your errors?

And really, how are the post-deploy checks going to save your system once you've broken it?


答:
jQuery's primary role is to normalize the DOM API which is the one thing browsers haven't agreed on for over a decade (until IE9 came out). It's better thought of as a tool than a library. It's basically just a factory function that returns an adapter merged with a bit of decorator that wraps and normalizes the DOM object API with lots of cruft reduction and some additional goodies like the animate function and an event system that lets you fire and listen for new events on the fly on any object without even defining them somewhere first.

What it doesn't do is help you with writing more complex, maintainable app-oriented code (well, the event thing is neat-o but easy enough to DIY), use objects well, or use any of the core ECMA spec obects that really form the basis for the core language of JavaScript.

Among proper JavaScript devs, it takes very little time to filter out the devs who are going to be useful on a project from web designers or CMS-only devs gunning for a salary increase by doing awful things with a tool they'd rather not understand under the hood if they can avoid it.

Also, the DOM API is pretty verbose with method names that practically write their own documentation (by approaching paragraph length basically), which is a good thing, IMO. We want the core native stuff to be obvious and spelled out. But the tedious nature of writing with it encourages us to use JavaScript to do something it's very good at. Eliminate cruft, normalize, and bend the API to a paradigm that works better for us. I personally think jQuery did a bang-up job of this compared to most of its contemporaries and that you can learn a lot about JavaScript (like how to keep your objects really lightweight as far as memory is concerned) by studying jQuery under the hood.

But I wouldn't use it as a pre-fab UI library namespace. And I wouldn't discard loops in favor of using .each on everything. And I often downshift to DOM API methods when JQuery is adding work without really eliminating cruft which brings up one of the most important features of jQuery to those of us who actually know what we're doing. It doesn't get in your way when you don't want it there.

But make no mistake. If you don't know how to do it without jQuery you're at best an entry-level JavaScript/client-side dev. On the flip-side if you only know JavaScript and only have minimal understanding of CSS, you better be focused on something other than UI problems.

Edit: I realize I focused on JQ a bit too much for a question that was asked more generally.

Most other popular JS tools/libraries/frameworks are either UI libraries, none of which I'm a big fan of (too inflexible typically), and rapid-application building frameworks that apply concepts from MVC or similar patterns. I'd rather DIY architecture personally (and I'm a little wary of this model-binding in templates trend) but these new frameworks aren't the sorts of things implemented by JS devs who can't handle code problems that require JS-literacy themselves I would wager.

Title: JavaScript vs third party libraries

Body:
I program in Java and it doesn't make sense to me to think about learning a Java library or a framework without knowing the actual language the thing is built with. Same goes for C. I always avoided JavaScript simply because I wasn't interested in the client side of things but that has changed now.

I'm confused as to how and why do people avoid learning JavaScript and instead jump right ahead with a library like JQuery ?
How can I program without knowing the features of JS, what is a prototype based language, functions as first class citizens, OOP, closures, etc.

Also, are most of the things today in the client-side world built with the help of third party libraries?


答: The advantages of using higher level languages like Python or Ruby are that (1) their syntax is very close to pseudocode and (2) their standard libraries provide useful data structures out of the box (the batteries included concept that @Robert mentioned). So it's perfectly fine to prefer using them. Use whatever maximizes your productivity, instead of picking a language just because it is mainstream or "cool".</p>


问:
Is there a different usage rationale for abstract classes/interfaces in C++ and Java
According to Herb Sutter one should prefer abstract interfaces (all pure virtual functions) to abstract classes in C++ to decouple the implementation as far as possible. While I personally find this rule very useful, I have recently joined a team with many Java programmers and in the Java code this guideline does not seem to exist. Functions and their implementations are very frequently located in abstract classes.
So did I get Herb Sutter all wrong even for C++ or is there a general difference in the usage of abstract functions in C++ compared to Java. Are abstract classes with implementation code more sensible in Java than in C++ and if yes why ?</p>

答:
OOP has composition and substitution.

C++ has multiple inheritance, template specialisation, embedding and value/move/pointer semantics.

Java has single inheritance and interfaces, embedding and reference semantics.

The common way the OOP school uses these languages is to employ inheritance for object substitution and embedding for composition. But you also need a common ancestor and a way to runtime-cast (in C++ is called dynamic_cast, in Java is just asking an interface from another).

Java does all this by its own java.lang.Object rooted hierachy. C++ doesn't have a predefined common root, so you should at least define it, to come to a same "picture" (but this is limiting some C++ possibilities...).

After that, the possibility to have compile-time polymorphism (think to CRTP) and value semantic can offer also other alternatives to the way the concept of "OOP object" can be ported into a C++ program.

You can even imagine the heresy to use embedding and implicit conversion to manage substitution and private inheritance to manage composition, in fact inverting the traditional school paradigm. (Of course, this way is 20 years younger than the other, so don't expect a wide community support in doing that)

Or you can imagine a virtual common base to all classes, form interface (no implementation) to final classes (fully implemented) going through partially implemented interfaces an even interface clusters, using "dominance" as dispatching from interface to implementations through a "multi stacked-parallelogram" inheritance scheme.

Comparing OOP to java to C++ assuming there is just one and only OOP way is limiting the capabilities of both the languages.

Forcing C++ to strictly adhere to Java coding idioms is denaturating C++ as forcing Java to behave as a C++-like language is denaturating Java.

Is not a matter of "sensibility" but of different "aggregation mechanisms" the two languages have and different way to combine them that makes some idiom more profitable in one language than the other and vice versa.

OwnerDisplayName: Martin


答:
I can't comment, so I'll have to answer here.  Robert is onto something with his comments.  This seems to be a management and communication issue, and less one of testing.  So management should point the finger right back at themselves or just get over it, pointing fingers does a lot of nothing in making the product better and causes people to form sides.  /soapbox

As for the testing, there are many methodologies that match this.  Methods like Test Driven Development even place this first, before your production code is written.  Write the test that meets your specification, then write code to pass it.  These tests can be left in and made accessible for future pushes/merges of your code as a base level of acceptance, providing they don't have security issues related to the data of course.  I personally use this method in my org in our CI environment and it works great.

The main cons of using something like this when deployed to a production environment are mostly security (if you've exposed a new attack surface through one of your test hooks), or performance due to excessive use, loops, or excessive logging. The value of all of the additional information this can provide though is quite a big check in the "pro" category.  Providing someone actually uses the info, of course.  But that's a mess I won't get into.

Title: Is there much thought towards internal diagnosis testing within an enterprise application?

Body:
Imagine a discussion between four people - one a developer, one a manager, one a tester and one a deployment/operations type.

The Manager is very angry as a system has fallen over after a new version of code was deployed into production. He is looking to point fingers.

Operations person pleads ignorance - they followed the deployment steps exactly.

Tester pleads ignorance - they have functionally tested code and it worked fine in test environment.

Development person pleads ignorance - they provided good code, and claim that the system badly configured.

This situation may seem familiar to some. There's always an excuse, some mistake made along the chain - from design to deployment - that allows a system to be upgraded but doesn't work as intended.

What are the pros and cons of diagnosis testing - tests run built into the application (perhaps through a command line API or something) that would allow a system to check it's internal connections (database, middleware, filesystem etc) and confirm that everything it expects to work is correct?

This is rather than relying on an external monitoring system that may not be configured in the same fashion as the application? (new release, different properties, looking at the wrong database etc)

An example :

I'm writing a class that interacts with a database. Within this class, I create a method that interacts with the database without affecting it, say a simple select query.

In the constructor of this class, I pass to an observer a test based on the arguments passed into the constructor. This observer can be called to run all the tests it has at any time so as to test for the validity of the connection - even while the system is actually running.


答:
You make it sound as though this enterprise application is a web application.  Rarely, are test environments every exact mirrors of production.  Even if there is a pre-prod environment between test and prod, it's a challenge to keep it as an exact mirror of prod, especially in an enterprise environment where there may be different teams responsible for the maintenance of each environment.  All of the testing in the world may not have caught this before going to production.

What you are suggesting sounds much like a common health check page.

Cons:

Many developers may feel that it is a waste of time

People may forget that it exists and not use it

Everything that Telastyn mentioned

Pro's:

Allows for on the fly checking of all key config files and
integration points

Speeds up trouble-shooting immensely.  Support staff can often diagnose issues before getting development team involved.

Allows preliminary validation to be completed before production smoke
testing is even started

Personally, I'm a huge fan of these kinds of tests.  They make my life as a tester a whole lot easier.  Support staff and developers also tend to really like these pages as well after needing them once.  Can make the world's difference when trouble-shooting.


答:
In my experience, when people have excess difficulty coding algorithms in C, it's often because they are tightly coupling their data structure management with their algorithm instead of creating appropriate abstractions.  For example, manually manipulating linked list pointers everywhere instead of making push() and pop() functions.  They are too accustomed to having those abstractions provided to them.

While this problem is much more evident with lower level abstractions, failure to recognize tight coupling and create appropriate abstractions is a problem at any level.  Practicing these skills in C until you can make an algorithm that looks clean and readable will carry over to any language you use.

The other problem I occasionally see among python programmers is difficulty adapting for performance at scale.  Granted, performance isn't usually the primary concern, but the most pythonic way to implement an algorithm for a relatively small data structure can grind your system to a halt when you're working with gigabytes or more of data.  Becoming a good C programmer helps you be more aware of those kinds of issues in any language.

Can you learn those skills in other languages?  Sure, but C helps by making it a lot more obvious when you get it wrong.

That being said, I use python for algorithmic programming when I have a choice, even though I'm just as comfortable in C.  Python has language features that make it very nice for that kind of programming, and performance differences are usually negligible.  I can't speak to why other programmers who know both would choose C.  I imagine a lot of them do it simply to set themselves apart from the crowd.


问:
Should a github maintainer rewrite author's in pull requests?
I'm not a programmer by profession, but I do some coding and have used github some.  I've run across what I find to be a surprising situation.  I'm very familiar with git.

There is a project which I found a (small) bug in that was affecting me.  I spent an afternoon finding and fixing it.  I forked the repository, commit the change, and issued a pull request.   After seeing that it was closed as "Merged into development branch" I figured all was well.

I was browsing the repo today getting ready to remove my branch, and I can't find where the commit was merged into the maintainer's repo at all.  After some time I realize it's been added as a commit, but the author is no longer me.

As far as I can tell the only way to do that would be to specifically use a rebase, amend, or other history rewrite to remove the original author.

This seems very wrong to me.  At best it's confusing, at worst the author of this repo is taking credit for everyone's commits and then the history of the original contributor is lost.  Again it's a small bug, I don't use this for my professional resume, it just seems dishonest.

Is this normal?
Should I say something about it?

Edit: The general feeling seems to be that I should go ask, so I'll do just that this morning.

As per the request below.  I've checked and my code exists and was applied exactaly as I wrote it (including the comment).  I verified that both the committer and author have been changed.  There was one additional change also added at the same time as my changes.  It's a single line, which would affect the patch as well as other code before it.  IE the one line addition is not related to the bug I was fixing.

Update
It seems the answer was that the author maintains a development branch and does not want to merge from his master branch into it.  He re-authored my commit to avoid a merge.  I wasn't concerned with the original branch b/c git's plenty powerful to cherry-pick, rebase, and merge commits around as needed.

Is this typical on github?

Should I be contacting the maintainer of a project to ask which branch to apply patches to?

答:
You have left out some key details here.

If the way you "fixed" the bug was not to the maintainers liking, or even
incorrect in that it introduced its own bugs, then the maintainer might have
had to edit your work before committing. In which case it is understandable to
change the author.

As others have mentioned the author is quite different from the
committer. As you may already know the author is the one who actually
created the commit, while the committer would be the one to apply it.

You should take a close look at the commit and update your question with your findings.

OwnerDisplayName: svnpenn


答:
On the whole, Javascript frameworks solve DOM interaction problems. The rest JS has nothing to do with the DOM.

Of course, many frameworks supply functions to JS behave more like a standard OO language, such as by adding "classes" (uugh, now my mouth tastes dirty). I'd say, just learn JS for what it is and avoid that crap. To me it's like trying to program C++ as a functional language. You can kind of do it, but it's better to learn C++ as it really is.

Title: JavaScript vs third party libraries


问:
What simple techniques do you use to improve performance?
I'm talking about the way we write simple routines in order to improve performance without making your code harder to read... for instance, this is the typical for we learned:

```<code>for(int i = 0; i < collection.length(); i++ ){
   // stuff here
}
</code>```

But, I usually do this when a foreach is not applicable:

```<code>for(int i = 0, j = collection.length(); i < j; i++ ){
   // stuff here
}
</code>```

I think this is a better approach since it will call the length method once only... my girlfriend says it's cryptic though. Is there any other simple trick you use on your own developments?

答:
I have a very simple technique.

I make my code work.

I test it for speed.

If it's fast, I go back to step 1 for some other feature.  If it's slow, I profile it to find the bottleneck.

I fix the bottleneck.  Go back to step 1.

There are plenty of times where it saves time to circumvent this process, but in general you'll know if that's the case.  If there's doubt, I stick to this by default.


答:
If a question ever goes on about 'Big O notation' and you try and measure that, then it can be harder to do in Python unless you know a lot more about how python implements things, for example a Python list is not a linked list; Pythons sort is TimSort; Python garbage collects at certain times...

I always find it easier to connect a C program to what is likely to be happening on a processor, but even here, there is processor caching; time-slicing of the OS; Compiler optimizations etc that can affect my intuition.

I find it quicker to write and debug Python code so, when given a choice, I would write first in Python concentrating on getting something that worked. With this working Python program you can often slot it into a larger system and find out not only that it worked but also if it was fast enough or in what aspect was it slow. Getting some real performance data then helps when you optimize for speed and allows you to test the Python version against any later rewrites in Python or C or whatever.

So drawbacks to using just Python is that it can be difficult to reap the benefits of algorithms that were written expecting some C-like compilation to processor model.
Drawbacks to using just C are as you have stated: Its a pig to write and debug and you end up having to write your own libraries too often.

I think it would be best to use them both (and other languages), until you get a feel for their trade-offs. I myself was a good C coder but now write very little original C code, although I still have to read (and sometimes debug) C code in my work. Although I prefer Python, I know and still use Perl and Awk (and sed and grep and sort and Tcl and C and ...).


问:
How big does my project need to be for me to unit test it?
I assume that my project is decoupled enough to allow for unit testing. But how big, exactly, in terms of clases and functions does my project need to be to make unit testing worthwhile?

We all make mistakes and no one's perfect, but I consider myself a decent programmer to handle small projects' errors with stepping through. Or is unit testing a hard necessity no matter of what size your project is?

答:
It really isn't a matter of size-- it's what you do with it (and how old it is). If I'm noodling around learning how a technology works and plan on throwing the thing away (we call this a spike in Scrum), I'll just code without doing much testing. If you are planning on developing it further (even if you are just noodling around), you should write tests around the code. TDD is a design technique even before it is a testing technique. You want to have a clear picture of what you want the code to do before you get bound up in the particulars of the execution. I would also NOT recommend trying to write extensive unit tests around large amounts of legacy code. Try to identify those parts that are complex (have a high cyclomatic complexity/spaghetti code feel to them) and those parts which fail frequently (they will often be the same).
As others have suggested, I'd go read Kent Beck's book on TDD and definitely read Michael Feather's book. What they don't cover very much is the political aspect to writing unit tests around code. A lot of developers hate having to alter their code to make it testable, and a lot of developers do not feel the need to test code at all. It is something we have to work on as a profession. Every other engineering discipline is required to prove (often mathematically) that their work met the specification. We should do the same.


问:
Public-private key pair handling on a Windows ecosystem
I've been thinking about how to architect an infrastructure for one of our business applications with the following requirement:

Data written by some user can only be read by that user and his superior and a 3rd person yet to be defined

I'm thinking in using some sort of asymmetric algorithm, such as RSA for data encryption.

We can generate a public-private key pair for each user and store the public key of each one openly on a database, but how should we handle the private key ?

If we just let the users manage their private key one day we will have a big headache if one of them loses his key.

If the private key becomes public somehow then the data would become public too, rendering the architecture invalid.

Our infrastructure is heavily Microsoft-oriented: All applications are ASP.Net MVC3, our dabatase is SQL Server 2005 and we use Active Directory for user authentication and basic data, such as e-mail/phone number.

How would you guys architect a solution to solve this problem ?

Bottom-line: This is not a banking or financial application, it's some kind of 360-degree personal feedback system.

EDIT:
Adding more requirements, hoping to make it more clear:

This database will be in production environment, where developers don't have access;

When the database is restored, developers should not be able to recover the data;

The DBA should not be able to view the data by SELECT'ing the rows on the tables;

EDIT 2: Bounty info.
Bounty went to the answer with more upvotes, although my personal feel is that none of the answers provided addressed the question correctly. For this reason, I'm granting the bounty but not marking the answer as correct.

答: Just a thought, you might be getting bogged down in the HOW and forgetting the WHAT. What you want is keep reviews anonymous to anyone but the user, the person who supervises him, and one other person (possibly a third party auditor). I would keep the public/private key as one option, but not the only option. It sounds like you need to create a graph situation where relationships grant certain privileges. I've been looking at using something like Neo4j for a business-oriented internal social graph. You could have more luck using something like this than your traditional relational database. Neo4j can be queried by http/https (so you can do this from MVC). I'm kind of new at playing around with graph databases, but they look promising for doing a lot of these kinds of things.


问:
Feature vs. Function
Often I hear PMs (Project Managers) talk about feature and function. And I'm just so puzzled to differentiate them. Sometimes I think of a feature to be equivalent to a user story. Something like "As a user, Bob should be able to see a list of his payments", and they call it a feature. Sometimes it gets as big as a subsystem, something like "the ability to send SMS via web application". Function on the other hand sometimes gets as small as a task, "implementing digit grouping for number inputs", while there are cases when it gets as big as a whole CRUD operation.

My question is, how can we differentiate feature from function?

答:
Behind each feature is the functionality needed to provide the user with the intended purpose of the feature.

Example: A university's registration system would have a "student registers for classes" feature.  This task requires quite a bit of functionality as well as access to a database. The design for the feature would involve an understanding of the user's actual task - registering for classes.  This would be a prerequisite to the "interaction design" necessary to facilitate the users task. The functionality would be designed to implement the interaction requirements.

Programmers are looking for functions to code.  Interaction designers are looking for the best way to deliver this needed functionality through the design of the software's  interaction with the user. Understanding of how the user can best achieve his or her objective comes first.  Identification of the needed functionality follows.

The above is not scientific, it is only my opinion.

Title: Feature vs. Function


问:
Is it bad practice to use an interface for categorization only?
For example:

Say I have classes A, B, C. I have two interfaces, lets call them IAnimal and IDog. IDog inherits from IAnimal. A and B are IDogs, while C is not, but it is an IAnimal.

The important part is that IDog supplies no additional functionality. It is only used to allow A and B, but not C, to be passed as an argument to certain methods.

Is this bad practice?

答:
There is nothing wrong with having an interface which inherits another interface without adding new members, if all implementations of the latter interface will be expected to be able to usefully do things which some implementations of the former may not.  Indeed, it's a good pattern which IMHO should have been used more in things like the .net Framework, especially since an implementer whose class would naturally satisfy the constraints implied by the more-derived interface can indicate that simply by implementing the more-derived interface, without having to change any of the member-implementation code or declarations.

For example, suppose I have the interfaces:

```
interface IMaybeMutableFoo {
  Bar Thing {get;set;} // And other properties as well
  bool IsMutable;
  IImmutableFoo AsImmutable();
}
interface IImmutableFoo : IMaybeMutableFoo {};
```

An implementation of IImmutableFoo.AsImmutable() would be expected to return itself; an mutable class implementing IMaybeMutableFoo.AsImmutable() would be expected to return a new deeply-immutable object containing a snapshot of the data.  A routine which wants to store a snapshot of the data held in an IMaybeMutableFoo could offer overloads:

```
public void StoreData(IImmutableFoo ThingToStore)
{
  // Storing the reference will suffice, since ThingToStore is known to be immutable
}
public void StoreData(IMaybeMutableFoo ThingToStore)
{
  StoreData(ThingToStore.AsImmutable()); // Call the more-specific overload
}
```

In cases where the compiler doesn't know that the thing to be stored is an IImmutableFoo, it will call AsImmutable().  The function should return quickly if the item is already immutable, but a function call through an interface does still take time.  If the compiler knows that the item is already an IImmutableFoo, it can skip the needless function call.

Body:
There is nothing wrong with having an interface which inherits another interface without adding new members, if all implementations of the latter interface will be expected to be able to usefully do things which some implementations of the former may not.  Indeed, it's a good pattern which IMHO should have been used more in things like the .net Framework, especially since an implementer whose class would naturally satisfy the constraints implied by the more-derived interface can indicate that simply by implementing the more-derived interface, without having to change any of the member-implementation code or declarations.

For example, suppose I have the interfaces:

interface IMaybeMutableFoo {
  Bar Thing {get;set;} // And other properties as well
  bool IsMutable;
  IImmutableFoo AsImmutable();
}
interface IImmutableFoo : IMaybeMutableFoo {};

An implementation of IImmutableFoo.AsImmutable() would be expected to return itself; an mutable class implementing IMaybeMutableFoo.AsImmutable() would be expected to return a new deeply-immutable object containing a snapshot of the data.  A routine which wants to store a snapshot of the data held in an IMaybeMutableFoo could offer overloads:

public void StoreData(IImmutableFoo ThingToStore)
{
  // Storing the reference will suffice, since ThingToStore is known to be immutable
}
public void StoreData(IMaybeMutableFoo ThingToStore)
{
  StoreData(ThingToStore.AsImmutable()); // Call the more-specific overload
}

In cases where the compiler doesn't know that the thing to be stored is an IImmutableFoo, it will call AsImmutable().  The function should return quickly if the item is already immutable, but a function call through an interface does still take time.  If the compiler knows that the item is already an IImmutableFoo, it can skip the needless function call.


答:
I believe a correct distinction has to be drawn for a specific methodology or a specific requirements culture. The following is my own interpretation.

Function: A core requirement that affects the value of the software dramatically, that the user must have at a specific release. Example: Save function on a text editor.

Feature: A nice to have capability of the software, that adds value to the software but is not an absolute must for the software to function properly and perform its functions. For example, have an undo feature on a data entry form or save a document as gif file for a text editor(wired!).

Title: Feature vs. Function

Body:
Often I hear PMs (Project Managers) talk about feature and function. And I'm just so puzzled to differentiate them. Sometimes I think of a feature to be equivalent to a user story. Something like "As a user, Bob should be able to see a list of his payments", and they call it a feature. Sometimes it gets as big as a subsystem, something like "the ability to send SMS via web application". Function on the other hand sometimes gets as small as a task, "implementing digit grouping for number inputs", while there are cases when it gets as big as a whole CRUD operation.

My question is, how can we differentiate feature from function?


问:
When is a BIG Rewrite the answer?
Just read the question about the Big Rewrites and I remembered a question that I've been wanting answered myself.

I have a horrible project passed down to me, written in old Java, using Struts 1.0, tables with inconsistent relationships, or no relationships at all and even tables without primary keys or fields meant to be primary keys but aren't unique at all. Somehow most of the app "just works". Most of the pages are reused (copy pasted code) and hard-coded. Everyone who's ever worked on the project has cursed it in one form or the other.

Now I had long considered to propose to upper management a total rewrite of this horrendous application.  I'm slowly attempting to on personal time but I really feel that this deserves some dedicated resources to make it happen. Having read the articles on big rewrites I'm having second thoughts. And that's not good when I want to convince my superiors to support my rewrite. (I work in a fairly small company so the proposal has the possibility of being approved)

TL;DR
When is a big rewrite the answer and what arguments can you use to support it?

答:
Well I can imagine hypothetical scenarios where I might just throw out the existing code base (hypothetical situations where the bucky balls have zero weight and volume, where no one cares if we lose weeks or months of productivity as we scramble to add overlooked features and bug fixes into the system, and where the system is so trivial and hated by an organization that I can replace the entire thing and army of servers with notepad++ and a netbook in ten minutes and boost everyone’s productivity and moral across the board.)

For almost any real world scenario though I would just recommend refactoring in place. ^_^. There tend to be too many hidden, unanticipated costs to rewrites when undocumented legal and business requirements start to pop-up and the last minute hacking things together last minute starts to ensue.

==Refactoring in Place for greater good, and stuff==

Refactoring legacy code with the regular old incremental approach,

If you have the chance convert to UML and document what little knarly architecture there is.

If you are on version control look into generating some code churn reports and figuring out which files and file sections have been changed the most frequently. Make a note of these as they will likely be the areas you will want to deal with first.

Before you change any code always try to add some test coverage (even ugly full stack functional tests will do).

If dealing with large messy procedurial code extract logic you intend on changing into some reasonably named method or function and if possible add some test cases that verify your new method.  make whatever god awful hack you have to and if possible paramatize the change if it is something commonly tweaked like margin width or title so it will be a little more straight forward to update the next time.

Use the adapter pattern and work away at hiding the knarly bits of legacy code under a rug of logically named classes and methods so that for most common tasks you and the other developers perform you wont need to worry about the scary bits that are going on behind your back behind those nice little clean methods and classes you've hidden that legacy code behind -- like those nice families that keep deformed murderous zombie former family members in barns so that they don't spoil the day to day going-on’s of the farm . . . normally.

As you continue to whittle away and clean up the sections of the code continue to boost your test coverage. Now you can dig down even deeper and "rewrite" even more code when needed/desired with ever increasing confidence.

 Repeat, or apply additional refactoring approaches to continue to improve your codebase.

Branching By Abstraction

Define the trouble spot in the code you want to remove (the persistence layer, the pdf generator, the invoice tally mechanism, the widget generator, etc.).

run (write if necessary) some functional test cases (automated or manual but you know automated) against the code base that targets this functionality along with general behavior.

Extract logic related to that component from the existing sourcebase into a class with some reasonable interface.

Verify all code is now using the new interface to perform activity X which was previously dispersed randomly throughout the code(Grep the code base, add a trace to the new class and verify pages that should be calling it are, etc.), and that you can control which implementation will be used by modifying a single file.(object registry, factory class, whatever   IActivityXClass = Settings.AcitivtyXImplementer();)

 rerun functional test cases that verify everything is still functioning with all of Activity X throwin into your new class.

Write unit tests where possible around the new activity X wrapper class.

implement a new class with less insane spaghetti logic than the legacy implementation that adheres to the same interface as the legacy class.

verify that the new class passes the unit tests you wrote for the legacy class.

update your code by changing the registry/factorymethod/whatever to use the new class instead of the old class.

verify that your functional tests still pass.

Open Closed Principle and a Common Business Logic/Persistence Layer

To some extent you might be able to get away with separating out your presentation, business and persistence layer and writing a new app that is fully backwards compatible with the legacy solution, or at a minimum can still handle data inputted by legacy solution. I would probably not recommend this approach but sometimes it is a reasonable compromise of time/schedule/resources/required new functionality.

 At a minimum separate the presentation layer away from the business and persistence layers.

 implement a new ui and better presentation layer that uses the same common business and persistence layer.

 Verify that data created with new ui does not break old ui.  (you're going to be in hot water if users of the new tool interrupt users of the old tool).

If you are striving for full backwards compatibility you should be saving everything to the same persistence layers. If you just want forward compatibility into the new tool then use a new database and new tables or extension tables to track data not in legacy system.

 For new functionality and persistence layer needs add new tables and methods don't change existing legacy logic, or add columns, constraints to existing tables.

e.g. if you need to start tracking employers emergency contact and some other fields don't modify the existing employee table (we have no idea what assumptions the legacy data makes about that table)  add an extension table employee_ext  id, employee_id, emergency_contact_id, etc_id.

Slowly migrate users onto new system. if possible put legacy system into read only mode, or just add some warning telling users it will no longer be available after date X.

implement any hi priority missed functionality or business requirements in the new ui

 roll over users base.

 continue on to clean-up the business logic and persistence layer users other refactoring methodologies.

Title: When is a BIG Rewrite the answer?


问:
Where Should I Put Configuration Files?
I'm creating a project that I want to be able to distribute across platforms. I'm writing in Java and AWT which already gives me a pretty large range of devices, but I'm mostly interested in Windows and Linux (Debian/Ubuntu).

I'm trying to determine where I should put config files. I have application-wide configuration files and user-specific files. Where are common directories to put these files?

Here's my current setup:

Windows:

App Config: %PROGRAMDATA%\MyApp\config\

User Config: %USERPROFILE%\AppData\Local\MyApp\

Other:

App Config: /opt/MyApp/config

User Config: $HOME/.MyApp/

答:
This sounds OK, it's pretty much what most software does. But in Linux, you might want to put the app configuration files in /etc (or under a subdirectory, e.g. /etc/myapp) as it's more fitting to the FHS:

/etc Host-specific system-wide configuration files

Also, you might want to put user configuration in ~/.config/MyApp rather than ~/.MyApp. This helps reduce clutter in the user's home directory.

Title: Where Should I Put Configuration Files?


答:
I'm no expert, but in my experience, Linux puts some default (non-editable) config files in /etc/your-app-here, whereas user-editable config files these days go in ~/.config/your-app-here (that is $HOME/.config/your-app-here)

Reference link

Title: Where Should I Put Configuration Files?

Body:
I'm creating a project that I want to be able to distribute across platforms. I'm writing in Java and AWT which already gives me a pretty large range of devices, but I'm mostly interested in Windows and Linux (Debian/Ubuntu).

I'm trying to determine where I should put config files. I have application-wide configuration files and user-specific files. Where are common directories to put these files?

Here's my current setup:

Windows:

App Config: %PROGRAMDATA%\MyApp\config\

User Config: %USERPROFILE%\AppData\Local\MyApp\

Other:

App Config: /opt/MyApp/config

User Config: $HOME/.MyApp/


答:
Binding a Projects in limits of classes or functionality and then judging if this is suitable for unit testing may be wrong. There are numerous benefits of unit testing an application but real beauty starts when you have to maintain an application or have to work in distributed environment. So the choice comes here. Even a small change in your code can cause disasters.

I would not only suggest 'Unit Testing' but would also recommend to check your code coverage, ensuring maximum of your code is covered with Unit Test. Threshold for code coverage shall not be less than 95% and target must be around 100%. You can go for tools to track your code coverage and generate a report.

Visual Studio Provides Coverage Data - http://msdn.microsoft.com/en-us/library/ms182496(v=vs.80).aspx

Also you can use NCover or dotCover.

Title: How big does my project need to be for me to unit test it?

Body:
I assume that my project is decoupled enough to allow for unit testing. But how big, exactly, in terms of clases and functions does my project need to be to make unit testing worthwhile?

We all make mistakes and no one's perfect, but I consider myself a decent programmer to handle small projects' errors with stepping through. Or is unit testing a hard necessity no matter of what size your project is?


答:
JS has more in common with languages like LISP or PROLOG than Java. Syntax is similar to Java, which is misleading and the frameworks are designed for not-so-clever PHP beginners. So they try to emulate some outdated, horrible OOP model. And the code these beginners produce is just sub-standard, ugly and hard to modify.

Of course that OOP model works on server side very well, but it's horrible for client side UI. JS has completely different programming model, very well suited for UI developping (easy callbacks, prototypal inheritance, super-easy encapsulation, very clean object model, etc.).

jQuery... that's most easy to use, but it is most horrible. With constructs like parent().parent().parent()... it's designed to "shield" you from "real" JS by providing some horrible PHP-like OOP model. That's why, probably is so widely adopted. People don't have time to learn JS so they just use jQuery and pretend it's Java or PHP.

instead jump right ahead with a library like JQuery ?

Just stay away from it. There is no worse code in JS that code written using JQuery. Or course if you previously used Java it'd look "ok" for you. But that's not true. You can write so much better, error-free and modular code using pure JS or mootools (because it's extending JS rather than replacing it's object model).

Using that BS those frameworks provide (like "classes") it's like going back from C++ to C, just because you can't think beyond simple functions and global variables. So you need something that'll "dumb down" the language so you can write some very crappy code without learning any new things.

Title: JavaScript vs third party libraries


问:
Have you ever found yourself using a specific tool in favor of another just because it looks better?
I found that this was the case with Eclipse.
When I first started learning Java a lot of people told me to start with NetBeans because it's easier, comes with a lot of predefined functionality and most of the configuration is done by default. Indeed it seemed like an easy IDE but I just hated the way it looked. The UI to me was horrible.

Then I downloaded Eclipse. I was pretty impressed with it. Everything looked shiny, fonts looked awesome and the UI in general was amazing compared to NetBeans'. So I stayed with Eclipse.

Has something like this ever happen to you? Should the UI be of such a relevance to a programmer, is this bad ? The problem of the UI extends to everything for me, not only IDE's (e.g. even on linux I have to customize the WM the way I want before starting working with it).

答:
Sure. I'm moving a number of my projects to Visual Studio 2010 from older versions. Partly it's so I can use the same tool on all my projects, partly it's because of all the great extensions for 2010, and partly it's because 2010 looks nicer and has a nicer UI. Productivity is the name of the game for software developers and if you are more relaxed and happy using a tool, you're more productive.

That said, "looks better" is in the eye of the beholder. I can't tell you how many times I've been told that Expression (Blend, Web etc) "looks better" than Visual Studio. I hate the black look, I hate that all the menus and toolbars behave differently depending on the thing you click first, I hate the tiny font and I hate that it's so cluttered and clicky oriented. I use it only when I have to. That proves I guess that I choose my tools based on looks when I can, but my point is one person's "looks better" is another "I hates it".


问:
Analogy for Thread Pools
I am working on an application which spawns a new thread per request. Sometimes the number of threads active on the machine at one time is in the high hundreds. It's suspected that this is causing all sorts of problems. I would like to experiment with using thread pool instead to see if this improves work throughput. But first, I have to convince the powers that be to allow me the time.

As part of my argument, I think a good analogy that compares the brute-force "launch x threads" method to the technique of thread pools would help. Is there a text-book analogy for this?

答:
Not quite a text-book analogy:

Thread pooling for application is like recycling for communities.

Every time we're thirsty we can go ahead and buy a new bottle of water made of all new matrials. It's easy, relatively cheap for us and quite profitable for a manufacturer. Unfortunately it doesn't scale:

In a similar way, creating a new thread each time from the ground up is wasteful (potentially slow), and it doesn't have a safeguard. Too many threads could exhaust resources of an execution environment, just like too many plastic bottles could overwhelm and poison a natural habitat.

Title: Analogy for Thread Pools


答:
Threads in thread pools are often called "worker thread" for good reasons. They are like some workers in a company, ready to work on some "tasks", each one taking some work space to work, each one having it's queue of task to process.

Launching a thread just to execute a task is like finding the resources to hire someone specifically for this task, making her do it, then firing her.

Obviously, if the task is very long, rare and specific, there might be no trouble with this, but the more often this occur, the more expensive it is.

In this case, just putting the task on top of the task queue of a worker can be enough. If he take too much time to start working on it, another worker that will have no more tasks to do can steal the task from his queue. If no worker are available for some time then it means that either you don't have enough workers, or it cannot be done fast with the available resources. In particular, if you already have the maximum amount of workers you can use without everybody walking on feet of others, like in a thread pool, then you can do nothing about it other than have a bigger place (better hardware) or reduce work load.

This analogy can also easily explain the cost of interruption and communication.

Title: Analogy for Thread Pools

Body:
I am working on an application which spawns a new thread per request. Sometimes the number of threads active on the machine at one time is in the high hundreds. It's suspected that this is causing all sorts of problems. I would like to experiment with using thread pool instead to see if this improves work throughput. But first, I have to convince the powers that be to allow me the time.

As part of my argument, I think a good analogy that compares the brute-force "launch x threads" method to the technique of thread pools would help. Is there a text-book analogy for this?


答:
Imagine eating an entire package of Oreo cookies. The experience would be so much more enjoyable if you didn't have to eat the dry chocolate wafers every time you want a delicious creamy center, right? Using thread pools is like stacking the centers of all those cookies between a single pair of wafers!

That analogy will be much more convincing if you profile your code and show how much time your machines spend starting and stopping threads (eating the wafers) vs. time spent on creamy centers (actually handling requests).

Take a look at libdispatch if you need an implementation.

Title: Analogy for Thread Pools


问:
Is it bad to use Unicode characters in variable names?
I recently tried to implement a ranking algorithm, AllegSkill, to Python 3.

Here's what the maths looks like:

No, really.

This is then what I wrote:

```<code>t = (µw-µl)/c  # those are used in
e = ε/c        # multiple places.
σw_new = (σw**2 * (1 - (σw**2)/(c**2)*Wwin(t, e)) + γ**2)**.5
</code>```

I actually thought it is unfortunate of Python 3 to not accept √ or ² as variable names.

```<code>>>> √ = lambda x: x**.5
  File "<stdin>", line 1
    √ = lambda x: x**.5
      ^
SyntaxError: invalid character in identifier
</code>```

Am I out of my mind? Should I have resorted for a ASCII only version? Why? Wouldn't an ASCII only version of the above be harder to validate for equivalence with the formulas?

Mind you, I understand some Unicode glyphs look very much like each other and some like     ▄ (or is that ▗▖ ) or ╦  just can't make any sense in written code. However, this is hardly the case for Maths or arrow glyphs.

Per request, the ASCII only version would be something along the lines of:

```<code>winner_sigma_new = ( winner_sigma ** 2 *
                    ( 1 -
                     ( winner_sigma ** 2 -
                       general_uncertainty ** 2
                     ) * Wwin(t,e)
                    ) + dynamics ** 2
                   )**.5
</code>```

...per each step of the algorithm.

答:
Do you understand the code? Does everyone else who needs to read it? If so, there's no problem.

Personally I'd be glad to see the back of ASCII-only source code.


答:
I believe that it's not the size of the project but the type of project which decides if it should use testing or not.

If you are working on a proof of concept, or on some other project where the goal is to learn from the coding, then testing is not required. If the project is meant to be used, maybe even sent into production, then it should be tested.

A quote from Robert C. Martin's "Clean Code": "If it's trivial to write, it's trivial to test", so there's no excuse to skip on the testing for short and trivial programs.


问:
How have languages influenced CPU design?
We are often told that the hardware doesn't care what language a program is written in as it only sees the compiled binary code, however this is not the whole truth. For example, consider the humble Z80; its extensions to the 8080 instruction set include instructions like CPIR which is useful for scanning C-style (NULL-terminated) strings, e.g. to perform strlen(). The designers must have identified that running C programs (as opposed to Pascal, where the length of a string is in the header) was something that their design was likely to be used for. Another classic example is the Lisp Machine.

What other examples are there? E.g. instructions, number and type of registers, addressing modes, that make a particular processor favour the conventions of a particular language? I am particularly interested in revisions of the same family.

答: I did a quick page search and it seems that no one has mentioned CPU's developed specifically to execute Forth. The Forth programming language is stack based, compact, and used in control systems.</p>


问:
What are the similarities between Perl and Java?
I have my mind set that I'm learning Java as my second language (I am a Perl developer). But just from reading a little of the online tutorials, I really can't find any similarities between the two. What will I have an easy time understanding when learning Java?</p>

答:
Taking a stab at an alternative answer since the currently selected one seems to be focusing on differences between the two (truly there are not a lot of similarities between Perl and Java).

Similarities

They are both C-like (they have loops and braces and semi-colons)

They are principally imperative

Neither produce compiled binaries

They are both very mature

They are both battle-tested in the enterprise (Perl more as ops glue and Java more as applications/services)

They are both popular

They both support object-orientation

They both have a wide array of frameworks available

They both have books published about them

They are both higher-level than C/assembly

They are both "slow" (for various, specific scenarios of slow in that neither are C/assembly)

They both manage memory automatically ("garbage collection")

Neither are hip/cool as of summer 2012

They are both entrenched in the open source community

They are both available for many platforms

If your Perl code is very rigorous and orthogonal (well-tested, well-documented, uses Moose or strict object-orientation), then those concepts will carry very well into Java, since Java is extremely orthogonal and not as expressive.


问:
How to search for information related to Go programming language?
If there's something that would kill Go language, then it's name.

I find it very hard to find anything in web related just by using "Go" in the query. The word is on of the most frequent in English. So I see everything in the result except Go-related stuff. Even Google, who sponsors the language and famous for tracking anything I search, can not track I'm a programmer so interested in the programming language and not English grammar.

How to search for information related to the programming language itself, excluding the results related to English grammar?

Imagine for example a blog post where someone mentions his observation about Go. He probably won't use the easy-to-search sentence like "go programming language", maybe something "there's one thing I like about Go".

答:
Answering myself with a little hint I found
Bing search engine has an interesting operator linkfromdomain. The search restricts results to pages that were linked from mentioned domain. Sure, stackoverflow.com is good choice for this. So anyone searching for Go related information (for example [Go inheritance]) can query Bing with

```<code>linkfromdomain:stackoverflow.com Go inheritance
</code>```

and get much more programming-related information than with usual queries.

Body:
Answering myself with a little hint I found
Bing search engine has an interesting operator linkfromdomain. The search restricts results to pages that were linked from mentioned domain. Sure, stackoverflow.com is good choice for this. So anyone searching for Go related information (for example [Go inheritance]) can query Bing with

linkfromdomain:stackoverflow.com Go inheritance

and get much more programming-related information than with usual queries.


问:
How to inspire an intern with programming?
The situation is this - we took an intern for a summer with a mind that if he will catch up during summer, we will keep him as a part time junior developer.

We took him after his first year in university, so his knowledge was way too low to be involved into real projects(actually he programmed only in university), so my task was to push as much stuff as I can to have him ready for joining real projects in September. As long as we are remote developing team, we gave him possibility to have its internship remotely, with flexible hours.

So two months passed and I'm not impressed with his progress. I gave several tasks to implement, access to learning resources, recommended start paths and so on, agreed that he will report every couple days, we had pair sessions from time to time, reviewed his code together and etc.

Anyway, it looks like he spent less time writing code than I expected and before I would say that he didn't performed well enough to join our team, I was thinking may be that is my fault, may be I was pushing too much stuff, that is important in real life projects (like unit testing, structuring code, database stuff, etc.) and not enough fun stuff, that would hook up him on programming and that is the reason he spent less time than I hoped.

So I have ~20 days left and I can use them to inspire him with programming, question is with what and how?

答:
It sounds like you pushed too hard and he might be a bit overwhelmed, I've known seasoned developers that couldn't really grasp unit testing and I imagine it was too much to handle for someone with only a year of formal education. And you can't really force inspiration.

The first thing I would do would be to talk to him and find out what he found enjoyable so far, and concentrate on that for the rest of his internship. We can propose a thousand fun programming related activities, but what's fun for me will probably not be fun for your intern.

If there's at least one aspect of the job he found enjoyable I'd suggest the two of you build a mini project around it, even something unrelated with the job. If for example he enjoyed working with databases (doubt it ;), you could build a basic CRUD application, and then expand on stored procedures and other database related black magic stuff.

At the end of the day though, you should be prepared for the possibility that he's just not what you are looking for.


答:
You might be pushing too hard with unit testing and real-world database staff. However, his skill level should be in a good shape to fix bugs by now.

My understanding of internship is a bit different. Mostly interns are in their last year of Computer Science study, who have good potential for re-search as well as know basics of writing code, building their own small applications. However, being in a first year of university and not having code experience before starting university makes intern candidate very low skilled.

I do belief that most important skill in intern/junior programmer is his analytically reasoning skills. It might be better to have him in the office and guide him face-to-face while tracking his progress and approach in implementation of assigned tasks. Because, you may also observe about his soft skills (like communication, attitude, overall fit to your company environment).

In terms of motivation: you may inspire him by guiding to the right resources (to improve his skills or provide chance to learn) and assigning small, doable tasks every day. He might be feeling more satisfied if he would be accomplishing some low level tasks everyday and get more interested in the process of learning and contributing to the real code. However, i would strongly recommend to review his code before checking to the main trunk.

Title: How to inspire an intern with programming?

Body:
The situation is this - we took an intern for a summer with a mind that if he will catch up during summer, we will keep him as a part time junior developer.

We took him after his first year in university, so his knowledge was way too low to be involved into real projects(actually he programmed only in university), so my task was to push as much stuff as I can to have him ready for joining real projects in September. As long as we are remote developing team, we gave him possibility to have its internship remotely, with flexible hours.

So two months passed and I'm not impressed with his progress. I gave several tasks to implement, access to learning resources, recommended start paths and so on, agreed that he will report every couple days, we had pair sessions from time to time, reviewed his code together and etc.

Anyway, it looks like he spent less time writing code than I expected and before I would say that he didn't performed well enough to join our team, I was thinking may be that is my fault, may be I was pushing too much stuff, that is important in real life projects (like unit testing, structuring code, database stuff, etc.) and not enough fun stuff, that would hook up him on programming and that is the reason he spent less time than I hoped.

So I have ~20 days left and I can use them to inspire him with programming, question is with what and how?


答:
Separate the two parts of your problem.

1) To inspire.

2) To teach.

He's a post graduate with coding experience, so it may be too late to inspire him, or make him "see" the majesty of code. It isn't your responsibility to inspire him, but I understand why you would want to.

Teaching on the other hand, from your description it sounds like you've dumped a lot of stuff on him and expected him to sort it out. As you have a limited amount of time, set smaller projects, dish them out one at a time and get daily feedback. Make sure you follow up on him during the day and make it clear that if they have a problem, to ask rather than spend all day struggling and achieving nothing.


问:
Is there a programming language where 1/6 behaves the same as 1.0/6.0?
While I was programming in C++ some days ago, I made this mistake (that I have history of making it!). In one part of my code, I had 1/6 and I was expecting it be 0.16666666666 which is not the case. As you all know the result is 0 - C, C++, Java, Python, all behave the same.

I post it on my Facebook page and now there is debate on if there is a programming language where 1/6 behaves the same as 1.0/6.0.

答: Actually this behavior was changed in Python 3 and it now does behave like you expect (// is now used for integer division).


答:
There are many languages where ((1/6)*6) results in 1, not in 0. For example, PL/SQL, many BASIC dialects, Lua.

Accidentally, in all those langauges 1/6 results in .166666667, or 0.16666666666667 or something similar. I chose the ((1/6)*6)==1 variant to get rid of those little differences.

Title: Is there a programming language where 1/6 behaves the same as 1.0/6.0?

Body:
While I was programming in C++ some days ago, I made this mistake (that I have history of making it!). In one part of my code, I had 1/6 and I was expecting it be 0.16666666666 which is not the case. As you all know the result is 0 - C, C++, Java, Python, all behave the same.

I post it on my Facebook page and now there is debate on if there is a programming language where 1/6 behaves the same as 1.0/6.0.


问:
Is there much thought towards internal diagnosis testing within an enterprise application?
Imagine a discussion between four people - one a developer, one a manager, one a tester and one a deployment/operations type.

The Manager is very angry as a system has fallen over after a new version of code was deployed into production. He is looking to point fingers.

Operations person pleads ignorance - they followed the deployment steps exactly.

Tester pleads ignorance - they have functionally tested code and it worked fine in test environment.

Development person pleads ignorance - they provided good code, and claim that the system badly configured.

This situation may seem familiar to some. There's always an excuse, some mistake made along the chain - from design to deployment - that allows a system to be upgraded but doesn't work as intended.

What are the pros and cons of diagnosis testing - tests run built into the application (perhaps through a command line API or something) that would allow a system to check it's internal connections (database, middleware, filesystem etc) and confirm that everything it expects to work is correct?

This is rather than relying on an external monitoring system that may not be configured in the same fashion as the application? (new release, different properties, looking at the wrong database etc)

An example :

I'm writing a class that interacts with a database. Within this class, I create a method that interacts with the database without affecting it, say a simple select query.

In the constructor of this class, I pass to an observer a test based on the arguments passed into the constructor. This observer can be called to run all the tests it has at any time so as to test for the validity of the connection - even while the system is actually running.

答:
IMHO internal diagnosis can be a good thing - when it is done correctly and in a way that shows potential errors, which would otherwise stay undetected. But I think your example shows a case where this should normally not apply. Testing for validity of a database connection should by no means need additional programming effort by an application developer: that is a test the underlying database framework should do by itself every time a query is executed against the database - in case the connection is broken, this should result in throwing an exception or an automatic reconnect (proper error handling in any application assumed, which is a different thing).

However, a good diagnosis test is to check the database (schema) version or patch level, in case there are dependencies between the application version and the database version. That check could be run whenever a db connection is established. Such a test requires that you have something like a version number stored in your database, which is properly updated whenever you update your db schema.

When you are trying to build a fail safe system, internal diagnosis may be one thing, but IMHO more important is redundancy: your example

the Manager is very angry as a system has fallen over after a new version of code was deployed

shows a situation where someone did not expect failures when upgrading a system. This is a totally wrong approach - everyone must (!) expect failure in such a situation, and should have proper preventive measures taken beforehand, like a proper backup of all data and applications of the previous version or a simulation of the restore process to make sure it works and is fast enough. This includes mostly organizational measures like not sending all your admins into holidays right after such an upgrade, and running enough tests afterwards to make sure the system works as intended.

Any kind of diagnosis (internal or external) cannot prevent you from failure, but it may help to detect failure earlier.


答:
Yes, Perl does. The one-liner

```<code>perl -e '$x=1/6;print "$x\n";'
</code>```

results in the output of:

```<code>0.166666666666667
</code>```

I believe that PHP works the same way.

Edited to add: I also believe that a necessary (but not sufficient) condition for 1/6 == 1.0/6.0 is for the language in question to be weakly typed.

Body:
Yes, Perl does. The one-liner

perl -e '$x=1/6;print "$x\n";'

results in the output of:

0.166666666666667

I believe that PHP works the same way.

Edited to add: I also believe that a necessary (but not sufficient) condition for 1/6 == 1.0/6.0 is for the language in question to be weakly typed.


答:
I think the best way to inspire him is to give him some real tasks, it doesn't mean that you should involve him in the development of the product, but usually there are always processes that need improvement inside the development process, giving him some tasks developing some utilities that will later be used by the team(s) could be a great way to make him gain interest and at the same time know how the internal processes work.

Cheers


答:
How about working in mini day-long sprints.

Start the day (9am) by getting him/her to state what he/she intends to do over the day (and manage his expectations) and then talk over what he/she's completed (5pm) - including how problems were dealt with. Slowly, over time, extend the sprints once you are happier with the behaviour.

Other than that, let him/her get on with it. If they don't feel the motivation to get the work done, then that's why you take an intern on - both for them to get experience, but for you to learn how they work too. C'est la vie.


答:
Personally, I would hate to see code where I have to bring up the character map to type it again. Even though the unicode closely matches what's in the algorithm, it's really hurting readbility and ability to edit. Some editors might not even have a font that supports that character.

What about an alternative and just have up top //µ = u and write everything in ascii?

Title: Is it bad to use Unicode characters in variable names?

Body:
I recently tried to implement a ranking algorithm, AllegSkill, to Python 3.

Here's what the maths looks like:

No, really.

This is then what I wrote:

```<code>t = (µw-µl)/c  # those are used in
e = ε/c        # multiple places.
σw_new = (σw**2 * (1 - (σw**2)/(c**2)*Wwin(t, e)) + γ**2)**.5
</code>```

I actually thought it is unfortunate of Python 3 to not accept √ or ² as variable names.

```<code>>>> √ = lambda x: x**.5
  File "<stdin>", line 1
    √ = lambda x: x**.5
      ^
SyntaxError: invalid character in identifier
</code>```

Am I out of my mind? Should I have resorted for a ASCII only version? Why? Wouldn't an ASCII only version of the above be harder to validate for equivalence with the formulas?

Mind you, I understand some Unicode glyphs look very much like each other and some like     ▄ (or is that ▗▖ ) or ╦  just can't make any sense in written code. However, this is hardly the case for Maths or arrow glyphs.

Per request, the ASCII only version would be something along the lines of:

```<code>winner_sigma_new = ( winner_sigma ** 2 *
                    ( 1 -
                     ( winner_sigma ** 2 -
                       general_uncertainty ** 2
                     ) * Wwin(t,e)
                    ) + dynamics ** 2
                   )**.5
</code>```

...per each step of the algorithm.


问:
What are the practical ways to implement the SRP?
Simply what are the practical techniques people use to check if a class violates the single responsibility principle?

I know that a class should have only one reason to change, but that sentence is somewhat lacking a practical way to really implement that.

The only way I found is to use the sentence "The ......... should ......... itself." where the first space is the class name and the later is the method (responsibility) name.

However, sometimes it's hard to figure out if a responsibility really violates the SRP.

Are there more ways to check for the SRP?

Note:

The question is not about what the SRP means, but rather a practical methodology or a series of steps to check and implement the SRP.

UPDATE

I have added a sample class that clearly violates the SRP. It would be great if people could use it as an example to explain how they approach the single responsibility principle.

The example is from here.

答:
The way I check for the SRP is to check every method (responsibility) of a class and ask the following question:

"Will I ever need to change the way I implement this function?"

If I find a function that I'll need to implement in different ways (depending on some kind of configuration or condition) then I know for sure that I need an extra class to handle this responsibility.


问:
What Discrete Mathematics topics should the average computer science student know?
I know that Discrete Mathematics is a pretty broad topic that's used in a number of fields but I was just wondering what are some of the topics from it that you would expect an average computer science student to know?

Here are the range of topics from the table of contents of a book titled "Discrete Mathematics and it's Applications 6th edition" by Kenneth H Rosen:

```<code>1 The Foundations: Logic and Proofs
    1.1 Propositional Logic
    1.2 Propositional Equivalences
    1.3 Predicates and Quantifiers
    1.4 Nested Quantifiers
    1.5 Rules of Inference
    1.6 Introduction to Proofs
    1.7 Proof Methods and Strategy
2 Basic Structures: Sets, Functions, Sequences and Sums
    2.1 Sets
    2.2 Set Operations
    2.3 Functions
    2.4 Sequences and Summations
3 The Fundamentals: Algorithms, the Integers, and Matrices
    3.1 Algorithms
    3.2 The Growth of Functions
    3.3 Complexity of Algorithms
    3.4 The Integers and Division
    3.5 Primes and Greatest Common Divisors
    3.6 Integers and Algorithms
    3.7 Applications of Number Theory
    3.8 Matrices
4 Induction and Recursion
    4.1 Mathematical Induction
    4.2 Strong Induction and Well-Ordering
    4.3 Recursive Definitions and Structural Induction
    4.4 Recursive Algorithms
    4.5 Program Correctness
5 Counting
    5.1 The Basics of Counting
    5.2 The Pigeonhole Principle
    5.3 Permutations and Combinations
    5.4 Binomial Coefficients
    5.5 Generalized Permutations and Combinations
    5.6 Generating Permutations and Combinations
6 Discrete Probability
    6.1 An Introduction to Discrete Probability
    6.2 Probability Theory
    6.3 Bayes Theorem
    6.4 Expected Value and Variance
7 Advanced Counting Techniques
    7.1 Recurrence Relations
    7.2 Solving Linear Recurrence Relations
    7.3 Divide-and-Conquer Algorithms and Recurrence Relations
    7.4 Generating Functions
    7.5 Inclusion-Exclusion
    7.6 Applications of Inclusion-Exclusion
8 Relations
    8.1 Relations and Their Properties
    8.2 n-ary Relations and Their Applications
    8.3 Representing Relations
    8.4 Closures of Relations
    8.5 Equivalence Relations
    8.6 Partial Orderings
9 Graphs
    9.1 Graphs and Graph Models
    9.2 Graph Terminology and Special Types of Graphs
    9.3 Representing Graphs and Graph Isomorphism
    9.4 Connectivity
    9.5 Euler and Hamilton Paths
    9.6 Shortest-Path Problems
    9.7 Planar Graphs
    9.8 Graph Coloring
10 Trees
    10.1 Introduction to Trees
    10.2 Applications of Trees
    10.3 Tree Traversal
    10.4 Spanning Trees
    10.5 Minimum Spanning Trees
11 Boolean Algebra
    11.1Boolean Functions
    11.2 Representing Boolean Functions
    11.3 Logic Gates
    11.4 Minimization of Circuits
12 Modeling Computation
    12.1 Languages and Grammars
    12.2 Finite-State Machines with Output
    12.3 Finite-State Machines with No Output
    12.4 Language Recognition
    12.5 Turing Machines
Appendixes
    A.1 Axioms for the Real Numbers and the Positive Integers
    A.2 Exponential and Logarithmic Functions
    A.3 Pseudocode
</code>```

答:
Concrete Mathematics: A foundation for Computer Science, by Knuth e.a. was written exactly for this purpose.

It provides mathematical knowledge and skills for computer science, especially for the analysis of algorithms. According to the preface, the topics in Concrete Mathematics are "a blend of CONtinuous and disCRETE mathematics."

Wikipedia, 27 July 2012