问:
Best practice for combining a Java Applet/ Android interface?
I'm working on an online game, which I am seriously considering writing a Java Applet for it. The game is not overly complex on the features. I'm considering at some point having at least 3 versions of the game, which include a Java stand alone, applet, and Android game. I know from Design Patterns that the best way to use differing things like buttons and the like is to use a Bridge interface, where I have a common template for the common buttons.

However, I'm having a bit of difficulty understanding what to do about the following. I know that Android programs use an Activity structure, which I am well familiar with, and that Applets extend the Applet interface, which I am not as familiar with. I also know that a stand alone java program uses basically a main() function, which doesn't have much structure. I'm convinced that there should be a way to design a common design pattern between the two, but somehow I'm missing what that is exactly. What can I do to make the different frameworks work with as much common code as possible?

答:
According to the answers to stackoverflow: recommended-ways-to-produce-app-portable-between-android-and-other-platforms the best way is

```<code> keeping UI and biz logic / model separate
</code>```

and writing seperate gui-s for android, applet, j2se, j2me.

But eaven keeping biz logic seperate is difficuilt because in the android world many api-s are based on the android Context which is the gateway to the operating system.

i have developped crossplatform biz logic for j2se and j2me for 2 projects. but i failed to do crossplatform for j2se/android because database and android-Context-api-s where to different from j2se.

Body:
According to the answers to stackoverflow: recommended-ways-to-produce-app-portable-between-android-and-other-platforms the best way is

 keeping UI and biz logic / model separate

and writing seperate gui-s for android, applet, j2se, j2me.

But eaven keeping biz logic seperate is difficuilt because in the android world many api-s are based on the android Context which is the gateway to the operating system.

i have developped crossplatform biz logic for j2se and j2me for 2 projects. but i failed to do crossplatform for j2se/android because database and android-Context-api-s where to different from j2se.


问:
One language to rule them all? (Them being platforms.)
I have been discussing a project with a client and they want to use a single language to deploy to as many platforms as possible.

(I am not sure that it's such a good idea, because each platform offers a different user experience and UI metaphor. In some cases, screen sizes vary as well. Also, iPhone is out of the running no matter what language we use. But, I digress...)

The project is going to display an arbitrary block of text each day and will track if the user has "read" it. Some other features on the table are "nags" and the ability to go to another days' text.

I know Flash from the CS3 days, and I think that translates into AIR, but I dont know if AIR can do what we want.

On the other hand, I have (a) little experience with Java or Python, but those seem like good contenders also.

Which language should I use here? Why?

Edit:

This is going to run on desktop platforms too.

答: uhm, how about haXe? You can target a lot of platforms by now and should you learn OCaml you're free to write a new backend for whatever you fancy.</p>

ContentLicense: CC BY-SA 2.5


问:
When should I use parallelism?
After asking this question, I got to realize that parallelism may not always be good.

So far I can see that parallelism (under c#) is

A little complicated code-wise

Will probably insert some concurrency complications

Will not always be faster

I am looking inside parallelism because I want to make existing and new applications work faster, but now I see that it is no silver bullet.

When should I use it? are there any best practices?
Is it just a waste of time in most cases?
Is it suitable for a specific kind of applications?

I am looking forward for your insights on this matter.

答:
While it's definitely not a silver bullet, .Net 4's Task Parallel Library can simplify some aspects of parallelising your code, once you've already made the decision to do so.

To answer your question, there certainly are differences between types of problems, in terms of how much benefit they gain from being parallelised.  Some problems are referred to as embarassingly parallel, and the definition has a lot to do with the amount of communication necessary between the tasks.

Although I am sure you could come up with a set of guidelines for the types of tasks that benefit greatly from parallelisation in general (e.g. see linkerro's answer for some), you can also simply analyse the problem and make a judgement call yourself (assuming you understand concepts at a fairly low level).

Having said all of this, there is a lot to be said for simplicity and code readability.  In general, unless you are dealing with problems that greatly benefit from parallelism and / or performance is a high priority, attempting to make everything parallel is just going to complicate things and bite you.  Most of the time, there are better places to spend your spare brainpower :)

ContentLicense: CC BY-SA 3.0

Title: When should I use parallelism?


问:
Is it a responsibility of the software developer to understand what the customer meant with his request?
Kind of a yes / no question and why?

Is it the responsibility of the software developer to understand what the customer meant with his/her request or is it the responsibility of the customer to properly explain his/her request to the developer?

The situation at work is currently "the customer already explained us, what he wants. It's your responsibility to understand the request, not ask more questions".

While English is not my strong suite, all the requests are written in obscure English with misplaced words and hard to understand sentences, some requests assume previous understanding of the system on my part.

I'm the 3rd or 4th developer of the system (the last developers quit the job) and that might be the reason the customer expects some understanding on the developers side.

The system itself is quite messy both in the UI and source code level. This looks like monkey coding to me - code and hope you get the request right, while not actually understanding the request.

I'm actually thinking about quitting the job, but haven't yet, given I'm not sure about who's right and who's wrong.

答:
I think it is always the responsibility of the service provider to ensure that the they have understood the clients intentions.

As experts in our field, it is not just our job to complete briefs but also to help guide our customers through the process of using our service, and this involved educating them on the possibilities we offer, and what we do now.

I believe a customer focussed approach is absolutely the way to do things, it is a tried and tested business model.


答:
I think that the actual role specifying who takes care of understanding requirements varies depending on some of these variables

Team size

Company's standards

The way the boss is used to work

Different expertise among the team members

So if you are just a one man team, you should make every effort to get to the bottom of the requests. if you are new in an ongoing project, you should make an effort to go over the requests again with the customer.

EDIT:
Most importantly, the customer may not know he made such poor requirements, and the process of gathering requirements is often long and tedious, but it's an important process, and if it falls on you because no one else does it, then you should do it with them.

Title: Is it a responsibility of the software developer to understand what the customer meant with his request?

Body:
Kind of a yes / no question and why?

Is it the responsibility of the software developer to understand what the customer meant with his/her request or is it the responsibility of the customer to properly explain his/her request to the developer?

The situation at work is currently "the customer already explained us, what he wants. It's your responsibility to understand the request, not ask more questions".

While English is not my strong suite, all the requests are written in obscure English with misplaced words and hard to understand sentences, some requests assume previous understanding of the system on my part.

I'm the 3rd or 4th developer of the system (the last developers quit the job) and that might be the reason the customer expects some understanding on the developers side.

The system itself is quite messy both in the UI and source code level. This looks like monkey coding to me - code and hope you get the request right, while not actually understanding the request.

I'm actually thinking about quitting the job, but haven't yet, given I'm not sure about who's right and who's wrong.


答:
The customer and developers need to work together to refine their understanding of the system.

The software company needs to come to an agreement with the client as to what is required of each party, that is the fundamental aspect of a contract. If there is no "meeting of minds" then, in a very real sense, there is no contract.

Assuming that you are a competent programmer,  if the specification is not clear then simply being told "It's your responsability to understand the request, not ask more questions" is rather silly.


答:
When your clients and superiors leave you with a messy paper trail, the only thing you can do is gather as much sense as you can from what you have and start writing scenarios in plain English in an attempt to structure what knowledge there is about how the system is supposed to behave.

Given/When/Then scenarios make it possible for you to get into detail about what needs to happen and because they're written in plain English and they're structured, you can use them to communicate to your superior and client: "Listen, I've gotten to this point and I have no idea what the system is supposed to do here".

If your simply shunned away when you ask for additional clarification, even though you've invested effort to document everything that you do and do not understand, then the previous developers failed not because they didn't know how to communicate the specifications, but because it's impossible to do so.


答:
All tasks are not created equal. Some tasks lend themselves to parallelism naturally. For example, consider that you are creating a travel website like Kayak. One of the most important thing to do is, use the API's provided by search providers like British Airways, Singapore airways etc., You set of a different thread to different APIs so that, fetching can be done in parallel.If a thread does not return the result in time, abort it(may be). As you can imagine, it is very difficult to do this task without using concurrency.

With processors arriving with multiple cores these days, concurrent programming is becoming more and more relevant.

Title: When should I use parallelism?

Body:
After asking this question, I got to realize that parallelism may not always be good.

So far I can see that parallelism (under c#) is

A little complicated code-wise

Will probably insert some concurrency complications

Will not always be faster

I am looking inside parallelism because I want to make existing and new applications work faster, but now I see that it is no silver bullet.

When should I use it? are there any best practices?
Is it just a waste of time in most cases?
Is it suitable for a specific kind of applications?

I am looking forward for your insights on this matter.


答:
In my opinion both (customer and developer) have to get the same understanding of the problem and its solution.

If you don't understand the request you cannot create the solution.

So you have to read the specs. If the spec is not clear enough (or there is no written spec) there should be someone who can give the answers.

I work in teams that have one person that can answer the business-questions. This business owner is either a member of the development-company I work for that knows the customers business or a member of the customers team.


答:
If it's your job to understand, it is your job to ask questions until you do

The person you ask may be someone who is not the customer (i often talked to an intermediary, who was in contact with the customer), so the ones who forbid you to talk to the customer should instead answer the questions themselves or refer you to someone who can.

But, in the end there has to be SOME kind of communication. If they deny it (and providing some documents that you don't unterstand is effectively denying communication), you should do as your predecessors did: run away, quickly.


答: Code paths that don't do substantial work would not be very useful to execute in parallel. Look at the Amdahl's Law for details.</p>

Title: When should I use parallelism?


答:
There a some cases when you should use parallelism, the simpliest case is to perform big task in background to remain responsive GUI. It is a task parallelism.
Another case is when you have to process a lot of data - video decoding, solving optimization problems and so on. Such type of parallelism is called as data parallelism.
In data parallelism case a task are processed faster, because all chunks of data are processed independently.
But for task parallelism the performance is not always the main purpose. Often you should use it to improve usability.</p>

Title: When should I use parallelism?


问:
IntelliJ with Maven compilation
I have a project that needs Hibernate jars.

I added them as dependencies in the pom.xml and Maven compiles my project well.

However, in the IDE, all annotations and calls to Hibernate API are marked as unresolved (red).

How could I get IntelliJ being able to resolve them ?

Is there a way to use Maven when I click on Build Project ? (ctrl+F9)

Also, I am confused with the concept of facets within IntelliJ. Do I need them, let's say JPA facets to enable Persistence assistant etc... or there's an option to let Maven take care about ?

答:
Clear the cache or reimport

Sometimes Intellij gets in a tangle with projects. When that happens the general approach is as follows:

Try Build | Rebuild Project

If no, check that the project will compile from the command line

If yes, then use File | Invalidate Caches followed by Build | Rebuild All

If no, then delete your local project files and check them out from version control once again using the pom.xml as the project file

If no, then there is a serious problem with your Intellij installation

Title: IntelliJ with Maven compilation


问:
When is unit testing inappropriate or unnecessary?
It seems to be generally assumed (on Stack Overflow at least) that there should always be unit tests, and they should be kept up to date. But I suspect the programmers making these assertions work on different kinds of projects from me - they work on high quality, long-lasting, shipped software where bugs are A Really Bad Thing.

If that's the end of the spectrum where unit testing is most valuable, then what's the other end? Where are unit tests least valuable? In what situations would you not bother? Where would the effort of maintaining tests not be worth the cost?

答:
Where are unit tests least valuable?

You should be writing unit tests only for logical code. Definition of logical code is below:

Logical code is any piece of code that has some sort of logic in it,
small as it may be. It’s logical code if it has one or more of the
following: an IF statement, a loop, switch or case statements,
calculations, or any other type of decision-making code.

If that's the end of the spectrum where unit testing is most valuable,
  then what's the other end?

Tightly coupled code can't be easily tested. Sometimes it can't be tested at all. For example ASP.NET web forms are a nightmare and sometimes impossible to test, as opposed to ASP.NET MVC which is built with unit testing in mind.

I may choose not to write tests for very small and simple projects. This is perfectly justifiable in a world with limited time and resources. Yes, it's risky, but it's perfectly acceptable when the company you work for has a limited time to market.

What situations would you not bother? Where would the effort of
  maintaining tests not be worth the cost?

Once unit tests are in place, their maintenance cost becomes very insignificant. Unit tests with high code coverage give you a valuable sense of confidence that system behaves how you expect it to. The same applies to integration tests, but that's not your question.

My answer is based on the following assumptions:

You know difference between unit, integration and functional tests.

You are proficient with one of the unit-testing frameworks, and it takes you very little effort to write a unit test.

You don't feel like you are doing extra work when you are writing unit tests.

Reference: Art of Unit Testing


答:
It seems in your specific sitation, the project manager fears that the customer will be annoyed if they're asked the same questions multiple times (necessary because of developer turnover), and that this will reflect poorly on him and his company.

Of course, if you don't ask those questions, it will take you much longer to complete/modify the system and the result may not be what the customer wanted, which will cause more delays and ALSO reflect poorly on the project manager and his company, at least in the eyes of the customer.

There are some reasons why the project manager might choose not to let you ask questions:

He doesn't really understand the negative consequences or is in denial about them.

He's aware of the alternatives but knows the customer to be more likely to accept delays and poor quality than annoying questions.

He's playing political games: maybe he knows he's leaving the project soon and wants to keep problems hidden until then, or he's planning to blame you for the problems caused by this lack of communication.

IMO reason 2 is unlikely. In order to eliminate reason 1, try explaining the alternatives to him and ask him to make an explicit choice between them - suggest explaining the problem to the customer to reduce the annoyance. In order to eliminate reason 3, do this in writing so you can prove you were aware of potential probleams early on and tried to fix them. But to be honest, if you suspect this to be necessary you should probably get out there as quickly as possible.


答:
In my view, product/code prototypes don't require testing as they are often delivered using a completely different process and for completely different purposes than a finished product.

Imagine this common scenario. You have some sort of technology that your company is famous for, your sales team or a chief exec goes to a client and is able to sell them a different product that is leveraging your technology. They sell it there and then and promise the client they'll see a beta version in a month time. You don't have anything, even a development team.

What happens next is you quickly design a solution based on the points agreed/sold to the client, assemble a team of (often star) engineers and start writing code. It would be ideal of course if your dates didn't slip (they always do) and you managed to write code in three weeks time rather than four. In this case you have an extra week, and if you were able to secure a QA team's time for this week - you will test it. In reality you won't have an extra week and/or your QA team is booked for another two months supporting other product deliveries. Moreover you won't have any design specs, so QA team won't have any idea what they are supposed to be testing. So you end up delivering what you wrote with a bit of your own smoke testing, which isn't really a testing as such, simply because you aren't qualified to test your own code. The biggest factor here, is that the client will see some of the promised functionality very quickly. If your prototype does the job, then you're back to the drawing board, where you design and plan the actual version 1.0 - properly this time.

As far as unit-tests go, they are good to maintain certain contracts (I promise my code will do this, if it doesn't - it's broken). In case of prototyping, you may not care so much for contracts, because often enough your prototypes will not live to become version 1.0, whether because the client has went away, or because you ended up developing your version 1.0 using different technologies/tools. An example here would be a quick prototype website written very quickly on PHP in a month's time by one person, and then you assemble a team to rewrite it in JEE. Even the database will often not survive this change.

Title: When is unit testing inappropriate or unnecessary?

Body:
It seems to be generally assumed (on Stack Overflow at least) that there should always be unit tests, and they should be kept up to date. But I suspect the programmers making these assertions work on different kinds of projects from me - they work on high quality, long-lasting, shipped software where bugs are A Really Bad Thing.

If that's the end of the spectrum where unit testing is most valuable, then what's the other end? Where are unit tests least valuable? In what situations would you not bother? Where would the effort of maintaining tests not be worth the cost?


问:
The modern way to perform error handling...
I've been pondering this problem for a while now and find myself continually finding caveats and contradictions, so I'm hoping someone can produce a conclusion to the following:

Favour exceptions over error codes

As far as I'm aware, from working in the industry for four years, reading books and blogs, etc. the current best practice for handling errors is to throw exceptions, rather than returning error codes (not necessarily an error code, but a type representing an error).

But - to me this seems to contradict...

Coding to interfaces, not implementations

We code to interfaces or abstractions to reduce coupling. We don't know, or want to know, the specific type and implementation of an interface. So how can we possibly know what exceptions we should be looking to catch? The implementation could throw 10 different exceptions, or it could throw none. When we catch an exception surely we're making assumptions about the implementation?

Unless - the interface has...

Exception specifications

Some languages allow developers to state that certain methods throw certain exceptions (Java for example, uses the throws keyword.) From the calling code's point of view this seems fine - we know explicitly which exceptions we might need to catch.

But - this seems to suggest a...

Leaky abstraction

Why should an interface specify which exceptions can be thrown? What if the implementation doesn't need to throw an exception, or needs to throw other exceptions? There's no way, at an interface level, to know which exceptions an implementation may want to throw.

So...

To conclude

Why are exceptions preferred when they seem (in my eyes) to contradict software best practices? And, if error codes are so bad (and I don't need to be sold on the vices of error codes), is there another alternative? What is the current (or soon to be) state of the art for error handling that meets the requirements of best practices as outlined above, but doesn't rely on calling code checking the return value of error codes?

答:
Yes, exceptions can cause leaky abstractions. But are error codes not even worse in this regard?

One way to deal with this problem is to have the interface specify exactly which exceptions can be thrown under what circumstances and declare that implementations must map their internal exception model to this specification, by catching, converting and re-throwing exceptions if necessary. If you want a "prefect" interface, that's the way to go.

In practice, it's usually sufficient to specify exceptions that are logically part of the interface and which a client may want to catch and do something about. It's generally understood that there can be other exceptions when low-level errors happen or a bug manifests, and which a client can only handle generally by showing an error message and/or shutting down the application. At least the exception can still contain information that helps diagnosing the problem.

In fact, with error codes, pretty much the same thing ends up happening, just in a more implicit fashion, and with far more likelihood of information getting lost and the app ending up in an inconsistent state.


答:
The cost isn't in maintaining tests, but rather in not maintaining working code. If you divorce testing and implementation, you are assuming that what you write will work without the benefit of proof. Tests give you that proof, and the confidence to maintain the code as time passes.  Sure you might think that you'll never revisit that app you thought was a throw-away, however the reality is that any time you spend writing software is an investment that your employer doesn't want to treat lightly.  Let's face it, software developers don't generally come cheap, and time spent on code to throw away is money simply burned to your employer.

If you are spiking a problem, writing a few lines of code to see how something works, or simply throwing together an example for Programmers.SE, then it's really a case of creating something that you fully intend to throw away once you've satisfied your understanding of a problem. In such cases, unit testing can be a hindrance to the task and can safely be left out. In all other cases however, I'd say that testing is always appropriate, even if the program seems relatively unimportant, and you should always aim to write software to a professional standard with enough test support to reduce the difficulty in maintaining the code in the future.


答:
You should really have tests for any code that you intend to run on more than 1 occasion.

If you intend to run it once then throw it away, tests may not be useful, though if the domain is complex, I might well write the tests anyway to help me with my design and implementation.

Otherwise, even if the only thing the tests do is confirm that your assumptions are still correct, they are valuable. And any code that lasts more than a single session will need modifications, at which point the tests will pay for themselves 10 times over.


答:
First of all, I would disagree with this statement:

Favour exceptions over error codes

This is not always the case: for example, take a look at Objective-C (with the Foundation framework). There the NSError is the preferred way to handle errors, despite the existence of what a Java developer would call true exceptions: @try, @catch, @throw, NSException class, etc.

However it is true that many interfaces leak their abstractions with the exceptions thrown. It is my belief that this is not the fault of the "exception"-style of error propagating/handling. In general I believe the best advice about error handling is this:

Deal with the error/exception at the lowest possible level, period

I think if one sticks to that rule of thumb, the amount of "leakage" from abstractions can be very limited and contained.

On whether exceptions thrown by a method should be part of its declaration, I believe they should: they are part of the contract defined by this interface: This method does A, or fails with B or C.

For example, if a class is an XML Parser, a part of its design should be to indicate that the XML file provided is just plain wrong. In Java, you normally do so by declaring the exceptions you expect to encounter and adding them to the throws part of the declaration of the method. On the other hand, if one of the parsing algorithms failed, there's no reason to pass that exception above unhandled.

It all boils down to one thing:
Good interface design.
If you design your interface well enough, no amount of exceptions should haunt you.
Otherwise, it's not just exceptions that would bother you.

Also, I think the creators of Java had very strong security reasons to include exceptions to a method declaration/definition.

One last thing: Some languages, Eiffel for example, have other mechanisms for error handling and simply do not include throwing capabilities. There, an 'exception' of sort is automatically raised when a postcondition for a routine is not satisfied.

Title: The modern way to perform error handling...

Body:
I've been pondering this problem for a while now and find myself continually finding caveats and contradictions, so I'm hoping someone can produce a conclusion to the following:

Favour exceptions over error codes

As far as I'm aware, from working in the industry for four years, reading books and blogs, etc. the current best practice for handling errors is to throw exceptions, rather than returning error codes (not necessarily an error code, but a type representing an error).

But - to me this seems to contradict...

Coding to interfaces, not implementations

We code to interfaces or abstractions to reduce coupling. We don't know, or want to know, the specific type and implementation of an interface. So how can we possibly know what exceptions we should be looking to catch? The implementation could throw 10 different exceptions, or it could throw none. When we catch an exception surely we're making assumptions about the implementation?

Unless - the interface has...

Exception specifications

Some languages allow developers to state that certain methods throw certain exceptions (Java for example, uses the throws keyword.) From the calling code's point of view this seems fine - we know explicitly which exceptions we might need to catch.

But - this seems to suggest a...

Leaky abstraction

Why should an interface specify which exceptions can be thrown? What if the implementation doesn't need to throw an exception, or needs to throw other exceptions? There's no way, at an interface level, to know which exceptions an implementation may want to throw.

So...

To conclude

Why are exceptions preferred when they seem (in my eyes) to contradict software best practices? And, if error codes are so bad (and I don't need to be sold on the vices of error codes), is there another alternative? What is the current (or soon to be) state of the art for error handling that meets the requirements of best practices as outlined above, but doesn't rely on calling code checking the return value of error codes?


答:
IM-very-HO exceptions are to be judged on a case by case basis, because by breaking control flow they will increase the actual and perceived complexity of your code, in many cases unnecessarily so. Putting aside the discussion related to throwing exceptions inside your functions - which may actually improve your control flow, if one is to look at throwing exceptions through call boundaries, consider the following:

Allowing a callee to break your control flow may not provide any real benefit, and there may be no meaningful way to deal with the exception. For a direct example, if one is implementing the Observable pattern (in a language such as C# where you have events everywhere and no explicit throws in the definition), there is no actual reason to let the Observer break your control flow if it crashes, and no meaningful way to deal with their stuff (of course, a good neighbor should not throw when observing, but nobody's perfect).

The observation above can be extended to any loosely coupled interface (as you pointed out); I think it's actually a norm that after creeping up 3-6 stack frames, an uncaught exception is likely to end up in a section of code which either:

is too abstract to deal with the exception in any meaningful way, even if the exception itself is upcasted;

is performing a generic function (couldn't care less about why you failed, such as a message pump, or the observable);

is specific, but with a different responsibility, and it really shouldn't worry;

Considering the above, decorating interfaces with throws semantics is only a marginal functional gain, because a lot of callers thru interface contracts would only care if you failed, not why.

I would say it then becomes a question of taste and convenience: your primary focus is gracefully recovering your state in both the caller and the callee after an "exception", therefore, if you have a lot of experience in moving error codes around (coming from a C background), or if you're working in an environment where exceptions can turn evil (C++), I don't believe that throwing stuff around is so important for nice, clean OOP that you can't rely on your old patterns if you're uncomfortable with it. Especially if it leads to breaking SoC.

From a theoretical perspective, I think a SoC-kosher way of handling exceptions can be derived directly from the observation that most of the times the direct caller only cares that you failed, not why. The callee throws, someone very close above (2-3 frames) catches an upcasted version, and the actual exception is always sunk to a specialized error handler (even if only tracing) - this is where AOP would come in handy, because these handlers are likely to be horizontal.


答:
I have no clue about unnecessary but I'll shoot for when I think Unit Tests are inappropriate in that they add cost without proportional benefit:

If our organization / dev team isn't doing any unit tests, then unless you are able to convince your fellow developers of running, fixing (and also creating on their own) unit tests, the tests you create aren't going to be run and maintained. (This implies you are working on a piece of software together with someone else.)

Not everyone is doing unit testing, they're sometimes shoddily supported by local team culture, and in such environments you first need to get them in place for the majority of devs and probably also for the build-process ("[continuous] integration") before actually starting to write unit tests makes sense.

Given time pressure and delivery dates and "your" relative standing with the team -- the time remaining until writing unit tests makes sense can easily be months or years.

ContentLicense: CC BY-SA 4.0


答:
I will personally not write unit tests for situations where:

The code has no branches is trivial. A getter that returns 0 doesn't need to be tested, and changes will be covered by tests for its consumers.

The code simply passes through into a stable API. I'll assume that the standard library works properly.

The code needs to interact with other deployed systems; then an integration test is called for.

If the test of success/fail is something that is so difficult to quantify as to not be reliably measurable, such as steganography being unnoticeable to humans.

If the test itself is an order of magnitude more difficult to write than the code.

If the code is throw-away or placeholder code. If there's any doubt, test.


答:
You should write unit tests when when the logical comprehension required to maintain or extend or communicate the logic of the application without flaws exceeds (or will likely in the future exceed) the ability of the least knowledgeable member of your team to meet that understanding.

Basically depends how much you can keep in your head at once. On your own you might have more confidence that you can code (in full knowledge of the impact of your changes) until a certain complexity has been reached. Until that point unit tests are a distraction, a hindrance and will slow you down. In a team, the threshold is going to be much lower so you pretty much need unit tests straight away to counteract group-stupidity. If you pick up a testless project from someone else (or you've forgotten about a project from a while ago) you'll want to write unit tests before you change anything because your understanding will be zero.

Note: writing less code and practising YAGNI, keeps down complexity and hence the number of required unit tests.


答:
Unless you are going to write code without testing it, you are always going to incur the cost of testing.

The difference between having unit tests and not having them is the difference between the cost of writing the test and the cost of running it compared to the cost of testing by hand.

If the cost of writing a unit test is 2 minutes and the cost of running the unit test is practically 0, but the cost of manually testing the code is 1 minute, then you break even when you have run the test twice.

For many years I was under the misapprehension that I didn't have enough time to write unit tests for my code. When I did write tests, they were bloated, heavy things which only encouraged me to think that I should only ever write unit tests when I knew they were needed.

Recently I've been encouraged to use Test Driven Development and I found it to be a complete revelation. I'm now firmly convinced that I don't have the time not to write unit-tests.

In my experience, by developing with testing in mind you end up with cleaner interfaces, more focussed classes & modules and generally more SOLID, testable code.

Every time I work with legacy code which doesn't have unit tests and I have to manually test something, I keep thinking "this would be so much quicker if this code already had unit tests". Every time I have to try and add unit test functionality to code with high coupling, I keep thinking "this would be so much easier if it had been written in a de-coupled way".

Comparing and contrasting the two experimental stations that I support. One has been around for a while and has a great deal of legacy code, while the other is relatively new.

When adding functionality to the old lab, it is often a case of getting down to the lab and spending many hours working through the implications of the functionality they need and how I can add that functionality without affecting any of the other functionality. The code is simply not set up to allow off-line testing, so pretty much everything has to be developed on-line. If I did try to develop off-line then I would end up with more mock objects than would be reasonable.

In the newer lab, I can usually add functionality by developing it off-line at my desk, mocking out only those things which are immediately required, and then only spending a short time in the lab, ironing out any remaining problems not picked up off-line.

TL;DR version:

Write a test when the cost of writing the test, plus the cost of running it as many times as you need to is likely to be less than the cost of manually testing it as many times as you need to.

Remember though that if you use TDD, the cost of writing tests is likely to come down as you get better at it, and unless the code is absolutely trivial, you probably end up running your tests more often than you expect.


问:
How to decide whether to implement an operation as Entity operation vs Service operation in Domain Driven Design?
I am reading Evans's Domain Driven Design. The book says that there are entity and there are services. If I were to implement an operation, how to decide whether I should add it as a method on an entity or do it in a service class?

e.g. myEntity.DoStuff() or myService.DoStuffOn(myEntity)?

Does it depend on whether other entities are involved? If it involves other entities, implement as service operation? But entities can have associations and can traverse it from there too right?

Does it depend on stateless or not? But service can also access entities' variable, right? Like in do stuff myService.DoStuffOn, it can have code like

```<code>if(myEntity.IsX) doSomething();
</code>```

Which means that it will depend on the state?

Or does it depend on complexity? How do you define complex operations?

答:
As far as I'm concerned, I always try to add an operation into an Entity before considering using a Service, because that's the natural place you'll look in if the operation is closely related enough to the Entity.

Just because a method involves several entities doesn't mean it can't be placed into one of them. Especially, invariants and business rules that span across several of an Aggregate's Entities are often implemented in the Aggregate Root.

I only use a Service if the operation doesn't seem to belong in any of the existing Entities. A good example of that is the TransferFunds() method. Should it be a method of the source account ? It would mean the source account can alter the balance of the destination account, which seems a bit weird. Same thing with the destination account.

So this is a perfect case for a FundsTransferService with the following method :

```<code>public void TransferFunds(Account source, Account destination, decimal amount)
</code>```

It shouldn't happen all that often though.

Also, keep in mind that it's not just an Entities vs Services world. You've got plenty of other objects to put your operations in - Factories, Policies, Specifications, etc.

Body:
As far as I'm concerned, I always try to add an operation into an Entity before considering using a Service, because that's the natural place you'll look in if the operation is closely related enough to the Entity.

Just because a method involves several entities doesn't mean it can't be placed into one of them. Especially, invariants and business rules that span across several of an Aggregate's Entities are often implemented in the Aggregate Root.

I only use a Service if the operation doesn't seem to belong in any of the existing Entities. A good example of that is the TransferFunds() method. Should it be a method of the source account ? It would mean the source account can alter the balance of the destination account, which seems a bit weird. Same thing with the destination account.

So this is a perfect case for a FundsTransferService with the following method :

public void TransferFunds(Account source, Account destination, decimal amount)

It shouldn't happen all that often though.

Also, keep in mind that it's not just an Entities vs Services world. You've got plenty of other objects to put your operations in - Factories, Policies, Specifications, etc.


答:
Sometimes you don't have time to unit test. That's okay.

External constraints exists and you may not feel the need for tests in a  given moment, as you may think you have a firm grasp on the whole system state and know how changes will ripple trough it.

But I still believe you should feel a little guilty about it.
So when things start to fall apart, you will know it's because: "oh, yeah, I'm not testing stuff, let's start testing."

Before that moment, the feel of guilt will help you avoid certain architectural choices that would prevent you from being able to automate code tests later.


问:
Choosing a rate to charge a client for training their programmer
We've been put in a bit of a difficult situation and I'm trying to figure out the best way to deal with it and how to charge for it.

We've built a custom web app for a customer and I've been maintaining it for the last 1.5 years. They sent email an email a couple weeks ago saying they've hired a developer and would like to take the project in house. (Nothing had been mentioned regarding taking it in house before.) I was of course surprised as I had expected to be working on the project for another year or more.

I met with the developer a week ago and went over the basics of the site. After my offer (including suggestion of a different rate) and follow-up email, they asked me if I'd be willing to do some training on how to continue development of the app using the libraries/techniques currently used. (The developer is experienced with the language, but not with the libraries.)

I'm wondering how much I should charge for 1-on-1 training tailored specifically for the site and the libraries (libraries which are reusable)? I'm thinking the training would between 3 and 6 hours, depending on how much the developer's skill level.

Here are my difficulties in coming up with the rate:

We're going to be loosing 10s of thousands of dollars by not having the client and project any more (not to mention future opportunities). So in part, I'd like to replace some of this income through training.

I'm essentially training someone to do what we do and giving them the opportunity to compete against us. They are a reasonably large company that has the possibility of competing against our company directly, although it's not likely our 2 companies will be direct competition.

We've spent years learning the libraries (50% external and 50% ours) and the technology behind them (which we haven't been paid for directly).

I'm not sure what the going rate for training is the area, specifically for 1-on-1 training.

I want to do the right thing because there is a slight possibility of affecting other business relationships.

My first thought was to to charge something around 5 times the rate we're charging them currently, but I have a feeling they'll think this is high.

(We're not terribly concerned with getting the contract to do the training, but it would be a unique opportunity where we could learn as well.)

Thanks for your suggestions and ideas. I know this is a bit of a subjective question, but I'm just looking for suggestions or something I'm not thinking of.

答:
Look at the cost of other paid training in your area. You may be able to charge 2 or 3 times the price.

Frequently if you want to attend a one day training class for technology X there is breakeven point of around 5 people where they will come to your location for training. Less than 5, students travel to the trainer, 5 or more the trainer comes to the student. Use this as your justification to your client.

Yes the rate has to be beyond your normal rate to pay for the time it will take to develop the class.

You will not be able to get a rate high enough to make up for all the lost hours for the next year.

Another option is to setup a consulting fee and a retainer. So that you can answer questions when they occur after the transition.


问:
Linking Libraries in iOS?
This is probably a totally noob question but I have missing links in my mind when thinking about linking libraries in iOS. I usually just add a new library that's been cross compiled and set the build and linker paths without really know what I'm doing. I'm hoping someone can help me fill in some gaps.

Let's take the OpenCV library for instance. I have this totally working btw because of a really well written tutorial( http://niw.at/articles/2009/03/14/using-opencv-on-iphone/en ), but I'm just wanting to know what is exactly going on.

What I'm thinking is happening is that when I build OpenCV for iOS is that your creating object code that gets placed in the .a files. This object code is just the implementation files( .m ) compiled. One reason you would want to do this is to make it hard to see the source code and so that you don't have to compile that source code every time.

The .h files won't be put in the library ( .a ). You include the .h in your source files and these header files communicate with the object code library ( .a ) in some way.

You also have to include the header files for your library in the Build Path and the Library itself in the Linker Path.

So, is the way I view linking libraries correct? If , not can someone correct me on this ?

答:
Your ideas are generally correct, however it seems to me that you're in some sort of delusion about the amount of 'magic' that happens during a build:

these header files communicate with the object code library ( .a ) in some way.

The truth is simpler than this: there's no connection between headers and the library archive (.a files are compressed .o files). The only thing that the header file contains is the declarations of the functions used. This tells the compiler that these functions exist, somewhere. At the compilation phase, the compiler assumes that they do, and creates object code only for functions that are defined. Then, at the linking phase, the linker searches for the declared  functions, that are not found in the original file. This is why you must #import/#include the proper header and import the dylib or add the .a file.

In fact, you could manage without the header file if you know the declarations of the functions you are going to use and declare them on top of the file where you are using them. Of course, this would be insane, since you are stripping a lot of information from the compiler and if you make an error in the function declaration, it would either produce a compile error for not using the function properly, or a linking error for not finding the (improperly declared) function implementation.

EDIT: I just tested the following code:

```<code>myfunkyfunction();
</code>```

in Objective-C this generates the classic compiler warning for "implicit declaration of..." and the linker error "Symbol(s) not found".

The following code, however, fails with a compiler error "Funkster undeclared".

```<code>Funkster* hipster = [[Funkster alloc] init];
</code>```

Therefore, while you can entirely omit declarations of C functions, declaring Objective-C classes is mandatory at compile-time.

Title: Linking Libraries in iOS?

Body:
Your ideas are generally correct, however it seems to me that you're in some sort of delusion about the amount of 'magic' that happens during a build:

these header files communicate with the object code library ( .a ) in some way.

The truth is simpler than this: there's no connection between headers and the library archive (.a files are compressed .o files). The only thing that the header file contains is the declarations of the functions used. This tells the compiler that these functions exist, somewhere. At the compilation phase, the compiler assumes that they do, and creates object code only for functions that are defined. Then, at the linking phase, the linker searches for the declared  functions, that are not found in the original file. This is why you must #import/#include the proper header and import the dylib or add the .a file.

In fact, you could manage without the header file if you know the declarations of the functions you are going to use and declare them on top of the file where you are using them. Of course, this would be insane, since you are stripping a lot of information from the compiler and if you make an error in the function declaration, it would either produce a compile error for not using the function properly, or a linking error for not finding the (improperly declared) function implementation.

EDIT: I just tested the following code:

myfunkyfunction();

in Objective-C this generates the classic compiler warning for "implicit declaration of..." and the linker error "Symbol(s) not found".

The following code, however, fails with a compiler error "Funkster undeclared".

Funkster* hipster = [[Funkster alloc] init];

Therefore, while you can entirely omit declarations of C functions, declaring Objective-C classes is mandatory at compile-time.


答: Charge your standard fee for the training and the time it takes you to prepare for the training. Let them know that you are open to answer any further questions beyond the training as a consultant. Beyond that, it sounds like it is time to move on. The well has dried up and no amount of training is going to replace this source of revenue. You will only lose those 10s of thousands if you do not find work to replace it.</p>

Title: Choosing a rate to charge a client for training their programmer

Body:
We've been put in a bit of a difficult situation and I'm trying to figure out the best way to deal with it and how to charge for it.

We've built a custom web app for a customer and I've been maintaining it for the last 1.5 years. They sent email an email a couple weeks ago saying they've hired a developer and would like to take the project in house. (Nothing had been mentioned regarding taking it in house before.) I was of course surprised as I had expected to be working on the project for another year or more.

I met with the developer a week ago and went over the basics of the site. After my offer (including suggestion of a different rate) and follow-up email, they asked me if I'd be willing to do some training on how to continue development of the app using the libraries/techniques currently used. (The developer is experienced with the language, but not with the libraries.)

I'm wondering how much I should charge for 1-on-1 training tailored specifically for the site and the libraries (libraries which are reusable)? I'm thinking the training would between 3 and 6 hours, depending on how much the developer's skill level.

Here are my difficulties in coming up with the rate:

We're going to be loosing 10s of thousands of dollars by not having the client and project any more (not to mention future opportunities). So in part, I'd like to replace some of this income through training.

I'm essentially training someone to do what we do and giving them the opportunity to compete against us. They are a reasonably large company that has the possibility of competing against our company directly, although it's not likely our 2 companies will be direct competition.

We've spent years learning the libraries (50% external and 50% ours) and the technology behind them (which we haven't been paid for directly).

I'm not sure what the going rate for training is the area, specifically for 1-on-1 training.

I want to do the right thing because there is a slight possibility of affecting other business relationships.

My first thought was to to charge something around 5 times the rate we're charging them currently, but I have a feeling they'll think this is high.

(We're not terribly concerned with getting the contract to do the training, but it would be a unique opportunity where we could learn as well.)

Thanks for your suggestions and ideas. I know this is a bit of a subjective question, but I'm just looking for suggestions or something I'm not thinking of.


答:
You could charge an annual license fee for your libraries. </p>

<p>Also recently we were charged £750 per day for training our accounts people on a new accounts system. For more specialist stuff I'd say you can charge more. I've seen course fees in the £1950 a day range for some things. </p>

Body:
You could charge an annual license fee for your libraries.

Also recently we were charged £750 per day for training our accounts people on a new accounts system. For more specialist stuff I'd say you can charge more. I've seen course fees in the £1950 a day range for some things.


答:
you should charge your normal rate for the training and bill them for all time used in planning the training. You or your client is grossly underestimating the time its going to take to train their developer, 3-6 hours to get them up to speed on the libraries and site is off by a lot, unless this is a very small and simple app.

Also you are going to have to work out if they own all the code/rights to use libraries and can actually do this, which is a separate manner.


问:
How to go about training IComparable to a team?
I (am just a developer) am tasked with training my team on a technique or technology. I zeroed upon System Interfaces, IComparable and IEquatable to be specific. How does one go about teaching (even if it is 1 hour), what an IComparable is and where we can use it by giving them an example.

However, I am not entirely sure whether that would make my team to understand and start using IComparable.

In my project, however, I do have a Discount class and there are instances where I have to merge two lists of Discounts. Now, that would be a really good instance of where IEquatable would be helpful when I do the merge wouldn't it?

I had the following template for training.

Introduction: Why does one need IComparable? (And, I could not get an answer that I can use for teaching).

Structure of IComparable (Again, what else can I talk about other than CompareTo method).

Sample Code

Where we can use that in our project

Questions.

答:
You really need to express the benefits of using these interfaces. I personally have found them useful when storing domain objects in collections and needing to either sort the collections or search for items in the collections.

Demonstrate the necessary code to do sorting/searching in a collection without using these interfaces and then demonstrate how using these interfaces makes the necessary code easier to maintain and use. Use the example you mentioned with the Discount class if you want, or any other class that your team is already familiar with.


问:
Why is Python slower than Java but faster than PHP
I have many times seen various benchmarks that show how a bunch of languages perform on a given task.

These benchmarks always reveal that Python is slower than Java, and faster than PHP, and I wonder why that's the case.

Java, Python, and PHP run inside a virtual machine

All three languages convert their programs into their custom byte codes that run on top of the OS -- so none is running natively

Both Java and Python can be "compiled" (.pyc for Python) but the __main__ module for Python is not compiled

Python and PHP are dynamically typed, and Java statically -- is this the reason Java is faster, and if so, please explain how that affects speed.

And, even if the dynamic-vs-static argument is correct, this does not explain why PHP is slower than Python -- because both are dynamic languages.

You can see some benchmarks here and here, and here

答: It has to do with the quality of the compiler, java's compiler has been continually optimized for much longer, and optimization is more important because all code is compiled for Java. I'm not sure the exact reason for python to be faster than PHP, but I would bet its because of Google's influence with Python.</p>


答:
JVM code can be JIT-compiled efficiently, using a trivial (and fast) ad hoc compiler. But the same would be exceptionally hard for PHP and Python, because of their dynamically typed nature. JVM translates to a fairly low level and straightforward native code, quite similar to what would a C++ compiler produce, but for the dynamic languages you'd have to generate dynamic dispatch for literally all the basic operations and for all the method calls. This dynamic dispatch is the primary bottleneck for all the languages of this kind.

In some cases it is possible to eliminate the dynamic dispatch (as well as the virtual calls in Java) using a much more complicated tracing JIT compiler. This approach is still in its infancy, not doing too much of an abstract interpretation, and such a compiler is likely to choke on eval calls (which are very typical for the dynamic languages).

As for the difference between Python and PHP, the latter is just of a much lower quality. It could run faster in theory, but it never will.

Title: Why is Python slower than Java but faster than PHP

Body:
I have many times seen various benchmarks that show how a bunch of languages perform on a given task.

These benchmarks always reveal that Python is slower than Java, and faster than PHP, and I wonder why that's the case.

Java, Python, and PHP run inside a virtual machine

All three languages convert their programs into their custom byte codes that run on top of the OS -- so none is running natively

Both Java and Python can be "compiled" (.pyc for Python) but the __main__ module for Python is not compiled

Python and PHP are dynamically typed, and Java statically -- is this the reason Java is faster, and if so, please explain how that affects speed.

And, even if the dynamic-vs-static argument is correct, this does not explain why PHP is slower than Python -- because both are dynamic languages.

You can see some benchmarks here and here, and here


问:
Unit testing: about easy- and hard-first strategies
I've never written a unit test.

I'm reading The art of Unit Testing by Osherove, and he explains a way to choose where to start when you're writing tests for legacy code. Basically you end up with two kinds of tests to write: easy (on components with few dependencies) and hard (on components with many dependencies).

Then he says that starting from the hard ones you have to be more experienced, but that it lets you refactor and make testable a wide part of the system, making later work much easier.

But isn't it true the way around too? I mean, if you start from easy tests, shouldn't you end up making hard tests easier?

答: I would start with the easy unit tests first just to get the experience of writing them under your belt. Ensure that your tests are thorough and that you are testing all of the cases you can think of for all combinations of input to the classes/methods you are testing. Starting with writing harder tests may discourage you from unit testing at all.</p>


答:
Go for the easy tests first, if only because when you start writing the hard tests, you'll be able to do some regression to ensure that your refactorings didn't break anything.

As per your question: That shouldn't be the case unless the system is incredibly highly coupled. The easy tests shouldn't force refactorings to make the harder tests easier. This may end up being the case, but your code should be as orthogonal as possible, thus making your tests just as orthogonal.

You could make a stronger case for your integration tests helping to do that.

Title: Unit testing: about easy- and hard-first strategies

Body:
I've never written a unit test.

I'm reading The art of Unit Testing by Osherove, and he explains a way to choose where to start when you're writing tests for legacy code. Basically you end up with two kinds of tests to write: easy (on components with few dependencies) and hard (on components with many dependencies).

Then he says that starting from the hard ones you have to be more experienced, but that it lets you refactor and make testable a wide part of the system, making later work much easier.

But isn't it true the way around too? I mean, if you start from easy tests, shouldn't you end up making hard tests easier?


问:
What non-programming books should a programmer read to help develop programming/thinking skills?
There are a lot of questions about what programming books should be on the programmer's bookshelf. How about non-programming related books that can help you become a better programmer or developer? It would also be interesting to know why they would help.

My first choice would be Sun Tzu's "Art of War" (however cliché), because it made it obvious that the success of any project depends on the strength of its weakest link (and warfare is a big project).

答: "How to solve it" by George Pólya. While targeted for mathematics, the problem solving strategies can readily be applied to programming.</p>


答:
if you start from easy tests, shouldn't you
  end up making hard tests easier?

After implementing easier tests the hard tests will become a tiny bit easier in the sense that you get experience as @Bernard stated.

however the difficulty with the hard tests is that non tdd developed modules are usually tightly coupled and it is nearly impossible to test functionality in isolation.

my advice:

do some easy tests to get experience.

create integration tests for the hard cases.

don't create unit tests for the hard cases as long as you are a tdd-novice.

do test-driven development for new features to get experience how implementation with loosely coupled functionality


答:
I would consider charging them for two things:

Training on a time and materials basis (doesn't need to have arbitrary x-factors).

A lump sum for handing over control of the application to them.

That lump sum is going to be what they'll try to negotiate. IMHO it should, at least, be a significant fraction (>1/2) of the amount you'd get for maintenance for that remaining year.


答:
Assuming we're talking about platform applications, I think you will next-to-always end-up needing some form of parallelism as your application grows more complex (as per the reading material recommended by gnat). There is always a large file to load, or a complaint from the customer that some web service dependency is too slow.

However, be wary about using vanilla threads and basic synchronization primitives, because multithreading is hard; instead, try to use higher-level primitives, patterns and components (you will find lots of great stuff to start with in the System.Threading.Tasks and the System.Collections.Concurrent namespaces). More importantly, as the complexity of your solution increases, avoid clever tricks.

Specifically, your friendly neighborhood platform application in C# is likely to have a UI message pump, and stuff executing in the background, in order a) to prevent locking the UI or b) to leverage multiple logical CPUs. A good decision list on "how to parallelize the heavy stuff in the background" would be:

if the task is simply not CPU intensive, but may spend a lot of time waiting (ex. for IO or for other tasks), send it to the Thread Pool. A good pattern here is to send to the TP just the call that may make you wait - the framework already has something for that, you will find Begin*/End* methods where you may wait a long time - and to marshal back to some safe context (ex. the UI thread) when the chicken's done. This way, your exposure to parallelism problems is low - and is bound to be ridiculously low in the next versions of .NET, with async and await.

inhomogeneous tasks with low granularity - that's usually task parallelism, the Command/Task design pattern is your friend, also, try to borrow from functional programming - avoid mutable and shared data, use continuations - and use the framework (specifically - the TPL, or at the very least a BlockingCollection implementing a producer-consumer);

homogeneous tasks with high granularity - that's usually data parallelism, where the data structures and algorithms you deploy make all the difference. Try to isolate the units of work with this profile from the rest of your logic, and consider going purely functional with it - use map-reduce as a good hint.

Title: When should I use parallelism?


答:
Well Exception handling can have their own interface implementation. Depending on the the type of the exception thrown, perform the desired steps.

The solution to your design problem is to have two interface/abstraction implementations. One for the functionality and the other for exception handling. And depending on the type of the Exception caught, call appropriate exception type class.

Implementation of Error codes is an orthodox way of handling exception. It is like usage of string vs. string builder.

OwnerDisplayName: Estefany Velez


答:
Unit tests are nice and all, but in complicated systems with lots of "moving parts", they really don't actually test much.

As we know, Unit tests ensure that given input X for a unit, you get output Y where X is all appropriate input and Y is all appropriate output. However, I find that most code does what the developer thought it should.. but not necessary what it actually should do.

(You might think of it like a gun. A gun has a bunch of precision parts manufactured separately and then assembled. It doesn't matter if each particular part is tests well for functionality if the gun explodes when actually fired. Disclaimer: I know nothing about fire arms (: )

In this cases, we need actual system tests in a model production environment. Since functionality is tested here anyway, the value of unit tests is slightly diminished.

However, unit tests are still valuable in this case because they provide assurance that functionality that you wished to remain unchanged does in fact remain unchanged. This is quite valuable because it gives you confidence for areas of the system need focused testing.


答:
The main utility of the built-in interfaces is that they are built-in; if you need to define that two objects can be compared for equality, IEquatable is right there. Same for IComparable and the ability to compare for relative magnitude.

This leads to another main reason why you'd use them; the .NET Framework does. Linq looks to see if the objects are ICompatable/IEquatable and uses those implementations when it can. Collections that are sortable require IComparable; collections with IndexOf()-type methods generally require IEquatable implementations on their collected type. So, in order to use what the Framework gives you, you have to use what the Framework gives you.

So, to answer the questions you pose in your template succinctly:

Conceptually, you need IComparable whenever you need to tell other code that this object can be compared to another object to determine relative magnitude. That other code then knows, much like any other interface, the exact name and signature of the method to call to perform this operation.

IComparable's "structure" IS the declaration of the CompareTo() method that takes an Object (in the non-generic variant) or an object of a strongly-defined type (for the generic interface; usually this type is the same type as the class). The only other thing you have to discuss is the expected result; a value of zero if the two instances are equal, a value of less than zero if the instance on which you are calling the method precedes the instance passed as the parameter, and a value greater than zero if the instance on which the method was called succeeds the instance passed as the parameter.

Code samples abound; check the MSDN documentation.

Pretty much anything you need to be able to sort by some default, esoteric subset of its data.

Title: How to go about training IComparable to a team?

Body:
I (am just a developer) am tasked with training my team on a technique or technology. I zeroed upon System Interfaces, IComparable and IEquatable to be specific. How does one go about teaching (even if it is 1 hour), what an IComparable is and where we can use it by giving them an example.

However, I am not entirely sure whether that would make my team to understand and start using IComparable.

In my project, however, I do have a Discount class and there are instances where I have to merge two lists of Discounts. Now, that would be a really good instance of where IEquatable would be helpful when I do the merge wouldn't it?

I had the following template for training.

Introduction: Why does one need IComparable? (And, I could not get an answer that I can use for teaching).

Structure of IComparable (Again, what else can I talk about other than CompareTo method).

Sample Code

Where we can use that in our project

Questions.


答:
I would just like to note that exceptions and error codes aren't the only way to deal with errors and alternate code paths.

Out of the top of the mind, you can have an approach like the one taken by Haskell, where errors can be signaled via abstract data types with multiple constructors (think discriminated enums, or null pointers, but typesafe and with the possibility of adding syntatic sugar or helper functions to make the code flow look good).

```<code>func x = do
    a <- operationThatMightFail 10
    b <- operationThatMightFail 20
    c <- operationThatMightFail 30
    return (a + b + c)
</code>```

operationThatMightfail is a function that returns a value wrapped in a Maybe.
It works like a nullable pointer, but the do notation guarantees that the whole thing evaluates to null if any of a, b, or c fail. (and the compiler protects you from making an accidental NullPointerException)

Another possibility is passing an error handler object as an extra argument to every function you call. This error handler has a method for each possible "exception" that can be signaled by the function you pass it to, and can be used by that function to treat the exceptions where they occur, without necessarily having to rewind the stack via exceptions.

Common LISP does this, and makes it feasible by having syntatic support (implicit arguments) and having the built-in functions follow this protocol.

Body:
I would just like to note that exceptions and error codes aren't the only way to deal with errors and alternate code paths.

Out of the top of the mind, you can have an approach like the one taken by Haskell, where errors can be signaled via abstract data types with multiple constructors (think discriminated enums, or null pointers, but typesafe and with the possibility of adding syntatic sugar or helper functions to make the code flow look good).

func x = do
    a <- operationThatMightFail 10
    b <- operationThatMightFail 20
    c <- operationThatMightFail 30
    return (a + b + c)

operationThatMightfail is a function that returns a value wrapped in a Maybe.
It works like a nullable pointer, but the do notation guarantees that the whole thing evaluates to null if any of a, b, or c fail. (and the compiler protects you from making an accidental NullPointerException)

Another possibility is passing an error handler object as an extra argument to every function you call. This error handler has a method for each possible "exception" that can be signaled by the function you pass it to, and can be used by that function to treat the exceptions where they occur, without necessarily having to rewind the stack via exceptions.

Common LISP does this, and makes it feasible by having syntatic support (implicit arguments) and having the built-in functions follow this protocol.


问:
Build a native dll or .net dll to be used independently in either set-up
Here's a simple question (kind of), but I'm having a hard time taking a decision. First, a history on how I came to have this problem. In my new job, we need to use a third party API to communicate with their proprietary database (this is manufacturing technologies). This API only comes with very simple c example (not simple syntax ;) ) on how to use this API. Functions have no documentations and the syntax is thick, since it was probably build sometime in the last century, so parameters have short  non significant names same with the functions names.

Very few help is found on the web and the company itself can't really help us. Over the web, the small crumb found are about people not able to translate it into simpler language call (like VB6). People before me here tried to use it, without success.

The good news is I have been able to make the example work and modified them to fit our basic needs to send or read data. I have wrapped these new version in a c++/CLR assembly dll, to use it in c#, which is our almost current language(Yeah , it moves slow in this world)

Depending on the version of the software we use (every client we have can have different setup, from legacy to brand new setup). This can have an influence an what language we use. So I was asked to try and make my dll available in native & managed setting.

So, here lies my question. Should I leave my dll to have a managed signature and if it needs to be use in vb6, make sure it is understood how to make it work in native mode (which I need to learn), or should I make a native dll and make it P/Invoke in managed setting? Or should I build two distinct dll? IMO, I would keep it as a managed dll, but I was wondering if it's the best way to do it?

On a last note, the current version is a v.1 build to showcase how we can use it,and start using it fast. Writing this makes me realize I need to build an interface!:). I plan to rebuild the whole program, but the API's calls will always be to their native dll, unless they have .net SDK coming, but no word about it yet.

答:
There are two drawbacks to keeping just the managed DLL:

a) you will need the .NET Framework on the target machine

b) there will be two layers of marshaling between an unmanaged caller and the code you've wrapped: a COM Callable-Wrapper between the native caller and the COM interface of your .NET Assembly, and the managed-unmanaged transition between your wrapper and the inner code - this may be a serious performance hit if you're marshaling a lot, and it may be complex if your interface to the callers is wide.

If neither of these is a real problem (i.e. adding the CCW in terms of performance and complexity), then you have no other direct incentive that I can see to modify your current solution.

As far as extensibility goes, if you plan to add managed code to the wrapper - if you need to complement the solution you're wrapping and need to add stuff to it at the low-cost of managed code, then you're pretty much stuck with the managed DLL, because presumably both the VB6 callers and the managed callers would need the new functionality. If, on the other hand you need to add native code, then you could still add it to the unmanaged CLI part of the managed DLL.


答:
Introduction: Why does one need IComparable? (And, I could not get an
  answer that I can use for teaching).

Because you want to be able to compare different type of objects without worrying how the actual comparison is done. You want to declare a responsibility and not worry about actual implementation as it may vary. Interface does just that.

It's concerned with comparing objects. Nothing more, nothing less.

Structure of IComparable (Again, what else can I talk about other than
  CompareTo method).

There is no implementation or structure as such. It exposes a behaviour, or a concern. There is nothing more to it.

Sample Code

Declare an interface

Create two implementations

Make an emphasis that you don't care about how implementations work, all you care about is being able to compare objects.

Where we can use that in our project

Comparing investments is interesting. Investment X might be less profitable, as profitable or more profitable than investment Y.

You can then define the following interface:

```<code>public interface IComparable<IInvestment>
{
   int Compare();
}
</code>```

You can have two implementations of IInvestment: RealInvestment and FakeInvestment (dummy version for unit tests and mocks)

Finally, you'll have two different comparison routines for real and fake investments:

```<code>public RealInvestmentComparable : IComparable<RealInvestment>
{
    // Implement interface
}

public FakeInvestmentComparable : IComparable<FakeInvestment>
{
    // Implement interface
}
</code>```

If you can base your training on a different interface, then maybe it's a better idea. It's normally very easy to talk about IRepository. You can then have multiple implementations of that repository, e.g. FakeRepository, EFRepository. You can use fake repository with unit tests.

Body:
Introduction: Why does one need IComparable? (And, I could not get an
  answer that I can use for teaching).

Because you want to be able to compare different type of objects without worrying how the actual comparison is done. You want to declare a responsibility and not worry about actual implementation as it may vary. Interface does just that.

It's concerned with comparing objects. Nothing more, nothing less.

Structure of IComparable (Again, what else can I talk about other than
  CompareTo method).

There is no implementation or structure as such. It exposes a behaviour, or a concern. There is nothing more to it.

Sample Code

Declare an interface

Create two implementations

Make an emphasis that you don't care about how implementations work, all you care about is being able to compare objects.

Where we can use that in our project

Comparing investments is interesting. Investment X might be less profitable, as profitable or more profitable than investment Y.

You can then define the following interface:

public interface IComparable<IInvestment>
{
   int Compare();
}

You can have two implementations of IInvestment: RealInvestment and FakeInvestment (dummy version for unit tests and mocks)

Finally, you'll have two different comparison routines for real and fake investments:

public RealInvestmentComparable : IComparable<RealInvestment>
{
    // Implement interface
}

public FakeInvestmentComparable : IComparable<FakeInvestment>
{
    // Implement interface
}

If you can base your training on a different interface, then maybe it's a better idea. It's normally very easy to talk about IRepository. You can then have multiple implementations of that repository, e.g. FakeRepository, EFRepository. You can use fake repository with unit tests.


答:
Leaky abstraction

Why should an interface specify which exceptions can
  be thrown? What if the implementation doesn't need to throw an
  exception, or needs to throw other exceptions? There's no way, at an
  interface level, to know which exceptions an implementation may want
  to throw.

Nope. Exception specifications are in the same bucket as return and argument types- they are part of the interface. If you can't conform to that specification, then don't implement the interface. If you never throw, then that's fine. There's nothing leaky about specifying exceptions in an interface.

Error codes are beyond bad. They're terrible. You have to manually remember to check and propagate them, every time, for every call. This violates DRY, for a start, and massively blows up your error-handling code. This repetition is a far bigger problem than any faced by exceptions. You can never silently ignore an exception, but people can and do silently ignore return codes- definitely a bad thing.


问:
What is wrong with the Unlicense?
I have often heard that I should not use the Unlicense because of issues regarding putting things into the public domain. However, I do not understand why this would be an issue for the Unlicense. The Unlicense attempts to put whatever is being unlicensed into the public domain, and if that works, awesome! However, the author of the Unlicense understands that putting something into the public domain is not so simple, it may even be impossible, and therefore the Unlicense contains a backup clause (the 2nd paragraph) which clearly states that everyone is free to do whatever they want with the Unlicensed software. The Unlicense even includes a disclaimer containing the usual "this software is provided as-is blah blah" legalese.

Is the Unlicense bad because it is short and doesn't define who the "unlicensor", the "unlicensee" and Santa Claus is? If yes, then what about the MIT/BSD-style licenses? They are generally considered to be valid, so why isn't the Unlicense? Is the opposition to public domain waivers with permissive license backup clauses, such as the Unlicense, and even the Creative Commons CC0, just FUD or are there really major legal issues with them?

Here is the full text of the Unlicense:

This is free and unencumbered software released into the public
  domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
  distribute this software, either in source code form or as a compiled
  binary, for any purpose, commercial or non-commercial, and by any
  means.

In jurisdictions that recognize copyright laws, the author or authors
  of this software dedicate any and all copyright interest in the
  software to the public domain. We make this dedication for the benefit
  of the public at large and to the detriment of our heirs and
  successors. We intend this dedication to be an overt act of
  relinquishment in perpetuity of all present and future rights to this
  software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to http://unlicense.org/

答:
(Disclaimer: IANAL - for reliable advice on legal issues, ask a lawyer.)

See the discussion on the OSI mailing list for some of the immediate issues with the license. My interpretation:

It's not global. It doesn't make sense outside of a commonwealth ecosystem,  is explicitly illegal in some places (Germany), and of unclear legality in others (Australia)

It's inconsistent. Some of the warranty terms cannot, logically, co-exist, given the current legal ecosystem, as written, with the licensing terms.

Its applicability is unpredictable. The license is short, clearly expressing intent, at the cost of not carefully addressing common license, copy-right and warranty issues. It leaves a lot of leeway interpretation - meaning that, in the US, it will take a few trials before you can reliably know when the license is applicable, and how.

Personally, I think of the license as having been written in human-readable pseudo-code, without having been properly compiled yet to a given set of legal systems.

Title: What is wrong with the Unlicense?


问:
Publish/Subscribe/Request for exchange of big, complex, and confidential data?
I am working on a project where a website needs to exchange complex and confidential (and thus encrypted) data with other systems. The data includes personal information, technical drawings, public documents etc.

We would prefer to avoid the Request-Reply pattern to the dependent systems (and there are a LOT of them), as that would create an awful lot of empty traffic.

On the other hand, I am not sure that a pure Publisher/Subscriber pattern would be appropriate -- mainly because of the complex and bulky nature of the data to be exchanged.

For that reason we have discussed the possibility of a "publish/subscribe/request" solution. The Publish/Subscribe part would be to publish a message to the dependent systems, that something is ready for pickup. The actual content is then picked up by old-school Request-Reply action.

How does this sound to you?

答:
Consider PubSubHubbub

PubSubHubbub works by first offering a general AtomPub feed with links to various hubs. Subscribers register with the hubs using a direct socket feed (typically reverse Ajax using Comet). This allows the hubs to push data out to subscribers on demand without consuming too many resources. Publishers send data to the hubs for dissemination. Hubs can be clustered.

In your situation, you could do the following (subject to your own data protection policies):

A new subscriber is provided with a secret symmetric key along with their login credentials

The subscriber registers with a hub to receive data

The publisher creates the data specific to a subscriber and sends it to the hub encrypted along with their symmetric key

The hub handles the process of sending the data to the subscriber

In the Java world, a combination of Jetty (version 7+), OData4J and Atmosphere would probably achieve most of what you need.


问:
Internship vs Open Source in terms of experience
I'm currently a second year undergraduate Computer Science student. I'm having a hard time deciding to either apply for an internship or spend the summer back home, working on some fields I feel I haven't yet got a good grasp of (OOP, algorithms) + working on one or two open source projects I found really attractive.

I don't really care about getting paid from doing the internship, I'm only looking for experience. I'll still do an internship next year since it's mandatory (University rules) and most probably the year after.

What weighs more for an employer and what would benefit me most in the long run?

答: Internship. You'll learn how to work with people and get references when looking for a job later.</p>


答: Internship. You can always hack for open source.</p>

Title: Internship vs Open Source in terms of experience

Body:
I'm currently a second year undergraduate Computer Science student. I'm having a hard time deciding to either apply for an internship or spend the summer back home, working on some fields I feel I haven't yet got a good grasp of (OOP, algorithms) + working on one or two open source projects I found really attractive.

I don't really care about getting paid from doing the internship, I'm only looking for experience. I'll still do an internship next year since it's mandatory (University rules) and most probably the year after.

What weighs more for an employer and what would benefit me most in the long run?


答: Internship shows you can work with people in an office setting and have an idea how offices work, a good recommendation from the company you intern for can show that you have programming skills and other important soft skills. Internships also have the potential to lead to a full time position within the company. Contributing to open source projects really just shows you can program. Basically working on open source projects is similar to community service, its helpful and can make you feel good, but its not the most efficient/best way to improve a resume.</p>


答:
Personally, I generally do not write unit tests for:

Changes to existing non-unit-tested (legacy) code. While theoretically it's never too late to start unit testing, in practice the gains from adding unit tests to code that was never TDDed are small. The sole advantage is regression prevention; you can see what effect a change makes on areas you may or may not have expected it to affect. However, the unit test only proves that the code still works the way it did when you wrote the test; because the test wasn't written based on the original requirements, the test does not prove the current implementation is "correct". Making unit-tested changes to such a codebase is even more of a nightmare in my experience then simply making the change and manually exercising affected areas of the program; you first have to write a proper unit test for the code in question (which may require refactoring the code to allow for mocking and other TDD-friendly architecture), prove it passes AND that the refactor didn't break anything (and when this is the first unit test ever written for a million-LoC codebase, that can be difficult), then change the test to expect something different and change the code to make the changed test pass.

UI Layout and top-level behavior. In some cases it's just not feasible; many IDEs with "designers" declare UI elements as private, and they shouldn't be public conceptually. Making them internal would require putting the unit tests into the same assemblies as production code (bad) and making them protected would require a "test proxy" that exposes what we need to know about the controls (also generally not the way it's done). Even if it was acceptable to make all controls public and thus have access to their type, position, formatting properties, etc, tests that verify the UI is designed the way you expect are extremely brittle. You can usually still unit-test event handlers in codebehinds/viewmodels and then it's trivial to prove that clicking the button fires the handler.

Database Persistence. This is, by definition, an integration test. You always mock the repository when dealing with code that passes data to the repository, and you mock the ORM's hooks when developing within the repository itself. While there are "database unit tests" and you can "mock" a database using something like SQLite, I find that these tests just never fit at the unit level.

Third-party code. You test YOUR code however you want, and trust that the developers of the third-party tools you're using (including components of the .NET Framework itself like WPF, WCF, EF, etc) did their job right, until proven wrong. A unit test that proves you make the correct WCF call does not require actually crossing the service proxy, and it is unnecessary to test that a particular WCF service call works correctly in a unit test (whether it works or not depends on environment-specific variables that may be perfect in a local testing environment but not at the build-bot, or in the QA, Staging or UAT environments; this is where higher-level integration, AAT and manual testing still have value).

In almost every other case, a test-first methodology has significant value in enforcing requirements and YAGNI, preventing regression, identifying requirements conflicts, etc. Even in cases of "trivial" code, that verification that "yes, this property does still return this value and so you can trust that in other tests" has value to me as a developer.


问:
switch statement - handling default case when it can't be reached
If I'm using a switch statement to handle values from an enum (which is owned by my class) and I have a case for each possible value - is it worth adding code to handle the "default" case?

```<code>enum MyEnum
{
    MyFoo,
    MyBar,
    MyBat
}

MyEnum myEnum = GetMyEnum();
switch (myEnum)
{
    case MyFoo:
        DoFoo();
        break;
    case MyBar:
        DoBar();
        break;
    case MyBat:
        DoBat();
        break;
    default:
        Log("Unexpected value");
        throw new ArgumentException()
}
</code>```

I don't think it is because this code can never be reached (even with unit tests).
My co-worker disagrees and thinks this protects us against unexpected behavior caused by new values being added to MyEnum.

What say you, community?

答:
I say:

Try adding another type to MyEnum. Then change this line:

```<code>MyEnum myEnum = GetMyEnum();
</code>```

to

```<code>MyEnum myEnum = SomethingElse;
</code>```

Then run your code with the default case and without the default case. Which behaviour do you prefer?

Having the default case can also be useful for trapping NULL values and preventing NullPointerExceptions.

Body:
I say:

Try adding another type to MyEnum. Then change this line:

MyEnum myEnum = GetMyEnum();

to

MyEnum myEnum = SomethingElse;

Then run your code with the default case and without the default case. Which behaviour do you prefer?

Having the default case can also be useful for trapping NULL values and preventing NullPointerExceptions.


答: Adding a Default case even if you never expect to reach it can be a good thing. It will make debugging much easier if your code throws a "This shouldn't have happened" exception right away rather than later in the program, trowing some mysterious exception or returning unexpected results with no error.</p>

Title: switch statement - handling default case when it can't be reached

Body:
If I'm using a switch statement to handle values from an enum (which is owned by my class) and I have a case for each possible value - is it worth adding code to handle the "default" case?

```<code>enum MyEnum
{
    MyFoo,
    MyBar,
    MyBat
}

MyEnum myEnum = GetMyEnum();
switch (myEnum)
{
    case MyFoo:
        DoFoo();
        break;
    case MyBar:
        DoBar();
        break;
    case MyBat:
        DoBat();
        break;
    default:
        Log("Unexpected value");
        throw new ArgumentException()
}
</code>```

I don't think it is because this code can never be reached (even with unit tests).
My co-worker disagrees and thinks this protects us against unexpected behavior caused by new values being added to MyEnum.

What say you, community?


答:
Including the default case doesn't change the way your code works, but it does make your code more maintainable. By making the code break in an obvious way (log a message and throw an exception), you're including a big red arrow for the intern that your company hires next summer to add a couple features. The arrow says: "Hey, you! Yes, I'm talking to YOU! If you're going to add another value to the enum, you'd better add a case here too." That extra effort might add a few bytes to the compiled program, which is something to consider. But it'll also save someone (maybe even the future you) somewhere between an hour and a day of unproductive head-scratching.

Update: The situation described above, i.e. protecting against values added to an enumeration at some later time, can also be caught by the compiler. Clang (and gcc, I think) will by default issue a warning if you switch on an enumerated type but don't have a case that covers every possible value in the enumeration. So, for example, if you remove the default case from your switch and add a new value MyBaz to the enumeration, you'll get a warning that says:

```<code>Enumeration value 'MyBaz' not handled in switch
</code>```

Letting the compiler detect uncovered cases is that it largely eliminates the need for that unreachable default case that inspired your question in the first place.

Body:
Including the default case doesn't change the way your code works, but it does make your code more maintainable. By making the code break in an obvious way (log a message and throw an exception), you're including a big red arrow for the intern that your company hires next summer to add a couple features. The arrow says: "Hey, you! Yes, I'm talking to YOU! If you're going to add another value to the enum, you'd better add a case here too." That extra effort might add a few bytes to the compiled program, which is something to consider. But it'll also save someone (maybe even the future you) somewhere between an hour and a day of unproductive head-scratching.

Update: The situation described above, i.e. protecting against values added to an enumeration at some later time, can also be caught by the compiler. Clang (and gcc, I think) will by default issue a warning if you switch on an enumerated type but don't have a case that covers every possible value in the enumeration. So, for example, if you remove the default case from your switch and add a new value MyBaz to the enumeration, you'll get a warning that says:

Enumeration value 'MyBaz' not handled in switch

Letting the compiler detect uncovered cases is that it largely eliminates the need for that unreachable default case that inspired your question in the first place.


答: Since you are looking for examples for IComparable, why not try something simple (everyone likes money): revenue and expenses ? Or compare different people's skills from a human resource perspective (creating simple but different  metrics for developers, engineers, accountants, machine operators...) You can build a very simple example based on this idea, touching every item on your list. So the answer "why use IComparable" would be something like being able to compare characteristics of dissimilar objects based on a single similar characteristic...  I like the idea of trying to get the same program to work with, or without IComparable or other nice interfaces.</p>