答:
This is really the point of make. Only rebuild what you need to rebuild, nothing more. As such, your makefile should be set up so that the built components do not get in your way while you work, such as dumping them into a build directory. It should also have proper dependencies set up, so that any relevent sections of the project will recompile if you change their dependencies.

I suggest going through the makefile you have for your project, and learning what all the different pieces do. It's another important and useful tool. The manual isn't very long, and goes over everything. Or, you can read Managing Projects with Gnu Make, which goes over how make is more than just a software compiler.

Title: Is a new build required everytime I make a change to the code?

Body:
I am working on a project that has around a hundred different files (.cpp & .h), and it requires around an hour to build the entire project on MSVC 2008, suppose that I now make a change to any one file, do I need to build the entire project once again, right from the beginning, or is there a way out ?

I know it is very very noob like, but I am wasting a lot of time, hence I was wondering


问:
When working with contractors/interns how protective should one be of your codebase?
We're considering hiring a contractor or intern to work with us on our iOS project but this causes me to get really paranoid that we're giving somebody who doesn't work for the company access to our precious codebase.  I mean, I could just give them access to the classes I'd like them to work on but that seems rude and it would make it more difficult for them to develop what we need them to.

How paranoid should one be about people running off with their entire application?

答: You should have a non compete and/or Non disclosure agreement in place when you bring them on.  This will allow you to bring in a contractor and should they choose to run off on their own and create the next Face book with out you, based on your work, you can take it all back.  But realistically that does not happen often.  If you go through a reputable company then you will probably get a professional who wants to help you succeed.  Do not hinder them by trying to compartmentalize them to the point that they want you to fail.</p>

ContentLicense: CC BY-SA 3.0


答:
The don't need access to code they don't need; it will only confuse them or waste their time.

There should be legal agreements that this is your code and they're not alowed to use it for other purposes or there will be consequences. This should all be very standard.

If you've hired quality professionals there is nothing rude about it and for them to protest too much would be suspicious.

Title: When working with contractors/interns how protective should one be of your codebase?

Body:
We're considering hiring a contractor or intern to work with us on our iOS project but this causes me to get really paranoid that we're giving somebody who doesn't work for the company access to our precious codebase.  I mean, I could just give them access to the classes I'd like them to work on but that seems rude and it would make it more difficult for them to develop what we need them to.

How paranoid should one be about people running off with their entire application?


问:
Is a new build required everytime I make a change to the code?
I am working on a project that has around a hundred different files (.cpp & .h), and it requires around an hour to build the entire project on MSVC 2008, suppose that I now make a change to any one file, do I need to build the entire project once again, right from the beginning, or is there a way out ?

I know it is very very noob like, but I am wasting a lot of time, hence I was wondering

答: A 'make clean' should only be neccessary once if you just started working on an already existing project, e.g. it was just downloaded and unpacked, or if you want to be sure that everything is up to date, e.g. for a release. If just a few files were modified, a simple 'make' should suffice. It is then up to the 'make' utility to find and compile just the modified files, and link the results together with the already compiled files to create the finished binary.</p>


问:
Handling (many) multiple projects in Git in an enterprise environment
One of the advantages of older version control systems such as CVS and SVN in enterprise development is that anyone can connect to source control and see all the projects that the company has. This can make it easier to get a high level view of what kid of development is happening outside your sprint and also keeps everything in one place and easy to find.

However, distributed version control systems (Git, specifically) use the repository as their base unit. They work best with one project (or several closely related projects) per repository. This makes repository management more difficult in most enterprise environments where it is not unusual to have more than 25-50 projects to support. As far as I have been able to determine, you have to keep a list somewhere else of all the repos you have. There is software available, like GitHub, that help, but that still is an extra step beyond a single connection string and listing the contents of the repository.

What is the best way to deal with the complexity of multiple repositories?

答:
You may create your a kind of your own Github or  Gitorious

Information how you can do it can be found at Stackoverflow: Is there a Github clone that I can run on my own server?


答:
I use gitolite as far as repository management.  This gives you the ability to manage each repository on an individual level down to the branch level very easily.

As far as being able to see all of the repositories at once I know there are solutions for that but I have never had the need for it.

Title: Handling (many) multiple projects in Git in an enterprise environment

Body:
One of the advantages of older version control systems such as CVS and SVN in enterprise development is that anyone can connect to source control and see all the projects that the company has. This can make it easier to get a high level view of what kid of development is happening outside your sprint and also keeps everything in one place and easy to find.

However, distributed version control systems (Git, specifically) use the repository as their base unit. They work best with one project (or several closely related projects) per repository. This makes repository management more difficult in most enterprise environments where it is not unusual to have more than 25-50 projects to support. As far as I have been able to determine, you have to keep a list somewhere else of all the repos you have. There is software available, like GitHub, that help, but that still is an extra step beyond a single connection string and listing the contents of the repository.

What is the best way to deal with the complexity of multiple repositories?


问:
Triggering custom events in AJAX callbacks
I'm pretty new to JavaScript, but one of the things that's been frustrating is that our AJAX callbacks have been getting packed with different functionality, making it difficult to keep everything separated and organized.

I'm really new to programming, I have a feeling learning MVC a bit more would help me, but for now using custom events seems like it could help me keep my code a lot cleaner and prevent some problems. Here's what I'm talking about:

```<code>function myAjaxFunctionThatGetsTestData(){
    $.post('ajax/test.html', function(data) {
        $(document).trigger('testDataLoaded',data);
    });
}

function myOtherFunctionThatsDependentUponAjax(){
    getSomeTestData(); //start process of retrieving the data from ajax
    //then let me know when data has been retrieved
    $(document).one('testDataLoaded', function(data){
        alert (data);
    }
}

function getSomeTestData(){
    //maybe data was already retrieved by a different module, so check first
    if (data){
        $(document).trigger('testDataLoaded',data);
    }
    else{
        myAjaxFunctionThatGetsTestData();
    }
}
</code>```

I also don't know if it's ok that I'm triggering document or not...

Are there any patterns that look like this that I can read more about? What are the potential problems with this?

答:
If I didn't misunderstood your question, you are doing something like this (with jQuery):

```<code>// Bind to some arbitrary event name
$("body").bind("arbitrary", function(evt){
  alert("o/");
});

// Create a random event
var e = jQuery.Event("arbitrary");

// Fire the event
$("body").trigger(e);
</code>```

...and asking if it is ok. It is a common technique, used in rails, for example. Also, jQuery offers these events a nice set of properties to play with. I don't see any problem with binding to 'document'.

Body:
If I didn't misunderstood your question, you are doing something like this (with jQuery):

// Bind to some arbitrary event name
$("body").bind("arbitrary", function(evt){
  alert("o/");
});

// Create a random event
var e = jQuery.Event("arbitrary");

// Fire the event
$("body").trigger(e);

...and asking if it is ok. It is a common technique, used in rails, for example. Also, jQuery offers these events a nice set of properties to play with. I don't see any problem with binding to 'document'.


问:
Many small scripts, one repository or multiple?
A co-worker and myself have run into an issue that we have multiple opinions on.

Currently we have a git repository that we are keeping all of our cronjobs in. There are about 20 crons and they are not really related except for the fact that they are all small python scripts and essential for some activity.  We are using a fabric.py file to deploy and a requirements.txt file to manage requirements for all of the scripts.

Our issue is basically, do we keep all of these scripts in one git repository or should we be separating them out into their own repositories?  By keeping them in one repository it is easier to deploy them onto one server.  We can use just one cron file for all the scripts.

However this feels wrong, as the 20 cronjobs are not logically related.  Additionally, when using one requirements.txt file for all the scripts, it's hard to figure out what the dependencies are for a particular script and they all have to use the same versions of packages.

We could separate all of the scripts out into their own repositories but this creates 20 different repositories that need to be remembered and dealt with.  Most of these scripts are not very large and that solution seems to be overkill.

A related question is, do we use one big crontab file for all cronjobs, or a separate file for each?  If each has their own, how does one crontab's installation avoid overwriting the other 19?  This also seems like a pain as there would then by 20 different cron files to keep track of.

In short, our main question and issue is do we keep them all closely bundled as one repository or do we separate them out into their own repository with their own requirements.txt and fabfile.py? We feel like we're also probably looking over some really simple solution. Is there an easier way to deal with this issue?

答:
Unless there is a really good reason for the split (performance; overwhelming organizational/security concerns etc..) my instinct is to keep source documents together in the same repository.

Splitting systems out into separate repositories generally creates barriers that inhibit reuse; since reuse is just about the only way that an organization has to amortize the cost of development, anything that gets in the way of reuse is ipso facto a bad thing.


问:
A programmer should concentrate on at least how many languages?
For me I am C# and Java person. I find these 2 languages are quite similar so its easier for me to crossover each other. I'm not sure if its good idea to pick up other different languages. Any thoughts?</p>

答: You should concentrate on the languages you need and use for what you're doing.  Really learning a language comes from practice, so you get the benefit of that language when you're practicing it.  If you are going to learn a new language in your spare time, then do it by implementing it in tasks of increasing complexity, so that you really get a handle on it.

ContentLicense: CC BY-SA 2.5


问:
What is the role of traditional issue tracker when Scrum / Kanban board is used?
From a very high level view, to me it seems there are generally 2 types of Project Management tools:

Traditional issue trackers like Fogbugz, JIRA, BugZilla, Trac, Redmine etc.

Virtual card boards / agile project management tools like Pivotal Tracker, GreenHopper, AgileZen, Trello etc.

Sure, they overlap in one way or another, e.g. Pivotal Tracker tasks can be imported to JIRA, GreenHopper itself is implemented on top of JIRA issue base etc. but I think one can still see the difference in orientation between those two types of tools.

Traditional issue tracker seems to be used even in companies otherwise doing agile project management. My question is, why do they do that? I also feel that we should use an issue tracker in my company but when I'm thinking about it, I'm not actually sure why should we need it.

For example, Trello development seems to be managed by using Trello itself (see this virtual wall) even though they have access to Fogbugz, one of the best issue trackers around. So maybe we don't need traditional issue tracker when we'll be doing 100% of our work in an agile manner using one of the agile PM tools?

答:
We run an issue tracker called DoneDone which fits #3 in Joel's answer - the more traditional role of a bug tracker. Indeed, we built it because our consultancy historically delivers lots of code (in the form of websites) at non-regular intervals.

We did a little outreach to our DoneDone user base a month ago though and quite a few of them have requested a front-end akin to Trello and Sprint.ly for their more continuous code/release cycles. Another useful piece of insight was that many of these folks are using DoneDone before their QA ever begins so they'd like all that data in one place as their projects (or features) move between cycles.

My two cents is it's all data with a bit of workflow applied. The distinction is really the UI and how it accommodates the team and whichever methodology and/or project phase they're in at the time.


问:
Are there Negative Impact of opensource on commercial environment?
My company has a very broad range of products and there are a few that are not strategic to us so I wanted to open source them (so we can focus on what makes us unique and open source the products that every firm has).

Our industry(hedgefund) does not open source(we would be the first firm to try this) and the feedback I'm getting from my management team is either 1) we'll destroy the industry or 2) all competitive commercial firms will unite against us and we'll be wiped out either way.  It's a big battle in my firm right now between the IT people who have seen the positive effects of sharing and the business people who think we'll be giving up everything (they prefer we sell parts we want to opensource, but in their defense this is standard when divesting something).

So what are your thoughts? Does open sourcing apply generally or is it only really applicable to software? Is it overall good for people in the industry and outside? I'm actually more interested in the negativeness effects(although positive are welcomed as well)

Update: Long story short, although code is involved this is not so much about code as it is more about the idea of open sourcing.

We are a mid sized quant hedge fund.  We have some unique strategies but also have the standard long/short, arbitrage, global macro, etc.. funds.

We are keeping the unique funds we have but the other stuff that everyone else has we are considering open sourcing (We have put in years of work & millions of dollars into. Our funds is pretty popular and our performance is either in first or second quartile so I suspect there will be interest from firms in or thinking of getting into the industry but I don't know to what extent).

The goal is not to get a community to work for us, the goal is to let anyone who wants to tinker with it do so and create anything they want (it will not be part of our product line although I may unofficially allocate some our of staff's time to assist any community that grows).  Although the code base is quite large, the value in this is the industry knowledge and approaches we have acquired (there are many books on artificial intelligence and quant trading but they are often years behind what's really going on as most firms forbid their staff from discussing what they are doing). Long story short, there maybe value here for people or not but I'm approaching open sourcing as a way to benefit the general public while we divest a product line up. But the flip side, is this is a core product to many other firms and they won't be happy(I think about linux/windows, wikipedia/britannica, google maps/commercial map firms, and so on).  I'm fine with people disliking me but I'd rather it not be for unindented consequences and this question is to try to understand what those consequences generally are on industries that get core areas open sourced. For example, its hard to judge what part of the OS market grew because of Linux or was naturally growing on its own and so on. Technology has such fast grow and I'm struggling to understand how open sourced impacted it(and if it was positive or not. I.e. one of our large competitors has very large grants to top universities which obviously helps the schools, would open source limit the need for things like that?).

I understand this can seem very specific to me but I'm trying to understand general impact of open sourcing and software seemed like a good place to learn.

答:
Let me add my 2 cents on what @FrustratedWithFormsDesign said.

To get your company to do anything you have to do something to quantify the impact/benefit. No amount of talk or feeling or emotional outbursts (or frustration) will help in any way.

Use the 5-Why's technique to nail down the 'end-benefit' of actually open-sourcing the project. (You may need to ask more than 5 :) Now, you may land up with more than 1 end-goal, of course - since you can branch off on any answer and keep asking 'Why' (i.e. you may get a graph of causally linked goals and not just a linear tree).

See if you can quantify the goals as value gained to organization - if you think it's hard to measure I suggest reading "How to Measure Anything - Doug Hubbard" Now this should be used as your 'weapon of choice' for taking it to the higher management showing them the 'value' of open-sourcing. Unless the numbers are believable (along with risks factored in!) they won't even bother looking at it.

If they find something worthy of interest, they will spend some time to look into it further. Unless it aligns with their strategic interests and is value adding they WON'T look at it (or rather won't bother looking at it).

Hope this helps.

PS: You may also want to look up Business Model Canvas as an alternate means of communicating the same.


答:
i'm gonna try answer your question. I think whats happening here is your AJAX methods are setup to get data asynchronously therefore when you try and use the data variable its not set because the AJAX call is still being executed in the background. What you need to do is setup your ajax call not to be asynchronous but synchronous therefore your code will wait till AJAX call has been completed before it moves on.

use Firebug plugin for FireFox to debug your Javascript code it will help you understand how AJAX works and a lot more other things related to using jQuery library.

update this method:

```<code>function myAjaxFunctionThatGetsTestData(){
   $.post('ajax/test.html', function(data) {
    $(document).trigger('testDataLoaded',data);
   });
}
</code>```

To:

```<code>function myAjaxFunctionThatGetsTestData(){
   $.ajax({
    type: "POST",
    dataType: "html",
    url: "ajax/test.html",
    data: "",
    async: false, //by default all AJAX calls are set to true
    contentType:  "text/html",
    success: function(data){
     //successful call to server side and back
     //add data to you _data global variable
     //or do your data check here
     _data = data;
    },
    error: function(jqXHR, textStatus, errorThrown){
     //display error message, ajax call failed
     alert(textStatus);
    }
   });
}
</code>```

Title: Triggering custom events in AJAX callbacks

Body:
I'm pretty new to JavaScript, but one of the things that's been frustrating is that our AJAX callbacks have been getting packed with different functionality, making it difficult to keep everything separated and organized.

I'm really new to programming, I have a feeling learning MVC a bit more would help me, but for now using custom events seems like it could help me keep my code a lot cleaner and prevent some problems. Here's what I'm talking about:

```<code>function myAjaxFunctionThatGetsTestData(){
    $.post('ajax/test.html', function(data) {
        $(document).trigger('testDataLoaded',data);
    });
}

function myOtherFunctionThatsDependentUponAjax(){
    getSomeTestData(); //start process of retrieving the data from ajax
    //then let me know when data has been retrieved
    $(document).one('testDataLoaded', function(data){
        alert (data);
    }
}

function getSomeTestData(){
    //maybe data was already retrieved by a different module, so check first
    if (data){
        $(document).trigger('testDataLoaded',data);
    }
    else{
        myAjaxFunctionThatGetsTestData();
    }
}
</code>```

I also don't know if it's ok that I'm triggering document or not...

Are there any patterns that look like this that I can read more about? What are the potential problems with this?

Body:
i'm gonna try answer your question. I think whats happening here is your AJAX methods are setup to get data asynchronously therefore when you try and use the data variable its not set because the AJAX call is still being executed in the background. What you need to do is setup your ajax call not to be asynchronous but synchronous therefore your code will wait till AJAX call has been completed before it moves on.

use Firebug plugin for FireFox to debug your Javascript code it will help you understand how AJAX works and a lot more other things related to using jQuery library.

update this method:

function myAjaxFunctionThatGetsTestData(){
   $.post('ajax/test.html', function(data) {
    $(document).trigger('testDataLoaded',data);
   });
}

To:

function myAjaxFunctionThatGetsTestData(){
   $.ajax({
    type: "POST",
    dataType: "html",
    url: "ajax/test.html",
    data: "",
    async: false, //by default all AJAX calls are set to true
    contentType:  "text/html",
    success: function(data){
     //successful call to server side and back
     //add data to you _data global variable
     //or do your data check here
     _data = data;
    },
    error: function(jqXHR, textStatus, errorThrown){
     //display error message, ajax call failed
     alert(textStatus);
    }
   });
}


答:
I've worked as a contractor in a number of companies on a number of different codebases over the years and in nearly all cases there's been a pretty standard catch-all clause in the contract I sign that says anything I see or do there is confidential.

The wording varies but the intent is the same - to protect the company in the case of me running off to a competitor with their trade secrets. That's understood and accepted (by me anyway, I can't speak for anyone else) and it means that the company in turn can just let me dive in and do my job without having to be hindered by constantly asking for permission to see another piece of source.

In one place I worked the crown jewels of the company were bound up in some highly specialized IP that had restricted access even within the regular employees. That code was wrapped up in a library so it could just be called without ever knowing how it did what it did which is another option for you if you need to protect some core code against prying eyes. Even that is probably not completely foolproof, but then again you do need to have a certain level of trust in the people working for you otherwise nothing will ever get done!


答:
You use NDA & non-compete agreements, but basically you trust them.

Self-reflection is also important.  It would be much better to hire an employee right? You probably don't because of the cost, especially to keep and retain a good one.

If you have the next killer-app that would be fine, however if you're not there 'yet' and you're still out-sourcing, this is part of the risk and the cost.

If you have an idea that people will throw money at even to get 1% of the equity, then you have a killer idea and you'll have the $$ to match.

There's a certain amount of pretty killer Darwinism going on in this space right now.  It's not always logical but it's  actually a lot more saner that the dot-com time that I also lived through professionally.


答:
There are two kinds of builds: clean builds and incremental.

A clean build always starts from scratch: it takes nothing but the bare project as input, figures out dependencies, and builds all the parts in order, then assembles them into the final output. A clean build, by definition, has to recompile all the source files in your project; while doing this, it produces intermediate files, such as .obj files, which are neither source nor shippable binaries - once the build is complete, you could throw them away (which is what Build>Clean Solution is supposed to do), or you can leave them in place for later, which brings us to...

Incremental builds. An incremental build compares every source file's last-modified date to the timestamp on the intermediate files it produces, as well as anything else that depends on it ('targets'); if any dependency has been modified after the target was last built, the target is rebuilt, otherwise the file from the previous build is reused. For example, if you have users.c, which gets compiled into users.obj (a build target) and includes users.h and basics.h (dependencies), then the incremental build would check the timestamps on all these files, and if any of them is newer than the one on users.obj, then users.obj gets rebuilt; otherwise, the existing users.obj is considered valid, and this particular build step can be skipped.

Because incremental builds only rebuild what needs to be, they are typically much faster than clean builds - for large but well-structured projects, the difference can be one of mere seconds vs. lunch break.

However, correctly determining dependencies borders on black magic, and some overall settings invalidate all intermediates (e.g. if you switch target architecture), so if you want "the real thing", most people will recommend doing a complete clean build. In fact, pretty much all Continuous Integration setups (where a build server executes a complete build each time new code gets pushed to the master repository, fully automated) use clean builds, simply because they are the only reliable way of making sure everything is really really up-to-date.


问:
Dynamic Post-build event in Visual Studio
I am building a video server application that has multiple projects in Visual Studio. One project, the video server project, needs to call a shell script to generate documentation. This works fine when you build the video server project, because the script is simply

```<code>cd "$(SolutionDir)"
start documentationgenerator
</code>```

However, there is also an SDK project that, when built, also builds the video server project. However, when it does this, it does not know where the shell script is, since it tries to use the SDK Project's Solution Directory.

SDK Project

Video Server Project

shell script

So the question is: how do I make the SDK Project find the Video Server Project? I checked the MSBuild properties and there are no properties that seem to deal with 'nested' projects.

答:
(Edited in response to comments)

The trick to getting a consistent build when reusing projects across solutions is to try and identify a known, common root and work relative to there. In your place the common root would seem to be the video server project.

Instead of using $(SolutionDir) in your video project (post build event?), try and do something with the video servers $(ProjectDir) - that will always be set no matter what solution it lives in. From your example something like this should resolve to the same place as $(SolutionDir) - you'll probably have to play with quotes and leading\trailing backslashes - I can't remember what the VS macros do with those now.

```<code>cd "$(ProjectDir)..\"
start DocumentationBuilder
</code>```

Body:
(Edited in response to comments)

The trick to getting a consistent build when reusing projects across solutions is to try and identify a known, common root and work relative to there. In your place the common root would seem to be the video server project.

Instead of using $(SolutionDir) in your video project (post build event?), try and do something with the video servers $(ProjectDir) - that will always be set no matter what solution it lives in. From your example something like this should resolve to the same place as $(SolutionDir) - you'll probably have to play with quotes and leading\trailing backslashes - I can't remember what the VS macros do with those now.

cd "$(ProjectDir)..\"
start DocumentationBuilder


答:
There's a good possiblity that your firm could significantly change financial market making by releasing the source code.  Having mulled through the idea, I have to agree that the pros outweigh the cons.

For what it's worth, I'm fairly familar with market structure. I interviewed with an exchange to join their IT staff.  It wasn't a good fit and I didn't join them.  But I think I understand the ramifications of what you're proposing.

Educational tool

There is a dearth of available programming talent in financial services.  In my opinion, one of the biggest barriers to entry is (lack of) subject matter knowledge.  There are few, if any, reference frameworks, and as you note, academia can't teach about information that isn't accessible.

I think there are a number of professors who could utilize the information and concepts instantiated by the source code.  Theory is one thing; but having a concrete example is quite another.

Your firm's past results will be poured over by academics and competitors alike to determine what impact the flaws in the model(s) could have had on your returns.  Disclaimer: all models have flaws, so that's not a critique by any means.

Driver for growth

There are a number of solid, successful open-source projects that have driven dramatic growth in the industry.  Eclipse, Linux, and Apache are just three examples.

You described the projects you're releasing as being low-end, borderline commodity.  Releasing them will absolutely push those areas into commodity land.  That's not necessarily bad, as it enables many more people to participate. It also allows for untold innovation.  It's impossible to predict what can happen when outside viewpoints are allowed to pick up the pieces and put them back together again.

Technology disrupter

On the negative side, this can be a serious technology disrupter like Linux, cell phones, digital media, etc.  Whenever you open up a previously locked-down environment with a high barrier to entry, there is no telling what can or will occur.  Some folks will end up losing jobs as the industry adapts to the game changers that could come out of this.  Some would turn around and argue that this will introduce greater efficiencies and the ends justify the means.

Without being too dramatic, this is kind of like dropping a grenade in some of your competitors' laps.  Effectively, you are forcing them to adapt to using more sophisticated models and to exit the soon-to-be completely commmodity environments they were working within.

Market Transparency

Given some of the recent SEC comments and public (mis)information about trading activity and dark pools, this may provide your company more attention than it was expecting.  Some of it will be good.  Some of it will be bad.  Either way, it is something to consider.

Reference framework / Community

I would encourage you to allocate some staff time in order to document the projects and be available for follow-up questions.  Dumping a large blob of otherwise opaque code into the ether will simply be an exercise in bit shuttling.  If you provide a roadmap so people can understand the code base, then they'll have a means to dig in and start working with it.

Adoption rates and end-impact are difficult, if not impossible, to predict due to the number of variables involved.  In almost all cases, though, the game changers started out small and grew incrementally.  All the variants of Linux grew out of alpha geeks swapping stacks of 3.5" floppies or the occasionally revered burnt CD.  Accessibility is a key aspect, and it's crucial to have folk available who understand the codebase.

To take things a step further, you could reach out to counterparts in other firms to see if they are considering a similar thing.  Putting together a consortium, a.k.a. what is now the Apache Foundation, is one way of gaining critical mass.  Another approach would be to generate tutorials, a la CodeAcademy, and run a minor public relations campaign in order to advertise it.  These methods would help push the likely outcome into positive territory, but going into details would go beyond the scope of the original question.

To summarize the negatives:

- This can really disrupt the patterns that many have fallen into.

- Doing so will anger some of your competitors, who will malign you.

- You'll also pick up some negative press based upon misunderstandings of how the code and / or the market worked.

I would encourage you to use a GPLv3 license for this release precisely because of the viral nature of the license.  Future modifications that are distributed must have their source released, which will in turn help grow any sort of community that may come from this.

To reframe this with your peers:

- This will make you look good in the eyes of the SEC (U.S. Securities and Exchange Commission) since you are trying to foster a level playing field.

- This code is a sunk cost that is no longer profitable for you. The long term benefits of improving available programming talent in the market are incalculable.

- This will encourage greater market efficiency, which is what we're all supposed to aspire to, since it gets us closer to correct valuation for equities.

Title: Are there Negative Impact of opensource on commercial environment?

Body:
My company has a very broad range of products and there are a few that are not strategic to us so I wanted to open source them (so we can focus on what makes us unique and open source the products that every firm has).

Our industry(hedgefund) does not open source(we would be the first firm to try this) and the feedback I'm getting from my management team is either 1) we'll destroy the industry or 2) all competitive commercial firms will unite against us and we'll be wiped out either way.  It's a big battle in my firm right now between the IT people who have seen the positive effects of sharing and the business people who think we'll be giving up everything (they prefer we sell parts we want to opensource, but in their defense this is standard when divesting something).

So what are your thoughts? Does open sourcing apply generally or is it only really applicable to software? Is it overall good for people in the industry and outside? I'm actually more interested in the negativeness effects(although positive are welcomed as well)

Update: Long story short, although code is involved this is not so much about code as it is more about the idea of open sourcing.

We are a mid sized quant hedge fund.  We have some unique strategies but also have the standard long/short, arbitrage, global macro, etc.. funds.

We are keeping the unique funds we have but the other stuff that everyone else has we are considering open sourcing (We have put in years of work & millions of dollars into. Our funds is pretty popular and our performance is either in first or second quartile so I suspect there will be interest from firms in or thinking of getting into the industry but I don't know to what extent).

The goal is not to get a community to work for us, the goal is to let anyone who wants to tinker with it do so and create anything they want (it will not be part of our product line although I may unofficially allocate some our of staff's time to assist any community that grows).  Although the code base is quite large, the value in this is the industry knowledge and approaches we have acquired (there are many books on artificial intelligence and quant trading but they are often years behind what's really going on as most firms forbid their staff from discussing what they are doing). Long story short, there maybe value here for people or not but I'm approaching open sourcing as a way to benefit the general public while we divest a product line up. But the flip side, is this is a core product to many other firms and they won't be happy(I think about linux/windows, wikipedia/britannica, google maps/commercial map firms, and so on).  I'm fine with people disliking me but I'd rather it not be for unindented consequences and this question is to try to understand what those consequences generally are on industries that get core areas open sourced. For example, its hard to judge what part of the OS market grew because of Linux or was naturally growing on its own and so on. Technology has such fast grow and I'm struggling to understand how open sourced impacted it(and if it was positive or not. I.e. one of our large competitors has very large grants to top universities which obviously helps the schools, would open source limit the need for things like that?).

I understand this can seem very specific to me but I'm trying to understand general impact of open sourcing and software seemed like a good place to learn.


问:
Developing an internet-enabled application as a Kiosk on Windows 7
I am finalizing development of a desktop Java application that communicates with an outside web server, and now I need to start seriously considering deployment.

This application will run on a large touchscreen all-in-one workstation running Windows 7.

It will be located in a public-area and thus must be LOCKED-DOWN Hanibal Lecter style.  Early in the project nobody really concerned themselves with this fact just assuming that we can buy some magical software for Windows 7 that will automatically take care of all this, however I am finding now that this looks to be a LOT more complicated than my manager ever thought.

I need to:
 - Lock down the standard hot-keys (ALT+TAB, ALT+CTRL+DEL, etc...)

Prevent the user from opening ANY programs other than the kiosk application and its spawned executables

Prevent the user from closing the application

Start the kiosk application on startup (this can be done without kiosk software)

Auto-login to Windows on reboot (Windows Updates, power failure, bratty kid pressing the power button, etc...)

Administrator passcode escape sequence for routine maintenance by desktop support professionals.

To my dismay I am having a really hard time finding software that contains the whole package and am finding numerous swaths of competing information on the best way to do this.  I am not necessarily looking for free or open source software and am willing to pay for software that can help me achieve this.

Have any of you ever wrote kiosk software before and if so what approaches have you taken to do this?

答: Public Web Browser by Team Software might be your solution.  I have used it in public libraries for years.  Try if free and then the license is really inexpensive.  Then build your kiosk around it.</p>


答:
I can think of at least five reasons to learn a language, and it seems like you should eventually learn one for each of these.

One language to get your first job - likely Java/C#/C++

One language to get things done - likely Bash/Perl/Python/Ruby

One language to bend your mind - likely Haskell/Clojure/Scala/F#

One language for domain specific reasons - likely JavaScript/Objective C

One language to get your hands dirty - likely C/Assembly

Title: A programmer should concentrate on at least how many languages?

Body: For me I am C# and Java person. I find these 2 languages are quite similar so its easier for me to crossover each other. I'm not sure if its good idea to pick up other different languages. Any thoughts?</p>


问:
Are too many assertions code smell?
I've really fallen in love with unit testing and TDD - I am test infected.

However, unit testing is normally used for public methods. Sometimes though I do have to test some assumptions-assertions in private methods too, because some of them are "dangerous" and refactoring can't help further. (I know, testing frameworks allow testing private methods).

So it became a habit of mine that the first and the last line of a private method are both assertions.

However, I've noticed that I tend to use assertions in public methods (as well as the private) just "to be sure". Could this be "testing duplication" since the public method assumptions are tested from the outside by the unit testing framework?

Could someone think of too many assertions as a code smell?

答:
Those assertions are really useful for testing your assumptions, but they also serve another really important purpose: documentation. Any reader of a public method can read the asserts to quickly determine the pre and post conditions, without having to look at the test suite. For this reason, I recommend you keep those asserts for documentation reasons, rather than testing reasons. Technically you are duplicating the assertions, but they serve two different purposes and are very useful in both.

Keeping them as asserts is better than simply using comments, because they actively check assumptions whenever they are run.

Title: Are too many assertions code smell?


答:
I think that using assertions in public methods is even more important, since there you do not control the inputs and may be more likely to have an assumption broken.

Testing input conditions should be done in all public and protected methods.
If the inputs are passed directly to a private method, then testing its inputs may be redundant.

Testing output conditions (e.g. object state or that return value != null) should be done in the inner methods (e.g. private methods). If the outputs are passed directly from a private method to the output of a public method without additional calculations or inner state changes, then testing the output conditions of the public method may be redundant.

I do agree with Oleksi, however, that the redundancy may increase readability and it also may increase maintainability (if direct assignment or returning is no longer the case in the future).

Title: Are too many assertions code smell?

Body:
I've really fallen in love with unit testing and TDD - I am test infected.

However, unit testing is normally used for public methods. Sometimes though I do have to test some assumptions-assertions in private methods too, because some of them are "dangerous" and refactoring can't help further. (I know, testing frameworks allow testing private methods).

So it became a habit of mine that the first and the last line of a private method are both assertions.

However, I've noticed that I tend to use assertions in public methods (as well as the private) just "to be sure". Could this be "testing duplication" since the public method assumptions are tested from the outside by the unit testing framework?

Could someone think of too many assertions as a code smell?


答:
Having duplicate asserts is not wrong per se, but having the asserts "just to make sure" isn't the best.  It really boils down to what exactly each test is trying to accomplish.  Only assert what is absolutely needed.  If a test uses Moq to verify a method is invoked, it doesn't really matter what happens after that method is invoked, the test is only concerned with making sure the method is invoked.

If every single unit test has the same set of asserts, except for one or two, then when you refactor a bit all of the tests could fail for the exact same reason, instead of showing you the true impact of the refactor.  You could end up in a situation where you run all the tests, they all fail because every test has the same asserts, you fix that failure, run the tests again, they fail for another reason, you fix that failure.  Repeat until done.

Also consider the maintenance of your test project.  What happens when you add a new parameter, or the output is tweaked every so slightly, would you have to go back through a bunch of tests and change an assert or add a assert?   And, depending on your code, you could end up having to setup a lot more just to make sure all the asserts pass.

I can understand the allure of wanting to include duplicate asserts in the unit test, but it really is overkill.  I went down the same path with my first test project.  I went away from it because the maintenance alone was driving me nuts.

Title: Are too many assertions code smell?


答:
It sounds like you are trying to do Design-by-Contract by hand.

Doing DbC is a good idea, but you should at least consider switching to a language which does support it natively (such as Eiffel) or at least use a contract framework for your platform (e.g. Microsoft Code Contracts for .NET is pretty nice, arguably the most sophisticated contract framework out there, even more powerful than Eiffel). That way, you can better leverage the power of contracts. E.g. using an existing framework, you can surface the contracts in your documentation or an IDE (e.g. Code Contracts for .NET are shown in IntelliSense and, if you have VS Ultimate, can even be checked statically by an automatic theorem prover at compile time while you type; likewise many Java contract frameworks have JavaDoc doclets that will automatically extract the contracts into your JavaDoc API documentation).

And even if it turns out that in your situation there is no alternative to doing it manually, you now at least know what it is called, and can read up about it.

So, in short: if you are indeed doing DbC, even if you don't know it, then those assertions are perfectly fine.

Title: Are too many assertions code smell?


问:
Is it correct to fix bugs without adding new features when releasing software for system testing?
This question is to experienced testers or test leads.
This is a scenario from a software project:

Say the dev team have completed the first iteration of 10 features and released it to system testing. The test team has created test cases for these 10 features and estimated 5 days for testing. The dev team of course cannot sit idle for 5 days and they start creating 10 new features for next iteration. During this time the test team found defects and raised some bugs. The bugs are prioritised and some of them have to be fixed before next iteration. The catch is that they would not accept the new release with any new features or changes to existing features until all those bugs fixed. The test team says that's how can we guarantee a stable release for testing if we also introduce new features along with the bug fix. They also cannot do regression tests of all their test cases each iteration. Apparently this is proper testing process according to ISQTB.

This means the dev team has to create a branch of code solely for bug fixing and another branch where they continue development. There is more merging overhead specially with refactoring and architectural changes.

Can you agree if this is a common testing principle. Is the test team's concern valid. Have you encountered this in practice in your project.

答: Where I work we handle this scenario where each intended release to production has it's own branch.  For example, let's assume for a second there is going to be a release at the end of June and another at the end of July.  The June release would get it's own branch, and all the features would be added there and sent to QA.  At this point we would begin working on July's release, and branch from June's branch.  When QA finds bugs we fix them in June's branch and once the fixes have been pushed to QA they are merged into July's release branch.  This does add a bit of overhead to handle these merges, but typically the merges are fairly painless.  Once in a while it is big pain in the you know what, but that only occurs when wholesale changes are made, and those shouldn't happen during the QA cycle (but they happen, more than I like to admit).  But with a good suite of tests (unit and integration), and code coverage and all the other TDD buzzwords, the risks are mitigated a bit.  To help out, we typically have one person handle merges for each project.</p>


答:
It's bad practice.

You shouldn't test public/private methods. You should test the class as a whole. Just make sure you have good coverage.

If you go the (primitive) way of testing each method separately as a rule of thumb, you'll find it extremely hard to refactor your class in the future. And that's one of the best things TDD enables you to do.

Besides, it is duplication. Furthermore, it suggests that the writer of the code didn't really know what he was doing. And the funny thing is, you do.

Some people treat their tests with less care than their production code. They shouldn't. If anything, my experience suggests to even treat the tests with more care. They're worth it.

Title: Are too many assertions code smell?


答:
However, unit testing is used for public methods.

If your testing framework allows for accessors, then unit testing private methods is also a good idea (IMO).

Could someone think of too many assertions as a code smell?

I do. Assertions are okay, but your first goal should be making it so that the scenario isn't even possible; not just that it doesn't happen.

Title: Are too many assertions code smell?


问:
Factors to be Considered for Software Risk Management
What are the risk factors that we need to consider while planning for a software project.</p>

答: Steve McConnell's Rapid Development contains a chapter on risk management, with a usefully long list of potential risks. I've used it as a starting point more than once.


问:
What is So Unique About Node.js?
Recently there has been a lot of praise for Node.js.  I am not a developer that has had much exposure to network application.  From my bare understanding of Nodes.js, its strength is: we have only one thread handling multiple connections, providing an event-based architecture.

However, for example in Java, I can create only one thread using NIO/AIO (which is non-blocking APIs from my bare understanding), and handle multiple connections using that thread, and I provide an event-based architecture to implement the data handling logic (shouldn't be that difficult by providing some callback etc.)?

Given JVM being a even more mature VM than V8 (I expect it to run faster too), and event-based handling architecture seems to be something not difficult to create,  I am not sure why Node.js is attracting so much attention.  Did I miss some important points?

答:
Probably the main reason is that it uses JavaScript to write server-side components for things such as web servers, web applications or web services. This unifies the traditional front end (client-side) development language JavaScript with the server-side language.

You're right - the fact it is non-blocking, using the reactor pattern is not unique - it has been done before using other languages and frameworks, such as Ruby's EventMachine or Python's Twisted for example.

Title: What is So Unique About Node.js?


问:
function works fine without return value in c++
I forgot to write return 'a'; in the show function and return 0; in main function but it works fine in Code::Blocks.

```<code>#include <iostream>

using namespace std;

char show()
{
  cout<<"this is show function"<<endl;
}

int main()
{
  show();
}
</code>```

I am using Code::Blocks 10.05 in Ubuntu 12.04.
Why does this code work fine in Code::Blocks but not in Turbo C++?

答:
If a function is declared to return a value, and fails to do so, the result is undefined behavior (in C++). One possible result is seeming to work, which is pretty much what you're seeing here.

As an aside, in C, you wouldn't actually have undefined behavior -- in C, you get undefined behavior only if you try to use the return value, and the function didn't specify a value to return.

ContentLicense: CC BY-SA 4.0


答:
Adding to the list of (mostly) exceptional answers, another reason for lots of asserts, and duplication, is that you don't know how, when or by whom the class will be modified over it's life time. If you are writing throw away code that will be dead in a year, not a concern. If you are writing code that will be in use in 20+ years, it will look quite different - and a assumption you have made may no longer be valid. The guy who makes that change will thank you for the asserts.

Also not all programmers are perfect - again, the asserts mean that one of those "slip ups" won't propagate too far.

Do not underestimate the effect these asserts (and other checks about assumptions) will have in reducing the cost of maintenance.

Title: Are too many assertions code smell?


答:
I have previously worked as a contractor who was not allowed to see the customers "Crown Jewels". This was an operation with Military contracts, confidentiality printed on every page, rooms with locks and more locks and "If you go in there we will have to shoot you" kind of things going on. I was GIVEN the "Crown Jewels" several times by accident. I gave up reporting it deleted it if I was ever given it.

My advise is unless you have an exceptionally robust process don't bother, you won't succeed in locking down the code.

Hire professionals, stitch them in NDA's (Which are pretty much unenforceable until the losses get into millions of dollars), and trust them to get on with the job. If you cannot trust them, why give them access to any code, let alone let them program for you?


问:
What do you look at first: the code or the design?
If you've just been introduced to a new project, what's the first thing you look for to get an idea of how it works?

Do you look for the design first?  If there is a design, what do you look for in it? Class diagrams or deployment diagrams or sequence diagrams or something else?

Or do you go straight for the code? If so, how do you understand how the different layers interact?

答: It depends upon the type of application. If its a data-centric app, I usually start with the database design. If it has a UI you can run (or good screen designs) those can also give you a good idea what the app does very quickly (I'm talking just a few hours here at most). After that I start digging into code and it will make more sense because I know what the application is doing.</p>


问:
Senior Interview LINQ questions
I'm preparing a LINQ section in interview questions for senior programmers. What are the most interesting questions in LINQ to include? And why?</p>

答:
Ask them to build a small rules engine, using Func[]rules{}.
Each rule has to be true, the array replacing case or if statements.

I just started on linq and lambdas but figure this is a nice test of problem solving and linq literacy.

In addition to the more qualified suggestions on here.

OwnerDisplayName: mBotros

Title: Senior Interview LINQ questions


问:
Asynchronous update design/interaction patterns
These days many apps support asynchronous updates. For example, if you're looking at a list of widgets and you delete one of them then rather than wait for the roundtrip to the server, the app can hide the one you deleted, giving immediate feedback. The actual deletion on the server will happen in the background. This can be seen in web apps, desktop apps, iOS apps, etc.

But what about when the background operation fails. How should you feed back to the user? Should you restore the UI to the pre-deletion state? What about when multiple background operations fail together?

Does this behaviour/pattern have a name? Perhaps something based on the Command pattern?

答:
Since it is "just hypothetical" for now here are a few suggestions to 'help discover' this for yourself. Although it's best to put on a user's hat every now and then and see if you'd like it if you were in their place.

Let's assume every 'interaction' is a use-case or XP's user-story. Think of what it means to be 'done' or 'successful' i.e. when will you say it's fully functional and ready for delivery? That should give you the list of alternate scenarios that you probably already have.

Now for every alternate scenario trace out the steps. See if you can easily write it as step 1, step 2, ... , step N. If you can you be readily assured that you are keeping it simple. If it gets too convoluted, may be that's not the way to go and you need to look for something simpler or rethink your strategy.

Another option: Prototype the GUIs. What looks good or feels intuitive? Try capturing the steps as above and see if the 'use case' is simple/complex.

If you 'feel happy' about it you may think you've done a good job. Cross verify this with other humans who think differently than you. Reason? MS devs love their product (Windows) but most people would not like the UI :P So you need the perspective of people who'll probably use your system but are not techies.

Note: every thing should provide valuable information. Is restoring the UI to pre-deletion valid and expected? Maintain the natural/commonly found interactions so that the system is usable and intuitive.

So think of how you want to handle the failure of multiple background operations. Should you show an 'alert for each' or 'batch them up' or show it at point of submission? It depends on what are the needs and what makes life easier. Since it's all hypothetical it's hard to say and keeps things subjective. I doubt if there'll ever be an objective answer.

This pattern doesn't have any name other than 'analysis-design-feedback-iterate' IMHO :)

My suggestion: First build the app and once you actually hit the spot where this is a concern you may ask a more specific 'tactical' question.

Best of luck!


答:
While that concept can indeed be implemented in many languages (and as dodgy_coder mentioned, it has been implemented in Ruby and Python at least), it's not quite as trivial as you state.

True, Java has non-blocking IO APIs. So you can do raw disk/network IO in a non-blocking way. However every API that somehow wraps or handles IO needs to be implemented in a non-blocking way as well. Every XML parser, every Database driver, every file-format converter needs to be written to support non-blocking IO. Because if a single library is blocking in this pattern, then that brings down your servers performance to stone-age values.

Node.js has that library infrastructure, because it was always designed that way: every library that strives to become popular has to provide an asynchronous API or it will not be used.

Title: What is So Unique About Node.js?

Body:
Recently there has been a lot of praise for Node.js.  I am not a developer that has had much exposure to network application.  From my bare understanding of Nodes.js, its strength is: we have only one thread handling multiple connections, providing an event-based architecture.

However, for example in Java, I can create only one thread using NIO/AIO (which is non-blocking APIs from my bare understanding), and handle multiple connections using that thread, and I provide an event-based architecture to implement the data handling logic (shouldn't be that difficult by providing some callback etc.)?

Given JVM being a even more mature VM than V8 (I expect it to run faster too), and event-based handling architecture seems to be something not difficult to create,  I am not sure why Node.js is attracting so much attention.  Did I miss some important points?


问:
Why is x=x++ undefined?
It's undefined because the it modifies x twice between sequence points. The standard says it's undefined, therefore it's undefined.

That much I know.

But why?

My understanding is that forbidding this allows compilers to optimize better. This could have made sense when C was invented, but now seems like a weak argument.

If we were to reinvent C today, would we do it this way, or can it be done better?

Or maybe there's a deeper problem, that makes it hard to define consistent rules for such expressions, so it's best to forbid them?

So suppose we were to reinvent C today. I'd like to suggest simple rules for expressions such as x=x++, which seem to me to work better than the existing rules.

I'd like to get your opinion on the suggested rules compared to the existing ones, or other suggestions.

Suggested Rules:

Between sequence points, order of evaluation is unspecified.

Side effects take place immediately.

There's no undefined behavior involved. Expressions evaluate to this value or that, but surely won't format your hard disk (strangely, I've never seen an implementation where x=x++ formats the hard disk).

Example Expressions

x=x++ - Well defined, doesn't change x.

First, x is incremented (immediately when x++ is evaluated), then it's old value is stored in x.

x++ + ++x - Increments x twice, evaluates to 2*x+2.

Though either side may be evaluated first, the result is either x + (x+2) (left side first) or (x+1) + (x+1) (right side first).

x = x + (x=3) - Unspecified, x set to either x+3 or 6.

If the right side is evaluated first, it's x+3. It's also possible that x=3 is evaluated first, so it's 3+3. In either case, the x=3 assignment happens immediately when x=3 is evaluated, so the value stored is overwritten by the other assignment.

x+=(x=3) - Well defined, sets x to 6.

You could argue that this is just shorthand for the expression above.

But I'd say that += must be executed after x=3, and not in two parts (read x, evaluate x=3, add and store new value).

What's the Advantage?

Some comments raised this good point.

I certainly don't think expressions such as x=x++ should be used in any normal code.

Actually, I'm much more strict than that - I think the only good usage for x++ in as x++; alone.

However, I think the language rules must be as simple as possible. Otherwise programmers just don't understand them. the rule forbidding changing a variable twice between sequence points is certainly a rule most programmers don't understand.

A very basic rule is this:

If A is valid, and B is valid, and they're combined in a valid way, the result is valid.

x is a valid L-value, x++ is a valid expression, and = is a valid way to combine an L-value and an expression, so how come x=x++ isn't legal?

The C standard makes an exception here, and this exception complicates the rules. You can search stackoverflow.com and see how much this exception confuses people.

So I say - get rid of this confusion.

=== Summary of Answers ===

Why do that?

I tried to explain in the section above - I want C rules to be simple.

Potential for optimization:

This does take some freedom from the compiler, but I didn't see anything that convinced me that it might be significant.

Most optimizations can still be done. For example, a=3;b=5; can be reordered, even though the standard specifies the order. Expressions such as a=b[i++] can still be optimized similarly.

You can't change the existing standard.

I admit, I can't. I never thought I can actually go ahead and change standards and compilers. I only wanted to think if things could have been done differently.

答:
Legacy

The assumption that C could be reinvented today cannot hold. There are so many lines of C codes that have been produced and are daily used, that changing the rules of the game in the middle of the play is just wrong.

Of course you can invent a new language, say C+=, with your rules. But that will not be C.

Title: Why is x=x++ undefined?


答: I would start at a higher level.  If there is any user facing documentation - user manual or guide.  Failing that then have a look at the requirements spec so that you have some idea as to what the software is supposed to do.  I would than look at the design and try to map it onto the code files.  Hopefully these are structured into folders in some sensible way.  I would then pick part of the design and go into the files to follow the flow of the code without getting too bogged down into the fine detail.</p>

Title: What do you look at first: the code or the design?

Body:
If you've just been introduced to a new project, what's the first thing you look for to get an idea of how it works?

Do you look for the design first?  If there is a design, what do you look for in it? Class diagrams or deployment diagrams or sequence diagrams or something else?

Or do you go straight for the code? If so, how do you understand how the different layers interact?


问:
Any one ever heard of the term collapsed Backbone?
Any one ever heard of the term collapsed Backbone?  Could it be a virtual network that could be referred also to this term.</p>

答:
Yes they are referring to a virtual network.

A non distributed backbone where all network segments are interconnected via a single internetworking device. A collapsed backbone may be a virtual network segment existing in a device such as a repeater, router, or bridge.

http://bitwisertraining.com/Glossary/CollapsedBB.htm


答:
Maybe you should first answer the question why it should be defined? Is there any advantage in programming style, readability, maintainability or performance by allowing such expressions with additional side effects? Is

```<code>y = x++ + ++x;
</code>```

more readable than

```<code>y = 2*x + 2;
x += 2;
</code>```

Given that such a change is extremely fundamental and breaking to the existing code base.

Title: Why is x=x++ undefined?

Body:
It's undefined because the it modifies x twice between sequence points. The standard says it's undefined, therefore it's undefined.

That much I know.

But why?

My understanding is that forbidding this allows compilers to optimize better. This could have made sense when C was invented, but now seems like a weak argument.

If we were to reinvent C today, would we do it this way, or can it be done better?

Or maybe there's a deeper problem, that makes it hard to define consistent rules for such expressions, so it's best to forbid them?

So suppose we were to reinvent C today. I'd like to suggest simple rules for expressions such as x=x++, which seem to me to work better than the existing rules.

I'd like to get your opinion on the suggested rules compared to the existing ones, or other suggestions.

Suggested Rules:

Between sequence points, order of evaluation is unspecified.

Side effects take place immediately.

There's no undefined behavior involved. Expressions evaluate to this value or that, but surely won't format your hard disk (strangely, I've never seen an implementation where x=x++ formats the hard disk).

Example Expressions

x=x++ - Well defined, doesn't change x.

First, x is incremented (immediately when x++ is evaluated), then it's old value is stored in x.

x++ + ++x - Increments x twice, evaluates to 2*x+2.

Though either side may be evaluated first, the result is either x + (x+2) (left side first) or (x+1) + (x+1) (right side first).

x = x + (x=3) - Unspecified, x set to either x+3 or 6.

If the right side is evaluated first, it's x+3. It's also possible that x=3 is evaluated first, so it's 3+3. In either case, the x=3 assignment happens immediately when x=3 is evaluated, so the value stored is overwritten by the other assignment.

x+=(x=3) - Well defined, sets x to 6.

You could argue that this is just shorthand for the expression above.

But I'd say that += must be executed after x=3, and not in two parts (read x, evaluate x=3, add and store new value).

What's the Advantage?

Some comments raised this good point.

I certainly don't think expressions such as x=x++ should be used in any normal code.

Actually, I'm much more strict than that - I think the only good usage for x++ in as x++; alone.

However, I think the language rules must be as simple as possible. Otherwise programmers just don't understand them. the rule forbidding changing a variable twice between sequence points is certainly a rule most programmers don't understand.

A very basic rule is this:

If A is valid, and B is valid, and they're combined in a valid way, the result is valid.

x is a valid L-value, x++ is a valid expression, and = is a valid way to combine an L-value and an expression, so how come x=x++ isn't legal?

The C standard makes an exception here, and this exception complicates the rules. You can search stackoverflow.com and see how much this exception confuses people.

So I say - get rid of this confusion.

=== Summary of Answers ===

Why do that?

I tried to explain in the section above - I want C rules to be simple.

Potential for optimization:

This does take some freedom from the compiler, but I didn't see anything that convinced me that it might be significant.

Most optimizations can still be done. For example, a=3;b=5; can be reordered, even though the standard specifies the order. Expressions such as a=b[i++] can still be optimized similarly.

You can't change the existing standard.

I admit, I can't. I never thought I can actually go ahead and change standards and compilers. I only wanted to think if things could have been done differently.

Body:
Maybe you should first answer the question why it should be defined? Is there any advantage in programming style, readability, maintainability or performance by allowing such expressions with additional side effects? Is

y = x++ + ++x;

more readable than

y = 2*x + 2;
x += 2;

Given that such a change is extremely fundamental and breaking to the existing code base.


答:
Eric Lippert, a principal designer on the C# compiler team, posted on his blog an article about a number of considerations that go into choosing to make a feature undefined at the language spec level.  Obviously C# is a differently language, with different factors going into its language design, but the points he makes are relevant nonetheless.

In particular, he points out the issue of having existing compilers for a language that have existing implementations and also have representatives on a committee.  I'm not sure if that's the case here, but tends to be relevant to most C and C++ related spec discussions.

Also of note is, as you said, the performance potential for compiler optimization.  While it's true that the performance of CPUs these days are many orders of magnitude greater than they were when C was young, a large amount of C programming done these days are done specifically because of the potential performance gain, and the potential for (hypothetical future) CPU instruction optimizations and multicore processing optimizations would be silly to preclude because of an overly-restrictive set of rules for handling side effects and sequence points.

Title: Why is x=x++ undefined?


答:
It's hard to be language-agnostic about this issue, as the details of how assertions and 'proper' error/exception handling are implemented have a bearing on the answer. Here's my $0.02, based on my knowledge of Java & C++.

Assertions in private methods are a good thing, assuming you don't go overboard and put them everywhere. If you're putting them on really simple methods or repeatedly checking things like immutable fields, then you're cluttering up the code needlessly.

Assertions in public methods are generally best avoided. You should still be doing things like checking that the method contract isn't violated, but if it is then you ought to be throwing suitably-typed exceptions with meaningful messages, reverting state where possible, etc. (what @rwong calls "the full proper error handling treatment").

Generally speaking, you should only be using assertions to help your development/debugging. You can't assume that whoever uses your API will even have assertions enabled when they use your code. Though they do have some use in helping document the code, there are often better ways to document the same things (i.e. method documentation, exceptions).

Title: Are too many assertions code smell?


问:
Benefits of classic OOP over Go-like language
I've been thinking a lot about language design and what elements would be necessary for an "ideal" programming language, and studying Google's Go has led me to question a lot of otherwise common knowledge.

Specifically, Go seems to have all of the interesting benefits from object oriented programming without actually having any of the structure of an object oriented language. There are no classes, only structures; there is no class/structure inheritance -- only structure embedding. There aren't any hierarchies, no parent classes, no explicit interface implementations. Instead, type casting rules are based on a loose system similar to duck-typing, such that if a struct implements the necessary elements of a "Reader" or a "Request" or an "Encoding", then you can cast it and use it as one.

Is there something about OOP as implemented in C++ and Java and C# that is inherently more capable, more maintainable, somehow more powerful that you have to give up when moving to a language like Go? What benefit do you have to give up to gain the simplicity that this new paradigm represents?

EDIT

Removed the "obsolete" question that readers seemed to get excessively hung up on and infuriated by.

The question is, what does the traditional object oriented paradigm (with hierarchies and such) as frequently seen in common language implementations have to offer that can't be done as easily in this simpler model? Or, in other words, if you were to design a language today, is there a reason you would want to include the concept of class hierarchies?

答:
There is no new paradigm. Object orientation is a pattern you use to write programs, which is not even clearly defined. Various languages provide various traits typical of object orientation (definition of new types, encapsulation, type hierarchies, polymorphism, message passing and more) but may fail to provide others. In those cases it is up to programmers to emulate them if the need arises.

Many of the languages that provide these features do not have an analogue of the class concept - for instance Javascript and Common Lisp. The implementation provided by Java-like languages (class-based, with single inheritance, interfaces, type-based dispatch) is just one of the possibilities, and not necessarily the best one.


问:
Staying alert and awake while coding
What methods do you use to stay awake and alert while working?

Personally I drink coffee non stop throughout the day.  But I've also heard of this thing called exercise that should help too.  Does anyone else have tips and tricks to stay more awake and alert while working?  Redbull? Maybe a magic pill that won't require me to sleep?

答: Frequent short breaks at regular intervals (get up from chair, and think of something else for a few minutes). Then a longer break after 4 short ones. </p>

Title: Staying alert and awake while coding


问:
What popular "best practices" are not always best, and why?
"Best practices" are everywhere in our industry.  A Google search on "coding best practices" turns up nearly 1.5 million results.  The idea seems to bring comfort to many; just follow the instructions, and everything will turn out fine.

When I read about a best practice - for example, I just read through several in Clean Code recently - I get nervous.  Does this mean that I should always use this practice?  Are there conditions attached?  Are there situations where it might not be a good practice?  How can I know for sure until I've learned more about the problem?

Several of the practices mentioned in Clean Code did not sit right with me, but I'm honestly not sure if that's because they're potentially bad, or if that's just my personal bias talking.  I do know that many prominent people in the tech industry seem to think that there are no best practices, so at least my nagging doubts place me in good company.

The number of best practices I've read about are simply too numerous to list here or ask individual questions about, so I would like to phrase this as a general question:

Which coding practices that are popularly labeled as "best practices" can be sub-optimal or even harmful under certain circumstances?  What are those circumstances and why do they make the practice a poor one?

I would prefer to hear about specific examples and experiences.

答:
Don't use anything open-source (or non-Microsoft for you .NET developers)

If Microsoft didn't develop it -- we don't use it here.  Want to use ORM - EF, want to use IOC - Unity, want to log - enterprise logging application block.  So many better libraries exist -- yet I'm always stuck ordering from the dollar menu of the development world.  I swear every time I hear Microsoft Best Practices I think "McDonald's Nutritional Guidelines".  Sure, you'll probably live if you follow them, but you'll also be malnourished and overweight.

Note this might not be your best practice, but it's a common one followed almost everywhere I've worked.


问:
Big O(n log n) and Quicksort number of operations
I have an Array with 1,000,000 unsorted elements. I need to calculate expected number of operations that needs to be performed to sort array using Quicksort algorithm in common situations (not the n^2 worst case).

I am not sure how (n log n) is calculated  - does it even makes sense to calculate this?

If (n log n) = (n*log(some base)n) what base would be for Quicksort?

答:
The article on quicksort on Wikipedia explains what the algorithm is.

It shows an animation of how the sorting is being performed.

The base is '2'.


答:
Before you go on and continue your maths, I would recommend trying to understand big O notation. The notation helps you to have an idea about the evolution of computation costs when input size changes. The base of the log is irrelevant here as it just affects the constant factor

If you need to provide a precise number of operations, you have to analyse the algorithm and the data structure used for its implementation, and not just use a formula.

Title: Big O(n log n) and Quicksort number of operations

Body:
I have an Array with 1,000,000 unsorted elements. I need to calculate expected number of operations that needs to be performed to sort array using Quicksort algorithm in common situations (not the n^2 worst case).

I am not sure how (n log n) is calculated  - does it even makes sense to calculate this?

If (n log n) = (n*log(some base)n) what base would be for Quicksort?


答: the log here is in base 2, the big O notation merely says, that if you increase the value of number of elements, that is n in this case, how would the time to compute the output depend on it.</p>


问:
Handling (many) multiple projects in Git in an enterprise environment
One of the advantages of older version control systems such as CVS and SVN in enterprise development is that anyone can connect to source control and see all the projects that the company has. This can make it easier to get a high level view of what kid of development is happening outside your sprint and also keeps everything in one place and easy to find.

However, distributed version control systems (Git, specifically) use the repository as their base unit. They work best with one project (or several closely related projects) per repository. This makes repository management more difficult in most enterprise environments where it is not unusual to have more than 25-50 projects to support. As far as I have been able to determine, you have to keep a list somewhere else of all the repos you have. There is software available, like GitHub, that help, but that still is an extra step beyond a single connection string and listing the contents of the repository.

What is the best way to deal with the complexity of multiple repositories?

答:
Pro Git, the completely free book endorsed on Git's homepage explains very well how to setup a central server for managing multiple Git repositories.

http://git-scm.com/book/en/Git-on-the-Server-Gitosis

This is section 4.7 in chapter 4, I think it is a good match for your use case.


答:
OOP is not obsolete.

As Andrea said there have been many concepts proposed as an alternative to classes (for ex: haskell typeclass). OOP has one big benefit: it is taught in many places, and the culture of OOP is largely shared among developpers.

This enables richer communication inside a team. One can talk about factories more easily than about Zygohistomorphic prepromorphisms. OOP structures the way you will organize and communicate about your programm with commonly used diagrams. This is a powerful asset.

Title: Benefits of classic OOP over Go-like language

Body:
I've been thinking a lot about language design and what elements would be necessary for an "ideal" programming language, and studying Google's Go has led me to question a lot of otherwise common knowledge.

Specifically, Go seems to have all of the interesting benefits from object oriented programming without actually having any of the structure of an object oriented language. There are no classes, only structures; there is no class/structure inheritance -- only structure embedding. There aren't any hierarchies, no parent classes, no explicit interface implementations. Instead, type casting rules are based on a loose system similar to duck-typing, such that if a struct implements the necessary elements of a "Reader" or a "Request" or an "Encoding", then you can cast it and use it as one.

Is there something about OOP as implemented in C++ and Java and C# that is inherently more capable, more maintainable, somehow more powerful that you have to give up when moving to a language like Go? What benefit do you have to give up to gain the simplicity that this new paradigm represents?

EDIT

Removed the "obsolete" question that readers seemed to get excessively hung up on and infuriated by.

The question is, what does the traditional object oriented paradigm (with hierarchies and such) as frequently seen in common language implementations have to offer that can't be done as easily in this simpler model? Or, in other words, if you were to design a language today, is there a reason you would want to include the concept of class hierarchies?


答:
No, there's nothing new here, nor is OOP obsolete. C++ has implicit interfaces too in the form of templates, but people still use virtual functions. You need explicit interfaces to cope with, e.g., binary interfaces, or interfaces where the other code simply isn't known at compile-time.

You could argue that this is simply a case of inference vs stating it explicitly, which is nothing like a "new paradigm" and really just more convenient.


答:
Declaring that something is defined won't change the existing compilers to respect your definition. That is especially true in the case of an assumption which may have been relied on explicitly or implicitly in a lot of places.

The major issue for the assumption isn't with x = x++; (compilers can easily check for it and should warn), it is with *p1 = (*p2)++ and equivalent (p1[i] = p2[j]++; when p1 and p2 are parameters to a function) where the compiler can't know easily if p1 == p2 (in C99 restrict has been added to spread out the possibility of assuming p1 != p2 between sequence points, so it was deemed that the optimization possibilities were important).

Title: Why is x=x++ undefined?


问:
What are the design principles that promote testable code? (designing testable code vs driving design through tests)
Most of the projects that I work on consider development and unit testing in isolation which makes writing unit tests at a later instance a nightmare. My objective is to keep testing in mind during the high level and low level design phases itself.

I want to know if there are any well defined design principles that promote testable code. One such principle that I have come to understand recently is Dependency Inversion through Dependency injection and Inversion of Control.

I have read that there is something known as SOLID. I want to understand if following the SOLID principles indirectly results in code that is easily testable? If not, are there any well-defined design principles that promote testable code?

I am aware that there is something known as Test Driven Development. Although, I am more interested in designing code with testing in mind during the design phase itself rather than driving design through tests. I hope this makes sense.

One more question related to this topic is whether it's alright to re-factor an existing product/project and make changes to code and design for the purpose of being able to write a unit test case for each module?

答:
YOUR FIRST QUESTION:

SOLID is indeed the way to go. I find that the two most important aspect of the SOLID acronym, when it comes to testability, is the S (Single Responsibility) and the D (Dependency Injection).

Single Responsibility:
Your classes should really only be doing one thing, and one thing only. a class that creates a file, parses some input, and writes it to the file is already doing three things. If your class only does one thing, you know exactly what to expect of it, and designing the test cases for that should be fairly easy.

Dependency Injection (DI): This gives you control of the testing environment. Instead of creating forreign objects inside your code, you inject it through the class constructor or the method call. When unittesting, you simply replace real classes by stubs or mocks, that you control entirely.

YOUR SECOND QUESTION:
Ideally, you write tests that document the functioning of your code before refactoring it.  This way, you can document that your refactoring reproduces the same results as the original code. However, your problem is that the functioning code is hard to test. This is a classic situation! My advice is: Think carefully about refactoring before unit testing. If you can; write tests for the working code, then refactor the code, and then refactor the tests. I know it will cost hours, but you will be more certain, that the refactored code does the same as the old. Having said that, I have given up a lot of times. Classes can be so ugly and messy that a rewrite is the only way to make them testable.

OwnerDisplayName: bot

OwnerDisplayName: Morten


答:
I have read that there is something known as SOLID. I want to understand if following the SOLID principles indirectly results in code that is easily testable?

If applied correctly, yes. There's blog post by Jeff explaining SOLID principles in a really short way (mentioned podcast is worth listening too), I suggest giving a look there if longer descriptions are throwing you off.

From my experience, 2 principles from SOLID play major role in designing testable code:

Interface segregation principle - you should prefer many, client-specific interfaces instead of fewer, general-purpose ones. This goes in pair with Single Responsibility Principle and helps you design feature/task-oriented classes, which in return are much easier to test (as compared to the more general ones, or often abused "managers" and "contexts") - less dependencies, less complexity, more fine-grained, obvious tests. In short, small components lead to simple tests.

Dependency inversion principle - design by contract, not by implementation. This will benefit you the most when testing complex objects and realizing you don't need whole graph of dependencies just to set it up, but you can simply mock the interface and be done with it.

I believe these two will aid you the most when designing for testability. Remaining ones also have an impact, but I'd say not as large.

(...) whether it's alright to re-factor an existing product/project and make changes to code and design for the purpose of being able to write a unit test case for each module?

Without existing unit tests, it is simply put - asking for troubles. Unit test is your guarantee that your code works. Introducing breaking change is spotted immediately if you have proper tests coverage.

Now, if you want to change existing code in order to add unit tests, this introduces a gap where you don't have tests yet, but do have changed code already. Naturally, you might not have a clue what your changes broke. This is situation you want to avoid.

Unit tests are worth writing anyways, even against code that is difficult to test. If your code is working, but is not unit tested, appropriate solution would be to write tests for it and then introduce changes. However, note that changing tested code in order to make it more easily testable is something your management might not want to spend money on (you'll probably hear it brings little to no business value).

Title: What are the design principles that promote testable code? (designing testable code vs driving design through tests)

Body:
Most of the projects that I work on consider development and unit testing in isolation which makes writing unit tests at a later instance a nightmare. My objective is to keep testing in mind during the high level and low level design phases itself.

I want to know if there are any well defined design principles that promote testable code. One such principle that I have come to understand recently is Dependency Inversion through Dependency injection and Inversion of Control.

I have read that there is something known as SOLID. I want to understand if following the SOLID principles indirectly results in code that is easily testable? If not, are there any well-defined design principles that promote testable code?

I am aware that there is something known as Test Driven Development. Although, I am more interested in designing code with testing in mind during the design phase itself rather than driving design through tests. I hope this makes sense.

One more question related to this topic is whether it's alright to re-factor an existing product/project and make changes to code and design for the purpose of being able to write a unit test case for each module?


答:
The argument that making this undefined behavior allows better optimization is not weak today. In fact, it's much stronger today than it was when C was new.

When C was new, machines that could take advantage of this for better optimization were mostly theoretical models. People had talked about the possibility of building CPUs where the compiler would instruct the CPU about what instructions could/should be executed in parallel with other instructions. They pointed to the fact that allowing this to have undefined behavior meant that on such a CPU, if it ever really existed, you could schedule the "increment" part of the instruction to execute in parallel with the rest of the instruction stream. While they were right about the theory, at the time there was little in the way of hardware that could really take advantage of this possibility.

That's not just theoretical anymore. Now there is hardware in production, and in wide use, (e.g., Itanium, VLIW DSPs) that can really take advantage of this. They really do allow the compiler to generate an instruction stream that specifies that instructions X, Y and Z can all be executed in parallel. This is no longer a theoretical model -- it's real hardware in real use doing real work.

IMO, making this defined behavior is close to the worst possible "solution" to the problem. You clearly should not use expressions like this. For the vast majority of code, the ideal behavior would be for the compiler to simply reject such expressions entirely. At the time, C compilers didn't do the flow analysis necessary to detect that dependably. Even at the time of the original C standard, it still wasn't at all common.

I'm not sure it would be acceptable to the community today either -- while many compilers can do that kind of flow analysis, they typically only do it when you request optimization. I doubt most programmers would like the idea of slowing down "debug" builds just for the sake of being able to reject code they (being sane) would never write in the first place.

What C has done is a semi-reasonable second-best choice: tell people not to do that, allowing (but not requiring) the compiler to reject the code. This avoids (still further) slowing compilation for people who'd never use it, but still allows somebody to write a compiler that will reject such code if they want to (and/or have flags that will reject it that people can choose to use or not as they see fit).

At least IMO, making this defined behavior would be (at least close to) the worst possible decision to make. On VLIW-style hardware, you choices would be to generate slower code for the reasonable uses of the increment operators, just for the sake of crappy code that abuses them, or else always require extensive flow analysis to prove that you aren't dealing with crappy code, so you can produce the slow (serialized) code only when truly necessary.

Bottom line: if you want to cure this problem, you should be thinking in the opposite direction. Instead of defining what such code does, you should define the language so such expressions simply aren't allowed at all (and live with the fact that most programmers will probably opt for faster compilation over enforcing that requirement).

Title: Why is x=x++ undefined?


问:
using source control to create release notes?
Lets say i have an off the shelf eccomerce cart. I put all the code inside subversion. I start to make changes and check the code changes back in.

is it possible to then display each "check in" with the developer messages so that i can make release notes?

I would like to use this for actual quoted time.

答:
Check out svn log. It should do what you're after.

...the repository is like a time machine. It keeps a record of every change ever committed, and allows you to explore this history by examining previous versions of files and directories as well as the metadata that accompanies them... There are several commands that can provide you with historical data from the repository...

To find out information about the history of a file or directory, use the svn log command. svn log will provide you with a record of who made changes to a file or directory, at what revision it changed, the time and date of that revision, and, if it was provided, the log message that accompanied the commit...

If you want even more information about a file or directory, svn log also takes a --verbose (-v) switch. Because Subversion allows you to move and copy files and directories, it is important to be able to track path changes in the filesystem, so in verbose mode, svn log will include a list of changed paths in a revision in its output...


答: In some cases, this kind of code was defined in the new C++11 Standard.

Title: Why is x=x++ undefined?


答:
Object orientation

There is the assumption, just because code is "object-oriented", it's magically good. So people go on squeezing functionality into classes and methods, just to be object-oriented.

Title: What popular "best practices" are not always best, and why?

Body:
"Best practices" are everywhere in our industry.  A Google search on "coding best practices" turns up nearly 1.5 million results.  The idea seems to bring comfort to many; just follow the instructions, and everything will turn out fine.

When I read about a best practice - for example, I just read through several in Clean Code recently - I get nervous.  Does this mean that I should always use this practice?  Are there conditions attached?  Are there situations where it might not be a good practice?  How can I know for sure until I've learned more about the problem?

Several of the practices mentioned in Clean Code did not sit right with me, but I'm honestly not sure if that's because they're potentially bad, or if that's just my personal bias talking.  I do know that many prominent people in the tech industry seem to think that there are no best practices, so at least my nagging doubts place me in good company.

The number of best practices I've read about are simply too numerous to list here or ask individual questions about, so I would like to phrase this as a general question:

Which coding practices that are popularly labeled as "best practices" can be sub-optimal or even harmful under certain circumstances?  What are those circumstances and why do they make the practice a poor one?

I would prefer to hear about specific examples and experiences.


答:
What benefit do you have to give up to gain the simplicity that this new paradigm represents?

The type checking for a structural type system is a lot more complex than simply checking if the baseclass is in your inheritance list. Virtual dispatch becomes a bit trickier, and likely less performant.

Does such a system obsolete the concept of OOP?

No. As long as you can make the program in terms of 'objects that do things' rather than a list of instructions, or a declared set of rules, or a cascading series of functions... the implementation doesn't matter. Likewise, changing the type system doesn't invalidate any of the common OO principles.

You can still work on a base type and not care about its actual type. You can still extend types without modifying them. You can still make a type do only one thing. You can still supply fine grained interfaces. You can still supply abstractions to your types.

How a language allows that doesn't really matter.


问:
Why does iPhone and iPad apps have a Free version and a full version, instead of "unlocking" it through in-app purchase?
Many apps have a Free version and a Full version.  How is it compared to, installing a single version, and use an in-app purchase of $0.99 or $1.99 to unlock to the program to make it a full version?  It does have the advantage that the user doesn't have to go to the App Store and install the program one more time and thus making it easier for the users to purchase.</p>

答: if you look at ratings and comments for apps that require in-app purchase to get the complete functionality people often regard it as a ripp-off. why? because people are moving fast and do not read. so they see a free app, read the feature list and download it only to discover later that most features have to be enabled via in-app purchase. of you provide both, free and full version, you have two possibilities to explain it in the app store. and just by adding "free" or "light" to your app name you make it obvious that there are 2 versions with different functionalities. you cannot do this with in-app purchase. in-app purchase is only good for adding new functionality and features, not for unlocking the basic functionality.</p>