答:
You are assuming that session storage and database storage are exclusive.  They aren't.  But let's start by assuming they are.

The advantage to session storage is three-fold:

No need to explicitly insert data into the database.  You just simply set a session variable and you're done.  Simple and low-risk functionally.

No need to manage the lifecycle of a user visit and shopping cart as containers / frameworks do it for you

Usually auto-cleanup of old idle sessions is done for you.

Disadvantages of session storage:

Session affinity, unless you investigate replication

No failover, unless you investigate replication or manual persistence of session state to disk, which can get complicated.

All sessions must be stored in memory.  This is amplified if you employ replication.

Advantages of database storage:

No need to worry about session affinity or state replication.  You can round-robin all requests.

Less memory overhead in application.

If the order is completed, everything ends up in the database anyway, so this could make completion easy because the data is already present.

Disadvantages of database storage:

Abandoned carts - some anonymous user added an item to their shopping cart and disappeared.  That data sticks around forever unless you have some sort of expiration process.

You need to come up with a way to track users and figure out if, for a given request, this represents an existing or new browsing session.  (yes, this is probably easy if you use a cookie, but how do you ensure two users don't end up with the same id?).

More code

You didn't mention what platform you are using.  I would seek an approach that uses a database-backed session where the session data only exists in memory during the life of a request/response cycle, loading it from the database and saving back to the database.  This has served me well in the past.

Advantages of a database-backed session:

No need for server affinity.

Easy on the app server memory

Idle / abandoned session data is cleaned up for you.

Lifecycle of user first visit, repeat visit, session end is all figured out for you.

Easy to code

Disadvantages of a database-backed session:

Configuration - you need to investigate your container, whether it's PHP, Java EE (Tomcat, Jetty, JBoss, etc.), node.js + express.js or whatnot support this and supply the right configuration.

You may need to load test this since you are adding 2 database operations per request.

There is a third possibility, which somebody touched on earlier.  You could skip the use of sessions altogether and use client-side storage by either embedding everything in a cookie or html local storage.

I'll leave the pros/cons of that as an exercise to you, but I'll give you a hint that for html5 storage, browser compatibility may be something to review carefully.

I've outlined the facts for you.  Hopefully this helps you make the right decision for your situation.

Title: HTTP Session or Database approach

Body:
I am confused a little as what should be my approach, Working on a design of shopping cart and i need to store shopping cart either in session or in database but not sure which approach would be best.here are the use case

User is not logged in and adding product to cart (Anonymous user)

User is logged in and adding product to cart.

First case is more confusing to me, since there can be many cases where user just visiting web-shop and adding product without logging in and can be quite possible that he might not going for a checkout process.

But still we need to create a Shopping-Cart for this user, in order to create and save shopping-cart i have two option.

When user adding a product, create a cart in the database and associate this cart with this user, moment he logged in move this cart to logged in user.

Create Cart, add product to it and save it to the Session, when user logged in create Cart in the database and associated logged in user with this cart with User.

I know that both database driven Cart system as well Session based can have there positive as well negative aspects, but not sure which one might be the best approach taking in to account following points

Scalability

Flexibility

Extensibility

Application Should take care of speed

Looking for input on this aspect to decide the path.


问:
Client = Html5 + CSS3 + JS + Jquery. Server =?
I want to build most of my functionality on the client. However I'm not quite sure which server-side web development framework can provide me with a nice REST endpoint to handle resources, business logic, etc. I come from a JAVA EE world, where JSF is mostly stateful and component based (both have their pros and cons, I'd just rather not keep a component tree, etc).. However...

I used to build templates in Facelets, how can I do this now if I don't use JSF/Facelets as my presentation layer? Or how do I create HTML tables iterating over collections, etc? I'm open to using any language/framework. I see a lot of discussion yet not really any valuable input. Perhaps I have yet to look in the right places.

There's a lot of people talking about JS + RESTful ws... Is this actually possible for a whole web site? I think that if I drop my component based web framework I'll have to implement so many things by myself, like conditionally rendered portions of the website, iterating over data to build grids, tables, handling multiple-page operations, view scoped data.

Maybe someone could also tell me: are you out of your mind? Go hybrid or don't do that. Any directions will help.

答:
There are lots of nice RESTful libraries in Java (as you mentioned you are from JEE background).

I believe all well-known languages available do have usable RESTful libraries.  The choice of language should be more determined by something like: What language you want to develop your middle tier logic on? Is there any legacy code to make use? How it is integrating with other systems, etc.  Simply "RESTful WS" is never a driving factor to choose the technology to use on server side (at least true for me).

ContentLicense: CC BY-SA 3.0


问:
why are noSQL databases more scalable than SQL?
Recently I read a lot about noSQL DBMSs. I understand CAP theorem, ACID rules, BASE rules and the basic theory. But didn't find any resources on why is noSQL scalable more easily than RDBMS (e.g. in case of a system that requires lots of DB servers)?

I guess that keeping constraints and foreign keys cost resources and when a DBMS is distributed, it is a lot more complicated. But I expect there's a lot more than this.

Can someone please explain how noSQL/SQL affects scalability?

答:
It's true that NoSQL databases (MongoDB, Redis, Riak, Memcached, etc.) don't maintain foreign key constraints, and atomic operations must be more explicitly specified.  It's also true that SQL databases (SQL Server, Oracle, PostgreSQL, etc.) can be scaled to handle very large performance requirements by seasoned DBAs.

NoSQL databases allow seasoned programmers, who are well aware of race-conditions and atomic operations, to forego a large amount of processing only required in a small percentage of today's web application code.  NoSQL databases certainly have atomic operations and most all transactional requirements present in SQL databases can also be obtained NoSQL databases.  The difference is the level of abstraction.  NoSQL databases remove the higher levels of abstraction and hand that capability to the application programmer, thereby resulting is faster code overall with the increased probability of data corruption by unseasoned programmers.

As a result we are much more likely to see NoSQL databases being used more and more heavily in the web application space, where development time and performance are very important.  Financial and corporate software is likely to retain it's SQL heritage because hardware performance is relatively cheap, they have seasoned DBAs on-hand, and the increased risk caused by unseasoned programmers is not palatable.


答:
There's no "right" answer to your question, but I'll tell you what I've chosen, and a bit about why.

Back-End

I come from a similar background, and I've chosen to use Spring Data REST as the service layer, because it provides a simple and flexible way to expose CRUD functionality for my data. Until I found this project I was writing the data access and REST service code myself, so it has saved me many months of work. It works well for me because there's not a lot of specific business logic that I'm worried about exposing in client-side JS.

If you prefer more control over your business logic, Spring Web MVC is really powerful but makes it easy to expose your services with a web service inteface.

Front-End

I started work on the web front-end using JSPs, and the page refreshes felt really sluggish compared to the more responsive client-side webapps that only retrieve the data that changes between pages, and only re-render sections of the page as necessary.

If you start looking into it, you'll find lots of different client-side JS frameworks that'll help reduce boilerplate and structure your code to be extendable and maintainable. My main reference for deciding on one was this comparison which considers around 10 of the most popular and describes how you might pick one based on your needs. Linked from there I found TodoMVC, which is a simple todo webapp implemented in all the same frameworks and more, which allows you to see them in action, and compare how they implement various common patterns in client-side JS development.

For myself, I chose Backbone.js because it met my needs and seemed to be the most widely-used, so I have a lot of resources when finding solutions to common problems. There are lots of secondary libs that can be used alongside Backbone.js as well, such as Marionette, Backbone.ModelBinder, and others.

Title: Client = Html5 + CSS3 + JS + Jquery. Server =?

Body:
I want to build most of my functionality on the client. However I'm not quite sure which server-side web development framework can provide me with a nice REST endpoint to handle resources, business logic, etc. I come from a JAVA EE world, where JSF is mostly stateful and component based (both have their pros and cons, I'd just rather not keep a component tree, etc).. However...

I used to build templates in Facelets, how can I do this now if I don't use JSF/Facelets as my presentation layer? Or how do I create HTML tables iterating over collections, etc? I'm open to using any language/framework. I see a lot of discussion yet not really any valuable input. Perhaps I have yet to look in the right places.

There's a lot of people talking about JS + RESTful ws... Is this actually possible for a whole web site? I think that if I drop my component based web framework I'll have to implement so many things by myself, like conditionally rendered portions of the website, iterating over data to build grids, tables, handling multiple-page operations, view scoped data.

Maybe someone could also tell me: are you out of your mind? Go hybrid or don't do that. Any directions will help.


问:
Can I convert ALL CAPS sections of an OSI license to regular case (and bold)?
Update: I've got a response from the FSF on this down in the answers

From the answer to Can I remove all-caps and shorten the disclaimer on my License?, it appears that the APP CAPS sections of a software license are largely to provide extra legal ammo and increase the weight of those sections.

On the flip side, ALL CAPS TEXT is more difficult to read in paragraph form.  Furthermore, with formats like markdown, we can provide cleaner alternatives to all-caps "bolding" of text.

So, I'd like to convert (for example) the warranty clause of the MIT license from:

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

to (markdown):

```<code>**The software is provided "as is", without warranty of any kind, express or
implied, including but not limited to the warranties of marchantability,
fitness for a particular purpose and noninfringement. In no event shall the
authors or copyright holders be liable for any claim, damages or other
liability, whether in an action of contract, tort or otherwise, arising from,
out of or in connection with the software or the use or other dealings in the
software.**
</code>```

Is this legally murky territory?  (particularly w/ GPL?)

答:
Some notes from FSF on the subject:

The license states that only verbatim copying is allowed, but
historically I believe we have not been concerned about superficial
changes. As long as you're not changing the text itself or using wonky
formatting tricks to try and deceive users about what the license
actually says, it shouldn't be an issue for us.

On why these sections exist:

Those sections are disclaimers of liability and warranties. In some
jurisdictions, such disclaimers are only effective if they are made
somehow conspicuous. This makes some sense; the disclaimer is meant to
put the user on notice that they should be on guard regarding the item,
so trying to sneak the disclaimer by them by mushing it in with a bunch
of other text (or even making it smaller or harder to read) wouldn't be
fair. So they are made all-caps to stand out from the rest of the text.
I'm not sure whether bold vs. all-caps makes a difference in terms of
the effectiveness of the disclaimer (you'd have to consult a lawyer in
the particular jurisdiction you are concerned about), but if I had to
guess, all-caps was selected because these licenses are generally
distributed in plain text.


问:
How do I manage multiple relationships from a software design perspective?
How do I go about managing projects when there are two fundamental relationships that need to be maintained?  The most obvious example that I can think of would be a firm doing some kind of location-based consulting.

I've been wracking my brain on how to explain this, in essence, this is the bullet point version:

Each client that has multiple locations

There are several projects that relate to specific client locations

There are deliverables for these projects

Each deliverable my only relate to a few locations the project is linked to

The system seems to break down when you overlay these two main relationships; a client with multiple locations which have projects assigned to them, and deliverables that link back to individual locations.  You just end up with too many many-to-many relationships that are difficult to manage.

The problem is then visualizing this in a system.  You have a client record with location sub-records.  Each location record has many project records associated with it.  Each Project record has deliverable records, and then those deliverables relate to specific loations.

I realize that this seems a bit estoeric, but is there a way to simplify this so that it is visually understandable?

答:
This seems like a fairly straightfoward relational data structure.

```<code>client <- location; or
client <- clientLocation -> location

project <- location; or
project <- projectLocation -> location

deliverable <- location; or
deliverable <- project; or
deliverable <- location
            <- project
</code>```

It's true that if you have a number of many-many relationships you'll end up with more tables, but we're only talking about a few entities.

It's not true to say that

The system seems to break down when you overlay these two main relationships

The system will work fine if it properly describes the relationships. If it becomes too complex to visualize then the proper way to proceed is to break down the visualization into stages or tiers.

For example, do you need to view data from multiple clients at once? If not, then simply have an initial filter that restricts the relevant data to a single client. Alternatively you might be able to restrict to a single location or project.

The key is in prioritizing the visualization process with regards to importance and logical progression. e.g. A user will first select a client, then select the relevant projects, and finally sort by location.

OwnerDisplayName: Addikt

Body:
This seems like a fairly straightfoward relational data structure.

client <- location; or
client <- clientLocation -> location

project <- location; or
project <- projectLocation -> location

deliverable <- location; or
deliverable <- project; or
deliverable <- location
            <- project

It's true that if you have a number of many-many relationships you'll end up with more tables, but we're only talking about a few entities.

It's not true to say that

The system seems to break down when you overlay these two main relationships

The system will work fine if it properly describes the relationships. If it becomes too complex to visualize then the proper way to proceed is to break down the visualization into stages or tiers.

For example, do you need to view data from multiple clients at once? If not, then simply have an initial filter that restricts the relevant data to a single client. Alternatively you might be able to restrict to a single location or project.

The key is in prioritizing the visualization process with regards to importance and logical progression. e.g. A user will first select a client, then select the relevant projects, and finally sort by location.


问:
clojure/erlang/go for high volume server
I have a project that will need to handle 1000s of requests a second with a decent amount of processing for each.  For the most part, the processing will be done on a list of items, basically filtering it and returning a smaller list.  This process can be done in parallel fairly easily and I should also say, speed is important.  I've narrowed my language of choice for the project down to clojure, erlang, and go, and have researched them all to a moderate degree.

My question is, what factors should I be looking at in my decision?  What language is better for what (examples would be great)?  Because it's a little difficult for me to tell.

答:
I'd pick Go, but then I've had a good time using it for "real stuff" for a while and never got past the "play stage" with Erlang and haven't used Clojure.

It seems like it's a problem that's small enough that it might be a good test case for trying all three languages so you can see how you like each?

Maybe report back what you find when you are done; or go to the codereview stack site for suggestions on each program. :-)


问:
How do you store "fuzzy dates" into a database?
This is a problem I've run into a few times. Imagine you have a record that you want to store into a database table. This table has a DateTime column called "date_created". This one particular record was created a long time ago, and you're not really sure about the exact date, but you know the year and month. Other records you know just the year. Other records you know the day, month and year.

You can't use a DateTime field, because "May 1978" isn't a valid date. If you split it up into multiple columns, you lose the ability to query. Has anyone else run into this, if so how did you handle it?

To clarify the system I'm building, it is a system that tracks archives. Some content was produced a long time ago, and all that we know is "May 1978". I could store it as May 1 1978, but only with some way to denote that this date is only accurate to the month. That way some years later when I'm retrieving that archive, I'm not confused when the dates don't match up.

For my purposes, it is important to differentiate "unknown day in May 1978" with "May 1st, 1978". Also, I would not want to store the unknowns as 0, like "May 0, 1978" because most database systems will reject that as an invalid date value.

答:
In your case you need only year, month and day. Year and month are required, day is optional. I'd use something like that:

```<code>year smallint not null,
month smallint not null,
day smallint
</code>```

Plus is, you can still use indexes very effectively. The (tiny= minus, queires get a bit more "complicated" (longer).

Body:
In your case you need only year, month and day. Year and month are required, day is optional. I'd use something like that:

year smallint not null,
month smallint not null,
day smallint

Plus is, you can still use indexes very effectively. The (tiny= minus, queires get a bit more "complicated" (longer).


答:
Why not store two dates.

Created_After and Created_Before. The actual semantics being "created on or after" and "created on or before"

So if you know the exact date then Created_After and Created_Before will be the same date.

If you know it was the first week in May 2000 then Created_After = '2000-05-01' and Created_Before = '2000-05-07'.

If you just know May 1999 then the values will be '1999-05-01' and '1999-05-30'.

If it's "Summer of '42" then the values would be '1942-06-01' and '1942-08-31'.

This schema is simple to query with normal SQL, and quite easy for a non technical user to follow.

For instance to find all documents that might have been created in May 2001:

```<code>SELECT * FROM DOCTAB WHERE Created_After < '2001-05-31' And Created_Before > 2001-05-01;
</code>```

Conversely to find all documents that were definitely created in May 2001:

```<code>SELECT * FROM DOCTAB WHERE Created_After > '2001-05-01' And Created_Before < 2001-05-31;
</code>```

Title: How do you store "fuzzy dates" into a database?

Body:
This is a problem I've run into a few times. Imagine you have a record that you want to store into a database table. This table has a DateTime column called "date_created". This one particular record was created a long time ago, and you're not really sure about the exact date, but you know the year and month. Other records you know just the year. Other records you know the day, month and year.

You can't use a DateTime field, because "May 1978" isn't a valid date. If you split it up into multiple columns, you lose the ability to query. Has anyone else run into this, if so how did you handle it?

To clarify the system I'm building, it is a system that tracks archives. Some content was produced a long time ago, and all that we know is "May 1978". I could store it as May 1 1978, but only with some way to denote that this date is only accurate to the month. That way some years later when I'm retrieving that archive, I'm not confused when the dates don't match up.

For my purposes, it is important to differentiate "unknown day in May 1978" with "May 1st, 1978". Also, I would not want to store the unknowns as 0, like "May 0, 1978" because most database systems will reject that as an invalid date value.

Body:
Why not store two dates.

Created_After and Created_Before. The actual semantics being "created on or after" and "created on or before"

So if you know the exact date then Created_After and Created_Before will be the same date.

If you know it was the first week in May 2000 then Created_After = '2000-05-01' and Created_Before = '2000-05-07'.

If you just know May 1999 then the values will be '1999-05-01' and '1999-05-30'.

If it's "Summer of '42" then the values would be '1942-06-01' and '1942-08-31'.

This schema is simple to query with normal SQL, and quite easy for a non technical user to follow.

For instance to find all documents that might have been created in May 2001:

SELECT * FROM DOCTAB WHERE Created_After < '2001-05-31' And Created_Before > 2001-05-01;

Conversely to find all documents that were definitely created in May 2001:

SELECT * FROM DOCTAB WHERE Created_After > '2001-05-01' And Created_Before < 2001-05-31;


答:
From IBM developerWorks: Supply cloud-level data scalability with NoSQL databases

Scalability is the system that should be able to support very large databases with very high request rates at very low latency.

NoSQL systems have a number of design features in common:

The ability to horizontally scale out throughput over many servers.

A simple call level interface or protocol (in contrast to a SQL
binding).

Support for weaker consistency models than the ACID transactions in
most traditional RDBMS.

Efficient use of distributed indexes and RAM for data storage.

The ability to dynamically define new attributes or data schema.

Why relational databases may not be optimal for Scaling

In general, relational database management systems have been considered as a "one-size-fits-all solution for data persistence and retrieval" for decades. They have matured after extensive research and development efforts and very successfully created a large market and solutions in different business domains.

The ever-increasing need for scalability and new application requirements have created new challenges for traditional RDBMS, including some dissatisfaction with this one-size-fits-all approach in some web-scale applications. The answer to this has been a new generation of low-cost, high-performance database software designed to challenge dominance of relational database management systems. A big reason for the NoSQL movement is that different implementations of web, enterprise, and cloud computing applications have different requirements of their databases — not every application requires rigid data consistency, for example.

Another example: For high-volume websites like eBay, Amazon, Twitter, or Facebook, scalability and high availability are essential requirements that cannot be compromised. For these applications, even the slightest outage can have significant financial consequences and impacts customer trust.

Over on DBA.SE: What does horizontal scaling mean?

Horizontal Scaling is essentially building out instead of up. You don't go and buy a bigger beefier server and move all of your load onto it, instead you buy 1+ additional servers and distribute your load across them.

Horizontal scaling is used when you have the ability to run multiple instances on servers simultaneously. Typically it is much harder to go from 1 server to 2 servers then it is to go from 2 to 5, 10, 50, etc.

Once you've addressed the issues of running parallel instances, you can take great advantage of environments like Amazon EC2, Rackspace's Cloud Service, GoGrid, etc as you can bring instances up and down based on demand, reducing the need to pay for server power you aren't using just to cover those peak loads.

Relational Databases are one of the more difficult items to run full read/write in parallel.

Title: why are noSQL databases more scalable than SQL?

Body:
Recently I read a lot about noSQL DBMSs. I understand CAP theorem, ACID rules, BASE rules and the basic theory. But didn't find any resources on why is noSQL scalable more easily than RDBMS (e.g. in case of a system that requires lots of DB servers)?

I guess that keeping constraints and foreign keys cost resources and when a DBMS is distributed, it is a lot more complicated. But I expect there's a lot more than this.

Can someone please explain how noSQL/SQL affects scalability?


答:
ISO 8601 date time format comes with duration definition, e.g.

2012-01-01P1M (read: 2012, January 1st, period: 1 month) is what should be “in January 2012”.

I would use this to store the data. You may need a database field of type String to do so. It’s a different topic how to conduct a sensible search on that.


问:
How can I ensure a method is called only once when using a API?
In general, if I am using an API whose methods have side-effects that I only want to occur once, how can I guarantee that my own application only calls them once even if an error occurs before it can register a response?

For example, if I am calling a payment processing API once each month for a subscription service, how can I ensure that I don't double-bill if I create a new transaction and the application suffers a fatal error before I get the response from that? It seems like cooperation with the API would be a solution:

```<code>t = Transaction.new(user, price, etc);
if(t.persistToLocalDatabase()){ t.beginRemoteProcessing(); }
</code>```

Is there a way to solve this for the case where I have no control over the API and it begins processing on transaction creation?

答:
Use a variable to flag the call to the method. Check this immediately and return if the flag is set.

In C/C++ you can use a static local variable to store the flag.


答:
The first thing to do is to write a flag to disk before you start the transaction to indicate that this month's transaction has been attempted. That way you never accidentally call the API twice.

In the case of any kind of error, you need to make sure the system notifies a human (e.g. send an email) who can verify the transaction status and offers them a way to manually reprocess the transaction.

After a few months you'll discover either (a) The humans are bored of being contacted and you need to redesign the system (e.g find a way to automate the check/retry via the API) or (b) The system is running smoothly and everyone's happy. Hopefully (b).

Title: How can I ensure a method is called only once when using a API?

Body:
In general, if I am using an API whose methods have side-effects that I only want to occur once, how can I guarantee that my own application only calls them once even if an error occurs before it can register a response?

For example, if I am calling a payment processing API once each month for a subscription service, how can I ensure that I don't double-bill if I create a new transaction and the application suffers a fatal error before I get the response from that? It seems like cooperation with the API would be a solution:

```<code>t = Transaction.new(user, price, etc);
if(t.persistToLocalDatabase()){ t.beginRemoteProcessing(); }
</code>```

Is there a way to solve this for the case where I have no control over the API and it begins processing on transaction creation?


答:
If you are sending a request which can fail indistinguishably either before or after it's side-effects occur (as is the case of any network request where either request or response may get lost), there is no way to ensure the side-effects occur exactly once. Only either at most once (you don't retry) or at least once (you keep retrying until you get a response).

To get around this limitation, you need cooperation from the server side, i.e. the side where the side-effects occur. There are two options:

The operation should be idempotent. That is if it executes multiple times, the effects are the same as if it did just once.

You can inquire about status of the operation separately.

Both cases require that the data sent by client uniquely identify the transaction in some way. So than you generate the transaction data, persist them locally and send the request. If it is idempotent, you keep retrying until you get response. If it has separate query, you ignore the response and do the query, retrying the query until you get response for it, and retrying the request while the status is not carried out.

If the API does not support either, the only chance, as grahamparks suggested, is to report the error to human operator to fix things up by other means.


答:
Advantage of Erlang is that it has distributed processing including fail-over built in while for the other two languages you would have to give a bit of thought to making sure it can run on multiple servers in parallel. If the requests are independent, it will be trivial in any language, if they are strongly dependent, Erlang may give some advantage.

For the rest, hardware is cheap compared to developer time, so choose the language depending on what your team is most comfortable with.

Benchmarks suggest Erlang is the slowest of the three, but than it's just benchmark and the relation may be completely different in your particular case, so don't give it much thought. For what it's worth most web applications out there is implemented in PHP, Ruby and Python and they are the three slowest languages according to benchmarks. But they are easy to write in and reading the data is bigger bottleneck for most webs anyway, so it ends up being cheaper even with the bit extra hardware needed.

Title: clojure/erlang/go for high volume server

Body:
I have a project that will need to handle 1000s of requests a second with a decent amount of processing for each.  For the most part, the processing will be done on a list of items, basically filtering it and returning a smaller list.  This process can be done in parallel fairly easily and I should also say, speed is important.  I've narrowed my language of choice for the project down to clojure, erlang, and go, and have researched them all to a moderate degree.

My question is, what factors should I be looking at in my decision?  What language is better for what (examples would be great)?  Because it's a little difficult for me to tell.


问:
Python multiple inheritance or decorators for composable behaviours
I recently discovered (or rather realised how to use) Python's multiple inheritance, and am afraid I'm now using it in cases where it's not a good fit. I want to have some starting data source (NewsCacheDB,TwitterStream) that gets transformed in various ways (Vectorize,SelectKBest,SelectPercentile).

I found myself writing the following sort of code (Example 1) (the actual code is a bit more complex but the idea is the same). The point being that for ExperimentA and ExperimentB I can define exactly what self.data is, by just relying on class inheritance. Is this really a useful way of achieving the desired behaviour?

I could also use decorators (Example 2). Using the decorators would be less code.

Which approach is preferable? I'm not looking for arguments of the "I like writing decorators better" kind, but rather arguments about

readability

maintainability

testability

pythonicity (yes it's a word).

EXAMPLE 1

```<code>class NewsCacheDB(object):
    """Play back cached news articles from a database"""
    def __init__(self):
        super(NewsArticleCache, self).__init__()

    @property
    def data(self):
        # setup access to data base
        while db.isalive():
            yield db.next() # slight simplification here

class TwitterCacheDB(object):
    """Play back cached tweets from a database"""
    def __init__(self):
        super(TwitterCache, self).__init__()

    @property
    def data(self):
        # setup access to data base
        while db.isalive():
            yield db.next() # slight simplification here

class TwitterStream(object):
    def __init__(self):
        super(TwitterStream, self).__init__()

    @property
    def data(self):
        # setup access to live twitter stream
        while stream.isalive():
            yield stream.next()

class Vectorize(object):
    """Turn raw data into numpy vectors"""
    def __init__(self):
        super(Vectorize, self).__init__()

    @property
    def data(self):
        for item in super(Vectorize, self).data:
            transformed = vectorize(item) # slight simplification here
            yield transformed

class SelectKBest(object):
    """Select K best features based on some metric"""
    def __init__(self):
        super(SelectKBest, self).__init__()

    @property
    def data(self):
        for item in super(SelectKBest, self).data:
            transformed = select_kbest(item)  # slight simplification here
            yield transformed

class SelectPercentile(object):
    """Select the top X percentile features based on some metric"""
    def __init__(self):
        super(SelectPercentile, self).__init__()

    @property
    def data(self):
        for item in super(SelectPercentile, self).data:
            transformed = select_kbest(item)  # slight simplification here
            yield transformed

class ExperimentA(SelectKBest, Vectorize, TwitterCacheDB):
    # lots of control code goes here

class ExperimentB(SelectKBest, Vectorize, NewsCacheDB):
    # lots of control code goes here

class ExperimentC(SelectPercentile, Vectorize, NewsCacheDB):
    # lots of control code goes here
</code>```

EXAMPLE 2

```<code>def multiply(fn):
    def wrapped(self):
        return fn(self) * 2
    return wrapped

def twitter_cacheDB(fn):
    def wrapped(self):
        user, pass = fn(self)
        # setup access to data base
        while db.isalive():
            yield db.next() # slight simplification here
    return wrapped

def twitter_live(fn):
    def wrapped(self):
        user, pass = fn(self)
        # setup access to data base
        while stream.isalive():
            yield stream.next() # slight simplification here
    return wrapped

def news_cacheDB(fn):
    def wrapped(self):
        user, pass = fn(self)
        # setup access to data base
        while db.isalive():
            yield db.next() # slight simplification here
    return wrapped

def vectorize(fn):
    def wrapped(self):
        for item in fn():
            transformed = do_vectorize(item)  # slight simplification here
            yield transformed
    yield wrapped

def select_kbest(fn):
    def wrapped(self):
        for item in fn():
            transformed = do_selection(item)  # slight simplification here
            yield transformed
    yield wrapped

class ExperimentA():
    @property
    @select_kbest
    @vectorize
    @twitter_cacheDB
    def a(self):
        return 'me','123' # return user and pass to connect to DB

class ExperimentB():
    @property
    @select_kbest
    @vectorize
    @news_cacheDB
    def a(self):
        return 'me','123' # return user and pass to connect to DB
</code>```

答:
Less code, as long as it's readable is better than more code

From a code size point of view I always go with the solution that requires the least amount of code that is still readable and maintainable.  Less code means less chance for defects and less code to maintain.

Multiple Inheritance is not a good choice for Composition

From a design stand point I would not use multiple inheritance the way you describe for the following reasons:

attribute/method overloading

You are changing the way data is behaving in the different classes.  While it doesn't directly violate the Open/Closed Principle of OO with the initial implementation, any changes in the future have a good chance of modifying the behaviors in one or more locations. You are also relying on behavior pulled through super which will only works correctly if you have the base classes ordered correctly in the class definition.

fragile tight (vertical) coupling

Relying on the class definition to specify the correct ordering of classes create a fragile system.  It's fragile because you can't choose classes that have particular interfaces defined, you actually have to know the implemented logic so the super calls get executed in the correct order.  It's also an extremely tight coupling as a result. Since it's using class inheritance we also get vertical coupling which basically means there are implicit dependencies not just in individual methods, but potentially between the different layers (classes).

multiple inheritance pitfalls

Multiple inheritance in any language often has many pitfalls.  Python does some work to fix some issues with inheritance, however there are numerous ways of unintentionally confusing the method resolution order (mro) of classes.  These pitfalls always exist, and they are also a prime reason to avoid using multiple inheritance.

Alternatives

Alternatively I would leave data source specific logic in the classes (ie. *_CacheDB).  Then use either decorator or functional composition to add the generalized logic to automatically apply the transformations.

OwnerDisplayName: Matti Lyra


问:
Books/sources on inner workings of JavaScript
When I started studying C++ a couple of years ago, a lot of the books and texts I read did a very thorough job of explaining, how the code written would translate into concrete operations in the hardware (like dynamically memory allocation, pointer arithmetics etc.). I found those explanations extremely helpful in order to fully understand the language.

Now I am studying JavaScript and learning about the whole functional programming paradigm, with functions as first class objects and so on. I have read a lot of texts and books about how to use JavaScript, but I have yet to come across a source, that explains the low-level inner workings of the language (like how a function is represented in memory, what excactly happens when a function is called with .apply() and a new context is provided etc.).

I guess you could say, that what I am looking for is the knowledge needed to write a JS compiler/VM..? How the runtime environments handle the different aspects of the language at a low level.

Does anyone know where to find books or text, that goes into the very low level details of the language?

答:
Memory representation etc is implementation details specific for each js compiler. There is no right or wrong way to do it, as long as your implementation works as expected.

But what you are looking for is probably the ECMAScript specification, which is detailed enough.

If you're interested in implementation details, I suggest you check out the various projects, such as Chromes' V8 engine. It comes with code as well :)

There are no books about JavaScript Engines as far as I know.


答:
I would simply store the exact time for normal dates and make the time portion of the fuzzy date generic like 00:00:00. I would then make all the fuzzy dates the 1st of the month.

When you query, you

check for date ranges where the time is also equal to 00:00:00 (fuzzy)

check for date ranges where the time is NOT equal to 00:00:00 (real)

check for date ranges but ignore the time portion (combined)

There are better solutions than this, but I personally hate metadata (data about my data). It just has a habit of getting out of hand after a while.


答:
It's not about NoSQL vs SQL, it's about BASE vs ACID.

Scalable has to be broken down into its constituents:

Read scaling = handle higher volumes of read operations

Write scaling = handle higher volumes of write operations

ACID-compliant databases (like traditional RDBMS's) can scale reads. They are not inherently less efficient than NoSQL databases because the (possible) performance bottlenecks are introduced by things NoSQL (sometimes) lacks (like joins and where restrictions) which you can opt not to use. Clustered SQL RDBMS's can scale reads by introducing additional nodes in the cluster. There are constraints to how far read operations can be scaled, but these are imposed by the difficulty of scaling up writes as you introduce more nodes into the cluster.

Write scaling is where things get hairy. There are various constraints imposed by the ACID principle which you do not see in eventually-consistent (BASE) architectures:

Atomicity means that transactions must complete or fail as a whole, so a lot of bookkeeping must be done behind the scenes to guarantee this.

Consistency constraints mean that all nodes in the cluster must be identical. If you write to one node, this write must be copied to all other nodes before returning a response to the client. This makes a traditional RDBMS cluster hard to scale.

Durability constraints mean that in order to never lose a write you must ensure that before a response is returned to the client, the write has been flushed to disk.

To scale up write operations or the number of nodes in a cluster beyond a certain point you have to be able to relax some of the ACID requirements:

Dropping Atomicity lets you shorten the duration for which tables (sets of data) are locked. Example: MongoDB, CouchDB.

Dropping Consistency lets you scale up writes across cluster nodes. Examples: riak, cassandra.

Dropping Durability lets you respond to write commands without flushing to disk. Examples: memcache, redis.

NoSQL databases typically follow the BASE model instead of the ACID model. They give up the A, C and/or D requirements, and in return they improve scalability. Some, like Cassandra, let you opt into ACID's guarantees when you need them. However, not all NoSQL databases are more scalable all the time.

The SQL API lacks a mechanism to describe queries where ACID's requirements are relaxed. This is why the BASE databases are all NoSQL.

Personal note: one final point I'd like to make is that most cases where NoSQL is currently being used to improve performance, a solution would be possible on a proper RDBMS by using a correctly normalized schema with proper indexes. As proven by this very site (powered by MS SQL Server) RDBMS's can scale to high workloads, if you use them appropriately. People who don't understand how to optimize RDBMS's should stay away from NoSQL, because they don't understand what risks they are taking with their data.

Update (2019-09-17):

The landscape of databases has evolved since posting this answer. While there is still the dichotomy between the RDBMS ACID world and the NoSQL BASE world, the line has become fuzzier. The NoSQL databases have been adding features from the RDBMS world like SQL API's and transaction support. There are now even databases which promise SQL, ACID and write scaling, like Google Cloud Spanner, YugabyteDB or CockroachDB. Typically the devil is in the details, but for most purposes these are "ACID enough". For a deeper dive into database technology and how it has evolved you can take a look at this slide deck (the slide notes have the accompanying explanation).

ContentLicense: CC BY-SA 4.0


问:
Why would anyone need this java syntax?
One day while trawling through the Java language documentation, as you do, I found this little beauty lurking within Double:

```<code>0.25 == 0x1.0p-2
</code>```

Now, obviously (!) this means take the number hexadecimal 1 and right shift it decimal 2 times. The rule seems to be to use base 16 on the integer side and base 2 on the real side.

Has anyone out there actually used the right hand syntax in a necessary context, not just as a way getting beers out of your fellow developers?

答:
Just a guess:  Some numbers that are rational in base10 are irrational in base2, and conversely some numbers that are rational in base2 are irrational in base10 (Please correct me if I'm wrong...I'm looking this up to confirm).

EDIT: thanks to "Note to self - think of a name" for correcting me.

I supposed that if you had a need to specify an exact binary value as a floating point (such as some epsilon value in graphical programming), then it might be more convenient to use this syntax.  For example, 1/1024 is 0.0009765625 in base 10, but using this syntax it can be written as 0x1.0p-10

ContentLicense: CC BY-SA 2.5

Title: Why would anyone need this java syntax?


问:
Silverlight support from Microsoft
I heard Silverlight will not be supported any more by Microsoft. It is true? If so, could anyone share with me Microsoft announcement? And if there are already application developed by Silverlight, what is the new technology to migration to?

thanks in advance,
Lin

答:
Microsoft will no longer support, or at least does not encourage, use of Silverlight on the desktop but still advocates its usage on mobile. I'll try and find the link.

First I heard of it.

A developer's complaint.

Title: Silverlight support from Microsoft


问:
Using scoped enums for bit flags in C++
An enum X : int (C#) or enum class X : int (C++11) is a type that has a hidden inner field of int that can hold any value. In addition, a number of predefined constants of X are defined on the enum. It is possible to cast the enum to its integer value and vice versa. This is all true in both C# and C++11.

In C# enums are not only used to hold individual values, but also to hold bitwise combinations of flags, as per Microsoft's recommendation. Such enums are (usually, but not necessarily) decorated with the [Flags] attribute. To make the lives of developers easier, the bitwise operators (OR, AND, etc...) are overloaded so that you can easily do something like this (C#):

void M(NumericType flags);

M(NumericType.Sign | NumericType.ZeroPadding);
```

<p>I am an experienced C# developer, but have been programming C++ only for a couple of days now, and I am not known with the C++ conventions. I intend to use a C++11 enum in the exact same way as I was used to do in C#. In C++11 the bitwise operators on scoped enums are not overloaded, so I wanted to overload them. </p>

<p>This solicited a debate, and opinions seem to vary between three options:</p>

<ol>
<li><p>A variable of the enum type is used to hold the bit field, similar to C#:</p>

<pre class="lang-cpp prettyprint-override"><code>void M(NumericType flags);

// With operator overloading:
M(NumericType::Sign | NumericType::ZeroPadding);

// Without operator overloading:
M(static_cast<NumericType>(static_cast<int>(NumericType::Sign) | static_cast<int>(NumericType::ZeroPadding)));
</code>```

But this would counter the strongly typed enum philosophy of C++11's scoped enums.

Use a plain integer if you want to store a bitwise combination of enums:

void M(int flags);

M(static_cast<int>(NumericType::Sign) | static_cast<int>(NumericType::ZeroPadding));
```

<p>But this would reduce everything to an <code>int</code>, leaving you with no clue as to which type you're supposed to put in the method.</p></li>
<li><p>Write a separate class that will overload operators and hold the bitwise flags in a hidden integer field:</p>

<pre class="lang-cpp prettyprint-override"><code>class NumericTypeFlags {
    unsigned flags_;
public:
    NumericTypeFlags () : flags_(0) {}
    NumericTypeFlags (NumericType t) : flags_(static_cast<unsigned>(t)) {}
    //...define BITWISE test/set operations
};

void M(NumericTypeFlags flags);

M(NumericType::Sign | NumericType::ZeroPadding);
</code>```

(full code by user315052)

But then you have no IntelliSense or whatever support to hint you at the possible values.

I know this is a subjective question, but: What approach should I use? What approach, if any, is the most widely recognized in C++? What approach do you use when dealing with bit fields and why?

Of course since all three approaches work, I'm looking for factual and technical reasons, generally accepted conventions, and not simply personal preference.

For example, because of my C# background I tend to go with approach 1 in C++. This has the added benefit that my development environment can hint me on the possible values, and with overloaded enum operators this is easy to write and understand, and quite clean. And the method signature shows clearly what kind of value it expects. But most people here disagree with me, probably for good reason.

答:
Typically you'd define a set of integer values that correspond to single-bit set binary numbers, then add them together. This is the way C programmers usually do it.

So you'd have (using the bitshift operator to set the values, eg 1 << 2 is the same as binary 100)

```<code>#define ENUM_1 1
#define ENUM_2 1 << 1
#define ENUM_3 1 << 2
</code>```

etc

In C++ you have more options, define a new type rather that is an int (use typedef) and similarly set values as above; or define a bitfield or a vector of bools. The last 2 are very space efficient and make a lot more sense for dealing with flags. A bitfield has the advantage of giving you type checking (and therefore intellisense).

I'd say (obviously subjective) that a C++ programmer should use a bitfield for your problem, but I tend to see the #define approach used by C programs a lot in C++ programs.

I suppose the bitfield is the closest to C#'s enum, why C# tried to overload an enum to be a bitfield type is weird - an enum should really be a "single-select" type.

Title: Using scoped enums for bit flags in C++

Body:
Typically you'd define a set of integer values that correspond to single-bit set binary numbers, then add them together. This is the way C programmers usually do it.

So you'd have (using the bitshift operator to set the values, eg 1 << 2 is the same as binary 100)

#define ENUM_1 1
#define ENUM_2 1 << 1
#define ENUM_3 1 << 2

etc

In C++ you have more options, define a new type rather that is an int (use typedef) and similarly set values as above; or define a bitfield or a vector of bools. The last 2 are very space efficient and make a lot more sense for dealing with flags. A bitfield has the advantage of giving you type checking (and therefore intellisense).

I'd say (obviously subjective) that a C++ programmer should use a bitfield for your problem, but I tend to see the #define approach used by C programs a lot in C++ programs.

I suppose the bitfield is the closest to C#'s enum, why C# tried to overload an enum to be a bitfield type is weird - an enum should really be a "single-select" type.


问:
Understanding the meaning of "multiple lifecycles application development"?
Some Agile job posts have a requirement "strong understanding of multiple lifecycles application development", what does it means ?

So my question would be: what's that field for, and what would I need to learn, knowing that I got Java EE experience and Agile more than 2 years.

Sorry if my question isn't constructed well, nor I putted some time searching the meaning :) my self, but all my research yielded job posts :D.

答:
It probably means they want you to have had experience of making several releases of an application i.e. you have know about taking things through from initial requirements to finished code for several releases.

Given that you have 2 years agile dev experience you should have this box ticked (assuming you made a few releases in those 2 years, if you didn't then you weren't really agile)


问:
How do you deal with boring repetitive tasks and activities?
When you encounter in your work some boring, repetitive (possibly not-programming) task how do you deal with it? Do you try to automate it immediately? Do you postpone automation till you encounter the task twice? Do you try to delegate it? Do you try to find something interesting in it? What do you do to make the work more joyful? Learn deeper to make it more interesting? Learn deeper immediately or when you need it regularly? </p>

答:
Like others have said: if it's common enough to be worth automating, I automate it. If not, I just slog through it.

And if it starts to feel like the whole job is just one big pile of boring, repetitive tasks, then I burn out and move on. :)


问:
Abstracting out a module or using the Module Singleton directly?
I am working on a module which is dependent on other module for some functionality. Now the dependent module provides a lot of functionality and I need only few of them, hence got the idea to create an abstraction of the same in my module which is again be a singleton only.

My question is when to abstract out and when to use the modules singleton class directly? Is there any guidelines for the same? Or its depend upon project to project?

答:
My question is when to abstract out and when to use the modules singleton class directly?

Never (yes, never) use a singleton.

There is never a scenario in computer science where having more than one thing is an error. Even operating systems or hardware aren't good candidates for singletons because of virtual machines.

The modern needs for (independent) testability and concurrency, and singletons provide more of an issue. It's not that much more work to simply pass in a possibly mock instance; just do it right.


答:
You should use dependency injection and, possibly, add a facade wrapper around your independent module.

Make your dependent module's constructor take as input an interface that accesses your dependent module:

```<code>public MyDependentModule(IPartsOfIndependentModuleIUse partOfIndependent) {
    _partOfIndependent = partOfIndependent;
}
</code>```

Wrap your independent module:

```<code>public class PartsOfIndependentModuleIUse : IPartsOfIndependentModuleIUse {
    Independent _independent = new Independent();

    public MethodOneThatIUse() {
        _independent.MethodOne();
    }
}
</code>```

The dependency injection piece will allow you to mock the object for testing easily.

Title: Abstracting out a module or using the Module Singleton directly?

Body:
I am working on a module which is dependent on other module for some functionality. Now the dependent module provides a lot of functionality and I need only few of them, hence got the idea to create an abstraction of the same in my module which is again be a singleton only.

My question is when to abstract out and when to use the modules singleton class directly? Is there any guidelines for the same? Or its depend upon project to project?

Body:
You should use dependency injection and, possibly, add a facade wrapper around your independent module.

Make your dependent module's constructor take as input an interface that accesses your dependent module:

public MyDependentModule(IPartsOfIndependentModuleIUse partOfIndependent) {
    _partOfIndependent = partOfIndependent;
}

Wrap your independent module:

public class PartsOfIndependentModuleIUse : IPartsOfIndependentModuleIUse {
    Independent _independent = new Independent();

    public MethodOneThatIUse() {
        _independent.MethodOne();
    }
}

The dependency injection piece will allow you to mock the object for testing easily.


答:
Historically, I would always have used the old (weakly-typed) enumeration to name the bit constants, and just used the storage class explicitly to store the resulting flag. Here, the onus would be on me to make sure my enumerations fit in the storage type, and to keep track of the association between the field and it's related constants.

I like the idea of strongly-typed enums, but I'm not really comfortable with the idea that variables of enumerated type may contain values that aren't among that enumeration's constants.

Eg, assuming the bitwise or has been overloaded:

```<code>enum class E1 { A=1, B=2, C=4 };
void test(E1 e) {
    switch(e) {
    case E1::A: do_a(); break;
    case E1::B: do_b(); break;
    case E1::C: do_c(); break;
    default:
        illegal_value();
    }
}
// ...
test(E1::A); // ok
test(E1::A | E1::B); // nope
</code>```

For your 3rd option, you need some boilerplate to extract the enumeration's storage type. Assuming we want to force an unsigned underlying type (we can handle signed too, with a little more code):

```<code>template <size_t Size> struct IntegralTypeLookup;
template <> struct IntegralTypeLookup<sizeof(int64_t)> { typedef uint64_t Type; };
template <> struct IntegralTypeLookup<sizeof(int32_t)> { typedef uint32_t Type; };
template <> struct IntegralTypeLookup<sizeof(int16_t)> { typedef uint16_t Type; };
template <> struct IntegralTypeLookup<sizeof(int8_t)>  { typedef uint8_t Type; };

template <typename IntegralType> struct Integral {
    typedef typename IntegralTypeLookup<sizeof(IntegralType)>::Type Type;
};

template <typename ENUM> class EnumeratedFlags {
    typedef typename Integral<ENUM>::Type RawType;
    RawType raw;
public:
    EnumeratedFlags() : raw() {}
    EnumeratedFlags(EnumeratedFlags const&) = default;

    void set(ENUM e)   { raw |=  static_cast<RawType>(e); }
    void reset(ENUM e) { raw &= ~static_cast<RawType>(e); };
    bool test(ENUM e) const { return raw & static_cast<RawType>(e); }

    RawType raw_value() const { return raw; }
};
enum class E2: uint8_t { A=1, B=2, C=4 };
typedef EnumeratedFlags<E2> E2Flag;
</code>```

This still doesn't give you IntelliSense or autocompletion, but the storage type detection is less ugly than I originally expected.

Now, I did find an alternative: you can specify the storage type for a weakly-typed enumeration. It even has the same syntax as in C#

```<code>enum E4 : int { ... };
</code>```

Because it's weakly-typed, and implicitly converts to/from int (or whatever storage type you choose), it feels less weird to have values which don't match the enumerated constants.

The downside is that this is described as "transitional" ...

NB. this variant adds its enumerated constants to both the nested and the enclosing scope, but you can work around this with a namespace:

```<code>namespace E5 {
    enum Enum : int { A, B, C };
}
E5::Enum x = E5::A; // or E5::Enum::A
</code>```

Title: Using scoped enums for bit flags in C++

Body:
An enum X : int (C#) or enum class X : int (C++11) is a type that has a hidden inner field of int that can hold any value. In addition, a number of predefined constants of X are defined on the enum. It is possible to cast the enum to its integer value and vice versa. This is all true in both C# and C++11.

In C# enums are not only used to hold individual values, but also to hold bitwise combinations of flags, as per Microsoft's recommendation. Such enums are (usually, but not necessarily) decorated with the [Flags] attribute. To make the lives of developers easier, the bitwise operators (OR, AND, etc...) are overloaded so that you can easily do something like this (C#):

void M(NumericType flags);

M(NumericType.Sign | NumericType.ZeroPadding);
```

<p>I am an experienced C# developer, but have been programming C++ only for a couple of days now, and I am not known with the C++ conventions. I intend to use a C++11 enum in the exact same way as I was used to do in C#. In C++11 the bitwise operators on scoped enums are not overloaded, so I wanted to overload them. </p>

<p>This solicited a debate, and opinions seem to vary between three options:</p>

<ol>
<li><p>A variable of the enum type is used to hold the bit field, similar to C#:</p>

<pre class="lang-cpp prettyprint-override"><code>void M(NumericType flags);

// With operator overloading:
M(NumericType::Sign | NumericType::ZeroPadding);

// Without operator overloading:
M(static_cast<NumericType>(static_cast<int>(NumericType::Sign) | static_cast<int>(NumericType::ZeroPadding)));
</code>```

But this would counter the strongly typed enum philosophy of C++11's scoped enums.

Use a plain integer if you want to store a bitwise combination of enums:

void M(int flags);

M(static_cast<int>(NumericType::Sign) | static_cast<int>(NumericType::ZeroPadding));
```

<p>But this would reduce everything to an <code>int</code>, leaving you with no clue as to which type you're supposed to put in the method.</p></li>
<li><p>Write a separate class that will overload operators and hold the bitwise flags in a hidden integer field:</p>

<pre class="lang-cpp prettyprint-override"><code>class NumericTypeFlags {
    unsigned flags_;
public:
    NumericTypeFlags () : flags_(0) {}
    NumericTypeFlags (NumericType t) : flags_(static_cast<unsigned>(t)) {}
    //...define BITWISE test/set operations
};

void M(NumericTypeFlags flags);

M(NumericType::Sign | NumericType::ZeroPadding);
</code>```

(full code by user315052)

But then you have no IntelliSense or whatever support to hint you at the possible values.

I know this is a subjective question, but: What approach should I use? What approach, if any, is the most widely recognized in C++? What approach do you use when dealing with bit fields and why?

Of course since all three approaches work, I'm looking for factual and technical reasons, generally accepted conventions, and not simply personal preference.

For example, because of my C# background I tend to go with approach 1 in C++. This has the added benefit that my development environment can hint me on the possible values, and with overloaded enum operators this is easy to write and understand, and quite clean. And the method signature shows clearly what kind of value it expects. But most people here disagree with me, probably for good reason.

Body:
Historically, I would always have used the old (weakly-typed) enumeration to name the bit constants, and just used the storage class explicitly to store the resulting flag. Here, the onus would be on me to make sure my enumerations fit in the storage type, and to keep track of the association between the field and it's related constants.

I like the idea of strongly-typed enums, but I'm not really comfortable with the idea that variables of enumerated type may contain values that aren't among that enumeration's constants.

Eg, assuming the bitwise or has been overloaded:

enum class E1 { A=1, B=2, C=4 };
void test(E1 e) {
    switch(e) {
    case E1::A: do_a(); break;
    case E1::B: do_b(); break;
    case E1::C: do_c(); break;
    default:
        illegal_value();
    }
}
// ...
test(E1::A); // ok
test(E1::A | E1::B); // nope

For your 3rd option, you need some boilerplate to extract the enumeration's storage type. Assuming we want to force an unsigned underlying type (we can handle signed too, with a little more code):

template <size_t Size> struct IntegralTypeLookup;
template <> struct IntegralTypeLookup<sizeof(int64_t)> { typedef uint64_t Type; };
template <> struct IntegralTypeLookup<sizeof(int32_t)> { typedef uint32_t Type; };
template <> struct IntegralTypeLookup<sizeof(int16_t)> { typedef uint16_t Type; };
template <> struct IntegralTypeLookup<sizeof(int8_t)>  { typedef uint8_t Type; };

template <typename IntegralType> struct Integral {
    typedef typename IntegralTypeLookup<sizeof(IntegralType)>::Type Type;
};

template <typename ENUM> class EnumeratedFlags {
    typedef typename Integral<ENUM>::Type RawType;
    RawType raw;
public:
    EnumeratedFlags() : raw() {}
    EnumeratedFlags(EnumeratedFlags const&) = default;

    void set(ENUM e)   { raw |=  static_cast<RawType>(e); }
    void reset(ENUM e) { raw &= ~static_cast<RawType>(e); };
    bool test(ENUM e) const { return raw & static_cast<RawType>(e); }

    RawType raw_value() const { return raw; }
};
enum class E2: uint8_t { A=1, B=2, C=4 };
typedef EnumeratedFlags<E2> E2Flag;

This still doesn't give you IntelliSense or autocompletion, but the storage type detection is less ugly than I originally expected.

Now, I did find an alternative: you can specify the storage type for a weakly-typed enumeration. It even has the same syntax as in C#

enum E4 : int { ... };

Because it's weakly-typed, and implicitly converts to/from int (or whatever storage type you choose), it feels less weird to have values which don't match the enumerated constants.

The downside is that this is described as "transitional" ...

NB. this variant adds its enumerated constants to both the nested and the enclosing scope, but you can work around this with a namespace:

namespace E5 {
    enum Enum : int { A, B, C };
}
E5::Enum x = E5::A; // or E5::Enum::A


问:
Who owns code if project cancelled
The problem: I am working on a freelance marketplace, and I decided to cancel project with one of my clients, because client is impossible to work with with limitless delays and lots of bugs in his backend. I want to give him a partial refund (partial because I worked for two months and there is 3k lines of code, though application still not working due to problems from his backend).

The question: who is "owner" of code which I have wrote? We did no agreement about it upon project was started. Can I tell him to not use my code? I understand, that he can ignore my forbid anyway, I just want to know if I have formal "right" to say so.

答:
This is best something you'd contact a lawyer for. It depends on your country and what's in the current contract, but I suspect the following would be relevant:

As you wrote the code, it should be yours (this is true for any written text, even if you don't explicitly mention copyright stuff, as far as I know)

Once again, certain wordings in the contract may give you or the customer different rights, and local laws will apply. I definitely recommend you contact a lawyer for a definite answer. If you can't or don't want to pay a lawyer, I'd assume the code isn't important enough. So you'll have to weigh the advantages and disadvantages.

On the other hand, think about how important it is if he does use the code. You wrote it so you know the most about it. He'll have no support, no further development (unless hiring someone else who has to work himself/herself in), etc. You on the other hand could use the code going forward.

Title: Who owns code if project cancelled


问:
I don't understand value iteration
In class I am learning about value iteration and markov decision problems, we are doing through the UC Berkley pac-man project, so I am trying to write the value iterator for it and as I understand it, value iteration is that for each iteration you are visiting every state, and then tracking to a terminal state to get its value.

I have a feeling I am not right, because when I try that in python I get a recursive depth exceed. So I return to the pseudo-code, and there is a Vk[s] and Vk-1[s'], which I had thought to mean value of state, and value of newState, but I must be missing something.

So what is the significance of the k and k-1?

My Code:

```<code> def val(i, state):
        if mdp.isTerminal(state) or i == 0:
            return 0.0
        actionCost = {}
        for action in mdp.getPossibleActions(state):
            actionCost[action] = 0
            for (nextState, probability) in mdp.getTransitionStatesAndProbs(state, action):
                reward = mdp.getReward(state, action, nextState)
                actionCost[action] += probability * reward + discount * val(i - 1, nextState)
        return actionCost[max(actionCost, key=actionCost.get)]

    for i in range(iterations):
        for state in mdp.getStates():
            self.values[state] = val(i, state)
</code>```

Pseudo Code:

```<code>k ←0
repeat
      k ←k+1
      for each state s do
          Vk[s] = maxa ∑s' P(s'|s,a) (R(s,a,s')+ γVk-1[s'])
until ∀s |Vk[s]-Vk-1[s]| < θ
</code>```

答:
Vk and Vk-1 are different iterations of the approximation of V. You could rewrite the pseudo code as:

```<code>V ← 0
V' ← 0
while true
  for each state s do
      V ← V'
      V = maxa ∑s' [ P(s'|s,a) R(s,a,s')+ γV'[s'] ]
  if ∀s |V[s]-V'[s]| < θ
      return V
</code>```

Note that the pseudo-code is not recursive. This is the idea of value-iteration/dyanmic-programming which make it efficient :

Compute the optimal value function for 0 time step: V0=0

then compute the optimal value function for 1 time step: V1=H(V0)

then compute the optimal value function for 2 time steps: V2=H(V1)

then compute the optimal value function for 3 time steps: V3=H(V2)

...

then compute the optimal value function for n time steps: Vn=H(Vn-1)

with H defined as:

```<code> H(V) = max_a ( Pa [ Ra + γ V ] )
</code>```

Your code is recursive (val calls val) which triggers some stack overflow error. Value iteration is not recursive but iterative. Your 'eval' function make this:

```<code>actionCost[action] += probability * reward + discount * val(i - 1, nextState)
</code>```

which recomputes recursively a values that you have already computed at the previous iteration (k-1). val(i - 1, nextState) is in fact:

```<code> self.previous_values[nextState]
</code>```

(assuming you keep a copy of previousValue).

Title: I don't understand value iteration

Body:
Vk and Vk-1 are different iterations of the approximation of V. You could rewrite the pseudo code as:

V ← 0
V' ← 0
while true
  for each state s do
      V ← V'
      V = maxa ∑s' [ P(s'|s,a) R(s,a,s')+ γV'[s'] ]
  if ∀s |V[s]-V'[s]| < θ
      return V

Note that the pseudo-code is not recursive. This is the idea of value-iteration/dyanmic-programming which make it efficient :

Compute the optimal value function for 0 time step: V0=0

then compute the optimal value function for 1 time step: V1=H(V0)

then compute the optimal value function for 2 time steps: V2=H(V1)

then compute the optimal value function for 3 time steps: V3=H(V2)

...

then compute the optimal value function for n time steps: Vn=H(Vn-1)

with H defined as:

 H(V) = max_a ( Pa [ Ra + γ V ] )

Your code is recursive (val calls val) which triggers some stack overflow error. Value iteration is not recursive but iterative. Your 'eval' function make this:

actionCost[action] += probability * reward + discount * val(i - 1, nextState)

which recomputes recursively a values that you have already computed at the previous iteration (k-1). val(i - 1, nextState) is in fact:

 self.previous_values[nextState]

(assuming you keep a copy of previousValue).


问:
Is this a Proper "Rule" for Identifying the "Big O" Notation of an Algorithm?
I've been learning more about Big O Notation and how to calculate it based on how an algorithm is written. I came across an interesting set of "rules" for calculating an algorithms Big O notation and I wanted to see if I'm on the right track or way off.

Big O Notation: N

```<code>function(n) {
    For(var a = 0; i <= n; i++) { // It's N because it's just a single loop
        // Do stuff
    }
}
</code>```

Big O Notation: N2

```<code>function(n, b) {
    For(var a = 0; a <= n; a++) {
        For(var c = 0; i <= b; c++) { // It's N squared because it's two nested loops
            // Do stuff
        }
    }
}
</code>```

Big O Notation: 2N

```<code>function(n, b) {
    For(var a = 0; a <= n; a++) {
        // Do stuff
    }
    For(var c = 0; i <= b; c++) { // It's 2N the loops are outside each other
        // Do stuff
    }
}
</code>```

Big O Notation: NLogN

```<code>function(n) {
    n.sort(); // The NLogN comes from the sort?
    For(var a = 0; i <= n; i++) {
        // Do stuff
    }
}
</code>```

Are my examples and the subsequent notation correct? Are there additional notations I should be aware of?

答:
Formally, big-O notation describes the degree of complexity.

To calculate big-O notation:

identify formula for algorithm complexity. Let's say, for example, two loops with another one nested inside, then another three loops not nested: 2N² + 3N

remove everything except the highest term: 2N²

remove all constants: N²

In other words two loops with another one nested inside, then another three loops not nested is O(N²)

This of course assumes that what you have in your loops are simple instructions. If you have for example sort() inside the loop, you'll have to multiply complexity of the loop by the complexity of the sort() implementation your underlying language/library is using.


答:
This would be the issue of work for hire. Typically*, if you're employed by someone and they have you make something, they own it. But you're a contractor/freelancer, so that shouldn't apply to you. Which is why most contracting work mentions something about this in the contract. If there was literally no contract and you just kinda legally eyeballed it, I believe you still own it.

I don't say this often, but in this case, yeah, you should probably go talk to a lawyer if you really want to apply any legal pressure on anyone.

Also, it doesn't matter at all if you've given him the source code in the past. Copyright doesn't work that way. Even if we all had the source-code to Windows8, it wouldn't mean anyone but Microsoft owned the rights to it.

*In most states of the USA. Offer not available in Antigua, who is specifically ignoring all US IP laws right now**.

**Update: In 2014 Antigua finally fined someone under the 2003 copyright act. Antigua and the USA are still in a tiff over online gambling, but the politics may be shifting.

Title: Who owns code if project cancelled

Body:
The problem: I am working on a freelance marketplace, and I decided to cancel project with one of my clients, because client is impossible to work with with limitless delays and lots of bugs in his backend. I want to give him a partial refund (partial because I worked for two months and there is 3k lines of code, though application still not working due to problems from his backend).

The question: who is "owner" of code which I have wrote? We did no agreement about it upon project was started. Can I tell him to not use my code? I understand, that he can ignore my forbid anyway, I just want to know if I have formal "right" to say so.


问:
In plain English, what is a database index most similar to?
Setup: Suppose you are teaching an introduction to Databases class, the students are CS students that have a working knowledge of tree structures, how they can speed up searches, and have probably implemented a few in their lifetime.

Question: How would you describe the way in which a database uses indexes to search a table for a set of keys? What structure is a database index most similar to?

Bonus: How does someone write a SQL query where clause to take advantage of the searching capability of the index they design on a given table?

Answers should correspond to all database products as a whole. I'm looking for general tips which allow faster searching on all databases. Plain english descriptions please, no code, Big O searching descriptions are fine. This question might be too specific for this site, I considered asking on StackExchange but since I'm requesting a plain english description of a broad concept I thought this site would be Ok.

答:
I mean, it's most similar to an index.  Instead of rummaging through the entire book, you look it up in the index and find the page it's on.

The magic works because the index is organized in an easier-to-search way than the book, i.e. alphabetically.


答:
Take a book, any technical book.

Go to the end - where there is an... Index.

Why is it there? Same reason for the DB. So you don't have to search through a whole book for a specific entry.

Think about a dictionary. It is an index of words, sorted alphabetically.

Title: In plain English, what is a database index most similar to?

Body:
Setup: Suppose you are teaching an introduction to Databases class, the students are CS students that have a working knowledge of tree structures, how they can speed up searches, and have probably implemented a few in their lifetime.

Question: How would you describe the way in which a database uses indexes to search a table for a set of keys? What structure is a database index most similar to?

Bonus: How does someone write a SQL query where clause to take advantage of the searching capability of the index they design on a given table?

Answers should correspond to all database products as a whole. I'm looking for general tips which allow faster searching on all databases. Plain english descriptions please, no code, Big O searching descriptions are fine. This question might be too specific for this site, I considered asking on StackExchange but since I'm requesting a plain english description of a broad concept I thought this site would be Ok.


答:
Database indexes are modeled after textbook indexes, then made more efficient:

The non-indented parts are the primary part you're searching on, and the indented part underneath some of them further identifies specific topics.  Each indentation level is similar to another column on the index.

Taking advantage of indexes is (I think) partially implementation-specific.  For example:

If you query column food for "chicken", the index will be utilized.

For "chick%", I would say it depends on the database/type of index, although all the ones I know of will still use it.

Similar rules apply for querying columns food and drink for "chicken" and "water":  First it limits results based on the first column in the index, then the second - just as if you used the outer index, then the indented index, in a textbook.

Likewise for "chik%" and "wat%"

However, "%ken" cannot be searched in an index in the databases I know of, because they index from the front of the word, not the back - same as textbook indexes.  So the database will have to scan the whole table.


答:
From Use the Index Luke:

A database index is, after all, very much like the index at the end of a book: it occupies its own space, it is highly redundant, and it refers to the actual information stored in a different place.


问:
Identifying Users
We have a site that allows users to generate their own content.  If users generate illegal content, we'll be submitting a report to the authorities. In the event that we do have to report a user, we want as much info as possible on that user. With that said, I have two questions:

Is tracking the user's ip address enough to identify them?

And, we track the user's ip address in the sessions table which gets wiped clean periodically.  Should we archive the sessions data to retain that info or should we put an ip_address field in the our Post and Comments tables instead?

答:
An IP address identifies devices (at a certain point of time), not people. The use of proxies lets many devices appear under the same IP address.

The only way to identify users is to let them create an account and log in in order to generate content. And not even this guarantees that the user using the account is the user owning the account.

Title: Identifying Users


答: It doesn't have to be a b-tree, but many databases do use b-trees to implement their databases.  Anything you want to know about how an index works, and what its performance characteristics are, you can find out by studying b-trees.</p>


答:
Assuming that the audience really has "a working knowledge of tree structures, how they can speed up searches" (and thus "plain English" is really not what they need):

A DB index is a B-Tree using the values of one or more columns (tuples in the case of multiple columns) as keys and references to the corresponding records as values.

A B-Tree is a search tree with a very high branching degree that is optimized for data locality and thus still performs well when it's too large to be kept in RAM (and random access becomes extremely expensive).

From this, it should be clear that an index can only help speed up a query when the WHERE clause involves the columns of the index either in an equality condition, a greater/smaller condition or by specicfying a prefix (which uses the columns in the sam order they appear in the index, for multicolumn indexes) - because those are the operations supported by a search tree.


问:
What does Microsoft Public License (Ms-PL) clause 3 section (A) actually limit?
I've been looking at the Ms-PL license that ASP.NET MVC and DotNetOpenAuth are published under and 3A says this:

```<code>3 Conditions and Limitations

(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.
</code>```

Does this mean that I cannot name my project ASP.NET MVC DotNetOpenAuth Sample Project and publish it if I use these two technologies or does it just mean that I cannot use the author's name to promote this project?

答: The author's name (assuming a real person) is most likely not trademarked, so I don't think the clause says anything about that; what it says that the license does not give you any rights to use trademarks like "Microsoft", "Windows", "ASP.NET" etc</p>


问:
How much business logic should the database implement?
I've worked in some projects where most of the business logic was implemented on the database (mostly through stored procedures). On the other side, I've heard from some fellow programmers that this is a bad practice ("Databases are there to store data. Applications are there to do the rest").

Which of these approaches is the generally better?

The pros of implementing business logic in the DB I can think of are:

Centralization of business logic;

Independency of application type, programming language, OS, etc;

Databases are less prone to technology migration or big refactorings (AFAIK);

No rework on application technology migration (e.g.: .NET to Java, Perl to Python, etc).

The cons:

SQL is less productive and more complex for business logic programming, due to the lack of libraries and language constructs the most application-oriented languages offer;

More difficult (if possible at all) code reuse through libraries;

Less productive IDEs.

Note: The databases I'm talking about are relational, popular databases like SQL Server, Oracle, MySql etc.

Thanks!

答:
There's a middle ground that you need to find.  I've seen scary projects where the programmers use the database as nothing more than an overpriced key/value store.  I've seen others where the programmers fail to use foreign keys & indices.  On the other end of the spectrum, I've seen projects where most if not all of the business logic is implemented in database code.

As you've noted, T-SQL (or its equivalent in other popular RDBMSs) is not exactly the best place to be coding complex business logic.

I try to build a reasonably decent data model, use features of the database to protect my assumptions about that model (i.e., FKs and constraints), and use database code sparingly.  The database code is useful when you need something (i.e., a sum) that the database is very good at doing and can spare you from moving a zillion records over the wire when you don't need them.


答:
I have worked in 2 different companies that had different vision on the subject.

My personal suggestion would be to use Stored Procedures when execution time is important (performance). Since Stored Procedure are compiled, if you have a complex logic to query the data, it's better to keep that on the database itself. Also, it will only send the final data to your program at the end.

Otherwise, I think the logic of a program should always be in the software itself. Why? Because a program needs to be testable and I don't think there is an easy way to unit test stored procedure. Don't forget, a program that is not tested is a bad program.

So use Stored Procedure with caution, when it's needed.

Title: How much business logic should the database implement?

Body:
I've worked in some projects where most of the business logic was implemented on the database (mostly through stored procedures). On the other side, I've heard from some fellow programmers that this is a bad practice ("Databases are there to store data. Applications are there to do the rest").

Which of these approaches is the generally better?

The pros of implementing business logic in the DB I can think of are:

Centralization of business logic;

Independency of application type, programming language, OS, etc;

Databases are less prone to technology migration or big refactorings (AFAIK);

No rework on application technology migration (e.g.: .NET to Java, Perl to Python, etc).

The cons:

SQL is less productive and more complex for business logic programming, due to the lack of libraries and language constructs the most application-oriented languages offer;

More difficult (if possible at all) code reuse through libraries;

Less productive IDEs.

Note: The databases I'm talking about are relational, popular databases like SQL Server, Oracle, MySql etc.

Thanks!


问:
Web application (Spring, JSF) forks, how to reuse existing code for subprojects?
my question is going to be somewhat philosophical and "architectural oriented" so bear with me.

Right now we have existing Java web application built on top of Spring and JSF(facelets) with maven. These are basically our tools that limit our scope of possible solutions.

Now to the point. We need to implement a fork of this application that will be running on different domain for different "end consumers" and implement some change requests for both versions, but code base of these versions will probably always be ~90% same. Same change requests can be defined for implementation in both versions simultaneously BUT separate change requests only for chosen version might come as well. We have no control over what change requests there might come in later in project (but we are expecting quite a few). The differences in functionality may occur both on bean and view part of the application.

We don't want to create 2 completely separate projects as implementing changes might sometimes mean implementing them twice. THE BIG ISSUE is that we expect to have even more forks in the future so the effort might multiply even further.

The question is what ways of control or architectural patterns can we introduce to promote better maintainability of our projects. One solution might be for example:

using Spring profiles to inject proper components based on current fork of application and completely separating view (xhtml) implementation.

In summary we are looking for best way to implement application wide changes that can be isolated and activated only based on some context variable (how to propagate it everywhere?).

Any input, idea or new perspective is appreciated.

答:
You need to look into multi-tenant techniques, including

partitioning your db to allow multiple clients, or db-per-client

compositing your app, using switchable components

OwnerDisplayName: Jan Mathauser


答:
If your business logic involves set operations, most likely a good place for it is in the database because database systems are really good at performing set operations.

http://en.wikipedia.org/wiki/Set_operations_(SQL)

If the business logic involves some sort of calculation it probably belongs outside of the database/store procedure since databases are not really designed for looping and calculating.

Although these are not hard and fast rules, its a good starting point.


问:
Is it OK to have a team with same abilities but different skill levels?
I believe that in an ideal team, members should have different but complementary abilities. But is that true about software development teams?

As an example we are a small team of 5. We almost have the same abilities and interests but with different levels of skills. Regarding such situation I think we don't cover our teammates' weaknesses.

Is there any pattern to follow to manage and improve such team?

Should I setup a team with different abilities and interests to maximize the performance and productivity?

-- EDIT --

Our current team has a specific lifetime. We work together in a per-project manner. In another word we may change the team arrangement for each project depending on the project and developers situation. Actually we've provided a sort of floating situation.

In short, we are a network of developers rather than a fixed-size development team.

答:
But is that true about software development teams?

Every software development team will have different levels of skills and complementary abilities.  This is a reflection of the exposure to technology, the depth of knowledge, the level of interest, etc.

I think we don't cover our teammates' weaknesses.

Then cover them.  Training?  Activities? Address the weaknesses to enable a strong development team with greater cohesion.

Is there any pattern to follow to manage and improve such team?

There are a plethora of team management resources but perhaps what you want to do is address a specific area of technical expertise and the best way to do that is have your team do it.  If members of your team must get up to speed, then create ways in which that can be done without stifling the team.

Should I setup a team with different abilities and interests to maximize the performance and productivity?

I think that does maximize performance and productivity.  creativity and other factors that cause a team to be successful comprises diversity and brings results.


答:
I would never encourage taking on a lesser quality developer because this will some how provide better balance for the team. Ideally, you want the best person to perform every task, but that becomes impossible with large projects and short development time goals. If all the team members are top-level programmers, it doesn't matter who does what. Anyone should be able to research and learn any skills that the team lacks (Sort of a trait of good programmers.).

In the real world, it is difficult to find and compensate an entire team of top-level programmers, so you find ones that are good enough. Initially they are given tasks they can handle which may help motivate the top performers since they can take on newer and tougher tasks. Hopefully the mentorship provided to the entry -level developers will allow them to improve their skill set.

It will become more difficult to maintain this team. People get bored and there is not always enough compensation to go around. A top level team should be able to provide the software to generate enough revenue, but management, market trends, and other unavoidable factors can prevent this.

To keep entry-level developers motivated, they can be encouraged to learn one of the skills the team lacks if it is not too critical.

There are many ways to make teams with different abilities and skill sets function.

Title: Is it OK to have a team with same abilities but different skill levels?

Body:
I believe that in an ideal team, members should have different but complementary abilities. But is that true about software development teams?

As an example we are a small team of 5. We almost have the same abilities and interests but with different levels of skills. Regarding such situation I think we don't cover our teammates' weaknesses.

Is there any pattern to follow to manage and improve such team?

Should I setup a team with different abilities and interests to maximize the performance and productivity?

-- EDIT --

Our current team has a specific lifetime. We work together in a per-project manner. In another word we may change the team arrangement for each project depending on the project and developers situation. Actually we've provided a sort of floating situation.

In short, we are a network of developers rather than a fixed-size development team.


答:
Business logic doesn't go into the database

If we're talking about multi-tier applications, it seems pretty clear that business logic, the kind of intelligence that runs a particular enterprise, belongs in the Business Logic Layer, not in the Data Access Layer.

Databases do a few things really well:

They store and retrieve data

They establish and enforce relationships between different data entities

They provide the means to query the data for answers

They provide performance optimizations.

They provide access control

Now, of course, you can codify all sorts of things in a database that pertain to your business concerns, things like tax rates, discounts, operation codes, categories and so forth.  But the business action that is taken on that data is not generally coded into the database, for all sorts of reasons already mentioned by others, although an action can be chosen in the database and executed elsewhere.

And of course, there may be things that are performed in a database for performance and other reasons:

Closing out an accounting period

Number crunching

Nightly batch processes

Fail-over

Naturally, nothing is engraved in stone.  Stored Procedures are suitable for a wide array of tasks simply because they live on the database server and have certain strengths and advantages.

Stored Procedures Everywhere?

There's a certain allure to coding all of your data storage, management and retrieval tasks in stored procedures, and simply consuming the resulting data services.  You certainly would benefit from the maximum possible performance and security optimizations that the database server could provide, and that's no small thing.

But what do you risk?

Vendor lock-in

The need for developers with special skill sets

Spartan programming tools, overall

Extremely tight software coupling

No separation of concerns

And of course, if you need a web service (which is probably where this is all heading, anyway), you're still going to have to build that.

So what is typical practice?

I would say that a typical, modern approach is to use an Object-Relational Mapper (such as Entity Framework) to create classes that model your tables.  You can then speak to your database through a repository that returns collections of objects, a situation that is very familiar to any competent software developer.  The ORM dynamically generates SQL corresponding to your data model and the information requested, which the database server then processes to return query results.

How well does this work?  Very well, and much more rapidly than writing stored procedures and views.  This generally covers about 80% of your data access requirements, mostly CRUD.  What covers the other 20%?  You guessed it: stored procedures, which all of the major ORMs support directly.

Can you write a code generator that does the same thing as an ORM, but with stored procedures?  Sure you can.  But ORMs are generally vendor-independent, well-understood by everyone, and better supported.


答:
It works fine as long as those weak points never come op. If no-one in the team knows how to speak swahili, but it's never called for, so what? Or handling big data. Or producing hardware when you're a software company.

If there's something that is likely to come up, there's a chance someone on the team can become an expert in it. Go grab the rosetta stone and give it a few months. Other topics are simply too deep. Switching from crunching Java to IC board fabrication is a REALLY big jump. Something you could learn, but you'd probably want to start with college courses.

I don't think firing everyone and starting from scratch sounds like a good idea. It depends on the business model. If there's a skillset you're missing on the team, and it's needed, go fill that skillset. Even how you fill it depends on the problem. You could tell someone to go do it and leave them for a month, or send them off for training, or have the whole team tackle it together, or hire a guy.