问:
Why are there so few C compilers?
C is one of the most widely-used languages in the world. It accounts for a huge proportion of existing code and continues to be used for a vast amount of new code. It's beloved by its users, it's so widely ported that being able to run C is to many the informal definition of a platform, and is praised by its fans for being a "small" language with a relatively clean set of features.

So where are all the compilers?

On the desktop, there are (realistically) two: GCC and Clang. Thinking about it for a few seconds you'll probably remember Intel exists as well. There are a handful of others, far too obscure for the average person to name and almost universally not bothering to support a recent language version (or often even a well-defined language subset, just "a subset"). Half of the members of this list are historical footnotes; most of the rest are very specialized and still don't actually implement the full language. Very few actually seem to be open-source.

Scheme and Forth - other small languages that are beloved by their fans for it - probably have more compilers than actual users. Even something like SML has more "serious" implementations to choose between than C. Whereas the announcement of a new (unfinished) C compiler aiming at verification actually sees some pretty negative responses, and veteran implementations struggle to get enough contributors to even catch up to C99.

Why? Is implementing C so hard? It isn't C++. Do users simply have a very skewed idea about what complexity group it falls in (i.e. that it actually is closer to C++ than Scheme)?

答:
C/C++ is unique amongst compiled languages in that it has 3 major implementations of a common specification.

Going by the rule of dismissing anything that's not used much, every other compiled language has 0 to 1.

And I think javascript is the only reason you need to specify 'compiled'.

Title: Why are there so few C compilers?


问:
Persistent RESTful state on client without cookies
I'm reading Roy Fielding's dissertation Architectural Styles and the Design of Network-based Software Architectures, which introduces the REST architectural style.

Roy explains that cookies are a violation of REST as they introduce stateful behaviour - cached responses may no longer apply (for example, hitting the back button), and server-side statelessness is a constraint of REST.

There is no reason why the client should not maintain state however, this is perfectly acceptable.

So if I have a RESTful API - for an online store for example - and I want to persist user state client side for a long time - between multiple sessions, are there any alternatives to using cookies to persist local state in modern browsers?

If it matters, I assume I'm running a javascript app in the browser.

Are there any ways I can create client-side-only cookies?

This question is related a similar question about cookies for authentication in REST...

UPDATE:

...but in my case I am not concerned with authentication strategies - just in how to persist state between sessions without sending state to the server.

To give the discussion better context, when talking about cookie based authentication, Roy says:

cookie-based applications on the Web will never be reliable.  The same functionality should have been accomplished via anonymous authentication and true client-side state.

答:
The point that Roy Fielding makes about cookies relates to sending these cookies to the server and maintaining state on the server based on those cookies.
Using a cookie purely client-side to store state for any period of time does not violate REST and actually doesn't concern the server-side at all. </p>

<p>EDIT:
You could store a cookie on a path that is not used by your server. That way you can access it from your javascript, but it will never get sent. </p>

ContentLicense: CC BY-SA 3.0

Body:
The point that Roy Fielding makes about cookies relates to sending these cookies to the server and maintaining state on the server based on those cookies.
Using a cookie purely client-side to store state for any period of time does not violate REST and actually doesn't concern the server-side at all.

EDIT:
You could store a cookie on a path that is not used by your server. That way you can access it from your javascript, but it will never get sent.


问:
Get inspired by real world objects and their interactions
Based on this question I think while the aim of OOP is not necessarily to copy real world objects, they could be source of inspiration to design a software or solve a problem or even learn the OOP itself.

For example for an application which deals with drawing, a Bitmap could be regarded like a Page, then as a page has back color, we can define a BackColor attribute for it. But we may realize a real page has not text color and it's the attribute of the pen, so we can define a class named Pen which is used for drawing and has a Color, LineWeight or ..

I always look for such analogy and inspirations of objects and their interactions when I develop a software, but I don't have a systematic or clear definition for what I am doing. I don't know which aspects of OOP I am copying.

Is it an acceptable technique in OOP? Do you use it? Is it possible that I violate an OOP guideline while I am using this technique?

I would like to know how this technique may help me to follow OO principles, so I can consciously use it.

答:
You're conflating multiple things when you over analyse the problem.

For example, when designing a page object that reflects a real-world sheet of paper you start to consider pens. Don't!

Take just the sheet of paper and consider its properties. It has a paper colour, texture, size.  Then do not try to map your preconceptions of computing terms to the object. A sheet of paper does not have a 'backcolour'. It has a colour, of the dye or material used in the manufacture of the paper. This is different to any concept of drawing using a pen that has 2 inks (assuming a very unusual pen that draws both a wide underlay and a ink nib).

Its important to try not to 'map' your concepts to the item. and simply look at the entity as an independant thing. consider what only it does, not what can be done to it or any other item. Then you'll find the properties fall into place, and you can move onto the next item, eg a pen and what properties it has.

When considering the object, also forget the methods you'll use to modify it. Start with the properties only. Methods are added as ways to interact and modify those properties so they are not really important in the design stage. eg. your paper can hold writing on it, so its property is that it can maintain text blocks in particular positions. You'll add a method to add new writing to it but when designing its the writing held by the paper that is much more important than how that writing gets written.

Hopefully this'll help clear your thoughts, design can be a bit vague and loose at the best of times!


答:
You don't have to use cookies, but if you have secured resources (eg my shopping basket as opposed to your basket) then you do need some way to detect which request corresponds to which of us. That id is usually held in a cookie as the detection is performed on the server via expensive auth mechanisms you want to store temporarily and repeat every request.

logically there's nothing stopping you from performing the authentication on every request. (except in the real world you won't do this unless you have, say, client certificates proving your identity to the server)

I imagine you could use some unique identifier that is known to the client, and use that as a mapping between client and secured user id after login instead, but they're hard to come by and maintain security.

Title: Persistent RESTful state on client without cookies

Body:
I'm reading Roy Fielding's dissertation Architectural Styles and the Design of Network-based Software Architectures, which introduces the REST architectural style.

Roy explains that cookies are a violation of REST as they introduce stateful behaviour - cached responses may no longer apply (for example, hitting the back button), and server-side statelessness is a constraint of REST.

There is no reason why the client should not maintain state however, this is perfectly acceptable.

So if I have a RESTful API - for an online store for example - and I want to persist user state client side for a long time - between multiple sessions, are there any alternatives to using cookies to persist local state in modern browsers?

If it matters, I assume I'm running a javascript app in the browser.

Are there any ways I can create client-side-only cookies?

This question is related a similar question about cookies for authentication in REST...

UPDATE:

...but in my case I am not concerned with authentication strategies - just in how to persist state between sessions without sending state to the server.

To give the discussion better context, when talking about cookie based authentication, Roy says:

cookie-based applications on the Web will never be reliable.  The same functionality should have been accomplished via anonymous authentication and true client-side state.


问:
c++11 random: why different range of int and real?
In the c++11, we now have <random> to produce random number.
About uniform distributions, we have following int_distribution and double_distribution:

```<code>uniform_int_distribution-produces integer values evenly distributed across a range

uniform_real_distribution-produces real values evenly distributed across a range
</code>```

The first produces random integer values i, uniformly distributed on the closed interval [a, b], but the second, ie real one, produces random floating-point values i, uniformly distributed on the interval [a, b)

Question: why int and real distribution have different range, ie for one b] is inclusive but for another b) is exclusive?

If it is related with the algorithms behind, I would like to know what are they and where are the differences. Or preferences about it.

答: Uniform_real_distribution had a closed range until 2006, after which it was changed to a half-open range because developers are said to be more comfortable with it.


答:
There's HTML5 local storage, which allows you to keep data without it contaminating the HTTP requests you make. It's intended for pretty much exactly this use case: complex Javascript applications that want to store persistent information locally.

http://www.w3.org/TR/webstorage/

Note that REST doesn't mean banning all state from the server, sometimes you genuinely want to update things; especially in the "airline ticket" example you might want to explicitly create a "reservation" object before payment with a POST that returns a URL for the reservation. The client then hangs onto the URL, but the server-side object exists to prevent booking the same seat twice.


问:
Should a newcomer to Perl learn both Perl 5 and 6?
I have started playing around with Perl 5 lately, and it seems very interesting. I would like to spend some time learning it more in depth when I can.

My question, since Perl 6 is slowly taking place (I believe...) and is said to break backward compatibility, is this: am I better learning Perl 5 and then Perl 6, or is learning Perl 6 directly a better time investment according to you?

If the changes from Perl 5 to 6 are making it hard to understand Perl 5, I should certainly start with Perl 5 to be able to read "old" scripts, then check Perl 6. There is also the "Perl 6 is not yet completely released" problem. I know there's an early adopter implementation for Perl 6, but if Perl 6 isn't officially released before some more years, I'll stick to 5 for now.

I would certainly like some insight on this. Feel free to discuss related stuff. My interest in scripting languages is fairly new.

Thanks!

答:
Perl 5 and Perl 6 are different languages, not two versions of the same. Perl 6 is heavily inspired by Perl 5, but not exclusively. I would suggest focusing on Perl 5 for now. If you watch the community (I'd suggest the Planet Perl Iron Man aggregator, you'll also see posts and content from the Perl 6 community and can keep an eye on it. Also, many features of Perl 6 are slowly coming back to Perl 5.

Also: Despite some people's hate for Perl, it's 2010 now, not 1995 anymore, and Perl has immensely moved forward, and continues to do so.

ContentLicense: CC BY-SA 2.5


问:
How to iterate through all permutations of valid links between nodes
Imagine a 2D area, with a number (array) of nodes (or points) defined within it, in arbitrary (but known) positions (integer x,y coordinates), like this:

From there I want to be able to, programmatically, add as many "links" as possible.
A "link" is a straight line between any two nodes, but a link cannot cross another link.
I already have a method created that can verify if two links cross. eg

With any given set of nodes, there is a finite number of ways that links can be laid out and I want to be able to generate all of those possible (valid) combinations.

However, I have absolutely no idea where to start on this.
I could randomly fill the nodes with valid links, but I don't know how to iteratively generate each possible permutation.

I'm guessing that some kind of algorithm exists for problems like this, probably based around recursion, but my searches so far have been fruitless.

I'm not looking for a coded solution, I can do that part. What I need is the high level design process, or algorithm, that can be followed to solve this problem.

答:
To cut down on the count of recursive calls I thought of introducing a strict ordering of links to be able to eliminate duplicates in the initialization phase (before any recursion):

on the links define any (arbitrary) strict ordering order

on the links define a method doesNotCrossWith() returning the set of links of higher order which this link does not cross (capable of executing in constant time after initialization)

on the links define a method doesNotCrossWithIntersectionOf(Set<Link>) returning the intersection of the parameter and doesNotCrossWith()

define the main recursive method getValidPermutations(Link link, Set<Link> linksNotForbidden) (Pseudocode):

```<code>Set<Set<Link>> validPermutationsIncludingLink;

// add the current link (alone) itself to the possible permutations (to be added to):
validPermutations.add(new Set(link));

Set<Link> linksStillAllowed = link.doesNotCrossWithIntersectionOf(linksAllowed);

for (Link otherLink : linksStillAllowed) {
    Set<Set<Link>> validPermutationsOfOther;

    //recursive call:
    for (Set<Link> validPermutation : getValidPermutations(otherLink, linksStillAllowed)) {
        validPermutation.add(otherLink);
        validPermutationsOfOther.add(validPermutation);
    }
    validPermutations.addAll(validPermutationsOfOther);
}

return validPermutations;
</code>```

call getValidPermutations for each link and build a union of the results.

The maximum recursive depth is the number of (possible) links n.

P.S.: With 7 nodes roughly arranged as in your example I get ~150ms running time with this implementation on my machine resulting in 37055 possible permutations, for a large number of nodes additional optimizations might be needed.

Body:
To cut down on the count of recursive calls I thought of introducing a strict ordering of links to be able to eliminate duplicates in the initialization phase (before any recursion):

on the links define any (arbitrary) strict ordering order

on the links define a method doesNotCrossWith() returning the set of links of higher order which this link does not cross (capable of executing in constant time after initialization)

on the links define a method doesNotCrossWithIntersectionOf(Set<Link>) returning the intersection of the parameter and doesNotCrossWith()

define the main recursive method getValidPermutations(Link link, Set<Link> linksNotForbidden) (Pseudocode):

Set<Set<Link>> validPermutationsIncludingLink;

// add the current link (alone) itself to the possible permutations (to be added to):
validPermutations.add(new Set(link));

Set<Link> linksStillAllowed = link.doesNotCrossWithIntersectionOf(linksAllowed);

for (Link otherLink : linksStillAllowed) {
    Set<Set<Link>> validPermutationsOfOther;

    //recursive call:
    for (Set<Link> validPermutation : getValidPermutations(otherLink, linksStillAllowed)) {
        validPermutation.add(otherLink);
        validPermutationsOfOther.add(validPermutation);
    }
    validPermutations.addAll(validPermutationsOfOther);
}

return validPermutations;

call getValidPermutations for each link and build a union of the results.

The maximum recursive depth is the number of (possible) links n.

P.S.: With 7 nodes roughly arranged as in your example I get ~150ms running time with this implementation on my machine resulting in 37055 possible permutations, for a large number of nodes additional optimizations might be needed.


问:
DDD friendly N-Tier alternatives
In Eric Evans book on DDD in the Modules section he says,

[tiered design] is attempting to address two legitimate issues. One is
  the logical division of concerns: One object has responsibility for
  database access, another for business logic, etc. This makes it easier
  to understand the functioning of each tier (on a technical level) and
  makes it easier to switch out layers. The trouble is that the cost to
  application development is not recognized. This is not a book on
  framework design, so I won’t go into alternative solutions to that
  problem, but they do exist. And even if there were no options, it
  would be better to trade this off for a more cohesive domain layer.

The other motivation for these packaging schemes is the distribution
  of tiers. This could be a strong argument if the code actually gets
  deployed on different servers. Usually it does not. The flexibility is
  sought just in case it is needed. On a project that hopes to get
  leverage from MODEL-DRIVEN DESIGN, this sacrifice is too great.

Can you give an example of an alternative solution to tiered applications that is DDD friendly?

答:
Tiers and DDD are orthogonal concerns.

Your tiers shouldn't care about the design of your objects.  That would imply tight coupling, an undesirable attribute.  In most tiered systems, there is some sort of data transfer object or data stream that is communicating information between the tiers. XML and JSON are common.  Each tier has its own objects it concerns itself with, and is not particularly concerned about some other tier's object design.

If you doubt this, then consider how DDD friendly your email server is.  While your email server does have a concept of what a "contact" is, it's highly likely that it's not exactly the same object as it is in your CRM system.  There are software mechanisms that can "sync" between email servers and CRM systems using the Adapter pattern, but it's not true blue DDD by any means.

Title: DDD friendly N-Tier alternatives


问:
Retry design for high volume
I have a Java system using ActiveMQ for messaging. And the system processes about 400 to 600 transactions a second and we have no issue when everything is running smoothly. The system also got to send these transactions to an external system.

When the external System is down for a prolonged time (say an hour or two), what we do is that we drop off failed messages that were not successfully sent to the external system during the outage to a queue (what we call Retry queue).

We need to process these messages in a timely manner so that we give the external system ample time to recover.

We tried several approaches and none seems to work perfectly. Most of them work when we deal with a fewer number of messages.

Approach #1:
We used ActiveMQ delay where we set timestamp in the JMS header (Please see here for more details: http://activemq.apache.org/delay-and-schedule-message-delivery.html) and it worked when there are like a few hundred or thousand messages in the queue.

We found message loss when there were like 500k or more messages.We found that messages appear mysteriously without giving us any clue.

For example, I see that messages disappeared even for 20k messages.

We set the delay as 5 minutes so that messages are tried for up to 12 times in an hour.
When the external system was down for an hour, we expected that all 20k messages were retried at least for 12 times.

What we observed was that when we consume every 5 minutes:

Attempt 1: 20k messages
Attempt 2: 20k messages

Attempt 7: 19987 messages
Attempt 10: 19960 messages
Attempt 12: 19957 messages

Sometimes all the 20k messages were processed but the test results were inconsistent.

Approach #2:

We used ActiveMQ's redelivery policy where we set the policy at the connection factory level, make the session transacted, throw an exception when the external system is down, so that the broker keeps redelivering the messages based on the redelivery policy configuration.
This approach too didn't work well when the outage lasts for a longer duration and we need t to have non-blocking consumers. It works at the dispatch queue level itself, straining the queue when there are a lot of incoming transactions.

Approach #3:

We used Quartz scheduler that wakes up every X minutes and it creates connection, consumers to get messages from the Retry queue, try processing them further and if the external system is still down, they put the failed message to the back of the queue. This approach has lot of issues such that it forced us to manage connections, consumers etc.,

For example, when there are a couple of messages in the queue, when we have more consumers than the number of messages, it resulted in a message picked up by a consumer, again the same consumer dropping off the message back into Retry (as the external system is still down) with another consumer picking it up, resulting in back and forth traveling of message between Consumer and Broker.

Approach #4:

We tried off storing the failed messages in DB and have the quartz scheduler run every X minutes to pick up the messages from the DB.

This is not optimized as well as it involves a lot of transaction check between DB consumer(s) running across multiple nodes and the DB.

My environment is Java, JBoss, ActiveMQ 5.9, MySQL 5.6 and  Spring 3.2.

I went thru several other approaches such as Retry template (from Spring) and Asynchronous Retry pattern with Java 7/8

My take on the issue is that most solutions work when there is minimum load and they seem to break when the outage lasts longer or when message volume is really high.

I am looking for something where I can store and forward failed messages.
For a 400 TPS system, in an hour, I may have 1.44 million messages.

If the external System is down, then how I process these 1.44 million messages giving each message an equal chance to be retried without losing messages or performance.

I am looking for a solution within the scope of the environment I have.

答:
Here is the assumption
each node has a message queue and all these nodes are using one DB.All these nodes are trying to send messages to one external system.

A slight change in third approach may work.

When a node starts create a table to store only new messages in case of external    system goes down.Let's say node1 has created messages_node1 table to store messages.

Now use case is if 3 nodes are running all of a sudden external system goes down, then each node should store newly arriving messages to corresponding table instead of en-queuing in MQ.Keep undelivered messages in queue itself.Thus no matter how much time external system takes to recover , existing messaging queue will not be loaded.Once node realizes that external system is up , then start en-queuing messages from corresponding table.

This approach solves lot problems
1.It does not depend recovery time of external system
2.It does not crash in case of too many incoming messages while external system is down.
3.Contention among nodes is minimized as each node has its own table.
4.Order of the messages is preserved to some extent.

You can write APIs to trigger these events.
Any correction with the above approach reply

Title: Retry design for high volume


答:
You can use cookies to maintain client state, because they are a client side storage mechanism. You can use other client side storage mechanisms, for example websql or localstorage.

The only problem with the cookies, that session cookies are violating the statelessness constraint. So unless you use session cookies you are okay. You should ask yourself what would happen when the server reboots. In the case of session cookies, your session will be lost. In the case of normal cookies, nothing relevant happens, your requests will be responded the same way as before.

I think when the server writes the cookies that is a grey zone thing, especially if we are talking about HTTP-only cookies (which are not accessible in browser javascript). In this case the service directly changes the client state. We could argue that set cookie headers are part of the representation, but that's a half truth I think. If your REST API has a different domain than your client, then set cookies only on the client domain and access their content for example with client side javascript if we are talking about browsers.

I don't know whether caching and cookies conflict with each other. I don't remember such an issue.

You should use the Authorization header instead of cookie, but I think it is not a tragedy if you set the username and password in a HTTP-only header. Or you set a persistent cookie with some hash (if it is registered on the server as a resource for a long while). I think it is still safer than storing this data for example in the localstorage.


答:
You've got quite hard a problem here.

I'm thinking of a method resembling Sieve of Eratosthenes .

First, you can "name" or "number" each link.
Let's assume we just have 5 nodes, so we'll have 10 links. Number each one from 1 until 10.

Now, we can put them all into an array.

Let's assume we have this list represents two links who intersect each other:

1 - 3

1 - 4

1 - 7

1 - 10

2 - 4

2 - 8

3 - 4

6 - 9

6 - 10

Now let's visualize this. First, I choose to draw link 1.

*For the images below, green means I choose to draw the link, red means the link cannot be drawn (because it intersects a selected link), and white means the link can be drawn.

Then, check each element from link #2 to link #10: does it intersect link #1? If yes, we should eliminate them (means we must not draw them). In this case : links #3, #4, #7, #10 (from the list above)

Now, you can choose which one is the next to draw: either #2, #5, #6, #8, or #9?
Let's say you choose #2, then you do the same procedure. Check the rest of the element: If it's already red then you may skip it, but if it's white (can still be drawn), check if it intersects link #2. Link #2 intersects with #4 and #8, but since #4 is already eliminated, we just eliminate #8.

Then, pick another link, and so on. Note that we can make use of two arrays: one integer array containing the links, and the other a boolean array to check if it's eliminated or not.

You can do this in iteration: picking which link to draw and eliminate the ones intersecting them.
This way, you can avoid drawing unnecessary links.

Well, it's just an idea that might work. But, I neither think this way is easy to implement, nor do I think it can be considered "efficient" in terms of complexity.

Title: How to iterate through all permutations of valid links between nodes

Body:
Imagine a 2D area, with a number (array) of nodes (or points) defined within it, in arbitrary (but known) positions (integer x,y coordinates), like this:

From there I want to be able to, programmatically, add as many "links" as possible.
A "link" is a straight line between any two nodes, but a link cannot cross another link.
I already have a method created that can verify if two links cross. eg

With any given set of nodes, there is a finite number of ways that links can be laid out and I want to be able to generate all of those possible (valid) combinations.

However, I have absolutely no idea where to start on this.
I could randomly fill the nodes with valid links, but I don't know how to iteratively generate each possible permutation.

I'm guessing that some kind of algorithm exists for problems like this, probably based around recursion, but my searches so far have been fruitless.

I'm not looking for a coded solution, I can do that part. What I need is the high level design process, or algorithm, that can be followed to solve this problem.


问:
GUI concept for a reactive, asynchronous graphical editor
I think I could describe this problem in an abstract way, but I suppose it will be easier to understand when I describe it in a real world environment.

The Problem

Imagine a graphical editor where different graphical objects can be inserted via drag and drop:

Now when I drop the half transparent object there. Through some heavy computations the following result is achieved:

Up until now we do the computation at the time when the user releases the mouse synchronously. Meaning, he waits lets say two seconds until he can use the program instead. As I said previously this is just a simplified example. It needs quite more than this interaction to have a two second calculation time, but it happens.

Now we thought it would be nice to do the whole computation asynchronously, so that the user use the rest of the application during this time. And there lies the problem The user could now in these two seconds trigger additional drops as he pleases.

Meaning he has dropped three objects (a,b,c) while not even the first was completely calculated (A).

Solution 1

The user can drop the objects as he pleases. The changes are accumulated after the first calculation is ready.

Problem with this solution is, that the user drops objects on the initial state of the worksheet probably assuming that the first object (a) was never inserted. It will definitively confuse the user.

Solution 2

The dropped objects (b,c) are just ignored. Of course the UI would be "blocked" with an overlay and drop would be made impossible.

Problem with this solution is, that I would have again blocked the UI only now with my own custom overlay.

The Question

Have you encountered any of these problems? Is there a smarter solution than any of the two presented?

答:
Solution 1 is the one preferred by most users, based on my experience. The problem you described, "he user drops objects on the initial state of the worksheet probably assuming that the first object (a) was never inserted," can be mitigated with a temporary placeholder visual that indicates an object was dropped, but its state is not yet computed. I would make the visual similar to the final result, but with a difference that indicates the final result is being computed. Also, have another visual somewhere, either in a status area, or as part of the temporary visual, with a small, unobtrusive animation, indicating calculations are occurring.

Finally, I would work hard to make these calculations faster. Perhaps there is a problem with the algorithm, or perhaps you need to pre-fetch some data remotely. The faster you can speed up the calculations, the more friendly your application will appear to the user.


问:
Should all possible counter-cases be tested?
I'm currently trying to unit test a behavior which, in some very particular cases, returns B instead of A. It may depend on the value of 3 different attributes for example.

How should I test this?

Test only the specific case where the behavior is true

Test the specific case and one other random combination of values for which the behavior isn't true

Test the specific case and all possible combinations

The last option seems like a maintenance nightmare as any new attribute or value for an attribute would require massive updates in all tests on behaviors that use these, but at least you would have 100% coverage of the behavior.

To give an example, we might want to know if a person is eligible for free tickles. To be eligible, you need to belong to category A, D and F, be more than 20 years old, be a lefty and have red hair.

Should I just test that "categories A or D or F + > 20yo + lefty + red hair" gives eligibility? Should I also test some random combination such as "E, 25yo, lefty, blond" is not flagged as eligible? Should I test absolutely every possible combination or category, below/above 20yo, hand and hair, one being true, all the others being false?

答: If the number of possible combinations is reasonably small, you can test all of them. But if it is not the case and it is very difficult to maintain tests that cover all possible inputs, I would recommend testing only the most typical cases and edge cases(if there are any). </p>


答:
For a long boolean expression you generally don't test every possible combination, but you test that each individual parameter has the appropriate effect.  For example, given the following expression to test:

```<code>(A or B or C) and D and E
</code>```

Test A by setting B and C false, and D and E true.  Toggling A should now toggle the result of the entire expression.

Test B by setting A and C false, and D and E true.  Toggling B should now toggle the result of the entire expression.

Likewise for the other variables.  You set each one up so you know it's the variable under test that's changing the result.

That gives you 5 tests (O(n)) instead of 32 (O(2n)), but still provides good coverage.

Title: Should all possible counter-cases be tested?

Body:
I'm currently trying to unit test a behavior which, in some very particular cases, returns B instead of A. It may depend on the value of 3 different attributes for example.

How should I test this?

Test only the specific case where the behavior is true

Test the specific case and one other random combination of values for which the behavior isn't true

Test the specific case and all possible combinations

The last option seems like a maintenance nightmare as any new attribute or value for an attribute would require massive updates in all tests on behaviors that use these, but at least you would have 100% coverage of the behavior.

To give an example, we might want to know if a person is eligible for free tickles. To be eligible, you need to belong to category A, D and F, be more than 20 years old, be a lefty and have red hair.

Should I just test that "categories A or D or F + > 20yo + lefty + red hair" gives eligibility? Should I also test some random combination such as "E, 25yo, lefty, blond" is not flagged as eligible? Should I test absolutely every possible combination or category, below/above 20yo, hand and hair, one being true, all the others being false?

Body:
For a long boolean expression you generally don't test every possible combination, but you test that each individual parameter has the appropriate effect.  For example, given the following expression to test:

(A or B or C) and D and E

Test A by setting B and C false, and D and E true.  Toggling A should now toggle the result of the entire expression.

Test B by setting A and C false, and D and E true.  Toggling B should now toggle the result of the entire expression.

Likewise for the other variables.  You set each one up so you know it's the variable under test that's changing the result.

That gives you 5 tests (O(n)) instead of 32 (O(2n)), but still provides good coverage.


问:
Is checking that a property doesn't throw an exception a valid unit test?
I'm writing tests for the following class:

```<code>public class Foo : INotifyPropertyChanged
{
  private int _failCount;
  private int _totalCount;
  public double FailRate
  {
     get
     {
        double returnValue = 0.0;
        if (_totalCount > 0)
        {
           returnValue = (double) _failCount / _totalCount * 100;
        }
        return returnValue;
     }
  }

  public int FailCount
  {
     get { return _failCount; }
     set
     {
        if (value != _failCount)
        {
           _failCount = value;
           onNotifyPropertyChanged();
           onNotifyPropertyChanged("FailRate");
        }
     }
  }
  public int TotalCount
  {
     get { return _totalCount; }
     set
     {
        if (value != _totalCount)
        {
           _totalCount = value;
           onNotifyPropertyChanged();
           onNotifyPropertyChanged("FailRate");
        }
     }
  }
  protected virtual void onNotifyPropertyChanged([CallerMemberName]string name = null)
  {
     if (PropertyChanged != null)
     {
        PropertyChanged(this, new PropertyChangedEventArgs(name));
     }
  }

  public event PropertyChangedEventHandler PropertyChanged;
}
</code>```

I was writing some tests for the FailRate property, and it occurred to me that I should probably make sure that getting FailRate doesn't throw an exception.  The case being someone (probably me) removes the if (_totalCount > 0) check, and then getting FailRate throws a DivideBy0Exception.

So I wrote a test that makes sure getting FailRate doesn't throw an exception.

```<code>[TestMethod]
public void GettingTheFailRateWhenTheTotalCountIsZeroDoesNotThrowAnException()
{
   Defect defect = new Defect();
   defect.FailCount = 0;
   defect.TotalCount = 0;
   double dummy = defect.FailRate;
}
</code>```

However, that test doesn't have an explicit check, and will pass as long as the property doesn't throw an exception.

Is just checking that a property doesn't throw an exception a "valid" test?

答:
Is just checking that a property doesn't throw an exception a "valid" test?

Yes, it can be. In this example, I would explicitly check that FailRate returns 0 for that input.

And I certainly would validate that the bad input is handled properly by writing the test. I'd probably write a test with a negative value as well to make sure it was > 0 rather than == 0 since it takes like 10 seconds and better encodes the requirements into the test.


答:
In my opinion, yes. All logic - meaning all conditional code - can be tested. And this is an edge case, too.

By the way, this code is not thread-safe - _totalCount could change between reading its value in if and actually dividing by it. But thread-safety might not be among your requirements.

As for the check being explicit or not, it's a matter of taste. You could catch DivideByZeroException and call Assert.Fail (or whatever it's called) in the catch block. More verbose, but very clear for the reader. As a fellow coder, I'd be okay either way.

And that the routine being tested is so simple? Mixing imperial and metric units crashed a space probe worth $125 million, and this doesn't sound like a very sophisticated bug.

Maybe someone is going to write a similar piece of code for this project - calculating estimated time left, for instance - and having seen this test will prevent a mental lapse by reminding them there are zeroes in this world and zero can't be divided by? It can't hurt...

Title: Is checking that a property doesn't throw an exception a valid unit test?

Body:
I'm writing tests for the following class:

```<code>public class Foo : INotifyPropertyChanged
{
  private int _failCount;
  private int _totalCount;
  public double FailRate
  {
     get
     {
        double returnValue = 0.0;
        if (_totalCount > 0)
        {
           returnValue = (double) _failCount / _totalCount * 100;
        }
        return returnValue;
     }
  }

  public int FailCount
  {
     get { return _failCount; }
     set
     {
        if (value != _failCount)
        {
           _failCount = value;
           onNotifyPropertyChanged();
           onNotifyPropertyChanged("FailRate");
        }
     }
  }
  public int TotalCount
  {
     get { return _totalCount; }
     set
     {
        if (value != _totalCount)
        {
           _totalCount = value;
           onNotifyPropertyChanged();
           onNotifyPropertyChanged("FailRate");
        }
     }
  }
  protected virtual void onNotifyPropertyChanged([CallerMemberName]string name = null)
  {
     if (PropertyChanged != null)
     {
        PropertyChanged(this, new PropertyChangedEventArgs(name));
     }
  }

  public event PropertyChangedEventHandler PropertyChanged;
}
</code>```

I was writing some tests for the FailRate property, and it occurred to me that I should probably make sure that getting FailRate doesn't throw an exception.  The case being someone (probably me) removes the if (_totalCount > 0) check, and then getting FailRate throws a DivideBy0Exception.

So I wrote a test that makes sure getting FailRate doesn't throw an exception.

```<code>[TestMethod]
public void GettingTheFailRateWhenTheTotalCountIsZeroDoesNotThrowAnException()
{
   Defect defect = new Defect();
   defect.FailCount = 0;
   defect.TotalCount = 0;
   double dummy = defect.FailRate;
}
</code>```

However, that test doesn't have an explicit check, and will pass as long as the property doesn't throw an exception.

Is just checking that a property doesn't throw an exception a "valid" test?


问:
How should I unit test mathematical formulae?
I have a number of functions that are pretty close to the mathematical definition of a function. For example, a simplified version of one of these functions may look like:

```<code>int function foo(int a, int b) {
    return a * b;
}
</code>```

I'd like to unit test them, but I'm not sure what the best way to approach those tests, as these functions have very large ranges for parameter values. Every approach I've come up with feels lacking:

If I test with a discrete pre-defined subset of possible values, I fear the set I choose may not be representative of the whole, leading to a potentially endless cycle of adding new values to the subset every time an unexpected value is found. This seems like defeating the point of having a unit test in the first place.

If I test with a discrete subset of possible values that's randomly determined, I inherit all of the problems of picking the subset manually as well as the real chance that tests will fail randomly every run.

If I test with every possible value (e.g. 0 to 264), the tests will take forever.

My final thought on how to approach the problem was to avoid testing the implementation of the function entirely, either by:

Only testing that the function accepts two integers and returns an integer, or

Not testing the function at all

But if I'm not testing the functions at all—either in practice or in principle—I'm not sure how I can guarantee the correctness of the functions in the case of an eventual refactor.

What is the best way to test functions that have completely deterministic output, but can operate on a large range of possible inputs?

答:
Mathematical functions are especially amenable to property-based testing.

With property-based testing, you declaratively define high-level invariants that your API must satisfy. The test framework generates a large number of test cases and tries to find a counterexample to your invariants.

Let's write some properties for your example - a function * which multiplies two numbers. Property-based testing originated in the functional programming community, so I'm going to use QuickCheck (a Haskell-based tool), but similar test frameworks are now available for most imperative languages.

We define properties by writing functions which take arbitrary values as arguments. For each of these functions, QuickCheck will randomly generate 100 combinations of arguments and check that the property holds for each of them.

```<code>prop_commutative x y = (x * y) == (y * x)

prop_associative x y z = (x * y) * z == x * (y * z)

prop_distributive x y z = x * (y + z) == (x * y) + (x * z)

prop_identity x = (1 * x) == x

prop_zero x = (0 * x) == 0
</code>```

Our tests look like mathematical definitions! They say "For all x and y, x * y equals y * x" and so on. If, say, you were developing a set of trigonometric functions, you could write a similar set of properties testing things like the double-angle formulae. Property-based testing really comes into its own for  mathematical programming.

The output of running these tests looks like this:

```<code>=== prop_commutative ===
+++ OK, passed 100 tests.

=== prop_associative ===
+++ OK, passed 100 tests.

=== prop_distributive ===
+++ OK, passed 100 tests.

=== prop_identity ===
+++ OK, passed 100 tests.

=== prop_zero ===
+++ OK, passed 100 tests.
</code>```

When a property is untrue, QuickCheck finds a counter-example. This property doesn't hold for numbers less than 1:

```<code>prop_multiplyingMakesItBigger x y = (x * y) > x
</code>```

QuickCheck spots our mistake and prints out the values of x and y which disproved our property:

```<code>=== prop_multiplyingMakesItBigger ===
*** Failed! Falsifiable (after 1 test):
0
0
</code>```

QuickCheck tests your properties with values you hadn't anticipated, which helps you find bugs.

You can also use property-based testing to test against a model. If you have a naïve implementation of a function which you know is correct (but perhaps is not fast enough), you can use it as a model for regression testing of an improved version. Here's an example where we check that * is equivalent to repeated adding:

```<code>prop_repeatedAddingModel (NonNegative (Small x)) y = (x * y) == (foldr (+) 0 (replicate x y))
</code>```

Here I'm also demonstrating how to use QuickCheck to constrain test values. Our model doesn't work for negative x, and is prohibitively slow for large x, so we tell QuickCheck that we want x to be small and non-negative.

Real World Haskell has a great chapter on QuickCheck, with lots of examples.

Body:
Mathematical functions are especially amenable to property-based testing.

With property-based testing, you declaratively define high-level invariants that your API must satisfy. The test framework generates a large number of test cases and tries to find a counterexample to your invariants.

Let's write some properties for your example - a function * which multiplies two numbers. Property-based testing originated in the functional programming community, so I'm going to use QuickCheck (a Haskell-based tool), but similar test frameworks are now available for most imperative languages.

We define properties by writing functions which take arbitrary values as arguments. For each of these functions, QuickCheck will randomly generate 100 combinations of arguments and check that the property holds for each of them.

prop_commutative x y = (x * y) == (y * x)

prop_associative x y z = (x * y) * z == x * (y * z)

prop_distributive x y z = x * (y + z) == (x * y) + (x * z)

prop_identity x = (1 * x) == x

prop_zero x = (0 * x) == 0

Our tests look like mathematical definitions! They say "For all x and y, x * y equals y * x" and so on. If, say, you were developing a set of trigonometric functions, you could write a similar set of properties testing things like the double-angle formulae. Property-based testing really comes into its own for  mathematical programming.

The output of running these tests looks like this:

=== prop_commutative ===
+++ OK, passed 100 tests.

=== prop_associative ===
+++ OK, passed 100 tests.

=== prop_distributive ===
+++ OK, passed 100 tests.

=== prop_identity ===
+++ OK, passed 100 tests.

=== prop_zero ===
+++ OK, passed 100 tests.

When a property is untrue, QuickCheck finds a counter-example. This property doesn't hold for numbers less than 1:

prop_multiplyingMakesItBigger x y = (x * y) > x

QuickCheck spots our mistake and prints out the values of x and y which disproved our property:

=== prop_multiplyingMakesItBigger ===
*** Failed! Falsifiable (after 1 test):
0
0

QuickCheck tests your properties with values you hadn't anticipated, which helps you find bugs.

You can also use property-based testing to test against a model. If you have a naïve implementation of a function which you know is correct (but perhaps is not fast enough), you can use it as a model for regression testing of an improved version. Here's an example where we check that * is equivalent to repeated adding:

prop_repeatedAddingModel (NonNegative (Small x)) y = (x * y) == (foldr (+) 0 (replicate x y))

Here I'm also demonstrating how to use QuickCheck to constrain test values. Our model doesn't work for negative x, and is prohibitively slow for large x, so we tell QuickCheck that we want x to be small and non-negative.

Real World Haskell has a great chapter on QuickCheck, with lots of examples.


问:
Typedefs to convey relations between classes
I'm wondering if the following use of typedefs is any good practice, or if there are any downsides to it.

Basically I have alot of "data"-structs, which are intended to be used in (globally unique) containers, and they hold indices to other (globally unique) containers, the reason is to keep memory access localized. Rather than having the indice types be generic size_t I thought of naming them as follows for clarity:

```<code>typdef uint32_t MeshID;

typedef Mat4 Transform;
typedef std::vector<Transform>::size_type TransformIndex;

struct AABB
{
    AABB(const Vec3& center, const Vec3& extent);

    typedef std::vector<ModelMesh>::size_type AABBIndex;

    Vec3 mAABBCenter;
    Vec3 mAABBExtent;
};

struct ModelMesh
{
    ModelMesh(const MeshID meshID, const uint32_t aabbIndex, const uint32_t transformIndex);

    typedef std::vector<ModelMesh>::size_type ModelMeshIndex;

    const MeshID mMeshID;

    const AABB::AABBIndex mAABBIndex;
    const TransformIndex mTransformIndex;
};

struct ModelNode
{
    ModelNode(const uint32_t aabbIndex, const uint32_t transformIndex);

    typedef std::vector<ModelNode>::size_type ModelNodeIndex;

    const ModelNodeIndex mNodeStartIndex;
    const ModelNodeIndex mNodeEndIndex;

    const ModelMesh::ModelMeshIndex mMeshStartIndex;
    const ModelMesh::ModelMeshIndex mMeshEndIndex;

    const AABB::AABBIndex mAABBIndex;
    const TransformIndex mTransformIndex;
};

struct Model
{
    Model(const std::string& name, const Mat4& initialTransform, const Vec3& minBounds, const Vec3& maxBounds, const MeshID meshID, MaterialPtr material);
    Model(DX11Renderer& renderer, const JonsPackagePtr jonsPkg, const PackageModel& pkgModel, LoadMaterialFunc loadMaterialFunction);
    ~Model();

    bool operator==(const Model& m);
    bool operator==(const std::string& modelName);

    const std::string mName;
    const size_t mHashedID;

    const ModelNode::ModelNodeIndex mRootNodeIndex;
};
</code>```

The motivation is so that the relation between the structs are clear. The downside is perhaps alot of definitions? Too chatty?

Overall, is this good practice?

答:
In general, using a typedef is never really a bad thing, all it does is tell the compiler that when you use, say "Transform," you actually meant "Mat4." All typedef does is make it easier for the programmer to specify between separate types. There is usually no downside to using typedef.

Overall, it is neither a good nor bad practice. Just make sure you can remember what each typedef stands for.


答:
The heart of creating abstractions is to give things a good name, which makes clear what a specific data type represents. And that's what you are doing here, no less, no more. </p>

<p>Creating the right abstractions is what makes actually the difference between good code and bad code, so yes, assumed these abstractions serve you well, that is good practice. </p>

Title: Typedefs to convey relations between classes

Body:
I'm wondering if the following use of typedefs is any good practice, or if there are any downsides to it.

Basically I have alot of "data"-structs, which are intended to be used in (globally unique) containers, and they hold indices to other (globally unique) containers, the reason is to keep memory access localized. Rather than having the indice types be generic size_t I thought of naming them as follows for clarity:

```<code>typdef uint32_t MeshID;

typedef Mat4 Transform;
typedef std::vector<Transform>::size_type TransformIndex;

struct AABB
{
    AABB(const Vec3& center, const Vec3& extent);

    typedef std::vector<ModelMesh>::size_type AABBIndex;

    Vec3 mAABBCenter;
    Vec3 mAABBExtent;
};

struct ModelMesh
{
    ModelMesh(const MeshID meshID, const uint32_t aabbIndex, const uint32_t transformIndex);

    typedef std::vector<ModelMesh>::size_type ModelMeshIndex;

    const MeshID mMeshID;

    const AABB::AABBIndex mAABBIndex;
    const TransformIndex mTransformIndex;
};

struct ModelNode
{
    ModelNode(const uint32_t aabbIndex, const uint32_t transformIndex);

    typedef std::vector<ModelNode>::size_type ModelNodeIndex;

    const ModelNodeIndex mNodeStartIndex;
    const ModelNodeIndex mNodeEndIndex;

    const ModelMesh::ModelMeshIndex mMeshStartIndex;
    const ModelMesh::ModelMeshIndex mMeshEndIndex;

    const AABB::AABBIndex mAABBIndex;
    const TransformIndex mTransformIndex;
};

struct Model
{
    Model(const std::string& name, const Mat4& initialTransform, const Vec3& minBounds, const Vec3& maxBounds, const MeshID meshID, MaterialPtr material);
    Model(DX11Renderer& renderer, const JonsPackagePtr jonsPkg, const PackageModel& pkgModel, LoadMaterialFunc loadMaterialFunction);
    ~Model();

    bool operator==(const Model& m);
    bool operator==(const std::string& modelName);

    const std::string mName;
    const size_t mHashedID;

    const ModelNode::ModelNodeIndex mRootNodeIndex;
};
</code>```

The motivation is so that the relation between the structs are clear. The downside is perhaps alot of definitions? Too chatty?

Overall, is this good practice?

Body:
The heart of creating abstractions is to give things a good name, which makes clear what a specific data type represents. And that's what you are doing here, no less, no more.

Creating the right abstractions is what makes actually the difference between good code and bad code, so yes, assumed these abstractions serve you well, that is good practice.


问:
Pattern for separating UI code from logic in Wicket
I'm using Apache Wicket for developing web apps, I have developed a few  for the last year  and it has been great; today I was looking at a few pages and most of them look like this:

```<code>public class MyPage extends MyBasePage
{
    public MyPage() {
        constructUI();
    }

    private void constructUI() {
        //first build all the models..
        IModel aModel = new SomeModel(new SimeObject());

        //then build forms, links and buttons like this
        Form myForm = new Form("myForm", aModel) {

            //notice that the submit logic is not implemented here
            private void onSubmit() {
                myForm_submit();
            }
        }
    }

    private void myForm_submit() {
        //handle the form submision here, validation, service calling etc..
    }
}
</code>```

I usually handle the form submission and link/button clicking on separate methods in order to keep the constructUI method as short as possible, most pages have 1 or 2 grids, and 2-3 forms for different actions, for my specific needs and use cases this practice gives me these benefits:

The UI can be constructed/deconstructed in different ways (to refactor the markup for example) without having to copy/paste/move-around the whole submit handling logic

Having *_submit, *_click methods allows to easily navigate the class using "ctrl+o" (on Eclipse) to filter and find methods

So my question is, if there exists some software pattern that would allow to separate the "constructUI" logic into a different class, or something similar, because some pages are component heavy (even using custom components) and "constructUI" gets too large.

答:
If your pages get big try to decompose them into smaller Panels.

I dont like in your code that you have only one method in the constructor. If it it like this i would omit this method and write all in the constructor.

We use an approach where every component is created within a function and returned from there. This allows us to keep every information about a component in one place. Additionally the name of the function returning the component is the same as its wicket:id. This helps further to better read the code between java and html. Our pages/panels look like this:

```<code>public class MyPage extends MyBasePage
{

    Form form;

    public MyPage() {
        form = form();
        form.add(submit());
    }

    private Form form() {
        Form myForm = new Form("form", aModel);
        myForm.setOutputMarkupPlaceholderTag(true);
        return myForm;
    }

    private AjaxSubmitLink submit(){
        AjaxSubmitLink asl = new AjaxSubmitLink("submit") {

            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                someService.saveSomeEntity(aEntity);
                target.add(aFeedbackPanel);
            }

            @Override
            protected void onError(AjaxRequestTarget target, Form<?> form) {
                target.add(aFeedbackPanel);
            }

            @Override
            protected void onConfigure() {
                setVisible(ifSomeCondition());
                setEnabled(ifSomeOtherCondition());
            }

        };
        asl.setOutputMarkupId(true);
        asl.add(new SomeBehavior());
        return asl;
    }
}
</code>```

Body:
If your pages get big try to decompose them into smaller Panels.

I dont like in your code that you have only one method in the constructor. If it it like this i would omit this method and write all in the constructor.

We use an approach where every component is created within a function and returned from there. This allows us to keep every information about a component in one place. Additionally the name of the function returning the component is the same as its wicket:id. This helps further to better read the code between java and html. Our pages/panels look like this:

public class MyPage extends MyBasePage
{

    Form form;

    public MyPage() {
        form = form();
        form.add(submit());
    }

    private Form form() {
        Form myForm = new Form("form", aModel);
        myForm.setOutputMarkupPlaceholderTag(true);
        return myForm;
    }

    private AjaxSubmitLink submit(){
        AjaxSubmitLink asl = new AjaxSubmitLink("submit") {

            @Override
            protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
                someService.saveSomeEntity(aEntity);
                target.add(aFeedbackPanel);
            }

            @Override
            protected void onError(AjaxRequestTarget target, Form<?> form) {
                target.add(aFeedbackPanel);
            }

            @Override
            protected void onConfigure() {
                setVisible(ifSomeCondition());
                setEnabled(ifSomeOtherCondition());
            }

        };
        asl.setOutputMarkupId(true);
        asl.add(new SomeBehavior());
        return asl;
    }
}


问:
Can I modify existing GPL software to use a proprietary (closed-source) library and then distribute one or both?
Say I have GPL software A and proprietary library B. I modify A to use B. Am I then free to distribute A by itself? The GPL FAQ seems to indicate that is there case here:
https://www.gnu.org/licenses/gpl-faq.html#FSWithNFLibs

Now what if I already own the license to B. Am I now able to distribute both A and B together even though B is closed-source? I don't see how I could be forced to license B as GPL since it already existed independent from and is in no way derived from A.

All linking to B is done dynamically at runtime.

答:
You can distribute software A as GPL, but only without the additional features provided by proprietary library B.  If you bind new features in software A to proprietary library B, then you must also distribute B's source code under the GPL.  Binding the two softwares in this fashion creates a derivative work.

The only way you might get away with licensing A separately is by dynamically binding library B at runtime.  If the library isn't made available by the user, the features simply won't be present in Software A.  But software A must be able to substantially function without library B.

There are other considerations as well.  The FSF only considers such an arrangement valid if the communication between Software A and Library B "takes place at arm's length."  The exact meaning of "arm's length" is not specifically stated by the FSF, but it's probably fair to say that your software can't be the only software that uses library B.

Further, to fulfill the spirit of the GPL, you must allow the consumer of Software A to substitute a suitable library for Library B, or even to write their own.  That's the freedom that the GPL is designed to provide; the freedom to use your software in any way they see fit, including redistributing it to others (provided they also follow the GPL).

So it is imperative that Software A's functionality is not impaired in any substantial way by the absence of proprietary library B.


答:
A lot depends on what will be riding on the software.

If this is your basic Web app or your basic iPhone game, you probably don't have to do THAT much.

If human lives will be riding on it, you darned well better believe you need to test the holy crap out of it.

The Therac 25 story should be well known by now.  Several people died as a direct result of its software defect.

The Uwatec Aladin Air X Nitrox dive computer story is not as well known.  Five divers were bent into pretzels, suffering major permanent neurological injuries, by its software defect.  (Full Disclosure: I know one of the injured divers involved, slightly.)


问:
Selecting the (right?) technology and environment
We are two developers on the edge of starting new web product development.

We are both fans of lean start-up approach and would like to practice continuous deployment.

Here comes the dilemma - we are both coming from a C# / Windows background and we need to decide between:

Stick to .NET and Windows, we will not waste time on learning new technologies and put all our effort in the development.

Switch to Ruby on Rails and Linux which has a good reputation of fast ramp up and vast open source support. The negative side is that we will need to put a lot of effort in learning Ruby, Rails and Linux...

What would you do? What other considerations should we take?

答: Well the leanest option is to use .NET, as the effort you spend in learning the other platform is (from the business perspective) effort wasted on not bringing the product to your customers.</p>


问:
Object Oriented Analysis and Design and DDD together
I fear this question seems to broad, so I'll try to explain what I mean with some detail. I couldn't, however, find a way to divide it into other questions. If that's really the case, I gladly accept suggestions on how to break this question down in more focused ones.

I work with object oriented programming and one of the first things I've heard about was the process of OOAD where starting with requirements, mainly in the form of use cases, we figure out the domain model classes we are going to need and the relationships between those classes.

On the other hand, on the last few weeks, I've been studying about Domain-Driven Design and there are many things that seems to help a lot with object oriented design. One of those is the division of the application with bounded contexts which solves the problem of confusions about the meaning of a certain term from the domain. Another things that seems to help a lot is the idea of entities, value objects, aggregates, repositories, factories, services and domain events.

Now, when programming, it's clear how we implement lots of those things with object orientation and classes. My doubt is: how we can join the process of OOAD and the use of DDD?

I mean, when planing, without coding anything, how do we join OOAD and DDD? OOAD puts enphasis on some work on paper before coding, like use cases, user stories, diagrams and so on. DDD doesn't seem to talk about this kind of things. How DDD enters this design phase of the project?

I imagine something like this: we first understand the domain, then divide it into subdomains, then for each subdomain we perform the process of OOAD, writing use cases and so on and when making the classes we keep in mind DDD ideas. Is it like that?

答: Eric Evans has said that DDD is just (one flavor of) good object-oriented design. He just wrote it down and gave it a catchy name. The two are not at odds, they are, in fact, one and the same.</p>


问:
How does this kind of application and DDD relate?
In Domain-Driven Design the application is divided, as I understand, into four layers:

Presentation Layer

Application Layer

Domain Layer

Infrastructure Layer

I understand this well, for instance, when developing desktop applications with, for instance, WPF on Windows.

Now, there's another kind of application that personally I find very important today. I don't know if there's one technical term yet for this kind of application (probably there is but I didn't find it yet), but I'll describe it.

We have one server hosting one N-tier application that has one RESTful Web API where clients can make requests. The other tiers are for background processing and communicating with devices, sending notifications and so on. This kind of architecture is seem on Microsoft Azure Cloud Services, for instance, where we can host multiple web roles (the Web API, for instance) and multiple worker roles (which do background processing).

Now I fail to see how can I relate this to the kind of division DDD does of an application.

The domain layer is of course on the server and the requests to the API as well as the background processing have side effects on the domain model. The infrastructure layer is also on the server.

On my understanding, the application layer is this whole N-tier application (in Azure case, composed of all web and worker roles).

But finally, there's no presentation. This thing is an API, it is built to deal with tons of devices. Web browsers, smartphones, tablets and so on.

I'm trying to benefit from DDD on this kind of application, but I'm failing to see how both relate. How does this kind of application and DDD relate and how can one benefit from DDD on those scenarios?

答: I don't think they necessarily relate at all. DDD is about designing software from a business domain perspective, utilizing an ubiquitous language that you and your customer both understand. Many software developers mistake it for a programming technique, but it's more of a way to organize potential software structures (i.e. classes) around business domain concepts. Software layers don't really have much to do with that, inasmuch as they're merely a different (but sometimes complementary) abstraction.</p>


问:
cpp and h/hpp #include: "why" question
Why does the source include a header and not also the other way around? I googled it but only found questions regarding the use of header files, how to include them but nowhere to say why it is like it is.
If the header is merely the declaration, how does the compiler know the definition only from it?

For example: take foo.cpp, bar.h, bar.cpp. This is what everybody does:

in foo.cpp:

#include "bar.h"

but the bar.cpp is not included neither in the bar.h or foo.cpp. That's why I deem logical that bar.cpp be included in bar.h and so, indirectly in foo.cpp.

答:
Your question indicates that you don't understand the compilation process (most of this will apply to c as well as c++.)

The fundamental unit of compilation is a source file; for C++ the convention is to use the .cpp file extension. The extension could be anything, but most compilers use the extension to determine how to process the file, ex. .cpp means c++, .o means object, .c means straight c, etc. Source files are complied into object (nominally .obj or .o) files. Object files are linked together to create executable files.

The compiler doesn't know anything about header files. There is a pre-processor that replaces the #include directives with the content of the header file, and processes other pre-processor directives, the resulting output is what the compiler sees as input; this is the reason why headers are included in source files and not vice versa.

Header files aren't strictly necessary to compile source to object; they are a tool to manage complexity, organize and modularize your source files. As the other answers have explained, when foo.cpp needs to reference something in bar.cpp, say baz(), foo.cpp needs to have some descriptive information about baz() so it can generate a reference that the linker can resolve.

One could simply put this information in foo.cpp, but this would duplicate the information in bar.cpp. The solution to this duplication is to put all the descriptive information in another file, which we call a header file (nominally .h or .hpp.) With bar.h the information that needs to be included in foo.cpp and bar.cpp is only in one file, which is inserted into the file when the pre-processor finds the #include directive. This becomes invaluable as the complexity of the project increases.

Much of the compilation process is hidden behind an IDE or a makefile. Compiling a small project by hand will be very instructive in learning how the compilation process actually works. The first time I had to write a .makefile from scratch in school all mystery about the compilation process vanished; I had to learn all the details to accomplish the task.

Compiling and linking your example would be 3 operations, in two stages:

Compile the source files:

Compile foo.cpp into foo.o (ex. gcc -c -o foo.o foo.cpp)

Compile bar.cpp into bar.o (ex. gcc -c -o bar.o bar.cpp)

Link the object files:

link foo.o and bar.o into program (ex. gcc -o program foo.o bar.o)

During the compilation stage each file is processed individually. The resulting object files contain machine code and external references (things not in the source file, but located some other source file.)

The final step is to link the objects, this is when the references are resolved, if you forget to include the object file in the link command, it will fail with unresolved external references; this is the step where all the information is needed. Modern compilers can handle all those steps with a single command, but that hides the process.

Title: cpp and h/hpp #include: "why" question


问:
Making an automotive system more 'modular' in terms of software?
I am working on an automotive project that we are supposed to make more modular. I am a software specialist and I have very little knowledge of automotive hardware. I don't have any requirements or details about the project other than "making it more modular/portable" and "think in terms of software not hardware". By making it more modular they mean that they want to be able to pick any car and replace its conventional battery or pump with a different type without having to redesign the entire system.

So far the only thing I have come up with is to separate the system into two layers with the first layer having the general code that can be reused in all cars and the second layer has code specific to each component. Of course I don't have the actual source code. I think I am required to produce a general software architecture that they can use for implementing all their systems. I don't have any other idea at the moment.

Any help, direction or source of information is appreciated.

EDIT: I am working with a few electrical engineers and they have some idea about cars. So I am not alone. But still we are lost as they want a modular system and want us to think more in terms of software to save their costs.

答:
In the early days of automobiles many parts ere interchangeable either directly or with the aid of a hacksaw and file. It was quite common for the engine, chassis and coachwork to be made by completely different companies.

In the fifties and sixties it was considered cool to fit the best motercycle engine (e.g. Triumph Bonneville) into the best frame (e.g. Norton Commando) with perhaps the brakes and shocks from a completely different machine.

All the was possible because the engineering was fairly crude and parts were not made to high tolerances.

In a modern vehicle even relatively inexpensive cars have highly optimized designs. Take as an example gas flows (the piece of engineering that most affects power output); the design must incorporate the air filter, carburetor/fuel injection, inlet manifold, valves, cylinder, piston, exhaust manifold, exhaust headers, the silencer and catalytic converter. Changing any one of those components will affect the gas flow and hence the power output and fuel consumption(probably for the worse).

Its difficult to see how you could have a plug and play approach to component design in this scenario.


问:
Which part of the code should rewind a file pointer?
If you had a function that took a handler to a file and then performed some actions that moved the pointer, would you expect it to put the pointer back when it was finished? Additionally, would you generally expect it to rewind to the start before it began its work?

```<code>def hash_contents(fp):
    original_pos = fp.tell()
    fp.seek(0)
    # do hashing / whatever
    fp.seek(original_pos)
</code>```

I've looked around a little to see what the most common assumptions are but I'm not sure what a good rule to follow is. For example, shutil.copyfileobj copies from whatever position the file started in and then consumes to the end.

What are the pros / cons and are there any standard rules of thumb to follow when designing these sort of functions?

This is actually a subquestion of something I was asking over at StackOverflow (Prefer BytesIO or bytes for internal interface in Python?) that really seems more suitable over here.

答:
In most cases, it is expected that any function that acts on a file will move the file pointer.  There are rare cases where I have used functions to peek ahead in the file, which where expected to leave the file pointer as it was found.  In all other cases, I expect the file pointer to move as a side effect of the function.

Functions that do not move the file pointer would break things severely in most case where I access file like objects.  However, I might expect a function to has the contents of the file to leave the file pointer in its original position.  However, there are cases where I would want X bytes from the current location hashed, and might not care where the pointer moved.  I would expect the behavior to be specified for such a function.

While side-effects of function calls are generally discouraged, this is one case where they are expected.  Unless you are dealing with code that has reason to do random access (databases of some sort) the expectation is that repeated calls of a function will advance through the file.

Database type code might have code that moves the position to the location of the data, and different code to read that data. Often the index and data files are separate, so it may be appropriate to do repeated reads after a repositioning.

In one case, I expected that a read would track where the file pointer was, so that a subsequent write would overwrite the data just read.  While this was the documented behavior, it failed drastically.   The write rewound the file and appeared not to have written anything.  The result was a loop where data was read to the location requiring and overwrite followed by a file rewind.  I changed the code to read from one file and write all data to the new file with the required changes applied.


答: In a startup, play to your strengths.  I would suggest sticking with .NET technologies and see if you can get into Microsoft's BizSpark program.  That'll get you affordable licenses to the software you need, with minimal risk involved.</p>

Title: Selecting the (right?) technology and environment

Body:
We are two developers on the edge of starting new web product development.

We are both fans of lean start-up approach and would like to practice continuous deployment.

Here comes the dilemma - we are both coming from a C# / Windows background and we need to decide between:

Stick to .NET and Windows, we will not waste time on learning new technologies and put all our effort in the development.

Switch to Ruby on Rails and Linux which has a good reputation of fast ramp up and vast open source support. The negative side is that we will need to put a lot of effort in learning Ruby, Rails and Linux...

What would you do? What other considerations should we take?


问:
Why is there "Unknown error" in real life?
As a programmer, I always try my best to explain what happened in the code when I have to show an error message, for example:

```<code>try {
    int a = b / 0;
} catch (NumberFormatException ex) {
    System.out.println("There was a problem with the number: " + ex.getMessage());
}
</code>```

I think this is a very basic practice that everyone should follow. But in real life, we still see some "unknown" errors with no error code nor anything we could follow to find the reason, like this one, or this one.

I mean, every "error" has a reason, so why there is "Unknown error"? Can anyone explain this for me?

答:
Because whoever was in charge of the information system didn't consider it worthwhile to preserve this information.

That is the basic reason in all such cases. However, many different motives can be behind that assumption (and in fact, they can be both reasonable and unreasonable).

Someone didn't think that anything could go wrong at all. It is rare for developers to be aware of all the things that can go wrong, and some don't have any awareness of the potential for exceptional conditions except the ones they have themselves encountered.

They didn't think that preserving the information was worth the additional effort. Using try on every action that might throw exceptions is a horrible strain on readability, and the information that is preserved may often be completely unintellegible to the average user anyway.

Increasingly, people work on isolated parts of large systems and don't have the information they would need to do this. With internet-deployed systems, very often the details of an error that caused a failure of service never leave the server on which it occurred. Any code running on a different machine is then fundamentally unable to explain the problem.

The full details are not the thing you would want to know. A division by zero is intuitively understandable, but the vast majority of exception stack traces are ultimately caused by variations of 'resourceManager is null'. It's technically true, but it doesn't help you at all with understanding or resolving the problem. Is the resourceManager supposed to be nullable (i.e. is my code faulty, or theirs)? How do I get a valid resourceManager? Did this happen because I accessed something to early? How can I avoid that? Do I even need a resource manager, or is that module a part of the system that I shouldn't be using in the first place? All these and thousands of other questions are not answered by an exception stack trace no matter how meticulously you report it, so maybe preserving the specifics of the error condition athand is not as useful as other mitigation measures would be.


答:
Computer programs as they grow on a large scale, become very complex. They act according to very precise logic (machine instructions), and there are many environmental factors which can affect this logic and change its direction.

Then sometimes we just [can] catch an error has occurred and to understand the reason needs a deep analysis of the software and even operating system and maybe a lot of time.

You may have noticed that many scenarios are possible for an small program, such scenarios grow exponentially when the software get larger and links to Operating System or I/O devices.

Title: Why is there "Unknown error" in real life?

Body:
As a programmer, I always try my best to explain what happened in the code when I have to show an error message, for example:

```<code>try {
    int a = b / 0;
} catch (NumberFormatException ex) {
    System.out.println("There was a problem with the number: " + ex.getMessage());
}
</code>```

I think this is a very basic practice that everyone should follow. But in real life, we still see some "unknown" errors with no error code nor anything we could follow to find the reason, like this one, or this one.

I mean, every "error" has a reason, so why there is "Unknown error"? Can anyone explain this for me?


问:
Embedding extremely basic scripts in application
I need to program a C++ application which will basically work as a script interpreter, but with extremely basic and limited scripts.

The scripts will have a format like this:

```<code>processedA = doProcessA(source)
processedB = doProcessB(source)
destination = mix(processedA, processedB)
</code>```

This denotes that in my C++ application this should happen (pseudocode):

```<code>while(source)
{
  processedA = doProcessA(*source);
  processedB = doProcessB(*source);
  *destination = mix(processedA, processedB);
  source++;
  destination++;
}
</code>```

I am not sure what my option are for interpreting my language. Parsing it should be simple.
Should I build an interpreter for my language, use llvm somehow to compile the flow (I'm not sure how), use a scripting language with c++ bindings or something else entirely?

I also need this to be reasonably fast (there isn't a limit but the faster the better).

答:
There are many easily embeddable interpreters, notably GNU guile (and other Scheme variants, e.g. libscheme), Lua, Tcl, and even Python, OCaml, Perl (e.g. with parrot), NekoVM ...

Notice that if your software becomes popular enough, and if its (advanced) users are permitted to script it (i.e. if the scripting ability is documented and accessible or configurable), there are chances that some remote user would use a lot (and even abuse) the scripting facilities.

So the implicit premises in your question ("extremely basic scripts") will eventually become false. At some point the scripts won't be basic anymore!

This is why a scripting language has to be a good enough programming language (with a familiar look). Some weird user will eventually code many thousands lines in it. (BTW, this social issue is probably what Ousterhout, the famous author of Tcl, under-estimated: he originally designed the first Tcl for small scripts, but eventually some people wrote huge Tcl scripts, and then Tcl became a burden, because it purposely lacks some features that real programming languages should have... efficient data structures, modularity, etc.. Since then, Tcl improved significantly.).

If for some reason you cannot (or do no want) to embed an existing interpreter in your product and decided to write your own scripting interpreter (which means many months of work!), study several programming and scripting languages before designing your own (and document the languages that inspired you). Take care of having good internal representation(s) of the interpreted script (at least some AST, and preferably some bytecode). Read notably Scott's book: programming language pragmatics and Queinnec's book: Lisp in Small Pieces and study several Domain Specific Languages; read about garbage collection, and perhaps application checkpointing & persistence.

You may consider using JIT compilation techniques (e.g. with llvm, libjit, libgccjit, luajit ...) and you could also consider instead generating C (or C++) code on the fly and compiling it and dlopen-ing it as a plugin (as I did in MELT). Current machines are fast enough to make that compatible with a REPL interaction.

Notice that embedding some interpreter in your application has a huge architectural impact, and should probably change or deeply affect the design of your application, and how it would be used by advanced users.

Remember that a scripting language is almost always Turing-complete (unless you take special care in its design to avoid that). Never forget about  the halting problem.

In the audio processing world, read about Faustine (by Karim Barkati, Haisheng Wang, and Pierre Jouvelot) and Faust (by Grame team in France).


答:
Use an existing one -= don't bother reinventing the wheel when there are better wheels available, that are cheaper for you to use.

Lua seems to be the most common C/C++ embedded script interpreter. There are even youtube tutorials on embeddeding it into your C++ programs, or codeproject.

Title: Embedding extremely basic scripts in application

Body:
I need to program a C++ application which will basically work as a script interpreter, but with extremely basic and limited scripts.

The scripts will have a format like this:

```<code>processedA = doProcessA(source)
processedB = doProcessB(source)
destination = mix(processedA, processedB)
</code>```

This denotes that in my C++ application this should happen (pseudocode):

```<code>while(source)
{
  processedA = doProcessA(*source);
  processedB = doProcessB(*source);
  *destination = mix(processedA, processedB);
  source++;
  destination++;
}
</code>```

I am not sure what my option are for interpreting my language. Parsing it should be simple.
Should I build an interpreter for my language, use llvm somehow to compile the flow (I'm not sure how), use a scripting language with c++ bindings or something else entirely?

I also need this to be reasonably fast (there isn't a limit but the faster the better).


答:
You need to consider the following factors:

1) The cost of deployment on your chosen platform (there are startup licenses for .NET / Windows but you'll need to pay eventually, plus the comparative hosting / hardware costs)

2) The time required to upskill (zero for .NET in this instance)

3) What you're building and the suitability of the platform for that in the short term (prototype, low volume use etc.) and the long term (will it scale and indeed do you intend it to scale or is it, say, B2B in which case volumes may always be comparatively low)

My instinct is stick with what you know as you'll have plenty going on without having to learn something else, but you need to weigh up the other factors based on the specifics of your idea.


问:
(How) should I change the copyright notice in a translated work?
I cannot find any guidance on this. Do I need to change the copyright notice for an application that is automatically translated from a programming language into another one (and recompiled and renamed)?
In my particular case, the original application is written in Java and translated into C# using a modified version of a commercial tool, if that makes a difference.

The original source coude is distributed under the MIT license, which is very permissive, except that it requires you to copy the original copyright notice in a derivatve work.
Now, the original copyright notice looks like this:

```<code>Copyright (c) 2014 Original Author <original@email.address>
</code>```

Should I leave this unchanged in my translated work or what should I do?

I don't need and don't want to claim authorship for a work I've just automatically translated using a tool, but I'm concerned that attributing my derivative work to the original author could be technically (or even legally) incorrect.
The original author doesn't kwon about my work and would be likely surprised to start receiving emails concerning this software with a different name, written in a different language.

答:
I propose a header like this, which keeps the original copyright notice intact (IMO a must) while making clear that contacting the original author doesn't make much sense:</p>

```<code>Original Java Version, see http://github.com/originaljavalib:
Copyright (c) 2014 Original Author <original@email.address>

C# Version, translated using foobartool:
Copyright (c) 2015 The Pyrate <thepyrate@thepyrate.com>
</code>```

Body:
I propose a header like this, which keeps the original copyright notice intact (IMO a must) while making clear that contacting the original author doesn't make much sense:

Original Java Version, see http://github.com/originaljavalib:
Copyright (c) 2014 Original Author <original@email.address>

C# Version, translated using foobartool:
Copyright (c) 2015 The Pyrate <thepyrate@thepyrate.com>


问:
How do you handle database security from a desktop application?
For about 10 years I've worked on various in-house desktop client applications with SQL Server data stores.  Rarely did I start these projects - most are takeover work.

One thing that seemed constant everywhere was that there was a single global SQL Server user account that this application used that granted it permission to the common database, and yes in some naive situations it used the sa user account, which I generally tried to fix when possible.

You can't really effectively hide this username and password that the application uses to access the database.  They're usually stored in an ini or config file, or possibly baked into the executable itself.  In all cases, they're visible to the user if they do a little digging.  In one case we actually used a config file but encrypted it, but of course the encryption key had to be stored in the executable (we weren't naive to the limitations of this, but it did effectively stop people from poking around who were savvy enough to look in config files).

All of these systems had a user-authentication system built into the application, but of course they were all managed through the application itself, meaning the user information was stored in the database.  The application restricted what things you could do based on your access level, but it's all kind of moot if you can just connect to the database and run ad-hoc queries.

I'm interested to know what other systems do to get around this problem.  Here are the options I know of:

Use SQL Server's security mechanism to maintain a user and roles list, and make the desktop application add and remove users through T-SQL queries.

Instead of connecting directly to the database, create some kind of web service that runs on the server and put the authentication logic in there.  Make every request do security validation.

The first options is a bit ugly because you're separating users from the database so users are no longer first class entities and you can't reference them with foreign key relationships, etc.

The second just seems like a major performance problem, and a lot of extra work, plus you can't as easily use ORM mappers like NHibernate (I think).

Does anyone have experience with this?  Best practices?

Edit

Thinking a bit more, can SQL Server Authentication actually solve this problem?  For instance, if your user must be able to insert and update timesheet records so you can edit your timesheet, there's no way SQL server can disallow access to other rows in the timesheet details table, meaning you can read and write other people's timesheets too.

答:
Similar to the answer by jmoreno, you can deny a user access to everything aside from EXECUTE permissions on stored procedures, then take advantage of ownership chaining to have the stored procedure perform the required operations on the tables.

See here for details https://msdn.microsoft.com/en-us/library/bb669058(v=vs.110).aspx

When the user enters their username/password client side, I store them and send as parameters to every stored procedure call.  You can then verify them against values stored in a table before performing the desired operation.

Definitely not the last word in security, but might be necessary if your PCs have generic logins, limiting your ability to use AD groups for permissions, or you have limited access to AD itself.


问:
Why every value is an object in python?
I know about writing programs (using C) that have:

Data values, that are manipulated. For example: integer, float values etc..

functions (rules), by which data values are manipulated.

object is a coherent abstraction of representing something that encompass it's properties(data values) + interactions (functions) && processes (functions) that can manipulate those data values.

As a python beginner, I would like to know, why data values (like integers and floats) and processes(like functions) are considered objects?

From Guido's blog as mentioned below, I could find some relevant information but does not answer why?

The internal implementation of Python made this simple to do. All of Python's objects were based on a common C data structure that was used everywhere in the interpreter. Variables, lists, functions, and everything else just used variations of this one data structure---it just didn't matter if the structure happened to represent a simple object such as an integer or something more complicated such as a class.

How can a computational process(function) be an object as per any language design?

答:
If you have an object oriented language, then it should be normal and expected that every value is an object; you need special justification if that is not the case.

Update: it seems you're uncertain what the statement means, probably due to lack of contrast.

So let me provide contrast: in other languages, even those which are considered OO languages, some values are not objects. For example, Java has so-called "primitive types" like int, char and double. These are not objects, you cannot call methods on them and you cannot assign them to a variable of type Object. They need special treatmeant in many places, which is often a bit annoying.

The designers of Java chose to do this mainly for performance reasons, since objects typically have a certain overhead.

Title: Why every value is an object in python?


问:
Is it reasonable to use a decorator to instantiate a singleton in Python?
Suppose I have a class like this:

```<code>class Foo(object):
    # some code here
</code>```

As it happens, Foo is a singleton.  There are numerous ways to write singletons in Python, but most of them don't really feel very Pythonic to me.  If someone else has a particularly strong reason for instantiating or subclassing my class, I see no reason to go out of my way to make things unreasonably difficult for them (beyond a minimal "this is not part of the public API and might break everything" hint).

So I hit upon this idea:

```<code>def singleton(cls):
    return cls()

@singleton
class foo_instance(object):  # note lower case
    # some code here
</code>```

I had to write singleton() myself because operator.call() isn't a thing for some strange reason.

Obviously, you can still just do type(foo_instance) and instantiate by hand, but the lack of a publicly visible class makes it obvious (to me) that you're not really supposed to do that (in much the same way as you're not supposed to mess around with type(enum.Enum) in 3.4+), and I think it looks cleaner than an underscore-prefixed "private" class such as class _Foo.

Is this a reasonable way to go about making a class singular?

答:
I think the simplest, most Pythonic way to implement a singleton class is with inheritance:

```<code>class Singleton(object):

    _instances = {}

    def __new__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = object.__new__(cls, *args, **kwargs)
        return cls._instances[cls]

class Foo(Singleton):  # Foo 'is a' Singleton
    pass
</code>```

Now the usage is simple:

```<code>>>> foo1 = Foo()
>>> foo2 = Foo()
>>> foo1 is foo2
True
</code>```

and won't break in the case you identify above:

```<code>>>> foo3 = type(foo1)()
>>> foo1 is foo3
True
</code>```

You can also inherit from Foo; the child class will also be a Singleton.

One issue to be aware if is that if you implement Foo.__init__, it will be called every time Foo() is called. If that is undesirable, move the initialisation to the constructor (i.e. implement Foo.__new__ instead, remembering to call the super constructor too).

Body:
I think the simplest, most Pythonic way to implement a singleton class is with inheritance:

class Singleton(object):

    _instances = {}

    def __new__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = object.__new__(cls, *args, **kwargs)
        return cls._instances[cls]

class Foo(Singleton):  # Foo 'is a' Singleton
    pass

Now the usage is simple:

>>> foo1 = Foo()
>>> foo2 = Foo()
>>> foo1 is foo2
True

and won't break in the case you identify above:

>>> foo3 = type(foo1)()
>>> foo1 is foo3
True

You can also inherit from Foo; the child class will also be a Singleton.

One issue to be aware if is that if you implement Foo.__init__, it will be called every time Foo() is called. If that is undesirable, move the initialisation to the constructor (i.e. implement Foo.__new__ instead, remembering to call the super constructor too).


答:
If all you did was run the translation tool over the sources, you have no claim to copyright on the translated version because no creative work on your part went into it.

As the original author will probably not be supporting the C# version, it is a good idea to mention that you are responsible for the C# version. You could do this like so:

Copyright (c) 2014 Original Author <original@email.address>

  Translated from Java to C# by The Pyrate <thepyrate@example.com> (using foobartool)

  Original Java Version available at http://example.com/originaljavalib

If, after translation, you made changes to the C# code (for example, to fix bugs caused by the translation), then you can claim copyright for those changes.

Title: (How) should I change the copyright notice in a translated work?

Body:
I cannot find any guidance on this. Do I need to change the copyright notice for an application that is automatically translated from a programming language into another one (and recompiled and renamed)?
In my particular case, the original application is written in Java and translated into C# using a modified version of a commercial tool, if that makes a difference.

The original source coude is distributed under the MIT license, which is very permissive, except that it requires you to copy the original copyright notice in a derivatve work.
Now, the original copyright notice looks like this:

```<code>Copyright (c) 2014 Original Author <original@email.address>
</code>```

Should I leave this unchanged in my translated work or what should I do?

I don't need and don't want to claim authorship for a work I've just automatically translated using a tool, but I'm concerned that attributing my derivative work to the original author could be technically (or even legally) incorrect.
The original author doesn't kwon about my work and would be likely surprised to start receiving emails concerning this software with a different name, written in a different language.