答:
You have right direction in choosing MVVM design pattern for WPF application.

```<code>Do I put the Models in the Domain layer?
</code>```

Yes, your models can be placed in domain

```<code>Where would I put my Repository and mappings of DB Object to Domain Object?
</code>```

Your repositories can be placed in the layer where your Domain is placed. Your mapping objects (also called DTOs - domain transfer objects) should be placed in your service layer and you may use a powerful mapping tool AutoMapper to easily map your domain objects to DTOs.

```<code>ViewModels also?
</code>```

Your ViewModels should be placed on your client side (layer). You may construct your viewmodels from one or more DTOs, depending on your views.

Regarding DDD , i would suggest to read about this and clarify to you really need to have Domain-Driven Design pattern. here is a discussion that 95% of all software applications fall into the “not so good for using DDD” categories.

Edit: reference has been added above, and thanks go for @Den!

Title: MVVM, DDD, and WPF Layered Application Project Structure Guidance

Body:
I am trying to setup my application's structure in VS and I want to "try" and future proof it to a reasonable level.  This application will be a WPF re-write of an old Winform app that had followed no conventions.  No Layers, Tiers, Acronyms, etc...

It is a fairly largish Enterprise Application.  I planned to use Linq To SQL as my DB's are and will most likely always be MS SQL.  Also I have an existing skill set with it.

I want to follow MVVM and DDD the best I can but I get confused on the structure of my application when combining these.  Let me try and illustrate with some examples.

When I follow MVVM my folder structure may look like this:

```<code>Views
Models
ViewModels
Helpers
</code>```

but how does that fit into a simplistic DDD layered approach where my Project Structure might resemble this:

```<code>MyApp.UI
MyApp.Domain
MyApp.Data
</code>```

Do I put the Models in the Domain layer or do I have 3 versions of say Person?  This leads to another question of where would I put my Repository and mappings of DB Object to Domain Object?  I would assume Data...

Views I get would go in UI but would ViewModels also?

Finally, where would I be embedding my Business Logic?

I found the following on CodePlex,DDD Example ,and it has been some help but seems to be for a Web App though that may not matter and is my ignorance shining through.

Don't get me wrong, I know I can have as many folders and call them whatever I want.  I am trying to figure out where to place things so that this will be scale-able, not what those places necessarily are called.

The heart of my question might be shown like this.

I have tblPerson object generated by *.dbml.  This is obvious and would belong in my "Data" layer.

Now I would have Model, DTO, Domain Model, or whatever it's called in a seperate Layer(project?) called Person.  I would need a Mapper for Person to tblPerson that I'm not sure where to put.

Then, I'll have a ViewModel for, say, EditPerson that would have it's own properties that it pulls from Person but possibly more as well.

Finally I'd have a View that was bound to that ViewModel....

To be clear that paragraph is FILLED with my assumptions and guesses and I am hoping someone will help clear the air for me or offer there insights so that 6 months to a year from now I am not kicking myself more than I need to.

Body:
You have right direction in choosing MVVM design pattern for WPF application.

Do I put the Models in the Domain layer?

Yes, your models can be placed in domain

Where would I put my Repository and mappings of DB Object to Domain Object?

Your repositories can be placed in the layer where your Domain is placed. Your mapping objects (also called DTOs - domain transfer objects) should be placed in your service layer and you may use a powerful mapping tool AutoMapper to easily map your domain objects to DTOs.

ViewModels also?

Your ViewModels should be placed on your client side (layer). You may construct your viewmodels from one or more DTOs, depending on your views.

Regarding DDD , i would suggest to read about this and clarify to you really need to have Domain-Driven Design pattern. here is a discussion that 95% of all software applications fall into the “not so good for using DDD” categories.

Edit: reference has been added above, and thanks go for @Den!


问:
Working on multiple things at work?
I was curious to know, if juggling between 2-3 projects at a time is a good or a common practice or not. When I say, 2-3 projects I mean:

1. 1 primary project,

2. 1 project with minor improvements/changes and

3. 1 project which comes at times for bug fixes

So essentially, I find my self generally working on 2 projects in parallel and sometimes the 3rd one comes in with a trivial fix.

Is this a problem? Or I should be learning to work on multiple projects at any given time. My personal opinion is, this style of work might affect how detailed and in-depth you think about a project.

答:
This is a pretty common case. We are developing, supporting(bug fixes), enhancing, etc. projects.

While 'juggling' these projects it is more than important to get prioritization (order of importance)) and planning of a daily work load.

The Project Manager have to identify these priorities and tell to the team or individual developer. If there is NO prioritization of work load, i would suggest to communicate and identify them as soon as possible.

ContentLicense: CC BY-SA 3.0

Title: Working on multiple things at work?


问:
Allocation problem identification
I have a matrix.  I have a list of people who have to occupy n1,n2,n3 etc cells, different number of cells in different rows.  I have to place the people in the cells.  Occupying the same cell across rows is considered overlap.  Overlap has to be minimized.

I have people referring to this variously as an optimization problem, an allocation problem and even linear programming.

I need to first get a consensus on what is this class of problem called.

Second, I need to know what an efficient solution should look like, in terms of the big-o notation or anything else.

Here is an example:

There is a board of 4 x 4 cells.  There are many pieces each of one color (R, G, B).  Each color peice has to fill a number of columns in each row.  A possible example:

```<code>      Row1   Row2   Row3   Row4
Red      1      2      3      2
Blue     2      2      0      0
Green    1      0      1      2
</code>```

That is the input.  The input arrangement could be different but it occupies the entire board... no cell is left blank.

The count of same color pieces occupying a COLUMN should be minimized.  One possible (bad) arrangement based on the input is this:

```<code>    1    2    3    4
1   r    b    b    g
2   r    r    b    b
3   r    r    r    g
4   r    r    g    g
</code>```

This is bad because it actually maximises the count of colors in the same column.  A better arrangement is like this:

```<code>    1    2    3    4
1   r    b    b    g
2   b    r    r    b
3   g    r    r    r
4   r    g    g    r
</code>```

Overlap is unavoidable, but should be minimized, and provably so.  I dont know if there is only one best solution or if there could be many solutions.  Even if there could be many solutions, we need to come up with just one.

As I think about it more, it looks like a loose version of eight-queens problem.  I am getting worried because I keep seeing recursion and back-tracking.

EDIT 1:

I am thinking a relaxed version of sudoku puzzle generation.

答:
I think that a linear time solution might be possible. This is because your number of colours and the width of the matrix are fixed. It reminds me of both a packing problem and a graph colouring problem (both are NP-Complete).

Consider that the optimum arrangement for any colour looks similar to an identity matrix (where 1 represents that colour and 0 represents one of the others). Then simply arrange in this fashion. For example, place the first red in the first column. Then for each next red, simply place it in the next column (modulo 4). Then repeat this process for the other two colours. This simple rotating arrangement should yield the optimal solution, I believe, as it always minimizes the duplication for each insertion.

Title: Allocation problem identification


问:
Application Logic Vs DB Triggers for database cleaning
When cleaning out old data from a set of database tables, is it safer to have the logic in the application or in a database trigger?

I am upgrading an application that I wrote a while back (and in a hurried fashion) and one of the things I want to clean up first is ensuring that data which is no longer being used is propmtly deleted. Currently this is being done in my application itself via a number of SQL calls to various tables. Some of these queries take a bit of time to run and as the application is PHP driven, I don't want users having to wait too long.

I was therefore thinking about creating a database trigger on one table that would merrily clean up all the other tables and then allow the single row delete to occur from my master table.

I am considering these pros and cons at the moment:

Database trigger

(+) Invisible to the application

(+) Simplifies application logic - new objects can be simplified

(-) Adds complexity to overall maintenance - have to maintain code and triggers during table changes etc.

Application Logic

(+) Keeps all maintenance tasks in one place

(-) Longer page loads on certain tasks

(-) More chance of a request timing out - orphaning data

If you have any further insight, considerations I haven't thought of here, experience with one vs the other or can point me towards some reading on the matter I would love to hear it.

Edit: I originally thought that my pages would run quicker, but if I am creating a Before Delete trigger, will the page loads be the same - as in the application sends a tiny query through but it won't be actioned until the entire set of statements in the trigger complete?

答:
In the case of archiving or deleting old or obsolete data, would you consider a third option, i.e. a scheduled batch job, which detects and deletes old data. The job could then be scheduled e.g. once per day at a relatively quiet time, thus having minimal impact on your application. The job could be part of other standard database jobs, e.g. OPTIMIZE / reindexing etc.

The one exception to this could be if. e.g. you are updating a 2 tables with a 1 : many relationship (e.g. Invoice and InvoiceLineItem), whereby you've decided to delete all existing invoice line items before inserting the new ones. Because the deletion is deterministic (you know exactly what you need to delete), and because you also want the deletion to be part of a larger transaction which includes the subsequent inserts, then I would say that this would be a good candidate for the application tier.

However, I cannot see the purpose of doing this in a trigger at all - this could cause unnecessary performance loss for your inserts / updates while your trigger searches for stale data, and then locks unrelated rows elsewhere after deleting them.


问:
What non-programming books should a programmer read to help develop programming/thinking skills?
There are a lot of questions about what programming books should be on the programmer's bookshelf. How about non-programming related books that can help you become a better programmer or developer? It would also be interesting to know why they would help.

My first choice would be Sun Tzu's "Art of War" (however cliché), because it made it obvious that the success of any project depends on the strength of its weakest link (and warfare is a big project).

答:
The Art of War
Sun Tzu

ContentLicense: CC BY-SA 2.5

Body:
The Art of War
Sun Tzu


问:
Implenting ActiveRecord with inheritance?
I recently converted an old application that was using XML files as the data store to use SQL instead. To avoid a lot of changes I basically created ActiveRecord style classes that inherited from the original business objects.

For example

```<code>SomeClassRecord :SomeClass
//ID Property
//Save method
</code>```

I then used this new class in place of the other one, because of polymorphism I didn't need to change any methods that took SomeClass as a parameter.

Would this be considered 'Bad'? What would be a better alternative?

答:
In no way is this is not a 'bad' thing to do. What you did is akin to the decorator pattern.  http://www.dofactory.com/Patterns/PatternDecorator.aspx

In fact I suggest that you do read up on the decorator pattern as its a useful tool to have in your design arsenal.


问:
Would this constitute MVC - even in a very loose sense?
I've been working on a kind of CRM for the sales guys in our office - not as a job role but as a spare time task type of thing - I don't claim to be a developer or anything like that, but I would definitely like to pursue a career as a web developer down the line, I just think I need a much stronger understanding of OOP principles and design patterns such as MVC before I could even consider it.

Basically the way I've developed it each section of the App is a html page, that uses jQuery to listen for events, which then sends ajax requests to the server, which are then redirected to class methods that will perform usually simple CRUD tasks, and send back a JSON response to the client which will then be reflected on the page - would that constitute mvc even in a loose sense, as presentation is completely seperate from things like database interaction and theres a go-between to interact between the two?

Like I say i'm in the very early stages of grappling the comprehension of MVC as a whole so any thoughts would be appreciated, thanks.

答:
Your solution is not classical MVC in my opinion, it's far better. What you have, my young Padawan, is more like a SOA approach.

I personally like this style of architecture. In the Business Logic Tier, the Service-Oriented Architecture (SOA) message is being heard. With its loose coupling and removal of implicit dependencies, the SOA model yields flexibility and uniformity through the specification of a definite Service Interface, which hides domain models and implementation technologies.

Unfortunately, no such clear architectural blueprint exists for the Presentation Tier. What does industry best practice say about developing the front-end of an application? What is the best way to connect the front-end neatly into the Service Interface?

Classical MVC suffers (imho) from at least three major architectural flaws:

It does not respect data, the data sent across the wire is highly presentation-oriented, marked-up data.

Data interchange and presentation logic are tightly coupled. It is not possible to move through the steps of the Presentation Flow without initiating what amounts to Data Interchange operations. Web pages are displayed in response to GET and POST requests sent by the browser. Even worse, every Data Interchange operation initiated by the browser willy-nilly forces a Presentation Flow. An infamous result of this tight coupling is the "browser back-button problem".

The third flaw is that the web model is request/response. It does not support peer-to-peer interaction styles that are required for server event notification.

At this juncture, one would be tempted to conclude that AJAX is the answer to these problems. Unfortunately, AJAX itself is just a raw capability and not a prescriptive model. It is possible to use AJAX and still come up with a horrible hybrid model where the web server continues to drive Presentation Flow in response to Data Interchange operations, and the AJAX interaction just hangs off to one side, so to speak.

The one model, that helps me most, is nevertheless based on MVC. MVC on server side, and on client side. The view on the server is the model in the client application, so to speak. An illustration:

Your application seems to follow this principle roughly. You probably had a hard time to come up with a good structure in your HTML and JS. Try to look at it with this approach. Your client Model is the server side view, your JSON data. Your event bindings and stuff is your Controller. The HTML is your View. Try to separate events and UI logic from data interchange, and you will find a very powerful way of creating web applications.


问:
Inheritance using non-abstract base class
This post is based on the question https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance/11758048#comment15634305_11758048.

Some people said - check whether there is “is-a” relationship. If it is there use inheritance. What I think is there should be a second check for using inheritance. Use inheritance only if the base class is abstract. If the base class need to be instantiated then use composition; not inheritance.

E.g 1. Accountant is an Employee. But I will not use inheritance because a Employee object can be instantiated. (When you talk to business people, they will tell you - Accountant is an Employee. But in OO world Accountant is not (should not be) an employee)

E.g 2. Book is a SellingItem. A SellingItem cannot be instantiated - it is abstract concept. Hence I will use inheritance. The SellingItem is an abstract base class (or interface in C#)

What I am looking for here is an example that will challenge my argument –that is a scenario in which inheritance is better than composition even though the base class is non-abstract (base class can be instantiated). Can you please provide such an example?

Note: It would be more helpful if you can provide a scenario based on Bank domain, HR domain, Retail domain or any other popular domain.

Note: In the design, please assume that we have full control of the code. That is we are not using any external API. Also we are starting from beginning.

I will mark as answered if there is an example that explains a scenario that proves my argument is wrong. It is not a mere discussion on whether to use Composition or Inheritance.

I support @anon answer in https://stackoverflow.com/questions/3351666/why-use-inheritance-at-all?lq=1

The main reason for using inheritance is not as a form of composition - it is so you can get polymorphic behaviour. If you don't need polymorphism, you probably should not be using inheritance.

@MatthieuM. says in Code Smell: Inheritance Abuse

The issue with inheritance is that it can be used for two orthogonal purposes:

interface (for polymorphism)

implementation (for code reuse)

REFERENCE

Employee- Accountant Example https://stackoverflow.com/questions/11759120/issue-in-using-composition-for-is-a-relationship

Selling Item Example  - https://codereview.stackexchange.com/questions/14077/is-it-proper-tpt-inheritance

Programming SOLID Principles

Code Smell: Inheritance Abuse

答:
Although you mentioned in a comment it's not the talk about "composition vs inheritance", I have to return to it. Because composition is better than inheritance If we assume that decoupling is always a good thing (Prefer composition to inheritance?).

Actually it is not always the case. Even if you see that "is a" can be replaced with "has a" or "has a" looks more promising, "is a" has a very nice automatic properties.

Consider any widget hierarchy. Usually everything related to dimension is buried deep at the root. And no matter how long the inheritance path, you can always directly call SetBounds of the instance and pass the instance to a procedure that expects deep base object, the compiler will accept it because from "is a" comes automatic type conversion and access.

But if you convert the inheritance hierarchy into composition hierarchy (technically it is always possible), you will lose convenience in both cases, because you should point to the concrete piece of composition tree in order to change the dimension or provide a procedure with particular class type. Compare

```<code> MyForm.SetBounds(...  // easy because of an "is a"-tree
 MyForm.ScrollingWinControl.WinControl.Control.SetBounds  //complex because of a "has a"-tree
</code>```

or

```<code> GetSomeInfoOfControl(MyForm) // easy ...
 GetSomeInfoOfControl(MyForm.ScrollingWinControl.WinControl.Control) //complex ...
</code>```

So despite the price of stronger coupling, inheritance sometimes is much easy to manage and abstract.

Body:
Although you mentioned in a comment it's not the talk about "composition vs inheritance", I have to return to it. Because composition is better than inheritance If we assume that decoupling is always a good thing (Prefer composition to inheritance?).

Actually it is not always the case. Even if you see that "is a" can be replaced with "has a" or "has a" looks more promising, "is a" has a very nice automatic properties.

Consider any widget hierarchy. Usually everything related to dimension is buried deep at the root. And no matter how long the inheritance path, you can always directly call SetBounds of the instance and pass the instance to a procedure that expects deep base object, the compiler will accept it because from "is a" comes automatic type conversion and access.

But if you convert the inheritance hierarchy into composition hierarchy (technically it is always possible), you will lose convenience in both cases, because you should point to the concrete piece of composition tree in order to change the dimension or provide a procedure with particular class type. Compare

 MyForm.SetBounds(...  // easy because of an "is a"-tree
 MyForm.ScrollingWinControl.WinControl.Control.SetBounds  //complex because of a "has a"-tree

or

 GetSomeInfoOfControl(MyForm) // easy ...
 GetSomeInfoOfControl(MyForm.ScrollingWinControl.WinControl.Control) //complex ...

So despite the price of stronger coupling, inheritance sometimes is much easy to manage and abstract.


问:
EE vs Computer Science: Effect on Developers' Approaches, Styles?
Are there any systematic differences between software developers (sw engineers, architect, whatever job title) with an electronics or other engineering background, compared to those who entered the profession through computer science?

By electronics background, I mean an EE degree, or a self-taught electronics tinkerer, other types of engineers and experimental physicists.

I'm wondering if coming into the software-making professions from a strong knowledge of flip flops, tristate buffers, clock edge rise times and so forth, usually leads to a distinct approach to problems, mindsets, or superior skills at certain specialties and lack of skills at others, when compared to the computer science types who are full of concepts like abstract data types, object orientation, database normalization, who speak of "closures" in programming languages - things that make little sense to the soldering iron crowd until they learn enough programming.

The real world, I'm sure, offers a wild range of individual exceptions, but for the most part, can you say there are overall differences?   Would these have hiring implications e.g. (to make up something) "never hire an electron wrangler to do database design"?   Could knowing about any differences help job seekers find something appropriate more effectively?   Or provide enlightenment or some practical advice for those who find themselves misfits in a particular job role?

(Btw, I've never taken any computer science classes; my impression of exactly what they cover is fuzzy.   I'm an electronics/physics/art type, myself.)

答:
I started out with a BSEE, went to work designing logic circuits for a large telephone R&D lab, and (this was some 40 years ago) realized most of what I was building could eventually be done with a computer program. So I went back and got an MSCS degree.

I have always been interested in computer architecture, and what happens at the hardware level.  Most of my career has been spent designing embedded microcontroller systems, where I try to find the best match between what is done in hardware and what is done in firmware.  However, I've done quite a bit of web programming, and some database design.

Without my background in CS, I think I would have a lot more trouble grasping more abstract concepts.   Besides many different assembler languages, I have used C, C++, C#, Pascal, Delphi, Perl, PHP, and some Lisp.  I am currently trying to learn Ruby and Python.  OO design I am pretty comfortable with.  Functional programming I am not (yet).

Same for databases.  I understand normalization.  I have trouble with some of the more esoteric JOINs and avoid them.  I'm not really comfortable with something unless I understand what is going on under the hood.

I want to be able to "see" how the computer would run the program in my head.


问:
Should we ever delete data in a database?
I am new to databases and trying to understand the basic concepts. I have learned how to delete data in a database.  But one of my friends told me that you should never delete data in a database.  Rather, when its no longer needed, it's better to simply mark it or flag it as 'not in use'.

Is that true? If so, how would a big company like IBM handle their data for a hundred or more years?

答:
Another situation than others presented is when data is deleted, but logs of operations done in the database (deletion included) are stored in archives for a long period of time. The main scope of this is implementing a rollback system to past dates, but it can also be used to store in some way deleted data (which is deleted from database, but stored in archives).

Storing archives of deleted data wouldn't be such a big deals. Big companies may also store versions of code and many more information (not to talk about non-technical related stuff) so in the end storing large data is something usual for them.


问:
Is restricting sessions to an absolute IP likely to have a wide impact on mobile networks?
Our website currently restricts a cookie-based session to the IP address that was originally sent the Set-Cookie HTTP header. In the past a user's IP would rarely change, so this didn't present much inconvenience. However, some of our clients accessing via 3G devices are experiencing session failures due to this IP restriction.

I know little about the network infrastructure used for mobile networks. Do the majority of providers attempt to route connections to a common public IP in order to maintain compatibility with websites like ours, or should I consider restricting sessions to an IP range instead?

答:
I'm not sure is it a need to tight the IP address to the specific user, unless you need the verification during online payment transaction or other critical operation. If you are going to store it permanently, it make no sense as the IP was dynamic.

Furthermore, if you talking about mobile IP, they are high frequent changer - the IP keep changing when you move around. You may try it out at any geo tracking site, e.g. http://www.ip2location.com, check your IP while you move around.

OwnerDisplayName: tjbp


答:
Looks more like a 3-tier system, where the view tier is client-side, the business-logic tier is in the services and data storage is in the RDBM. (MVC evolved out of 3-tier/3-layer designs)

You should know that MVC is just a very popular buzzword right now, like 3-tier or n-tier used to be up until 3-5 years ago. Don't try to put it on your resume just so it looks like everyone else's. N-tier app looks cooler for big enterprisie teams :)

Title: Would this constitute MVC - even in a very loose sense?

Body:
I've been working on a kind of CRM for the sales guys in our office - not as a job role but as a spare time task type of thing - I don't claim to be a developer or anything like that, but I would definitely like to pursue a career as a web developer down the line, I just think I need a much stronger understanding of OOP principles and design patterns such as MVC before I could even consider it.

Basically the way I've developed it each section of the App is a html page, that uses jQuery to listen for events, which then sends ajax requests to the server, which are then redirected to class methods that will perform usually simple CRUD tasks, and send back a JSON response to the client which will then be reflected on the page - would that constitute mvc even in a loose sense, as presentation is completely seperate from things like database interaction and theres a go-between to interact between the two?

Like I say i'm in the very early stages of grappling the comprehension of MVC as a whole so any thoughts would be appreciated, thanks.


答:
There have already been plenty of good answers to this that pretty much boil down to "Depends on the circumstance", and I can't add anything to those.

One thing that hasn't been mentioned, however, that I think needs to be mentioned, is that you should never ever reuse primary keys that have been generated by a sequence or an AUTO_INCREMENT system.

When you delete an item that had been assigned a primary key by such a system there will be gaps in the primary key column, left by the deleted data.  There is a great temptation to reassign those gaps to new items as they're added, or even worse, to shuffle the existing data to give it a new ID to remove the gaps, but doing so will give rise to issues that you'd never have to deal with if you just left the keys alone.

Say you're keeping a database of printers for managing reordering consumables.  Printer 13, an old laser printer, breaks down beyond economic repair so you throw it out.  Meanwhile, for an unrelated reason, someone orders a new thermal printer for doing barcode printing in the warehouse, and that printer happens to arrive before the replacement for printer 13.  The administrator logs that new printer into the database and, because 13 is now free and you're recycling IDs, the new thermal printer gets allocated 13 as its ID.

Now someone tells you that printer 13 is almost out of ink.  You remember that printer 13 is a laser printer so you don't bother looking it up in the database, and you place an order for a toner cartridge.  Only you actually needed to order a thermal ink pack because printer 13 isn't a laser printer anymore.  When the toner cartridge arrives you can't use it because it's the wrong ink refill for the printer, you can't print out any more bar codes and you can't ship any orders waiting to be dispatched.

Even worse, what happens if you delete printer 13 and shuffle all the printers that come after it down to fill the gap?  Printer 14 (some decrepit old dot matrix) becomes printer 13, printer 15 becomes printer 14 and so on.

All the printers have labels on them so they can be cross-referenced with the database, but now all the labels are out of date.  You'll have to go round, locate every printer in the business (which could run into hundreds!) and relabel them.  That's hardly an effective use of time.  And it's also an error-prone process, and what happens if it just never gets done?  Someone calls in to say printer 14 has broken down and needs fixing urgently, so you look it up and find that printer 14 is an inkjet printer in Reception.  Only because you've shuffled the IDs around, it's actually the dot matrix printer that needs fixing urgently.  The guy who called in the problem is left hanging, whilst the receptionist has a tech support guy she never called for turn up to fix a printer which wasn't broken.

You should think of IDs assigned by an auto-increment system as permanent, they're immutable and can't be reused, even if the thing that the ID refers to ceases to exist.  Some people claim that they don't want to have to worry about IDs running out, but even with 32 bit systems and signed IDs, there's still 2 billion or so IDs available.  If you can make the ID column unsigned then this doubles to 4 billion, and on 64 bit systems the number of available IDs is literally greater than the number of stars in the sky.  You're not going to run out of IDs.

Title: Should we ever delete data in a database?

Body:
I am new to databases and trying to understand the basic concepts. I have learned how to delete data in a database.  But one of my friends told me that you should never delete data in a database.  Rather, when its no longer needed, it's better to simply mark it or flag it as 'not in use'.

Is that true? If so, how would a big company like IBM handle their data for a hundred or more years?


问:
What is agile methodology?
Can any one explain about the agile methodology in simple sentences?</p>

答:
I think nothing puts it better than the Agile Manifesto itself:

We are uncovering better ways of developing

software by doing it and helping others do it.

Through this work we have come to value:

Individuals and interactions over processes and tools

Working software over comprehensive documentation

Customer collaboration over contract negotiation

Responding to change over following a plan

That is, while there is value in the items on

the right, we value the items on the left more.

from http://agilemanifesto.org/

Title: What is agile methodology?


问:
What should one consider in choosing a language for web application development?
To begin with, this isn't a question about which language one should choose :)

We're considering a language switch as our general direction is changing from content-driven web sites to data/action-driven web applications.

What sort of factors should one think about in order to successfully evaluate the various languages out there.

A few factors I've thought of so far, along with a supposed importance level:

Level of knowledge of language X within the company [medium/high]

Tooling available [medium]

Community size & activity [medium]

Availability of developers [medium]

Cost of developers [medium]

Frameworks are also an important consideration, however I'm just trying to focus on the language-selection question first :)

答: I would also take into account the possibility of hosting your applications or deploying them in a cloud (so I would recommend checking which languages and frameworks are supported by the biggest cloud vendors). Also an important factor to consider would be non-functional requirements, the size of your applications and the number of developers working on them.</p>


答:
You've listed everything but the most important: which language provides features that are most necessary for the very project you will work on.

This is sometimes more important. You could find many excellent developers and make them struggle with the language of your choice to implement the features required. Or you could hire fewer developers maybe with less experience, but who would get the project done since the language they're using provides everything necessary.

My boss always says that the problem should determine the technology to use, and not vice versa. We've had a bad experience in the company I work in. We had a brilliant developer who was trusted a big piece of the project. He chose the technology he knew best, and failed. His failure cost the company about 6 months and a lot of money.

Title: What should one consider in choosing a language for web application development?

Body:
To begin with, this isn't a question about which language one should choose :)

We're considering a language switch as our general direction is changing from content-driven web sites to data/action-driven web applications.

What sort of factors should one think about in order to successfully evaluate the various languages out there.

A few factors I've thought of so far, along with a supposed importance level:

Level of knowledge of language X within the company [medium/high]

Tooling available [medium]

Community size & activity [medium]

Availability of developers [medium]

Cost of developers [medium]

Frameworks are also an important consideration, however I'm just trying to focus on the language-selection question first :)


答:
Tooling (very high)

Community (very high)

Learning curve (very high; if a system has a high barrier to entry it can't be good for new people)

Level of knowledge in the company (medium-low; if the top 3 are met, you won't have problems here)

Hype (medium; can be good for recruiting)

Availability of developers (medium-low; is usually dictated by hype & community)

Cost of developers (medium-low; if everything else is fine the boss will pay more for developers)


答:
For me personally this is the ideal working scenario. With one condition: that I can choose when to work on what project for how many time. This gives me the opportunity to do the work I  am in the mood for!

For example, I have 2 projects to work on, one is new and one is old.

I start in the morning on the most recent project, because in the morning I am the most fresh in my mind, and I am highly productive. Somewhere after lunch I get stuck in a very tough problem to solve. After trying to come up with a solution for an hour, I am losing my concentration. Now it is ideal to move this forward to the next day, so I can look at it fresh, with new energy. The remaining time of the day can be filled with fixing easy bugs at the old project.

This is for me the most productive way of working, the flexibility to choose between different types of work depending on my mood, level of energy and concentration.

As other questions point out, it can also be counter-productive, but I think this mainly depends on the condition I pose at the start of my answer.

Bottom line is, you have to figure out what works best for you. Maybe you are really good at switching between tasks, which gives you a benefit above other developers. If you are not good at switching, try to minimize the switching by planning your work very carefully.

It all depends on what you are good at, and when you figure that out, try to adapt your working methods towards that.

Title: Working on multiple things at work?

Body:
I was curious to know, if juggling between 2-3 projects at a time is a good or a common practice or not. When I say, 2-3 projects I mean:

1. 1 primary project,

2. 1 project with minor improvements/changes and

3. 1 project which comes at times for bug fixes

So essentially, I find my self generally working on 2 projects in parallel and sometimes the 3rd one comes in with a trivial fix.

Is this a problem? Or I should be learning to work on multiple projects at any given time. My personal opinion is, this style of work might affect how detailed and in-depth you think about a project.


问:
Is this RabbitMQ / sockjs pub/sub connection setup a comet solution?
My company is attempting to set up a pub/sub connection using RabbitMQ and sockjs, on Windows servers. I have two questions:

My supervisor is calling this setup a comet solution, I was wondering if that is the right terminology?

Is there a better solution stack for having a data server asynchronously ship data to a client without the client requesting data (besides the initial subscription)?

答:
'Comet' is an approach that allows simulating push-style network communication over a stateless request-response protocol, typically HTTP. It is a solution to the problem that an HTTP server cannot actively push messages to a client - the only way for the server to get data to the client is to respond to a request.

The comet approach uses 'long polling' to achieve data pushes; it works like this:

client sends request to server, with a very long timeout

server keeps connection open, but doesn't respond immediately

as soon as the server wants to push something, it responds to the pending request

client, upon receiving and processing the response, immediately sends the next request

If this is what your solution does, then it's justified to call it a 'comet' solution.

The most prominent problem with comet-style communication is that the server must be prepared to keep a massive amount of requests open simultaneously - if you have 1000 users logged into your site, you will have 1000 pending requests, all the time. Also, timeouts and network issues (dropped connections etc.) can make comet solutions quite unreliable.

As for alternatives:

you can compromise on heartbeat-style short polling (client sends a heartbeat every x seconds, server responds with any available data)

you can try WebSockets, although browser support isn't ideal

you can decide step off the web platform and build a desktop application instead

you can find a browser plugin that provides asynchronous server-push communication


答:
What I am looking for here is an example that will challenge my argument

Examples abound:

Buttons. In many GUI frameworks, View is not an abstract class -- you can and often do create vanilla views. But there are also plenty of subclasses of View, such as Button.

Mutable objects. Some frameworks, e.g. Cocoa, have data container classes that are immutable (NSArray, NSString, NSDictionary, etc.) and also mutable subclasses of those (NSMutableArray, NSMutableString, etc.). You can do anything to an instance of NSMutableArray that you can do to an instance of NSArray, and then some.

Employee. Borrowing from your Accountant example, its likely that an Employee class might be a subclass of Person, but there's no reason that Person needs to be abstract.

Accountant. Your example is often given to illustrate how composition can/should be used in place of inheritance, but that doesn't mean that composition is always the best choice in this case. Yes, you can create an accountant by separating the 'job' aspects from the 'employee' and then configuring an instance of Employee with a particular job. But there may be good reasons to use inheritance instead. An accountant isn't just an employee who happens to crunch numbers; an accountant is a particular kind of employee, and you may want to use inheritance to reflect that. For example, you might want the Accountant class to implement a ProfessionalStanding interface or to include functionality that helps detect conflicts of interest. Also, creating an Accountant class makes it possible to use the language's type system to help prevent employees who aren't accountants from being used in roles where only an accountant should be used: Project::addAuditor(Accountant& a);

The decision to use or not use inheritance has little to do with whether a class is abstract. It's the other way around, actually: abstract classes are used to force you to create a subclass, generally to ensure that important missing functionality is provided. The fact that you can instantiate a class certainly doesn't mean that you should avoid subclassing.

Title: Inheritance using non-abstract base class

Body:
This post is based on the question https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance/11758048#comment15634305_11758048.

Some people said - check whether there is “is-a” relationship. If it is there use inheritance. What I think is there should be a second check for using inheritance. Use inheritance only if the base class is abstract. If the base class need to be instantiated then use composition; not inheritance.

E.g 1. Accountant is an Employee. But I will not use inheritance because a Employee object can be instantiated. (When you talk to business people, they will tell you - Accountant is an Employee. But in OO world Accountant is not (should not be) an employee)

E.g 2. Book is a SellingItem. A SellingItem cannot be instantiated - it is abstract concept. Hence I will use inheritance. The SellingItem is an abstract base class (or interface in C#)

What I am looking for here is an example that will challenge my argument –that is a scenario in which inheritance is better than composition even though the base class is non-abstract (base class can be instantiated). Can you please provide such an example?

Note: It would be more helpful if you can provide a scenario based on Bank domain, HR domain, Retail domain or any other popular domain.

Note: In the design, please assume that we have full control of the code. That is we are not using any external API. Also we are starting from beginning.

I will mark as answered if there is an example that explains a scenario that proves my argument is wrong. It is not a mere discussion on whether to use Composition or Inheritance.

I support @anon answer in https://stackoverflow.com/questions/3351666/why-use-inheritance-at-all?lq=1

The main reason for using inheritance is not as a form of composition - it is so you can get polymorphic behaviour. If you don't need polymorphism, you probably should not be using inheritance.

@MatthieuM. says in Code Smell: Inheritance Abuse

The issue with inheritance is that it can be used for two orthogonal purposes:

interface (for polymorphism)

implementation (for code reuse)

REFERENCE

Employee- Accountant Example https://stackoverflow.com/questions/11759120/issue-in-using-composition-for-is-a-relationship

Selling Item Example  - https://codereview.stackexchange.com/questions/14077/is-it-proper-tpt-inheritance

Programming SOLID Principles

Code Smell: Inheritance Abuse


答:
I'd throw in:

Suitability for the problem at hand (Is the project web-centric? Does it use a lot of concurrency? Is real-time performance important? Is there a lot of number-crunching involved? Is it mainly transactional? etc.)

Overall quality of available tools and third-party libraries

Bindings for other technology (doesn't make sense to use a language that doesn't have any decent libraries for your choice DBMS)

Legal and licensing issues (not usually a problem, but licensing the tools can be a cost factor)

Platform support (even more important if you have to support multiple platforms, or want to be able to switch platforms down the road)

Integration with other systems (e.g., .NET works best if combined with other Microsoft technology; PHP and Apache go well together; etc.)

Paradigm support

Philosophy

Semantic properties (static vs. dynamic, etc.)

Maturity

Stability (Will your code break in 5 years? Will you be able to fix it?)

Quality of available programmers (it's easy to find a hundred PHP programmers, but about 95 of them will be incompetent; it's hard to round up 5 Lisp programmers, but those that you do find know their stuff)

Security - no programming language is inherently secure or insecure, but some provide more and better tools for secure programming than others; for example, avoiding XSS is much easier in Haskell (use the type system to distinguish between raw strings and HTML) than it is in PHP (remember to call htmlspecialchars appropriately)


答:
I would consider the following order as important factors before decision:

Learning curve - if your team finds it difficult to adopt and there is no good introductions and tutorial, better skip it

Active Community - around this technology/framework/language is very important, this is driving force

Tooling - how much productivity tools exist around it

Comfort level - of developers in a team or company

Availability of developer(s) who has experience and build some proto-types with this language/framework


答:
I've been working on an Foreign exchange application for a couple of years where this came up. The data that the application collected over the years had an impact on performance (say exponentional).

After we've done what we could in terms of code we proposed to the managegement to archive data older than a year. They verified the concept (legal issues) and luckily we were able to do it. So we deleted but we also archived the data so business could still run their reports etc.


答:
I faced a similar problem recently with a system I had designed. For security, upon logging in the user was assigned a hash, which was stored in a cookie. This was then verified against the record in the database on each request, and compared with their IP address to ensure it was the same user.

This worked fine for years, but as the users began to access the system via mobiles (or a laptop using a 3G dongle) they began to encounter problems.

In order to preserve battery life, mobiles will connect, download the web page, then close the connection. When the user clicks on a link, the mobile will then reconnect, download the page and close the connection again. As a result each request will have a different IP address. The same will happen if using a laptop over a 3G dongle, in this case there is often a setting in the properties to stop this behaviour, but very few if any users will have changed this away from the default behaviour.

As such it is no longer feasible to rely on the IP address to verify a users identity. I have since re-written the application to move this restriction.

Title: Is restricting sessions to an absolute IP likely to have a wide impact on mobile networks?

Body:
Our website currently restricts a cookie-based session to the IP address that was originally sent the Set-Cookie HTTP header. In the past a user's IP would rarely change, so this didn't present much inconvenience. However, some of our clients accessing via 3G devices are experiencing session failures due to this IP restriction.

I know little about the network infrastructure used for mobile networks. Do the majority of providers attempt to route connections to a common public IP in order to maintain compatibility with websites like ours, or should I consider restricting sessions to an IP range instead?


问:
Generating different combinations from a list of muscles
Suppose we have a model of a human muscular system containing the following muscles each within a specific muscle group:

Arms

Biceps

Triceps

Forearms

Torso Front

Abs

Chest

Shoulders

Torso Back

Trapezius

Lats

Rear Shoulders

Lower Back

Lower Body

Quads

Hams

Hip & Butt

Calves

Now, given a list of selected muscles, I need to find combinations following the given rules:

If all muscles are selected from a group:

```<code>Full body (All muscles)
Arms
Torso
Torso Front
Torso Back
Lower Body
</code>```

If there are full groups together:

```<code>Arms and torso
Arms and torso front
Arms and torso back
Arms and lower body
Torso and lower body
Torso front and lower body
Torso back and lower body
</code>```

When both the front and back of the torso is selected it can be considered just "torso".

If there are more than 2 muscles selected from a group but not all:

```<code>Parts of torso (This is the case where there are muscles selected from both front- and back-torso)
Parts of torso back
Parts of lower body
</code>```

"Parts of torso front" and "Parts of arms" never occur on their own as they only have a total of 3 muscles, thus those cases can be represented by their names: eg. "biceps and triceps", etc.

Combinations of these aforementioned "parts"

```<code>Parts of arms and torso
Parts of arms and lower body
Parts of torso and lower body
Parts of  arms, torso and lower body.
</code>```

Parts = groups are not full and there are more than 2 muscles selected. This "rule of 2" is the most important one.

Examples of output

biceps, triceps and chest: parts of arms and torso

biceps, triceps, calves, tai biceps, triceps, quads, hams, hip & butt: Parts of arms and lower body

biceps, abs, calves: Parts of arms, torso and lower body

biceps, triceps: Biceps and triceps

biceps, triceps, forearms: Arms

chest, shoulders, abs, trapezius, lats, rear shoulders, lower back: Torso

and so on, there are multiple possible variations.

Now my problem is that I have no idea how to write this as clean and modular as possible, so that rules can be added or removed if necessary.

I could just write a massive if-elseif-else pile that would consider all cases, but you know why I won't.

How would you tackle this kind of task?

答:
Here, briefly in Java :

if may be replaced by the Observable/Observer Pattern, more useful, stable and secure.

A type is defined in enum, each typeName of refer to an Observer, the ordinal() position in enum give the bit of the type [ordinalBitOfType].

A muscle have a set of one or more ordinalBitOfType

The Observable have a HashSet of ordinalBitOfType to request: enumType.ARMS.ordinal() and enumType.TORSO.ordinal()

Then it activates observers. All concerned Observers print "hello" and can update Map or something else in the Observable, others do nothing.

EDIT

In Observable/Observer Pattern only one if by Observer is needed to respond at : is myBit contained in the Observable.Set?

If you create New types, you have to create new Obervers, don't worry about already Observers jobs, they will work fine, just put the new bits in the right muscles.

You can had Observable Pattern in a Observer for nested if.

Take care, you cannot decide the order of the Observers called by the JVM.

EDIT 2 : some rewriting + O'Reilly book

The clearest book about Pattern design I've read : "Head First Design Patterns", encourage to master it.

EDIT 3

I open a second answer because I realize I was blinded by the if/then/else  problem, and also because Observable  instance passed to an Observer which can modify it, is a good pattern for limited and stable parameters to manage intricated ifs.


问:
How many types of programming languages are there?
Basically, I want to learn lots of programming languages to become a great programmer.  I know only a handful to depth and I was hoping someone could elaborate on how many classes or types of programming languages there are.  Like how you would lump them together if you had to learn them in groups.

Coming from a Java background, I'm familiar with static typing, but I know that in addition to dynamic typing there has to be such variety in available languages that I would love to see a categorical breakdown if possible.

答:
Click the image to see PDF.

You should look at Programming Paradigms for Dummies: What Every Programmer Should Know by Peter Van Roy. This will give you an overview about how it is going on outside.

If you want to go further, you can read Concepts, Techniques, and Models of Computer Programming. You will not learn a banch of languages by this way, but you will learn paradigms which lie behind different kinds of languages. So, learning a new language will be more easy for you.


答:
Create a class "MuscleGroup"

Init each object of that class with the list of muscles belonging to that class, and the name of the group

add a method PrintRelatedParts(SetOfMuscles som) to that class (SetOfMuscles should be some container type for the given input)

the method should count how many of the given muscles in som are in the muscle group. If there are 0, it prints nothing, if there are 1 or 2, it prints the names of the muscles, if there are more than 2, it prints "parts of ...", and if there are all muscles of that group, it prints just the name of the group.

add some logic to combine the output of all muscle group objects with "and" and ","

The essential decision you have to program here is just a decision between 4 cases, not a "massive if-elseif-else pile".

Title: Generating different combinations from a list of muscles

Body:
Suppose we have a model of a human muscular system containing the following muscles each within a specific muscle group:

Arms

Biceps

Triceps

Forearms

Torso Front

Abs

Chest

Shoulders

Torso Back

Trapezius

Lats

Rear Shoulders

Lower Back

Lower Body

Quads

Hams

Hip & Butt

Calves

Now, given a list of selected muscles, I need to find combinations following the given rules:

If all muscles are selected from a group:

```<code>Full body (All muscles)
Arms
Torso
Torso Front
Torso Back
Lower Body
</code>```

If there are full groups together:

```<code>Arms and torso
Arms and torso front
Arms and torso back
Arms and lower body
Torso and lower body
Torso front and lower body
Torso back and lower body
</code>```

When both the front and back of the torso is selected it can be considered just "torso".

If there are more than 2 muscles selected from a group but not all:

```<code>Parts of torso (This is the case where there are muscles selected from both front- and back-torso)
Parts of torso back
Parts of lower body
</code>```

"Parts of torso front" and "Parts of arms" never occur on their own as they only have a total of 3 muscles, thus those cases can be represented by their names: eg. "biceps and triceps", etc.

Combinations of these aforementioned "parts"

```<code>Parts of arms and torso
Parts of arms and lower body
Parts of torso and lower body
Parts of  arms, torso and lower body.
</code>```

Parts = groups are not full and there are more than 2 muscles selected. This "rule of 2" is the most important one.

Examples of output

biceps, triceps and chest: parts of arms and torso

biceps, triceps, calves, tai biceps, triceps, quads, hams, hip & butt: Parts of arms and lower body

biceps, abs, calves: Parts of arms, torso and lower body

biceps, triceps: Biceps and triceps

biceps, triceps, forearms: Arms

chest, shoulders, abs, trapezius, lats, rear shoulders, lower back: Torso

and so on, there are multiple possible variations.

Now my problem is that I have no idea how to write this as clean and modular as possible, so that rules can be added or removed if necessary.

I could just write a massive if-elseif-else pile that would consider all cases, but you know why I won't.

How would you tackle this kind of task?


问:
Unit test coding standards
Usually when talking about coding standards we refer to the code of the program itself, but what about the unit tests? Are there certain coding standards guidelines that are unique to unit tests? What are they? </p>

答:
Off the top of my head, I can think of three differences in coding style for test code.

In naming test methods, I follow the pattern of shouldDoSomethingWhenSomeConditionHolds.

Inside the test, it is customary to follow the following spacing pattern:

```<code>@Test
shouldReturnAccountBalenceWhenGetBalenceIsCalled() {
    // Some lines
    // of setup code
    // go here.

    // The action being tested happens after a blank line.

    // An assertion follows another blank line.
}
</code>```

Some insist on only one assertion per test, but this is far from universal.

The DRY (Don't Repeat Yourself) is less of a consideration in test code than in production code.  While some repeated code should be placed in a setUp method or a testUtils class, striving for zero repetition in test code will lead to tightly coupled and inflexible tests, which discourages refactoring.

Title: Unit test coding standards

Body:
Off the top of my head, I can think of three differences in coding style for test code.

In naming test methods, I follow the pattern of shouldDoSomethingWhenSomeConditionHolds.

Inside the test, it is customary to follow the following spacing pattern:

@Test
shouldReturnAccountBalenceWhenGetBalenceIsCalled() {
    // Some lines
    // of setup code
    // go here.

    // The action being tested happens after a blank line.

    // An assertion follows another blank line.
}

Some insist on only one assertion per test, but this is far from universal.

The DRY (Don't Repeat Yourself) is less of a consideration in test code than in production code.  While some repeated code should be placed in a setUp method or a testUtils class, striving for zero repetition in test code will lead to tightly coupled and inflexible tests, which discourages refactoring.


问:
To be an interviewer - Java
The internet is full of references on how to get prepared for an interview. Many websites are loaded with questions and answers. But I can't find any useful information about what exactly an interviewer should do to evaluate a candidate.

What I mean is not just collecting good questions to be asked. I am asking about strategy for evaluating a candidate and find out if he is really good or just learnt the questions and answers well. I wonder if someone can share his experience in interviewing SWES, and what do you think about the following

What to expect from a junior java developer? what he should know?

What to expect from a senior java developer? what he should know?

答:
What I mean is not just collecting good questions to be asked I am
  asking about strategy for evaluating a candidate and find out if he
  really good or just just studied well questions and answers.

Well, if he studied the right questions/answers, that's already a plus for him.

Then, there's this: http://www.codinghorror.com/blog/2012/03/how-to-hire-a-programmer.html

But, you know, that might not be the right strategy for you.

What exactly are you looking for? Is it someone who has a lot of experience in a certain technology and knows its gotchas or someone who can adopt to new things quickly? Or someone who's creative and can think outside of the box?

When you realise what you need, it shouldn't be too hard to find the right questions for the candidate. If you're looking for questions on the internet, and are concerned that someone might actually learn the solution by heart (or something silly like that), you can always modify it a bit, or come up with your own questions.

Having said that, you shouldn't expect too much technical knowledge from a junior developer. Just make sure that he's bright and interested.

When it comes to senior developers, they should already have a lot of experience, so you can always ask them to talk about what they've done before.

Title: To be an interviewer - Java


答:
Ask real-world problems

We have set of pre-compiled questions and tests asked to each candidate to see how well he meets minimum requirements for position. We expect good understanding of the required technical topics.

We start our face-to-face interview (after a pre-screening phone interview(s) of course) with a question on what are the interests of the candiate, and continue with basic fundamental questions and then adjusting the level on how deep we would like to continue with that topic.

Our guidance in technical topics is candidates resume. Thus, spending 10 minutes to read resume before interview is more than important. We try to check important stack of technologies by real-world daily routine questions, that only hands-on experienced candidate may have glue about.

I would suggest to combine some real-world problem solving questions and try to see how candidate reasoning of problem work. If candidate answers honestly, and saying he does not know topics that we ask, we really appreciate honesty and not bullsh**ing.

As an example: if some candidate claims 6+ months of work with jQuery, but can not explain what is "selector", i would just stop asking further. Because, power of jQuery is coming from good understanding of selectors.

Same thing holds true for other topics like indexes in Database. If someone memorized what is cluster and non-cluster index is, but could not give proper explanation when and where we need indexes, by claiming 2 years of experience in DB development then everything is clear.

Title: To be an interviewer - Java

Body:
The internet is full of references on how to get prepared for an interview. Many websites are loaded with questions and answers. But I can't find any useful information about what exactly an interviewer should do to evaluate a candidate.

What I mean is not just collecting good questions to be asked. I am asking about strategy for evaluating a candidate and find out if he is really good or just learnt the questions and answers well. I wonder if someone can share his experience in interviewing SWES, and what do you think about the following

What to expect from a junior java developer? what he should know?

What to expect from a senior java developer? what he should know?


答:
I think 3 of those factors are really the same thing. If developers aren't available, you can hire some and train them, but it adds cost. Some fields have more expensive developers - which adds cost. And training up those you have adds cost. Fundamentally, though, I think most professional developers can move from language to language without too much hassle - though picking up new frameworks can be a pain - and this cost is usually at the start of when they work with a technology. Personally, I wouldn't worry too much about these factors.

Tooling and community I think are both enablers - they make a developer much more effective over the long run. This would concern me more. I work mostly with Microsoft stuff, and I'm no fanboy - but the tooling and community size is very useful when I compare it with other things I've worked with.

One thing not mentioned there is also the human factor of such a change. For example, we had a change in direction which caused some developers to leave. They were already invested in a particular suite of technologies and that was where they saw their careers. When the company changed, they left. Worth thinking about.


问:
Use `using` in C++ or avoid it?
Discounting subtly different semantics due to ADL, how should I generally use using, and why? Is it situation-dependent (e.g. header which will be #included vs. source file which won't)?

Also, should I prefer ::std:: or std::?

Namespace-level using namespace:

```<code>using namespace std;

pair<string::const_iterator, string::const_iterator>
f(const string &s) {
    return make_pair(s.begin(), s.end());
}
</code>```

Being fully explicit:

```<code>std::pair<std::string::const_iterator, std::string::const_iterator>
f(const std::string &s) {
    return std::make_pair(s.begin(), s.end());
}
</code>```

Namespace-level using-declarations:

```<code>using std::pair;
using std::string;

pair<string::const_iterator, string::const_iterator>
f(const string &s) {
    return make_pair(s.begin(), s.end());
}
</code>```

Function-local using-declarations:

```<code>std::pair<std::string::const_iterator, std::string::const_iterator>
f(const std::string &s) {
    using std::make_pair;
    return make_pair(s.begin(), s.end());
}
</code>```

Function-local using namespace:

```<code>std::pair<std::string::const_iterator, std::string::const_iterator>
f(const std::string &s) {
    using namespace std;
    return make_pair(s.begin(), s.end());
}
</code>```

Something else?

This is assuming pre-C++14, and thus no return-type-deduction using auto.

答:
When putting a using statement in a source file, PLEASE, just pull in the things you need. For instance:

```<code>using std::string;
using std::ostringstream;
</code>```

The issue here is that if you do

```<code>using namespace std;
</code>```

you pull in EVERY SINGLE THING from std into the global namespace. Which leads to very interesting error messages when you accidentally use a name in your code that matches one you were completely unaware of in std. If you just pull in the stuff you want, then you won't have that problem (or, more precisely, the next programmer to work on your code won't have that problem).

ContentLicense: CC BY-SA 4.0

Title: Use `using` in C++ or avoid it?

Body:
When putting a using statement in a source file, PLEASE, just pull in the things you need. For instance:

using std::string;
using std::ostringstream;

The issue here is that if you do

using namespace std;

you pull in EVERY SINGLE THING from std into the global namespace. Which leads to very interesting error messages when you accidentally use a name in your code that matches one you were completely unaware of in std. If you just pull in the stuff you want, then you won't have that problem (or, more precisely, the next programmer to work on your code won't have that problem).


问:
How is Sencha Touch performing on Android in practice?
I'm just about to start a project using Sencha Touch, and just done some minor testing on my HTC desire device. All tutorial videos at Vimeo seems to be using an iPhone emulator running on a Mac. Im not sure how fast this emulator is compared to a real iPhone device or even an real Android device, but from what i have experienced, it seems that my HTC desire is not performing that nicly as this emulator.

All animations (sliding, fading, etc) seems abit laggy. You can easily notice that the FPS is much less than on the Vimeo videos.

HTC desire is a relativly new and modern Android 2.2 phone, running with decent hardware, so im wondering if Sencha Touch is "ready" for the Android platform.

Anybody with practical experience with Android and Sencha Touch ?

答:
Please refer to this article by LinkedLN Engineering team on how they improved the performance of their HTML5 app by hand coding DOM Manipulations:

http://engineering.linkedin.com/linkedin-ipad-5-techniques-smooth-infinite-scrolling-html5

In the context of this article I see two issues with Sencha Touch:

Sencha Touch builds its UI by converting Javascript objects into Dom Nodes and adding them into the Dom Tree. Chrome Tools will show that it ends up adding a relatively high number of DIVs and other DOM elements to the Dom tree. Wouldn't this have a detrimental effect on the performance.

Most of the Dom nodes in the Sencha UI are generated by Sencha API code and not from markup. If we write code to directly manipulate these Dom elements, can we be sure that it will not produce any side effects ?

I have posted this query on the official Sencha Forum today. Will update this answer with the response.


答:
Consider studying Programming Interviews Exposed, 2nd Edition by Mongan, Kindler, Giguère.

Chapters 3 through 11 are strongly recommended reading for interviewers - these give an excellent reference on how to do technical questions. These chapters also make good reading for hiring managers - to get an idea of how much effort might it take to prepare a good question.

Title: To be an interviewer - Java


答:
In one sentence this looks like this:

Agile software development is a group of software development methodologies based on iterative and incremental development, where requirements and solutions evolve through collaboration between self-organizing, cross-functional teams.

This is coming from the wikipedia definition, and I like it very much. I highlighted core principles.

Title: What is agile methodology?

Body: Can any one explain about the agile methodology in simple sentences?</p>


问:
MVVM, DDD, and WPF Layered Application Project Structure Guidance
I am trying to setup my application's structure in VS and I want to "try" and future proof it to a reasonable level.  This application will be a WPF re-write of an old Winform app that had followed no conventions.  No Layers, Tiers, Acronyms, etc...

It is a fairly largish Enterprise Application.  I planned to use Linq To SQL as my DB's are and will most likely always be MS SQL.  Also I have an existing skill set with it.

I want to follow MVVM and DDD the best I can but I get confused on the structure of my application when combining these.  Let me try and illustrate with some examples.

When I follow MVVM my folder structure may look like this:

```<code>Views
Models
ViewModels
Helpers
</code>```

but how does that fit into a simplistic DDD layered approach where my Project Structure might resemble this:

```<code>MyApp.UI
MyApp.Domain
MyApp.Data
</code>```

Do I put the Models in the Domain layer or do I have 3 versions of say Person?  This leads to another question of where would I put my Repository and mappings of DB Object to Domain Object?  I would assume Data...

Views I get would go in UI but would ViewModels also?

Finally, where would I be embedding my Business Logic?

I found the following on CodePlex,DDD Example ,and it has been some help but seems to be for a Web App though that may not matter and is my ignorance shining through.

Don't get me wrong, I know I can have as many folders and call them whatever I want.  I am trying to figure out where to place things so that this will be scale-able, not what those places necessarily are called.

The heart of my question might be shown like this.

I have tblPerson object generated by *.dbml.  This is obvious and would belong in my "Data" layer.

Now I would have Model, DTO, Domain Model, or whatever it's called in a seperate Layer(project?) called Person.  I would need a Mapper for Person to tblPerson that I'm not sure where to put.

Then, I'll have a ViewModel for, say, EditPerson that would have it's own properties that it pulls from Person but possibly more as well.

Finally I'd have a View that was bound to that ViewModel....

To be clear that paragraph is FILLED with my assumptions and guesses and I am hoping someone will help clear the air for me or offer there insights so that 6 months to a year from now I am not kicking myself more than I need to.

答:
Before we delve into what goes where, let's talk about what each layer should be doing.

The selling point of MVVM is the binding between the view and the view-model.  The goal here is to eliminate logic within the view.

Like the View, the Model should be pretty lightweight and used only to access the information (data) that is necessary for the view-model to operate.  The Model can blend access to different data sources, but it shouldn't have business logic.  In most cases, you have a single data store to hit.  In some cases you don't.  When you don't, it's appropriate to use the Model to obscure the source of the data from the VM.

An implicit point of MVVM is that the data is already stored and your project isn't responsible for maintaining its organization.  Some projects are lucky enough to get away with that assumption, most of the projects I've worked on haven't been so lucky.  Suffice it to say that Data is another layer we'll have to contend with.

I would lay out my project like this:

```<code> project.Views
 project.ViewModel
 project.Model
 project.DataStructs
</code>```

and this layer can be added in as needed:

```<code> project.Helpers
</code>```

I'm separating the Helpers from the rest of the stack so it doesn't get confused as being a layer of your application stack.

Disclaimer:  I'm not a DDD expert, but I understand the general gist and see the value in the approach.

Your Domain is going to be the problem set that you are considering.

The Domain Models are going to correspond primarily to the ViewModels that you create; a little bit within the Views; and a small chunk within the Model / DataStructs.

So how is that going to work out?

IF you have the ability to change up the existing data structures, then the new ones you create should correlate to the problem you're trying to solve.  Got a customer object?  Then you should have a / some tables related to the Customer.  Got invoices or products?  Same story - tables and structures that map to those business objects should be created.

The Domain will be expressed through your ViewModel objects and the Views you present of those objects.  If you need to edit Customer records then you'll have a VM for handling that task.

On to your questions:

Don't try to overlay DDD onto MVVM.  It just isn't going to work.  DDD isn't a layout pattern, it's an approach to viewing your overall problem.

Repository and Mappings will live in either project.Data or project.Model as appropriate.

Don't have a layer called UI unless that's what you want to call project.Views.

Business Logic will go in the View-Model.

OwnerDisplayName: Refracted Paladin

Body:
Before we delve into what goes where, let's talk about what each layer should be doing.

The selling point of MVVM is the binding between the view and the view-model.  The goal here is to eliminate logic within the view.

Like the View, the Model should be pretty lightweight and used only to access the information (data) that is necessary for the view-model to operate.  The Model can blend access to different data sources, but it shouldn't have business logic.  In most cases, you have a single data store to hit.  In some cases you don't.  When you don't, it's appropriate to use the Model to obscure the source of the data from the VM.

An implicit point of MVVM is that the data is already stored and your project isn't responsible for maintaining its organization.  Some projects are lucky enough to get away with that assumption, most of the projects I've worked on haven't been so lucky.  Suffice it to say that Data is another layer we'll have to contend with.

I would lay out my project like this:

 project.Views
 project.ViewModel
 project.Model
 project.DataStructs

and this layer can be added in as needed:

 project.Helpers

I'm separating the Helpers from the rest of the stack so it doesn't get confused as being a layer of your application stack.

Disclaimer:  I'm not a DDD expert, but I understand the general gist and see the value in the approach.

Your Domain is going to be the problem set that you are considering.

The Domain Models are going to correspond primarily to the ViewModels that you create; a little bit within the Views; and a small chunk within the Model / DataStructs.

So how is that going to work out?

IF you have the ability to change up the existing data structures, then the new ones you create should correlate to the problem you're trying to solve.  Got a customer object?  Then you should have a / some tables related to the Customer.  Got invoices or products?  Same story - tables and structures that map to those business objects should be created.

The Domain will be expressed through your ViewModel objects and the Views you present of those objects.  If you need to edit Customer records then you'll have a VM for handling that task.

On to your questions:

Don't try to overlay DDD onto MVVM.  It just isn't going to work.  DDD isn't a layout pattern, it's an approach to viewing your overall problem.

Repository and Mappings will live in either project.Data or project.Model as appropriate.

Don't have a layer called UI unless that's what you want to call project.Views.

Business Logic will go in the View-Model.


答:
Usually all that matters is what fad do your current programmers believe in. This is the only thing which matters and what comes after usually is rationalizing this argument.

Every webpage can be written in basically any turing complete language. I've written web services in bash, and there was a design rationale behind it.

Performance is also an issue, however, I'm yet to see a person to claim that java is just awfully slow on average sized projects sometimes (and slowness is easy: response should be around 200ms for end-user),

Ease of use and adherence to platform is also an issue, for example sometimes you feel that ASP.NET library developers have only developed libraries in their life, but never web applications.

Noone will ever claim that as they either believe in a language, and know it, or don't believe, and don't know it. I'm over with believing in technologies, and maybe the projects have moved on (I won't ever write a web application in java 1.4 again for sure, and I hope postback was killed by now)

The java community seriously believed for years that J2EE 1.4 is suitable for web application development. Today, Spring is much closer to Ruby on Rails or PHP than it is to J2EE. The .NET community seriously believed that postback is a good idea. It was a usability disaster, able to make planets extinct.

We all know that these were brain-dead ideas, the communities have moved on. We have new brain-dead ideas and a huge bunch of people claiming it's the way to do it.

It doesn't matter. Keep the cognitive time limits, ensure that the user interface is responsive, and do whatever your coders feel fine with it.

So,

Have a list of what technologies your current coders know on a whiteboard,

Give everyone 5 sticks, and ask them to place it wherever they see it fit.

Grab the top two or three, form teams and ask them to create prototype

Walk through each prototype in a code review session

Make a decision.


答:
Andy has already linked to the Agile Manifesto, which I think just about covers it.

I think it's useful to look at where the Agile Manifesto came from as well. There were a number of methodologies out there which had some common elements and a lot of similar motivations: Extreme Programming (XP), Scrum, DSDM, Adaptive Software Development, Crystal, Feature-Driven Development, Pragmatic Programming (list from Alistair Cockburn). The people proposing those methodologies decided to come up with a marketing term to cover the things which they had in common so that the force of what they were saying would be enhanced.

Interestingly (according to what someone told me) there were a number of names on the shortlist which could have been picked instead of "Agile" - one of which was "Adaptive". I personally think that as a single word that sums up better what agile is really about better than "agile"!

Title: What is agile methodology?


答:
SockJS is a bit more than "Comet". "Comet" is mostly about polling (like http long-polling). SockJS will use native streaming WebSockets when available. In other words: SockJS will use "proper" Websockets if possible and "comet" otherwise.

No. SockJS is probably as good as it can be if you need to support IE6 and IE7 and weird network configurations. If you can limit your supported browsers to IE10, new FF and Chrome, and don't care about users behind broken proxies using native WebSockets might be an alternative.

As a side note, please take a look at RabbitMQ-Web-Stomp plugin. It might be a useful to an extent.

Title: Is this RabbitMQ / sockjs pub/sub connection setup a comet solution?

Body:
My company is attempting to set up a pub/sub connection using RabbitMQ and sockjs, on Windows servers. I have two questions:

My supervisor is calling this setup a comet solution, I was wondering if that is the right terminology?

Is there a better solution stack for having a data server asynchronously ship data to a client without the client requesting data (besides the initial subscription)?


答: I would not think too much about making it extensible. Human bodies are not going to change in a foreseeable future. I would model the data structures after who the users are. Are they chiropractors? Physical therapists? Gym rats? A few conditionals in one place is often better than introducing two design patterns and a handful of classes.</p>


答:
I would avoid rote, memorization type questions.  IMO, all they tell is whether or not the programmer has hit that particular situation before or if they found the "right" question to study ahead of time.

Providing technical problems to solve is a good approach - it gives you an opportunity to see how they solve new problems and what their approach will be.  Pick something related to your program's domain.  The difficulty or scope of the question can be scaled based upon the position you are hiring for.  Junior developers should have questions that you would expect them to be able to solve.  Senior developers should get the more challenging, open-ended type questions since you would expect them to lead product development.

To gauge personality, I'm a big fan of behavioral based interviewing.  Instead of asking "what would you do" it's asking "what did you do?"  Since it's from the past, all the candidate has to do is recount what actually happened they don't have to think through a situation and determine what is the "right" answer.  It's okay for candidates to bring up bad situations they were in so long as they explain how they would do things differently the next time.  BBI is a great way to figure out if the candidate is going to be a good fit for your team.  It does take some practice to get used to, but it's the best technique I have found to understand the candidates personality.

Title: To be an interviewer - Java


答:
Agile is a lot of things and practices, but I think the core of it is just iterative development.

Iterative:
Think a bunch of very small waterfalls.  That is, the waterfall method (requirements->spec->code->test), but instead of doing it over the course of a year or so, you do it over the course of a few weeks for a manageable chunk of the overall project.  At the end of 'iteration/sprint/increment', you have a small but complete and tested set of additional functionality.

This allows you to rapidly change the course of the project if it turns out that what you're doing isn't what the customer wants, or the business needs change, or whatever.  Hence the term "agile."

Title: What is agile methodology?


问:
What backs up the claim that C++ can be faster than a JVM or CLR with JIT?
A reoccurring theme on SE I've noticed in many questions is the ongoing argument that C++ is faster and/or more efficient than higher level languages like Java. The counter-argument is that modern JVM or CLR can be just as efficient thanks to JIT and so on for a growing number of tasks and that C++ is only ever more efficient if you know what you're doing and why doing things a certain way will merit performance increases. That's obvious and makes perfect sense.

I'd like to know a basic explanation (if there is such a thing...) as to why and how certain tasks are faster in C++ than the JVM or CLR? Is it simply because C++ is compiled into machine code whereas the JVM or CLR still have the processing overhead of JIT compilation at run time?

When I try to research the topic, all I find is the same arguments I've outlined above without any detailed information as to understanding exactly how C++ can be utilized for high-performance computing.

答:
JIT compilation actually has a negative impact on performance. If you design a "perfect" compiler and a "perfect" JIT compiler, the first option will always win in performance.

Both Java and C# are interpreted into intermediate languages, and then compiled to native code  at runtime, which reduces the performance.

But now the difference is not that obvious for C#: Microsoft CLR produces different native code for different CPUs, thus making the code more efficient for the machine its running on, which isn't always done by C++ compilers.

P.S. C# is written very efficently and it hasn't many abstraction layers. This isn't true for Java, which isn't that efficient. So, in this case, with its greate CLR, C# programs often show better performance than C++ programs. For more about .Net and CLR take a look at Jeffrey Richter's "CLR via C#".


答:
"Is it simply because C++ is compiled into assembly/machine code whereas Java/C# still have the processing overhead of JIT compilation at runtime?" Basically, yes!

Quick note though, Java has more overheads than just JIT compilation. For example, it does much more checking for you (which is how it does things like ArrayIndexOutOfBoundsExceptions and NullPointerExceptions). The garbage collector is another significant overhead.

There's a pretty detailed comparison here.

Title: What backs up the claim that C++ can be faster than a JVM or CLR with JIT?

Body:
A reoccurring theme on SE I've noticed in many questions is the ongoing argument that C++ is faster and/or more efficient than higher level languages like Java. The counter-argument is that modern JVM or CLR can be just as efficient thanks to JIT and so on for a growing number of tasks and that C++ is only ever more efficient if you know what you're doing and why doing things a certain way will merit performance increases. That's obvious and makes perfect sense.

I'd like to know a basic explanation (if there is such a thing...) as to why and how certain tasks are faster in C++ than the JVM or CLR? Is it simply because C++ is compiled into machine code whereas the JVM or CLR still have the processing overhead of JIT compilation at run time?

When I try to research the topic, all I find is the same arguments I've outlined above without any detailed information as to understanding exactly how C++ can be utilized for high-performance computing.


答:
This is not a duplicate of your questions, but the accepted answer answers most of your question:
A modern review of Java

To sum-up:

Fundamentally, the semantics of Java dictate that it is a slower
  language than C++.

So, depending on with which other language you compare C++, you might get or not the same answer.

In C++ you have:

Capacity to do smart inlining,

generic code generation that have strong locality (templates)

as small and compact as possible data

opportunities to avoid indirections

predictable memory behaviour

compiler optimizations possible only because of the usage of high level abstractions (templates)

These are the features or side-effects of the language definition that makes it theorically more efficient on memory and speed than any language that:

use indirection massively ("everything is a managed reference/pointer" languages): indirection mean that the CPU have to jump in memory to get the necessary data, increasing the CPU cache failures, which means slowing down the processing - C uses also indirections a lot even if it can have small data as C++;

generate big size objects which members are accessed indirectly: this is a consequence of having references by default, members are pointers so when you get a member you might not get data close to the core of the parent object, again triggering cache misses.

use a garbarge collector: it just makes predictability of performance impossible (by design).

C++ agressive inlining of the compiler reduce or eliminate a lot of indirections. The capacity to generate small set of compact data makes it cache friendly if you don't spread these data all over the memory instead of packed together (both are possible, C++ just let you choose). RAII makes C++ memory behaviour predictable, eliminating a lot of problems in case of real-time or semi-real-time  simulations, which require high speed. Locality problems, in general can be summed-up by this: the smaller the program/data, the faster the execution. C++ provide diverse ways to make sure your data are where you want it to be (in a pool, an array, or whatever) and that it is compact.

Obviously, there are other languages that can do the same, but they are just less popular because they don't provide as much abstraction tools as C++, so they are less useful in a lot of cases.


答:
Is it simply because C++ is compiled into assembly/machine code
  whereas Java/C# still have the processing overhead of JIT compilation
  at runtime?

Partially, but in general, assuming an absolutely fantastic state-of-the-art JIT compiler, proper C++ code still tends to perform better than Java code for TWO main reasons:

1) C++ templates provide better facilities for writing code that is both generic AND efficient.  Templates provide the C++ programmer with a very useful abstraction that has ZERO runtime overhead.  (Templates are basically compile-time duck-typing.) In contrast, the best you get with Java generics is basically virtual functions.  Virtual functions always have a runtime overhead, and generally can't be inlined.

In general, most languages, including Java, C# and even C, make you choose between efficiency and generality/abstraction.  C++ templates give you both (at the cost of longer compile times.)

2) The fact that the C++ standard doesn't have much to say about the binary layout of a compiled C++ program gives C++ compilers much more leeway than a Java compiler, allowing for better optimizations (at the cost of more difficulty in debugging sometimes.)  In fact, the very nature of the Java language specification enforces a performance penalty in certain areas.  For example, you can't have a contiguous array of Objects in Java.  You can only have a contiguous array of Object pointers (references), meaning that iterating over an array in Java always incurs the cost of indirection.  The value semantics of C++ however, enable contiguous arrays.  Another difference is the fact that C++ allows objects to be allocated on the stack, whereas Java does not, meaning that, in practice, since most C++ programs tend to allocate objects on the stack, the cost of allocation is often close to zero.

One area where C++ might lag behind Java is any situation where many small objects need to be allocated on the heap.  In this case, Java's garbage collection system will probably result in better performance than standard new and delete in C++ because the Java GC enables bulk deallocation.  But again, a C++ programmer can compensate for this by using a memory pool or slab allocator, whereas a Java programmer has no recourse when faced with a memory-allocation pattern that the Java runtime is not optimized for.

Also, see this excellent answer for more information about this topic.


问:
How much help should I give during technical interviews?
I'm asked to perform or sit in during many technical interviews. We ask logic questions and simple programming problems that the interviewee is expected to be able to solve on paper. (I would rather they have access to a keyboard, but that is a problem for another time.) Sometimes I sense that people do know how to approach a problem, but they are hung up by nervousness or some second-guessing of the question (they aren't intended to be trick questions).

I've never heard my boss give any help or hints. He just thanks the interviewee for the response (no matter how good or bad it is) and moves on to the next question or problem. But I know something about the rabbit hole that defeat and nerves can lead you down, and how it disables your mind, and I can't help wondering if providing a little help now and then would ultimately help us end up with more capable programmers instead of more failed interviews.

Should I provide hints and assistance for befuddled interviewees (and if so, how far should I go while still being fair to the more prepared candidates)?

答: I remember being asked a particular problem solving question from an interviewer who had a very specific result in mind, but he was not able to communicate the question clearly to me. This describes the situation that many interviewees run into.  Sometimes the blank stare is not because the person is not a good problem solver, but because the person asking the question is not being clear in what they are asking.  In that case, your colleague's approach of saying and doing nothing just proves that the candidate doesn't think like your colleague, or isn't inside your colleague's head.  I think providing clarification of the question in different words might provide better results for all involved.</p>


答:
Roy Osherove recommends the following pattern for naming your tests:

```<code>NameOfMethodUnderTest_StateUnderTest_ExpectedBehavior()
</code>```

See http://weblogs.asp.net/rosherove/archive/2005/04/03/TestNamingStandards.aspx

Title: Unit test coding standards

Body: Usually when talking about coding standards we refer to the code of the program itself, but what about the unit tests? Are there certain coding standards guidelines that are unique to unit tests? What are they? </p>

Body:
Roy Osherove recommends the following pattern for naming your tests:

NameOfMethodUnderTest_StateUnderTest_ExpectedBehavior()

See http://weblogs.asp.net/rosherove/archive/2005/04/03/TestNamingStandards.aspx


答:
It's all about the memory (not the JIT). The JIT 'advantage over C' is mostly limited to optimizing out virtual or non-virtual calls through inlining, something that the CPU BTB is already working hard to do.

In modern machines, accessing RAM is really slow (compared to anything the CPU does), which means applications that use the caches as much as possible (which is easier when less memory is used) can be up to a hundred times faster than those that don't. And there are many ways in which Java uses more memory than C++ and makes it harder to write applications that fully exploit the cache:

There is a memory overhead of at least 8 bytes for each object, and the use of objects instead of primitives is required or preferred in many places (namely the standard collections).

Strings consist of two objects and have an overhead of 38 bytes

UTF-16 is used internally, which means that each ASCII character requires two bytes instead of one (the Oracle JVM recently introduced an optimizaion to avoid this for pure ASCII strings).

There is no aggregate reference type (i.e. structs), and in turn, there are no arrays of aggregate reference types. A Java object, or array of Java objects, has very poor L1/L2 cache locality compared to C-structs and arrays.

Java generics use type-erasure, which has poor cache locality compared to type-instantiation.

Object allocation is opaque and has to be done separately for each object, so it is impossible for an application to deliberately lay out its data in a cache-friendly way and still treat it as structured data.

Some other memory- but not cache-related factors:

There is no stack allocation, so all non-primitive data you work with has to be on the heap and go through garbage collection (some recent JITs do stack allocation behind the scenes in certain cases).

Because there are no aggregate reference types, there is no stack passing of aggregate reference types. (Think efficient passing of Vector arguments)

Garbage collection can hurt L1/L2 cache contents, and GC stop-the-world pauses hurt interactivity.

Converting between data types always requires copying; you cannot take a pointer to a bunch of bytes you got from a socket and interpret them as a float.

Some of these things are tradeoffs (not having to do manual memory management is worth giving up a lot of performance for most people), some are probably the result of trying to keep Java simple, and some are design mistakes (though possibly only in hindsight, namely UTF-16 was a fixed length encoding when Java was created, which makes the decision to choose it a lot more understandable).

It's worth noting that many of these tradeoffs are very different for Java/JVM than they are for C#/CIL. The .NET CIL has reference-type structs, stack allocation/passing, packed arrays of structs, and type-instantiated generics.


答:
Do you know the Google research paper about that topic?

From the conclusion:

We find that in regards to performance, C++ wins out by a large
  margin. However, it also required the most extensive tuning efforts,
  many of which were done at a level of sophistication that would not be
  available to the average programmer.

This is at least a partially explanation, in the sense of "because real world C++ compilers produce faster code than Java compilers by empirical measures".