问:
Why do I have to keep my open source software license in the root?
Nearly all open source software licenses require (or at least lawyers generally suggest they require) users to include the full license in the root of the project that they are protecting.

One lawyer I spoke to suggests this is a legacy of the CD age, when it was necessary that a full license be included in a jewel case.

But today, we're living in the cloud age. Why can't I, for instance, simply host the full license at my website, and include the title + URL of that license in the header of my source files?

Bonus: If it's generally agreed that established licenses must be kept intact in the root, why hasn't the OSI of FSF approved a license that you can refer to by URL, and what is keeping someone from creating that license?

答:
From the GPL FAQ (but the advice is applicable to all licenses):

Why does the GPL require including a copy of the GPL with every copy of the program?

Including a copy of the license with the work is vital so that everyone who gets a copy of the program can know what his rights are.

It might be tempting to include a URL that refers to the license, instead of the license itself. But you cannot be sure that the URL will still be valid, five years or ten years from now. Twenty years from now, URLs as we know them today may no longer exist.

The only way to make sure that people who have copies of the program will continue to be able to see the license, despite all the changes that will happen in the network, is to include a copy of the license in the program.

(emphasis mine)

The moment the site hosting you license goes down or changes its URL paths, people who have copies of your software can no longer verify what rights they may safely exercise. Suppose even that you could somehow guarantee that that exact URL will be forever online: the ability for users to verify that their use of your software is legal still depends upon the ability to connect to that particular URL. While this requirement may not onerous in your particular city/country/planet, it may be onerous elsewhere. You should not impose this requirement, especially when the workaround (including the full license text) is trivial.

You might answer this complaint by saying, "So what? If the URL does go down or is not accessible, an unambiguous descriptor like 'GNU GPL v3' should be sufficient. Full-text copies of the GPL are plentiful; users can look up the license themselves." A few problems immediately spring to mind:

This doesn't generalize to license identifiers that are less clear (the phrase "BSD license" comes to mind).

This doesn't generalize well to licenses that are less common or have been customized ("GPL with linking exceptions" comes to mind: which linking exceptions?). How common does a license need to be before it's reasonable to expect a user to find it reliably by name?

This still requires users to have an Internet connection, which may not be the case, even if they had a connection at the time they got the software. (And they may not have had Internet access when they got the software: "the CD age" has not yet ended in many parts of the world. As an additional case, consider national populations that have widespread Internet access but censor large parts of it.) A consequence of freely-redistributable software is that a recipient may not receive a copy of your software directly from you or through a distribution channel you originally anticipated.

One final argument against license links is noted by MichaelT's comment below: it could allow you to dynamically, retroactively change the license. This could be done intentionally, but it could also be done by accident, if you changed the license between versions of the software, but used the same license link for both versions, thereby clobbering your old license out of existence. Such a switch would add difficulty for people who need to prove they got their older copy under a different license than the current version.

So why do I have to keep the license in the project root?

I'm not a lawyer, but I've never seen any compelling argument that you do need to keep licenses in the project root. Even the GPL, which specifies that the license must accompany each copy of the work, is silent on how it must accompany the work. (This may be because the GPL could be applied in non-software contexts, where the notion of "root directory" is not meaningful.)

Keeping the license in the root directory is probably a good idea because it maximizes the likelihood the user will see it, and thereby minimizes both user frustration and the likelihood of complaints against you for trying to hide the license in some obscure directory. If you have many licenses, it might make more sense to place them all in their own folder, and include an obvious project README that contains file paths to find the license for each component.

Placing your license in the directory root is a helpful practice also because it can disambiguate the licenses of modules that are licensed differently that the work as a whole. Suppose my project FooProj uses the stand-alone module BarMod. FooProj might be GPL-licensed, while the standalone module might be MIT-licensed. When I first open FooProj, I see a copy of the GPL in the root and understand that work as a whole is GPL-licensed. When I descend into the folder for BarMod, I see a new license file there, and I understand that the contents of this folder are MIT-licensed. Of course, this is only a helpful aid; you should always indicate the licensing of your modules explicitly in a README, NOTICE, or similar file.

In sum, using the file root is a matter of convenience and clarity. I have not seen any legally binding open-source license text that requires it, nor do I know of any reason why it would be legally required. Your license should be reasonably easy for the recipient to discover; including the license in the project root is sufficient, but not necessary, to satisfy this criterion.


问:
How to handle assumptions while designing any system?
I have been going through various system design examples to understand how we approach any system design question.
Here is what I have understood till now.

Know the system first and find out how it works.

Think of all use case.

Identify key components and their responsibilities.

Connect all the components so that they can communicate to each other.

Use all standard practices while integrating components and if possible use standard design patterns.

Sometimes we make assumptions about the system, so those assumptions should be used to remove one use case or to add a variation.

I will put this  question in context of Parking Lot design.

If I assume that Parking Lot is not commercial, and it is free parking lot, then design of parking lot should handle free parking lot as one of use cases , and it should be generic. OR Simply design parking lot which will never work for Commercial parking lot.

Main idea is that if someone asks you to design a parking lot and that is free parking lot, then design should be generic or specific?

答:
Rule #1: Never make assumptions, develop a bare minimum

Rule #2: You Aren't Gonna Need It: http://en.wikipedia.org/wiki/You_aren't_gonna_need_it

Rule #3: Start by writing unit tests

ContentLicense: CC BY-SA 3.0


问:
Professional Development: Finding that "pet project" to work on - then managing other commitments
At the moment, like a fair few of you I'd imagine, I spend at least 40 hours working on projects that use a specific set of technologies. Sometimes I'm doing maintenance, and have those technologies enforced, and sometimes I'm doing new builds.. but have the skillset of the team enforced due to maintenance reasons (quite rightly).

Yet I've got a growing set of technologies I want to test the waters with; be they custom Javascript frameworks or new Mobile Development techniques.

I have no idea how to get to grips with them though! Take for instance the Chromium Embedded Framework; I've always been a fan of the UI of the GitHub app, and also been impressed by both Evernote and Spotify. When I found out how those UIs were produced I naturally tried thinking of a project that I could toy about with and produce over a weekend. (Which, with minimal OS interaction (perhaps simple file manipulations), should be ample) But I can't think of a single thing to develop.

At work I've been tasked with retraining on Ruby on Rails; not wanting to go in blind - I decided to hammer a few books and try a few techniques. Now aside from the usual Lynda.com examples, and the very good "Agile Web Development with Rails" project from the book... I can't think of a single thing to develop.

Ordinarily I'd consider contributing to some FOSS software, and with frameworks I use regularly I do actually have a few ideas and I belong to the relevant mailing lists - i.e The Apache Cordova mailing list, and have signed the appropriate paperwork where required. (i.e For Apache Licensed projects)

Sometimes it's good to have an idea and run with it from scratch though, especially if you're new to the technology. So how do my fellow programmers manage doing that, and more importantly, how do you get ideas that allow you to use that specific framework/technology? It's hard to shoehorn ideas in to specific technologies at times.

I fear this is half the battle and the other half is how to keep such a project when work commitments can eat in to your personal time, and as it is, downtime is quite a valuable commodity!

答:
There are a couple ways I get ideas for things to work on. As you go through your normal life, think of useful programs that might be nice to have and then make a note of the idea.  That way, when you have a need to learn a new technology, you can look at this list rather than trying to come up with an idea from a blank slate.

Here are the ways I do it.

Standard utilities

I've got a few general utility programs I keep around that I rewrite into new technologies. For example, I've written a program to print addresses on envelopes on pretty much everything I've owned.  Keeping one or two ideas like this around is great because you already know the requirements, you can focus on learning the technology to build it.

For example, if you want to learn CEF, you can build a really nice HTML view for the envelope and a pretty UI.  You could build it in ruby on rails and install it on your home server so that it can store common addresses and be accessed by your whole household.  If you want to learn an image framework, you can start making the printouts prettier.  You can write a mobile phone app for it to learn iOS or Android.

Hobbies

Hobbies are usually a good source of ideas too. There's usually some fairly easy things that could use automation or support.  Here are some examples from my life:

I've got a friend who has a small golf league and needed a website to track scores, compute handicaps and create round-robin matches.

A local charity my mom worked with was spending a lot of time manually writing labels for their Angel Tree program at Christmas. A few hours spent got the info out of their systems and put it on the labels.

Keeping track of all of the possible adventure and plot hooks for a roleplaying game can be difficult, but a system to tie them together works well.

Data mining home finances by extracting transaction data from various bank accounts, categorizing it and doing projections.

Anything can work

Just remember, your idea does not need to be original! It's perfectly fine to reproduce something that already exists, because the goal is to learn, not to produce a finished product.  If you have an idea that is new and that you can share with the world, that's great.  But don't get stuck because you can't find the next world-changing product.


答:
Personally, I'm a big fan of YAGNI - (you ain't gonna need it).

Designing the general solution is hard.

The general rule I've seen (but naturally can't find a link to when I want it) is

Write the first block of code to solve the problem.

When you see a second instance of the problem, copy the first code & make changes to suit.

When you see a third instance of the problem, refactor to a general solution.

You might find the story about the Object Toaster useful reading.  It's a cautionary tale about the dangers of over thinking a problem.

Title: How to handle assumptions while designing any system?

Body:
I have been going through various system design examples to understand how we approach any system design question.
Here is what I have understood till now.

Know the system first and find out how it works.

Think of all use case.

Identify key components and their responsibilities.

Connect all the components so that they can communicate to each other.

Use all standard practices while integrating components and if possible use standard design patterns.

Sometimes we make assumptions about the system, so those assumptions should be used to remove one use case or to add a variation.

I will put this  question in context of Parking Lot design.

If I assume that Parking Lot is not commercial, and it is free parking lot, then design of parking lot should handle free parking lot as one of use cases , and it should be generic. OR Simply design parking lot which will never work for Commercial parking lot.

Main idea is that if someone asks you to design a parking lot and that is free parking lot, then design should be generic or specific?


问:
I feel lost among the various web technologies and I'm looking for pointers
In the last 3-5 months I was thinking about which web programming language I should use. PHP? Ruby? C#? Python? Perl? And you know what? Every time I keep changing my mind like crazy! I learn some things about each one of them and then move to another.  Now I'm totally lost, totally lost guys. :)

What I want form you is to help me to decide, not to decide for me, and give me some recommendations. It would be more than helpful if you can tell me a short story about yourself, how you got started, where you are now and what web programming technologies you are using.

答: I can only assume you switch so often because you expect much and are a bit disappointed when you see just how much work a proper web application requires; so I'd propose you choose something like Ruby on Rails or Grails, which lets you archive results quickly.</p>

ContentLicense: CC BY-SA 2.5


问:
How much should we spend on improving software security?
Is there a "scientific" method to determine how much resources/money should be spent on improving the security of a piece of software?

I work in a team where our work is prioritized by a product owner (ala Scrum). The product owner is kind of sales driven and focuses on new functionality requested by customers and less on the infrastructure. I think I need a way to convince him that we need to spend more time on improving the security.

Of course I don't want to convince him by spreading fear and I'm not sure myself how much money we should spend on improving security. Of course, the security of our software is improved all the time but I suspect - without knowing for sure - that it would be sane to double the efforts in the area.

I have a weak memory reading about this, where something like the following was suggested:

Think about a weak point in the security in the system

Estimate what a succesfull attack would cost in terms of lost/dis-satisifed customers (X)

Estimate how likely that it is that this would occur in a given year. (Y)

Calculate how much should be spend on fixing the weak points, based on X and Y. We don't have to solve the issue immediately, but we should spend Z percent on it.

答:
You would probably spend as much money on the analysis as you would on just fixing the known security problems in the first place, and by following good program design and best  security practices.

Consider the universe of information that you may never know.  When buffer overrun attacks were discovered in software written in C, nobody foresaw that happening (except the attackers).  Who is expecting someone to flood a buffer with characters so that they can inject code outside its boundaries?  How could you predict this, if you never saw it before?

Your biggest threat is not highly-sophisticated cyber attacks, but mundane people factors.  Folks who write down their passwords somewhere where they are easily accessed, because they can't remember them.  Social engineering attacks.  Casual use of USB flash drives.  Phishing.  You can't defend against these with technology, unless you...

Unplug.  How do government agencies deal with this kind of uncertainty?  They unplug.  Computers with classified information on them are kept physically and electrically isolated from the Internet and from other computers.  Well, that is, until recently.

You're not qualified to deal with the problem.  Your expertise is not computer security (well, unless it is.  But then, you're probably not writing applications, unless they are defender-type programs like virus scanners).

So what do you do?  Send your people to programming-oriented security classes.  Follow security and software design best practices.  Learn everything you can about common security attacks, and how to defend against them.  And cross your fingers.

If you still want the analysis, hire a consultant that possesses the necessary expertise.

ContentLicense: CC BY-SA 4.0


答:
Assumptions are a fact of life in IT projects.

Requirements change, and no matter how often we wish they would be locked down, they often are not.

So you need to deal with your assumptions and keep an eye on them.

Maybe keeping an issues log or something similar. Marking items with statuses levels to indicate how big an issue they could become etc.

With your parking lot example, you could assign a time estimate to each "level" of design and have an assumption in your issue log that talks about the assumption you have made, and what the cost would be of doing it one way or the other.


问:
Utilizing a Java Concurrent Utility from a Web App
I have the following lines of code in my application:

```<code>return "Service is alive since: " + TimeUnit.MILLISECONDS.toMinutes(mxBean.getUptime()) + " minutes";
</code>```

It uses the following package:

```<code>import java.util.concurrent.TimeUnit;
</code>```

My application is a web application. Does it means that I have something wrong logically if I use something from concurrent package at a web application?

答: Using TimeUnit.MILLISECONDS.toMinutes(...) is fine as it doesn't actually invoke any threading behaviour (which would be incorrect in a Java EE container).  It's part of core Java, so no overheads.</p>


答:
Main idea is that if someone asks you to design a parking lot and that is free parking lot, then design should be generic or specific?

Avoid a specific design as much as possible, as you would need to modify it once requirements clarify or change.

Eliminate your assumptions by clarifying requirements and minimizing/simplifying the scope of work. Usually, over-architectural design introduces unnecessary complexity to the project.

The rule of thumb while designing a software, with pre-mature requirements and assumptions, is to keep it simple. There are number of posts on this topic that combined in a famous phrase YAGNI!

In another words, best design patterns to stick with are KISS and YAGNI  !

YAGNI - You aren't gonna need it

KISS - Keep it simple stupid


答:
But today, we're living in the cloud age. Why can't I, for instance, simply host the full license at my website, and include the title + URL of that license in the header of my source files?

There do exist licenses that permit that. Apache 2.0, for example. Apache 2.0 requires only that each source file contain a small header that points to the Apache 2.0 License's canonical URL. There is no need to reproduce the full license in the source tree.

From the Apache 2.0 license itself:

```<code>APPENDIX: How to apply the Apache License to your work

To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets "[]" replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included
on the same "printed page" as the copyright notice for easier identification
within third-party archives.

    Copyright [yyyy] [name of copyright owner]

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
</code>```

Title: Why do I have to keep my open source software license in the root?

Body:
Nearly all open source software licenses require (or at least lawyers generally suggest they require) users to include the full license in the root of the project that they are protecting.

One lawyer I spoke to suggests this is a legacy of the CD age, when it was necessary that a full license be included in a jewel case.

But today, we're living in the cloud age. Why can't I, for instance, simply host the full license at my website, and include the title + URL of that license in the header of my source files?

Bonus: If it's generally agreed that established licenses must be kept intact in the root, why hasn't the OSI of FSF approved a license that you can refer to by URL, and what is keeping someone from creating that license?

Body:
But today, we're living in the cloud age. Why can't I, for instance, simply host the full license at my website, and include the title + URL of that license in the header of my source files?

There do exist licenses that permit that. Apache 2.0, for example. Apache 2.0 requires only that each source file contain a small header that points to the Apache 2.0 License's canonical URL. There is no need to reproduce the full license in the source tree.

From the Apache 2.0 license itself:

APPENDIX: How to apply the Apache License to your work

To apply the Apache License to your work, attach the following boilerplate
notice, with the fields enclosed by brackets "[]" replaced with your own
identifying information. (Don't include the brackets!) The text should be
enclosed in the appropriate comment syntax for the file format. We also
recommend that a file or class name and description of purpose be included
on the same "printed page" as the copyright notice for easier identification
within third-party archives.

    Copyright [yyyy] [name of copyright owner]

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


问:
When using int's as boolean values, is it in poor form to use 0's and 1' directly?
Is it better to do this

```<code>#define INT_TRUE 1
#define INT_FALSE 0

int someFunctionalityIsEnabled = INT_TRUE;
</code>```

or this?

```<code>int someFunctionalityIsEnabled = 1;
</code>```

It can be safely assumed that false will always be zero and true will be non-zero.

答:
The result is the same. Using the

```<code>#define TRUE 1
#define FALSE 0
</code>```

is more verbose, but it may make your code more readable for future generations (of programmers or your own brain cells) who are maintaining the application and trying to decipher the code.

Body:
The result is the same. Using the

#define TRUE 1
#define FALSE 0

is more verbose, but it may make your code more readable for future generations (of programmers or your own brain cells) who are maintaining the application and trying to decipher the code.


答:
It can be safely assumed that false will always be zero and true will be non-zero.

In this case, your question is almost pointless: If you are sure that everyone reading your code knows how "true" and "false" are represented as numbers, then you might not need those #define macros.

Positive side effect of these #defines. I am saying "almost" because these #defines still have value: Without names like TRUE and FALSE, choosing sensible variable names becomes somewhat more important. For example:

```<code>int is_enabled = 1;
int age_in_years = 1;
</code>```

How can you tell which variable stores a boolean value, and which an integer number? By looking at the variable names. Now, how about this?:

```<code>int is_enabled = TRUE;
int age_in_years = 1;
</code>```

The #defines add some redundancy (besides well-chosen variable names) that helps you recognise the "real" type of those int variables more easily.

For this reason of added clarity, I would recommend using such #defines, or if you are using a C99-conforming compiler, #include <stdbool.h>.

Negative side effect of these #defines. There's also a bad side to declaring a TRUE literal. You are saying that "true" may be represented by "any non-zero integer". Defining TRUE as being equivalent to 1 is therefore inaccurate, since that is only one out of many possible values meaning "true". (FALSE doesn't suffer from this.) This leads to the somewhat absurd consequence that writing is_enabled == FALSE will work as expected, but is_enabled == TRUE might not. There's two ways out of this issue:

DO NOT ever compare boolean values using == or !=. Instead,

DO write is_enabled instead of is_enabled == TRUE, and

DO write !is_enabled instead of is_enabled == FALSE.

CONSIDER re-defining "true" as "the integer number 1" instead of as "any non-zero integer number". (I would not, since it contradicts how C interprets integers as boolean values... but it's a theoretical possibility.)

I recommend you go with #1 for the reason mentioned.

Title: When using int's as boolean values, is it in poor form to use 0's and 1' directly?

Body:
Is it better to do this

```<code>#define INT_TRUE 1
#define INT_FALSE 0

int someFunctionalityIsEnabled = INT_TRUE;
</code>```

or this?

```<code>int someFunctionalityIsEnabled = 1;
</code>```

It can be safely assumed that false will always be zero and true will be non-zero.

Body:
It can be safely assumed that false will always be zero and true will be non-zero.

In this case, your question is almost pointless: If you are sure that everyone reading your code knows how "true" and "false" are represented as numbers, then you might not need those #define macros.

Positive side effect of these #defines. I am saying "almost" because these #defines still have value: Without names like TRUE and FALSE, choosing sensible variable names becomes somewhat more important. For example:

int is_enabled = 1;
int age_in_years = 1;

How can you tell which variable stores a boolean value, and which an integer number? By looking at the variable names. Now, how about this?:

int is_enabled = TRUE;
int age_in_years = 1;

The #defines add some redundancy (besides well-chosen variable names) that helps you recognise the "real" type of those int variables more easily.

For this reason of added clarity, I would recommend using such #defines, or if you are using a C99-conforming compiler, #include <stdbool.h>.

Negative side effect of these #defines. There's also a bad side to declaring a TRUE literal. You are saying that "true" may be represented by "any non-zero integer". Defining TRUE as being equivalent to 1 is therefore inaccurate, since that is only one out of many possible values meaning "true". (FALSE doesn't suffer from this.) This leads to the somewhat absurd consequence that writing is_enabled == FALSE will work as expected, but is_enabled == TRUE might not. There's two ways out of this issue:

DO NOT ever compare boolean values using == or !=. Instead,

DO write is_enabled instead of is_enabled == TRUE, and

DO write !is_enabled instead of is_enabled == FALSE.

CONSIDER re-defining "true" as "the integer number 1" instead of as "any non-zero integer number". (I would not, since it contradicts how C interprets integers as boolean values... but it's a theoretical possibility.)

I recommend you go with #1 for the reason mentioned.


问:
Alternative inheritance paradigms in object-oriented design
My apologies if a variation of this question has been asked before, but due to its nature it is hard to search for.

I am having a discussion with a colleague about object-oriented design, and it basically comes down to a choice between two different paradigms.  What I had been searching Google for was a discussion between these - as I've seen both discussed.

Paradigm A

Have a small number of classes which answer a lot of public methods, many of which are not applicable unless in certain circumstances.  In these cases, they throw a runtime exception.

Example: a mathematical vector class can have any number of elements.  This class answers 'Cross', but returns an error if it has anything other than 3 elements.

Paradigm B

A deeper inheritance tree, with methods only appearing where they are applicable.

Example: the mathematical vector class is specialised as a 3D-vector, with only the 3D-vector answering 'Cross'.  3D vectors are a special case as there are many functions relevant to a positional vector alone (Dot, Cross, Distance, AngleTo, etc).

I'm not actually asking for opinions on the above (although clearly the second is better!) but where can I find a good discussion on this - and similar - design issues.  I can find many beginners' discussions/tutorials on the subject, but I haven't had any luck finding the more in-depth articles.

Edit:

After a prompt from @JohnDibling, I'll rephrase the question (and add another Paradigm on request):

Paradigm C

Lightweight objects with a suite of functions to interpret them, and throw errors if the provided arguments weren't valid.

Example: all vectors only respond to the most basic requests, and a series of functions like Size(vector), Cross(vector) do all of the work.  Cross would throw a (runtime) error if an argument of the wrong size is given.

Could anyone give me specific reasons why A or C might be preferable to B, or point me to an article which discusses this issue in depth?

答:
Well I would say that neither are good ^^

Basically because the first paradigm do not follow the Liskov substitution principle.

(See the wikipedia link for some good references ...)

As a designer, you must try to limit coupling. As inheritance is one of the strongest link possible, you should avoid it whenever possible, see Herb Sutter on the subject (part 2) for example.

The second smells bad as it seems to do that sort of thing. By the way, you will end up with vector4D, vector5D, ...

modern design try to use inheritance sparsely. Most design patterns [GoF] do exactly that ! They try to limit the coupling between classes, replacing inheritance relationship with something else ^^

OwnerDisplayName: Mike Sadler

OwnerDisplayName: neuro


答:
What about option C: A mathematical vector with a sparse interface in a namespace that provides free-functions such as Cross that accept any vector you wish but throws an exception if it doesn't meet pre-conditions?

See also one of the fine books at the SO book list: https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list

Title: Alternative inheritance paradigms in object-oriented design

Body:
My apologies if a variation of this question has been asked before, but due to its nature it is hard to search for.

I am having a discussion with a colleague about object-oriented design, and it basically comes down to a choice between two different paradigms.  What I had been searching Google for was a discussion between these - as I've seen both discussed.

Paradigm A

Have a small number of classes which answer a lot of public methods, many of which are not applicable unless in certain circumstances.  In these cases, they throw a runtime exception.

Example: a mathematical vector class can have any number of elements.  This class answers 'Cross', but returns an error if it has anything other than 3 elements.

Paradigm B

A deeper inheritance tree, with methods only appearing where they are applicable.

Example: the mathematical vector class is specialised as a 3D-vector, with only the 3D-vector answering 'Cross'.  3D vectors are a special case as there are many functions relevant to a positional vector alone (Dot, Cross, Distance, AngleTo, etc).

I'm not actually asking for opinions on the above (although clearly the second is better!) but where can I find a good discussion on this - and similar - design issues.  I can find many beginners' discussions/tutorials on the subject, but I haven't had any luck finding the more in-depth articles.

Edit:

After a prompt from @JohnDibling, I'll rephrase the question (and add another Paradigm on request):

Paradigm C

Lightweight objects with a suite of functions to interpret them, and throw errors if the provided arguments weren't valid.

Example: all vectors only respond to the most basic requests, and a series of functions like Size(vector), Cross(vector) do all of the work.  Cross would throw a (runtime) error if an argument of the wrong size is given.

Could anyone give me specific reasons why A or C might be preferable to B, or point me to an article which discusses this issue in depth?

OwnerDisplayName: Mark B


答:
It depends on what you're trying to accomplish.

Generally when you use OOP or any other architectural technique you want to leverage the benefits that it's approach facilitates.  One of those benefits may be more reuse.  Reuse is considered good because it can reduce the overall load of code that must be reviewed,code that must be written, etc.

The OOP architectural paradigm also offers information hiding and encapsulation, important for managing and reducing complexity.  Reducing complexity in code is crucial to improving code quality and increasing overall development speed.

In my opinion, one of the best ways to refine your underlying OOP architecture is to begin to build a reference implementation.  Try to actually implement the high level functionality, at least conceptually or in pseudo code.  Doing this forces you to continue the architectural pattern you begin with the fundamental class definitions.  In this way you can get feedback from your implementation attempts about what OOP patterns are working cleanly and clearly to express your higher level functionality and which are hindering those efforts by making things more difficult by enforcing unnecessary conformance or, conversely, allowing excessive, distracting and confusing abstraction.

Known (GOF...) design pattern can help you by providing expert heuristics about which things have worked for many people over many trials.

But ultimately it is your project's requirements which will have to guide the final OOP foundation construction.

The core concept for me is whether a particular architectural approach is going to have a NET benefit or a NET loss.  If it takes longer to create a whole boatload of abstraction concepts and work out all the kinks in your inheritance hierarchy, that it would to just do a more quick and dirty approach and fix a few bugs or issues. Well, it's a judgement call.

Also, it depends on what you plan to do,  if these classes are intended to be the foundation of another 100,000 lines of OOP class hierarchy definitions, it may be time well spent to thoughtfully refine the abstractions as tightly as possible.

OwnerDisplayName: Andyz Smith


答:
There is no requirement that it must be in the root of the project. It's simply the most common place, and thus the first place people will look in order to find the license. For that matter, even if it weren't common, it's still likely the first place people will look. Since the license exists to inform, hiding the information doesn't make much sense.

If you hide it behind a URL, there's no absolute guarantee that that URL will be always be available. If it's a file in the root of the project, by definition it will always be available.

In short, this is the most effective, most user-friendly place to put it.


问:
What is a first class connector?
I was reading Towards Architecture-based Self-Healing Systems, and came upon the term
first-class connectors. What are they?

Searching some more finds this paper Systematic Construction of Software Architecture Supported by
Enhanced First-Class Connectors, which looks like it might have an answer, and I might read it in detail later, but regardless, it would be useful to have the question up here with an answer shorter than that paper. :)

An example of why having a connector being first class might also be relevant.

答:
I feel I must be missing something in the question, since a pretty good answer looks like it appears in the first paper linked in the question (Towards Architecture-based Self-Healing Systems). Still, I'll try to answer here...

Short version: a "connector" is a communications channel between "components", where "components" are independently-deployable parts of an application. A "first-class connector" is a connector that can be easily manipulated by a tool, such as an architecture manipulation engine. An application where "first-class connectors" might be useful is, to choose an example perhaps not quite at random, let's say, an Architecture-based Self-Healing System.

I'll get into the details below. First, you asked:

What is a first-class connector?

I think this is best answered in two parts:

What is a connector?

What does it mean for the connector to be "first-class"?

What is a connector?

A "connector", in this case, is a communications channel between system "components", where a "component" is an independently deploy-able part of the system that communicates with other components via connectors. To put that another way, if you consider that you can break down an application into independently deploy-able entities, which can communicate via some mechanisms, then the independently deploy-able entities can be called "components", while the communications mechanisms would be "connectors".

This is a bit outside of my comfort zone (I work in embedded systems), so I have a hard time going into detail in presenting examples, but consider EJB. Every "bean" is independently deployable, and can be considered a "component". If two beans communicate via CORBA, then CORBA would be considered a connector.

What does it mean for the connector to be "first-class"?

First of all, something can be considered first-class only in the context of some (broadly-defined) tool. In other words, the entities that are considered first-class are a function of the tool that works with those entities. When these authors suggest defining first-class connectors, they are actually advocating the creation or use of tools specifically designed to enable manipulating connectors. (If it unnatural to manipulate connectors with the tool, then connectors would not be "first-class" entities for that tool.)

I think this will become more clear when we address the next part of your question:

Why would first-class connectors be useful?

For example, you may want to insert a tap between two components connected by a uni-directional channel. A first-class connector could facilitate this by allowing you to identify the end-points of the existing connector, create one new connector from the old connector's source port to the tap's input port, another new connector from the tap's output port to the old connector's destination port, and destroy the old connector. A tool designed to support operations like this could be said to have first-class connectors.

An Architecture-based Self-Healing System might require that connectors be first class in order to perform actions like:

Analyze the data flowing through certain connectors, to ensure that some level of service is being met;

Replace connections to failing components with their redundant back-ups;

Test the load that a component can handle, by adjusting the rate of comms through the connector;

Identify communications bottlenecks;

Et cetera.

I haven't read through either paper, entirely, and this is a bit outside of my wheelhouse, so take this with some caution. Still, I hope it's helpful.

Title: What is a first class connector?


问:
longest list of words with matching start and end letters
My friend gave me a problem that he says is easy, but I can't figure out a good algorithm to use to do it.

You are given an input of 100 random English words.  You have to find the longest string of words where the last letter in one word matches the first letter in the next word.  You can only use each word once.

For example, if you were given the words "cat", "dog", "that", the longest string you could make would be "cat -> that".  If you were given the words "mouse", "moose", "unicorn", the longest string you could make would just be one word (since none of those words link).  If you were given the words "bird", "dish", "harb", the longest string you could make would be "harb -> bird -> dish" (or "dish -> harb -> bird" or "bird -> dish -> harb").

I came up with the idea of modeling this as a directed cyclic graph.  Each node would just be a word, with vertices going to each word/node that started with the letter this word ended with.

```<code>+-------+         \ +------+
|  cat  |-----------| that |
+-------+         / +------+
    |                  |
   \|/                 |
+-------+ /            |
|  the  |--------------+
+-------+ \
</code>```

This problem appears to be a longest path search, which is NP-Hard.

Is there a better way to do it?  Or even some sort of approximation algorithm that could be used?  Or some way to exploit qualities of English to reduce the search space?

答:
I think this is related to the longest path (LP) problem that you mentioned, but it's a little different.  The primary difference is that the LP problem has a higher degree of connectivity than what your suggested problem does.  By restricting your connections to the last and first letters, you remove a large number of potential combinations.

Here's how I would recommend tackling this one:

For each word in the list, count the possible connections in and connections out.

Discard any words that have 0 ins and 0 outs.

Identify an initial set of "starter words" with the lowest numbers of ins and outs, and the outs must be greater than 0.

Each starter word receives its own working copy of the ins / outs connection count.  This forms the head of the chain.

For each chain, identify a list of "next words" based upon:

last letter of starter or previous word

lowest number of of ins and outs connections (again, the outs must be greater than 0)

For each next word, repeat step 5 until the chain terminates.

Keep in mind that:

You'll need to keep track of the length of the chains and have some global mechanism to identify the longest chain.

You'll also need to remove each word from the working copy of the connection counts in order to avoid a recursive loop.

At some point, your chain will terminate and you have to select a word with a 0 connection out count.

You may have to recalculate ins / outs as words are removed from the working lists.  At first glance, I don't think this will be necessary as the overall sets will be relatively small.  If you scaled out to 1000 words, then having static counts may slow down the algorithm from converging.

I kind of saw this as a packing problem.  To me, the connections in and out identify the shape to be packed.  The lower the connections, the more odd the shape.  The more odd the shape, the sooner I want to pack it as I perceived having decreasing odds of being able to pack an odd shape the later I got into the chain.

As an example:

```<code>{dog, gopher, alpha, cube, elegant, this, that, bart}

dog     0, 1
gopher  1, 0
alpha   0, 0
cube    0, 1
elegant 1, 2
this    3, 0
that    2, 1
bart    0, 2

//alpha is dropped with 0 in and 0 out.
//two candidates found: dog, cube

//chain 1
dog => gopher
//chain 2
cube => elegant => that => this

//Note 1: the following chain won't occur due to selection rules
//that takes priority over this because of output count
cube => elegant => this

//Note 2: this chain won't occur either due to selection rules
bart => that => this
</code>```

Body:
I think this is related to the longest path (LP) problem that you mentioned, but it's a little different.  The primary difference is that the LP problem has a higher degree of connectivity than what your suggested problem does.  By restricting your connections to the last and first letters, you remove a large number of potential combinations.

Here's how I would recommend tackling this one:

For each word in the list, count the possible connections in and connections out.

Discard any words that have 0 ins and 0 outs.

Identify an initial set of "starter words" with the lowest numbers of ins and outs, and the outs must be greater than 0.

Each starter word receives its own working copy of the ins / outs connection count.  This forms the head of the chain.

For each chain, identify a list of "next words" based upon:

last letter of starter or previous word

lowest number of of ins and outs connections (again, the outs must be greater than 0)

For each next word, repeat step 5 until the chain terminates.

Keep in mind that:

You'll need to keep track of the length of the chains and have some global mechanism to identify the longest chain.

You'll also need to remove each word from the working copy of the connection counts in order to avoid a recursive loop.

At some point, your chain will terminate and you have to select a word with a 0 connection out count.

You may have to recalculate ins / outs as words are removed from the working lists.  At first glance, I don't think this will be necessary as the overall sets will be relatively small.  If you scaled out to 1000 words, then having static counts may slow down the algorithm from converging.

I kind of saw this as a packing problem.  To me, the connections in and out identify the shape to be packed.  The lower the connections, the more odd the shape.  The more odd the shape, the sooner I want to pack it as I perceived having decreasing odds of being able to pack an odd shape the later I got into the chain.

As an example:

{dog, gopher, alpha, cube, elegant, this, that, bart}

dog     0, 1
gopher  1, 0
alpha   0, 0
cube    0, 1
elegant 1, 2
this    3, 0
that    2, 1
bart    0, 2

//alpha is dropped with 0 in and 0 out.
//two candidates found: dog, cube

//chain 1
dog => gopher
//chain 2
cube => elegant => that => this

//Note 1: the following chain won't occur due to selection rules
//that takes priority over this because of output count
cube => elegant => this

//Note 2: this chain won't occur either due to selection rules
bart => that => this


问:
What constitutes "improper use" of the javascript Eval feature?
Eval is a notoriously controversial language feature.  Douglas Crockford flat out rejects it. I'm wondering what specific risks Eval brings about.  According to this question, Improper use of eval opens up your code for injection attacks.

What are some improper uses of the Eval command, and what security holes do they open up?

答:
There are some things that are impossible to do in JS without an eval-like function (eval, Function, and maybe more).

Take apply for example. It is easy to use when using it on ordinary function calls:

foo.apply(null, [a, b, c])

But how would you do this for objects you are creating via new syntax?

new Foo.apply(null, [a, b, c]) doesn't work, nor do similar forms.

But you can work around this limitation via eval or Function (I use Function in this example):

```<code>Function.prototype.New = (function () {
    var fs = [];
    return function () {
        var f = fs[arguments.length];
        if (f) {
            return f.apply(this, arguments);
        }
        var argStrs = [];
        for (var i = 0; i < arguments.length; ++i) {
            argStrs.push("a[" + i + "]");
        }
        f = new Function("var a=arguments;return new this(" + argStrs.join() + ");");
        if (arguments.length < 100) {
            fs[arguments.length] = f;
        }
        return f.apply(this, arguments);
    };
}) ();
</code>```

Example:

Foo.New.apply(null, [a, b, c]);

Of course, you could manually build the functions that Function.prototype.New uses, but not only is this verbose and clunky, it (by definition) has to be finite. Function allows the code to work for any number of arguments.

Body:
There are some things that are impossible to do in JS without an eval-like function (eval, Function, and maybe more).

Take apply for example. It is easy to use when using it on ordinary function calls:

foo.apply(null, [a, b, c])

But how would you do this for objects you are creating via new syntax?

new Foo.apply(null, [a, b, c]) doesn't work, nor do similar forms.

But you can work around this limitation via eval or Function (I use Function in this example):

Function.prototype.New = (function () {
    var fs = [];
    return function () {
        var f = fs[arguments.length];
        if (f) {
            return f.apply(this, arguments);
        }
        var argStrs = [];
        for (var i = 0; i < arguments.length; ++i) {
            argStrs.push("a[" + i + "]");
        }
        f = new Function("var a=arguments;return new this(" + argStrs.join() + ");");
        if (arguments.length < 100) {
            fs[arguments.length] = f;
        }
        return f.apply(this, arguments);
    };
}) ();

Example:

Foo.New.apply(null, [a, b, c]);

Of course, you could manually build the functions that Function.prototype.New uses, but not only is this verbose and clunky, it (by definition) has to be finite. Function allows the code to work for any number of arguments.


问:
Collecting user information for debugging and support
I have a Java application that I need to support. I'd like it to collect user information, such as system information: OS and hardware for easier diagnostics and support.

Are there any security & privacy regulations I need to follow?

Do I specifically need consent from the user to do this?

答:
In short: It is mandatory to get consent of the users. The application should get user consent and acknowledge them about the information that is gathered. Because, by different country laws not disclosing this activity is considered to be crime.

Disclaimer : I am not a lawyer, and you may probably would need to contact a lawyer who would advice you on exact procedures and "disclaimer terms" that you should have in place.

However, generally speaking the application should have Terms and Conditions that users need to accept, in order to be able to use the systems.

There are related discussion on this topic that you may look for here.

For example: StackExchange has the following disclaimer in place.


答:
It's always a good idea to instrument systems and have a communication path back to the developer with the results of the instrumentation.  (I'm not talking about spyware; a log file or a "stats" screen will do).

Part of good instrumentation is providing data relevant to the assumptions.  Ie; a parking lot app should report the number of cars it's supposed to handle, and maybe add a special warning flag if it's suppose to handle a million cars...


答:
A somewhat direct answer on my part was developing a developer-oriented API-testing area. We gave a text area on a page, and a Run button. The central point of the page was for them to be able to try things out in Javascript against our iframe-communicating API that weren't so easy to do in a local environment.

Anything malicious that could have been done in that case could also have been done by the developer opening up their F12 tools.

Title: What constitutes "improper use" of the javascript Eval feature?

Body:
Eval is a notoriously controversial language feature.  Douglas Crockford flat out rejects it. I'm wondering what specific risks Eval brings about.  According to this question, Improper use of eval opens up your code for injection attacks.

What are some improper uses of the Eval command, and what security holes do they open up?


问:
How does a program process concurrent executions
I have a console application that is run by taking the input parameters. It can be configured by passing report name parameter, for e.g. reportgen.exe sales.xml. It hits the database and retrieves the data into xml file and sends to sftp site.

Whole of this process is logged and the xml files are being saved in a directory. This exe needs to be scheduled on daily basis, so what happens if the exe is scheduled at same time with different parameters.

Is it thread safe and can be considered as independent execution doing what it supposed to do?

Edit:
It uses log4net for logging the debug info. into a file. So, how does it write log statements into single file for concurrent executions.

答:
Well it depends how you have programmed your application. We can view a couple of pitfalls, you can find on your way.

Pitfalls

The first problem can happen in the database. Your application access the database, retrieve data from various tables and then start processing the data. But suddenly the application comes to a halt. Certain data seems to be inconsistent. What happened here?

What happened is, that you loaded your data from various tables without using transactions. The database is not able to provide read consistency and somebody else updated one of the tables.

Thus run the critical queries in one transaction, so your database can provide the consistency you need.

The second problem happens on filesystem level. While you save you save your xml file, another instance of the program is writing at the same time. This will corrupt the file, because two writers can make quite a mess.

While your use case doesn't point to this situation, it is still worth securing.

This is easily solvable by using file locking. A exclusive write lock will save this for you. Nobody can read the file and only you can write it. Or you have to wait on the other program.

The last thing you can do, is create a pidfile (process id file) for your program, but I don't think it is needed here.
So if you run a different instance, it can check another instance is running and then goes into a waiting mode until the pidfile is given free. You can lock the pidfile as above, but then with a shared lock. If your program hangs, then you can kill it easily by reading the pidfile and kill the process.

In pseudocode you do this:

```<code>if(lock_file(pidfile)){
     write_process_id(pidfile)
     run_program()
     unlock_file(pidfile)
}
</code>```

Log4net

As mentioned here log4net can't do concurrent writes to a single log file:

log4net-can-2-applications-write-to-the-same-log-file

Body:
Well it depends how you have programmed your application. We can view a couple of pitfalls, you can find on your way.

Pitfalls

The first problem can happen in the database. Your application access the database, retrieve data from various tables and then start processing the data. But suddenly the application comes to a halt. Certain data seems to be inconsistent. What happened here?

What happened is, that you loaded your data from various tables without using transactions. The database is not able to provide read consistency and somebody else updated one of the tables.

Thus run the critical queries in one transaction, so your database can provide the consistency you need.

The second problem happens on filesystem level. While you save you save your xml file, another instance of the program is writing at the same time. This will corrupt the file, because two writers can make quite a mess.

While your use case doesn't point to this situation, it is still worth securing.

This is easily solvable by using file locking. A exclusive write lock will save this for you. Nobody can read the file and only you can write it. Or you have to wait on the other program.

The last thing you can do, is create a pidfile (process id file) for your program, but I don't think it is needed here.
So if you run a different instance, it can check another instance is running and then goes into a waiting mode until the pidfile is given free. You can lock the pidfile as above, but then with a shared lock. If your program hangs, then you can kill it easily by reading the pidfile and kill the process.

In pseudocode you do this:

if(lock_file(pidfile)){
     write_process_id(pidfile)
     run_program()
     unlock_file(pidfile)
}

Log4net

As mentioned here log4net can't do concurrent writes to a single log file:

log4net-can-2-applications-write-to-the-same-log-file


问:
How to migrate my thinking from C++ to C#
I am an experienced C++ developer, I know the language in great details and have used some of its specific features intensively. Also, I know principles of OOD and design patterns. I am now learning C# but I cannot stop the feeling not being able to get rid of C++ mindset. I tied myself so hard to the strengths of C++ that I cannot live without some of the features. And I cannot find any good workarounds or replacements for them in C#.

What good practices, design patterns, idioms that are different in C# from C++ perspective can you suggest? How to get a perfect C++ design not looking dumb in C#?

Specifically, I cannot find a good C#-ish way to deal with (recent examples):

Controlling the lifetime of resources that require deterministic cleanup (like files). This is easy having using in hand but how to use it properly when ownership of the resource is being transfered [... betwen threads]? In C++ I would simply use shared pointers and let it take care of 'garbage collection' just at the right time.

Constant struggling with overriding functions for specific generics (I love things like partial template specialization in C++). Should I just abandon any attempts to do any generic programming in C#? Maybe generics are limited on purpose and it is not C#-ish to use them except for a specific domain of problems?

Macro-like functionality. While generally a bad idea, for some domain of problems there is no other workaround (e.g. conditional evaluation of a statement, like with logs that should only go to Debug releases). Not having them means that I need to put more if (condition) {...} boilerplate and it is still not equal in terms of triggering side effects.

答:
In my experience, there is no book to do this. Forums help with idioms and best practices, but in the end you're going to have to put in the time. Practice by solving a number of different problems in C#. Look at what was hard/awkward and try to make them less hard and less awkward next time. For me, this process took about a month before I "got it".

The biggest thing to focus on is the lack of memory management. In C++ this lords over every single design decision you make, but in C# it is counter productive. In C#, you often want to ignore the death or other state transitions of your objects. That sort of association adds unnecessary coupling.

Mostly, focus on using the new tools most effectively, not beating yourself up over an attachment to the old ones.

How to get a perfect C++ design not looking dumb in C#?

By realizing that different idioms push towards different design approaches. You can't just port something 1:1 between (most) languages and expect something beautiful and idiomatic on the other end.

But in response to specific scenarios:

Shared unmanaged resources - This was a bad idea in C++, and is just as much a bad idea in C#. If you have a file then open it, use it, and close it. Sharing it between threads is just asking for trouble, and if only one thread is really using it then have that thread open/own/close it. If you really have a long lived file for some reason, then make a class to represent that and let the application manage that as needed (close before exit, tie close to Application Closing sort of events, etc)

Partial Template Specialization - You're out of luck here, though the more I've used C# the more I find the template usage I did in C++ to fall into YAGNI. Why make something generic when T is always an int? Other scenarios are best solved in C# by liberal application of interfaces. You don't need generics when an interface or delegate type can strongly type what you want to vary.

Preprocessor conditionals - C# has #if, go nuts. Better yet, it has conditional attributes that will simply drop that function from the code if a compiler symbol is not defined.


答:
You mentioned two specific C++ features.  I'll discuss RAII:

It is usually not applicable, since C# is garbage collected.  The closest C# construction is probably the IDisposable interface, used as follows:

```<code>using (FileStream fs = File.OpenRead(@"c:\path\filename.txt"))
{
   //Do stuff with the file.
} //File will be closed here.
</code>```

You shouldn't expect to implement IDisposable often (and doing so is slightly advanced), as it's not necessary for managed resources.  However, you should use the using construct (or call Dispose yourself, if using is infeasible) for anything implementing IDisposable.  Even if you mess this up, well-designed C# classes will try to handle this for you (using finalizers).  However, in a garbage-collected language the RAII pattern doesn't fully work (since collection is non-deterministic), so your resource cleanup will be delayed (sometimes catastrophically).

Title: How to migrate my thinking from C++ to C#

Body:
I am an experienced C++ developer, I know the language in great details and have used some of its specific features intensively. Also, I know principles of OOD and design patterns. I am now learning C# but I cannot stop the feeling not being able to get rid of C++ mindset. I tied myself so hard to the strengths of C++ that I cannot live without some of the features. And I cannot find any good workarounds or replacements for them in C#.

What good practices, design patterns, idioms that are different in C# from C++ perspective can you suggest? How to get a perfect C++ design not looking dumb in C#?

Specifically, I cannot find a good C#-ish way to deal with (recent examples):

Controlling the lifetime of resources that require deterministic cleanup (like files). This is easy having using in hand but how to use it properly when ownership of the resource is being transfered [... betwen threads]? In C++ I would simply use shared pointers and let it take care of 'garbage collection' just at the right time.

Constant struggling with overriding functions for specific generics (I love things like partial template specialization in C++). Should I just abandon any attempts to do any generic programming in C#? Maybe generics are limited on purpose and it is not C#-ish to use them except for a specific domain of problems?

Macro-like functionality. While generally a bad idea, for some domain of problems there is no other workaround (e.g. conditional evaluation of a statement, like with logs that should only go to Debug releases). Not having them means that I need to put more if (condition) {...} boilerplate and it is still not equal in terms of triggering side effects.

Body:
You mentioned two specific C++ features.  I'll discuss RAII:

It is usually not applicable, since C# is garbage collected.  The closest C# construction is probably the IDisposable interface, used as follows:

using (FileStream fs = File.OpenRead(@"c:\path\filename.txt"))
{
   //Do stuff with the file.
} //File will be closed here.

You shouldn't expect to implement IDisposable often (and doing so is slightly advanced), as it's not necessary for managed resources.  However, you should use the using construct (or call Dispose yourself, if using is infeasible) for anything implementing IDisposable.  Even if you mess this up, well-designed C# classes will try to handle this for you (using finalizers).  However, in a garbage-collected language the RAII pattern doesn't fully work (since collection is non-deterministic), so your resource cleanup will be delayed (sometimes catastrophically).


问:
How should I architect a RESTful webservice to use 3rd party (i.e. Google, Facebook, Twitter) for authentication?
For my job we have a nice RESTful webservice we've built out that we use to drive a couple websites we have.  Basically the webservice lets you create and work with support tickets, and the website is responsible for the front end.  Any webservice requests use an auth header which we use to validate the user and their password for each call.

This year we're looking to expand our login options so that users on the website can log in via Google, Twitter, and Facebook (possibly others).  However I'm having a lot of trouble figure out how to architect this so the webservice can use the 3rd party authentication providers to ensure the users is who they say they are.  Is there any best practices out there for how to do this?

Currently we're thinking of having the website handle authenticating the users themselves, and then use a new setSessionId call that registers their current session with the webservice back end.  Each additional request to the webservice will pass along that sessionId and will validate it.  These seems okay, but I have that feeling in the back of my head that I'm not thinking this through and all my forum browsing and reading oauth and openid specs is just confusing me more.  Any tips for how to tackle this?

答:
How to make it extensible

First you should notice all these api's use the same mechanism for logging in. They all use OAuth for their authentication. This you need to leverage by starting with a general OAuth library. Don't use their own libraries for authentication, these will be unusable for other providers. If you get the hang of OAuth2 it is quite easy to add more providers.

You need unfortunately two of them, because twitter still hasn't jumped the OAuth2 bandwagon.

OAuth needs you to create an interface for the authenticating party. The tokens will be exchanged server to server. Create one entry point, which can handle all the communication.

The token should be stored in a separate table from your account, this is because their can be multiple tokens and multiple linked profiles. Some services give you two tokens, one of them is a refresh token.

Now you design an interface, which encapsulates the other functionality you need. I would personally setup a separate REST-service for this. This way you can easily extend the authentication to other places.

Some services use JSON to communicate, other go for XML etc. For the front user you need to unify them all. This is a pretty painful process, but it is possible to derive some common grounds here.

Another problem here, is that not all the services provide the same functionality. This can mean, that your services cannot provide the full API as you specified. You need to have a strategy here, which let the application gracefully downgrade.

This all will ensure you can easily add new 3rd party providers.

Token problems

The tokens are limited in time, thus you need a couple of cron jobs, which can check if the token is still usable, otherwise you have to delete it. You can also refresh a token by this mechanism.

It sometimes happens, that an user retracts the token. Be ready for this.

Data storage

If you have this design, you need to think about the data you need. This follows partly from your just created interface. Design some tables for this and look if the data is actually retrievable. Some services don't let you grab a lot of data. You should also take into account, that the more data you need, the heftier the privacy messages become. So be modest in your needs, otherwise users won't use it.

For extra verification, you can store the profiles in a separate, but linked table to your users. This will provide you with a lot more information about someone.

Also check your local laws, for some data you need extra precautions.

Last thing
Don't make the fault where you don't create an account on your own services. If the user gets banned from facebook, he will effectively be unable to login on your service. This is a situation you don't want to create. This is often overlooked.


问:
Am I doing events right?
My problem is with JavaScript in the browser but I guess it could apply to any event-driven environment.

I have coded up a widget in my app. The widget allows a user to select an item using 3 different sub-widgets (table, map & gallery). The sub-widgets display the same items and a selection can be made from whichever sub-widget the user prefers to use. Whenever a selection is made by the user or set in code a "selection-changed" event is fired by the sub-widget. The main widget listens for these "selection-changed" events.

This worked fine until I started getting further on with the project and realized that I needed to adjust the selection in the other 2 widgets when the selection changes (If the user selects an item on the map, it should highlight that same item in the table and gallery). The problem is that when I set the selection in the other 2 sub-widgets they in-turn fire the "selection-changed" event and that ends up getting pretty recursive. This also happens when I need to clear the selection in all of the sub-widgets (I get 3 "selection-changed" events with the same empty data). This leads to several redundant calls being made for external resources and gives me the feeling it will lead to further problems in future.

So my question is am I doing events right? The answer is obviously 'no' because I've got myself in to a pickle so early on but I wonder how other people use events without getting in to these problems - what kind of architecture would be better in this situation?

Maybe I could have a way of setting and clearing selections in the sub-widgets that doesn't go on to fire the event but this feels like a hack and may end up conflicting with the framework I'm using to handle my views/models.

答:
This is a common problem with an event system. There is one main central authority, which pushes the events from and to the listeners. It is pretty crude, but workable.

There is a small catch here. The system soon gets more complicated and the propagation of the events is more or less opaque. It is difficult to determine, what the system is actually doing. Also unwanted effects can creep in.

There are already two solutions given, which are fine solutions, but I also want to give a solution, which is a refinement on the event model.

Reactive programming

If you take a crude event system and you break it up in smaller parts, you will see there are several functionalities, which seems to be shared:

Filtering of events

Pushing events into the stream of events (which is a source of events)

Acting onto the stream of events. (which is a sink of events)

Manipulating the events in the stream (eg. mapping over them)

In reactive programming these components are separated and as you can see, it is possible to build the crude model from this. The key element is that you separate the input from the  output.

With these components you can build a network and explicitly route your events through your application. This makes the working of your system more transparent and also adds a lot of flexibility. The cool thing about this, is that you can unify events from callbacks into the system.

A network looks typically like this:

```<code>clickbutton -> some switching -> change picture
app1-change --/  /          \----> stopclock
clock_tick -----/            \----> start clock
</code>```

An interesting in the concept of reactive programming is the following site: functional-reactive-programming-with-bacon-js/

In functional reactive programming, there are two thing which can propagate through your network. Behaviors, which are continuous signals. Think about  the user mouse movement. And events, which discrete signals. This goes somewhat theoretical deeper waters than normal reactive programming.

Title: Am I doing events right?

Body:
This is a common problem with an event system. There is one main central authority, which pushes the events from and to the listeners. It is pretty crude, but workable.

There is a small catch here. The system soon gets more complicated and the propagation of the events is more or less opaque. It is difficult to determine, what the system is actually doing. Also unwanted effects can creep in.

There are already two solutions given, which are fine solutions, but I also want to give a solution, which is a refinement on the event model.

Reactive programming

If you take a crude event system and you break it up in smaller parts, you will see there are several functionalities, which seems to be shared:

Filtering of events

Pushing events into the stream of events (which is a source of events)

Acting onto the stream of events. (which is a sink of events)

Manipulating the events in the stream (eg. mapping over them)

In reactive programming these components are separated and as you can see, it is possible to build the crude model from this. The key element is that you separate the input from the  output.

With these components you can build a network and explicitly route your events through your application. This makes the working of your system more transparent and also adds a lot of flexibility. The cool thing about this, is that you can unify events from callbacks into the system.

A network looks typically like this:

clickbutton -> some switching -> change picture
app1-change --/  /          \----> stopclock
clock_tick -----/            \----> start clock

An interesting in the concept of reactive programming is the following site: functional-reactive-programming-with-bacon-js/

In functional reactive programming, there are two thing which can propagate through your network. Behaviors, which are continuous signals. Think about  the user mouse movement. And events, which discrete signals. This goes somewhat theoretical deeper waters than normal reactive programming.


答:
The thing that was most different for me was the tendency to new everything. If you want a object, forget trying to pass it to a routine and share the underlying data, it seems the C# pattern is just to create yourself a new object. This, in general, seems to be much more of the C# way. At first this pattern seemed very inefficient, but I guess creating most objects in C# is a quick operation.

However, there's also the static classes that really annoy me as every so often you try to create one only to find you have to just use it. I find its not so easy to know which to use.

I'm quite happy in a C# program to just ignore it when I no longer need it, but just remember what that object contains - generally you only have to think if it has some 'unusual' data, objects that only consist of memory will just go away by themselves, others will have to be disposed or you'll have to look at how to destroy them - manually or by a using block if not.

you'll very quickly pick it up though, C# is hardly any different from VB so you can treat it as the same RAD tool it is (if it helps to think of C# like VB.NET then do so, the syntax is only slightly different, and my old days of using VB got me into the right mindset for RAD development). The only difficult bit is determining what bit of the huge .net libraries you should use. Google is most definitely your friend here!


问:
How should a REST API handle PUT requests to partially-modifiable resources?
Suppose a REST API, in response to a HTTP GET request, returns some additional data in a sub-object owner:

```<code>{
  id: 'xyz',
  ... some other data ...
  owner: {
    name: 'Jo Bloggs',
    role: 'Programmer'
  }
}
</code>```

Clearly, we don't want anyone to be able to PUT back

```<code>{
  id: 'xyz',
  ... some other data ...
  owner: {
    name: 'Jo Bloggs',
    role: 'CEO'
  }
}
</code>```

and have that succeed. Indeed, we probably aren't going to even implement a way for that to even potentially succeed, in this case.

But this question is not just about sub-objects: what, in general, should be done with data that should not be modifiable in a PUT request?

Should it be required to be missing from the PUT request?

Should it be silently discarded?

Should it be checked, and if it differs from the old value of that attribute, return a HTTP error code in the response?

Or should we use RFC 6902 JSON patches instead of sending the whole JSON?

答:
Idem potency

Following the RFC, a PUT would have to deliver full object to the resource. The main reason of this, is that PUT should be idempotent. This means a request, which is repeated should evaluate to the same result on the server.

If you allow partial updates, it cannot be idem-potent anymore. If you have two clients. Client A and B, then the following scenario can evolve:

Client A gets a picture from resource images. This contains a description of the image, which is still valid.  The client B puts a new image and update the description  accordingly. The picture has changed. Client A sees, he doesn't have to change the description, because it is as he wishes and put only the image.

This will lead to an inconsistency, the image has the wrong metadata attached!

Even more annoying is that any intermediary can repeat the request. In case it decides somehow the PUT failed.

The meaning of PUT cannot be changed (although you can misuse it).

Other options

Luckily there is a another option, this is PATCH. PATCH is a method which allows you to partially update a structure. You can simply send an partial structure. For simple applications, this is fine. This method is not guaranteed to be idem potent. The client should send a request in the following form:

```<code>PATCH /file.txt HTTP/1.1
Host: www.example.com
Content-Type: application/example
If-Match: "e0023aa4e"
Content-Length: 20
{fielda: 1, fieldc: 2}
</code>```

And the server can reply back with 204 (No content) to flag success. On error you cannot update a part of the structure. The PATCH method is atomic.

The disadvantage of this method is, is that not all browsers support this, but this is the most natural option in a REST-service.

Example patch request:
https://www.rfc-editor.org/rfc/rfc5789#section-2.1

Json patching

The json option seems to be pretty comprehensive and an interesting option. But it can be difficult to implement for third parties. You have to decide if your user base can handle this.

It is also somewhat convoluted, because you need to build an small interpreter which converts the commands to an partial structure, which you are going to use to update your model. This interpreter should also check, if the provided commands make sense. Some commands cancel each other out. (write fielda, delete fielda). I think you want to report this back to the client to limit debug time on his/her side.

But if you have the time, this is a really elegant solution. You still should validate the fields of course. You can combine this with the PATCH method to stay into the REST model. But I think POST would be acceptable to here.

Going bad

If you decide to go with the PUT option, which is somewhat risky. Then you should at least not discard the error. The user has a certain expectancy (the data will be updated) and if you break this, you are going to give some developers not a good time.

You could chose for flagging back: 409 Conflict or a 403 Forbidden. It depends how you look at the update process. If you see it as a set of rules (system-centric), then conflict will be nicer. Something like, these fields are not updateable. (In conflict with the rules). If you see it as an authorization problem (user-centric), then you should return forbidden. With: you aren't authorized to change these fields.

You still should force users to send all the modifiable fields.

A reasonable option to enforce this is to set it to a sub-resource, which only offers the modifiable data.

Personal opinion

Personally I would go (if you don't have to work with browsers) for the simple PATCH model and then later extend it with a JSON patch processor. This can be done by differentiating on the mimetypes:
The mime type of json patch:

application/json-patch

And json:
application/json-patch

makes it easy to implement it in two phases.

Body:
Idem potency

Following the RFC, a PUT would have to deliver full object to the resource. The main reason of this, is that PUT should be idempotent. This means a request, which is repeated should evaluate to the same result on the server.

If you allow partial updates, it cannot be idem-potent anymore. If you have two clients. Client A and B, then the following scenario can evolve:

Client A gets a picture from resource images. This contains a description of the image, which is still valid.  The client B puts a new image and update the description  accordingly. The picture has changed. Client A sees, he doesn't have to change the description, because it is as he wishes and put only the image.

This will lead to an inconsistency, the image has the wrong metadata attached!

Even more annoying is that any intermediary can repeat the request. In case it decides somehow the PUT failed.

The meaning of PUT cannot be changed (although you can misuse it).

Other options

Luckily there is a another option, this is PATCH. PATCH is a method which allows you to partially update a structure. You can simply send an partial structure. For simple applications, this is fine. This method is not guaranteed to be idem potent. The client should send a request in the following form:

PATCH /file.txt HTTP/1.1
Host: www.example.com
Content-Type: application/example
If-Match: "e0023aa4e"
Content-Length: 20
{fielda: 1, fieldc: 2}

And the server can reply back with 204 (No content) to flag success. On error you cannot update a part of the structure. The PATCH method is atomic.

The disadvantage of this method is, is that not all browsers support this, but this is the most natural option in a REST-service.

Example patch request:
https://www.rfc-editor.org/rfc/rfc5789#section-2.1

Json patching

The json option seems to be pretty comprehensive and an interesting option. But it can be difficult to implement for third parties. You have to decide if your user base can handle this.

It is also somewhat convoluted, because you need to build an small interpreter which converts the commands to an partial structure, which you are going to use to update your model. This interpreter should also check, if the provided commands make sense. Some commands cancel each other out. (write fielda, delete fielda). I think you want to report this back to the client to limit debug time on his/her side.

But if you have the time, this is a really elegant solution. You still should validate the fields of course. You can combine this with the PATCH method to stay into the REST model. But I think POST would be acceptable to here.

Going bad

If you decide to go with the PUT option, which is somewhat risky. Then you should at least not discard the error. The user has a certain expectancy (the data will be updated) and if you break this, you are going to give some developers not a good time.

You could chose for flagging back: 409 Conflict or a 403 Forbidden. It depends how you look at the update process. If you see it as a set of rules (system-centric), then conflict will be nicer. Something like, these fields are not updateable. (In conflict with the rules). If you see it as an authorization problem (user-centric), then you should return forbidden. With: you aren't authorized to change these fields.

You still should force users to send all the modifiable fields.

A reasonable option to enforce this is to set it to a sub-resource, which only offers the modifiable data.

Personal opinion

Personally I would go (if you don't have to work with browsers) for the simple PATCH model and then later extend it with a JSON patch processor. This can be done by differentiating on the mimetypes:
The mime type of json patch:

application/json-patch

And json:
application/json-patch

makes it easy to implement it in two phases.


答:
It sounds like there are two goals:

Easy for end-users to authenticate with their existing social accounts

Easy for developers using your webservice

Authorizing people to use resources on your site makes OAuth2 a preferred mechanism due to the popularity and availability of client libraries.

1. Easy for end-users to authenticate with their existing social accounts

The end-user visits a site that uses your API and chooses to login.  They are sent to your OAuth login page.  Your login page shows a normal username and password prompt for accounts  managed on your site and a set of social auth buttons where they can click to login via a site like Facebook.  When the user chooses Facebook you redirect them to Facebook to approve the choice (starting the facebook auth flow).  When the end-user completes the login at Facebook they are redirected back to your site.

When the user is redirected back to your site from Facebook you save that user's information into a user record in your database and then generate a new session for that user. You immediately redirect the end-user to their original downstream site with the oauth access_token, completing the original oauth flow.

2. Easy for developers using your webservice

If you are the provider of authorization then you should create a simple interface for developers to depend upon which does not change every time you add a new upstream auth provider which doesn't implement oauth perfectly.  This is why I believe you should implement an OAuth2 provider site and that site should be a consumer of the social auth sites.

To the developer using your nice rest API, they will not be aware of the Facebook interaction unless you choose to give them a hint through the session capture post (for example).

TL;DR

Make consumers of your APIs like you by implementing OAuth2 and hiding social auth complexities.  You can, during your oauth flow for your downstream sites, trigger an additional oauth flow with facebook.

Image because picture == words * 1000:

Can we call this oauth2-piggy-back?

Step by step flow

End user visits site that uses your API

End user is sent to your site to authorize or signup (oauth2)

End user picks social auth, clicks facebook login button

Your site sets a cookie or sets the state in the facebook oauth to know where the user came from

End user redirected to Facebook and accepts connection at facebook site

End user redirected to your site to complete facebook auth process

You lookup or create the user in your database

You create a new session on your server

You redirect the user back to their original site with your session token

Title: How should I architect a RESTful webservice to use 3rd party (i.e. Google, Facebook, Twitter) for authentication?

Body:
For my job we have a nice RESTful webservice we've built out that we use to drive a couple websites we have.  Basically the webservice lets you create and work with support tickets, and the website is responsible for the front end.  Any webservice requests use an auth header which we use to validate the user and their password for each call.

This year we're looking to expand our login options so that users on the website can log in via Google, Twitter, and Facebook (possibly others).  However I'm having a lot of trouble figure out how to architect this so the webservice can use the 3rd party authentication providers to ensure the users is who they say they are.  Is there any best practices out there for how to do this?

Currently we're thinking of having the website handle authenticating the users themselves, and then use a new setSessionId call that registers their current session with the webservice back end.  Each additional request to the webservice will pass along that sessionId and will validate it.  These seems okay, but I have that feeling in the back of my head that I'm not thinking this through and all my forum browsing and reading oauth and openid specs is just confusing me more.  Any tips for how to tackle this?


问:
Possible holes in a spam-registration prevention approach?
I was thinking of creating some login code (probably to work with BrowserID so users don't need to store their passwords with my site while also ensuring the supplied email account belongs to them) which required any user accounts to be an email address in the ".name" or possibly ".me" TLD (or in any other TLD that was intended for individuals or individual corporate employees only--i.e., not open to public registration) and perhaps disallowing subdomains (as it might be tempting for some companies to purchase a generic domain and lease out the personalized subdomains); of course it wouldn't stop a company from leasing out names like user123@spam-friendly-site.name, but as the TLD is intended for individuals, it would hopefully be easier to blacklist any such bad behavior-enabling sites wholesale.

The purpose would be two-fold:

Raise the threshold for spammers as they would have to either purchase a new domain any time they wanted a new spam account (and any abusing domains could be blacklisted and shared as a public list) or obtain control of a legitimate user's email account or browser/system.

Encourage people to throw off the yoke of dependency on fixed third parties for emails as well as website hosting, chatting, etc. by getting their own domains. One wouldn't want a phone number like 555-123-1234@att.com because one could not freely change providers. And there are no doubt many would-be content creators who would share more freely if they had a site belonging to them. If one wanted to be anonymous, one could reserve domains like anonymous567.name (e.g., me@anonymous567.name) -- and this would be fine with me as my purpose is not to positively ID people outside of the context of confirming they control the email address they give me but to raise barriers to spammers. It would add a small price to do content creation on the site as users would have to purchase a domain and configure email on it and would cost more so to become truly anonymous (e.g., to purchase separate domains for each site to avoid tracking between sites), but I think the burden should not lie on content websites to deal with spam registrations.

If this really gets going, one might also be able to set up one's email filters to block anyone not belonging to such a personalized domain as well, giving an auto-reply of how to register for one.

Does anyone have feedback on the idea, specifically any unexpected barriers I might encounter (such as ways it could be circumvented)? I know of course that it will raise barriers for some users, but any potential technical challenges?

答:
I think you have already identified one flaw.  In general, web hosting providers have no interest in checking on the identity of their users, or of ensuring that they use domain names for legitimate purposes.  Indeed, use of domain names as a proxy identities is probably not covered by their "terms of service" ... and not of interest to them.

In short, it won't be a significant impediment to spammers.

The second problem is that most people who don't already have a domain name don't want to be bothered with it.  It costs money to get and keep a domain name.  It costs time to organize.  There is a learning curve. And so on.

In short, it will be a significant impediment to a significant subset of your real users.

And the other issue is that your scheme does not address your primary requirement ... authorization and access control.

You asked about technical challenges.  Well my take is that the first problem above is a technical challenge.  Unless you insist on your users using specific hosting providers with specific procedures, your scheme provides no significant impediment to spammers.  All serious ("professional") spammers have ways to get an unlimited number of throw-away DNS addresses for free.  So you are just going to be playing "whack a mole" at a different level.


问:
VB stand alone application or ASP web application
I have experience developing software and web applications and I have decided to do some freelance work on the side. Well, I met with my first client and they are requesting a relatively simple, custom system that (without being long winded) tracks client’s paperwork as it progresses through the business’s different manual processes.

It is a small business that has about 10 employees, but all of the employees will interact with the client’s paperwork, therefore everyone would need access to the new system. When I say track I literally mean that the employees will check as complete on a simple page the increases a progress bar at different stages for the paperwork.

Now I am %110 capable of coding the custom system that meets their needs, but I am unsure about how I should go about doing it.
The information that is being tracked in the new system and stored in the DB is confidential information that they are very protective of. My main question is how should I be developing this to be as secure as I can?

They have their own server in house, so should I develop an application (VB and SQL) for the server and require employees to log on remotely to use it? Can more than one person access/use the application at a time?

Or should I develop a web application (ASP.Net/VB and SQL) that is only accessible on their network to their employees? They plan to expand offices, could they set up a VPN to access the site?

I’m leaning towards a web application, but I have not done too much in term of security. What specific options do I have for security that aren't too complex.

Basically I’m looking for pros and cons for either option or any suggestions on what I should.

答:
Actually, you have two independent choices to make:

Web application vs. desktop application,

An application available from anywhere vs. an application available only on local network.

The first choice has nothing to do with the network security and must be dictated by two elements:

The constraints related to the permissions required on the local machine. For example, you can't force print something from a web application, but only to invite the user to print it, you can't access local file system, etc.

The UX concerns, desktop applications being able to provide richer interaction design while having lesser impact on the performance. This is less true since HTML 5.

The second choice should be motivated by the ease of access to the system:

Entering passwords is tiring. They can be remembered, but once a user changes his Active Directory password, let's say once per month, he should enter his password again in his application.

For an application which is accessed from the internet, there is nothing you can do. On the other hand, when the user is on a local network, use Windows authentication to save the user the burden of entering a password.

VPNs are difficult to set up, often tied to a specific version of an operating system and rarely upgraded, etc. Don't use them.

If you want to provide the easiest way to use your app, make it available from anywhere, but also make it aware of the case where it is on a local network. In the first case, it will prompt for a username and a password; in the second case, it will be authenticated automatically.

If you're concerned about security, don't reinvent the authentication mechanism, use salts and hashes, use PBKDF2, read a good book about security and visit IT Security Stack Exchange website.

Note: why are you talking about ASP in the title of your question, while the question has nothing to do with it?


答:
To add to @MainMa's answer, this sounds to me more like a Project Management question, rather than a technical one.

The classic Project Manager's triangle:

You control one side, the client control's the other two.

You said you wanted to do web, but worried about security (scope).  Does your budget allow for training / research / education? (cost).  Even if you can afford the training, does the time frame allow you the time required to learn it? (schedule).

The old adage, "Sales Solves Everything" certainly applies.

Which technical direction can you afford?

Title: VB stand alone application or ASP web application

Body:
I have experience developing software and web applications and I have decided to do some freelance work on the side. Well, I met with my first client and they are requesting a relatively simple, custom system that (without being long winded) tracks client’s paperwork as it progresses through the business’s different manual processes.

It is a small business that has about 10 employees, but all of the employees will interact with the client’s paperwork, therefore everyone would need access to the new system. When I say track I literally mean that the employees will check as complete on a simple page the increases a progress bar at different stages for the paperwork.

Now I am %110 capable of coding the custom system that meets their needs, but I am unsure about how I should go about doing it.
The information that is being tracked in the new system and stored in the DB is confidential information that they are very protective of. My main question is how should I be developing this to be as secure as I can?

They have their own server in house, so should I develop an application (VB and SQL) for the server and require employees to log on remotely to use it? Can more than one person access/use the application at a time?

Or should I develop a web application (ASP.Net/VB and SQL) that is only accessible on their network to their employees? They plan to expand offices, could they set up a VPN to access the site?

I’m leaning towards a web application, but I have not done too much in term of security. What specific options do I have for security that aren't too complex.

Basically I’m looking for pros and cons for either option or any suggestions on what I should.


答:
To add To Christian's answer, I think it's only your decision so far. It will be better to think all the possibilities based on the information that you are having, prepare the answers and estimates, then communicate with your client.

Communication is one of the key parts to be an consultant. I have been seeing a lot of consultant without good tech skills, but they can solve the clients' problems.

Clients like options, but sometime, they lost in the options, and you can help them or give suggestions at that time. However, make sure they understand all the scenarios, causes/effects.