答:
one suggestion regarding how tedious it is using grep to search for code: set up bash aliases in your .bashrc file. So then its just a single command:

```<code>alias searchCode='find -iname \*.cpp | xargs grep $1'
alias searchCodeHeaders='find -iname \*.h | xargs grep $1'
</code>```

there's probably better ways to write the command, but the idea is the same. Wanna search code ? write an alias called searchCode. Remember that although they're tedious and complicated, unix tools can also be used to make your life easier.

Body:
one suggestion regarding how tedious it is using grep to search for code: set up bash aliases in your .bashrc file. So then its just a single command:

alias searchCode='find -iname \*.cpp | xargs grep $1'
alias searchCodeHeaders='find -iname \*.h | xargs grep $1'

there's probably better ways to write the command, but the idea is the same. Wanna search code ? write an alias called searchCode. Remember that although they're tedious and complicated, unix tools can also be used to make your life easier.


问:
How can I  define and measure simplicity in code?
There are many answers in my previous question about simplicity relating to readability that helped me see my definition and understanding of simplicity in code was, quite possibly, incorrect.

How can I define simplicity in code? What software measurements and metrics are available to measure code simplicity?

答:
Instead of looking at a formal mode of defining simplicity, i would rather like to define simplicity as an attribute of quality of code writing.

I am not putting some measure of simplicity but when do you call something simple or not.

1. Code Traversal:

How easy it is to navigate through the code? Is it easy to spot where the API functions are written? Is it easy to understand call flows, for example which methods are calling others (and why)- are there good state machines implemented or cleanly identified algorithms?

When the code traversal is easy, the code is simple to follow.

2. Naming

While other codding standards help make code look cleaner - the most important thing is the naming of classes/object-instances/Variables/methods. The use clear and unambiguous names is clearly has a great impact on the Simplicity of the code. When it is difficult to identify a simple name, it is a sign that you might want to re-think the idea being that variable/method.

3. Interpretation and references

Does each of your method has a clear role to play. Does each variables/attributes are easy to determine the role they are playing?
When a piece of code does something which has implies assumptions or affects unrelated set of variables, can become a maintenance nightmare.

4. Dependency or coupling

This is difficult to judge just by looking at the code, but becomes very evident if someone tries to fix your bugs. When some other things change in some other object, does the operation here changes? Are those changes obvious? Do you require to change the API so often to accommodate stuff. These suggest that intermodule relationships is not simple

5. Inputs User or Applications

Finally how simple are the user inputs or application are accepted on the API/UI? When multiple possible Users/Applications (for different purposes) needs to give you - are they obvious? Are there states/details that are not related to the higher abstraction but still goes back-n-forth the interface?

A simple question i would generally ask is as follow: If instead of a program, if i would have asked the same function to be performed by a human, would i have filled this information on a paper form? If not, i am not simple enough here.

I won't say this list is exhaustive, but i but i guess criteria is how easy or difficult it is to use and modify the software. That is simple.

ContentLicense: CC BY-SA 3.0


问:
Should you really keep your js, html and css separate?
I hear/read all the time that it is cleaner to keep your js, html and css separated. Supposedly it makes it more easy to maintain, debug. Supposedly it is more efficient, because it allows caching/minifying css and js files.

As far as I am concerned, using web frameworks (Django, Rails, ...), javascript templating libraries, ... I tend to split quite a lot a single html page into multiple reusable templates - some kind of widgets if you wish. For example I can have a news feed widget, a select multiple widget, etc ... each of them having a consistent layout throughout the different pages, and each being controlled by its piece of javascript.

With this organization - which seems to me as clean as it can get, maximizing reusability - I have trouble to understand why it would be simpler to keep all js and css in separate files. I kind of think it would be so much simpler for example :

in the select multiple widget file

html

basic css layout

control of direct interactions and UX enhancements with a bit of JS.

I think that way it is more reusable, much more maintainable, because you don't have to scroll through a fat js file, then switch to and scroll through a fat css file, switch again to your html file ... back and forth.

So I'd love to know how you guys organize your code, if you stick to the separation that is usually recommended.

Are there really good reasons to do so ?

isn't it that the guides on the web usually assume that you won't use any fancy tool (in which case I'd love to get more up-to-date online readings for best practices) ?

Is it just a matter of preference ?

答: generally the convention is to have separate files for JS/CSS/HTML to maintain a separation of content, presentation and behavior. However, if speed becomes an issue then anything goes. </p>


问:
Programming standards and principles to become better programmer
I am a c# developer.

I have always been interested in increasing my skills and knowledge and trying to pickup new technology.

However now I want to enhance my knowledge in Programming standards and principles. So for example I want to know about how to structure code, refactor code, coding standards and good practices etc...

Does anyone have any recommendation on any books or website links?

答: For C# development, in particular, I'd strongly recommend reading Framework Design Guidelines and the C# Programming Language.  Both are very useful in providing a good, solid understanding about why the .NET framework and the C# language has its current design.  They also both (though the guidelines more so) have quite a few tips on standards and principles specific to C# and .NET.</p>


答:
Clean Code can definitely help

But it seems we need longer answers:

If you are looking for a good book that can help you in your endeavour, I think Clean Code can definitely help. It's written by Robert C. "Uncle Bob" Martin, whose biography is available here:  biography

To avoid further scripts from picking this post, I thought it would be interesting to point out that this author is also the author of the well known principle: SOLID.

Good read!

Title: Programming standards and principles to become better programmer

Body:
I am a c# developer.

I have always been interested in increasing my skills and knowledge and trying to pickup new technology.

However now I want to enhance my knowledge in Programming standards and principles. So for example I want to know about how to structure code, refactor code, coding standards and good practices etc...

Does anyone have any recommendation on any books or website links?


答:
If you want to improve your general knowledge and principles, look at this question on SO. Note that Code Complete as mentioned by Leons is there as first book. Also Pragmatic Programmers and many, many more very important books. Focus on 3 areas:

software development in general (process, coding, ...)

object orientation (sounds easy but is not)

your language and frameworks of your language.


答:
I maintain this structure

For each page or control, I give it a folder for it's html page (or aspx, or php, etc).  In that folder is also folders for js, xml, images and css files.  Those are for page/control specific, not shared resources.

In the site root, are also js, xml, images and css folders, each of which contains site wide resources.

The site wide js and css files are rolled up server side and returned as a single js file.  The page specific ones, as there is usually only one per page, are left alone.

This organizes my resources as to their scope.  And while I may have a dozen js files in the root js folder, they will be returned as one js resource by combining and minifying them server side (and caching the result).

I also am not loading resources specific to pagex when I'm on pagey.  The only "waste" might be in the site wide resource file, but since it's cached, and many of the resources WILL be used in multiple places, it's more efficient.

Title: Should you really keep your js, html and css separate?

Body:
I hear/read all the time that it is cleaner to keep your js, html and css separated. Supposedly it makes it more easy to maintain, debug. Supposedly it is more efficient, because it allows caching/minifying css and js files.

As far as I am concerned, using web frameworks (Django, Rails, ...), javascript templating libraries, ... I tend to split quite a lot a single html page into multiple reusable templates - some kind of widgets if you wish. For example I can have a news feed widget, a select multiple widget, etc ... each of them having a consistent layout throughout the different pages, and each being controlled by its piece of javascript.

With this organization - which seems to me as clean as it can get, maximizing reusability - I have trouble to understand why it would be simpler to keep all js and css in separate files. I kind of think it would be so much simpler for example :

in the select multiple widget file

html

basic css layout

control of direct interactions and UX enhancements with a bit of JS.

I think that way it is more reusable, much more maintainable, because you don't have to scroll through a fat js file, then switch to and scroll through a fat css file, switch again to your html file ... back and forth.

So I'd love to know how you guys organize your code, if you stick to the separation that is usually recommended.

Are there really good reasons to do so ?

isn't it that the guides on the web usually assume that you won't use any fancy tool (in which case I'd love to get more up-to-date online readings for best practices) ?

Is it just a matter of preference ?


问:
Database design good practices
I recently joined a new position as SW developer and during the interview process everyone stressed the importance and the pride of the quality standards of the firm in each and every process they have. (This was one of the aspects that made me decide to accept the offer)

When I started inspecting the database I realised that it was far from being perfect, far from being good and far from being not bad. Also I realised that all my team mates do think that the database is complex because the business is complex.

What is wrong with this database then?

inconsistent naming

de normalised table (with conflicting data)

plenty of stored procedures and tvf with if/switch/case based on values in the tables themselves

tvf that depend on tvf that depend on tvf making the code unreadeable and unmaintainable

no FK constraints and in some cases PKs

no distinction between data abstraction and business logic (too many encapsulated TVFs)

I decided to bring the matter up during my next review because I believe my manager (non technical) does not have a clue of what is going on.

I need help to come with a list of aspects to consider to asses the quality of a database design and then assess the score of our database against this list. This will help at least my manager to take steps in the right direction (I hope).

Which points should I consider to asses whether a database is well designed?

Well designed means:

does it job

it does not break (or do so in a sensible manner)

it follows a structure that make it easy to maintain and expand

答:
if the database meets their business needs and you have developers that can modify it as needed to meet changing needs then its already as good as I would push for as the new guy. If you can identify a few areas that could use improvement (not an exhaustive list) and share them with coworkers and try to get them to bring it up with managers, or at least let them know you intend to mention these things.

database changes are huge and probably the best place to have a "if it aint broke don't fix it" mentality.

Title: Database design good practices


答:
I think it comes down to what you mean when you say quality.  For instance, when an engineer says Quality, they mean "does what it's supposed to do, lasts a long time, and fails in a responsible manner."

Software developers seem to think more along the lines of "is easy to understand and change".  Engineers tend towards the "big design up-front" and don't have the mind-set of making it easy to change later.

Your co-workers are talking about quality in the eyes of the end-user.  They take pride in the fact that the users feel the system is rock-solid, well supported, easy to use, etc.  If the user never looks at the database tables, then table naming doesn't really factor into that measure of quality.

Title: Database design good practices

Body:
I recently joined a new position as SW developer and during the interview process everyone stressed the importance and the pride of the quality standards of the firm in each and every process they have. (This was one of the aspects that made me decide to accept the offer)

When I started inspecting the database I realised that it was far from being perfect, far from being good and far from being not bad. Also I realised that all my team mates do think that the database is complex because the business is complex.

What is wrong with this database then?

inconsistent naming

de normalised table (with conflicting data)

plenty of stored procedures and tvf with if/switch/case based on values in the tables themselves

tvf that depend on tvf that depend on tvf making the code unreadeable and unmaintainable

no FK constraints and in some cases PKs

no distinction between data abstraction and business logic (too many encapsulated TVFs)

I decided to bring the matter up during my next review because I believe my manager (non technical) does not have a clue of what is going on.

I need help to come with a list of aspects to consider to asses the quality of a database design and then assess the score of our database against this list. This will help at least my manager to take steps in the right direction (I hope).

Which points should I consider to asses whether a database is well designed?

Well designed means:

does it job

it does not break (or do so in a sensible manner)

it follows a structure that make it easy to maintain and expand


答:
Let's start with hte lack of FKs/PKs. Do some queries to see if you can find orphaned data or duplicated data. Once you can show how bad the integrity of the data is, you are in a better position to propose a clean up plan and the insitution of FKS.  If you can't find any orpahned records (given what you said, I'd find this highly unlikely), this may not be the best place to start.

Next start with the worst performing queries which I would be surprised to find are based on things like the TVF that call other TVFs or views that call other views.

Now take one and design the data the way you would like to see it stored and show how much easier it is to query and how much faster the query is. Once you have a track record for improvements that work, people will be more likely to listen to you.

Start withe worst things  from a performance, security and data integrity standpoint.

A good book to read is:
http://www.amazon.com/Refactoring-Databases-Evolutionary-Database-Design/dp/0321293533/ref=sr_1_1?ie=UTF8&s=books&qid=1268158669&sr=8-1

It will help you design a system to improve the mess one bit a time.

Title: Database design good practices


答:
in the select multiple widget file

html

basic css layout

control of direct interactions and UX enhancements with a bit of JS.

I have a organization tool (trinity) which promotes you do that.

Except that widget file is split into 3 small files, HTML, CSS and JS. This means you have your seperate files but they are still linked.

This avoids the problem of fat files but still gives you seperate files.

So simply put seperations of concerns does not mean you should have one big HTML/CSS/JS file. You should have multiple triplets of  for all your re-usable encapsulated code

Now there's nothing wrong in having all of these in one file as long as they are clearly seperated.

So a widget that looks like

```<code><div id="wrapper">
  <style scoped> CSS code </style>
  <script> JS code </script>
  HTML code
</div>
</code>```

Is fine, and great. Except having everything in one files makes it far too easy for a maintainer to start mixing and matching the CSS/JS/HTML.

It makes it far too easy for it turn into spaghetti over time.

The main reason people promote seperate files is two fold

seperate downloads. As soon as you copy and paste any css/js code into multiple "widgets" you need to factor it into it's own file.

Aggressively prevends spaghetti code by not relying on the author to keep their css/js/html nicely seperated in a single file

Body:
in the select multiple widget file

html

basic css layout

control of direct interactions and UX enhancements with a bit of JS.

I have a organization tool (trinity) which promotes you do that.

Except that widget file is split into 3 small files, HTML, CSS and JS. This means you have your seperate files but they are still linked.

This avoids the problem of fat files but still gives you seperate files.

So simply put seperations of concerns does not mean you should have one big HTML/CSS/JS file. You should have multiple triplets of <HTML, CSS, JS> for all your re-usable encapsulated code

Now there's nothing wrong in having all of these in one file as long as they are clearly seperated.

So a widget that looks like

<div id="wrapper">
  <style scoped> CSS code </style>
  <script> JS code </script>
  HTML code
</div>

Is fine, and great. Except having everything in one files makes it far too easy for a maintainer to start mixing and matching the CSS/JS/HTML.

It makes it far too easy for it turn into spaghetti over time.

The main reason people promote seperate files is two fold

seperate downloads. As soon as you copy and paste any css/js code into multiple "widgets" you need to factor it into it's own file.

Aggressively prevends spaghetti code by not relying on the author to keep their css/js/html nicely seperated in a single file


答:
There are valid reasons for putting business logic in a database, so you better wait until you have more information. There may be some reporting tools being used that cannot utilize complex logic or it needs to be shared by apps outside their control.

What problems are being caused by the lack of normalization and foreign key utilization?

All of this eventually gets weighed against having to refactor this database. Have you ever had to refactor a large and complex database? Maybe those names aren't so bad afterall.

Title: Database design good practices


问:
How to tackle massive Linux/makefile projects effectively?
I have been developing Windows applications in C++ for like 10 years now. And recently I've started digging into some Linux projects, and I can't stand how unproductive I am...

I'm a fast learner, and I've been using Linux as a primary platform for some time now. And I do feel very comfortable with shell, OS principles and GUI. But when it comes to development, it feels like I'm back to school.

As soon as I open some larger project, I'm stuck. Most of them are makefile based, so basically when I try to navigate them with QT or CodeBlocks, at best, I can use intellisense on a per-file basis. And most of the time variables leak from scope.

Then there is a go-to-definition stuff, which seems nonexistent, try to join some larger project from sourceforge, and you're stuck for days, because navigating to definitions is so hard... grep -r "this_def" . --include "*.cpp" --include "*.h" seems so slow and clumsy.

And then, the debugging, gdb does work, but no matter what I do, it seems like it's light years behind WinDbg or VisualStudio debugger.

And these things are making me desperate, I want to write code, but it just goes so slow... I'm starting to think that Linux developers learn function definitions by heart and analyze code by eyes, but I can't believe it's so.

Has anyone gone through this? Is there something that I'm missing that could make me more productive?

答:
My 2c as someone who has developed C++ on both platforms and likes them both.

1) Makefiles are painful - the best advice I can give you is to try switching to another build system, if possible.

2) For code editing and browsing, there are some quite useful tools. Sure, they are not integrated, but it doesn't really matter when it comes to getting things done. vim+ctags+grep will just get you there. Of course, there are IDEs as well, but frankly I didn't like anything I tried: Eclipse+CDT, KDevelop, Code::Block. You may come to different conclusion, though.

3) For debugging, just stick to command-line gdb. Sure, it is quite behind Windbg when it comes to features, but for most purposes it is just fine. Graphical front-ends (ddd, KDbg) were pretty buggy the last time I tried them, but again things may have changed :)

The bottom line is - yes you need to put some learning effort, but after that you'll be just as productive as you are on Windows.


答:
Is there any improvement you could implement (and thoroughly test) that would show immediate value to the company or the customer, while also correcting at least one of the quality problems you are seeing?  If so, propose that change--or better yet, volunteer to demonstrate the effectiveness of the change in a test environment.

Also, if you have the background and the skills to serve as either a data modeler or a DBA, and you have interests in that vein, you might talk to your manager about the necessity of the role and your interest in performing it.

Title: Database design good practices


问:
Is there a term used when internal variables are declared public and accessible?
If someone writes code so that an internal variable $_fields is accessible without using getter/setter methods, is there a proper term used to describe that?

Something polite enough to use with management :)

答: I would call such variables public member variables.


问:
Why don't more companies hire remotely?
I keep hearing about the desperate recruiting efforts of companies in tech hubs such as SF and NYC. However, every time I'm contacted by a startup I'm told the position is on-site and working remotely isn't possible.

Let me clarify that these are tech startups. They should be very comfortable with the idea of using technology to get things done and connect teams together.

With the housing market the way it is, many of us can't relocate even if we wanted to pay the higher cost of living. Why are so many companies still stuck in the industrial mindset of butts in seats?

答:
I've been working on distributed teams for the past 6 years.  While previous projects have struggled to integrate remote team members, my current project has hit a sweet spot, and has had great success by following the following principles...

For voice communication:

A high quality (Skype) audio call and text chat, is left open with the whole team connected all day.  At times nothing is being said, but this facilitates the "over-the-cube", watercooler, random gathering, etc. discussions that frequently occur in a physical office.

Avoid speakerphones, cell phones, etc whenever possible.  The limited bandwidth and call quality is a distraction and makes communication more difficult.

Any time the team needs to call someone without Skype, the entire call is joined to that person's phone

One-on-one or sidebar discussions take place on separate Skype calls, as needed.

For collaboration:

The Kanban board in an electronic project management tool, which replaces sticky notes on the wall

Rapid wireframing tools replace whiteboards

Remote desktop sharing tools are used for things like pairing, sharing, and mutual troubleshooting

Wikis are used for documentation

Daily meetings, reviews, planning meetings are all conducted via remote desktop sharing software.

By doing the above, our experience has been that there is little to no negative impact to the entire team being remote.  In fact we've seen productivity gains where team members have the best of both worlds, with the ability to hit the mute button to have "quiet hours" a few minutes to focus on a problem (while still keeping track of the text chat), and then join back to the group audio when finished.  You get rapid voice communication like in the office when needed, but you can also have a few quiet moments to focus when you need to.

Title: Why don't more companies hire remotely?


问:
Is Google App Engine's level of support robust enough for real-world production?
Google App Engine has been great for trying out ideas and learning stuff, but so far I haven't seen much confidence in the community in using it for production applications.

One significant issue that has come up over and over again is that when things go wrong, it's nearly impossible to actually talk to anyone at Google. This is really scary if your company is depending on this service for the production app.

However, their literature on Premier accounts looks promising, with the promise of better levels of support.

What has been your experience with using Google App Engine when it comes down to resolving support issues? Does it really take 4 hours to just acknowledge a P1?

答:
When it comes to real-world production, I don't think it's a matter of support in this case.

I think what's keeping off most people is the tight coupling with appengine API and datastore architecture. You have no hands on it, and are at the mercy of Google will, if they change anything, you'll probably need to rewrite things.

Whereas the competition is more SOA's friendly, you do everything yourself.

GAE provide so many thing out of the box that it's perfect for a lonely dev, but I don't think it fits a company needs and future-proofing that well.

If you want a recent example, just look at the amount of dissatisfaction from the way Google handled the appengine end of preview.


问:
Event subscription from nested classes
Is it OK to have a nested class raise an event and for the parent class that subscribes to that event subsequently raise another event, which it's parent class has subscribed to - thus passing the original event up the class hierarchy?

It may be easy to explain like this...

We have...

```<code>Class A
Class B
Class C
</code>```

Operation...

Class C raises an event

Class B subscribes to that event, on notification it raises another event

Class A subscribes to Class B event, on notification it does something

So the original event occurred in Class C and Class A is dealing with it.

Using this method means I require event handlers in the middle class (Class B) whose only function is to pass along the notification - this seems a little smelly to me.

答: First: I agree it's OK. But if you find yourself doing it a lot you may want to use an event bus instead. </p>

Title: Event subscription from nested classes


问:
Why is Zend Framework so complicated?
I am web developer and have experience of developing several web applications in PHP. I have an idea of developing a product for myself and decided to use a MVC based framework because I really like the idea of MVC and how one can easily manage and modify the application without any difficulty.

I chose Zend Framework and it seems more difficult than learning a new programming language. There are so many things going at one time even to run a small application.

Similarly the idea of routing is very complex as it is new for a core programmer. I know that the guys here read thousand of such questions like one I am asking but I am not looking to learn Zend Framework overnight. I am willing to give as much time as it needs but until now it's making no sense to me. There are thousand of classes in the Zend library, but how would a noob know where to use a specfic class and how to use it? I am still finding it very difficult to understand the bootstrap of Zend Framework and its mapping. I read the manual, follow it and things start working but I really don't exactly how they are actually happening.

I also still have no clue how models, views and controllers work together and how to plan an application in Zend Framework. When it comes to core php I exactly have the idea in my mind what to do and than easily translate them in code but in Zend Framework I don't know how to translate my idea.

答:
Zend Framework is like a bunch of independent libraries which together works like a framework. It is very hard to develop something at the same time decoupled and "easy to use". For "easy to use" I mean doing complex things with few lines of code.

So, starting with Zend is harder then other frameworks, like CakePHP. But I it also easier extends and customize your application with no dirty codes. Zend also follows standards and design patterns all over its code, so once you read the framework code, you can guess what's going on.

When you say you have no clue about how models, views and controllers work together, please, don't blame the framework. It implements MVC like any other framework, except it separates the Model from the Database structure, which in a lot of frameworks are implemented in the same class. So you gonna face a lot of classes like Zend_Db_Table, Zend_Db_Table_Row, Zend_Db_Table_Rowset, etc...

That's why I think Zend Framework is more complicated, because it is very decoupled and you can use its classes in others projects which don't use ZF.

Title: Why is Zend Framework so complicated?


答:
The reality is that many companies are stuck in the 1950s factory worker mentality, where the rule of the day was You can't manage what you can't see.  These places are so caught up in squeezing every productive hour out of employees that the concept of remote work is an anathema.  How dare I let somebody work from home where they might take an extra 30 minutes of lunch to do groceries, or god forbid they might have to pick their child up from school.

That's the answer, plain and simple.  The status quo of companies are used to making sure everyone is in the office and at their desk typing away, so it's very hard to modernize them.

Title: Why don't more companies hire remotely?

Body:
I keep hearing about the desperate recruiting efforts of companies in tech hubs such as SF and NYC. However, every time I'm contacted by a startup I'm told the position is on-site and working remotely isn't possible.

Let me clarify that these are tech startups. They should be very comfortable with the idea of using technology to get things done and connect teams together.

With the housing market the way it is, many of us can't relocate even if we wanted to pay the higher cost of living. Why are so many companies still stuck in the industrial mindset of butts in seats?


问:
Practical size limits of a Hashtable and Dictionary in C#
What are the practical limits for the number of items a C# 4 Dictionary or Hashtable can contain and the total number of bytes these structures can reasonable contain?

I'll be working with large numbers of objects and want to know when these structures start to experience issues.

For context, I'll be using a 64-bit system with tons of memory. Also, I'll need to find objects using some form or 'key'. Given the performance demands, these objects will need to reside in memory, and many will be long-lived.

Feel free to suggest other approaches/patterns, although I need to avoid using third-party or open-source libraries. For specification reasons, I need to be able to build this using native C# (or C++\CLI).

答: Practical limits can be relative to the machine your software is running on as well as how many objects you actually plan to contain within these data structures. As Oded mentioned, int.MaxValue is a large number, but does 2 billion items equate to a practical limit? Storing that many items in memory is likely not very practical.</p>

ContentLicense: CC BY-SA 4.0


问:
SQL Triggers and when or when not to use them.
When I was originally learning about SQL I was always told, only use triggers if you really need to and opt to use stored procedures instead if possible.

Now unfortunately at the time (a good few years ago) I wasn't as curious and caring about fundamentals as I am now so never did ask to the reason why.

What's the communities opinion in this? Is it just someone's personal preference, or should triggers be avoided (just like cursors) unless there is a good reason for them.

答:
Triggers are a requirement for any complex data integrity rules. These cannot be enforced anywhere except the database or you will have data integrity problems.

They are also the best place for auditing unless you don't want to capture all changes to the database (which is the problem of auditing from the application).

Triggers can cause performance issues if not written carefully and not enough developers are knowledgeable enough to write them well. This is part of where they get their bad rap.

Triggers are often slower than other means of maintaining data integrity, so if you can use a check constraint, use that instead of a trigger.

It is easy to write bad triggers that do stupid things like try to send emails. Do you really want to be unable to change records in the db if the email server goes down?

In SQL server, triggers operate on a batch of records. All too often developers think they only need to handle one record inserts, updates or deletes. That is not the only kind of data changes that happen to a database and all triggers should be tested under the conditions of 1 record change and many record changes. Forgetting to do the second test can lead to extremely poorly performing triggers or a loss of data integrity.


答:
It's called "not following a specific coding standard".

The OP wrote:

an internal variable $_fields is accessible without using getter/setter methods

That might be against your standard, and (thus) it might be code smell. But it is not necessarily poor encapsulation. Exposing an internal (as in "only of internal use") variable over getter and setters to the outside world would be even worse.

The question is: should $_fields be accessible for the outside world?

If so, we have a case where you would add getter/setter methods. These methods do not encapsulate anything but the fact that $_fields is a variable of some kind (as opposed to something calculated/fetched/etc. on the fly). Depending on the language, you'll probably still leak the type (aka an implementation detail) to the outside. Whether you always want getters/setters, or only when "needed" is a coding standard issue.

If $_fields should not be accessible, then, well, don't access it. Whether you should keep others from accessing it on the language level (private and friends) or not (which might ease debugging in certain circumstances) is - again - a coding standard issue.

The issue of encapsulation is entirely orthogonal to this. Violating encapsulation is absolutely possible with getters and setters. It's even easier to slip into, because most people's alarm bells don't ring when they see a bunch of getters and setters - code that's seemingly following best practices. Code, that might very well introduce much more dependencies on internal implementation details than a variable called $_fields that happens not to be specified as private.

I'm a fan of bad analogies: Calling that poor encapsulation is like calling someone who holds a gun a murderer.

Title: Is there a term used when internal variables are declared public and accessible?

Body:
If someone writes code so that an internal variable $_fields is accessible without using getter/setter methods, is there a proper term used to describe that?

Something polite enough to use with management :)


问:
What's the worst programming book you've ever read?
What's the worst programming-related or technical book you've ever read? This can be any book which one way or another can be connected to programming, as long as it's not fiction.</p>

答:
Programming Microsoft Visual C++, 5ed (Kruglinski, Shepherd, Wingo)

Not that the book was bad, but its title is very misleading, especially to people new to C++. The preface of the book promises to teach you how to program in VC++, and a background in C but not C++ is all you need. Truth be told, you absolutely cannot learn anything about C++ from this book.

I owned this book for about 10 years, and recently (after working for a C++/Windows job for 4 years) I started to find a few chapters to be a bit useful when explaining stuff to new hires.

People wishing to learn Windows Programming are advised to: (in chronological order)

Learn C (and preferably get a CS degree)

Find a C/C++ project team and join it, and focus on the pure C/C++ part of programming to master it

When something is needed, learn straight from MSDN (it has improved a lot in the last 4 years). Ask your coworkers for code snippets.

Finally, read this book. It will start to make sense.

ContentLicense: CC BY-SA 2.5


问:
Is there a valid reason to wrap built in type with your own
I am editing some c++ and all of the built in types have been wrapped in a corresponding wrapper class. All of the operators have been overloaded to do bizarre things like operator[] coded to ignore the argument or to exactly what the underlying type would do.  Is this malevolent or is there some possibility this is a good idea in some other universe.    </p>

答: Though I have never seen C++ code used this way. In C, stack implementations typically do not use built in types directly. They usually have some MY_INT_32 (not event int32_t from stdint.h). This is required for very high portability. You will be amazed by the peculiarities of some of the platforms (12 bit integers anyone?).</p>


问:
What are the London and Chicago schools of TDD?
I’ve been hearing about the London style vs. Chicago style (sometimes called Detroit style) of Test Driven Development (TDD).

Workshop of Utah Extreme Programming User's Group:

Interaction-style TDD is also called mockist-style, or London-style after London's Extreme Tuesday club where it became popular. It is usually contrasted with Detroit-style or classic
  TDD which is more state-based.

Jason Gorman's workshop:

The workshop covers both the Chicago school of TDD (state-based
  behaviour testing and triangulation), and the London school, which
  focuses more on interaction testing, mocking and end-to-end TDD, with
  particular emphasis on Responsibility-Driven Design and the Tell,
  Don't Ask approach to OO recently re-popularized by Steve Freeman's
  and Nat Pryce's excellent Growing Object-Oriented Software Guided By
  Tests book.

The post Classic TDD or "London School"? by Jason Gorman was helpful, but his examples confused me, because he uses two different examples instead of one example with both approaches. What are the differences? When do you use each style?

答:
The article Mocks Aren't Stubs, by Martin Fowler is a good introduction to the topic.

Depending on the design style you choose (and the design principles upon which you build your programs), there are at least two ways of seeing an object:

As a unit that performs computations based on inputs. As a result of this computation the object can return a value or change its state.

As an active element that communicates with other elements in the system by message passing.

In the first case, you are interested in what comes out of the processing or in which state the object is left after that processing. This is where methods such as assertEquals() enter the picture. In this case, it does not matter much what other objects were involved in the processing, which methods were called, etc. This kind of verification is called state-based verification and is the "classical" style.

In the second case, since most objects do not even return any result (e.g. void methods in Java), you are more interested in how the objects communicate with each other and if they pass the right messages under the circumstances imposed by the test. These interactions are usually verified with the aid of mock frameworks. This kind of verification is called behavior-based or interaction-based verification. One of its implications is the technique called Behavior Driven Development, by which you develop a class assuming that its collaborators already exist (even though they might not exist yet), so you can code against their interfaces.

Note that this is not an either/or choice. You can have a design style that mix both approaches to get the best out of each.

OwnerDisplayName: Arturo Herrero


答:
Suppose you have class called "ledger" a method called "calculate" that uses a "Calculator" to do different types of calculations depending on the arguments passed to "calculate", for example "multiply(x, y)" or "subtract(x, y)".

Now, suppose you want to test what happens when you call ledger.calculate("5 * 7").

The London/Interaction school would have you assert whether Calculator.multiply(5,7) got called.  The various mocking frameworks are useful for this, and it can be very useful if, for example, you don't have ownership of the "Calculator" object (suppose it is an external component or service that you cannot test directly, but you do know you have to call in a particular way).

The Chicago/State school would have you assert whether the result is 35. The jUnit/nUnit frameworks are generally geared towards doing this.

Both are valid and important tests.

Title: What are the London and Chicago schools of TDD?

Body:
I’ve been hearing about the London style vs. Chicago style (sometimes called Detroit style) of Test Driven Development (TDD).

Workshop of Utah Extreme Programming User's Group:

Interaction-style TDD is also called mockist-style, or London-style after London's Extreme Tuesday club where it became popular. It is usually contrasted with Detroit-style or classic
  TDD which is more state-based.

Jason Gorman's workshop:

The workshop covers both the Chicago school of TDD (state-based
  behaviour testing and triangulation), and the London school, which
  focuses more on interaction testing, mocking and end-to-end TDD, with
  particular emphasis on Responsibility-Driven Design and the Tell,
  Don't Ask approach to OO recently re-popularized by Steve Freeman's
  and Nat Pryce's excellent Growing Object-Oriented Software Guided By
  Tests book.

The post Classic TDD or "London School"? by Jason Gorman was helpful, but his examples confused me, because he uses two different examples instead of one example with both approaches. What are the differences? When do you use each style?


答:
One thing to point out is that the Dictionary is not going to hold the object itself (which may have a large memory footprint) but only a reference to the object so if the objects are complex this has no impact on the Dictionary size.

I have had collected several thousand items together in a Dictionary in memory and the issue is not the size of the Dictionary but the size of the objects themselves in memory.  In these cases the Dictionary itself was a tiny portion of the memory involved.

One thing to think about in the cases of large Dictionaries is manually configuring and managing the Dictionary capacity.  Under normal circumstances .Net manages this fine (in the current implementation if it runs out of space it resizes to a prime number that is at least twice the Dictionary current size).  However, if you know you are going to create a large Dictionary or are going to expand the Dictionary instead of .Net guessing and resizing the Dictionary for you (which is relatively costly) it is probably better you doing this yourself (certainly with the initial size and probably managing later resizes).  This can be done by managing the Dictionary capacity if you have a reasonable heuristic idea of what the capacity of the Dictionary should be.  Microsoft recommends this on MSDN in their remarks on the Dictionary object.  However, there seems to be some debate on the real value of this approach although I am not sure how rigorous that test is and if there are other optimisations that the .Net platform puts in place when a dictionary is resizing extremely rapidly.

This is a useful Stack Overflow question  about object and memory size.

Title: Practical size limits of a Hashtable and Dictionary in C#

Body:
What are the practical limits for the number of items a C# 4 Dictionary or Hashtable can contain and the total number of bytes these structures can reasonable contain?

I'll be working with large numbers of objects and want to know when these structures start to experience issues.

For context, I'll be using a 64-bit system with tons of memory. Also, I'll need to find objects using some form or 'key'. Given the performance demands, these objects will need to reside in memory, and many will be long-lived.

Feel free to suggest other approaches/patterns, although I need to avoid using third-party or open-source libraries. For specification reasons, I need to be able to build this using native C# (or C++\CLI).


答: Since the documentation does not tell where is the data physically stored and it does not specify the limit, I suggest you perform an experiment with the maximum expected size that you are likely to have and note the system memory before and after the storage allocation.</p>


问:
How to sell a high SO reputation at an interview
A question with absolutely no relevance to myself:

How would a programmer with a stellar SO reputation (like 30k+) market his or herself to poential employers/investors who have never heard of SO?
In other words, how can one describe SO in a few sentences that will make a high reputation sound impressive at an interview?

答:
No, you can't. Please don't. We despise you.

Seriously, I think posting well-thought, well-organized answers to non-trivial questions qualifies as a way to practice technical communication, as is careful reading of other people's great writings on SO.

Depending on the position you are interviewing for, technical communication may be an important and marketable skill, especially if the position is not entry-level. In this case, you should be able to demonstrate your writing and verbal skills without directly mentioning SO.


问:
How did you pick up the art of solving real life problems? Can you shortcut the process?
I have been coding on and off on C and to a certain extent on C++ since my college days(2003), but I never had the opportunity to work with a hard core programming responsibility, which could have taught me "industrial grade coding" better and what is needed really for solving real life problems. To me it looks like I had been coding naive codes, like linked lists, binary trees, and Dijkstra and Kruskal's Algos all these years.

Additionally I feel my academic experience just taught me the language not how to solve real life problems.

So my question is:

So how did you pick up the art of solving real life problems?

Any way to shortcut the process?

Is it only my education or in general everyone coding education sucked big time?

How often do you have to learn "new things" to solve a problem in a better way.

For example, though I have used delegates and events for simple windows programming, but my current problem will require a much more in depth knowledge of it, plus I have forgotten most of it. So its as good as new for me. I will have to learn threaded programming and multicore programming. So it gives me an impression-"heck then what did I learn really all these years?"

答: my advice is to climb the career ladder a little bit. I started out as a C++ dev in the gaming industry. At first it was a great job that got me started in the language, but pretty soon I realized I was capable of 200% of what the people around me were. So I shopped around, moved out of state, found a new industry, and came up to speed. There I took C++ to a new level. I bounced around a little since then, but I always took on new challenges. In reward, my pay has more than doubled since I started in 2006. But honestly I didn't do it for the money, I did it because I craved the challenge and worked hard at it.</p>


答: It has a lot to do with company's culture. If a company is set up to operate in a way that many (or most) developers work remotely, it can be done. It is much harder if only a small part of the team works that way.</p>

Title: Why don't more companies hire remotely?


问:
Elegant ways to handle if(if else) else
This is a minor niggle, but every time I have to code something like this, the repetition bothers me, but I'm not sure that any of the solutions aren't worse.

if(FileExists(file))
{
    contents = OpenFile(file); // <-- prevents inclusion in if
    if(SomeTest(contents))
    {
        DoSomething(contents);
    }
    else
    {
        DefaultAction();
    }
}
else
{
    DefaultAction();
}
```

Is there a name for this kind of logic?

Am I a tad too OCD?

I'm open to evil code suggestions, if only for curiosity's sake...

答:
What's wrong with the obvious

if(!FileExists(file)) {
    DefaultAction();
    return;
}
contents = OpenFile(file);
if(!SomeTest(contents))
{
    DefaultAction();
    return;
}
DoSomething(contents);
```

It seems pretty standard to me? For that kind of big procedure where lots of little things have to happen, failure of any of which would prevent the latter. Exceptions make it a bit cleaner if that's an option.

Title: Elegant ways to handle if(if else) else

Body:
What's wrong with the obvious

if(!FileExists(file)) {
    DefaultAction();
    return;
}
contents = OpenFile(file);
if(!SomeTest(contents))
{
    DefaultAction();
    return;
}
DoSomething(contents);

It seems pretty standard to me? For that kind of big procedure where lots of little things have to happen, failure of any of which would prevent the latter. Exceptions make it a bit cleaner if that's an option.


问:
What is a good code pattern for single retry then error?
I am writing a routine which has the following form:

```<code>TRY A
IF no success, B
IF no success, RETRY A
IF no success, throw error
</code>```

It's not trivial to extract either A or B into it's own routine, so what is most simple structure that will allow me to retry A without code duplication?

Currently, I have a do..while that allows N retries:

```<code>int retries = 1;

do {
    // DO A

    if ( /*success*/ ) {
        break;
    } else if (retries > 0)  {
        // DO B

        if ( /*success*/) {
            break;
        }
    } else {
        // throw Error
    }
} while (retries-- > 0);
</code>```

This is ugly and not ideal as it implies that I might want to ever retry more than once, which I don't.  I will have to use a loop, but there has to be a more simple way that I'm not seeing.

For context, this is code generated in Java, executing SQL statements to try an UPDATE first, then if no entry to update is found, INSERT, and if that command fails (concurrency, already created), try UPDATE again.

答:
Why don't you do a select to test if the row exists, as opposed to an updated with a failure test?

Then you can just either insert or update...


问:
Is Dijkstra's algorithm an appropriate solution to this signal routing problem?
I'm in the process of developing a signal management and routing module for an integrated audiovisual system and am designing it with the intent of being as flexible as possible across different signal distribution networks. The intent of the module is to handle routing across a number of stacked matrix switchers1 and handle necessary format conversion.

The best solution I've explored at this point is to map out the network to a graph with discrete vertices for each signal type supported by the switchers and which are then joined via nodes representing the video processors that handle format conversion.

Colours represent signal formats.
Round nodes are either switchers, sources or sinks.
Square nodes are video processors which perform format conversion.

From there I can use an implementation of Dijkstra's algorithm to identify the path that has to be formed in order to get input X to output Y. This should allow the data about the input / output configuration of all the switchers and processors to be passed in and the module adapt accordingly.

Is this an appropriate solution or is there an alternative approach that may be worth investigating?

1 aka 'crossbar switch', a video router with M input x N outputs that supports one-to-many connections. Each phsyical device may handle multiple signal formats and may or may not be capable of performing any format conversion.

edit: As mentioned by Péter Török, the graph will not necessarily be a tree, the diagram is a simple example to illustrate the idea. When implemented in the 'real world' multiple paths may exist which offer varying levels of definition (DVI > VGA > component > composite) which I was planning to represent with edge weighting.

edit 2: Here's an slightly more comprehensive example with directivity indicated and showing a network consisting of two signal types. The initial example has been modified slightly so that each input and output on a device is defined as a discrete node as this will provide the data required to control matrix routing / input selection.

答:
You may be able to use A* (the more general form of Dijkstra's algorithm) for searching the graph in question. You mention the costs of the weightings in your comment:

Additive. The theory being this will allow it to be defined such that
  the higher the definition of the signal path, the lower the weighting.
  Edges which connect nodes that perform format conversion would then be
  given a weighting higher than that assigned to edges which connect
  non-conversion nodes. This would route the signal in it's native
  format if possible, only involving format conversion (and associated
  signal degradation and equipment utilisation) when necessary

If I understand it correctly, you want to find the lowest cost path path from the start to the goal. If you provide each node both an actual cost and an estimate (heuristic) to the goal (that is both admissible and consistent), then A* is guaranteed to provide an optimal solution. It might be overkill though, depending on how well I understand your problem.


答:
I've written this in C, so I can't guarantee that it'll cut-and-paste into Java.

If you're certain you want to retry DoA only once, use can use one line:

```<code>bool DoIt()
{
    return DoA() || DoB() || DoA();
}

bool DoA() { } // Return true if successful.

bool DoB() { } // Return true if successful.
</code>```

If you want the option of more than one retry, use this loop.

```<code>bool DoIt(int retryLimit)
{
    if (DoA()) return true;
    for (int retries = 0; retries < retryLimit; retries++)
    {
        if (DoB()) return true;
        if (DoA()) return true;
    }
    return false;
}
</code>```

Edit: If you really cannot make time to extract DoA and DoB, then try the following block.  Remember that comments are your friend:

```<code>bool retry = false;
bool success = false;
do
{
    // Do A.
    success = // true or false
    if (success) break;

    // Attempt the above code twice and the below code once.
    if (retrying) break;
    retrying = true;

    // Do B.
    success = // true or false
    if (success) break;
}
if (success)
{
    // Celebrate.
}
else
{
    // Commiserate.
}
</code>```

Title: What is a good code pattern for single retry then error?

Body:
I am writing a routine which has the following form:

```<code>TRY A
IF no success, B
IF no success, RETRY A
IF no success, throw error
</code>```

It's not trivial to extract either A or B into it's own routine, so what is most simple structure that will allow me to retry A without code duplication?

Currently, I have a do..while that allows N retries:

```<code>int retries = 1;

do {
    // DO A

    if ( /*success*/ ) {
        break;
    } else if (retries > 0)  {
        // DO B

        if ( /*success*/) {
            break;
        }
    } else {
        // throw Error
    }
} while (retries-- > 0);
</code>```

This is ugly and not ideal as it implies that I might want to ever retry more than once, which I don't.  I will have to use a loop, but there has to be a more simple way that I'm not seeing.

For context, this is code generated in Java, executing SQL statements to try an UPDATE first, then if no entry to update is found, INSERT, and if that command fails (concurrency, already created), try UPDATE again.

Body:
I've written this in C, so I can't guarantee that it'll cut-and-paste into Java.

If you're certain you want to retry DoA only once, use can use one line:

bool DoIt()
{
    return DoA() || DoB() || DoA();
}

bool DoA() { } // Return true if successful.

bool DoB() { } // Return true if successful.

If you want the option of more than one retry, use this loop.

bool DoIt(int retryLimit)
{
    if (DoA()) return true;
    for (int retries = 0; retries < retryLimit; retries++)
    {
        if (DoB()) return true;
        if (DoA()) return true;
    }
    return false;
}

Edit: If you really cannot make time to extract DoA and DoB, then try the following block.  Remember that comments are your friend:

bool retry = false;
bool success = false;
do
{
    // Do A.
    success = // true or false
    if (success) break;

    // Attempt the above code twice and the below code once.
    if (retrying) break;
    retrying = true;

    // Do B.
    success = // true or false
    if (success) break;
}
if (success)
{
    // Celebrate.
}
else
{
    // Commiserate.
}


问:
What are the software technologies behind real time web apps?
What are some of the software technologies behind "real-time" web apps, like Twitter, Trello, or even Gmail? I know there's a webserver and probably a database on the backend, but what are the software pieces that make for that rich web interaction that I'm seeing more of today?</p>

答:
Client-side, Javascript and Ajax.

Server-side, a plethora of different technology stacks.. As Raynos eluded to in his comment, virtually anything can be used to build a real time web application...

You could use a web server (such as Apache) to mediate communication between your clients and data, but you don't necessarily need to. You could also write your own HTTP handling on a server rather than deal with the overhead of using a third party web server yourself. A few examples might be (assume Javascript/AJAX client-side for each):

```<code>Language   / Interface / Server
-------------------------------
Python     / WSGI      / nginx
Javascript / -         / node.js
C++        / FastCGI   / Apache
Erlang     / -         / Yaws (embedded)
PHP        / mod_php   / Apache
</code>```

Again, those are just a few examples of possibilities. The possible permutations of tech stacks for implementing server-side solutions is virtually endless.

Edit:

Silly me. HTML5 is probably the biggest addition to the client-side tech stack that allows for rich web applications these days. The addition of features such as audio (Firefox has even exposed audio data to allow visualization of an audio spectrum through Javascript), video, database (WebSQL, IndexedDB), filesystem (sandboxed on most browsers, full system access available in Firefox through XPCOM components), WebGL and WebSockets are just a few of the big additions that HTML5 has brought along.

Body:
Client-side, Javascript and Ajax.

Server-side, a plethora of different technology stacks.. As Raynos eluded to in his comment, virtually anything can be used to build a real time web application...

You could use a web server (such as Apache) to mediate communication between your clients and data, but you don't necessarily need to. You could also write your own HTTP handling on a server rather than deal with the overhead of using a third party web server yourself. A few examples might be (assume Javascript/AJAX client-side for each):

Language   / Interface / Server
-------------------------------
Python     / WSGI      / nginx
Javascript / -         / node.js
C++        / FastCGI   / Apache
Erlang     / -         / Yaws (embedded)
PHP        / mod_php   / Apache

Again, those are just a few examples of possibilities. The possible permutations of tech stacks for implementing server-side solutions is virtually endless.

Edit:

Silly me. HTML5 is probably the biggest addition to the client-side tech stack that allows for rich web applications these days. The addition of features such as audio (Firefox has even exposed audio data to allow visualization of an audio spectrum through Javascript), video, database (WebSQL, IndexedDB), filesystem (sandboxed on most browsers, full system access available in Firefox through XPCOM components), WebGL and WebSockets are just a few of the big additions that HTML5 has brought along.


问:
Converting a bounded knapsack problem to 0/1 knapsack problem
I ran across a problem where goal was to use dynamic programming (instead of other approaches). There is a distance to be spanned, and a set of cables of different lengths. What is the minimum number of cables needed to span the distance exactly?

To me this looked like a knapsack problem, but since there could be multiples of a particular length, it was a bounded knapsack problem, rather than a 0/1 knapsack problem. (Treat the value of each item to be its weight.) Taking the naive approach (and not caring about the expansion of the search space), the method I used to convert the bounded knapsack problem into a 0/1 knapsack problem, was simply break up the multiples into singles and apply the well-known dynamic programming algorithm. Unfortunately, this leads to sub-optimal results.

For example, given cables:

1 x 10ft,

1 x 7ft,

1 x 6ft,

5 x 3ft,

6 x 2ft,

7 x 1ft

If the target span is 13ft, the DP algorithm picks 7+6 to span the distance. A greedy algorithm would have picked 10+3, but it's a tie for minimum number of cables. The problem arises, when trying to span 15ft. The DP algorithm ended up picking 6+3+3+3 to get 4 cables, while the greedy algorithm correctly picks 10+3+2 for only 3 cables.

Anyway, doing some light scanning of converting bounded to 0/1, it seems like the well-known approach to convert multiple items to { p, 2p, 4p ... }. My question is how does this conversion work if p+2p+4p does not add up to the number of multiple items. For example: I have 5 3ft cables. I can't very well add { 3, 2x3, 4x3 } because 3+2x3+4x3 > 5x3. Should I add { 3, 4x3 } instead?

[I'm currently trying to grok the "Oregon Trail Knapsack Problem" paper, but it currently looks like the approach used there is not dynamic programming.]

答:
The way that I have seen used to transform a bounded knapsack problem into a 0/1 one is to just have multiple identical items. Say if you have the following items (given as weight, utility):

2 x 1, 2

3 x 2, 3

You would transform it into a 0/1 problem using items with

1, 2

1, 2

2, 3

2, 3

2, 3

And use a 0/1 algorithm to solve it. You will likely have multiple solutions of equal correctness so you select an arbitrary one.

Now about your wire problem: I would have the length of the cable be the wight and the value of each cable being exactly the same (call it 1, though any positive value will work). Now, use your favorite Knapsack solving algorithm but where you would normally select a (partial) solution that maximizes value, select one that minimizes it. Also, disregard all solutions that do not have a total weight that equals the capacity. I can probably (try to) write a more concrete algorithm with actual code if anyone wants it.


答:
Comet plays an important role in these applications.

Comet is a web application model in which a long-held HTTP request allows a web server to push data to a browser, without the browser explicitly requesting it.

http://en.wikipedia.org/wiki/Comet_%28programming%29

JavaScript is the glue between the comet servers and the browsers. Server software like Node.js are used to implement these comet servers that will have to handle many long-held connections.

Besides comet, these applications also need a good backend. The solutions may be very specific to the problem.

Twitter, for example, has to stream tweets to all your followers for each of your tweets. Facebook has to run machine learning algorithms to select which stories to stream on your News Feed.

Although different, these applications have many things in common: heavy use of cache, data denormalization, asynchronous jobs, are highly distributed.

Title: What are the software technologies behind real time web apps?

Body: What are some of the software technologies behind "real-time" web apps, like Twitter, Trello, or even Gmail? I know there's a webserver and probably a database on the backend, but what are the software pieces that make for that rich web interaction that I'm seeing more of today?</p>


答: An alternative would be to return IObservable instead of making events.  This would allow B to have a single method that simply delegates to the inner C instead of needing to have its own event and hook up an event handler to the inner C.

Title: Event subscription from nested classes

Body:
Is it OK to have a nested class raise an event and for the parent class that subscribes to that event subsequently raise another event, which it's parent class has subscribed to - thus passing the original event up the class hierarchy?

It may be easy to explain like this...

We have...

```<code>Class A
Class B
Class C
</code>```

Operation...

Class C raises an event

Class B subscribes to that event, on notification it raises another event

Class A subscribes to Class B event, on notification it does something

So the original event occurred in Class C and Class A is dealing with it.

Using this method means I require event handlers in the middle class (Class B) whose only function is to pass along the notification - this seems a little smelly to me.


问:
Immutable structures and deep composition hierarchy
I'm developing a GUI application, heavily working with graphics - you can think about it as a vector editor, for the sake of the example. It is very tempting to make all data structures immutable - so I could get undo/redo, copy/paste, and many other things almost without effort.

Fot the sake of simplicity, I will use the following example - application is used to edit polygonal shapes, so I have "Polygon" object, which is simply list of immutable points:

```<code>Scene -> Polygon -> Point
</code>```

And so I have only one mutable variable in my program - the one which holds current Scene object. The problem which I have starts when I try to implement point dragging - in mutable version, I simply grab a Point object and start modifying its coordinates. In immutable version - I am stuck. I could have stored indices of Polygon in current Scene, index of dragged point in Polygon, and replace it every time. But this approach does not scale - when composition levels go to 5 and further, boilerplate would become unbearable.

I'm sure this problem can be solved - after all, there is Haskell with completely immutable structures and IO monad. But I just cannot find how.

Can you give me a hint?

答:
I have worked on exactly the same problem (but only with 3 composition levels). The basic idea is to clone, then modify. In immutable programming style, the cloning and modification has to happen together, which becomes command object.

Note that in mutable programming style, cloning would have been necessary anyway:

To allow undo/redo

The display system may need to simultaneously display the "before edit" and "during edit" model, overlapped (as ghost lines), so that the user can see the changes.

In mutable programming style,

The existing structure is deep-cloned

The changes are made in the cloned copy

The display engine is told to render the old structure in ghost-lines, and the cloned/modified structure in color.

In immutable programming style,

Each user action that results in data modification is mapped to a sequence of "commands".

A command object encapsulates exactly what modification is to be applied, and a reference to the original structure.

In my case, my command object only remembers the point index that needs to be changed, and the new coordinates. (i.e. very lightweight, as I'm not strictly following immutable style.)

When a command object is executed, it creates a modified deep-copy of the structure, making the modification permanent in the new copy.

As user makes more edits, more command objects will be created.


答:
To reduce nested IF:

1/ early return;

2/ compound expression (short-circuit aware)

So, your example may be refactored like this:

if( FileExists(file) && SomeTest(contents = OpenFile(file)) )
{
    DoSomething(contents);
    return;
}
DefaultAction();
```

Title: Elegant ways to handle if(if else) else

Body:
This is a minor niggle, but every time I have to code something like this, the repetition bothers me, but I'm not sure that any of the solutions aren't worse.

if(FileExists(file))
{
    contents = OpenFile(file); // <-- prevents inclusion in if
    if(SomeTest(contents))
    {
        DoSomething(contents);
    }
    else
    {
        DefaultAction();
    }
}
else
{
    DefaultAction();
}
```

Is there a name for this kind of logic?

Am I a tad too OCD?

I'm open to evil code suggestions, if only for curiosity's sake...


问:
Patterns for Continuous Integration and DVCS
We currently use Subversion and TeamCity, we're going to move to using Mercurial (specifically Kiln as we're FogBugz users).

Obviously this will result in changes - hopefully improvements - in our development patterns (all two of us!) but the one issue I'm stuggling with is how to structure things so that we still enjoy the benefits of continuous integration/our CI server (that there are and will remain benefits is a given, discussion of which is outside the scope of this question).

With SVN we are committing to a limited number of central repositories - effectively one per project (more or less one Visual Studio Solution) so its easy to trigger a build and to get the reassurance that all the files have been commited and that there are no stray dependencies etc, etc. But if we're going to take proper advantge of mercurial we're going to want to have more repository instances - where I'd expect changes to generally flow towards a definitive "live" repo. The problem I'm struggling with is that the live repo seems to me to be too "late" to trigger my CI builds OTOH one CI build per project per developer is probably excessive (and causes other issues). I think that live is too late because - given that we can/should have more repos (clones of) - live should be deployable whereas we want to be building/running tests (unit at commit, integration at scheduled intervals) on development commits.

I'm fishing a bit but that's because one of the things that a central subversion repo gives one (me, with our setup!) is a lot of clarity about what to build when.

n.b. I'm not asking about the mechanics of using mercurial with continuous integration - I have that working a treat for a personal project, its patterns and structures and working practice/workflow that I'm trying to get my head round.

答:
We've been using Kiln for about a year now and have tried several different things. Where we've ended up is to used named branches (as opposed to branch clones) with the following branching strategy:

default tracks "completed" development

feature branches track work that's currently in progress

release branches track points where we released from default

So, work starts by creating a feature branch from the current tip of default. When the feature branch is done*, the branch is closed and merged back into default.

At some point, we decide that we're ready to release, so we create a new release branch from the current tip in default. This allows us to make changes to the code that's currently in production by committing to the release branch while still allowing active development on the feature branches and default.

As for continuous integration, we do two things:

An "always on" integration that monitors the status of default

New integrations for each release branch

The default branch job lets us know that our main source tree is always stable -- the release branch jobs let us know that those branches are stable and provide us with the build output we need to push a release into production.

*Our definition of "done" is that the feature is up-to-date with merges from default and has been approved in code review.


问:
What are the tools/frameworks used to build C# ASP.net applications?
I am basically a java programmer who wants to move to .net. I haven't worked in .NET companies so I don't have any idea about the tools they use. In a Java company people use Maven, Hibernate and frameworks such as JSF or Tapestry.

My questions are:

What are the tools/frameworks that .NET/C# companies use? Do they use ASP.NET MVC? Do they use any ORM tool? Do they use any framework?

I will be happy if someone could tell me about this.

答:
In .NET, we can develop various types of applications, such as:

Web Application -> WebForm or Model View Based Application typically called as MVC

WebSite

Console Application

Windows Application

and many others.

Each of above application can be develop in different framework (1.0,2.0,3.5,4.0 or 4.5 version)

You can simply start working with ASP.NET with Visual Studio 2005/2008/2010.

Based on the your project requirement, you can choose the web and windows with different language support. As you are java developer, I will sugguest you to go for C# .

You can find the complete details on www.msdn.com and Microsoft's other websites.


答:
There is no absolute tool to write a program with in .NET; as in Java you have several at your disposal to do what you want. You can go the "Microsoft way" using only Microsoft technologies all the way or you can use third party tools for nearly everything. Let's take the example of DBMS access:

Using Microsoft tools

ADO.NET ("standard" access to a DBMS)

Linq to SQL (ORM)

EntityFramework (ORM, similar to Hibernate)

Using third-party tools

MyBatis, aka Ibatis in Java

NHibernate, aka Hibernate in Java

and the list goes on and on, I just listed the first two that came to mind and that are also available in the Java world... (check out the huge list of ORM frameworks available for C#)

For every "part" of an application you have that choice, be it logging frameworks, testing frameworks, IOC frameworks, etc. In the beginnings of .NET there was only the "Microsoft Way" due to lacking third-party tools, now you have the choice.

To answer your other question on .NET web development, companies may use:

"old school" ASP.NET WebForms

ASP.NET MVC3

Silverlight (as a separate application, or in combination with ASP.NET applications)

As of now, ASP.NET MVC seems to be the preferred choice, see #1, #2 or #3 (this one to indicate that ASP.NET WebForms has its advantages)

One thing that @Anand is right about: if you know Java, use C#.

Title: What are the tools/frameworks used to build C# ASP.net applications?

Body:
I am basically a java programmer who wants to move to .net. I haven't worked in .NET companies so I don't have any idea about the tools they use. In a Java company people use Maven, Hibernate and frameworks such as JSF or Tapestry.

My questions are:

What are the tools/frameworks that .NET/C# companies use? Do they use ASP.NET MVC? Do they use any ORM tool? Do they use any framework?

I will be happy if someone could tell me about this.


答:
In the .NET world, you generally don't need third party software like Maven, Hibernate, etc. because Microsoft provides the basics.  Visual Studio has a command line build mechanism (msbuild).  Microsoft has released two ORMs: Entity Framework and LinqToSql, although you can still use NHibernate instead.

Web applications in .NET tend to be built in one of two ways:

Web Forms (ASP.NET "Classic")

ASP.NET MVC

Both of these are provided by Microsoft and you don't necessarily need to download anything, although Microsoft has been releasing updates to MVC asynchronously to Visual Studio releases.

There are open source software and frameworks in the .NET world, but it's not needed and many projects don't use it at all since Microsoft provides quite a bit out of the box.


问:
How to improve my algorithm for analyzing twitters messages from users?
Hello I think I have a nice idea to implement for human kind goodness. I call it FixTheUnFixed.

The idea goes like this, imagine you are driving or traveling all over the world and when you see some obstacle or damage - broken light, trash covering the street or any other problem you would like the responsible authority to fix it.

All you have to do is twit it, maybe add a photo, and of course provide the location using the inherit location service of twitter or Facebook.

```<code>     @FixTheUnFixed there is broken fire hydrant here
     @FixTheUnFixed my cellular company charged me 18,572$
       for using my iPhone aboard.
</code>```

I thought a lot about how to process the messages. The most frequent issues that will come up are municipality concerns and I would like them to receive that location either by a retwit or an email.

My two ideas for getting this address are by googling it (with google API) or just make a regular query mentioned in this pseudo Algorithm:

```<code>       1. get the location from the Twitter or Facebook status that was sent from.
       2. look for key words such as trash, cats, animals etc.
       3. find the relevant authority e-mail, twitter or Facebook account.
       4. send the message to the authority account and retwit it to the public
          world so they can follow if there is any cahnge.
</code>```

In the third step, is there any smart way to implement it?
I didn't find any good way to do this! I don't want to spam the authorities or publish spam of sneaky people.

How can I improve the algorithm?

How can I search for the communication resources of the relevant authorities?

Thanks

originally asked here:
https://stackoverflow.com/questions/8393424/how-to-improve-my-algorithm-for-analyzing-twitters-messages-from-users

答:
I don't know if an algorithm can solve all of that. I would preprocess the information as good as possible and then "crowdsource" the rest.

Especially the step where you are checking for spam and matching messages to relevant authorities look like something that need some sort of human interaction.

Finding relevant authorities will probably also be really hard and only solvable by a (trusted) user. I tried to report a broken traffic light once and it took me 15 minutes to find the right contact.

With that you are of course facing another set of problems: community building, trusted users, etc.


问:
Are there any best practices regarding the handover from architecture to development?
We are looking at improving the process for handing over tasks from architecture to development.

At one end of the scale it there is no architecture guidance you risk getting chaos, with each developer doing things his way.

At the other end of the scale where everything is specified, the specification takes longer than the development, and you risk having very boring development tasks.

Has anyone found an optimal middle ground between these extremes? Which artifacts do you deliver to development? For example: modules, class structure, or sequence diagrams?

答:
You need to give as much information as possible for the future team to maintain the code. If you do not have sequence diagrams for example, the developer is forced to trace the code step by step, thereby wasting time.

Also there is room for the new team making assumptions that are invalid.

In general there should be a document about what the project is , the technical specifications, unit test cases and sequence/class diagrams.


问:
Is it ethical to use personal code at work?
I am working on a side project at work where I find it beneficial to use some of my code that I have developed personally (outside of work) to speed my development. My side project is developing a C++ GUI application to let our power users run queries (built by me) against databases on several different platforms (DB2, Oracle, SQL Server and MySQL). In the past, I would usually just run these myself on request or build an Excel VBA application for them. Now that I have built several VBA applications for several different people, I find the need to build one central application that just reads in custom .sql files and executes against various databases.

The application that I am building is in C++ and uses an LGPL cross-platform GUI toolkit. However, I have a lot of code that in my own libraries that I have built over the years on leisure, non-work related projects. Is it okay to use this code at work, thus saving me (and the company) time? If so, can I port any bug fixes and enhancements back to my personal library? There seems to be a line that I do not know when I am going to cross it.

I just want to add that none of the personal code has anything to do with any business logic. They are just basic utility classes/wrappers.

答:
As always, it depends.  In this case, on what a) the license you put on the code says and b) on what your contract says.  You might want to come up with a business deal with the company that covers code you wrote before you got there.

There's no general ethical problem with this, so long as you think about it beforehand.

OwnerDisplayName: CodeBlew

OwnerDisplayName: Andrew McGregor


问:
Tools to help Agile team deliver value
My Agile team is following practices of XP like pair programming(J2EE), 45 work hours/week, TDD etc. Do you have any recommendations of open source tools (dev, test & build integration) and templates(user story, burndown charting) etc. for enabling my team to focus on business value delivery. I am the iteration manager and we have tried Hudson, Junit and Selenium.</p>

答:
Without rehashing all the litterature out there regarding agile organisation, I will just say, in my opinion, is the most important for a successful Agile project:

Communication You may have read that somewhere, it's the truth: agile is all about communication. It's all based on the fact you get frequent updates from the users (if they're actually involved in writing story, and maybe even in designing acceptance tests, that's even better), but also giving them frequent feeback (release after every iteration) and also communication within the team: pair-programming, daily stand-up, iteration planning meetings, retrospective meetings, etc. I found that an invaluable tool for communication is the story board: despite all our tries for online versions, we always came back to a physical board. Nothing beats being able to manually handle the cards to move them around, pick them when you're working on them, and having the standup meeting around the board where everyone can see what people are talking about, and decide what to do for the day.

In term of development, the most important is testing. Aim for a very high coverage (ideally 100%, but the most important is functional coverage), that's the only way to enable refactoring (paramount in agile dev) in a safe and efficient way. The ideal test coverage has three layers of tests:

Acceptance tests (ideally written by the users) maybe using something like JBehave or FITness to give the ability the write the stories in natural language, while being dynamically ran against your production code. Thus, these tests/story also act as documentation to your project. Very valuable to provide visual feedback to users and visitors, and remind you of everything your code is doing. ALL the stories yo're working on should have at least one of these tests attached to it, so that you know when the work is complete on that story: when the acceptance test(s) is(are) passing.

System / integration tests: These are tests designed to make sure all the various components in your project (database, web server, etc.) can interact nicely (this includes CRUD tests for your db entitities).

Unit-tests preferably using TDD (ideally BDD) to design the details of the system. Using JUnit and a mocking framework (My favourite is JMock v2)

And also

Flexibility. Don't try to blindly follow XP or Scrum as written in the books. Try different approaches, for a couple of weeks each time, see what works with your team and increase your productivity, and don't be afraid to adopt or dismiss practices. It's all about pragmatism and what works with your team. For example, I've been in project where we switched pair every day, every couple of days, and even every couple of hours. What's best for you will depend on the rate of your project, your users, and the developers in the team. Try everything, then decide. And feel free to change anytime you feel there's an advantage doing so. Use retrospective meetings (every month or couple of months) to discuss what works and what doesn't and get feedback from everyone. It's very important to discuss how the various practices are perceived by the team. Invite some users, and some external observers to these. It's amazing how someone who doesn't know anything about your project can sometimes contribute and bring a very interesting fresh point of view on a problem you may have.

Another couple of things that served us well in the past:

Always maintain a very detailed release notes document. Ideally available to your users for reference (through a website, or a wiki), it shows what went on a release iteration after iteration. Link to that document as often as you can. An agile project evolves very quickly (if you release after each iteration) and it's sometimes confusing for the users or related systems, who are not used to that pace for releases, and expect less frequent "big bang" releases. Educate them.

Always favor a flexible (spreadsheet-based?) approach for measures and reporting: a burndown chart is very nice to maintain daily and have available during standups, to see how good you are at estimating stories (it is not a measure of the productivity of the developers, in XP it's assumed everyone do the best they can)

Title: Tools to help Agile team deliver value

OwnerDisplayName: Guillaume


答:
Is it okay to use this code at work, thus saving me (and the company) time?

Yes, it's ethical. In the case you describe that you own the code, so you can freely give it to your company. They hired you to write code so they trust your code.

If so, can I port any bug fixes and enhancements back to my personal library?

Your contract probably forbids this unless you get permission (check your contract).

The best solution is to talk to your manager. I can't see any manager refusing your request. It also makes you look good when you point out how your personal coding is helping the company.

Title: Is it ethical to use personal code at work?

Body:
I am working on a side project at work where I find it beneficial to use some of my code that I have developed personally (outside of work) to speed my development. My side project is developing a C++ GUI application to let our power users run queries (built by me) against databases on several different platforms (DB2, Oracle, SQL Server and MySQL). In the past, I would usually just run these myself on request or build an Excel VBA application for them. Now that I have built several VBA applications for several different people, I find the need to build one central application that just reads in custom .sql files and executes against various databases.

The application that I am building is in C++ and uses an LGPL cross-platform GUI toolkit. However, I have a lot of code that in my own libraries that I have built over the years on leisure, non-work related projects. Is it okay to use this code at work, thus saving me (and the company) time? If so, can I port any bug fixes and enhancements back to my personal library? There seems to be a line that I do not know when I am going to cross it.

I just want to add that none of the personal code has anything to do with any business logic. They are just basic utility classes/wrappers.


答:
There have always been problems in how information is flowed from architecture to development test and operations. The way to tackle these problems imho depend on several factors like:

size of the software

complexity

culture in your organization

belief.

For certain combinations of these factors a pure agile approach cross-functional teams with emergent design is appropriate. The information flows by working together. The disciplines document what they need.

For other combinations of these factors a small team of architect,tester,operations expert and lead developers might start with architecture iterations slowly building up the architecture, documenting and getting immediate feedback on their architecture decisions. Slowly more developers that implement features can be added to the team and the original core team can be made smaller.

Mostly for government and finance projects it is required that more documentation is written upfront and that can take a long time with no real world feedback on your choices. In my mind the biggest reason that many of these projects fail. Still if this is your situation I would make the documentation to fit the requirements And than use option 1 or  2 to actually build the software and refine/adapt the documentation.

Hope this helps.

Title: Are there any best practices regarding the handover from architecture to development?

Body:
We are looking at improving the process for handing over tasks from architecture to development.

At one end of the scale it there is no architecture guidance you risk getting chaos, with each developer doing things his way.

At the other end of the scale where everything is specified, the specification takes longer than the development, and you risk having very boring development tasks.

Has anyone found an optimal middle ground between these extremes? Which artifacts do you deliver to development? For example: modules, class structure, or sequence diagrams?


问:
Algorithm for searching the neighbors neighbor of a directed graph
Is there an algorithm to search a directed graph (tree) for its neighbors neighbor?

My current brute-force solution works as follows:

```<code>for each node n:
   for each child c of n
      for each parent p of c
         if (p != n)
           insert edge (p,n)
</code>```

I am dealing with ca. 700.000 nodes each having between 1 to 1000 edges and currently I am facing too long running times: which is mainly due to the reason I am executing this algorithm on a graph database, since it would require too much memory.

答:
Are "for each child" and "for each parent" equally fast? If "for each parent" is slower, try this:

```<code>for each node p
  for each child c1 of p
     for each child c2 of p
       if (c1 != c2)
         insert edge (c1,c2)
</code>```

EDIT: The above version creates a different result, a list of siblings. Now for another approach...

```<code>for each node c
  ps:=c.parents()
  for each p1 in ps
     for each p2 in ps
       if (p1 != p2)
         insert edge (p1,p2)
</code>```

Body:
Are "for each child" and "for each parent" equally fast? If "for each parent" is slower, try this:

for each node p
  for each child c1 of p
     for each child c2 of p
       if (c1 != c2)
         insert edge (c1,c2)

EDIT: The above version creates a different result, a list of siblings. Now for another approach...

for each node c
  ps:=c.parents()
  for each p1 in ps
     for each p2 in ps
       if (p1 != p2)
         insert edge (p1,p2)


问:
How can I deal with the cargo-cult programming attitude?
I have some computer science students in a compulsory introductory programming course who see a programming language as a set of magic spells, which must be cast in order to achieve some effect (instead of seeing it as a flexible medium for expressing their idea of solution).

They tend to copy-paste code from previous, similar-looking assignments without considering the essence of the problem.

Are there some exercises or analogies to make these students more confident that they can, and should, understand the structure and meaning of each piece of code they write?

答:
I would like to point out teacher problem, with an intuitive seeing.

An actor (cinema) is someone with bankable image (able to sell it), a star for everybody look at it.

An actor (theater) is someone with skill ability to put itself in the author's roles, to shadow its ego behind his knowledge to give some part itself.

To enrich (with science and knowledge) your students you have to live in course like a theater's actor.

You need, beyond a solid technical knowledge, to give something from you : you are not a graduate/technical man knowing all about the informatic subject bound to delivery sentence like a book,

...  but a man with experience (a possible begining of intuition) with a panel of courses and exercices sharing experience and live knowledge.

Then you can demand to your students to have the same approach : not buy knowledge/grade, but assimilate a language and hability to master it, do something that you cannot copy/past, but which links spirit at job.

All tips given above are useless or not : are you able to be self confident, do you have guru/theater like mastery.
To reach this level, theater's courses may give you the pawl/spark. A good way to "know yourself" not in procedural manner.

The problem : it is up to you : you have to leave your seat, have consciousness of your body and space and other techniques, want to go deeper in language (what is beyong words, methods)

... a 'work' for all your live, with creativity skill.
... or not : all this 'work' for 5% of my job? (so, ask you what is "being alive") ...

In hope it is English readable,

Claude


答:
Some companies lay claim to the work you've done out of hours too. It depends on the company, some of them are big on IP control.

Everything should be down in your contract. The worry is if they lay claim to your freetime work, which has been a horror of mine.


答:
Try substracting:

```<code>surroundings = list[]

for each node p
  for each child c1 of p
    for each child c2 of c1
      if c2 not in surroundings
        surroundings->add(c2) # Add everything, don't mind if it's on the border or inside.
    if c1 in surroundings
      surroundings->remove(c1) # Remove what's not on the border.
  if p in surroundings
    surroundings->remove(p) # Remove the initial node.

for each node border in list
  # Do whatever you want.
</code>```

I'm sorry, I don't think you'll find anything smaller than an algorith in O(n³).

Title: Algorithm for searching the neighbors neighbor of a directed graph

Body:
Is there an algorithm to search a directed graph (tree) for its neighbors neighbor?

My current brute-force solution works as follows:

```<code>for each node n:
   for each child c of n
      for each parent p of c
         if (p != n)
           insert edge (p,n)
</code>```

I am dealing with ca. 700.000 nodes each having between 1 to 1000 edges and currently I am facing too long running times: which is mainly due to the reason I am executing this algorithm on a graph database, since it would require too much memory.

Body:
Try substracting:

surroundings = list[]

for each node p
  for each child c1 of p
    for each child c2 of c1
      if c2 not in surroundings
        surroundings->add(c2) # Add everything, don't mind if it's on the border or inside.
    if c1 in surroundings
      surroundings->remove(c1) # Remove what's not on the border.
  if p in surroundings
    surroundings->remove(p) # Remove the initial node.

for each node border in list
  # Do whatever you want.

I'm sorry, I don't think you'll find anything smaller than an algorith in O(n³).


问:
What is the difference between the "lib" and "vendor" folders?
Regarding source folder hierarchy, there are always some common features, such as the src, doc or test folders, which have rather easy-to-understand contents.

However, I realized that big projects have both a lib and vendor folders, while I had always thought they were the same, as their names hint at including “third-party libraries from external vendors”. Though, seeing both in the same project means there is a difference.

I couldn't find any information nor on Google nor on sources such as the Filesystem Hierarchy Standard, even though this is actually a somehow common practice.

Here is a more detailed example with Symfony: once you create a project, you get a lib folder at the root of your project. In this folder, the following structure is found:

```<code>lib
+--filter
+--form
+--…
+--vendor
    +--simpletest
    +--symfony
</code>```

Here, the symfony folder contains all Symfony's core.

答:
Generalizing @WayneM's answer but not daring to edit it so much.

So, it seems this structure can be observed in application frameworks (Rails and Symfony at least).

It is a way to keep the lib / src structure intact for application developers, while adding the other level of distance brought by the use of a framework: the vendor folder actually contains the framework's libraries, leaving the lib folder for the application's included libraries, and src for its source files.

It is a “more distant” lib, vital since without the framework, the application is useless, but not to be touched by the application's developer: it is the framework vendor's libraries.