问:
Functional testing must be done by external party to avoid bias?
Our developers demand that someone external to the development team completes the functional testing. Their argument is that they are biased and cannot test their own code as they are too close to it. Our last round of testing is with the client in the form of UAT.

To be clear by 'functional testing' I mean testing the code against the specs, eg. when you click on 'submit' the index page should load. By UAT I mean the client comes in and runs through use cases on the release candidate.

While I understand this argument of bias, is it reasonable for the developers to demand someone else complete their functional testing or is this just a way to avoid doing their job?

答:
At my job we (formally, specifics may vary) use two levels of testing before a product reaches a customer:

Developers test their own code using Unit Tests: test class invariants and functions contracts, ensure maximum code coverage. I'd love to push for fuzzy testing, but it's hard to setup in general...

Business Analysts (the guys who wrote the specifications) validate the code (once) and create Non-regression scenarios. This is done both for changes and fixes.

This means that we (developers) test the implementation specific details, while the Business Analysts test the functional details.

It would be great if BA could provide the functional tests before we code (TDD), however my team has the peculiarity of working on web sites, so it's much easier to work/test the produce iteratively until we reach what we want, and then record the actions to create a test case.


问:
How to significantly improve Java performance?
The team over at LMAX have a presentation about how they were able to do 100k TPS at less than 1 ms of latency. They have backed up that presentation with a blog, technical paper (PDF) and the source code itself.

Recently, Martin Fowler published an excellent paper on the LMAX architecture and mentions that they are now able to handle six million orders per second and highlights a few of the steps that the team took to go up another order of magnitude in performance.

So far I've explained that the key to the speed of the Business Logic
Processor is doing everything sequentially, in-memory. Just doing this (and
nothing really stupid) allows developers to write code that can process 10K TPS.

They then found that concentrating on the simple elements of good code could
bring this up into the 100K TPS range. This just needs well-factored code and
small methods - essentially this allows Hotspot to do a better job of
optimizing and for CPUs to be more efficient in caching the code as it's
running.

It took a bit more cleverness to go up another order of magnitude. There are
several things that the LMAX team found helpful to get there. One was to write
custom implementations of the Java collections that were designed to be
cache-friendly and careful with garbage.

Another technique to reach that top level of performance is putting attention
into performance testing. I've long noticed that people talk a lot about
techniques to improve performance, but the one thing that really makes a
difference is to test it

Fowler mentioned that there are several things that were found, but he only mentioned a couple.

Are there other architectures, libraries, techniques or "things" that are helpful to reach such levels of performance?

答:
Other than already stated in an excellent answer from Aaronaught I would like to note that code like that might be quite difficult to develop, understand and debug. "While very efficient... it is very easy to screw up..." as one of their guys mentioned in LMAX blog.

For a developer used to traditional queries-and-locks, coding for a new approach might feel like riding the wild horse. At least that was my own experience when experimenting with Phaser which concept is mentioned in LMAX technical paper. In that sense I would say this approach trades lock contention for developer brain contention.

Given above, I think that those choosing Disruptor and similar approaches better make sure that they have development resources sufficient to maintain their solution.

Overall, Disruptor approach looks quite promising to me. Even if your company can't afford utilizing it eg for the reasons mentioned above, consider convincing your management to "invest" some effort into studying it (and SEDA in general) - because if they don't then there's a chance that one day their customers will leave them in favor of some more competitive solution requiring 4x, 8x etc less servers.

ContentLicense: CC BY-SA 3.0


问:
one programmer, many languages -- the name dilemma
When you work across multiple programming languages, there is a problem you encounter...

A valid name (identifier) in one language is invalid in another. For example...

var new function this are a keywords in JavaScript, but you can use them freely in Python. Similarly list dict def can be used in JavaScript without problems.

This is a very common and something programmers generally quickly become acquainted with when they program in multiple languages.

However, when you're working in collaboration, you have to lay out some rules/guidelines for your team members to ensure consistency and uniformity in the code. With teams, this issue becomes more important than simply remembering what's valid and what's not while you program.

So, my question is, what strategies you adopt...

simply take a union of all the reserved words present in all the languages you use, hand out a list to everybody and abstain their use?

accept the diversity and take extra pains when "context switching"

adopt an intermediate ground where one language can use the other's, but not vice-versa

(Note: i am only talking about Python and JavaScript in this question ... but please answer the question more broadly)

-- UPDATE --

Thanks for all the answers. So the general consensus i see emerging is to let programmers use any name regardless of what they do other languages -- as long as names are descriptive, it doesn't hurt.

答:
I can't see how this could ever be a problem, unless you plan on moving code from one language to another. If you personally tend to forget what variable names are valid, then don't use a variable name unless you are personally sure it's valid. But if other people use invalid variable names, their code won't compile or run. So if you're working on someone else's code, and they called something 'var', you can be pretty sure it's a valid name on whatever language they're using.

If you might plan on moving code from one language to another, then you may need a list of prohibited names. For example, my C coding practices document prohibits using new or class as a variable because that makes the code harder to port to C++. In that case, it's reasonable to set rules that ease that job, should it become necessary,


问:
Does defining the stopping point of a genetic algorithm defeat the purpose of the algorithm?
Wikipedia defines the termination point of a GA to this:

Commonly, the algorithm terminates when either a maximum number of
  generations has been produced, or a satisfactory fitness level has
  been reached for the population. If the algorithm has terminated due
  to a maximum number of generations, a satisfactory solution may or may
  not have been reached.

Now, if it terminates when a satisfactory fitness level has been reached, and you are the one defining that fitness level, why wouldn't you just be able to create the "perfect" genome from the beginning yourself, since you already know the characteristics of this perfect genome?

I guess I'm just a little confused here. I thought the purpose of a GA was to constantly evolve and show us possibly an even better solution than what we thought of, and our fitness function was just something that helped it along the way, not something we put on the pedestal as the termination "perfect" state. Doesn't that destroy the point?

答:
A genetic algorithm requires some way to reward good genes with greater propagation. If you had no way to tell good genes from bad genes, you couldn't use a genetic algorithm at all.

For a genetic algorithm to work, you must allow the more fit solutions to reproduce in preference to the less fit solutions. Otherwise, you'd just be trying random solutions.

Here's a typical example from my own experience: Developing one of the first voice dialing systems, we had a hard time finding an algorithm to match a spoken name to a stored copy of that same name. We were told that 95% accuracy picking one name out of 25 was sufficient. We had a stored corpus of people saying 25 names 10 times each.

First, we developed an input system that measured the length of the spoken word and the frequency energy in several normalized chunks of it. Then we developed an algorithm that assigned weights to the matches on those parameters and compared two sets of parameters through those weights.

Now, we had one last step -- what should the value of those weights be?

We created 1,000 random sets of weights and tested them against the corpus. We threw away the 500 that performed the worst. For the remaining 500, we duplicated each one and in one of them, randomly raised or lowered one of the weights.

We repeated this process on a computer for about two weeks until it finally had a set of weights that met the 95% accuracy criterion. Then we tested it on data not in the corpus. It was about 92% accurate. So we ran longer to get to 98% accuracy on the corpus and that set of weights produced 95% accuracy on data not in the corpus.

So, the point is, you must have a fitness function to run a genetic algorithm. If you have no way to tell good genes from bad genes, how can you make sure the good genes reproduce and the bad genes don't?


问:
AGPL Question about Linking and Derivative Works
I'm thinking of selling a collection of Django apps I've written which provide the basic functionality of a Facebook game, but I'm also thinking of releasing it under a GNU Affero GPL.

I read the Affero GPL, and the extra clause specified that modified versions of a covered work have to be distributed under the same license. What I'm wondering is, do derivative works have to be distributed under the GNU Affero License, even if they don't modify the original? The scenario is someone could use my project and add a few features of their own contained in separate Django apps; would those new apps they've written which depend on my software have to be released under an Affero license as well?

答: Any work containing sufficient protectable expression from code covered by the AGPL (that is, a derivative work) must have its source code released if it is distributed. Such a work is a "work based on the Program".</p>


问:
How can a server side language span many servers?
I would like to ask you as experts about PHP, ASP.NET/C#, Python or any other server side language.

How do they span multiple servers? When I see a big website and look how many dedicated servers it uses, at least it uses 10 servers. I sit and think how the langauge that was used in building this site span these servers? Is there something in the language itself or its architecture that make it able to go with this and is there some language that are better than others regarding this?

Edit: But I see many ASP.NET and PHP powered sites that are on many servers, in this case how can the same programmed site be on server 1, on server 2, etc. Does Server 1 contain some functionality for example and Server 2 contain others? Or do they just progrm the site and the hosting company makes balance between these servers?

答:
There are several basic ways this is done, none of them require special support at the language level:

1) All servers can do everything that needs to be done. A user is assigned to a server randomly, based on the server closest to him netwise, or based on load. Each server just does its job without caring that a bunch of other servers are doing the same thing. The servers may access a common database.

2) Servers do completely different jobs. One server may hold static images. Another server may hold RSS feeds. Another server might store account information. A web page may contain assembled bits and pieces from many different servers and submit a form to yet some other server. Another server might handle email.

3) Servers do the same type of job, but divide the task space. For example, a news site might have five web servers, one for international news, one for local news, one for weather, and so on.

4) Servers use an assembly line approach. A front end server might receive web requests, confirm that they are valid, and pick a second-level server. The second-level server might log the request and figure out which third-level server handles the data the user is after. The third-level server assembles the data, possibly using a database, and hands it back to the second-level server. The second-level server builds the HTML or XML or whatever the user requires and passes it back to the first-level server.


答:
Won't particularly comment on the LMAX code because I think that is amply descibed, but here are some examples of things I've done that have resulted in significant measurable performance improvements.

As always, these are techniques that should be applied once you know that you have a problem and need to improve performance - otherwise you are likely just to be doing premature optimisation.

Use the right data structure, and create a custom one if needed - correct data structure design dwarfs the improvement you will ever get from micro-optimisations, so do this first. If your algorithm depends for performance on lots of fast O(1) random access reads, make sure you have a data structure that supports this! It's worth jumping through some hoops to get this right, e.g. finding a way that you can represent your data in an array to exploit very fast O(1) indexed reads.

CPU is faster than memory access - you can do quite a lot of calculation in the time it takes to make one random memory read if the memory is not in L1/L2 cache. It's usually worth doing a calculation if it saves you a memory read.

Help the JIT compiler with final - making fields, methods and classes final enables specific optimisations that really help the JIT compiler. Specific examples:

The compiler can assume that a final class has no subclasses, so can turn virtual method calls into static method calls

The compiler can treat a static final fields as a constant for a nice performance improvement, especially if the constant is then used in calculations that can be computed at compile time.

If a field containing a Java object is initialised as final, then the optimiser can eliminate both the null check and virtual method dispatch. Nice.

Replace collection classes with arrays - this results in less readable code and is trickier to maintain but is almost always faster as it removes a layer of indirection and benefits from lots of nice array-access optimisations. Usually a good idea in inner loops / performance sensitive code after you have identified it as a bottleneck, but avoid otherwise for the sake of readability!

Use primitives wherever possible - primitives are fundamentally faster than their object-based equivalents. In particular, boxing adds a huge amount of overhead and can cause nasty GC pauses. Don't allow any primitives to be boxed if you care about performance/latency.

Minimise low-level locking - locks are very expensive at a low level. Find ways to either avoid locking entirely, or lock at a coarse-grained level so that you only need to lock infrequently over large blocks of data and the low-level code can proceed without having to worry at all about locking or concurrency issues.

Avoid allocating memory - this might actually slow you down overall since JVM garbage collection is incredibly efficient, but is very helpful if you are trying to get to extremely low latency and need to minimise GC pauses. There are special data structures that you can use to avoid allocations - the http://javolution.org/ library in particular is excellent and notable for these.

Title: How to significantly improve Java performance?

Body:
The team over at LMAX have a presentation about how they were able to do 100k TPS at less than 1 ms of latency. They have backed up that presentation with a blog, technical paper (PDF) and the source code itself.

Recently, Martin Fowler published an excellent paper on the LMAX architecture and mentions that they are now able to handle six million orders per second and highlights a few of the steps that the team took to go up another order of magnitude in performance.

So far I've explained that the key to the speed of the Business Logic
Processor is doing everything sequentially, in-memory. Just doing this (and
nothing really stupid) allows developers to write code that can process 10K TPS.

They then found that concentrating on the simple elements of good code could
bring this up into the 100K TPS range. This just needs well-factored code and
small methods - essentially this allows Hotspot to do a better job of
optimizing and for CPUs to be more efficient in caching the code as it's
running.

It took a bit more cleverness to go up another order of magnitude. There are
several things that the LMAX team found helpful to get there. One was to write
custom implementations of the Java collections that were designed to be
cache-friendly and careful with garbage.

Another technique to reach that top level of performance is putting attention
into performance testing. I've long noticed that people talk a lot about
techniques to improve performance, but the one thing that really makes a
difference is to test it

Fowler mentioned that there are several things that were found, but he only mentioned a couple.

Are there other architectures, libraries, techniques or "things" that are helpful to reach such levels of performance?


答:
Well the way you describe it sounds to me like developers are rather trying to help you get them more productive.

In my experience, the border between developer and external testing is quite fuzzy and flexible and much depends on a concrete project details. I for one have been working in projects with dev:tester ratio varying from 10:1 to 1:2 and all of them went well and fine. The only one that sucked was where there were no testers at all - and it sucked really bad. :)

That border I mention above gets even fuzzier if you take into account that there might (maybe even should) be close collaboration between developers and testers. Eg, developers might contribute quite a lot into product testability while testers contributing into getting specs and design right at the early stages.

It's hard to tell beforehand what amount of testing would be most productive to "offload" to external party in your case, but your note about ...testing the code against the specs, eg. when you click on 'submit' the index page should load... makes me feel like your team can gain some significant performance boost if you wisely hire one or two professional testers or QA consultants. If you get these guys right, you'll not only get immediate gain but also will get someone to help you tune the right dev:testers balance in your team.

By the way, before diving deeper into these tricky matters I would recommend you to do some preliminary study. For that, you can eg simply study job descriptions in vacancies from successful software companies (there's plenty available in the web). Find out which are core competencies considered for testers and which are ones typically expected from developers, try to "sense" the differences and similarities. This study may help you make more informed decisions further down the road.

PS. developers are rather trying to help you get them more productive -- for the sake of completeness have to note their argumentation does not look very compelling. The bias they refer to is a real and serious issue but I think it can also be addressed without involving third party - eg by making them cross-test each other. In my experience this trick helped to tame bias to tolerable levels (though have to admit it pales in comparison to "surgical" objective analysis done by qualified professional tester). I believe that most critical issues solved by employing third party testers are more related to matters of professional focus and productivity, division of labour... stuff like that.

OwnerDisplayName: bobbyz

Title: Functional testing must be done by external party to avoid bias?

Body:
Our developers demand that someone external to the development team completes the functional testing. Their argument is that they are biased and cannot test their own code as they are too close to it. Our last round of testing is with the client in the form of UAT.

To be clear by 'functional testing' I mean testing the code against the specs, eg. when you click on 'submit' the index page should load. By UAT I mean the client comes in and runs through use cases on the release candidate.

While I understand this argument of bias, is it reasonable for the developers to demand someone else complete their functional testing or is this just a way to avoid doing their job?


问:
Is there a license where all rights are granted?
The licenses I know, including open source and the less restrictive ones like BSD, make it mandatory to:

Retain the copyright notice, and/or:

Indicate that the precise part of source code was written by the original author.

Let's say I want to share source code I've written and I want to grant all rights, including the right to:

Remove the copyright notice or substitute another one,

Sell the source code or use it in a commercial product with no restrictions,

Never indicate that this source code was written by me¹,

but at the same time disclaim any warranty as it is the case in BSD license.

Are there licenses which match this case?

Note: public domain is not a solution, since the term is unclear and change from one country to another.

¹ Why would anyone do that? Because we all have pieces of code which are not worth real licensing, but still useful for the community (example: removing diacritics from a text). Providing it "completely free" is in this case much for friendly that saying that in order to use your code, the person must read a few paragraphs or pages of an UNREADABLE ALL CAPITAL text, understand it, accept it, and then copy-paste your name and copyright notice every time the code is used.

答:
What you want is not possible because your requirements conflict. If someone can remove your copyright notice, how can you disclaim any warranty? Someone could just remove your disclaimer and then distribute the code to someone else who could argue that they had no idea there was no warranty.

The closest to what you want to do, in the United States, is to put a notice stating that you disclaim all warranties and place the work in the public domain. Placing the work in the public domain should sever your legal connection to the code.


问:
Need to make a stock inventory application
I need to make an application for my dad to keep track of stock trading inventory. He trades shares for himself and for his clients and would like to keep the records, things like buy/sell price of shares, profits, loss, date etc etc for his shares and his client shares and would like various kind of reports/views.

He uses windows. I want to provide a local html page where he will enter new information and this should go to a local database and from his html page, he can choose reports etc and the reports will be displayed on the webpage etc..

I am thinking of using struts (and windows,tomcat) and mysql to make this application. I know some stuff from college days, but would look into the tutorials to setup things and program.

Does this selection of technology looks good enough or something more easier and equally good exist?

update:

This is what I have settled for: Used mysql/windows, navicat lite and populated database/tables, and wrote some procedures taking some inputs. Like one procedure takes date and stock name as input and gives you quantity you have of that stock by that date and profit/loss so far, effective buy price of each share of that stock. This is for individual basis usage..and it looks like this will suffice for now -- very very simple, but I could custom create tables,custom create queries/procedures..Dad gets "contract notes" from his broker containing his daily transactions and I could get these notes online, compile these of last 2-3 years into one table and so the thing is in working state..very primitive, but works for his requirements for now.
and yes, made 2 accounts (one read-only priviledge account using which he will run his queries,procedures etc) and other root, which he will use when populating his tables say once or twice in 15 days.

答: I would imagine that there are off-the-shelf applications that already do this.  Personally, I'd rather spend some cash to get something that I know has been thoroughly tested than spend hours and hours developing one myself.</p>


问:
Is learning C# as a first language a mistake?
I know there are similar questions on here, which I've read, but I recently read this post by Joel Spolsky:

How can I teach a bright person, with no programming experience, how to program?

And it got me thinking about my way of learning and whether it might actually be harmful in the long run.

I've dabbled with various languages but C# is my first serious one, I've read "Head First C#" and created a few projects. But after reading the post above I've found it a bit disheartening that I may be going about it all wrong, obviously I respect Joel's opinion which is what has thrown me a bit.

I've started reading "Code" as recommended in the reading list and I'm finding it pretty hard going, although enjoyable. I feel like it's taken the shine off of my "noobish hacking about" in Visual Studio.

So now I'm unsure as to what path I should take? Should I take a step back and follow Joel's advice and start reading?

I guess my main aim is just to become a good programmer, like everyone else, but I don't want to be going into bad practice by learning a .NET language when someone who's opinion I respect thinks that it is harmful.

Thoughts?

答: The biggest downside that I can see is that Visual Studio and the associated tools are very, very nice -- things like intellisense and code completion can easily become crutches. I'd generally argue that the environment can be so nice and supportive that you tend to feel a bit lost when you need to, say, go hack ruby code in a text editor. Oh, and you'll usually miss stuff like linq too.</p>


问:
What can multiple threads do that a single thread cannot?
While threads can speed up execution of code, are they actually needed? Can every piece of code be done using a single thread or is there something that exists that can only be accomplished by using multiple threads?</p>

答:
First, threads can do two or more things at the same time (if you have more than one core). While you can also do this with multiple processes, some tasks just don't distribute over multiple processes very well.

Also, some tasks have spaces in them that you can't easily avoid. For example, it's hard to read data from a file on disk and also have your process do something else at the same time. If your task necessarily requires lots of reading data from the disk, your process will spend a lot of time waiting for the disk no matter what you do.

Second, threads can allow you to avoid having to optimize large amounts of your code that's not performance-critical. If you only have a single thread, every piece of code is performance critical. If it blocks, you are sunk -- no tasks that would be done by that process can make forward progress. With threads, a block will only affect that thread and other threads can come along and work on tasks that need to be done by that process.

A good example is infrequently-executed error handling code. Say a task encounters a very infrequent error and the code to handle that error needs to page into memory. If the disk is busy, and the process has only a single thread, no forward progress can be made until the code to handle that error can be loaded into memory. This can cause bursty response.

Another example is if you might very rarely have to do a database lookup. If you wait for the database to reply, your code will hit a huge delay. But you don't want to go to the trouble of making all this code asynchronous because it's so rare that you need to do these lookups. With a thread to do this work, you get the best of both worlds. A thread to do this work makes it non performance critical as it should be.


问:
What are the best practices regarding unsigned ints?
I use unsigned ints everywhere, and I'm not sure if I should.  This can be from database primary key id columns to counters, etc.  If a number should never be negative, then I will always used an unsigned int.

However I notice from other's code that no one else seems to do this.  Is there something crucial that I'm overlooking?

Edit: Since this question I've also noticed that in C, returning negative values for errors is commonplace rather than throwing exceptions as in C++.

答: Mixing signed and unsigned types can get you into a world of pain. And you can't use all unsigned types because you will encounter things that either have a valid range that includes negative numbers or need a value to indicate an error and -1 is most natural. So the net result is that many programmers use all signed integers types.</p>


问:
solve TOR edge node problem by using .onion proxy?
I would like to improve the TOR network, where the exit nodes are a vulnerability to concealing traffic. From my understanding, traffic to .onion sites are not decrypted by exit nodes, so therefore - in theory - a .onion site web proxy could be used to further anonymize traffic.

Yes/no? perhaps you have insight into the coding and routing behind these concepts to elaborate on why this is a good/not good idea.

答: It would make no difference. The proxy would just serve the same purpose as the exit node, still sending out the decrypted data. All it would do is allow you to choose your exit node.</p>


答: One thing to keep in mind, especially as a manager: testers typically command somewhat lower salaries than developers. So on top of the bias argument, there are also economic benefits in hiring dedicated testers if there is enough testing to be done to occupy at least one person full-time.</p>


问:
What would motivate you to do free programming work for work after work?
I'm not talking about working overtime for a project, but R&D, or test bed applications that benefit the company. These would become teaching tools, and eventually sales tools. I know it sounds crazy to even ask, but I'm seeing a trend in this industry with regard to rapidly changing technology, and a problem with getting programmers to bring the after hours knowledge gained in house. You would think it would spill over naturally, but I find most leads holding back because the work would then be "managed" by the company, and now the property of the company. Are there solid programs or initiatives that stimulate a back-and-forth, where you can actually bring something to the table and be rewarded for it?

EDIT

Can anyone provide additional feedback on this:

Are there solid programs or initiatives that stimulate a back-and-forth, where you can actually bring something to the table and be rewarded for it?

There appears to be a miscommunication here, where some users are under the impression I'm trying to figure out how to get free work out of colleagues. Just the opposite is true. I want to know if there are programs that exist, or ideas that you have that would motivate you, which doesn't necessarily have to be money.

答:
Many developers (perhaps, younger developers) are motivated by "fame" and recognition of their peers at least as much as by monetary compensation.

For example, while the '20%' projects done by developers at Google are, in the end, owned by the company, if the project spins off and becomes successful (like GMail), the individual developer who worked on that project gains some fame and recognition in the dev community; which brings a feeling of being respected by your peers.

If the company can keep the recognition spotlight on the developer even after the project has shipped, it would go a long way toward getting the company's and developers' motivations to align.


问:
Do you write unit testing or TDD as a line item requirement into your contracts or statements of work?
If you do, do you discuss coverage, continuous integration, quality control, or anything related to the difference between unit testing, functional testing and TDD in general? If clients ask, do you simply state that you will unit test, but leave out specifics?</p>

答:
Not as such, but we have a specified level of decision coverage and function coverage as the final acceptance criteria for our software, so we use unit tests to achieve this.

So we've made writing unit tests to achieve this level of coverage part of our definition of done. We're not doing TDD.


答:
IMO,unit testing is akin to an implementation detail. They are hidden, yet quite an unwritten expectation.

TDD would fall into this category as well since, again, it is really a process of software development. The contract defines expectations, not a process.

If a summary of time is expected, these should generally fall into categories of Design and Testing.

Title: Do you write unit testing or TDD as a line item requirement into your contracts or statements of work?

Body: If you do, do you discuss coverage, continuous integration, quality control, or anything related to the difference between unit testing, functional testing and TDD in general? If clients ask, do you simply state that you will unit test, but leave out specifics?</p>


答:
If you ask about motivation, let's consider the three most important ingredients, and then see if a company can give you any one of them...

first, you've got to be a passionate programmer -- without that nothing works. One must revel in programming -- even the very thought of converting a real world problem into computer instructions should excite you. How many programmers REALLY take pleasure in doing company's work, and how many of them would do it without pay for a single day?

second, you need to have a good idea -- and thinking about it should rev up the adrenalin in your brain for going after it. How many employees REALLY think about giving the company more value by giving it their valuable ideas?

third, and MOST IMPORTANTLY you need belief -- that putting time & brain into your idea would bring pleasure, satisfaction, and (some day) money to you. If you have THAT belief, would you REALLY let the company take share in it?

All I am trying to suggest is that there are VERY FEW people that absolutely LOVE the company they work for. And that's the reason nobody readily shares their "after hours knowledge" or ideas with the company. No matter how much you're rewarded, the moment you have all the above three -- you'll want to make it all your own and be the next Mark Zuckerberg or Sergey Brin.

The problem is that the source of passion, ideas and true beliefs doesn't really correspond with the "corporate evilness" of companies. (although it's completely a different matter that even those passionate ideators and believers oftentimes end up creating those corporations)

Are there solid programs or initiatives that stimulate...

It's really hard to get employees who give their "hearts" to the company. And that's why companies generally don't try to "stimulate" them that way. At least that's what my experience has been.

Title: What would motivate you to do free programming work for work after work?

Body:
I'm not talking about working overtime for a project, but R&D, or test bed applications that benefit the company. These would become teaching tools, and eventually sales tools. I know it sounds crazy to even ask, but I'm seeing a trend in this industry with regard to rapidly changing technology, and a problem with getting programmers to bring the after hours knowledge gained in house. You would think it would spill over naturally, but I find most leads holding back because the work would then be "managed" by the company, and now the property of the company. Are there solid programs or initiatives that stimulate a back-and-forth, where you can actually bring something to the table and be rewarded for it?

EDIT

Can anyone provide additional feedback on this:

Are there solid programs or initiatives that stimulate a back-and-forth, where you can actually bring something to the table and be rewarded for it?

There appears to be a miscommunication here, where some users are under the impression I'm trying to figure out how to get free work out of colleagues. Just the opposite is true. I want to know if there are programs that exist, or ideas that you have that would motivate you, which doesn't necessarily have to be money.


答:
and a problem with getting programmers to bring the after hours
  knowledge gained in house.

The problem is that you're not paying them to do that.

You would think it would spill over naturally,

No I wouldn't, free time is free time. If somebody chooses to spend their free time studying instead of going kite surfing or whatever, then of course they should be the ones to benefit from what they did during their free time. Why should you? What have you contributed to that time and effort that they put in?

but I find most leads holding back because the work would then be "managed" by the company, and now the property of the company.

Yup

Here's the thing, if you find value in the things that programmers do while not working for you, then why don't you have them working on those things during work hours.

Google understands this and that's why they have 20% time. But it's too easy to mess this up by trying to keep control over what employees work on during this time. A smart developer knows many things you could be doing to improve your business if only they are given a chance. Sure you now have one day a week less but after some time you will find that the work on the fifth day makes the work on the next four days a lot more productive and effective. It also makes smart devs love working for you as they no longer have to deal with bad decisions that affect their every day work, they can actually do something to positively change the situation.

If you want benefit from free time the only way you will get it is if the devs really, really like you and the company they work for.


问:
What do you do to make the client understand that requirements not mentioned in contract should be charged separately?
I've done a very small project for a specified amount of payment. The project was some client-side validation code. However, now client asks for code improvement (general code improvement including server-side, not mine which was purely jQuery and client-side) and says that these requirements are obvious duties of developers. What should I do? He doesn't pay till I do something for performance tuning, while we agreed on client-side validation only.

Should I forget about my money? Or maybe I should do the second requirement without expecting any return?

答:
As per usual, I am not a lawyer. However, if it was not specified in the original contract, then that's not what he agreed to pay for. He should pay you and then consider paying extra for the additional work. Performance tuning is an obvious duty of a developer- and paying them is an obvious duty of their employer. Of course, I do think that if you delivered code that it should work reasonably, but there's a line between fast enough and not fast enough which can only be derived from context and field-specific knowledge.

If your code isn't unusuable because of performance issues, then he has no right to hold payment over you.


答:
This is one of the problems with this kind of contract. The client can always insist that certain things were "obvious from the requirements". And the developer can always create horribly broken code that "meets the requirements'. I'd suggest you try to reach a reasonable agreement -- maybe do the additional work at a much lower fee than usual. That way you both "win" and maintain a good working relationship.

Don't let a client walk all over you though. You'll resent them. They won't respect you.

Title: What do you do to make the client understand that requirements not mentioned in contract should be charged separately?

Body:
I've done a very small project for a specified amount of payment. The project was some client-side validation code. However, now client asks for code improvement (general code improvement including server-side, not mine which was purely jQuery and client-side) and says that these requirements are obvious duties of developers. What should I do? He doesn't pay till I do something for performance tuning, while we agreed on client-side validation only.

Should I forget about my money? Or maybe I should do the second requirement without expecting any return?


答:
This would depend on your local laws and details about the contract. And of course other details about your relation to this customer.

If I understand this right, your contract was about client side code (was this mentioned in the contract?)

I have seen such customers before and since you don't want to do any business with them ever again, because this types will act like this again, you can simply tell them that they either pay or hear from your lawyer. Sometimes this works (I know of cases where it did). If it's actually worth the effort to have a lawyer handle this may depend on too many details. Here in Germany this mostly has a very positive effect on the customers decisions regarding payment.

Edit

Ok, this above was mainly in case you have no close relations to the customer and have given up on him more or less anyway.

Of course having a clear contract that describes the kind of work and payment to be received as exact as possible is something you should have. This is, as you say, not always possible for many reasons. So, if you can't have a firm contract, you must act firm. As David says, otherwise they won't respect you.

You can stay friendly and at the same time make your point, that you can't be expected to work for free.

Real world example (names changed of course)

Some unimportant meeting with customers project manager about the actual state of the project (refactoring a large website from another company they had messed up full scale, lots of debug work).

She (project manager): Oh, and do you think it is possible to add a CMS for those sites.

Me: Sure, we could add an editor in the admin interface and move the text into the database, maybe add some option to upload images and so on.

Three weeks later, meeting at customers office, discussion about state of project (online by now, no bugs, customers of customer very happy) and next steps:

She: Oh, and didn't you want to add a CMS?

Me (hard time not to laugh): Look Claire, we talked about if it is possible to add this feature. If whenever we talk about something being possible and I say that it is, that means I agree to do it without payment, then in future talking will become very, very complicated, because we will need to add a lot of extra clauses to every single sentence.

This made that point quite clear without becoming unfriendly. You have to go through such situations once in a while and learn how to handle them. You must understand, that often enough this is like a chess game for some people, they make their move to get a bit more. Especially if it's the manager type. If you counter that move they mostly don't try again. Those guys are not necessarily serious about this stuff, they often know well enough that they are in a weak position. They only try, because sometimes it works.


答:
Don't do it, it will set a precedent that you will never shake with this client.

Would you expect the people changing your tires to also then change your oil for free when you go and pick up your car, it was obviously a mechanical thing that needed to be done and they are mechanics right?

How about your dentist, you got your teeth cleans, why didn't they go ahead and do a whitening for free, it is obvious that it needed to be done.

Putting it in another context with them, maybe in the context of their business, would they don work for free to fix some one else's work?

NEVER WORK FOR FREE it hurts you, it hurts your peers and it hurts the industry!


问:
What to say when you don’t know the answer to an interview question?
When you have no clue about the question, how do you answer/act when you do not know the answer at all? Telling the truth is pretty obvious. But how could you try to transform this weakness into a strength?</p>

答:
if you don't know anything about it, the best thing is to be transparent and admit that. this way you don't waste anyone's time.

but, you better know a little something about everything: and introduction or what's it about or at least the domain to what that question/technology belongs to or what's the reasoning behind the existence of that technology.

show the interviewer you know the world around you.

on the other hand, if you do know a little bit, start from there.

most interviewers will help you, and even provide and explain the answer. this is where it's important to not just play dead. ask questions and try to understand what he/she's saying. make sure you leave that interview with something new.

some people do care about your ability to understand things and about your attitude towards new stuff

ContentLicense: CC BY-SA 2.5


答:
I would suggest either blackmail or threats of violence against them and their families.  Perhaps a horses head in their bed.

Honestly, I've done plenty of uncompensated work -- either because I've felt that I messed up and should fix the problem or because I wanted to learn something and work-related software seemed like the best place to do that (although most of this sort of work hasn't been put in production).  In either case if my employer had said I HAD to do the work unpaid I would have said no.

If you're wanting people to do work for you, they are entitled to be paid for it.  If they have an idea not related to what you're paying them for, you're no more entitled to it than your competiors are (although frankly most of them won't).  This halfway sounds like you don't want to pay for training and halfway like you think that because they work for you, everything they do should be for your benefit


问:
Domain-Driven-Design - external dependencies in the Entity problem
I'd like to start Domain-Driven-Design, but there are several problems I'd like to solve before starting :)

Let's imagine I have a Groups and Users and when user wants to join a group, I'm calling groupsService.AddUserToGroup(group, user) method. In DDD I should do group.JoinUser(user), which looks pretty good.

The problem appears if I there are some validation rules for adding a user, or some external tasks need to be started when user is added to the group. Having these tasks will lead to the entity having external dependencies.

An example could be - a restriction that user can only participate in 3 groups max. This will require DB-calls from inside group.JoinUser method to validate this.

But the fact that an Entity depends on some external services/classes doesn't seem so good and "natural" to me.

What's the proper way to deal with this in DDD?

答:
Let's imagine I have a Groups and Users and when user wants to join a
  group, I'm calling groupsService.AddUserToGroup(group, user) method.
  In DDD I should do group.JoinUser(user), which looks pretty good.

But DDD also encourages you to use (stateless) services to perform tasks, if the task at hand is too complex or would not fit into an entity model. It's ok to have services in the domain layer. But the services in the domain layer should only include business logic. External tasks and application logic (like sending an email) on the other hand, should use the domain service in the application layer, in which you could have a separate (application-)service wrapping it for example.

The problem appears if I there are some validation rules for adding a
  user ...

The validation rules do belong to the domain model! They should be encapsulated inside the domain objects (entities etc.).

... or some external tasks need to be started when user is added to
  the group. Having these tasks will lead to the entity having external
  dependencies.

While I don't know what kind of external task you're talking about, I assume it's something like sending an email etc. But this is not really part of your domain model. It should live in the application layer and be hanlded there imho. You can have a service in your application layer which operates on domain services and entities to perform those tasks.

But the fact that an Entity depends on some external services/classes
  doesn't seem so good and "natural" to me.

It is unnatural and shouldn't be happening. The entity should not know about stuff which is not its responsibility. Services should be used to orchestrate entity interactions.

What's the proper way to deal with this in DDD?

In your case, the relationship should probably be bidirectional. Whether the user joins the group or the group takes the user depends on your domain. Does the user join the group? Or is the user added to a group? How does it work in your domain?

Anyway, you have a bidirectional relationship and can thus determine the amount of groups the user already belongs to within the user-aggregate. Whether you pass the user to the group or the group to the user is technically trivial once you have determined the responsible class.

The validation should then be performed by the entity. The whole thing is called from a service of the application layer which also can do technical stuff, like sending emails etc.

However, if the validation logic is really complex, a domain service might be a better solution. In that case, encapsulate the business rules in there and then call it from your application layer.


问:
How to solve an event-queue problem in a computer emulator in Java
I'm writing a low-level emulator (in Java) of the IBM 1620, a late-50s computer.  By "low level," I mean that the lowest observable unit of work is the 20-microsecond "trigger" -- machine instructions achieve their objectives by running a series of these triggers; and I've written code to emulate almost all of them.  By "observable" I mean that the 1620's console contained a "Single Cycle Execution" key which allowed you to manually advance one trigger at a time - and most of the CPU's inner state (registers, PC, conditions) were displayed on a large console of lights.  I am guaranteeing correctness of the state at the single-cycle level.

Normally the emulator is either waiting for the operator to press START, or it's in its main run loop, executing trigger after trigger.  It also needs to be able to respond to external events like a thrown toggle switch, or the afore-mentioned Single Cycle Execution key, which are conveyed to the CPU Thread from the GUI thread by an event queue.  The run loop peeks at this queue before firing off the next trigger, and so far this has worked fine.

Now, however, I'm implementing the card-reader I/O instructions, and I have a problem.  All 1620 I/O was synchronous (the 1620 did not have interrupt capability), so when it executed the ReadCard instruction, it would literally wait in mid-trigger until the card reader delivered a card.  This normally took a tenth of a second, unless the operator had not mounted the card deck!  It's that latter contingency that creates the problem: the 1620 must wait in mid-trigger (i.e. the main run loop is not running), while remaining responsive to external events (thrown switches, the Reset key, or, of course, a card from the card reader).

I can't seem to think of a clean, elegant way to design this.  Polling for, and handling, "unrequested" events at the top of the run loop has worked well so far, but now I need a callable mechanism that does the same thing but is able to return control to its caller when the right event occurs.  Here's what it looks like right now:

```<code>state:
    MANUAL means unable to immediately process next trigger
    AUTO means we can go ahead and process next trigger

do forever {
    processQueuedEvents()  // event-processing never blocks
    if (state == MANUAL) {
       waitForEvents()     // this blocks until queue not empty
    } else {               // state == AUTO
       trigger = doTrigger(trigger) // run trigger and get next one
    }
}
</code>```

CPU trigger E30 sends a message to CardReader requesting a card buffer, and must wait to receive the event containing the buffer.  In the meantime, the CPU must continue to receive and process events as usual.

I could imagine this to be an operating-system design problem, but that's not my strong suit.  Can anyone provide some guidance?

答: Have the 'trigger' function return if it cannot make further forward progress. Then go back to waiting for events and what not. As soon as something changes, see if the 'trigger' function can make further forward progress. Don't block in the 'trigger' function, block in your 'wait for anything to happen' function.</p>


答:
The StackExchange software appears not to like messages that begin with a salutation. I'm sure it's trying to be helpful, but it confused the heck out of me just now. Following is the approach that I'd take: Stay positive, but stand your ground.

Dear customer:

I'm thrilled that you like my work enough to ask me to do more for you, and I look forward to continuing a mutually beneficial relationship. I hope you'll understand, however, that I arrived at our agreed upon price by estimating the time it would take me to implement the things that you specifically asked for.

I understand that you feel that it's "obvious" that I should provide performance tuning for your server-side code, but I hope you'll try to see the situation from my perspective. Had I included in my estimate work not explicitly required by our agreement, you could rightly accuse me of padding my estimate with tasks that you never asked me to perform. Worse, had I made unrequested changes to a part of your system that was written by someone else, I'd open myself up to blame for problems created by the original authors.

I'm confident that I can provide the performance tuning that you desire, and I'll be happy to meet with you to discuss the work that needs to be done following payment in full of the current invoice.

Sincerely,

...


答:
A (large) stake in the company. I'm not talking a few shares here and there, more like 5% or more(depending on the size of the company, of course).

(True) Ownership of my project. I.E. I build it in my off time, and the company licenses it from me. I guess this one is not so free ;)


答:
When programming at work place, specification, goals, schedules and licences come from someone else than you. Often even the ideas. On free time you can do whatever you want, with whatever schedule, and even if you never finish, it's not an issue. And you can contribute to common knowledge of the humankind, by releasing your ideas and work for everyone to see.

Personally I know very, very few really good programmers who don't have passion for solving problems by programming. You can be competent without passion, and passion not always manifests in spare time coding, but programming is very skill- and brain-intensive art, so people who lack passion don't usually have the inherent motivation on being better that keeps some programmers better than others. There are exceptions to this rule, but they are far and wide between.

So, if you employ programmers and find they code on their spare time, it means you've done a good hiring decision; these are the people who will shine in the long run.

And if you employ programmers and try to trick them for working for free, you pretty much drive away the ones who have better options for workplace. If people work without pay, they do it because they love their job, not because they hate it.


问:
What features contributed to the evolution of Pascal?
I am compiling a detailed history of the Pascal language, and there are a few details I am missing.

There are so many features today that we take for granted. What features significantly contributed to the evolution of Pascal, and why were they significant?

I'm looking for language features, not platform or framework features. So like operator overloading or default parameters, but not Linux support or new Rich Text widget.

I know there are a few different flavors of Pascal (Delphi, Free Pascal, Oxygene, Quick Pascal, Apple Pascal, etc.) and they introduced the same features at different times and in parallel. That is OK. I'm looking at the Pascal language as whole, and when the significant milestones occurred (dates, versions, etc.)

答:
The fight between many flavours of Pascal in the 80s and early 90s.

You had Apple Pascal, Microsoft Pascal and QuickPascal, and Turbo Pascal.

All introduced Object Pascal in one way or the other (QuickPascal 1.0 and Turbo Pascal 5.5 around the same time frame). Apple because they required it for their platform, Microsoft and Borland because OO was becoming 'cool' (then QuickPascal died soon after, and Turbo Pascal 6.0 added a reasonable OO framework called Turbo Vision).

Rudy Velthuis is quite complete on this in his forum posting.

You can download an ISO image with DOS 6.22 and a few of the DOS Pascal compilers from that era.


答: An opportunity to work with a really good programmer(s) on a project in an area I wanted to learn. Imagine being at Sony and hearing about a side project going on for a gaming device. Even if you didn't think it would be a hit, the idea has to be very interesting.</p>


问:
Is SQL important if I know ORM frameworks well?
I don't have any serious experience in SQL and I even hate to write SQL instead of LINQ. I am happy enough with ORMs.

From the employers and sector view point, is it important to know SQL? Do I have to master on it? Are companies that prefer pure SQL over ORM frameworks a "dinosaur" in the programming world?

答: Absolutely! SQL is still the lingua franca of databases and although you may do a lot with ORMs you have to understand SQL to understand the decisions ORMs make and the SQL they generate. Also, there are still lots of things that you have to do with custom sql and stored procedures as well. Sorry, no free lunch.</p>


答: If all you're ever required to do is interact with the database only though the application you are building, you probably don't need it. At some smaller companies or developer teams, you may have to do some support. It's a lot easier to connect to a client's database and run a few sql statements to see what is going on with their data. </p>

Title: Is SQL important if I know ORM frameworks well?

Body:
I don't have any serious experience in SQL and I even hate to write SQL instead of LINQ. I am happy enough with ORMs.

From the employers and sector view point, is it important to know SQL? Do I have to master on it? Are companies that prefer pure SQL over ORM frameworks a "dinosaur" in the programming world?


答:
SQL skill is a must have skill in IT today.
LINQ is a Microsoft Only technology.
SQL usages go beyond web and client/server application development.
You can't model databases and do ETL if you are not good with SQL.
You may not need to master SQL dialects used in ORACLE and SQL Server for their Data Warehous products, but you should know standard SQL.
SQL basics are simple, there are tons of material to get you started.</p>


答: Yes, you still need to know SQL.  ORMs are a very leaky abstraction, and do not provide access to the full power of SQL.  For toy applications you may be ok with limited SQL knowledge.  For enterprise applications, you will have to understand the database to get decent performance from the ORM.  Also there are a great many tasks that are much more easily accomplished with SQL than with an application language.  I have seen Java programmers spend days writing code to do something that could have been coded in SQL in an hour.  SQL knowledge is very valuable to anyone writing applications that use a relational database.


答:
This is hard to explain to a lot of programmers, because if you only know basic SQL then it really doesn't give you much of an advantage over the crutch of an ORM.  The more advanced SQL concepts, however, are a crucial part of the difference between applications that just work vs. applications that are high quality (in particular, fast and reliable).

I'm assuming somebody else designs the databases for you, because doing that without knowing any SQL is just beyond the pale.  But even if you're only developing against them, here is just a partial list of all the things that ORMs still tend to do poorly or not at all:

Recursive and/or hierarchy queries

Optional parameters (particularly translating them into range predicates)

User-defined data types

Platform-specific types (SQL hierarchyid and TVPs, Oracle arrays and nested tables, etc.)

Batch inserts/updates/upserts/deletes

Index hints

Lock hints (especially update locks and dirty reads)

Error handling

Outer joins - their result sets map poorly to the OOP model, many ORMs have their own query language but that is similar to knowing SQL itself;

Modularization through stored procedure and UDFs, especially inline UDFs and CROSS APPLY queries

Use of OUTPUT/RETURNING for staging data into multiple tables

Efficient paging queries

Queries based on windowing functions (rownum, rank, partitions)

The list goes on and on - a lot of these are things that a novice DBA has never had to do, and a novice developer has never even heard of - but they are very important in larger-scale apps.

ORMs are really great at speeding up the really boring SQL code - that is, all the repetitive CRUD and mapping and other plumbing code, so there is absolutely no shame in using them and don't listen to anybody who says they're evil.  But you definitely still need to learn and yes, even master SQL, and be prepared to drop down into raw DB commands/queries when the ORM isn't pulling its weight.


问:
Under what conditions is the use of MVVM appropriate?
Model View View-Model was developed by Microsoft to target UI development platforms which support event-driven programming, specifically Windows Presentation Foundation (WPF) and Silverlight on the .NET platforms using XAML and .NET languages.  In the years since, many Javascript frameworks such as Angular, Knockout and ExtJS have adopted the pattern.

Like most software patterns, MVVM has its appropriate uses, and its abuses.  Under what conditions is the use of MVVM appropriate?  When is it ill-advised?

答:
I really like MVVM and I find its challenges motivating and see the many benefits, but...

For application or games that require a lot of UI/interaction code to add a lot of custom behaviors while keeping perf up - it is often better to use a bit dirty MVVM - use it when it is useful or in more data centric as opposed to interaction centric areas of the code. Say you want to create a control and move it between different parent controls or otherwise cache it...

It has a pretty steep learning curve, so unless you have time, plan to develop a lot in WPF/SL, have designers skilled in Blend, feel the need to write test code for your UI or otherwise expect to do years of maintenance for your project - it might not pay off.

Not so many designers know Blend, not all project are worth focusing the automated testing on the presentation layer, since it needs to be tested manually anyway and that is how you'll find most important bugs, not by testing your VMs.

It really is an investment. You have to get a grasp of the basics of WPF/SL and XAML first, then figure out the ways to do the bindings right, hook up vs to vms in some order, get your commanding right, pick a framework in most cases which could be problematic due to licensing, build a sippets library to code efficiently, only to find that the platform does not always work well with bindings and needing to build up a library of behaviors that get you what you need.

Overall though - if you overcome all the hurdles and become fairly profficient in the pattern - it all pays back in clarity, maintainability and ... Bragging rights? :)


答:
The issue with the edges is not that they can trace it back to you. That is very difficult. The issue is that they can sniff your web traffic and gather thing such as plaintext http passwords, email logins, websites visited and other juicy bits of information.

So it does nothing because the tor network is already set up to be a anonymous proxy service.

Title: solve TOR edge node problem by using .onion proxy?

Body:
I would like to improve the TOR network, where the exit nodes are a vulnerability to concealing traffic. From my understanding, traffic to .onion sites are not decrypted by exit nodes, so therefore - in theory - a .onion site web proxy could be used to further anonymize traffic.

Yes/no? perhaps you have insight into the coding and routing behind these concepts to elaborate on why this is a good/not good idea.


问:
How do you unit test private methods?
I am working on a java project. I am new to  unit testing. What is the best way to unit test private methods in java classes?</p>

答:
You generally don't unit test private methods directly. Since they are private, consider them an implementation detail. Nobody is ever going to call one of them and expect it to work a particular way.

You should instead test your public interface. If the methods that call your private methods are working as you expect, you then assume by extension that your private methods are working correctly.

Title: How do you unit test private methods?


问:
How does office bureaucracy affect code quality
I'm interested in stories where office bureaucracy has had direct effect on the final code quality result.

For example, a friend just told me that at his previous work place the version control system was so bulky that programmers were not allowed to create new "modules" (root directories in the source tree) without asking permissions from the VCS gods. The result was that programmers were unwilling to go through the extra bureaucratic step and instead of properly componentizing their services they ended up piling unrelated functionality on top of existing modules even when functionality was just remotely related to the current definition of the module or the module's name was way in the past. (not to mention renaming a module...)

I'm interested in similar stories of office, operational or any other bureaucracy that eventually, perhaps unintentionally affected software quality

答: I stopped working on some particular modules in the Project because the code reviewer was a Smart A$$</p>


答:
If you're interacting with an SQL database, you must understand the SQL that the ORM is generating.  You must understand the concepts inherent in SQL databases, and you must understand what your ORM cannot do for you.  ORMs make life easier (and yes, I think working without one qualifies you as a dinosaur in many cases), but they're tools (to abstract things you know), not crutches (to prevent you from learning). </p>

<p>If you refuse to learn SQL, then you have no business whatsoever touching SQL databases, either with or without an ORM, and you should find another type of work. </p>

Body:
If you're interacting with an SQL database, you must understand the SQL that the ORM is generating.  You must understand the concepts inherent in SQL databases, and you must understand what your ORM cannot do for you.  ORMs make life easier (and yes, I think working without one qualifies you as a dinosaur in many cases), but they're tools (to abstract things you know), not crutches (to prevent you from learning).

If you refuse to learn SQL, then you have no business whatsoever touching SQL databases, either with or without an ORM, and you should find another type of work.


答:
In general, I would avoid it. If your private method is so complex that it needs a separate unit test, it often means that it deserved its own class. This may encourage you to write it in a way which is reusable. You should then test the new class and call the public interface of it in your old class.

On the other hand, sometimes factoring out the implementation details into separate classes leads to classes with complex interfaces, lots of data passing between the old and new class, or to a design which may look good from the OOP point of view, but does not match the intuitions coming from the problem domain (e.g. splitting a pricing model into two pieces just to avoid testing private methods is not very intuitive and may lead to problems later on when maintaining/extending the code). You don't want to have "twin classes" which are always changed together.

When faced with a choice between encapsulation and testability, I'd rather go for the second. It's more important to have the correct code (i.e. produce the correct output) than a nice OOP design which doesn't work correctly, because it wasn't tested adequately. In Java, you can simply give the method "default" access and put the unit test in the same package. Unit tests are simply part of the package you're developing, and it's OK to have a dependency between the tests and the code which is being tested. It means that when you change the implementation, you may need to change your tests, but that's OK -- each change of the implementation requires re-testing the code, and if the tests need to be modified to do that, then you just do it.

In general, a class may be offering more than one interface. There is an interface for the users, and an interface for the maintainers. The second one can expose more to ensure that the code is adequately tested. It doesn't have to be a unit test on a private method -- it could be, for example, logging. Logging also "breaks encapsulation", but we still do it, because it's so useful.

Title: How do you unit test private methods?

Body: I am working on a java project. I am new to  unit testing. What is the best way to unit test private methods in java classes?</p>


问:
Why is there still case sensitivity in some programming languages?
I don't see any use for case sensitivity in a programming language, apart from obfuscating code.

Why implement this in a programming language?

Update:

It looks like someone you know made a statement on this.

答:
People pay attention to the shape of words before they actually read them. Case sensitivity keeps the shape of a symbol consistent throughout code. I also agree with those above that state that different conventions denote different types of symbols. Case sensitivity and insensitivity can both be abused. Bad programmers will always generate bad code... they will find a way.

Take language as an example. Why do we start sentences and named things with capitals... Is it also because of unix?


问:
ASP.NET vs ASP.NET MVC
I just started learning the ASP.NET MVC framework and it's very different in architecture from regular ASP.NET development. Transitioning from windows forms to WPF was nice, and seemed a way forward in technology. But, while learning ASP.NET MVC, I don't feel the same, I am unable to convince myself that MVC is better than WebForms. It just seems that they made some tweaks to the already available web framework and adopted the MVC architecture from some other language.

Is ASP.NET MVC the step ahead in development?  Should I learn and develop my future projects based on this platform and architecture? To me, it just seems like Microsoft is throwing a new architecture just along with WPF or copying Ruby on Rails. WPF seems promising and great while ASP.NET MVC just makes you crumb-some [sic]. They have removed the controls, thrown a new control system and data-packaging, and it's all together an extreme change to WebForms.

I realize that with MVC you have great freedom in the testing aspect, but I don't believe that this makes a lot of difference in small website or projects. If you ignore the value of testing, What are your takes on this?

答:
I would definitely choose ASP.NET MVC over "classic" ASP.NET if I had the opportunity.

Sure, a lot of what's in ASP.NET MVC is similar to what you'll find in Ruby on Rails (or most MVC web frameworks these days) but that's not a bad thing -- the URL routing and separation of controllers from views is actually a really nice way to work, once you get the hang of it.

And by keeping the framework in tune with how the WWW actually works, rather than trying to cram a square peg into a round hole and force a "stateful" model onto a stateless protocol (like "classic" ASP.NET did), it drops all the horrible and leaky abstractions that ASP.NET had.

Should you learn ASP.NET MVC instead of WPF? I don't know, is that even a valid choice? You certainly can't use WPF in all the places ASP.NET MVC would work (and vice versa) so I don't think you should learn one "instead of" the other...

Title: ASP.NET vs ASP.NET MVC


答:
My personal opinion is that ASP.NET MVC is the step ahead.

ASP.NET Web Forms had some advantages mainly with the fact that you were programming as in Windows Forms with an event base approach. If you programmed in Windows Forms, sure you were practically at home. You also wrote as less HTML/CSS/Javascript as possible. However, you also have several drawbacks because even if the code is behind it is still directly coupled to your display logic, ... and ViewState/PostBack ? Enough said (It was necessary but what a mess...)

I could write a very long comparison between the two here but I give you this link, it draws a much more detailed comparison than I could give here, it's great: http://coderjournal.com/2008/12/introducing-aspnet-mvc-part-2-aspnet-mvc-vs-webforms/

I'll just add that since ASP.NET MVC is decoupled from the display logic, you may use different rendering engines (Razor is great IMHO), check out Wikipedia's information on this.

Title: ASP.NET vs ASP.NET MVC

Body:
I just started learning the ASP.NET MVC framework and it's very different in architecture from regular ASP.NET development. Transitioning from windows forms to WPF was nice, and seemed a way forward in technology. But, while learning ASP.NET MVC, I don't feel the same, I am unable to convince myself that MVC is better than WebForms. It just seems that they made some tweaks to the already available web framework and adopted the MVC architecture from some other language.

Is ASP.NET MVC the step ahead in development?  Should I learn and develop my future projects based on this platform and architecture? To me, it just seems like Microsoft is throwing a new architecture just along with WPF or copying Ruby on Rails. WPF seems promising and great while ASP.NET MVC just makes you crumb-some [sic]. They have removed the controls, thrown a new control system and data-packaging, and it's all together an extreme change to WebForms.

I realize that with MVC you have great freedom in the testing aspect, but I don't believe that this makes a lot of difference in small website or projects. If you ignore the value of testing, What are your takes on this?


问:
Is learning C# as a first language a mistake?
I know there are similar questions on here, which I've read, but I recently read this post by Joel Spolsky:

How can I teach a bright person, with no programming experience, how to program?

And it got me thinking about my way of learning and whether it might actually be harmful in the long run.

I've dabbled with various languages but C# is my first serious one, I've read "Head First C#" and created a few projects. But after reading the post above I've found it a bit disheartening that I may be going about it all wrong, obviously I respect Joel's opinion which is what has thrown me a bit.

I've started reading "Code" as recommended in the reading list and I'm finding it pretty hard going, although enjoyable. I feel like it's taken the shine off of my "noobish hacking about" in Visual Studio.

So now I'm unsure as to what path I should take? Should I take a step back and follow Joel's advice and start reading?

I guess my main aim is just to become a good programmer, like everyone else, but I don't want to be going into bad practice by learning a .NET language when someone who's opinion I respect thinks that it is harmful.

Thoughts?

答:
Wow a lot of answers.   Here is my point of view:

C# is no place to learn computer science.   I see it as an exceedingly bad idea. I will list some of my concerns below.

C# is a Microsoft language.  Not that I'm judging MS here, just that outside of the MS world there is little uptake.   If you just want to program MS hardware then go ahead but I don't see this a a solid approach to computer science.

I'm not a big fan of learning to program with managed languages.  I believe their is value in learning how to manage a programs memory and the construction of data structures.

Too tired to go on so quickly choose another language.


答:
Whatever you say, you should have two things there- honesty and confidence.

That's all I think.

Title: What to say when you don’t know the answer to an interview question?

Body: When you have no clue about the question, how do you answer/act when you do not know the answer at all? Telling the truth is pretty obvious. But how could you try to transform this weakness into a strength?</p>


答:
The answer to all these types of questions ("do I need to know X?") is "learn it the first time you need it, if you'll ever need it".

It's important though to not fall into the trap of doing things less efficiently because you are not aware of or are not willing to learn the efficient way to do them.

In this particular case, for example, what do you do if you realize that there was a bug in your program that caused the PostCount field of your user table to sometimes be inaccurate.

You fix the bug and now you have to update the PostCount for all users. How do you do it?

If you write a little script using ORM to do this then you are being very inefficient; a very simple SQL query will do.

Since these situations are fairly common I fear that you fell into the trap described above!


问:
Multiple inheritance use cases
Java omits multiple inheritance on the grounds that it obviates the design goal of keeping the language simple.

I wonder if Java (with its eco-system) is really "simple". Python is not complex and has multiple inheritance. So without being too subjective, my question is...

What are the typical problem patterns that benefit from a code designed to make heavy use of multiple inheritance

答:
First: multiple copies of base class (a C++ issue) & tight coupling between base and derived classes.

Second: multiple inheritance from abstract interfaces

Title: Multiple inheritance use cases


答:
Pros :

It sometimes allow more obvious modeling of a problem than other ways to model it.

If the different parrents have orthogonal purpose, it can allow some kind of compositing

Cons :

If the different parents don't have orthogonal purpose, it makes the type difficult to understand.

It's not easy to understand how it is implemented in a language (any language).

In C++ a good example of multiple inheritance used to composite orthogonal features is when you use CRTP to, for example, setup a component system for a game.

I've started to write an example but I think a real world example is more worth looking at. Some code of Ogre3D uses multiple inheritance in a nice and very intuitive way. For example, the Mesh class inherit from both Resources and AnimationContainer. Resources expose the interface common to all resources and AnimationContainer expose the interface specific for manipulating a set of animations. They are not related, so it's easy to think about a Mesh as being a resource that in addition can conain a set of animations. Feels natural isn't it?

You can look at other examples in this library, like the way memory allocation is managed in a fined grain way by making classes inherit from variants of a CRTP class overloading new and delete.

As said, the main problems with multiple inheritance rises from mixing related concepts. It makes the language have to set complex implementations (see the way C++ allows to play with the diamond problem...) and the user not being sure what's happening in that implementation. For example, read this article explaining how it is implemented in C++.

Removing it from the language helps avoiding people who don't know how the language is inforced to make things bad. But it forces to think in a way that, sometimes, don't feel natural, even if it's edge cases, it happen more often that you might think.

Title: Multiple inheritance use cases

Body:
Java omits multiple inheritance on the grounds that it obviates the design goal of keeping the language simple.

I wonder if Java (with its eco-system) is really "simple". Python is not complex and has multiple inheritance. So without being too subjective, my question is...

What are the typical problem patterns that benefit from a code designed to make heavy use of multiple inheritance


答:
I won't delve much in here but you can surely understand the multiple inheritance in python via the following link http://docs.python.org/release/1.5.1p1/tut/multiple.html :

The only rule necessary to explain the semantics is the resolution rule used for class attribute references. This is depth-first, left-to-right. Thus, if an attribute is not found in DerivedClassName, it is searched in Base1, then (recursively) in the base classes of Base1, and only if it is not found there, it is searched in Base2, and so on.

...

It is clear that indiscriminate use of multiple inheritance is a maintenance nightmare, given the reliance in Python on conventions to avoid accidental name conflicts. A well-known problem with multiple inheritance is a class derived from two classes that happen to have a common base class. While it is easy enough to figure out what happens in this case (the instance will have a single copy of ``instance variables'' or data attributes used by the common base class), it is not clear that these semantics are in any way useful.

This is just a small paragraph but big enough to clear the doubts I guess.

Title: Multiple inheritance use cases


答:
Before I talk about the question, a little introduction first; I love ORMs. And I hate SQL. I love ORMs because they hide the user-unfriendly mess that SQL is, and provide a nice language-integrated way of dealing with the database.

However I gotta admit that SQL has a lot of benefits, with the bigger one being precision. I can pretty much argue about the complexity of an SQL query, without detailed knowledge of the underlying database schema, just by going through the query. Therefore, when I use SQL, I am always alert, and I always have an intuition about where the complexity of a component is heading.

On the other hand, when using ORMs, I'm so overwhelmed by the ease of database integration, that I literally forget there even is a database. This has screwed me multiple times. Many times in the past, I have called innocent-looking ORM methods, that behind the scenes call massive and scary database joins, that destroy performance.

That's why for me, the truth is somewhere in between. I love using ORMs, and I will continue doing so, but I gotta be more careful and always study the implications (on SQL level) of any ORM method call. Knowing the implications of an abstraction layer is pure gold in this business, and justify the use of the abstraction. Anything else, is like shooting yourself on the foot.


问:
PHP framework most similar to ASP.NET MVC3?
I've done a bit of work with CodeIgniter and a lot with straight PHP...

I had the opportunity to use asp.net mvc3 recently and was absolutely blown away with my productivity. Despite not "knowing" the framework, the combination of scaffolding + intellisense + code generation through the context menus left me feeling just as productive with asp.net as with PHP.

I've evaluated YII, CakePHP, symfony (a long time ago, pre 2.0), and Kohana... and while YII seems most promising none quite matched up to my experience with mvc3.

答: If you're talking about total experience, I think phpStorm, http://www.jetbrains.com/phpstorm/, is the best IDE out there. It adds some of the features of Visual Studio as well as some of it's own. Now in terms of PHP framework that's similar to ASP.NET MVC, I haven't felt that any of them are that close. I feel like cakePHP is the most common, so likely easiest to get help on and be able to deliver something at the end of the day. </p>


答:
Apart from games and (mainly statistical) research, which I have no experience with, it seems that database access and operations are one of the few areas where wrong decisions lead to very large performance hit. I'm a strong believer in more powerful database abstractions in code, and I believe linq, which ties the database operations to the programming language, giving you all the tools of the language (type checking, syntax checking, all the things you like about your programming language) while still giving you plenty of power to do what you want is absolutely terrific. Unfortunately, it still doesn't always work. That means, if the abstraction layer gets its optimisations wrong, and you might be waiting for seconds instead of microseconds, or minutes instead of seconds for your result. Since these are very noticeable times, you have to optimise them away, or your application doesn't "work": performance becomes the greatest problem of your application. That means you have to get closer to the metal, and hand optimise.

When we get to the point that manipulating large datasets takes for example 3 ms when doing by hand, and 100 ms when you let the abstraction layer do it for you, by all means, let the abstraction layer handle it for you, because you might be 30 times slower, but you are still (probably, for most applications) fast enough. The reality of the situation is however that when you are looking at hand optimised solutions where you have a 200 ms response time, and when the abstraction layer handles it for you, the algorithm takes 'just' a 10 times performence hit, you have a 2 second delay, and then you care a whole lot, as it goes from not all that fast, to painfully slow. Seeing that relational database solutions don't scale well, I don't think this will be solved in two or three years. This means you will still have to get down to the bare metal for quite some time when it comes to larger databases, or your application will be so slow, it can't stand up to competitors.


问:
Why applications don't have constraint-based security?
In almost any security system I've ever seen, what is controlled is that which person has access to which part.

However, in real life, in many situations, security systems also consider when and where a person is permitted to do something.

For example, you can drive fast in day, but you can't drive fast in night, or you can marry a homosexual officially in X, but you can't marry the same gender in Y.

Does constraint-based security has any meaning in the context of software. For example, a system can prevent you from entering in certain times of the day (after work for example), or another system can let you stay signed in, only if you type fast enough, or another system can let you enter data, only if you are currently located in the USA (Geolocation API), etc.

Why computer security systems don't match real life scenarios?

答:
They do this, if it is needed. I worked for a large bank once, where the id cards had access rights to different parts of different buildings and at different times. So if you wanted to work over the weekend you had to make sure, that you would be able to enter the building.

But setting up such a system requires a lot of work. Each rule must be set up and assigned to a person or a group. You only want to do this kind of work if absolutely necessary, otherwise people will ignore it and managers will grant access rights to their whole team at any time to make sure they don't have to do extra work just because somebody needs to do some extra hours or come in very early.

It just generates extra work. I was doing contract work in that bank. The ID system was smart enough that you could limit building access to the date the contract would end. So when my contract was renewed for another three months, of course they forgot to renew ID access as well, so I had to get a paper signed from my boss and walk to the security department (different building several blocks away) to get my ID card updated.

There are many other rules of this kind. For example you can watch certain videos on Youtube only from within certain countries, depending on different rules. In Germany you can't watch Youtube videos if they use background music with copyrights from the major music production companies. Google Music Beta is only available in the United States.

With each new layer of security you add complexity. Some rules are difficult to implement, like location by IP, which you can get around by using a proxy server. This increases the risk of bugs and invites laziness by users.


问:
UnitTests, will cleaning up your act-statement make your test more or less clear?
Lets say that we are testing FooClass with the following method:

```<code>    public void Foo(string stringParameter, int intParameter, Action<Bar> successCallback, Action<Exception> errorCallback);
</code>```

If the call to Foo succeeds, the successCallback will be called with the result of Foo in the form of a Bar object. If it fails, the errorCallback will be called with an Exception.

So the tests will look something like this:

```<code>[TestMethod]
public void Foo_UnderGivenConditions_WeExpectAGivenResult()
{
    //Arrange
    var fooObject = CreateFooObjectWithGivenConditions( ... );

    //Act
    fooObject.Foo(String.Empty, 0, (bar) => { ... }, (error) => { ... });

    //Assert
    Assert.AreEqual(..., ...);
}
</code>```

Now, there are a lot of tests on this Foo-method, all of them containing a call to Foo, but not every test will care for all the parameters. Some may provide different string values, but doesn't care about the int param, and some will need to provide an error callback to assert that the right exception is thrown and so on.

Now, since all the parameters are mandatory, we have to pass a string value to the Foo method, even though the value has no meaning for the test. There will be a lot of "I don't care" or "some text". When some one else comes and read the test, they have to consider if the given value actually has a meaning for the test result or not. The same goes for the callbacks. Sometimes we need the callbacks to get to the result value or the exception, but most of the time we do not.

So lets implement an extension method, PerformFoo, that defaults every parameter:

```<code>public static Bar PerformBar(this FooClass fooObject, string stringParameter = "some text", int intParameter = 0, Action<Bar> successCallback = null, Action<Exception> errorCallback = null);
{
   Bar result = null;

   var ourCallback = (bar) =>
      {
          result = bar;
          if (successCallback != null)
              sucessCallback.invoke();
      }

   fooObject.Foo(stringParameter, intParameter, ourCallback, errorCallback);

   return result;
}
</code>```

The extension method will call Foo with default parameters, and even return the result if the successCallback is called. This lets us change the Act part of the test to something like:

```<code>//Act, all we care about is the string parameter:
fooObject.PerformFoo("A string that we care about");

//Act, we need the resulting bar when the int parameter is 10:
var bar = fooObject.PerformFoo(intParameter: 10);

//Act, we still needs to provide a callback to get the exception
fooObject.PerformFoo("SomeInvalidValueCausingAnException", errorCallback: (error) => { exceptionThrown = error; });
</code>```

So the questions would be:

Does this make the tests more readable?

Is it easier to get what the test really tests?

The fact that we call PerformFoo, which doesn't really exist on the class under test make the test less worth as an documentation?

Would dropping the extension method for a regular method taking the fooObject as the first parameter be less of a 'lie'? (e.g. PerformFoo(fooObject, intParameter: 10) )

How far would you go to make your tests clean and clear?

答:
If I were doing this, I would take a look at having a base setup that acts by calling Foo().
A base class would contain the Arrange with defaults, the Act would be in the base, and the assert would have to be assumed in the child test classes.

```<code>[TestClass] //you don't need this here but the
            //compiler warns otherwise with mstest :(
public void Base_Fooey_fixture
{
   protected String StringParameter { get; set; }
   protected int IntParameter { get; set; }
   // ...
   [ClassInitialize]
   public void Arrange()
   {
     StringParameter = "Default Value";
     //...
   }
   [TestInitialize]
   public void Act()
   {
    Foo(StringParameter, IntParameter, SuccessCallback, ErrorCallback);
   }
}
[TestClass]
public class RealTest : Base_Fooey_fixture
{
   [ClassInitialize]
   public class MyArrange()
   {
     StringParameter = "My real string value";
   }

   [TestMethod]
   public void Im_gonna_assert_for_this_setup()
   {
      //...
   }
}
</code>```

Body:
If I were doing this, I would take a look at having a base setup that acts by calling Foo().
A base class would contain the Arrange with defaults, the Act would be in the base, and the assert would have to be assumed in the child test classes.

[TestClass] //you don't need this here but the
            //compiler warns otherwise with mstest :(
public void Base_Fooey_fixture
{
   protected String StringParameter { get; set; }
   protected int IntParameter { get; set; }
   // ...
   [ClassInitialize]
   public void Arrange()
   {
     StringParameter = "Default Value";
     //...
   }
   [TestInitialize]
   public void Act()
   {
    Foo(StringParameter, IntParameter, SuccessCallback, ErrorCallback);
   }
}
[TestClass]
public class RealTest : Base_Fooey_fixture
{
   [ClassInitialize]
   public class MyArrange()
   {
     StringParameter = "My real string value";
   }

   [TestMethod]
   public void Im_gonna_assert_for_this_setup()
   {
      //...
   }
}


问:
What would motivate you to do free programming work for work after work?
I'm not talking about working overtime for a project, but R&D, or test bed applications that benefit the company. These would become teaching tools, and eventually sales tools. I know it sounds crazy to even ask, but I'm seeing a trend in this industry with regard to rapidly changing technology, and a problem with getting programmers to bring the after hours knowledge gained in house. You would think it would spill over naturally, but I find most leads holding back because the work would then be "managed" by the company, and now the property of the company. Are there solid programs or initiatives that stimulate a back-and-forth, where you can actually bring something to the table and be rewarded for it?

EDIT

Can anyone provide additional feedback on this:

Are there solid programs or initiatives that stimulate a back-and-forth, where you can actually bring something to the table and be rewarded for it?

There appears to be a miscommunication here, where some users are under the impression I'm trying to figure out how to get free work out of colleagues. Just the opposite is true. I want to know if there are programs that exist, or ideas that you have that would motivate you, which doesn't necessarily have to be money.

答:
As a developer, you are paid for your time and knowledge.

If you are giving that away free of charge to your employer, then there is a small group of things that would make that worthwhile.

1) You are behind in your work, and this is required to catch up so that your reputation isn't tarnished

2) You have an ownership stake in the company.

3) You are trying to make yourself look like you are worth more than the next guy for a potential promotion or to avoid getting laid off.

Otherwise, be very careful about doing so, especially when the only reward is fame.  The half-life of fame is about 6 months, but that extra time of your own that you spent is gone forever, even if the company is still benefiting from it.

Maybe I'm just old and cynical, but I have seen a lot of people at different companies give extra of themselves all the time, thinking it would be rewarded or help their company do better, only to get laid off when there was an economic pinch.


问:
What is the biggest obstacle ASP.NET MVC ever had for you? Why and how it can be fixed?
What aspects of ASP.NET MVC can be considered bad practices of Microsoft or problematic? In ASP.NET web forms, thing like ViewState, Automatically generated Id and names, single form usage and pattern like this are many times problematic. As no claim should be reason-less, so, it's better to mention why that aspect is an obstacle. Also finding any problem intrinsically means that we like to solve it. Therefore, Please also recommend ways to solve that issue. </p>

答:
Fat controllers are the biggest obstacles that I encounter.

Rule of Thumb with MVC:

Keep your models fat and your controllers skinny.

For more background, please see this thread.


答:
I think the choice is mainly based on issues due to the diamond problem.

Moreover, it is often possible to circumvent the use of multiple inheritance by delegation or other means.

I'm not sure of the meaning of your last question. But if it is "in which cases is multiple inheritance useful?", then in all cases where you would like to have an object A having functionalities of objects B and C, basically.

Title: Multiple inheritance use cases