答:
"All PKs are surrogates" is not a very sound strategy at all and certainly not one that you are ever likely to find an "authoritative" source for.

Firstly think about what is meant by "primary key" in this context. In the relational model there are no "primary" keys - meaning no one key which is fundamentally different from any other key of the same table. In principle all keys in a relational database can and do enjoy the same status and have the same features and function, except to the extent that the database designer chooses otherwise. The singling out of any one key in a table with multiple keys is therefore essentially arbitrary (that was the word used by E.F.Codd), subjective and purely psychological (the view of Chris Date, Codd's colleague and collaborator). Unless it is explained what distinction is being drawn between a "primary" key and any other key it is therefore pretty meaningless and of no merit at all to assert that such a key "should" or "must" be anything.

Secondly, the argument has very little to do with indexes, which are a physical storage feature. Keys are a logical matter, not a physical one and there is no absolute reason to assume that the storage considerations of a "primary" key are or should be any different to other keys (see previous paragraph). We might reasonably assume that whatever storage structures are used, the storage overhead will in some measure be greater with a surrogate key than with no such key but as always the best answer here is "it depends". Storage decisions should be made on a a case-by-case bases and blanket rules are of very little help.

Thirdly, from a logical point of view the absolute requirement of a surrogate key makes very little sense. The requirement for a natural key is exactly the same with or without a surrogate. The need for information to be identifiable in the domain of discourse (i.e. with a natural key AKA "business key", "domain key") is the same. Yes, keys may need to be updated but then that's the nature of things sometimes. Adding a surrogate doesn't in itself necessarily make key updates easier to handle and sometimes it can make them harder.

Title: Is there a canonical source supporting "all-surrogates"?

Body:
Background

The "all-PK-must-be-surrogates" approach is not present in Codd's Relational Model or any SQL Standard (ANSI, ISO or other).

Canonical books seems to elude this restrictions too.

Oracle's own data dictionary scheme uses natural keys in some tables and surrogate keys in other tables. I mention this because these people must know a thing or two about RDBMS design.

PPDM (Professional Petroleum Data Management Association) recommend the same canonical books do:

Use surrogate keys as primary keys when:

There are no natural or business keys

Natural or business keys are bad ( change often )

The value of natural or business key is not known at the time of inserting record

Multicolumn natural keys ( usually several FK ) exceed three columns, which makes joins too verbose.

Also I have not found canonical source that says natural keys need to be immutable. All I find is that they need to be very estable, i.e need to be changed only in very rare ocassions, if ever.

I mention PPDM because these people must know a thing or two about RDBMS design too.

The origins of the "all-surrogates" approach seems to come from recommendations from some ORM frameworks.

It's true that the approach allows for rapid database modeling by not having to do much business analysis, but at the expense of maintainability and readability of the SQL code. Much prevision is made for something that may or may not happen in the future ( the natural PK changed so we will have to use the RDBMS cascade update funtionality ) at the expense of day-to-day task like having to join more tables in every query and having to write code for importing data between databases, an otherwise very strightfoward procedure (due to the need to avoid PK colisions and having to create stage/equivalence tables beforehand ).

Other argument is that indexes based on integers are faster, but that has to be supported with benchmarks. Obviously, long, varying varchars are not good for PK. But indexes based on short, fix-length varchar are almost as fast as integers.

The questions

- Is there any canonical source that supports the "all-PK-must-be-surrogates" approach ?

- Has Codd's relational model been superceded by a newer relational model ?


问:
How do you get into the habit of using a repository (e.g. GitHub)?
Are there some best practices on the repository front, or some common newcomer-traps that I should avoid?

I have recently been reading about the benefits of repositories even for single-developer projects and, in addition, I am likely to start working with multiple other engineers in a short while but, how do I go from never having used a repository to setting one up - for multiple people, even!

Background: I am an electronics engineer before anything else, and while application programming has been part of that, it's never been something I've done a lot of - it has mainly been snippets of C for embedded systems where I was the only person working on it.

答:
Like most habits, you have to just start doing it to form it. So choose a version control system that you're wanting to learn and start using it.

In your case, I'd suggest using git. You'll want it if you're going to use GitHub, but better yet, because of its distributed nature it is extremely easy to start saving data in version control. Just do a git init on your project folder and start enjoying benefits such as:

Ability to see what you've changed over time.

Undo or stash uncommitted changes.

Removing the fear of changing things.

Ability to quickly branch and tag.

Then when you're ready to use GitHub, you can just push your existing repository up into GitHub.

There is kind of a high learning curve for git, so you might choose something else like Subversion (svn). But unfortunately, with centralized (vs. distributed) systems it is harder to set up the repository initially. Git makes it stupidly easy -- I don't go without version control on even the smallest code snippets anymore.

Just playing around with version control on any project will help you get familiar with your system of choice. With Git there are some different workflows (e.g. git flow) that are used, but to start off you can just experiment.

DOs:

Do experiment and try things out. Don't know how to branch and merge? Just try it on a sample project.

Do commit frequently.

Do learn how to view and use the history so you can get back old data.

Do integrate often (once you start working with others).

DON'Ts:

Don't be afraid. As long as it's your own repository, even if you mess things up you won't affect anyone else. And things won't get any worse (data loss wise) than if you didn't use version control.

Share code that breaks the build (i.e. won't compile, fails unit tests, etc.) When you're on your own it's not so important, but don't get into a bad habit.

ContentLicense: CC BY-SA 3.0


问:
Which parallel pattern to use?
I need to write a server application that fetches mails from different mail servers/mailboxes and then needs to process/analyze these mails.
Traditionally, I would do this multi-threaded, launching a thread for fetching mails (or maybe one per mailbox) and then process the mails.

We are moving more and more to servers where we have 8+ cores, so I would like to make use of these cores as much as possible (and not use 1 at 100% and leave the seven others untouched). So conceptually, as an example, it would be nice that I could write the application in such a way that two cores are "continuously" fetching emails and four cores are "continuously" processing/analyzing the emails (since processing and analyzing mails is more CPU intensive than fetching mails).

This seems like a good concept, but after studying some parallel patterns, I'm not really sure how this is best implemented. None of the patterns really fit. I'm working in VS2012, native C++, but I guess from a design point of view this does not really matter and just some pointers on how to organize this would be great!

答:
The actor model of concurrency seems like it might be a good fit for this.

The Model

In case you're not familiar with this model, it goes as follows:

Actors are threads that run in a loop. Each actor has a producer-consumer message queue; external code and other actors communicate with an actor by sending a message to it (queuing it in its message queue).

An actor's thread will block waiting for a message in its message queue, and when one appears the actor will deal with it, then loop back to process or wait for the next message. Repeat.

Note: "Actors" are sometimes called "Agents", but that term is misapplied. See the comment thread below for more.

Architecture

You could create actors specifically for downloading messages (say one per mailserver/mailbox) and other actors for processing the e-mails once they've been downloaded.

Connecting the two you could have a single routing actor that would receive references to the downloaded mail files from the fetching actors and either send each reference to an available processing actor or spin up another one to process it if all the other processing actors were busy. When a processing actor was finished processing, it would send a message to the routing actor saying it was done so the routing actor would know it could send another message to it to process.

I'm betting by this point there's a library for actors for C++ [UPDATE: See comment by @rwong below]. If all else fails you could try Erlang ;)

I'm not sure how the C++ threading libraries work -- whether they map threads to a single core or multiple cores -- but if this doesn't do it for you you could take the same concept and instead of using threads have them be discrete processes and use some sort of message passing framework for the communication.

Edit: I'm betting you'll have a bottleneck at the network, though, so it might not even make sense to want to occupy all the cores at once (unless the processing takes a loooong time).

Edit: Expanded answer and corrected terminology (Agent -> Actor)

Title: Which parallel pattern to use?


问:
How can I improve this design so that I don't need to dynamically scan classes at runtime?
I'm in the middle of a redesign on the part of my current project that deals with user permissions and authorization. I have an interface named IUserPermissions that encapsulates this information.

One part of a user's permissions are the Roles which they are a member of. I'm trying not to violate the Open/Closed Principle by adding every possible role to IUserPermissions as a property like this:

```<code>interface IUserPermissions {
    bool IsAdmin { get; set; }
    bool IsDeveloper { get; set; }
    // Many more...Yuck.
}
</code>```

I feel that having an interface like this would suit the OCP better:

```<code>interface IUserPermissions {
    ICollection<IRole> Roles { get; }
    bool IsInRole<T>() where T : IRole;  /* (For convenience; Would probably be
                                             implemented as an extension method) */
}
interface IRole {
    string Name { get; }
}
public class AdminRole : IRole {
    public string Name { get { return "Admin"; } }
}
</code>```

Where I'm falling down is how to implement something like this. I'm using the ASP.NET Roles API as the backing store, meaning I'll be given a string[] of role names for the user. My IUserPermissions implementation would have to start with this collection of strings and somehow work backwards, then instantiate a bunch of appropriate IRoles to populate the Roles property.

This could be done by scanning the assembly for IRoles with a parameterless constructor, instantiating them, and reading their Name property, but...ugh. How can I fix this design so that I don't have to do this?

答:
I don't know .NET buy I will explain myself with Java. You can see it as pseudocode.

You don't have to instantiate concrete roles inside the IUserPermissions implementors, nor you need have a list of all roles or role names.

Look:

```<code>package permissions;

import java.util.Collection;

public interface IUserPermissions {
    public Collection<IRole> getRoles();
    public void addRole(IRole role);     // add a role to the collection
    public void removeRole(IRole role);  // remove a role from the collection
    public boolean isInRole(IRole role);
    public boolean isInRole(String roleName);
}
</code>```

Implementor of public boolean isInRole(IRole role); just checks if role is present in the collection using the constains method or similar.

The difference is here is this:

Implementor of public boolean isInRole(String roleName); traverses the collection comparing the roleName string with each role's getName() method.

If all you have is an array of role names, you use isInRole(String roleName), otherwise you use isInRole(IRole roleName)

For this to work you must ensure that no two roles have the same name. You can do that with Factory class.

It's ok for factory classes to be coupled to concrete classes. Their work is to be the only place where "new" is executed, so the rest of the system is decoupled from concrete classes.

Body:
I don't know .NET buy I will explain myself with Java. You can see it as pseudocode.

You don't have to instantiate concrete roles inside the IUserPermissions implementors, nor you need have a list of all roles or role names.

Look:

package permissions;

import java.util.Collection;

public interface IUserPermissions {
    public Collection<IRole> getRoles();
    public void addRole(IRole role);     // add a role to the collection
    public void removeRole(IRole role);  // remove a role from the collection
    public boolean isInRole(IRole role);
    public boolean isInRole(String roleName);
}

Implementor of public boolean isInRole(IRole role); just checks if role is present in the collection using the constains method or similar.

The difference is here is this:

Implementor of public boolean isInRole(String roleName); traverses the collection comparing the roleName string with each role's getName() method.

If all you have is an array of role names, you use isInRole(String roleName), otherwise you use isInRole(IRole roleName)

For this to work you must ensure that no two roles have the same name. You can do that with Factory class.

It's ok for factory classes to be coupled to concrete classes. Their work is to be the only place where "new" is executed, so the rest of the system is decoupled from concrete classes.


答:
Have you considered creating an enum with all possible roles? Sure, if in the future you require a new role to be added, you'll have to modify the enum, which would break OCP, but I honestly do not believe it is worth it to go to such lengths just to avoid something that simple.

P.S.: Plus, you can use the Enum.Parse method to populate your collection from the array of strings.

Title: How can I improve this design so that I don't need to dynamically scan classes at runtime?

Body:
I'm in the middle of a redesign on the part of my current project that deals with user permissions and authorization. I have an interface named IUserPermissions that encapsulates this information.

One part of a user's permissions are the Roles which they are a member of. I'm trying not to violate the Open/Closed Principle by adding every possible role to IUserPermissions as a property like this:

```<code>interface IUserPermissions {
    bool IsAdmin { get; set; }
    bool IsDeveloper { get; set; }
    // Many more...Yuck.
}
</code>```

I feel that having an interface like this would suit the OCP better:

```<code>interface IUserPermissions {
    ICollection<IRole> Roles { get; }
    bool IsInRole<T>() where T : IRole;  /* (For convenience; Would probably be
                                             implemented as an extension method) */
}
interface IRole {
    string Name { get; }
}
public class AdminRole : IRole {
    public string Name { get { return "Admin"; } }
}
</code>```

Where I'm falling down is how to implement something like this. I'm using the ASP.NET Roles API as the backing store, meaning I'll be given a string[] of role names for the user. My IUserPermissions implementation would have to start with this collection of strings and somehow work backwards, then instantiate a bunch of appropriate IRoles to populate the Roles property.

This could be done by scanning the assembly for IRoles with a parameterless constructor, instantiating them, and reading their Name property, but...ugh. How can I fix this design so that I don't have to do this?


问:
Is it possible to develop a web application entirely in Javascript today (client and server) including a RESTful API exposing PostgreSQL data?
Where I work we have over a dozen internal SW systems that we have developed in-house using a variety of technologies, frameworks, and languages. Those include various from Microsoft (ASP.NET Web Forms, WebAPI, WinForms, SharePoint, Office Automation, Win8 Native Apps, SQL Server, SSRS) and others not from Microsoft (plain-old JS/HTML/CSS, PHP, Lithium, PostgreSQL, MySQL). Our SW dev team has grown and shrunk again to where it's just me and one other dev now. I love trying shiny new tech and taking advantage of different tools to get things done, which partly explains the huge span of different technologies we've chosen over the years, but we're suffering from the "jack of all trades, master of none" syndrome.

Now we've been told that the company is expecting significant new growth and that the two of us will need to produce a number of new applications over the next year. I'm ready to consolidate our skill sets and tool sets so that we can master the tools and focus more on the business problems we will face without having the slowdown of context switching between technologies. The two of us have been doing a lot of "plain old" JS/HTML5/CSS3 development recently and I would like to focus on that technology set moving forward.

We will be primarily using PostgreSQL as our data store on the back end (possibly augmenting with some NoSQL for very specific uses, and probably needing to find an advanced full-text search tool to integrate in). Our primary user interfaces will be a combination of traditional web apps and Single Page Apps (50%-50% mix), but there is the hope for native mobile apps down the line. Therefore I would like to expose our business data via a RESTful API so that it's easy to consume by various clients. And the most important factor in all of this is that I want to be able to code exclusively in Javascript from front to back (with the exception of writing SQL as necessary for the DB layer, and HTML5/CSS3 for the presentation).

This leaves me with the following questions:

Is it possible today to code all these layers/components exclusively in Javascript without resorting, for example, to PHP on the server, or C# for the RESTful API (i.e., WebAPI)?

Is node.js required to make this a reality, or can I use a non-node web server and still achieve the "Javascript-only" ideal? (related...would node.js just make more sense in a JS-only paradigm?)

Are there any frameworks for building JS-only RESTful APIs that can talk to PostgreSQL?

Are there any advanced full-text search tools (such as Lucene) that allow you to program against them with a JS-only approach?

答:
It is possible to exclusively use JavaScript to do what you described. I wouldn't agree that Node.js is the only way to do that however. Not that Node.js isn't a great/powerful tool, but JavaScript is just one implementation of ECMAScript https://en.wikipedia.org/wiki/ECMAScript

I have been writing server-side applications in EMCAScript for years before Node.js existed with Microsoft's JScript on classic ASP pages. The JavaScript that is used in client code across the internet is almost completely compatible with the JScript that is run by classic ASP as well as JScript.NET! I port code between my client and server scripts on a regular basis by adding and removing any calls to the DOM (which doesn't exist on the server). I added JSON.stringify()/JSON.parse() to all of my ASP pages with a simple call to Crockfords secureParse.js so that the server and client have a simple mechanism for passing data. That's how compatible the two scripting languages are. Aside from JavaScript having access to the DOM and JScript having access to COM and server mechanisms (cache control,buffer, flush, Reponse.Write, etc) they are practically idenical...

Writing in JScript (ASP) or JScript.NET also gives you access to all of the COM resources available to the server through ActiveX controls, which I use for IO calls, encryption, compression, all the data transfer protocols (i.e. ftp,http,smtp, etc), direct printing, DB connection, and I have even been known to borrow spellchecker from MS Word with

```<code>Word = new ActiveXObject("Word.Application");
</code>```

and without having to use anything further than JScript I can access the entire public facing API of any windows control :)

And for a faster execution, I write some modules that are fully encapsulated in the same JScript, then run it through a .NET compiler (called JSC.exe) and now the same code is no longer "interpreted", but compiled!

Unlike JavaScript (and therefore Node.js), this would require a windows server to run the server code. But you didn't say that that couldn't be a requirement...

I too like to be able to stick with what I know and not become a "Jack of all trades", but JavaScript is really the only language I know... So it helps that it's so flexible.

Body:
It is possible to exclusively use JavaScript to do what you described. I wouldn't agree that Node.js is the only way to do that however. Not that Node.js isn't a great/powerful tool, but JavaScript is just one implementation of ECMAScript https://en.wikipedia.org/wiki/ECMAScript

I have been writing server-side applications in EMCAScript for years before Node.js existed with Microsoft's JScript on classic ASP pages. The JavaScript that is used in client code across the internet is almost completely compatible with the JScript that is run by classic ASP as well as JScript.NET! I port code between my client and server scripts on a regular basis by adding and removing any calls to the DOM (which doesn't exist on the server). I added JSON.stringify()/JSON.parse() to all of my ASP pages with a simple call to Crockfords secureParse.js so that the server and client have a simple mechanism for passing data. That's how compatible the two scripting languages are. Aside from JavaScript having access to the DOM and JScript having access to COM and server mechanisms (cache control,buffer, flush, Reponse.Write, etc) they are practically idenical...

Writing in JScript (ASP) or JScript.NET also gives you access to all of the COM resources available to the server through ActiveX controls, which I use for IO calls, encryption, compression, all the data transfer protocols (i.e. ftp,http,smtp, etc), direct printing, DB connection, and I have even been known to borrow spellchecker from MS Word with

Word = new ActiveXObject("Word.Application");

and without having to use anything further than JScript I can access the entire public facing API of any windows control :)

And for a faster execution, I write some modules that are fully encapsulated in the same JScript, then run it through a .NET compiler (called JSC.exe) and now the same code is no longer "interpreted", but compiled!

Unlike JavaScript (and therefore Node.js), this would require a windows server to run the server code. But you didn't say that that couldn't be a requirement...

I too like to be able to stick with what I know and not become a "Jack of all trades", but JavaScript is really the only language I know... So it helps that it's so flexible.


问:
The 10 minutes technical interview
I must do a quick assessment of dozens of fresh students very quickly. I have 30 minutes meeting with each of them (in two or three days). I want to use most of the time to discuss non technical aspects. So I plan to use 10 minutes for technical questions. The same questions for all of them.

They are all hired already (they are students), what I need to know is the average level in order to prepare a training.

Ideally, the difficulty must be progressive in order to set a level for each. Level I will average, and I'll do an average on each question too.

If you had only 10 minutes and 10 questions to ask to a candidate, what would be your top 10 ?

答:
Bloom's Taxonomy is useful here. You want to hit a variety of knowledge levels, ranging from rote memorization to analytical. This gives you a chance to find out where their skill level lies. Since the OP was looking for questions to ask students, the list below doesn't suppose any more knowledge than a 3rd or 4th year student would (I hope) possess.

Conceptual

What is a stack underflow?

What's the difference between an object and a class?

What's the difference between a function and a method?

Identify some of the strengths and weaknesses of Quicksort and Insertion Sort.

Describe how a program you wrote would display all the values being stored in a binary tree.

Practical

Have you used a version control system? In what ways does it allow team members to more effectively collaborate?

Your compiler says "unidentified symbol." What does that mean?

What is a "segmentation violation"?

Name some data structures provided by the (insert language here) syntax or standard library.

How would you find and display all the email addresses in 10,000 files?

ContentLicense: CC BY-SA 2.5

Title: The 10 minutes technical interview


问:
Is 37Signals Basecamp a hype?
What's so unique about it? Heard great things about it, used it, found that beside the Google Apps Integration there's nothing really special about it. Maybe I just don't get it?

So, what's your reason to use basecamp?

答:
Basecamp is great for simple project managing. If you are running a company that just needs all the team members to see what is happening and stay on the same page, then it is great. I have also found that it works wonders for design teams. Todo lists, claender events, and facebook-like posts with comments, is what makes this easy and simple to pick up.

Many other project management tools are designed around software development. They have issues, tickets, bug reports, SCRUM sctructure or whatever. This makes sense to software devs, but designers and average businessmen just don't think that way. This is why basecamp is so popular. It was really created for those.

Basecamp does NOT work for software teams. Trust me, we have tried many times. If you are developing a software, then you need something like unfuddle, assembla, or Jira.

The real problem is that programmers do not work in a funnel. They need to deal with technical writers, designers, and project leads, and for this basecamp's tools are better. I am waiting for someone to come out with a tool that offers the best of both sides. Out of the thousands of project managers, they are all either on one side or the other.

Title: Is 37Signals Basecamp a hype?


问:
Is there any situation in which it would be appropriate to use unless... else?
This construction is considered wrong

```<code>unless
  #..
else
  #..
end
</code>```

This is for the general reason of double-negative confusions.  It translates to:

```<code>if not
  #..
if not not
  #..
end
</code>```

We all agree this is confusing.

Is there any situation (include semantic) that the unless..else construction would be more appropriate?

答:
No.

Any construct of that type can be rewritten in your second form, with better clarity.

In most languages, the if not not collapses into a simple if anyway, so the mind-bending consequences of unless else become especially pointless.


答:
I've not worked with ruby, but Perl has a similar construct which has the same kind of baggage around it.

There is no structural difference between these 3 constructs:

```<code>if condition
    OneThing()
else
    AnotherThing()

unless condition
    AnotherThing()
else:
    OneThing()

if not condition
    AnotherThing()
else:
    OneThing()
</code>```

However, semantically, I think the reason that people recommend it is that unless condition is really just syntactic sugar for if not condition. The difference is that not every language has unless so the latter is more instantly readable to a new programmer. When introducing unless it is usually in the context of the above definition.

Using unless then else just confuses things further, because while unless is a helpful shortcut, unless else adds confusion by having an unfamiliar construct used in an unneccessary way.

Any unless then else can trivially be rewritten as if then else, so I would suggest that there is no case where unless then else improves the readability or computability of the code.

Title: Is there any situation in which it would be appropriate to use unless... else?

Body:
This construction is considered wrong

```<code>unless
  #..
else
  #..
end
</code>```

This is for the general reason of double-negative confusions.  It translates to:

```<code>if not
  #..
if not not
  #..
end
</code>```

We all agree this is confusing.

Is there any situation (include semantic) that the unless..else construction would be more appropriate?

Body:
I've not worked with ruby, but Perl has a similar construct which has the same kind of baggage around it.

There is no structural difference between these 3 constructs:

if condition
    OneThing()
else
    AnotherThing()

unless condition
    AnotherThing()
else:
    OneThing()

if not condition
    AnotherThing()
else:
    OneThing()

However, semantically, I think the reason that people recommend it is that unless condition is really just syntactic sugar for if not condition. The difference is that not every language has unless so the latter is more instantly readable to a new programmer. When introducing unless it is usually in the context of the above definition.

Using unless then else just confuses things further, because while unless is a helpful shortcut, unless else adds confusion by having an unfamiliar construct used in an unneccessary way.

Any unless then else can trivially be rewritten as if then else, so I would suggest that there is no case where unless then else improves the readability or computability of the code.


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

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

void M(NumericType flags);

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

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

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

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

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

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

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

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

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

void M(int flags);

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

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

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

void M(NumericTypeFlags flags);

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

(full code by user315052)

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

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

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

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

答:
The simplest way is to provide the operator overloads yourself.
I am thinking of creating a macro to expand the basic overloads per type.

```<code>#include <type_traits>

enum class SBJFrameDrag
{
    None = 0x00,
    Top = 0x01,
    Left = 0x02,
    Bottom = 0x04,
    Right = 0x08,
};

inline SBJFrameDrag operator | (SBJFrameDrag lhs, SBJFrameDrag rhs)
{
    using T = std::underlying_type_t <SBJFrameDrag>;
    return static_cast<SBJFrameDrag>(static_cast<T>(lhs) | static_cast<T>(rhs));
}

inline SBJFrameDrag& operator |= (SBJFrameDrag& lhs, SBJFrameDrag rhs)
{
    lhs = lhs | rhs;
    return lhs;
}
</code>```

(Note that type_traits is a C++11 header and std::underlying_type_t is a C++14 feature.)

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

Body:
The simplest way is to provide the operator overloads yourself.
I am thinking of creating a macro to expand the basic overloads per type.

#include <type_traits>

enum class SBJFrameDrag
{
    None = 0x00,
    Top = 0x01,
    Left = 0x02,
    Bottom = 0x04,
    Right = 0x08,
};

inline SBJFrameDrag operator | (SBJFrameDrag lhs, SBJFrameDrag rhs)
{
    using T = std::underlying_type_t <SBJFrameDrag>;
    return static_cast<SBJFrameDrag>(static_cast<T>(lhs) | static_cast<T>(rhs));
}

inline SBJFrameDrag& operator |= (SBJFrameDrag& lhs, SBJFrameDrag rhs)
{
    lhs = lhs | rhs;
    return lhs;
}

(Note that type_traits is a C++11 header and std::underlying_type_t is a C++14 feature.)

ContentLicense: CC BY-SA 4.0


问:
SQL IN() versus OR
I was working with a query I wrote today had to change the code from the WHERE clause to use a IN(list of stuff) filter instead of using something like

```<code>item_desc = 'item 1'
OR item_desc = 'item 2'
OR item_desc = 'item 3'
OR item_desc = 'item 4'
</code>```

The above ran for 15 minutes and returned nothing, yet the following gave me my result set in 1.5 minutes

```<code>item_desc IN (
'item 1'
,'item 2'
,'item 3'
,'item 4'
)
</code>```

I did this in SQL and am wondering why the IN(list of items) performed so much faster then the OR statement.

-- EDIT --
SQL Server 2008, I do apologize for not putting this bit of info in in the first place.

Here is the Query in its entirety using the OR statements:

```<code>DECLARE @SD DATETIME
DECLARE @ED DATETIME
SET @SD = '2013-06-01';
SET @ED = '2013-06-15';

-- COLUMN SELECTION
SELECT PV.PtNo_Num AS 'VISIT ID'
, PV.Med_Rec_No AS 'MRN'
, PV.vst_start_dtime AS 'ADMIT'
, PV.vst_end_dtime AS 'DISC'
, PV.Days_Stay AS 'LOS'
, PV.pt_type AS 'PT TYPE'
, PV.hosp_svc AS 'HOSP SVC'
, SO.ord_no AS 'ORDER NUMBER'
--, SO.ent_dtime AS 'ORDER ENTRY TIME'
--, DATEDIFF(HOUR,PV.vst_start_dtime,SO.ent_dtime) AS 'ADM TO ENTRY HOURS'
, SO.svc_desc AS 'ORDER DESCRIPTION'
, OSM.ord_sts AS 'ORDER STATUS'
, SOS.prcs_dtime AS 'ORDER STATUS TIME'
, DATEDIFF(DAY,PV.vst_start_dtime,SOS.prcs_dtime) AS 'ADM TO ORD STS IN DAYS'

-- DB(S) USED
FROM smsdss.BMH_PLM_PtAcct_V PV
JOIN smsmir.sr_ord SO
ON PV.PtNo_Num = SO.episode_no
JOIN smsmir.sr_ord_sts_hist SOS
ON SO.ord_no = SOS.ord_no
JOIN smsmir.ord_sts_modf_mstr OSM
ON SOS.hist_sts = OSM.ord_sts_modf_cd

-- FILTER(S)
WHERE PV.Adm_Date BETWEEN @SD AND @ED
AND SO.svc_cd = 'PCO_REMFOLEY'
OR SO.svc_cd = 'PCO_INSRTFOLEY'
OR SO.svc_cd = 'PCO_INSTFOLEY'
OR SO.svc_cd = 'PCO_URIMETER'

AND SO.ord_no NOT IN (
    SELECT SO.ord_no
    FRROM smsdss.BMH_PLM_PtAcct_V PV
    JOIN smsmir.sr_ord SO
    ON PV.PtNo_Num = SO.episode_no
    JOIN smsmir.sr_ord_sts_hist SOS
    ON SO.ord_no = SOS.ord_no
    JOIN smsmir.ord_sts_modf_mstr OSM
    ON SOS.hist_sts = OSM.ord_sts_modf_cd
    WHERE OSM.ord_sts = 'DISCONTINUE'
    AND SO.svc_cd = 'PCO_REMFOLEY'
    OR SO.svc_cd = 'PCO_INSRTFOLEY'
    OR SO.svc_cd = 'PCO_INSTFOLEY'
    OR SO.svc_cd = 'PCO_URIMETER'
)
ORDER BY PV.PtNo_Num, SO.ord_no, SOS.prcs_dtime
</code>```

Thank you,

答:
The best way to tell is to look at the actual query plan using something like EXPLAIN. This should tell you exactly what the DBMS is doing, and then you can get a much better idea why it's more efficient.

With that said, DBMS systems are really good at doing operations between two tables (like joins). A lot of the optimizer's time is spent on these parts of the queries because they are generally more expensive.

For example, the DBMS could sort that IN list and, using an index on item_desc, filter the results very quickly. You can't do that optimization when you list a bunch of selections like in the first example.

When you use IN, you are making an impromptu table and filtering using these more efficient table combining techniques.

EDIT: I posted this answer before OP mentioned the specific DBMS. This is turns out to NOT be how SQL Server treats this query, but might be valid for other DBMS systems. See JNK's answer for a more specific, accurate answer.

Title: SQL IN() versus OR


问:
Established antipattern name? Only getting data ducks in a row right before you need them
This one's all over our codebase but I'm not sure I've ever heard a name put to it.

We have C# and Java (and Rails but we don't have to touch it very often) so I'll speak more generally. It's like the data concerns never get fully established until you're literally right in a view controller preparing to drop it on the page (note: we're way past the actual SQL queries in most cases here).

For instance, we have data for a certain product type coming in from CRMs, from scans done with our mobile app, and pulled up from inventory in DBs and yet somehow it's not until we get to the spot where we're literally about to drop it on the page that we suddenly discover that there's business logic to attend to. Our actions and view controllers are GIGANTIC. We're asking all kinds of questions of every object and branching on them, whether it isThis or hasThat, data sources, customer preferences and sometimes stuff so seemingly arbitrary it might as well be phase of the moon, migration habits of species I've never even heard of, most-googled film stars...

And it doesn't always stop at the controller. The Java in particular is notorious for letting it all spill out into the JSP and then even onto the client-side in the JS.

This phenomenon has to have a name, but I've never heard it. What is it?

答:
Craig Larman calls it "The Bloated Controller" in Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development

Poorly designed, a controller class will have low cohesion - unfocused
  and handling too many areas of resposibility; this is called a bloated
  controller. Signs of bloating include:

(...)

The controller itself performs many of the tasks necessary to fulfill the system event, without delegating the work. This usually
  involves a violation of Information Expert and High Cohesion.

(...)


问:
What is the best way to store configurations of shell/script code to execute later?
I am working on a tool (Python, may or may not be important) that will allow a user to maintain a configuration file containing arbitrary shell and/or language code to be executed on particular events and intervals. The code will potentially involve multiple statements.

I understand there are potential behavioral and security risks associated with executing arbitrary code from a file, but I don't think this is a concern because the configuration file is managed only by the end user. However, let me know if I'm overlooking something major.

My main question: what is the best way to store this code in a configurable way?

Some concepts I'm considering to store the code...

In a shared config file (which many Python libraries already look for):

```<code># setup.cfg
[my_program]
command_1 = cd /tmp && touch foobar
</code>```

In a YAML file:

```<code># my_program.yaml
command_1: cd /tmp && touch foobar
</code>```

In a source file as arguments to subprocess.call():

```<code># settings.py
command_1 = [['cd', '/tmp'], ['touch', 'foobar']] # requires special handling of 'cd'
</code>```

In a source file as a function:

```<code># settings.py
import os
import subprocess
def command_1():
    os.chdir('/tmp')
    subprocess.call(['touch', 'foobar'])
</code>```

答:
How about storing the commands in an actual executable file? The end user creates a bash/python/ruby script, and all they supply to your configuration is the name of the script to execute.

This allows the script to be arbitrarily simple or complex, and also lets the end user use any scripting language supported by their own environment.

Finally, they will need permissions to make the script file executable for this to work, which means they already had permissions to create and run any script anyways.


问:
Should I open pull requests from a branch on the official repo or my fork?
I have commit access on an open source project named Foo hosted on GitHub (there are many other committers if that is relevant).  I would like to make a change via pull request so that someone else reviews it before it gets committed to the master branch of the Foo codebase.

To make this pull request, I can either make a branch on the official Foo repository or I could fork Foo and commit to a branch on my fork.

What issues should I consider when I'm deciding whether to make my pull request on the official repo or my fork?

答:
I have no direct experience with it, but my expectation is that a pull request from a fork will be scrutinized more closely and rejected more easily than a pull request from a branch in the official repo.

My reasoning for this expectation is that everyone can create a fork and submit pull requests from that fork, so the reviewer will have less confidence that the author of the change really knows the project and really knows what he is doing.
For a pull request from a branch, however, the author must have gotten enough reputation among the other maintainers to have gained commit access to the official repo, so he is likely to already have shown he understands the project and wants an extra pair of eyes to look at the change because it is unusually large or involves some risk.


答:
Well, for your example script only the first two methods will actually work. It has a cd in it, and therefore the two commands must be part of the same shell script.

Therefore, if you want to use commands that have the form of a shell script, you have to store them in form of a string anyway. If the code you want to store may become longer, YAML might be the better idea, since it can handle multi-line strings better.

Title: What is the best way to store configurations of shell/script code to execute later?

Body:
I am working on a tool (Python, may or may not be important) that will allow a user to maintain a configuration file containing arbitrary shell and/or language code to be executed on particular events and intervals. The code will potentially involve multiple statements.

I understand there are potential behavioral and security risks associated with executing arbitrary code from a file, but I don't think this is a concern because the configuration file is managed only by the end user. However, let me know if I'm overlooking something major.

My main question: what is the best way to store this code in a configurable way?

Some concepts I'm considering to store the code...

In a shared config file (which many Python libraries already look for):

```<code># setup.cfg
[my_program]
command_1 = cd /tmp && touch foobar
</code>```

In a YAML file:

```<code># my_program.yaml
command_1: cd /tmp && touch foobar
</code>```

In a source file as arguments to subprocess.call():

```<code># settings.py
command_1 = [['cd', '/tmp'], ['touch', 'foobar']] # requires special handling of 'cd'
</code>```

In a source file as a function:

```<code># settings.py
import os
import subprocess
def command_1():
    os.chdir('/tmp')
    subprocess.call(['touch', 'foobar'])
</code>```


问:
Standards of unit testing output
Simple question, what's more common /  standard / won't make future developers look at me cross-eyed for unit testing:

Displaying just the errors, or reporting every passed test?

答:
I definitely vote for showing any test result, both passed and failed, maybe summarizing the failed tests at first.

IMHO when unit testing it's fundamental to get all details from test run.

Title: Standards of unit testing output


问:
What is good practice when inheriting static classes isn't possible/allowed
I am developing a project in C# and due to a design decision it is not possible to have a static class inherit another static class. But I have, in my opinion, a case where this would make sense.

I have a music player which is able to play music from many different music sources: local files, YouTube, SoundCloud, Jamendo, etc. I have currently one static class for each of these sources with static methods such as retrieving the top tracks, searching for tracks, etc.

Naturally, a lot of code is shared among all these classes so I wanted to refactor and put all common code into a more generic MusicSource class. But C# doesn't allow me to do that.

What would be the best practice here? I want to get rid of all my redundant code and make it easier to create new music sources.

答:
It is not possible to inherit static classes at all (at least in C#), regardless of any 'design decision'.

Perhaps your question needs rephrasing, but can you not use non-static classes like in this contrived and overly simple example;

```<code>abstract class MusicSource
{
    abstract MusicData LoadMusic(string source);

    protected string SomeCommonProperty { get; set; }
}

class JamendoSource : MusicSource
{
    override MusicData LoadMusic(string source)
    {
        // Jamendo-specific code
    }
}
</code>```

Body:
It is not possible to inherit static classes at all (at least in C#), regardless of any 'design decision'.

Perhaps your question needs rephrasing, but can you not use non-static classes like in this contrived and overly simple example;

abstract class MusicSource
{
    abstract MusicData LoadMusic(string source);

    protected string SomeCommonProperty { get; set; }
}

class JamendoSource : MusicSource
{
    override MusicData LoadMusic(string source)
    {
        // Jamendo-specific code
    }
}


答:
Those "music source" classes sound more like non-static classes which you happen to only want one instance of. They are two different things!

Here are some reasons why you might want to make them non-static:

If they have (or might eventually have) some internal state. e.g. Cached login credentials, or cached lists of the top 10 tracks. Stateful static classes are a bad idea! They are basically a poor implementation of a singleton.

If you're going to have a lot of music sources, you may well want to perform some actions on all of them. e.g. Find a particular track from any source. With static classes you're going to need a line for each class. If you've got non-static classes you can just loop over a collection of them.

There's a great answer here which gives more reasons and goes into more detail.

Title: What is good practice when inheriting static classes isn't possible/allowed

Body:
I am developing a project in C# and due to a design decision it is not possible to have a static class inherit another static class. But I have, in my opinion, a case where this would make sense.

I have a music player which is able to play music from many different music sources: local files, YouTube, SoundCloud, Jamendo, etc. I have currently one static class for each of these sources with static methods such as retrieving the top tracks, searching for tracks, etc.

Naturally, a lot of code is shared among all these classes so I wanted to refactor and put all common code into a more generic MusicSource class. But C# doesn't allow me to do that.

What would be the best practice here? I want to get rid of all my redundant code and make it easier to create new music sources.


答:
Why not code the mapping (Role as String -> Role as concrete IRole type) in a Factory class?</p>

```<code>public class RoleFactory
{
    public IEnumerable<IRole> CreateRoles(IEnumerable<String> roleStrings)
    {
        return roleStrings.Select(item => this.CreateRole(item)).ToList();
    }

    public IRole CreateRole(String roleString)
    {
        IRole result = null;

        switch(roleString)
        {
            case "Viewer":
                result = new ViewerRole();
                break;

            case "Admin":
                result = new AdminRole();
                break;

            case "Monkey":
                result = new MonkeyRole();
                break;

            default:
                throw new ArgumentException("Unexpected Role String");
        }

        // extra Defensive Programming
        if (result == null)
        {
            throw new InvalidOperationException("Role mapping is broken.");
        }

        return result;
    }
}
</code>```

Body:
Why not code the mapping (Role as String -> Role as concrete IRole type) in a Factory class?

public class RoleFactory
{
    public IEnumerable<IRole> CreateRoles(IEnumerable<String> roleStrings)
    {
        return roleStrings.Select(item => this.CreateRole(item)).ToList();
    }

    public IRole CreateRole(String roleString)
    {
        IRole result = null;

        switch(roleString)
        {
            case "Viewer":
                result = new ViewerRole();
                break;

            case "Admin":
                result = new AdminRole();
                break;

            case "Monkey":
                result = new MonkeyRole();
                break;

            default:
                throw new ArgumentException("Unexpected Role String");
        }

        // extra Defensive Programming
        if (result == null)
        {
            throw new InvalidOperationException("Role mapping is broken.");
        }

        return result;
    }
}


问:
Forcing logger/appender to output line logged at lower than its current level?
Consider the following scenario:

I am writing a Dispatcher Servlet that delegates processing to various handlers depending on the request URL; the handler objects having previously registered themselves for URL patterns, pretty much as Servlets register themselves in web.xml.

When a Handler registers or unregisters itself for a pattern, I want to log a line that includes the action and pattern; and also the current mappings, so that when a subsequent request processing logs a warning that a request was not processed I can go back in the logs and find out the mappings.

The question is how to ensure that lines logged by registerUrlPattern/unregisterUrlPattern actually appear in the log file:

It seems to me that these methods should log the mapping changes at INFO level, since it is additional INFO being logged. But the logger's level is WARN so that will not work. The logger get many other messages at INFO level so it is not possible to change its level to INFO in production, except for troubleshooting.

I could log it at WARN level, but qa/usability/customer does not like such warnings to appear.

I can think of the following alternatives:

Change the Logger's level to INFO when logging these lines, possibly by adding a forceInfo method in my Logger (which wraps a standard log4j type logger)

Use a different Logger for these methods and set its level to INFO

Log at warning level but change the language to indicate that it is not something to be worried about

答:
Instead of trying to force a message containing the data you want available when another message is logged, you should use Log4J's Thread Context capability to add the data to the other message.  That way, if the error message is issued, it carries along the data you want logged.  So, for example, instead of:

```<code>logger.ForceInfoOutputEvenThoughBelowLoggingLevel("Hey, I'm going to be processing record " + recordNumber + ", so if an error happens, you'll know what I'm doing!");
...
logger.Error("OMG!")
</code>```

which would presumably log:

```<code>INFO Hey, I'm going to be processing record 42, so if an error happens, you'll know what I'm doing!
ERROR OMG!
</code>```

you'd do this instead:

```<code>ThreadContext.put("recordNumber", recordNumber);
...
logger.Error("OMG!")
</code>```

which, with %x or %X in your Log4J config's layout definition, would log:

```<code>ERROR recordNumber=42 OMG!
</code>```

The point is to augment the error message with useful data, rather than to force another message into the log.  This has lots of benefits, including the fact that you can augment any message issued by any code, without having to modify that code, even if you don't have it's source.

Body:
Instead of trying to force a message containing the data you want available when another message is logged, you should use Log4J's Thread Context capability to add the data to the other message.  That way, if the error message is issued, it carries along the data you want logged.  So, for example, instead of:

logger.ForceInfoOutputEvenThoughBelowLoggingLevel("Hey, I'm going to be processing record " + recordNumber + ", so if an error happens, you'll know what I'm doing!");
...
logger.Error("OMG!")

which would presumably log:

INFO Hey, I'm going to be processing record 42, so if an error happens, you'll know what I'm doing!
ERROR OMG!

you'd do this instead:

ThreadContext.put("recordNumber", recordNumber);
...
logger.Error("OMG!")

which, with %x or %X in your Log4J config's layout definition, would log:

ERROR recordNumber=42 OMG!

The point is to augment the error message with useful data, rather than to force another message into the log.  This has lots of benefits, including the fact that you can augment any message issued by any code, without having to modify that code, even if you don't have it's source.


问:
What are some well known applications written in F#?
As part of a continuing quest for knowledge, I'm spending some time this week learning the basics of F# as an introduction to functional programming. I think I am understanding the construction of software under this model and some of the proposed benefits, but am still a little fuzzy on the real-world use cases.

I was hoping that a F# success stories, or at least a few applications that I'd be familiar with might make it a little clearer about when F# (or any functional programming language) would be appropriate for a project.

So back to the question, what are some well known applications that use F# or a similar functional programming language?

BTW: I am also open to hearing about some lesser-known apps, but if you mention one, please give the basics of what the app is about and why the language used was the appropriate choice.

答:
Iron JS.

I personally think that it is odd that the only application I know of that is written in F# is something that allows you to write in a language other than F#.

To me, that says a lot about the true value of functional programming. People can celebrate how "beautiful" it is all they want--if it were so beautiful, people would be using it more.


答:
Change the Logger's level to INFO when logging these lines, possibly by adding a forceInfo method in my Logger (which wraps a standard log4j type logger)

At some point down the line you will probably consider the register/unregister behaviour reliable enough that you don't want to log it any more, and you only want to see 'proper' warnings. At this point you'll have no option but to go and change the code.

Use a different Logger for these methods and set its level to INFO

Yep, do this. It gives you the fine-grained control that you need in this scenario.

Log at warning level but change the language to indicate that it is not something to be worried about

Don't do this. Your users/QA don't want it, ant the event isn't a warning, so don't make it one. Also, you again have to change the code in order to disable logging these events.

Title: Forcing logger/appender to output line logged at lower than its current level?

Body:
Consider the following scenario:

I am writing a Dispatcher Servlet that delegates processing to various handlers depending on the request URL; the handler objects having previously registered themselves for URL patterns, pretty much as Servlets register themselves in web.xml.

When a Handler registers or unregisters itself for a pattern, I want to log a line that includes the action and pattern; and also the current mappings, so that when a subsequent request processing logs a warning that a request was not processed I can go back in the logs and find out the mappings.

The question is how to ensure that lines logged by registerUrlPattern/unregisterUrlPattern actually appear in the log file:

It seems to me that these methods should log the mapping changes at INFO level, since it is additional INFO being logged. But the logger's level is WARN so that will not work. The logger get many other messages at INFO level so it is not possible to change its level to INFO in production, except for troubleshooting.

I could log it at WARN level, but qa/usability/customer does not like such warnings to appear.

I can think of the following alternatives:

Change the Logger's level to INFO when logging these lines, possibly by adding a forceInfo method in my Logger (which wraps a standard log4j type logger)

Use a different Logger for these methods and set its level to INFO

Log at warning level but change the language to indicate that it is not something to be worried about


问:
Multi-module web project with Spring and Maven
Assume we have a few projects, each containing some web resources (e.g., html pages).

```<code>parent.pom
 +- web           (war)
 +- web-plugin-1  (jar)
 +- web-plugin-2  (jar)
 ...
</code>```

Let's say web is the deployable war project which depends on the known, but selectable, set of plugins.

What is a good way to setup this using Spring and maven?

Let the plugins be war projects and use mavens poor support for importing other war projects

Put all web-resource for all plugins in the web project

Add all web-resources to the classpath of all jar web-plugin-* dependencie  and let spring read files from respective classpath?

Other?

I've previously come from using #1, but the copy-paste semantics of war dependencies in maven is horrible.

答:
well, i use to work with point 3, definining all dependencies at parent's pom, including dependencies form modules, like that:

```<code><parent>
    <groupId>cat.base.baseframe</groupId>
    <artifactId>projecte-pare-baseframe</artifactId>
    <version>0.0.11.a</version>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<modules>
    <module>ogc.domini</module>
    <module>ogc.logica</module>
    <module>ogc.ejb</module>
    <module>ogc.ear</module>
    <module>ogc.ui</module>
    <module>ogc.assistent</module>
</modules>

<dependencies>
    <dependency>
        <groupId>cat.base.cuesfeina</groupId>
        <artifactId>cuesfeina.domini</artifactId>
        <version>0.0.3</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>cat.base.gea</groupId>
        <artifactId>gea.domini</artifactId>
        <version>0.0.4</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>baseOnline.ajudes</groupId>
        <artifactId>ajudes.domini</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>cat.base.tramitador</groupId>
        <artifactId>tramitador.domini</artifactId>
        <version>0.0.4</version>
        <scope>provided</scope>
    </dependency>
<dependency>
        <groupId>cat.base</groupId>
        <artifactId>mme.domini</artifactId>
        <version>1.3.3</version>
        <scope>provided</scope>
    </dependency>
</code>```

-->

everything at pom's parent's it's easy to find what you need. if you need to call some service i i use to create a public jar with functions to call the service like ejb...

Body:
well, i use to work with point 3, definining all dependencies at parent's pom, including dependencies form modules, like that:

<parent>
    <groupId>cat.base.baseframe</groupId>
    <artifactId>projecte-pare-baseframe</artifactId>
    <version>0.0.11.a</version>
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<modules>
    <module>ogc.domini</module>
    <module>ogc.logica</module>
    <module>ogc.ejb</module>
    <module>ogc.ear</module>
    <module>ogc.ui</module>
    <module>ogc.assistent</module>
</modules>

<dependencies>
    <dependency>
        <groupId>cat.base.cuesfeina</groupId>
        <artifactId>cuesfeina.domini</artifactId>
        <version>0.0.3</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>cat.base.gea</groupId>
        <artifactId>gea.domini</artifactId>
        <version>0.0.4</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>baseOnline.ajudes</groupId>
        <artifactId>ajudes.domini</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>cat.base.tramitador</groupId>
        <artifactId>tramitador.domini</artifactId>
        <version>0.0.4</version>
        <scope>provided</scope>
    </dependency>
<dependency>
        <groupId>cat.base</groupId>
        <artifactId>mme.domini</artifactId>
        <version>1.3.3</version>
        <scope>provided</scope>
    </dependency>

-->

everything at pom's parent's it's easy to find what you need. if you need to call some service i i use to create a public jar with functions to call the service like ejb...


答:
Oleski's answer is incorrect.  For SQL Server 2008, an IN list gets refactored to a series of OR statements.  It may be different in say MySQL.

I'm fairly certain that if you generated actual execution plans for both your queries they would be identical.

In all likelihood the second query ran faster because you ran it second, and the first query had already pulled all the data pages from the database and paid the IO cost. The second query was able to read all the data from memory and execute a lot faster.

Update

The actual source of the variance is likely that the queries are not equivalent.  You have two different OR lists below:

```<code>WHERE PV.Adm_Date BETWEEN @SD AND @ED
AND SO.svc_cd = 'PCO_REMFOLEY'
OR SO.svc_cd = 'PCO_INSRTFOLEY'
OR SO.svc_cd = 'PCO_INSTFOLEY'
OR SO.svc_cd = 'PCO_URIMETER'
</code>```

and later

```<code> WHERE OSM.ord_sts = 'DISCONTINUE'
    AND SO.svc_cd = 'PCO_REMFOLEY'
    OR SO.svc_cd = 'PCO_INSRTFOLEY'
    OR SO.svc_cd = 'PCO_INSTFOLEY'
    OR SO.svc_cd = 'PCO_URIMETER'
</code>```

In both those WHERE clauses, operator precendence (where AND is handled before OR) means that the actual logic run by the engine is:

```<code>WHERE (ConditionA AND ConditionB)
OR ConditionC
OR ConditionD
OR ConditionE
</code>```

If you replace the OR lists with an IN expression, the logic will be:

```<code>WHERE ConditionA
AND (ConditionB OR ConditionC OR ConditionD OR ConditionE)
</code>```

Which is radically different.

Title: SQL IN() versus OR

Body:
I was working with a query I wrote today had to change the code from the WHERE clause to use a IN(list of stuff) filter instead of using something like

```<code>item_desc = 'item 1'
OR item_desc = 'item 2'
OR item_desc = 'item 3'
OR item_desc = 'item 4'
</code>```

The above ran for 15 minutes and returned nothing, yet the following gave me my result set in 1.5 minutes

```<code>item_desc IN (
'item 1'
,'item 2'
,'item 3'
,'item 4'
)
</code>```

I did this in SQL and am wondering why the IN(list of items) performed so much faster then the OR statement.

-- EDIT --
SQL Server 2008, I do apologize for not putting this bit of info in in the first place.

Here is the Query in its entirety using the OR statements:

```<code>DECLARE @SD DATETIME
DECLARE @ED DATETIME
SET @SD = '2013-06-01';
SET @ED = '2013-06-15';

-- COLUMN SELECTION
SELECT PV.PtNo_Num AS 'VISIT ID'
, PV.Med_Rec_No AS 'MRN'
, PV.vst_start_dtime AS 'ADMIT'
, PV.vst_end_dtime AS 'DISC'
, PV.Days_Stay AS 'LOS'
, PV.pt_type AS 'PT TYPE'
, PV.hosp_svc AS 'HOSP SVC'
, SO.ord_no AS 'ORDER NUMBER'
--, SO.ent_dtime AS 'ORDER ENTRY TIME'
--, DATEDIFF(HOUR,PV.vst_start_dtime,SO.ent_dtime) AS 'ADM TO ENTRY HOURS'
, SO.svc_desc AS 'ORDER DESCRIPTION'
, OSM.ord_sts AS 'ORDER STATUS'
, SOS.prcs_dtime AS 'ORDER STATUS TIME'
, DATEDIFF(DAY,PV.vst_start_dtime,SOS.prcs_dtime) AS 'ADM TO ORD STS IN DAYS'

-- DB(S) USED
FROM smsdss.BMH_PLM_PtAcct_V PV
JOIN smsmir.sr_ord SO
ON PV.PtNo_Num = SO.episode_no
JOIN smsmir.sr_ord_sts_hist SOS
ON SO.ord_no = SOS.ord_no
JOIN smsmir.ord_sts_modf_mstr OSM
ON SOS.hist_sts = OSM.ord_sts_modf_cd

-- FILTER(S)
WHERE PV.Adm_Date BETWEEN @SD AND @ED
AND SO.svc_cd = 'PCO_REMFOLEY'
OR SO.svc_cd = 'PCO_INSRTFOLEY'
OR SO.svc_cd = 'PCO_INSTFOLEY'
OR SO.svc_cd = 'PCO_URIMETER'

AND SO.ord_no NOT IN (
    SELECT SO.ord_no
    FRROM smsdss.BMH_PLM_PtAcct_V PV
    JOIN smsmir.sr_ord SO
    ON PV.PtNo_Num = SO.episode_no
    JOIN smsmir.sr_ord_sts_hist SOS
    ON SO.ord_no = SOS.ord_no
    JOIN smsmir.ord_sts_modf_mstr OSM
    ON SOS.hist_sts = OSM.ord_sts_modf_cd
    WHERE OSM.ord_sts = 'DISCONTINUE'
    AND SO.svc_cd = 'PCO_REMFOLEY'
    OR SO.svc_cd = 'PCO_INSRTFOLEY'
    OR SO.svc_cd = 'PCO_INSTFOLEY'
    OR SO.svc_cd = 'PCO_URIMETER'
)
ORDER BY PV.PtNo_Num, SO.ord_no, SOS.prcs_dtime
</code>```

Thank you,

Body:
Oleski's answer is incorrect.  For SQL Server 2008, an IN list gets refactored to a series of OR statements.  It may be different in say MySQL.

I'm fairly certain that if you generated actual execution plans for both your queries they would be identical.

In all likelihood the second query ran faster because you ran it second, and the first query had already pulled all the data pages from the database and paid the IO cost. The second query was able to read all the data from memory and execute a lot faster.

Update

The actual source of the variance is likely that the queries are not equivalent.  You have two different OR lists below:

WHERE PV.Adm_Date BETWEEN @SD AND @ED
AND SO.svc_cd = 'PCO_REMFOLEY'
OR SO.svc_cd = 'PCO_INSRTFOLEY'
OR SO.svc_cd = 'PCO_INSTFOLEY'
OR SO.svc_cd = 'PCO_URIMETER'

and later

 WHERE OSM.ord_sts = 'DISCONTINUE'
    AND SO.svc_cd = 'PCO_REMFOLEY'
    OR SO.svc_cd = 'PCO_INSRTFOLEY'
    OR SO.svc_cd = 'PCO_INSTFOLEY'
    OR SO.svc_cd = 'PCO_URIMETER'

In both those WHERE clauses, operator precendence (where AND is handled before OR) means that the actual logic run by the engine is:

WHERE (ConditionA AND ConditionB)
OR ConditionC
OR ConditionD
OR ConditionE

If you replace the OR lists with an IN expression, the logic will be:

WHERE ConditionA
AND (ConditionB OR ConditionC OR ConditionD OR ConditionE)

Which is radically different.


问:
Avoid malicious code while dynamically loading classes with ClassLoader

Background

One of the advantages of decoupled components in systems is that you can extend the system without having to touch the existing code.

Sometimes you don't even have to recompile the old code because you can dynamically load classes from disk like this:

```<code>clazz = Demo.class.getClassLoader().loadClass("full.package.name.to.SomeClass");
</code>```

That allows for a kind of plug-in architecture of sorts (give or take).

Question

How do you prevent malicious code from running when dynamically loading a class from disk using ClassLoader ?

答:
This question is a duplication of this one on Stack Overflow.

That being said, "plugin architecture" does not sound like something where you can meaningfully defend against malicious code, as it will need to interact closely with the rest of the system. That's a game you can't win, so don't play it. Simply accept that plugins can do whatever they want in your system, so only trusted plugins should be installed.


答:
Requiring the files to be signed could help somewhat.

Here is a wikipedia article about JAR signing.

Here's the section from the wikipedia article that is significant...

Developers can digitally sign JAR files. In that case, the signature
  information becomes part of the embedded manifest file. The JAR itself
  is not signed, but instead every file inside the archive is listed
  along with its checksum; it is these checksums that are signed.
  Multiple entities may sign the JAR file, changing the JAR file itself
  with each signing, although the signed files themselves remain valid.
  When the Java runtime loads signed JAR files, it can validate the
  signatures and refuse to load classes that do not match the signature.
  It can also support 'sealed' packages, in which the Classloader will
  only permit Java classes to be loaded into the same package if they
  are all signed by the same entities. This prevents malicious code from
  being inserted into an existing package, and so gaining access to
  package-scoped classes and data.

Developers can obfuscate JAR files so that a user of the JAR file
  doesn't get much information regarding the code it contains, or to
  reduce its size, which is useful in mobile phone application
  development.

I normally wouldn't just link and quote Wikipedia. No-one had mentioned this solution yet, but it's not in my area of expertise. If someone with a bit more Java experience would give a detailed answer, drop me a comment and I'll remove this answer.

Title: Avoid malicious code while dynamically loading classes with ClassLoader

Body:
Background

One of the advantages of decoupled components in systems is that you can extend the system without having to touch the existing code.

Sometimes you don't even have to recompile the old code because you can dynamically load classes from disk like this:

```<code>clazz = Demo.class.getClassLoader().loadClass("full.package.name.to.SomeClass");
</code>```

That allows for a kind of plug-in architecture of sorts (give or take).

Question

How do you prevent malicious code from running when dynamically loading a class from disk using ClassLoader ?


问:
Should I ask/tell my boss before freelancing?
I am currently working as an intern at a consulting firm. I am soon to move to a full time employee once I graduate next semester, and I love working there. However, as a student, I lack money and I have met a business owner outside of work who has offered to hire me for some freelance web development.

Because I met this individual outside of work, I feel it would not be a conflict of interest to freelance for him. However, the work his is wanting me to do is very similar to what I already do for my current boss.

Should I speak with my boss before considering the offer?

Edit: I understand that I cannot take IP from work, and I am not in a contract, I'm employed at will.

答:
I've done a combination of full-time jobs and contracts with freelancing on the side, and full-time freelancing, for about twenty years. So I try to keep up with legal and practical ramifications in the USA.

Does your employer prohibit or limit moonlighting? This would normally be in an employee handbook or in a document you signed when you joined the company.

Even if they have such a policy, you should check, because there are labor laws and case law precedents, on both national and state levels, that void some policies like that - even if you've signed that you agree to them.

Don't compete with your employer, or take gigs with companies that compete with them. If your day job is doing websites for a dog food company, doing a website for another pet food company would be competitive, but doing one for a martial arts school wouldn't. And if your employer sells website design services... don't do websites as a side gig.

Don't use your employer's time or resources for your side work. Buy your own computers, books, development tools, etc., and keep them off the company premises. Try to avoid taking phone calls at work, and if you have to, limit them to breaks or lunch, preferably outside your employer's office.

Once you're covered on all those bases, you don't need to say anything to your employer. However, if your boss is reasonable, it might be courteous just to mention, "A friend of mine asked me to do X in my spare time." I do that, and have never gotten grief about it.


问:
Is the List interface a leaky abstraction?
If I have a variable containing a List it could contain objects of a lot of different types e.g. ArrayList or LinkedList. The difference between a LinkedList and an ArrayList is pretty big. The big O behavior of the methods differs greatly. For example sorting the List and then using it to do binary searches is perfectly ok for an ArrayList but would not make sense with a LinkedList.

答: In Java, there is a RandomAccess interface which is defined as a list with generally constant random access time (O(1) get, put etc.). If you feel that your module requires a list with those performance characteristics, consider using RandomAccess instead of List. If you don't feel the need to make that change (and few do), then perhaps List is not so leaky.


问:
Is it technically possible to write a JS interpreter using Lisp macro readers, in the browser?
Using macros readers, it's possible to interpret JavaScript, and have it compiled just like normal Common Lisp code. Hence getting the benefits of Lisp implementations, notably their performance. Which would mean having native performance in the browser, without cheating.

Would it be technically possible to build this for the browser? I'm mainly worried about the DOM bindings.

答:
Common Lisp is not the fastest in terms of execution speed when it comes to implementation of other programming languages by compiling it to Common Lisp or even interpreting it in Common Lisp.

Even Common Lisp has basically three different speed ranges:

the normal Lisp language. It can be compiled efficiently, but there are inherent things which makes it less fast than C and other low-level languages. For example it needs a lot of runtime checks and runtime decisions.

a low-level Lisp language. This can be compiled to very efficient code. But here we need and exploit performance hints, type declarations, type inference, code inlining and more.

a high-level object system (CLOS), which is hard to compile to efficient code

But Common Lisp is still used to implement languages. Sometimes for research and exploration.

For example there was an implementation of Javascript in Common Lisp. It was written by Netscape to explore Javascript semantics:

http://mxr.mozilla.org/mozilla/source/js2/semantics/

But as you can see that implementation is not simple and no, 'reader macros' are not of much help.


问:
Recommended abstraction to transfer data over a nework than byte[] array?
I was curious, why do we prefer byte[] array to transfer data over the network and not anything else?

Or if I am missing anything, what are the other ways to transfer the data over a network.

答:
Basically, at the root level it's always bytes being sent. That's just how computers work. Each character that you're reading in this reply is a series of bytes encoded using the UTF-32 format (or, maybe it's another - I didn't code this site).

There are usually many libraries that will offer you forms of abstraction to sending blocks of bytes. The most popular is, tada, HTTP, or HyperText Transfer Protocol. Even when someone's not viewing a webpage, many network programmers like coding all communications as HTTP requests to simplify the request/response architecture, and make each block of information a (usually human-readable) string.

There are tiny tradeoffs in performance that are usually completely inconsequential - but high demand situations like video game networking or video calling will often take things back down to the root level and decide how each byte should be sent, in order to be most efficient.


问:
Should software engineers also act as tech support?
Should a software engineer also act as technical support? That is, should a company allow their engineers to wear both the software engineer and technical support hats. It seems that it would remove the ability to write software if much of an engineer's time is taken up by technical support.</p>

答:
I got into this trap when I joined a company with good pay. During the interview I have been told that there will be 70% development and 30% support and I accepted the offer. May be it is the company or environment that I'm currently working on. But actually it 90% support and 10% development. Its been a couple of years now I lost the grip of development. I regret that I accepted this offer.

But I feel like I have lost the grip of coding more over there a lot of new technologies and  frameworks. Now I don't know where to start again. I keep on preparing but these helloworld examples are not enough to have some good practical experience and it is really getting difficult to update my knowledge and experience. I can't even leave my job to start over because of family commitments.

Unfortunately I'm in a deadlock.

Please don't accept roles if you dont like or not interested in.


答:
You could do any other abstraction on top of the byte arrays, that's what serialization libraries do.

But to effectively communicate, both sides have to agree on the same (de)serialization format.  While there are several semi-standard ones (XML, JSON, MessagePack, Protocol Buffers), there's no real standard, so it's unlikely to include any one on the standard libraries, because it would be limited to only interoperate with Java programs at both ends.

Still, if you're writing both ends, it's easy to convene on any one.  I typically tend to JSON in most cases, and MessagePack when either time or space savings make up for the lower readability and interoperability.

Title: Recommended abstraction to transfer data over a nework than byte[] array?

Body:
I was curious, why do we prefer byte[] array to transfer data over the network and not anything else?

Or if I am missing anything, what are the other ways to transfer the data over a network.


答:
When you want to avoid malicious code, the question is "how do you define malicious behavior"? There are countless of things a plugin could do which is not in the best interest of the user, and forbidding them all would be a pointless exercise.

Instead of blacklisting forbidden functionality, you should rather whitelist allowed functionality.

When you want to limit plugins to limited functionality, you shouldn't implement them in Java. You should rather use a scripting language. Java interfaces pretty well with scripting languages. Per default a scripting language can't do anything, but you can selectively expose packets, classes and objects to the engine. This gives you fine-grained control over what the scripting engine can and can't do.


问:
Why don't companies ship multiple modules within a mobile app? Are there concerns about tight coupling?
Preface: My question does not exclusively pertain to Google and it doesn't exclusively pertain to iOS. I'm only using Google and iOS as examples because they are familiar to many. I could have just as easily used 'Company X', apps 'A', 'B', 'C', 'D', and 'E', and 'Android', but I wanted to keep my question rooted in the real world with a tangible example.

In the iOS app store, Google has many apps. At a glance, I can see 'Google Search', 'Google+', 'Google Maps', 'Google Earth', and 'Gmail'.

But I wonder - Why didn't Google simply create a 'Google' app which can provide all of the functionality that these five apps provide? The black menu bar at the top of each Google webpage makes this possible on the web; so why don't they make this possible by way of a menu button at the bottom of one "global" Google app?

Is Google concerned about tight coupling between the apps?

Is Google concerned about tight coupling between the teams that develop the apps?

Is Google concerned about app size?

Is Google concerned about the memory footprint or CPU load that such a monolithic app might incur when it is loaded?

[Not a rant. Merely playing devil's advocate.]

In spite of many advantages, some iOS critics say that multiple pages of apps leave the iPhone and the iPad feeling "cluttered". This is particularly relevant to my question because it seems a bit much to expect a user to know about (and manage) so many Google mobile offerings. From a product standpoint, and arguably a usability standpoint, it seems like it would be wise to ship a single app.

If you're curious, I own an iPhone and a Nexus 7; so I'm not wedded to either of the two major mobile platforms.

And I have a real problem to solve here - Whether to bundle multiple apps inside of one large app, or to distribute separate bits of functionality in multiple apps.

EDIT: In response, to @MichaelT's comment

While there is indeed a 2GB size limit for apps, the size of your sandbox is only limited by the remaining capacity on the device.

答:
In layman's words:

Not all users use all of a company's apps

Different users have different needs

Why force an user to buy a full package when he/she needs only a part ? (Ok, Google apps are free, but other software maker's aren't.)

Having those apps separate makes it possible to be updated separately and, most importantly, sold separately.

The fact that several apps are made by the same company doesn't mean they belong together.

Imagine having a single "Adobe" app that comprises Photoshop, Lightroom, Reader, Dreanweaver, etc.

Imagine a single "Apple" app with this modules: iPhoto, iTunes, Aperture, etc.

This logic applies for both desktop and mobile apps

Edit:

Mobile apps usually have memory limitations (@AndreF)

Mobile apps are usually downloaded over-the-air, so a huge file size is not a good idea

Multi-module apps need more steps to navigate. Mobile users need easier, faster GUIs.


问:
Enforcing a uniform Scrum approach to all teams within a department
Where I work we recently switched the Agile development using Scrum.  We went through the typical growing pains but have reached an approach that seems to work for now (whether it'll work in the long term is for another question!).

Obviously, the department management is happy the transition to Scrum is working.  But they have starting doing something that, to me, feels wrong.

Management will observe a team, see what works for them, and the prescribe it to the entire department.  Things like:

The definition of "Done"

Which story point values can be used for story pointing (eg, omitting 8 from the fib. sequence because 1, 2, 3, 5, 13, etc were the only ones used during a sprint they observed)

Telling teams they must calibrate their story point value of 1 to "updating a UI label," and limiting them to an upper bound of 20

(although not all our projects have clients and not all developers
have UI experience)

Telling teams to use story point estimates of 100 to mean "we'll split this story later"

Telling teams to use story point estimates of infinity to mean "this is an epic" or "we need more info"

I understand they're trying to be helpful, but shouldn't all the things above be Scrum-team specific?  That is to say, what works for one group of individuals on one project may not make sense to another group on another project.

I'm concerned we're drifting into a very prescriptive and stiff Agile approach.  Am I justified in thinking this, or am I overreacting?

Edit

Just to clarify... by "Management" and "Manager" I don't mean the Product Owner.  I mean any manager outside the Scrum Team, but within the Software Department.

答:
No your not overreacting and you have good reason to be concerned. Management should be focused on culture change. Management needs to set the right direction and present the context to the teams to go at it using the agile ceremonies that work well for the team to be productive.

I feel lucky that I work in an organisation that has been going through agile transformation from waterfall for over a year and started in the portfolio that I work in. They originally started with one project where an agile team was formed. The success of the delivery through agile ceremonies like retros, relative estimate, historical forecasting using velocity led to the whole portfolio forming additional teams with their own backlog.

From experience, Agile is not prescriptive and you can't roll out a cookie cutter approach. Just because it worked in one team doesn't mean it will work in another. I know this from experience because we originally thought we could jumpstart new teams by applying a the same things like DoD, what 1 point means, what 8 point means. But it doesn't work as contextually they have little meaning when applied to a different team. Incidentally, for one team story above 8 points meant it was too big and needed to be split.

What worked was setting guidelines for the teams, like they have to do stand-ups, retros, showcases at the same time and at each retro actions where teased out and implemented to improve the new teams. Other things like definition of done and sizing of story points was introduced after a couple of sprints as the team became more familiar with the concept of story narration and completing cards and not having it creep into the next sprint.

I know this is a hard sell to management as they want to know when projects will be delivered and when forming new agile teams it is difficult to give that picture upfront. But now the portfolio has a reputation of having strong agile delivery capability. We would still be stumbling if the cookie cutter approach continued to be pushed to the other teams.


问:
Designing an scalable message queue architecture
I have recently started learning the nuances of scalable and enterprise computer architecture, and one of the central components is a messaging queue. In order to learn the most I can from any programming paradigm, I am trying to implement my own version of a messaging queue service.

So far, my initial design runs on a threaded socket listener, but in order to prevent the same message being downloaded twice by two separate processing nodes, the message queue index register is locked when a read is initiated, and unlocked after the register has been updated. As such, this negates the need for it to be threaded, and means that there is a ceiling for the size of a scalable system based on the processing speed of the server the messaging queue service is running on.

The way to get around this would be run the message queue service on multiple servers, but this will increase the likelihood of the same message being downloaded twice. The only way to prevent such issues occurring would be to include a revocation callback that (after the servers, or even the threads on a single server, have synchronized their information and detected such a re-issuance) would command the processing node to stop its current job, and re-query the message queue for the next message, but again, there would be a ceiling where most of the traffic being sent would be synchronizations, and revocation callbacks, causing a bottleneck and slowing the processing of information so that a lot of the processing nodes would be performing null operations and wasting time.

The last way I can think of to get around this problem is to have each message queue server (and each thread on each server) would have a specific offset as to where in the queue it is looking, but that might have issues based upon the type of application, especially if the processing is required to be done in a specific order.

So, all that being said, are there any designs of message queue architecture's that could show me how existing enterprise grade message queue services avoid these problems?

答:
In short:

This is a hard problem. Don't reinvent the wheel.

Many technologies solve the message queue layer.  They include

ZeroMQ

RabbitMQ

Apache Kafka

Redis, with BLPOP or PUBSUB (I've asked how to do this here).

Other AMQP implementations besides RabbitMQ

I think it's out of scope for me to discuss the drawbacks of each, not the least because I don't claim the expertise to do this well cough don't use Rabbit cough.

Even if you don't want to use any of these technologies, read their documentation.

This will educate you on design patterns that are possible over one system. Reading ZeroMQ's documentation will educate you on many classic message queuing architectures they have graciously implemented. Even if you do not use ZeroMQ, knowing these patterns will help you evaluate other queuing technologies by asking if you can implement that pattern there.

Learn about RabbitMQ/AMQP's exchange-queue model. Routing may come up for you - this is supported by Redis PUBSUB but I don't recall being supported by ZeroMQ - and fanouts are something my shop has been using, albeit poorly implemented over a Memcached poll (yuck!), for quite some time.

How to choose one?

I work at a startup whose SLA is typical for a web-app - some outages are okay, as long as we can quickly restore service with little data loss.  We haven't had to think about scaling problems like Twitter or Tumblr has, so we haven't had to think about throughput volume. That being said, if you are implementing an SLA similar to mine, these considerations will come to mind:

do the client libraries work?  Is it easy to maintain a connection in them?  (ZeroMQ, Redis: yes. RabbitMQ: no).

is monitoring and management easy from a server console? (Redis: yes, RabbitMQ: yes, ZeroMQ: not that I recall but we did not use it that long)

do clients support internal queues so little data loss occurs in short outages?  (ZeroMQ, Redis: yes. RabbitMQ: no.)

Of course, if you are working for, say, a high-frequency trading shop, these will be your lesser concerns. You'll be more willing to put development time into a client-side library in exchange for higher throughput in the end. But I'm writing this more to warn you that these technologies tend to market based on their performance, not their out-of-the-box functionality. If you're a web-startup, you are far more interested in the latter than the former, and accordingly, something like Redis, which is more optimized for ease of use at good performance than the difficulty of use at great performance, is probably a better choice than RabbitMQ.  (I don't like RabbitMQ).


问:
How many lines per class is too many in Java?
In your experience, what is a useful rule of thumb for how many lines of code are too many for one class in Java?

To be clear, I know that number of lines is not even close to the real standard to use for what should be in a particular class and what shouldn't.  Classes should be designed according to proper OOP philosophies (encapsulation, etc.) in mind.  That said, a rule of thumb could provide a useful starting point for refactoring considerations (i.e. "Hmmm, this class has >n lines of code; it's probably unreadable and doing a lousy job of encapsulation, so I might want to see if it should be refactored at some point").

On the flip side, perhaps have you encountered examples of very large classes that still obeyed OOP design well and were readable and maintainable despite their length?

Here's a related, non-duplicate question about lines per function.

答:
The correct answer is 42.  Just kidding.

Actually, the maximum recommended lines per class is 2000 lines.

"Java Code Conventions" since 1999 have stated it this way:

Files longer than 2000 lines are cumbersome and should be avoided.

Having followed Sun/Oracle Coding conventions since Java was invented,
I've found this rule of thumb on lines per class to be reasonable.
99% of your Java Code should conform... And if it goes over 2000,
just put a TODO at the top saying the class needs work.

The worst thing is the opposite case when programmers create too many tiny
little classes with almost no real functionality in each class.  Ignoring the advice to "Favor Composition", programmers create hundreds of inheriting classes which create complicated object models that are far worse than the large class problem (which at least usually keep functionality with a relevant class name).

http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141855.html#3043


答:
Clean Code:

Classes Should Be Small!

The first rule of classes is that they should be small. The second rule of classes is that they should be
  smaller than that. No, we’re not going to repeat the exact same text
  from the Functions chapter. But as with functions, smaller is the
  primary rule when it comes to designing classes. As with functions,
  our immediate question is always “How small?”

** With functions we measured size by counting physical lines. With classes we use a different measure. We count responsibilities.**

The name of a class should describe what responsibilities it fulfills. In fact, naming
  is probably the first way of helping determine class size. If we cannot derive a concise
  name for a class, then it’s likely too large. The more ambiguous the class name, the more
  likely it has too many responsibilities. For example, class names including weasel words
  like Processor or Manager or Super often hint at unfortunate aggregation of
  responsibilities.

Then:

Just make sure your methods do only one thing.

Then make sure the class doesn't have too many responsabilities.

You will end up with a class of a manageable size.

Title: How many lines per class is too many in Java?

Body:
In your experience, what is a useful rule of thumb for how many lines of code are too many for one class in Java?

To be clear, I know that number of lines is not even close to the real standard to use for what should be in a particular class and what shouldn't.  Classes should be designed according to proper OOP philosophies (encapsulation, etc.) in mind.  That said, a rule of thumb could provide a useful starting point for refactoring considerations (i.e. "Hmmm, this class has >n lines of code; it's probably unreadable and doing a lousy job of encapsulation, so I might want to see if it should be refactored at some point").

On the flip side, perhaps have you encountered examples of very large classes that still obeyed OOP design well and were readable and maintainable despite their length?

Here's a related, non-duplicate question about lines per function.


答: Any line that falls within your class's problem domain written outside of the class is one line too few and one too many in the class where it lives. Think of a class as a topic. You have to cover it. As concisely as possible is ideal but if it takes 500 lines, it takes 500 lines. If 100 of those lines cover another topic, they belong somewhere else. Breaking into smaller subdomains within the class as interior classes makes sense but I would only define those outside of the class if they had use elsewhere.</p>


问:
The 10 minutes technical interview
I must do a quick assessment of dozens of fresh students very quickly. I have 30 minutes meeting with each of them (in two or three days). I want to use most of the time to discuss non technical aspects. So I plan to use 10 minutes for technical questions. The same questions for all of them.

They are all hired already (they are students), what I need to know is the average level in order to prepare a training.

Ideally, the difficulty must be progressive in order to set a level for each. Level I will average, and I'll do an average on each question too.

If you had only 10 minutes and 10 questions to ask to a candidate, what would be your top 10 ?

答:
The students are already hired and you want to set up a training program, so part of the deal is to figure out how fast they can learn (and/or what they know: who cares which?). Why not pick some easy, medium and hard questions and give them to them beforehand. Why ambush them with questions they might not know, if they can be easily learned (by some)?

You will see, contrary to what most people imagine, that many of the students will not do very well even with the questions in hand. This way, you'll learn about your students, their knowledge, and their ability to learn.

Title: The 10 minutes technical interview