问:
Can I use Apache Software License, Version 2.0 and GNU LGPL 3 licence plugins in my commercial web application?
I have two plug-ins. One has the GNU LGPL 3 license and the other has the Apache Software License, Version 2.0. Can I use them in my commercial app?
And if yes, what precautions should I take?</p>

答:
Can I use them in my commercial app?

It depends on what you intend to do with the software that you produce.

Firstly, neither ASL1, GPL or LGPL make any restrictions on what you can use software to do inside your organization.  The restrictions are all on code that is distributed outside of your organization.

For GPL the restriction is that if you incorporate GPL'ed code into your own software, AND you then distribute your software outside of your organization, THEN you must make the source code available under the terms of the GPL or a compatible open source license.

So if you use GPL'ed code in your application and you distribute it, then your application must be open source ... or else you are violating the license.

For LGPL, the restriction (see above) only applies to the source-code of the LGPL'ed library itself; i.e. if you change the library.  If you just use the library, you are not required to make your source code available.

There is also a restriction that the LGPL code in your application must be replaceable by the user of your code.  That means (in effect) that if you distribute your code as binaries only, then you cannot statically link your code against that the library.  You must use dynamic linking.

For ASL, the only significant restriction is that you must say if you have changed anything from the original version the ASL'ed code that you using.

Finally, just to make it clear, neither GPL, LPGL or ASL places any restriction on your purpose in using the software.  And that includes whether your purpose is to make money.  They just constrain the way you can make money ... and in the case of LGPL and ASL, the constraint is pretty minimal.

And if yes, what precautions should I take?

For LGPL and ASL, no precautions are necessary.

IANAL - I am not a lawyer.  If you need to be sure, ask a real, qualified expert; i.e. a lawyer who specializes in software IP law.

1 - For the purposes of this answer, ASL == Apache Software License version 2.


问:
Why do all <algorithm> functions take only ranges, not containers?
There are many useful functions in <algorithm>, but all of them operate on "sequences" - pairs of iterators. E.g., if I have a container and like to run std::accumulate on it, I need to write:

```<code>std::vector<int> myContainer = ...;
int sum = std::accumulate(myContainer.begin(), myContainer.end(), 0);
</code>```

When all I intend to do is:

```<code>int sum = std::accumulate(myContainer, 0);
</code>```

Which is a bit more readable and clearer, in my eyes.

Now I can see that there might be cases where you'd only want to operate on parts of a container, so it's definitely useful to have the option of passing ranges. But at least in my experience, that's a rare special case. I'll usually want to operate on whole containers.

It's easy to write a wrapper function which takes a container and calls begin() and end() on it, but such convenience functions are not included in the standard library.

I'd like to know the reasoning behind this STL design choice.

答:
Turns out there's an article by Herb Sutter on this very subject.
Basically, the problem is overload ambiguity. Given the following:

```<code>template<typename Iter>
void sort( Iter, Iter ); // 1

template<typename Iter, typename Pred>
void sort( Iter, Iter, Pred ); // 2
</code>```

And adding the following:

```<code>template<typename Container>
void sort( Container& ); // 3

template<typename Container, typename Pred>
void sort( Container&, Pred ); // 4
</code>```

Will make it hard to distinguish 4 and 1 properly.

Concepts, as proposed but ultimately not included in C++ 0x, would have solved that, and it's also possible to circumvent it using enable_if. For some of the algorithms, it's no problem at all. But they decided against it.

Now after reading all the comments and answers here, I think range objects would be the best solution. I think I'll have a look at Boost.Range.

ContentLicense: CC BY-SA 3.0

Body:
Turns out there's an article by Herb Sutter on this very subject.
Basically, the problem is overload ambiguity. Given the following:

template<typename Iter>
void sort( Iter, Iter ); // 1

template<typename Iter, typename Pred>
void sort( Iter, Iter, Pred ); // 2

And adding the following:

template<typename Container>
void sort( Container& ); // 3

template<typename Container, typename Pred>
void sort( Container&, Pred ); // 4

Will make it hard to distinguish 4 and 1 properly.

Concepts, as proposed but ultimately not included in C++ 0x, would have solved that, and it's also possible to circumvent it using enable_if. For some of the algorithms, it's no problem at all. But they decided against it.

Now after reading all the comments and answers here, I think range objects would be the best solution. I think I'll have a look at Boost.Range.


问:
Citations for inadvisability of globally unique password
I am having a disagreement with a client about the user authentication process for a system. The nub of it is that they want each user to have a globally unique password (i.e. no two users can have the same password).

I have wheeled out all the obvious arguments against this:

it's a security vulnerability,

it confuses identification with authentication,

it's pointless, etc.,

but they are insisting that there is nothing wrong with this approach.

I have done various gGoogle searches looking for authoritative (or semi-authoritative , or even just independent) opinions on this, but can't find any (mainly it's just such an obvious faux pas that it doesn't seem worth warning against, as far as I can tell).  Can anybody point me towards any such independent opinion, please?

EDIT: Thanks for all your answers, but I already understand the problems with this proposed approach/requirement, and can even explain them to the client, but the client wont't accept them, hence my request for independent and/or authoritative sources.

I'd also found the Daily WTF article, but it suffers from the problem that Jon Hopkins has pointed out - that this is such a self-evident WTF that it doesn't seem worth explaining why.

And yes, the passwords are going to be salted and hashed. In which case global uniqueness might well be difficult to ensure, but that doesn't solve my problem - it just means that I have a requirement that the client won't budge on, that's not only ill-advised, but is also difficult to implement. And if I was in a position to say "I'm not budging on salting and hashing", then I'd be in a position to say "I'm not implementing globally unique passwords".

Any pointers to independent and/or authoritative sources for why this is a bad idea still gratefully received...

答:
If you have advised them against this course of action, and supplied them with reasons, I would take them at their word and just implement the system as they suggest. It may not be satisfying, but you have done your job, and they are footing the bill, so they ought to get what they want.

There is one exception. If the negative consequences of a system breach would be severe (e.g. if very private information is likely to be compromised by a security breach) you may in fact have a professional duty not to implement the system they want. Don't expect it to make you popular if you refuse, but don't let that be your guide.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
Does commercial mean when you earn money by putting a ad to support you or is it something else like for a big company?
I been reading a few things about using libraries and stuff but they all talk about not using it for commercial purposes.

Does commercial mean when you earn money by putting a ad to support you or is it something else like for a big company?

答: Commercial (in very general terms) refers to monetizing their software for your use.  Example, you use one of the libraries that is designated for NON-commercial use, you would not be able to sell the application or make any kind of money off of it in anyways.   Possibly, this extends to your website if it is ad supported as well.  However, you would be able to use their libraries/software for personal use or open-source projects as long as you aren't trying to sell it. </p>


问:
implementing dynamic query handler on historical data

Context:

I have historical data about property (house) sales collected from various sources in a centralized/cloud data source (assume info collection is handled by a third party)

Planning to develop an application  to query and retrieve data from this centralized data source

Example Queries:

Simple : for given XYZ post code, what is average house price for 3 bed room house?

Complex: What is estimated price for an house at "DD,Some Street,XYZ Post Code" (worked out from average values of historic data filtered by various characteristics of the house: house post code, no of bed rooms, total area, and other deeper insights like house building type, year of built, features)?

In addition to average price, the application should support other property info ** maximum, or minimum price..etc and trend (graph) on a selected property attribute over a period of time**. Hence, the queries should not enforce the search based on a primary key or few fixed fields

In other words, queries can be

What is the change in 3 Bed Room house price (irrespective of location) over last 30 days?

What kind of properties we can get for X price (irrespective of location or house type)

The challenge I have is identifying the domain (BI/ Data Analytical or DB Design or DB Query Interface or DW related or something else) this problem (dynamic query on historic data) belong to, so that I can do further exploration

My findings so far

I could be wrong on the following, so please correct me if you think so

I briefly read about BI/Data Analytics - I think it is heavy weight solution for my problem and has scalability issues.

DB Design - As I understand RDBMS works well if you know Data model at design time. I am expecting attributes about property or other entity (user) that am going to bring in, would evolve quickly. hence maintenance would be an issue. As I am going to have multiple users executing query at same time, performance would be a bottleneck

Other options like Graph DB (http://www.tinkerpop.com/) seems to be bit complex (they are good. but using those tools meant for generic purpose, make me think like assembly programming to solve my problem )

BigData related solution are to analyse data from multiple unrelated domains

So,
Any suggestion on the space this problem fit in ? (Especially if you have  design/implementation experience of back-end for property listing or similar portals)

答:
I think that what would be the most useful for you would be Big Data as a "domain" for the problem you're trying to solve.

If you want people to be able to interesting things with the data, on the web, then you're going to want a low-latency system.  While there are a lot of approaches, one thing I don't think you'll be able to avoid is pre-calculating at least some level of rollups.

Using something like Hadoop with Hbase and Pig are an approach I've been fond of recently...using something like this you've got the ability to quickly and relatively easily re-calculate things as you refine your requirements from your original source data.  If you go in this general direction, you'll want to do some reading on effective row key design in large key/value stores (i.e. Hbase, Cassandra).


问:
Should I refactor large functions that mostly consist of one regex?
I just wrote a function that spans approximately 100 lines. Hearing that, you are probably tempted to tell me about single responsibilities and urge me to refactor. This is my gut instinct as well, but here is the issue: The function does one thing. It performs a complex string manipulation, and the function body consists mostly of one verbose regex, broken up into many lines that are documented. If I broke up the regex into multiple functions, I feel like I would actually lose readability, since I am effectively switching languages, and won't be able to take advantage of some features regexes offer. Here now is my question:

When it comes to string manipulation with regular expressions, are large function bodies still an anti-pattern? It seems like named capture groups serve a very similar purpose to functions. By the way, I have tests for every flow through the regex.

答: One thing that you may or may not have considered is to write a small parser in the language you are using instead of using a regex in that language. This may be easier to read, test, and maintain.</p>


问:
Design pattern for bidirectional signals/events
This problem feels rather basic, yet I've never known a great solution. I'm looking for a way for components in an application to notify each other while being as decoupled as possible (both at build/compile and run time), but also avoiding circular notifications in a way that components do not need to self-mitigate against. I happen to be hitting this issue (for the hundredth time) in JavaScript right now, but that is incidental.

Some means of decoupling include:

Dependency injection (DI). In this case I use require.js which allows, for instance, substituting mock implementations in unit tests by creating alternate require.config() setups.

Event dispatching. E.g. fooInstance.listen('action string', barInstance.actionHandler)

Publish/subscribe (aka pub/sub).

The last two are basically variants of the Observer pattern with different pros and cons.

The problem I want to solve is not specifically addressed by these patterns, and I'm not sure if its an implementation detail or if there is a pattern to apply:

fooObj sends a message (fires an event, whatever) that the "baz" property has changed

barObj.bazChanged() handles this event by calling its own setBaz() method

barObj.setBaz() fires an event that "baz" has changed

fooObj.bazChanged() handles this event ...

As a real case, imagine fooObj is a GUI component, with a slider for "tempo", and barObj is a music sequencing component that plays back a score. The slider should affect the tempo of the sequencer, but the score can contain tempo changes so when playing the sequencer should affect the slider position. A solution should be modeless.

One approach is to add guards, for example:

```<code>function handleTempoChanged(tempo) {
    if (this.tempo == tempo) return;
    ...
}
</code>```

This works but feels like a poor solution because it means every event handler needs to either assume it needs a guard, which is ugly boilerplate and often not required, OR needs to be aware of the other components in the system that would make a cycle possible. Arguably, this point is wrong, guards should always be used if the handler is going to fire a changed event directly or indirectly, but this still feels like boilerplate logic. This may be the only answer to my question...

Is there general case pattern to deal with potential cycles as described? Note that this is not about synchronous vs. asynchronous; either way the cycles can occur.

EDITED to reflect insight from commenters:

I realize it is possible to eliminate the boilerplate, using some sort of mixin. In pseudo-code:

```<code>class ObservablePropsMixin:

    // generic setter with gaurd
    function set(propName, value):
        if this[propName] = value: return
        this[propName] = value
        _fire(propName, value)

    // generic method to add listeners
    function observe(propName, handler):
        _observers[propName].add(handler)

    // private event dispatching method
    function _fire(propName, value):
        foreach observer in _observers[propName]:
            observer.call(propName, value)

    ...
</code>```

This is simplified to focus on my question, but a real mixin would implement other pubsub or event or signal semantics, analogous to any event dispatcher implementation. Components needing to be observers or observables would inherit/extend from the mixin (the above assumes some form of multiple or aggregate inheritance is possible in the language. This could be modified to work with composition instead, e.g. ObservableMixin.constructor(observedObject) rather than using "this".

答:
The guards are only possible solution. There is no way some 3rd party code could distinguish between loop in event chain and normal event chain.

While the guards might seem as boilerplate logic, they are actually quite simple to implement some kinds of them can be abstracted away if language supports it. For example onChange could automatically check if the value changed and only fire the event if the value changes.

OwnerDisplayName: Jason Boyd


问:
Using an issue tracker as a single programmer
If this is tl;dr, scroll down to "The Question"

Why this is not a duplicate:

The linked question talks about version control (which I have), a one step build script (which I have) and to "have an issue tracker at all" (which I have, but I'm having trouble optimizing), none of the answers to that question answer any of my questions.

This question is not about "minimum subset", it is about practical issues in a specific real world situation.

Background:

I am the sole developer at my company, which is only 5 people. Only one of my coworkers has any development experience, and he is not working on any of the production code. He is my boss, but he doesn't have any interest in the details in specific issues. My job is honestly more of a side project of one of the partners (my boss's boss), the company already makes money from things that have nothing to do with me. He is reluctant to give me more resources until I can prove that this project has viability; once I do, he plans to give me a lot more resources, but until then this is my situation.

The issue:

As a result, I am finding it challenging to use my project management platform (currently Redmine). I think that if there were more programmers or even testers, it would be a great communication tool. However, because I am doing 100% of the development work and 95% of the testing, it just seems like a massive time sink to keep the cases up to date, and sometimes even to create them!

Most of the time, when I find a bug, I just fix it immediately. The only time it ever makes it into the issue tracker is if it's not something I can fix and test in less than half an hour.

As the only programmer, there is no code review. No one who works here is interested in using my redmine server; I'm lucky if I get a bug report via email, usually they just walk over to my desk and tell me - and even that is rare. I have tried to get my boss to use the server by making him watcher of many of the cases, and having it email him when I make changes, but he hasn't even logged onto it in the last 3.5 months.

Before I was using redmine, I was using Wunderlist - and honestly that seemed to be a much better fit. It was definitely inferior from a features standpoint, but it did the job - I could make notes of things much more quickly.

Note: I am comfortable with my version control routines, most of the time; this is much more about issue tracking and communication with the non-developers.

The Question:

I would appreciate input on any of these questions:

As a lone programmer, do you prefer a full featured issue tracker like redmine or a simpler personal organization system like Wunderlist or Evernote?
-- If you use redmine or similar, do you use most of the features?

Any tips for getting YOUR BOSS who has had zero interest in using an issue tracker in the past to start using it?

When testing existing code (assume code that was not written with TDD), if you find a bug, in what situations to you add the issue to the issue tracker?

Any other advice that seems relevant for me.

答:
I say it depends. If you are working on a small project which is indented to stay small, you might be good with a task list. I use Wunderlist for some stuff. Typical projects are things like creating blog systems which follow a "do this from a to z" approach.

For projects of which I think (or hope) they become big I use an issue manager or Kanban styled board.

While I was using Atlassians Jira a lot in the past I found it was totally overblown even when I use it with my team of 5 people. I think such systems are good when you are working at an enterprise level as you have many options to customize, but not for small and agile teams.

Today I use Trello.com for task oriented things, even for issues. This works pretty well in my current super agile team. While Redmine allows you to assign release versions, we have decided to make multiple releases a day and that feature would just be "too much". Instead we move cards as we go and are very happy with it.

The tool needs to serve you and not vice versa.
From what I read from your post you definitely should use something easy, also please look into Trello.com (very easy, free to use and bit better for overseeing tasks).

Your Boss: tell him you need to organize your work, otherwise this will cost him a lot of money/time if don't. In example, if you have list of tasks you can focus. If you don't have that you need to think every day for approx 30 minutes what needs to be done. Money is usually what convinces most bosses.

Creating issues: If you see a bug (say a typo) i fix it straightaway. If I see a bug I cannot fix right now, I am creating an issue. If the bug is not done with a simple fix or changes the systems behavior significantly I create an issue too. The reason is I want to have it documented. Personally I am doing it agile, and you should do so to save time as long as you don't need to document every step to do.

Other tipps? Simply try whats best for you and what keeps your focused on your tasks.
There are a lot of issue trackers and they promise you heaven. But most of them have a problem: they often have so much features that they eat up a lot of time too. My vision is to have a took which supports me without ever thinking about it. As mentioned, my combination of Trello and Wunderlist works well.


答:
By the sounds of it the tool isn't working for you. Your boss isn't using it so all you're doing is spending valuable time feeding it data. So why not park it and use something else? Having used Trello myself like Christian, I too fully endorse it. It is all online and you can even use it on your smartphone. It doesn't require you to fill in massive amount of meaningless data either - you just enter what you need to and it is done.

Your task as I see it is to build interest in and be an evangelist for the project you're developing. OK, you're finding and fixing issues but why should your boss care about this?

Don't tell your local pedant, but TDD can be retrofitted to a completed/partially developed project. You just write a suite of tests and off you go. Sure it isn't as useful this way, but there is still definitely value to be had.

As for what to track - if it is a typo or something is not quite in the right place on screen, I'd be inclined just to attend to these. Similarly, if they're issues that only you yourself have found that can simply be fixed, then do so. Track anything that is more involved. As a rule of thumb - if your boss asked you for a demo now, what issues would you feel it was important to mention?

Title: Using an issue tracker as a single programmer

Body:
If this is tl;dr, scroll down to "The Question"

Why this is not a duplicate:

The linked question talks about version control (which I have), a one step build script (which I have) and to "have an issue tracker at all" (which I have, but I'm having trouble optimizing), none of the answers to that question answer any of my questions.

This question is not about "minimum subset", it is about practical issues in a specific real world situation.

Background:

I am the sole developer at my company, which is only 5 people. Only one of my coworkers has any development experience, and he is not working on any of the production code. He is my boss, but he doesn't have any interest in the details in specific issues. My job is honestly more of a side project of one of the partners (my boss's boss), the company already makes money from things that have nothing to do with me. He is reluctant to give me more resources until I can prove that this project has viability; once I do, he plans to give me a lot more resources, but until then this is my situation.

The issue:

As a result, I am finding it challenging to use my project management platform (currently Redmine). I think that if there were more programmers or even testers, it would be a great communication tool. However, because I am doing 100% of the development work and 95% of the testing, it just seems like a massive time sink to keep the cases up to date, and sometimes even to create them!

Most of the time, when I find a bug, I just fix it immediately. The only time it ever makes it into the issue tracker is if it's not something I can fix and test in less than half an hour.

As the only programmer, there is no code review. No one who works here is interested in using my redmine server; I'm lucky if I get a bug report via email, usually they just walk over to my desk and tell me - and even that is rare. I have tried to get my boss to use the server by making him watcher of many of the cases, and having it email him when I make changes, but he hasn't even logged onto it in the last 3.5 months.

Before I was using redmine, I was using Wunderlist - and honestly that seemed to be a much better fit. It was definitely inferior from a features standpoint, but it did the job - I could make notes of things much more quickly.

Note: I am comfortable with my version control routines, most of the time; this is much more about issue tracking and communication with the non-developers.

The Question:

I would appreciate input on any of these questions:

As a lone programmer, do you prefer a full featured issue tracker like redmine or a simpler personal organization system like Wunderlist or Evernote?
-- If you use redmine or similar, do you use most of the features?

Any tips for getting YOUR BOSS who has had zero interest in using an issue tracker in the past to start using it?

When testing existing code (assume code that was not written with TDD), if you find a bug, in what situations to you add the issue to the issue tracker?

Any other advice that seems relevant for me.


问:
Slugify via helper or store slug on database?
I have a simple question: Slugify via helper or store the slug on database?

I mean, let's suppose that I have Guilherme Oderdenge on database and I want to transform it into a human-readable URL such as http://myapp.com/guilherme-oderdenge/, what's the best way to perform this? Storing  guilherme-oderdenge in the database or transforming Guilherme Oderdenge in a slug with a helper like user.name.slugify?

I know there are some ways to reach the expected result, but which one is better? Or at least there is a better way?

It depends of the technology that you're using

-

I'm using Ruby On Rails with MySQL.

答:
I would store the slug in the database, this gives you the flexibility of being able to customize your slug if the logic to create a slug didn't create a desirable slug.

Also, if you had 2 pages with the same name, you would want to have two different slugs as they probably should be unique.

Thirdly this represents a good separation of concerns, the database if for querying data, not creating content.

Just to clarify, I recommend you create the slug in your app code, and store that in the db.


问:
Building complex algorithms with TDD
I'm trying to adopt TDD in my daily programming practice.  I use it at work very effectively, but I'm having trouble with my personal projects where I'm using some complex algorithms.

The particular algorithm that makes me ask this question is the Extended Kalman Filter.  It's complex enough that I'm not confident in the code I've written, but it's simple enough that it's hard to break up.

I could write a test for the algorithm with an input and the expected output, but I'll do a lot of thrashing and shotgun coding in the middle because I don't have confidence in those intermediate steps.

If you've worked with reasonable complex algorithms and use TDD, what is your approach?

答:
I'm new to TDD (read: I'm probably not doing it right), but it seems to be more suited to easily describable algorithms, when you can easily reason about which inputs match to what outputs.

When I'm doing more "I don't know what's the outcome gonna be yet"  TDD hasn't been very useful to me.  What I do instead, I use asserts very liberally on small portions I know work how they should work so far.  This way I don't get stuck trying to code to a target that I'm not sure should is the valid target, but I get some protection, localizing the pain areas to smaller portions of the code.

Once the algorithm is sorted out for correctness (as in I am sure about at least some inputs->outputs for spot checking), then I go back and write a test.  Then it's much safer to go back and refactor, or optimize for speed or resource usage.

Title: Building complex algorithms with TDD


问:
Why is quality engineering difficult?
In quality engineering there are 3 phases:

1.quality assurance

2.quality control

3.quality measurement

Quality Engineering is defined as “the branch of engineering which deals with the principles and practice of product and service quality assurance and quality control”.

Quality assurance is a way of preventing mistakes. Quality control is the testing of product to uncover defects. But I am confused, why is quality engineering thought to be difficult?

答:
Quality engineering can be quite subjective, and often your own stakeholders are working against you. And as we all know as software professionals, time is always against us.

Subjectiveness

Requirements can be pretty easy to test, e.g. "the edit user screen shall have two buttons to accept or reject the changes." Any lesser primate can look at the screen, see OK and Cancel buttons, and say the requirement is met.

Other requirements are difficult, such as performance. Even if the requirement is specific, there is often much left to interpretation: it is subjective, and especially near the deadline of a project, people will disagree about the requirement or say "what we have is good enough" when it is not. This means arguing, and often due to time constraints, the quality engineer loses.

Stakeholders

I have found that often customers will not understand what they need, not understand their own requirements, change their minds over time, and not update user stories.

What this means is while you are trying to validate requirements and ensure software quality, customers are simultaneously moving your target and possibly not even telling you.

Time

In a business, almost everything you do needs to have an economic justification. Quality engineering activities such as gathering and evaluating metrics, post-mortems, etc. tend to be rushed or discarded because hey, the software was delivered and it is time to move to the next project.

Enlightened employers realize these activities are investing in the future, not the present. They make the next project run smoother, deliver sooner, and with fewer defects (read: nonbillable hours). After all, this is one purpose of quality engineering.

When a quality engineer lacks sufficient time to do his job, he is unable to effect change in an organization that is beneficial. Without enough time, quality is a rush job and it is difficult to improve quality.

Title: Why is quality engineering difficult?


问:
Exceptions: Why throw early? Why catch late?
There are many well-known best practices about exception handling in isolation. I know the "do's and don'ts" well enough, but things get complicated when it comes to best practices or patterns in larger environments. "Throw early, catch late" - I've heard many times and it still confuses me.

Why should I throw early and catch late, if at a low-level-layer a null pointer exception is thrown? Why should I catch it at a higher layer? It doesn't make sense for me to catch a low-level exception at a higher level, such as a business layer. It seems to violate the concerns of each layer.

Imagine the following situation:

I have a service which calculates a figure. To calculate the figure the service accesses a repository to get raw data and some other services to prepare calculation. If something went wrong at the data retrieval layer, why should I throw a DataRetrievalException to higher level? In contrast I would prefer to wrap the exception into a meaningful exception, for example a CalculationServiceException.

Why throw early, why catch late?

答:
Others have summarized quite well why to throw early. Let me concentrate on the why to catch late part instead, for which I haven't seen a satisfying explanation for my taste.

SO WHY EXCEPTIONS?

There seems to be quite a confusion around why exceptions exist in the first place. Let me share the big secret here: the reason for exceptions, and exception handling is... ABSTRACTION.

Have you seen code like this:

static int divide(int dividend, int divisor) throws DivideByZeroException {
    if (divisor == 0)
        throw new DivideByZeroException(); // that's a checked exception indeed

    return dividend / divisor;
}

static void doDivide() {
    int a = readInt();
    int b = readInt();
    try {
        int res = divide(a, b);
        System.out.println(res);
    } catch (DivideByZeroException e) {
        // checked exception... I'm forced to handle it!
        System.out.println("Nah, can't divide by zero. Try again.");
    }
}
```

<p>That's not how exceptions should be used. Code like the above do exist in real life, but they are more of an aberration, and are really the exception (pun). The definition of <em>division</em> for example, even in pure mathematics, is conditional: it is always the "caller code" who has to handle the exceptional case of zero to restrict the input domain. It's ugly. It's always pain for the caller. Still, for such situations the <em>check-then-do</em> pattern is the natural way to go:</p>

<pre class="lang-java prettyprint-override"><code>static int divide(int dividend, int divisor) {
    // throws unchecked ArithmeticException for 0 divisor
    return dividend / divisor;
}

static void doDivide() {
    int a = readInt();
    int b = readInt();
    if (b != 0) {
        int res = divide(a, b);
        System.out.println(res);
    } else {
        System.out.println("Nah, can't divide by zero. Try again.");
    }
}
</code>```

Alternatively, you can go full commando on OOP style like this:

static class Division {
    final int dividend;
    final int divisor;

    private Division(int dividend, int divisor) {
        this.dividend = dividend;
        this.divisor = divisor;
    }

    public boolean check() {
        return divisor != 0;
    }

    public int eval() {
        return dividend / divisor;
    }

    public static Division with(int dividend, int divisor) {
        return new Division(dividend, divisor);
    }
}

static void doDivide() {
    int a = readInt();
    int b = readInt();
    Division d = Division.with(a, b);
    if (d.check()) {
        int res = d.eval();
        System.out.println(res);
    } else {
        System.out.println("Nah, can't divide by zero. Try again.");
    }
}
```

<p>As you see, the caller code has the burden of the pre-check, but does not do any exception handling after. If an <code>ArithmeticException</code> ever comes from calling <code>divide</code> or <code>eval</code>, then it   is <strong>YOU</strong> who has to do the exception handling and fix your code, because you forgot the <code>check()</code>. For the similar reasons catching a <code>NullPointerException</code> is almost always the wrong thing to do.</p>

<p>Now there are some folks who say they want to see the exceptional cases in the method / function signature, i.e. to explicitly extend the output domain. They are the ones who favor checked exceptions. Of course, changing the output domain should force any direct caller code to adapt, and that would indeed be achieved with checked exceptions. <strong>But you don't need exceptions for that!</strong> That's why you have <code>Nullable<T></code> generic classes, case classes, algebraic data types, and union types. Some OO people might even prefer returning <code>null</code> for simple error cases like this:</p>

<pre class="lang-java prettyprint-override"><code>static Integer divide(int dividend, int divisor) {
    if (divisor == 0) return null;
    return dividend / divisor;
}

static void doDivide() {
    int a = readInt();
    int b = readInt();
    Integer res = divide(a, b);
    if (res != null) {
        System.out.println(res);
    } else {
        System.out.println("Nah, can't divide by zero. Try again.");
    }
}
</code>```

Technically exceptions can be used for the purpose like the above, but here is the point: exceptions do not exist for such usage. Exceptions are pro abstraction. Exception are about indirection. Exceptions allow for extending the "outcome" domain without breaking direct client contracts, and deferring error handling to "somewhere else". If your code throws exceptions which are handled in direct callers of the same code, without any layers of abstraction in between, then you are doing it W. R. O. N. G.

HOW TO CATCH LATE?

So here we are. I have argued my way through to show that using exceptions in the above scenarios is not how exceptions are meant to be used. There exists a genuine use case though, where the abstraction and indirection offered by exception handling is indispensable. Understanding such usage will help understanding the catch late recommendation too.

That use case is: Programming Against Resource Abstractions...

Yeah, business logic should be programmed against abstractions, not concrete implementations. Top level IOC "wiring" code will instantiate the concrete implementations of the resource abstractions, and pass them down to the business logic. Nothing new here. But the concrete implementations of those resource abstractions can potentially be throwing their own implementation specific exceptions, can't they?

So who can handle those implementation specific exceptions? Is it possible to handle any resource specific exceptions at all in the business logic then? Nope, it is not. The business logic is programmed against abstractions, which does exclude the knowledge of those implementation specific exception details.

"Aha!", you might say: "but that's why we can subclass exceptions and create exception hierarchies" (check out Mr. Spring!). Let me tell you, that's a fallacy. Firstly, every reasonable book on OOP says concrete inheritance is bad, yet somehow this core component of JVM, exception handling, is closely tied with concrete inheritance. Ironically, Joshua Bloch could not have written his Effective Java book before he could get the experience with a working JVM, could he? It is more of a "lessons learnt" book for the next generation. Secondly, and more importantly, if you catch a high-level exception then how are you going to HANDLE it? PatientNeedsImmediateAttentionException: do we have to give her a pill or amputate her legs!? How about a switch statement over all the possible subclasses? There goes your polymorphism, there goes the abstraction. You got the point.

So who can handle the resource specific exceptions? It must be the one who knows the concretions! The one who instantiated the resource! The "wiring" code of course! Check this out:

Business logic coded against abstractions... NO CONCRETE RESOURCE ERROR HANDLING!

static interface InputResource {
    String fetchData();
}

static interface OutputResource {
    void writeData(String data);
}

static void doMyBusiness(InputResource in, OutputResource out, int times) {
    for (int i = 0; i < times; i++) {
        System.out.println("fetching data");
        String data = in.fetchData();
        System.out.println("outputting data");
        out.writeData(data);
    }
}
```

<h3>Meanwhile somewhere else the concrete implementations...</h3>

<pre class="lang-java prettyprint-override"><code>static class ConstantInputResource implements InputResource {
    @Override
    public String fetchData() {
        return "Hello World!";
    }
}

static class FailingInputResourceException extends RuntimeException {
    public FailingInputResourceException(String message) {
        super(message);
    }
}

static class FailingInputResource implements InputResource {
    @Override
    public String fetchData() {
        throw new FailingInputResourceException("I am a complete failure!");
    }
}

static class StandardOutputResource implements OutputResource {
    @Override
    public void writeData(String data) {
        System.out.println("DATA: " + data);
    }
}
</code>```

And finally the wiring code... Who handles concrete resource exceptions? The one who knows about them!

static void start() {
    InputResource in1 = new FailingInputResource();
    InputResource in2 = new ConstantInputResource();
    OutputResource out = new StandardOutputResource();

    try {
        ReusableBusinessLogicClass.doMyBusiness(in1, out, 3);
    }
    catch (FailingInputResourceException e)
    {
        System.out.println(e.getMessage());
        System.out.println("retrying...");
        ReusableBusinessLogicClass.doMyBusiness(in2, out, 3);
    }
}
```

Now bear with with me. The above code is simplistic. You might say you have an enterprise application / web container with multiple scopes of IOC container managed resources, and you need automatic retries and reinitialization of session or request scope resources, etc. The wiring logic on the lower level scopes might be given abstract factories to create resources, therefore not being aware of the exact implementations. Only higher level scopes would really know what exceptions those lower level resources can throw. Now hold on!

Unfortunately, exceptions only allow indirection over the call stack, and different scopes with their different cardinalities usually run on multiple different threads. No way to communicate through that with exceptions. We need something more powerful here. Answer: async message passing. Catch every exception at the root of the lower level scope. Don't ignore anything, don't let anything slip through. This will close and dispose all resources created on the call stack of the current scope. Then propagate error messages to scopes higher up by using message queues / channels in the exception handling routine, until you reach the level where the concretions are known. That's the guy who knows how to handle it.

SUMMA SUMMARUM

So according to my interpretation catch late means to catch exceptions at the most convenient place WHERE YOU ARE NOT BREAKING ABSTRACTION ANYMORE. Do not catch too early! Catch exceptions at the layer where you create the concrete exception throwing instances of the resource abstractions, the layer which knows the concretions of the abstractions. The "wiring" layer.

HTH. Happy coding!

Body:
Others have summarized quite well why to throw early. Let me concentrate on the why to catch late part instead, for which I haven't seen a satisfying explanation for my taste.

SO WHY EXCEPTIONS?

There seems to be quite a confusion around why exceptions exist in the first place. Let me share the big secret here: the reason for exceptions, and exception handling is... ABSTRACTION.

Have you seen code like this:

static int divide(int dividend, int divisor) throws DivideByZeroException {
    if (divisor == 0)
        throw new DivideByZeroException(); // that's a checked exception indeed

    return dividend / divisor;
}

static void doDivide() {
    int a = readInt();
    int b = readInt();
    try {
        int res = divide(a, b);
        System.out.println(res);
    } catch (DivideByZeroException e) {
        // checked exception... I'm forced to handle it!
        System.out.println("Nah, can't divide by zero. Try again.");
    }
}

That's not how exceptions should be used. Code like the above do exist in real life, but they are more of an aberration, and are really the exception (pun). The definition of division for example, even in pure mathematics, is conditional: it is always the "caller code" who has to handle the exceptional case of zero to restrict the input domain. It's ugly. It's always pain for the caller. Still, for such situations the check-then-do pattern is the natural way to go:

static int divide(int dividend, int divisor) {
    // throws unchecked ArithmeticException for 0 divisor
    return dividend / divisor;
}

static void doDivide() {
    int a = readInt();
    int b = readInt();
    if (b != 0) {
        int res = divide(a, b);
        System.out.println(res);
    } else {
        System.out.println("Nah, can't divide by zero. Try again.");
    }
}

Alternatively, you can go full commando on OOP style like this:

static class Division {
    final int dividend;
    final int divisor;

    private Division(int dividend, int divisor) {
        this.dividend = dividend;
        this.divisor = divisor;
    }

    public boolean check() {
        return divisor != 0;
    }

    public int eval() {
        return dividend / divisor;
    }

    public static Division with(int dividend, int divisor) {
        return new Division(dividend, divisor);
    }
}

static void doDivide() {
    int a = readInt();
    int b = readInt();
    Division d = Division.with(a, b);
    if (d.check()) {
        int res = d.eval();
        System.out.println(res);
    } else {
        System.out.println("Nah, can't divide by zero. Try again.");
    }
}

As you see, the caller code has the burden of the pre-check, but does not do any exception handling after. If an ArithmeticException ever comes from calling divide or eval, then it   is YOU who has to do the exception handling and fix your code, because you forgot the check(). For the similar reasons catching a NullPointerException is almost always the wrong thing to do.

Now there are some folks who say they want to see the exceptional cases in the method / function signature, i.e. to explicitly extend the output domain. They are the ones who favor checked exceptions. Of course, changing the output domain should force any direct caller code to adapt, and that would indeed be achieved with checked exceptions. But you don't need exceptions for that! That's why you have Nullable<T> generic classes, case classes, algebraic data types, and union types. Some OO people might even prefer returning null for simple error cases like this:

static Integer divide(int dividend, int divisor) {
    if (divisor == 0) return null;
    return dividend / divisor;
}

static void doDivide() {
    int a = readInt();
    int b = readInt();
    Integer res = divide(a, b);
    if (res != null) {
        System.out.println(res);
    } else {
        System.out.println("Nah, can't divide by zero. Try again.");
    }
}

Technically exceptions can be used for the purpose like the above, but here is the point: exceptions do not exist for such usage. Exceptions are pro abstraction. Exception are about indirection. Exceptions allow for extending the "outcome" domain without breaking direct client contracts, and deferring error handling to "somewhere else". If your code throws exceptions which are handled in direct callers of the same code, without any layers of abstraction in between, then you are doing it W. R. O. N. G.

HOW TO CATCH LATE?

So here we are. I have argued my way through to show that using exceptions in the above scenarios is not how exceptions are meant to be used. There exists a genuine use case though, where the abstraction and indirection offered by exception handling is indispensable. Understanding such usage will help understanding the catch late recommendation too.

That use case is: Programming Against Resource Abstractions...

Yeah, business logic should be programmed against abstractions, not concrete implementations. Top level IOC "wiring" code will instantiate the concrete implementations of the resource abstractions, and pass them down to the business logic. Nothing new here. But the concrete implementations of those resource abstractions can potentially be throwing their own implementation specific exceptions, can't they?

So who can handle those implementation specific exceptions? Is it possible to handle any resource specific exceptions at all in the business logic then? Nope, it is not. The business logic is programmed against abstractions, which does exclude the knowledge of those implementation specific exception details.

"Aha!", you might say: "but that's why we can subclass exceptions and create exception hierarchies" (check out Mr. Spring!). Let me tell you, that's a fallacy. Firstly, every reasonable book on OOP says concrete inheritance is bad, yet somehow this core component of JVM, exception handling, is closely tied with concrete inheritance. Ironically, Joshua Bloch could not have written his Effective Java book before he could get the experience with a working JVM, could he? It is more of a "lessons learnt" book for the next generation. Secondly, and more importantly, if you catch a high-level exception then how are you going to HANDLE it? PatientNeedsImmediateAttentionException: do we have to give her a pill or amputate her legs!? How about a switch statement over all the possible subclasses? There goes your polymorphism, there goes the abstraction. You got the point.

So who can handle the resource specific exceptions? It must be the one who knows the concretions! The one who instantiated the resource! The "wiring" code of course! Check this out:

Business logic coded against abstractions... NO CONCRETE RESOURCE ERROR HANDLING!

static interface InputResource {
    String fetchData();
}

static interface OutputResource {
    void writeData(String data);
}

static void doMyBusiness(InputResource in, OutputResource out, int times) {
    for (int i = 0; i < times; i++) {
        System.out.println("fetching data");
        String data = in.fetchData();
        System.out.println("outputting data");
        out.writeData(data);
    }
}

Meanwhile somewhere else the concrete implementations...

static class ConstantInputResource implements InputResource {
    @Override
    public String fetchData() {
        return "Hello World!";
    }
}

static class FailingInputResourceException extends RuntimeException {
    public FailingInputResourceException(String message) {
        super(message);
    }
}

static class FailingInputResource implements InputResource {
    @Override
    public String fetchData() {
        throw new FailingInputResourceException("I am a complete failure!");
    }
}

static class StandardOutputResource implements OutputResource {
    @Override
    public void writeData(String data) {
        System.out.println("DATA: " + data);
    }
}

And finally the wiring code... Who handles concrete resource exceptions? The one who knows about them!

static void start() {
    InputResource in1 = new FailingInputResource();
    InputResource in2 = new ConstantInputResource();
    OutputResource out = new StandardOutputResource();

    try {
        ReusableBusinessLogicClass.doMyBusiness(in1, out, 3);
    }
    catch (FailingInputResourceException e)
    {
        System.out.println(e.getMessage());
        System.out.println("retrying...");
        ReusableBusinessLogicClass.doMyBusiness(in2, out, 3);
    }
}

Now bear with with me. The above code is simplistic. You might say you have an enterprise application / web container with multiple scopes of IOC container managed resources, and you need automatic retries and reinitialization of session or request scope resources, etc. The wiring logic on the lower level scopes might be given abstract factories to create resources, therefore not being aware of the exact implementations. Only higher level scopes would really know what exceptions those lower level resources can throw. Now hold on!

Unfortunately, exceptions only allow indirection over the call stack, and different scopes with their different cardinalities usually run on multiple different threads. No way to communicate through that with exceptions. We need something more powerful here. Answer: async message passing. Catch every exception at the root of the lower level scope. Don't ignore anything, don't let anything slip through. This will close and dispose all resources created on the call stack of the current scope. Then propagate error messages to scopes higher up by using message queues / channels in the exception handling routine, until you reach the level where the concretions are known. That's the guy who knows how to handle it.

SUMMA SUMMARUM

So according to my interpretation catch late means to catch exceptions at the most convenient place WHERE YOU ARE NOT BREAKING ABSTRACTION ANYMORE. Do not catch too early! Catch exceptions at the layer where you create the concrete exception throwing instances of the resource abstractions, the layer which knows the concretions of the abstractions. The "wiring" layer.

HTH. Happy coding!


问:
What programming language generates fewest hard-to-find bugs?
What language, in your opinion, allows the average programmer to output features with the least amount of hard-to-find bugs? This is of course, a very broad question, and I'm interested in very broad and general answers and wisdoms.

Personally I find that I spend very little time looking for strange bugs in Java and C# programs, while C++ code has its distinct set of recurring bugs, and Python/similar has its own set of common and silly bugs that would be detected by the compiler in other languages.

Also I find it hard to consider functional languages in this regard, because I've never seen a big and complex program written in entirely functional code. Your input please.

Edit: Completely arbitrary clarification of hard-to-find bug: Takes more than 15 minutes to reproduce, or more than 1 hour to find cause of and fix.

Forgive me if this is a duplicate, but I didn't find anything on this specific topic.

答:
Instead of talking about languages what about talking about language-features

java forces you to think about exceptions (throws ...) and you must either publisch or handle these exceptions. Does that realy prevent me from forgetting errorsituations or am i using more exceptions that are derived from SystemException that do not need this handling?

what about "design by contract" (http://en.wikipedia.org/wiki/Design_by_contract) that forces me to think about pre and postconditions. I have read that is now possible with c#-4.0.


答:
I would say this kind of thing is more suitable for RDD: Reading-Driven Development.

This is where you read in a book the algorithm for something complicated like a Kalman filter, and then translate that into an implementation in your target environment.

The disadvantage is that doing things that way means you don't get test cases for free as part of the design process. On the other hand, something wll known like that almost certainly has an existing implementation (e.g. Commons Math). And then it's straighforward to use that as a test oracle for your new implementation; all you need to worry about is that your set of test cases covers all paths in your code.

Title: Building complex algorithms with TDD

Body:
I'm trying to adopt TDD in my daily programming practice.  I use it at work very effectively, but I'm having trouble with my personal projects where I'm using some complex algorithms.

The particular algorithm that makes me ask this question is the Extended Kalman Filter.  It's complex enough that I'm not confident in the code I've written, but it's simple enough that it's hard to break up.

I could write a test for the algorithm with an input and the expected output, but I'll do a lot of thrashing and shotgun coding in the middle because I don't have confidence in those intermediate steps.

If you've worked with reasonable complex algorithms and use TDD, what is your approach?


问:
Efficient algorithm for joining sieves
I'm trying to find an efficient algorithm for the following algorithm.

I have a sequence consisting of lists of indices denoting indices to be removed. The semantics are such that each sequence must be performed in order. I want to take these sequences and flatten them into one sequence of absolute indices to be removed.

This can be achieved by performing a series of sieves (somewhat akin to the Sieve of Eratosthenes). The caveat is that this technique is slow (quadratic).

Thus this group of relative indices:

```<code>R0: 0 3 10 15
R1: 2 7 20
R2: 1 11 12 14 17
R3: 0 1 2
</code>```

Would correspond to this group of absolute indices:

```<code>A0: 0 3 10 15
A1: 4 9 22
A2: 2 17 18 20 24
A3: 1 5 6
</code>```

And when merged into one sequence of absolute indices, I would have the following:

```<code>A': 0 1 2 3 4 5 6 9 10 15 17 18 20 22 24
</code>```

There may be any number of relative sequences, each of which may contain any number of elements and may have large gaps between indices. The input relative sequences are sorted in increasing order any may not contain duplicates.

Obtaining the intermediate A# lists is unnecessary. I only care about the list A' from the inputs R#.

Clarification on the algorithm

Let's take the list of non-negative integers

```<code>0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ...
</code>```

And remove the indices given by R0

Then we have

```<code>1 2 4 5 6 7 8 9 10 11 12 13 14 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ...
</code>```

The removed values yield A0 (0 3 10 15)

Now remove the indices given by R1

```<code>1 2 5 6 7 8 10 11 12 13 14 16 17 18 19 20 21 23 24 25 26 27 28 29 30 ...
</code>```

The removed values yield A1 (4 9 22)

Now remove the indices given by R2

```<code>1 5 6 7 8 10 11 12 13 14 16 19 21 23 25 26 27 28 29 30 ...
</code>```

The removed values yield A2 (2 17 18 20 24)

Now remove the indices given by R3

```<code>7 8 10 11 12 13 14 16 19 21 23 25 26 27 28 29 30 ...
</code>```

The removed values yield A3 (1 5 6)

答:
Your complexity analysis is wrong.  Generating each intermediate list is linear.  Merging the lists if the final list has n elements and you have k intermediate lists is O(k n) with a naive algorithm, and O(n log(k)) if you use a standard priority queue (which under the hood is probably a heap).

The only quadratic operation is removing the elements from the long list.  Odds are that you are calling a method to remove an element, which is going to have to recopy the whole list.  That is linear per element removed, which will scale quadratically when you remove a lot of elements.

Instead what you need to do is run through the list, keeping track of where you are copying from and where you are copying to.  When you run across elements to skip, just move the "copying from" location and don't copy.  When you finish running through the whole list, then change the length of the data to the last location you copied from.

Title: Efficient algorithm for joining sieves


问:
What are good unit tests to cover the use case of rolling a die?
I'm trying to get to grips with unit testing.

Say we have a die which can has a default number of sides equal to 6 (but can be 4, 5 sided etc.):

```<code>import random
class Die():
    def __init__(self, sides=6):
        self._sides = sides

    def roll(self):
        return random.randint(1, self._sides)
</code>```

Would the following be valid/useful unit tests?

test a roll in the range 1-6 for a 6 sided die

test a roll of 0 for a 6 sided die

test a roll of 7 for a 6 sided die

test a roll in the range 1-3 for a 3 sided die

test a roll of 0 for a 3 sided die

test a roll of 4 for a 3 sided die

I'm just thinking that these are a waste of time as the random module has been around for long enough but then i think if the random module gets updated (say i update my Python version) then at least i'm covered.

Also, do I even need to test other variations of die rolls e.g. the 3 in this case, or is it good to cover another initialized die state?

答:
The tests you suggest in your question don't detect a modular arithmetic counter as implementation. And they don't detect common implementation errors in probability distribution related code like return 1 + (random.randint(1,maxint) % sides). Or a change to the generator that results in 2-dimensional patterns.

If you actually want to verify that you are generating evenly distributed random-appearing numbers you need to check a very wide variety of properties. To do a reasonably good job at that you could run http://www.phy.duke.edu/~rgb/General/dieharder.php on your generated numbers. Or write a similarly complex unit-test suite.

That's not the fault of unit-testing or TDD, randomness just happens to be a very difficult property to verify. And a popular topic for examples.


问:
Should a large company standardize engineering tools across all teams internationally?
I've been thinking a lot about the problem of standardization across large companies.  For me, the answer is pretty clear: do not arbitrarily standardize on tools just because that's what everyone else does.  It's counter-productive.

I'm thinking about source control, bug tracking and testing tools primarily.  It seems so obvious to me that I can't really think of many good counter-arguments.  Some I've thought of :

Easier sharing between teams

Easier for IT to manage

(1) is definitely true if different teams are working on the same codebase/product.  But in cases where one team doesn't work directly with the code I don't think is a valid reason.

(2) is just kind of pisses me off if that's really an argument.  The limitations placed on programmers, I believe, is more burdensome than any extra work piled on to IT.  But I'm not an IT guy.

I'm hoping for some better arguments than those.

答:
I would say in the situation described below.

My company has a relatively small IT department aimed at supporting the software used to run the company. The application is written in two languages, Java and RPG. We use Rational Application Developer(based on Eclipse) as our only IDE. There are some other minor programs we also use, but those are mostly the choice of the developer if he wants to use them.

The reasons I see that this is good are, in no particular order:

Easily shared projects. We can save all the project settings in a zip and anyone else can see it without any issues between IDEs.

Easier IT updates. Yes, I think this is a valid argument - within reason! If this "standardization" argument is limiting development efforts by limiting what software a developer can use when he absolutely needs it, it is bad. That's not an issue at my workplace because we only work with a couple of code bases, so everyones needs are basically the same.

Teamwork is optimized. If everyone uses similiar tools, it is easier for anyone to come over and look at your code without having to orient himself to your IDE. With most IDEs now you can customize them to a workspace you like without losing the frame of reference. All console tabs look the same no matter where on the screen they are.

Project switching is easier. Any developer can move to any project without having to learn new ways of doing the meta stuff like version control. The same procedures and software used everywhere reduce context change time.

Overall I'd say that having everyone use the same IDE, version control, and bug tracking software is a good thing, and helps teams work better. Below that though the developer should be free to use what tools he needs. If he prefers TextEdit to Notepad++, let him use that - it won't cost any more. Or don't force him to use a query tools if he prefers to connect straight to the database for simple queries.


答:
Seeding the random number generator and verifying expected results is NOT, as far as I can see, a valid test. It makes assumptions as to HOW your dice works internally, which is naughty-naughty. The developers of python could change the random number generator, or the die (NOTE: "dice" is plural, "die" is singular. Unless your class implements multiple die rolls in one call, it should probably be called "die") could use a different random number generator.

Similarly, mocking the random function assumes that the class implementation works exactly as expected. Why might this not be the case? Someone might take control of the default python random number generator, and to avoid that, a future version of your die may fetch several random numbers, or larger random numbers, to mix in more random data. A similar scheme was used by the makers of the FreeBSD operating system, when they suspected the NSA was tampering with the hardware random number generators built into CPUs.

If it were me, I'd run, say, 6000 rolls, tally them, and make sure that each number from 1-6 is rolled between 500 and 1500 times. I would also check that no numbers outside that range are returned. I might also check that, for a second set of 6000 rolls, when ordering the [1..6] in order of frequency, the result is different (this will fail once out of 720 runs, if the numbers are random!). If you want to be thorough, you might find the frequency of numbers following a 1, following a 2, etc; but make sure your sample size is big enough, and you have enough variance. Humans expect random numbers to have fewer patterns than they actually do.

Repeat for a 12 sided, and 2 sided die (6 is the most used, so is the most expected for anyone writing this code).

Finally, I would test to see what happens with a 1-sided die, a 0 sided die, a -1 sided die, a 2.3 sided die, a [1,2,3,4,5,6] sided die, and a "blah"-sided die. Of course, these should all fail; do they fail in a useful way? These should probably fail on creation, not on rolling.

Or, perhaps, you want too handle these differently - perhaps creating a die with [1,2,3,4,5,6] should be acceptable - and perhaps "blah" as well; this might be a die with 4 faces, and each face having a letter on it. The game "Boggle" springs to mind, as does a magic eight ball.

And finally, you might want to contemplate this: http://lh6.ggpht.com/-fAGXwbJbYRM/UJA_31ACOLI/AAAAAAAAAPg/2FxOWzo96KE/s1600-h/random%25255B3%25255D.jpg

Title: What are good unit tests to cover the use case of rolling a die?

Body:
I'm trying to get to grips with unit testing.

Say we have a die which can has a default number of sides equal to 6 (but can be 4, 5 sided etc.):

```<code>import random
class Die():
    def __init__(self, sides=6):
        self._sides = sides

    def roll(self):
        return random.randint(1, self._sides)
</code>```

Would the following be valid/useful unit tests?

test a roll in the range 1-6 for a 6 sided die

test a roll of 0 for a 6 sided die

test a roll of 7 for a 6 sided die

test a roll in the range 1-3 for a 3 sided die

test a roll of 0 for a 3 sided die

test a roll of 4 for a 3 sided die

I'm just thinking that these are a waste of time as the random module has been around for long enough but then i think if the random module gets updated (say i update my Python version) then at least i'm covered.

Also, do I even need to test other variations of die rolls e.g. the 3 in this case, or is it good to cover another initialized die state?


答:
The issue seems to be that the issue tracker is not part of your workflow.  If it was, then you would be required to use it to get any work done.

IMO a good goal would be to just isolate a small issues or feature, enter one in your tracker, then create a matching branch.  I disagree with the previous answer in that I don't mind having issues for everything: typos, language changes, etc...  If it takes a while to create that issue, then improve the workflow so that it takes less time to create issues.

The benefit isn't just having an issue tracker, it's in how you use the tracker to improve the project's direction and workflow.

Sometimes I would type out an issue and think "This sounds like too large of a task, am i really going to work on this? Maybe I should break this up into smaller tasks" or "My description barely makes any sense, maybe I should research this and see if this is worth coding".  It also allows you to review and evaluate your own progress.

Many people won't care, but it's more for you and your future team than for your boss.  Your boss just needs to know that it's a part of developing software, like the patient file folder you see at the doctor's office.

Some examples of issue tracker integration:

hubot and redmine

Sub and Jira


问:
Is it bad practice to update an object in a static method?
Still learning .net and OOP and have a basic question I hope. This is an asp.net mvc app.

Looking at the code below, I am most concerned with the line in CheckShippingVendor that says ValidateDelivery(shipmentItem). Is it okay to pass in an object as a parameter and have the private static method update that item.

When I did a resharper Extract Method refactoring this is what it did for me.

Class is instantiated and call the CheckShippingVendor method:

```<code>var packageStatus = _inventoryService.CheckShippingVendor(shipmentId, shipmentFile);
</code>```

Here is the rest of the code:

```<code>public PackageStatus CheckShippingVendor(string shipmentId, mvFile shipmentFile)
{
        var packageStatus = new PackageStatus();
        using (var shipmentItem = shipmentFile.Read(shipmentId))
        {
                ValidateDelivery(shipmentItem);
                shipmentFile.Write(shipmentId, shipmentItem);
        }
        return packageStatus;
}

private static void ValidateDelivery(mvItem shipmentItem)
{
        int shipped;
        var shippedResult = Int32.TryParse(shipmentItem[1].ToString(), out shipped);
        if (!shippedResult)
            return;

        int delivered;
        var deliveredResult = Int32.TryParse(shipmentItem[57].ToString(), out delivered);
        if (!deliveredResult)
            return;

        shipmentItem.Message = "NO INFORMATION AT THIS TIME";
}
</code>```

答:
Note: this question may be better served in codereview.stackexchange.com

In general, I try to keep static methods side-effect free.

In your particular example, I would change it as follows:

```<code>public PackageStatus CheckShippingVendor(string shipmentId, mvFile shipmentFile)
{
    var packageStatus = new PackageStatus();
    using (var shipmentItem = shipmentFile.Read(shipmentId))
    {
        if(!ValidateDelivery(shipmentItem))
            shipmentItem.Message = "NO INFORMATION AT THIS TIME";

        shipmentFile.Write(shipmentId, shipmentItem);
    }
    return packageStatus;
}

private static bool IsDeliveryValid(mvItem shipmentItem)
{
    int shipped;
    var shippedResult = Int32.TryParse(shipmentItem[1].ToString(), out shipped);
    if (!shippedResult)
        return false;

    int delivered;
    return Int32.TryParse(shipmentItem[57].ToString(), out delivered);
}
</code>```

This does two things:

It removes the side-effect from your static method

It reduces your validation method to a single responsibility: giving you a yes/no answer to whether or not a delivery is valid.

That said, I would iterate on the CheckShippingVendor method some more:

The name gives no indication that there are side effects.

It always returns an empty PackageStatus, rendering the return value useless.

It appears to have several responsibilities which could be broken into separate helper methods.

Body:
Note: this question may be better served in codereview.stackexchange.com

In general, I try to keep static methods side-effect free.

In your particular example, I would change it as follows:

public PackageStatus CheckShippingVendor(string shipmentId, mvFile shipmentFile)
{
    var packageStatus = new PackageStatus();
    using (var shipmentItem = shipmentFile.Read(shipmentId))
    {
        if(!ValidateDelivery(shipmentItem))
            shipmentItem.Message = "NO INFORMATION AT THIS TIME";

        shipmentFile.Write(shipmentId, shipmentItem);
    }
    return packageStatus;
}

private static bool IsDeliveryValid(mvItem shipmentItem)
{
    int shipped;
    var shippedResult = Int32.TryParse(shipmentItem[1].ToString(), out shipped);
    if (!shippedResult)
        return false;

    int delivered;
    return Int32.TryParse(shipmentItem[57].ToString(), out delivered);
}

This does two things:

It removes the side-effect from your static method

It reduces your validation method to a single responsibility: giving you a yes/no answer to whether or not a delivery is valid.

That said, I would iterate on the CheckShippingVendor method some more:

The name gives no indication that there are side effects.

It always returns an empty PackageStatus, rendering the return value useless.

It appears to have several responsibilities which could be broken into separate helper methods.


答:
Modifying an object passed in as a parameter to a static method is a perfectly valid technique.  It is valid, because you are not holding any state changes outside the object being modified.

If your static method were changing some static state in your static class, that would be a different story.  That arrangement is widely regarded as "untestable."

Your static method name could be clearer, however.  There is no indication in the name of the method that the object being passed in is being modified.  Either change the method name to something like UpdateDeliveryStatus(), or change the method so that it returns some value that represents the delivery state without modifying the passed-in object.

Title: Is it bad practice to update an object in a static method?

Body:
Still learning .net and OOP and have a basic question I hope. This is an asp.net mvc app.

Looking at the code below, I am most concerned with the line in CheckShippingVendor that says ValidateDelivery(shipmentItem). Is it okay to pass in an object as a parameter and have the private static method update that item.

When I did a resharper Extract Method refactoring this is what it did for me.

Class is instantiated and call the CheckShippingVendor method:

```<code>var packageStatus = _inventoryService.CheckShippingVendor(shipmentId, shipmentFile);
</code>```

Here is the rest of the code:

```<code>public PackageStatus CheckShippingVendor(string shipmentId, mvFile shipmentFile)
{
        var packageStatus = new PackageStatus();
        using (var shipmentItem = shipmentFile.Read(shipmentId))
        {
                ValidateDelivery(shipmentItem);
                shipmentFile.Write(shipmentId, shipmentItem);
        }
        return packageStatus;
}

private static void ValidateDelivery(mvItem shipmentItem)
{
        int shipped;
        var shippedResult = Int32.TryParse(shipmentItem[1].ToString(), out shipped);
        if (!shippedResult)
            return;

        int delivered;
        var deliveredResult = Int32.TryParse(shipmentItem[57].ToString(), out delivered);
        if (!deliveredResult)
            return;

        shipmentItem.Message = "NO INFORMATION AT THIS TIME";
}
</code>```


问:
Preferred Scala code style for several embedded brace sets
I was wondering the correct way to format a situation such as this, where I have a def, a foreach and an if clause all nested, requiring braces. </p>

<p>Currently I find it hard to read, and there is no obvious place to put the 'x =>' bit. Thank you.    </p>

```<code>def getAnswer(): String =
{
  var sum = 0
  (0 until 1000).foreach
  { x =>
    if (x % 3 == 0 || x % 5 == 0)
    {
      sum += x
    }
  }
  sum.toString
}
</code>```

答:
Scala has an official style guide which recommends putting opening braces on the same line, not on a line of their own. Parameters should also be on the first line.

```<code>def getAnswer(): String = {
  var sum = 0
  (0 until 1000).foreach { x =>
    if (x % 3 == 0 || x % 5 == 0) {
      sum += x
    }
  }
  sum.toString
}
</code>```

In your specific case, you should probably remove most of your braces, as all but the outermost are not needed (also, filter would be idiomatic here):

```<code>def getAnswer(): String = {
  var sum = 0
  0 until 1000 filter (x => x % 3 == 0 || x % 5 == 0) foreach (x => sum += x)
  sum.toString
}
</code>```

Body:
Scala has an official style guide which recommends putting opening braces on the same line, not on a line of their own. Parameters should also be on the first line.

def getAnswer(): String = {
  var sum = 0
  (0 until 1000).foreach { x =>
    if (x % 3 == 0 || x % 5 == 0) {
      sum += x
    }
  }
  sum.toString
}

In your specific case, you should probably remove most of your braces, as all but the outermost are not needed (also, filter would be idiomatic here):

def getAnswer(): String = {
  var sum = 0
  0 until 1000 filter (x => x % 3 == 0 || x % 5 == 0) foreach (x => sum += x)
  sum.toString
}


答:
Giant regexes are a bad choice in most cases. In my experience, they are often used because the developer is not familiar with parsing (see Thomas Eding's answer).

Anyway, let's assume you want to stick to a regex-based solution.

As I don't know the actual code, I will examine the two possible scenarios:

The regex is simple (a lot of literal matching and few alternatives)

In this case the advanced features offered by a single regex are not indispensable. This means you will likely benefit from splitting it.

The regex is complex (a lot of alternatives)

In this case you cannot realistically have full test coverage, because you probably have millions of possibile flows. So, in order to test it, you need to split it.

I might lack imagination, but I can't think of any real-world situation where a 100-line regex is a good solution.

Title: Should I refactor large functions that mostly consist of one regex?

Body:
I just wrote a function that spans approximately 100 lines. Hearing that, you are probably tempted to tell me about single responsibilities and urge me to refactor. This is my gut instinct as well, but here is the issue: The function does one thing. It performs a complex string manipulation, and the function body consists mostly of one verbose regex, broken up into many lines that are documented. If I broke up the regex into multiple functions, I feel like I would actually lose readability, since I am effectively switching languages, and won't be able to take advantage of some features regexes offer. Here now is my question:

When it comes to string manipulation with regular expressions, are large function bodies still an anti-pattern? It seems like named capture groups serve a very similar purpose to functions. By the way, I have tests for every flow through the regex.


答:
Yes, but it needs to be done in a manner which is sensible and doesn't affect the productivity of developers for the sake of process.

There is definitely a case for standardisation of bug tracking/source control as a lot of enterprise IT is somewhat isolated and distributed. For instance, consultants might be hired to create something for one business unit, in-house staff might be maintaining a legacy system and over in the Republic of Elbonia HQ, another in-house team is working something else.

Common source control and bug tracking systems, place everyone on a level playing field and make it easier to deal with multiple systems. Imagine your support people having to learn 3 different bug tracking systems because each team preferred a different solution. Without standardisation you can also end up with the situation of the consultants using source control system X and in-house using source control system Y (or worse, no SC at all), which will lead to all sorts of fun when the software is completed and the consultancy either moves on or goes bust.

This doesn't always mean you'll end up standardising on the best software available though, often the software which is chosen is based upon compromise and practicalities rather than having all of the latest and greatest features.

Standardisation also requires common sense. There is a level where you just have to let the developer get on with the job without undue interference. Where that line lies depends on the culture of the organisation, the kind of products being worked upon and regulatory factors.

There is more to software than just code.

Title: Should a large company standardize engineering tools across all teams internationally?

Body:
I've been thinking a lot about the problem of standardization across large companies.  For me, the answer is pretty clear: do not arbitrarily standardize on tools just because that's what everyone else does.  It's counter-productive.

I'm thinking about source control, bug tracking and testing tools primarily.  It seems so obvious to me that I can't really think of many good counter-arguments.  Some I've thought of :

Easier sharing between teams

Easier for IT to manage

(1) is definitely true if different teams are working on the same codebase/product.  But in cases where one team doesn't work directly with the code I don't think is a valid reason.

(2) is just kind of pisses me off if that's really an argument.  The limitations placed on programmers, I believe, is more burdensome than any extra work piled on to IT.  But I'm not an IT guy.

I'm hoping for some better arguments than those.


问:
Proper way to structure JSON for front-end consumption
Having worked on several different web application code bases, I've seen some divergence in how back-ends serving JSON to front-ends structure that data. In particular, when a backend wants to return a number of objects of the same structure. Do you just wrap up all of the objects in an array? What about the "key" of the first array? What should that be?

For example, say my back end wants to return a number of "image" items. Each image item is structured like this:

```<code>{
    "id" : 123,
    "filename" : "someFile.jpg",
    "caption" : "some image or other",
    "gallery" : 123
}
</code>```

How would I structure a grouping of these items properly for consumption by a javascript front-end?

答:
Coming from rails and it auto-magical ability to transform ruby object into XML JSON... I would say that you should just send an array of your entities.
If you are worring about not knowing what could be inside the array. Should you be using a RESTful approach, the URL:HTTP_VERB pair will be telling you the resource you are accessing and what to expect from the response.</p>


答:
Coming from a front-end developer perspective, I prefer simple and semantic as much as possible. Generally inside a consistent envelope for debugging and tracking, the actual data would be as follows:

```<code>{
    "images" : [
        {
          "id" : 123,
          "filename" : "someFile.jpg",
          "caption" : "some image or other",
          "gallery" : 123
        },{
          "id" : 124,
          "filename" : "someFile.jpg",
          "caption" : "some image or other",
          "gallery" : 124
        }
    ]
}
</code>```

Envelopes often look something like this:

```<code>   {
      "messageID"     : "sflskdfj-asldkja-asdlk", // some uuid
      "sendDate"      : 1394134506764, // time at which the server sent the message
      "requestMethod" : "GET",
      // whatever else you want for front-end tracking or debugging
      "data"          : {
          "images" : [...]
      }
   }
</code>```

Title: Proper way to structure JSON for front-end consumption

Body:
Having worked on several different web application code bases, I've seen some divergence in how back-ends serving JSON to front-ends structure that data. In particular, when a backend wants to return a number of objects of the same structure. Do you just wrap up all of the objects in an array? What about the "key" of the first array? What should that be?

For example, say my back end wants to return a number of "image" items. Each image item is structured like this:

```<code>{
    "id" : 123,
    "filename" : "someFile.jpg",
    "caption" : "some image or other",
    "gallery" : 123
}
</code>```

How would I structure a grouping of these items properly for consumption by a javascript front-end?

Body:
Coming from a front-end developer perspective, I prefer simple and semantic as much as possible. Generally inside a consistent envelope for debugging and tracking, the actual data would be as follows:

{
    "images" : [
        {
          "id" : 123,
          "filename" : "someFile.jpg",
          "caption" : "some image or other",
          "gallery" : 123
        },{
          "id" : 124,
          "filename" : "someFile.jpg",
          "caption" : "some image or other",
          "gallery" : 124
        }
    ]
}

Envelopes often look something like this:

   {
      "messageID"     : "sflskdfj-asldkja-asdlk", // some uuid
      "sendDate"      : 1394134506764, // time at which the server sent the message
      "requestMethod" : "GET",
      // whatever else you want for front-end tracking or debugging
      "data"          : {
          "images" : [...]
      }
   }


问:
Canonical representation of a class object containing a list element in XML
I see that most implementations of JAX-RS represent a class object containing a list of elements as follows (assume a class House containing a list of People)

```<code><houses>
  <house>
    <person>
      <name>Adam</name>
    </person>
    <person>
      <name>Blake</name>
    </person>
  </house>
  <house>
  </house>
</houses>
</code>```

The result above is obtained for instance from Jersey 2 JAX-RS implementation,
notice Jersey creates a wrapper class "houses" around each house, however strangely it doesn't create a wrapper class around each person!
I don't feel this is a correct mapping of a list, in other words I'd feel more confortable with something like this:

```<code><houses>
  <house>
    <persons>
    <person>
      <name>Adam</name>
    </person>
    <person>
      <name>Blake</name>
    </person>
    </persons>
  </house>
  <house>
  </house>
</houses>
</code>```

Is there any document explaining how an object should be correctly mapped apart from any opninion?

答:
XML documents can only have a single root node, so the <houses> is necessary if you would want to serialize more than one <house>.

A <persons> element is not necessary as a node may contain any number of children with the same tag name – they can be disambiguated by position. It adds complication without adding value or structure. But such a grouping may be adequate e.g. when we have different kinds of inhabitants in our house:

```<code><house>
  <inhabitants>
    <human>
      <name>Larry</name>
    </human>
    <human>
      <name>Guido</name>
    </human>
    <dog>
      <name>Rasmus</name>
    </dog>
  </inhabitants>
</house>
</code>```

Here, <inhabitants> encodes a relation, whereas <human> and <dog> encode a type.

Body:
XML documents can only have a single root node, so the <houses> is necessary if you would want to serialize more than one <house>.

A <persons> element is not necessary as a node may contain any number of children with the same tag name – they can be disambiguated by position. It adds complication without adding value or structure. But such a grouping may be adequate e.g. when we have different kinds of inhabitants in our house:

<house>
  <inhabitants>
    <human>
      <name>Larry</name>
    </human>
    <human>
      <name>Guido</name>
    </human>
    <dog>
      <name>Rasmus</name>
    </dog>
  </inhabitants>
</house>

Here, <inhabitants> encodes a relation, whereas <human> and <dog> encode a type.


答:
I depend heavily on my issue tracker, to stop people coming in and taking 10 minutes to explain a problem to me, which, when I have time to do something about it, I will have forgotten completely.

By making them write it down, they can compose what they want to say, and the result tends to be more concise. It gives me all the outstanding problems in one place. It also means that I can easily annotate the issue with my thoughts/progress.

It sounds like your main problem is with getting it set up. You may be able to do this in stages:

   Stage 1. When your boss comes in, wait for them to explain the problem, taking notes (on computer, if you can). At the end, ask your boss to send you a reminder email so it doesn't get lost in the shuffle.

   Stage 2. Once your boss is used to sending you reminder emails, ask them to put a summary in the email.

   Stage 3. get them to put the entire problem in an email, after they have explained it to you

   Stage 4. get them to put the entire problem in an email, as soon as they start explaining the problem.

   Stage 5. Get them to put the entire problem in the bugtracker.

Make sure there is as little resistance for them as possible. If you can, get a bugtracker that doesn't have any required fields, and doesn't need a log in; just one edit box to put the problem. If they can email a specific address to add a bug, even better!

If you can get to stage 2, you can cut & paste the email into the bugtracker.


问:
Will Authentication over HTTPS Slow My Application?
I am building a web application and RESTful web service.

I have been reading various articles about the best way to authenticate the requests to the web service.

The best option for me seems to be to use HTTP basic authentication. Pretty much every article ive read says that authentication should be encrypted over SSL or equivalent.

Im not totally sure what this involves. Does this mean that my whole web service will have to be on a secure server? Will this slow things down?

答:
How are you going to accomplish the basic authentication?

If it is a hard coded username/password and you are using your webserver's built in functionality to do it, it will likely have a near zero impact.  If you are off doing crazy things in a database or something similar, then yes there could be an impact.

Like others have noted here, SSL & sending the extra headers will technically make things slower but it will not be significant in any way.


问:
Is there a minimum team size required to see a benefit from Agile?
I work at a company that has repeatedly cut the sizes of its development team, to the point that previous 10-man teams are now down to one developer per product (and a couple of testers shared between 5 products).  We used to be fairly process heavy, having been a spin off from a larger company, and inherited its multi-stage waterfall process.

It has come down from the executive team that we are not releasing software fast enough, and that this is likely the fault of the process (which may be a contributor, although the 90% loss of manpower probably didn't help).  There has been a push for us to move to an Agile process to avoid spending time writing design documents, etc.

I guess I'm just curious as to whether a switch to Agile will help with single-person teams.  It was my understanding that a lot of the benefits come from higher visibility and more communication between team members, but I know what I'm doing and so does my manager.  I already do TDD since we have no one to test the product anyway.

TL;DR version: I guess what I'm really asking is, can you implement Agile with single-person 'teams', and do you see any benefits from it, or is it usually something that's more effective for larger teams?

答:
Why do Agile as a one man team when you can instead form a single team of five developers with a single product backlog for your five products. Try one or two week iterations and focusing on one product at a time and see how your productivity improves with five engineers working together as a cohesive self-organizing team. Depending on how frequently you plan to release you may need to adjust the length of the sprint. I'm guessing the business may not want to wait 10 weeks between updates to a product, in which case the 1 week sprint lengths may work better. You could work on two products in a single sprint but I would try my best to avoid this so you can focus on a single product goal and doing that productively and with quality.

IMO having a single person dedicated to a single product is likely an unwise approach when there are five developers and five projects total, irrespective of your chosen methodology.


问:
Does TDD really work for complex projects?
I’m asking this question regarding problems I have experienced during TDD projects.
I have noticed the following challenges when creating unit tests.

Generating and maintaining mock data

It’s hard and unrealistic to maintain large mock data. It’s is even harder when database structure undergoes changes.

Testing GUI

Even with MVVM and ability to test GUI, it takes a lot of code to reproduce the GUI scenario.

Testing the business

I have experience that TDD works well if you limit it to simple business logic. However complex business logic is hard to test since the number of combinations of tests (test space) is very large.

Contradiction in requirements

In reality it’s hard to capture all requirements under analysis and design.  Many times one note requirements lead to contradiction because the project is complex. The contradiction is found late under implementation phase. TDD requires that requirements are 100% correct. In such cases one could expect that conflicting requirements would be captured during creating of tests. But the problem is that this isn’t the case in complex scenarios.

I have read this question: Why does TDD work?

Does TDD really work for complex enterprise projects, or is it practically limit to project type?

答:
If combination of budget, requirements and team skills are in the quadrant of the project-space lebelled 'abandon hope all ye who enter here', then by definition it is overwhelmingly likely the project will fail.

Perhaps the requirements are complex and volatile, the infrastructure unstable, the team junior and with high turnover, or the architect is an idiot.

On a TDD project, the symptom of this impending failure is that tests cannot be written on schedule; you try, only to discover 'that's going to take this long, and we only have that'.

Other approaches will show different symptoms when they fail; most commonly delivery of a system that doesn't work. Politics and contracts will determine whether that is preferable.


问:
how is ORM an example of message coupling?
In this slideshow on slide 26 it mentions ORM as an example of message coupling. How is that so?

With an ORM, certain code will call the ORM via an API, but that sounds like "control coupling". Also the ORM's api will take parameters to specify what you want, but that sounds like data coupling.

How is ORM an example of message coupling? maybe other examples of message coupling will help me understand.

答:
One of the fundamental principles of object orientation is "message passing."  Large object-oriented systems work by passing messages between objects.  Those messages can contain commands or data.  When I set a property on an object, I'm sending a data message.  When I call a method on an object, I'm sending a command message; I am dictating what action to take by choosing the method to call.  When I pass parameters to that method, I am sending a data message with the command message.

Message coupling in ORM's refers to both command messaging and data messaging.  I think it's fair to say that most messages in an ORM take the form of Create, Read, Update or Delete command messages.  There are methods corresponding to each of these command messages, and parameters that accept the data messages to be acted upon.

Coupling in an ORM refers to the fact that, when you make a call to an ORM, you must have some awareness of the data that you want.  Is it customers or products?  Later on in the slide, the author states that the only way to have no coupling at all is to have an empty reformatted hard drive (a blank slate, without any shape to the data, just random bits).

Data without shape is not meaningful or useful, so the first thing we do is we create shapes: customer records, product records, etc.  Once you do that, you've created coupling, because you have to know what a customer record or product record looks like in order to retrieve it and do anything useful with it.


问:
Citations for inadvisability of globally unique password
I am having a disagreement with a client about the user authentication process for a system. The nub of it is that they want each user to have a globally unique password (i.e. no two users can have the same password).

I have wheeled out all the obvious arguments against this:

it's a security vulnerability,

it confuses identification with authentication,

it's pointless, etc.,

but they are insisting that there is nothing wrong with this approach.

I have done various gGoogle searches looking for authoritative (or semi-authoritative , or even just independent) opinions on this, but can't find any (mainly it's just such an obvious faux pas that it doesn't seem worth warning against, as far as I can tell).  Can anybody point me towards any such independent opinion, please?

EDIT: Thanks for all your answers, but I already understand the problems with this proposed approach/requirement, and can even explain them to the client, but the client wont't accept them, hence my request for independent and/or authoritative sources.

I'd also found the Daily WTF article, but it suffers from the problem that Jon Hopkins has pointed out - that this is such a self-evident WTF that it doesn't seem worth explaining why.

And yes, the passwords are going to be salted and hashed. In which case global uniqueness might well be difficult to ensure, but that doesn't solve my problem - it just means that I have a requirement that the client won't budge on, that's not only ill-advised, but is also difficult to implement. And if I was in a position to say "I'm not budging on salting and hashing", then I'd be in a position to say "I'm not implementing globally unique passwords".

Any pointers to independent and/or authoritative sources for why this is a bad idea still gratefully received...

答:
He would probably like RSA two factor encryption.  If you're using Active Directory, or ASP.NET membership this is a no-brainer.

The hardware or software token generates a time dependent unique password that is followed by a PIN code.  This together provides a unique password for each user.