问:
Single database, multiple system dependency
Consider an environment where we have a single, core database, with many separate systems using this one database.

This leads to all of these systems have a common dependency, which ultimately introduces coupling between them.

This means that we cannot always evolve systems independently of each other.  Structural changes to the database (even if only intended for one, particular system), requires a full sweep test of ALL systems, and may require that other systems be 'patched' and subsequently released.

This is especially tricky when you want to have separate teams working on different projects.

What is a good 'pattern' to help in avoiding such coupling?

I would imagine that a database should be exclusively depended on by one system.  If other systems require data for whatever reason, they should request such from an API service of some kind.

A drawback of this approach which comes to mind is performance:  routing data between high-throughput systems through service calls is much slower than through a database connection.

答:
A few tips picked up over the years...

The database is the central repository of your data. It should be shared by many applications.

Databases are relatively benign when it comes to new projects requiring extension. Adding extra columns or tables should not upset existing products. If fields move, then yes your existing applications are affected, because your business needs changed.

Set up a "layer" around your database that does business operations rather than CRUD (e.g. makePayment(), placeOrder(); deliverTo()). If working with Java, my favourite tool is MyBatis, but there are lots of other options (Hibernate, TopLink, Spring JDBC to name a few)

Never use "select * from someTable... Always explicitly name the columns you need. So when someone adds an optional 5GB blob to your rows, you won't be hit with the overhead of reading a huge blob.

There is no silver bullet. An API hiding the details seldom helps. SOAP in particular is picky - the slightest change to the API means all clients need attention. REST is somewhat friendlier.

Good luck!


问:
Would you still use Java in your next project, despite the whole mess in JCP
It seems that there is a whole mess around current JCP.

Quite of number of highly respected guys like Doug Lea, Tim Peierls had quit JCP.

Reference :

Is JCP dead? and Final results of the JSR Review Ballot for JSR #336

This put Java in an unfavorable future. As a Java developer, will you still consider using Java in your next project?

答:
What Oracle does to Java won't matter in the short term.  All current JVMs and compilers and libraries will still be available, as well as the community.

Oracle's actions are, I think, likely to harm Java in the long run.

So, I'd have no hesitation about using it for my next project, but if I depended on it I'd consider a long-term exit strategy just in case.

ContentLicense: CC BY-SA 2.5


问:
How to release bundled software with different licenses?
Recently, I was in a situation where I wanted to release a simple piece of JavaScript software under an open source license.

However, I withdrew from it because the software contained several open source components that were released under different licenses.

Under what license should the bundled software be released (given that various third party components are mixed into the software at code level)?

答:
If parts of the bundle are under licenses that don't allow sublicensing (which is true for the majority of licenses), then you can't distribute that bundle under a single license.

The best option in that case is to explicitly state that different parts of the software are distributed under different licenses and to clearly indicate which parts fall under which license (down to identifying individual function if needed).

This can also be used if a single file contains parts that are under different licenses.

This is under the assumption that the licenses are compatible with each other and that you are thus allowed to distribute the software and that the bundle form one piece of software (it is not just a convenient collection of independent pieces of software).

If you have a bundle of independent pieces of software, then that bundle is not considered a work under copyright law and thus doesn't have a copyright of its own.

ContentLicense: CC BY-SA 3.0


答:
It depends on the license.

There are licenses like MIT or BSD, which allow you to include them in software licensed under different terms as long as you just include their copyright message somewhere where the user can read it.

On the other hand, there are licenses like the GPL which make it impossible to use a library for a software not also licensed under GPL.

Somewhere in between is the LGPL which you can use in a non-GPL project, but only as long as the library itself isn't changed and remains under GPL.

For more details, refer to the exact license terms of the libraries you are using.

Title: How to release bundled software with different licenses?

Body:
Recently, I was in a situation where I wanted to release a simple piece of JavaScript software under an open source license.

However, I withdrew from it because the software contained several open source components that were released under different licenses.

Under what license should the bundled software be released (given that various third party components are mixed into the software at code level)?


问:
How to refactor a myriad of similar classes
I'm faced with similar classes A1, A2, ..., A100. Believe it or not but yeah, there are roughly hundred classes that almost look the same. None of these classes are unit tested (of course ;-) ). Each of theses classes is about 50 lines of code which is not too much by itself. Still this is way too much duplicated code.

I consider the following options:

Writing tests for A1, ..., A100. Then refactor by creating an
abstract base class AA.

Pro: I'm (near to totally) safe by the tests that nothing goes wrong.

Con: Much effort. Duplication of test code.

Writing tests for A1, A2. Abstracting the duplicated test code and using the abstraction to create the rest of the tests. Then create AA as in 1.

Pro: Less effort than in 1 but maintaining a similar degree of safety.

Con: I find generalized test code weird; it often seems ... incoherent (is this the right word?). Normally I prefer specialized test code for specialized classes. But that requires a good design which is my goal of this whole refactoring.

Writing AA first, testing it with mock classes. Then inheriting A1, ..., A100 successively.

Pro: Fastest way to eliminate duplicates.

Con: Most Ax classes look very much the same. But if not, there is the danger of changing the code by inheriting from AA.

Other options ...

At first I went for 3. because the Ax classes are really very similar to each other. But now I'm a bit unsure if this is the right way (from a unit testing enthusiast's perspective).

答:
Your options look very well thought out.

The only true way to give a level of comfort that your refactoring doesn't break anything is option 1, as it is essential that refactoring doesn't change any behaviour, however option 3 sounds like the most sensible approach.

If I could see the same block(s) of code/logic is copy-pasted across multiple classes, then I know that logic will not be different in one class or many, so it makes sense to reduce that amount of work.

As a (very simplified) example, say we have 2 classes (C#):

```<code>Class1
{
    public int Method1(int x, int y)
    {
        int result = 0;

        result = x + y;

        return result;
    }
}

Class2
{
    public int Method1(int x, int y)
    {
        int result = 0;

        x++;
        y = y + 2;
        result = x + y;

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

In the classes above we can abstract result = x + y; into a base class:

```<code>BaseClass1
{
    public int AddTwoNumbers(int x, int y)
    {
        return x + y;
    }
}
</code>```

After both classes inherit from the base class we can safely replace result = x + y; with result = base.AddTwoNumbers(x, y); and expect the same results in the sub-classes.

Obviously result = x + y; is over simplified, and is meant to represent blocks of code that repeat, but an increased amount of code just makes it harder to come to the same conclusion: refactoring repeating code into a base class will work the same as if it was copy-pasted across many classes.

There will be caveats and what-ifs to what I've said, but the key question is what is your level of comfort in your refactoring ability?

Lastly, I assume your end result will go through a test team/environment/colleagues where you perform regression tests; this will validate that your refactoring is good, and if not you'll have the opportunity to fix it and re-test.

You're not an island, and should be able to rely on testers/colleagues to proof your work as part of the development lifecycle.

OwnerDisplayName: TobiMcNamobi

Body:
Your options look very well thought out.

The only true way to give a level of comfort that your refactoring doesn't break anything is option 1, as it is essential that refactoring doesn't change any behaviour, however option 3 sounds like the most sensible approach.

If I could see the same block(s) of code/logic is copy-pasted across multiple classes, then I know that logic will not be different in one class or many, so it makes sense to reduce that amount of work.

As a (very simplified) example, say we have 2 classes (C#):

Class1
{
    public int Method1(int x, int y)
    {
        int result = 0;

        result = x + y;

        return result;
    }
}

Class2
{
    public int Method1(int x, int y)
    {
        int result = 0;

        x++;
        y = y + 2;
        result = x + y;

        return result;
    }
}

In the classes above we can abstract result = x + y; into a base class:

BaseClass1
{
    public int AddTwoNumbers(int x, int y)
    {
        return x + y;
    }
}

After both classes inherit from the base class we can safely replace result = x + y; with result = base.AddTwoNumbers(x, y); and expect the same results in the sub-classes.

Obviously result = x + y; is over simplified, and is meant to represent blocks of code that repeat, but an increased amount of code just makes it harder to come to the same conclusion: refactoring repeating code into a base class will work the same as if it was copy-pasted across many classes.

There will be caveats and what-ifs to what I've said, but the key question is what is your level of comfort in your refactoring ability?

Lastly, I assume your end result will go through a test team/environment/colleagues where you perform regression tests; this will validate that your refactoring is good, and if not you'll have the opportunity to fix it and re-test.

You're not an island, and should be able to rely on testers/colleagues to proof your work as part of the development lifecycle.


问:
Coping with build order requirements in automated builds
I have three Scala packages being built as separate sbt projects in separate repos with a dependency graph like this:

```<code>  M---->D
  ^     ^
  |     |
  +--+--+
     ^
     |
     S
</code>```

S is a service. M is a set of message classes shared between S and another service. D is a DAL used by S and the other service, and some of its model appears in the shared messages.

If I make a breaking change to all three, and push them up to my Git repo, a build of S will be kicked off in Jenkins. The build will only be successful if, when S is pushed, M and D have already been pushed. Otherwise, Jenkins will find it doesn't have the right dependent package versions available. Even pushing them simultaneously wouldn't be enough -- the dependencies would have to be built and published before the dependent job was even started. Making the jobs dependent in Jenkins isn't enough, because that would just cause the previous version to be built, resulting in an artifact that doesn't have the needed version.

Is there a way to set things up so that I don't have to remember to push things in the right order?

The only way I can see it working is if there was a way that a build could go into a pending state if its dependencies weren't available yet.

I feel like there's a simple solution I'm missing. Surely people deal with this a lot?

答:
You could also take a look at this Jenkins plugin: https://wiki.jenkins-ci.org/display/JENKINS/Build+Blocker+Plugin.

I would recommend re-architecting your app. As a general approach and good practice, I would recommend versioning your projects/components. Each component will depend on a specific version of the other component. In this way you have full control on which dependency is being considered for the current build.


问:
Should I reference a CopyOnWriteArraySet from the Set interface?
There are two ways to use a CopyOnWriteArraySet:

```<code>// A
Set<Object> set = new CopyOnWriteArraySet<>();
</code>```

and

```<code>// B
CopyOnWriteArraySet<Object> set = new CopyOnWriteArraySet<>();
</code>```

With 'normal' sets like HashSet and TreeSet, case A is preferred, because it allows easy switching of the Set implementation.

However, in this case a conscious choice is made for a specific thread-safe Set implementation. Should I use case B to signify this intent?

答:
You can deliberately declare a more specific type to document your threading policy. However, a functioning threading policy requires much more than judiciously chosen types, so it doesn't add that much value.

In your example, you are invoking the constructor of the concrete class in the very same line, so the choice would have been obvious even anyway. It would be more worthwhile to use types for communicating if your set were returned to an external user, e.g. via an interface or a method return type.


问:
Best way to indicate more results available
We have a service to return messages. We want to limit the number returned, either allowing the caller to specify the max number to return, or else to use an internal hard limit. We also have thought it would be nice to include in the response whether more messages are available. The "best" way to go about this is not clear.

Here are some ideas so far:

Only set the "more messages" indicator if the user did not specify a max limit, and the internal max limit was hit.

Same as #1 except that "more messages" indicator set regardless of whether the internal hard limit is hit, or the user-specified limit is hit.

Same as #1 (or #2) except that we internally read limit + 1 records, but only return limit records, so we know "for sure" there is at least one additional message rather than "maybe" there are additional messages.

Do away with the "more messages" flag, as it is confusing and unnecessary. Instead force the user to keep calling the API until it returns no messages.

Change "more messages" indicator to something more akin to an EOF indicator, only set when the last message is known to have been retrieved and returned.

What do you think is the best solution? (Doesn't have to be one of the above choices.) I searched and couldn't find a similar question already asked. Hopefully this is not "too subjective".

答:
Maybe you can offer some more flexibility to the client. Your request can have a startWith element and the number of messages to retrieve noOfMessages. Your response can have a field called totalMessages that will held the total number of messages. This will allow you client to have something similar to pagination. startWith will default to zero; noOfMessages to a decent value.

For example if you have 56 messages, if the client wants to retrieve batches of 20s, they can send the following calls:

Request 1:

```<code>noOfMessages: 20
</code>```

Response1:

```<code>...message list...
totalMessages: 56
</code>```

Request 2:

```<code>startWith: 21
noOfMessages: 20
</code>```

Request 3:

```<code>startWith: 41
noOfMessages: 16
</code>```

Body:
Maybe you can offer some more flexibility to the client. Your request can have a startWith element and the number of messages to retrieve noOfMessages. Your response can have a field called totalMessages that will held the total number of messages. This will allow you client to have something similar to pagination. startWith will default to zero; noOfMessages to a decent value.

For example if you have 56 messages, if the client wants to retrieve batches of 20s, they can send the following calls:

Request 1:

noOfMessages: 20

Response1:

...message list...
totalMessages: 56

Request 2:

startWith: 21
noOfMessages: 20

Request 3:

startWith: 41
noOfMessages: 16


答:
Unit tests are great for refactoring!  Just make sure you write test code in such a way that you don't have to refactor the tests along with the code you are testing.  Refactoring the tests would undermine anything that the 100 cut-and-pasted tests would prove.

Write tests one layer removed from the code you are refactoring.  Meaning: Test the functionality that should be the same before and after, so that the tests can't tell which version of the underlying code you are testing.  That strategy may save you from writing 100 cut-and-pasted tests as well.

With a big refactor, some manual testing is often required.

Title: How to refactor a myriad of similar classes

Body:
I'm faced with similar classes A1, A2, ..., A100. Believe it or not but yeah, there are roughly hundred classes that almost look the same. None of these classes are unit tested (of course ;-) ). Each of theses classes is about 50 lines of code which is not too much by itself. Still this is way too much duplicated code.

I consider the following options:

Writing tests for A1, ..., A100. Then refactor by creating an
abstract base class AA.

Pro: I'm (near to totally) safe by the tests that nothing goes wrong.

Con: Much effort. Duplication of test code.

Writing tests for A1, A2. Abstracting the duplicated test code and using the abstraction to create the rest of the tests. Then create AA as in 1.

Pro: Less effort than in 1 but maintaining a similar degree of safety.

Con: I find generalized test code weird; it often seems ... incoherent (is this the right word?). Normally I prefer specialized test code for specialized classes. But that requires a good design which is my goal of this whole refactoring.

Writing AA first, testing it with mock classes. Then inheriting A1, ..., A100 successively.

Pro: Fastest way to eliminate duplicates.

Con: Most Ax classes look very much the same. But if not, there is the danger of changing the code by inheriting from AA.

Other options ...

At first I went for 3. because the Ax classes are really very similar to each other. But now I'm a bit unsure if this is the right way (from a unit testing enthusiast's perspective).


问:
How can if (sscanf(buf, "%i", &mode) != 1 || TRUE) be rewritten to if (TRUE)?
I got lost in the opening of this post on reddit.

How can if (sscanf(buf, "%i", &mode) != 1 || TRUE) be rewritten to if (TRUE)?  Does this assume that the sscanf never fails?

答:
I think it's assuming that even if sscanf does fail, it doesn't care.

Since the result is being ignored, I don't see the point of having this within the "if" at all.  I would guess that the sscanf call was originally on its own, then duff data started arriving (in buf) and messing up the sscanf call, so the "|| TRUE" was added to suppress the error.  Classic, Quick and Dirty fix.

Personally, I'd prefer to see this reworked:

```<code>sscanf( buf, "%i", &mode ); /* buf may or may not contain a valid mode */
</code>```

Of course, the data item addressed by &mode might well be left in an inconsistent state - possibly a value parsed from buf, possibly not - but this code doesn't care either way.

Body:
I think it's assuming that even if sscanf does fail, it doesn't care.

Since the result is being ignored, I don't see the point of having this within the "if" at all.  I would guess that the sscanf call was originally on its own, then duff data started arriving (in buf) and messing up the sscanf call, so the "|| TRUE" was added to suppress the error.  Classic, Quick and Dirty fix.

Personally, I'd prefer to see this reworked:

sscanf( buf, "%i", &mode ); /* buf may or may not contain a valid mode */

Of course, the data item addressed by &mode might well be left in an inconsistent state - possibly a value parsed from buf, possibly not - but this code doesn't care either way.


答:
It all depends to whom you want to signal this intent.

Specifics of your implementation should not be leaked to your clients. As @Killian mentions, if this fact is significant for clients useing your functionality you can document your intent into an interface that hides your actual implementation.

If you want to signal this to people that can actually modify the code, again, this can be easily documented at the method, interface level that hides the implementation.

I would suggest to stick to the first case for flexibility (as you may switch to another similar implementation) and clearly state the intentions in your documentation. Of course, having the right Unit Tests in place will prevent people adding "wrong" sets.

Title: Should I reference a CopyOnWriteArraySet from the Set interface?

Body:
There are two ways to use a CopyOnWriteArraySet:

```<code>// A
Set<Object> set = new CopyOnWriteArraySet<>();
</code>```

and

```<code>// B
CopyOnWriteArraySet<Object> set = new CopyOnWriteArraySet<>();
</code>```

With 'normal' sets like HashSet and TreeSet, case A is preferred, because it allows easy switching of the Set implementation.

However, in this case a conscious choice is made for a specific thread-safe Set implementation. Should I use case B to signify this intent?


问:
Storing and presenting custom table data
I have a web site upon which I want to provide users the ability to create tables of data. These tables will come from a predefined list of table definitions of which I will be adding to myself. This list will likely grown into the hundreds. The table definitions will be created as Java classes. They will define how many columns there are and their data types (string, numerical, boolean, pick from list). It will also predefine some columns as automatically calculated form other columns. The number of rows will be limited but this could range from 10 to 10000. Additionally I will give users an option to create a custom table type where they set the number of rows and columns and the column types (string, numerical, boolean, pick from list - no formulas).

The tables must be sortable on certain columns (with secondary sort columns depending on the first). The data sorting will (probably) be done by the application rather than the database as it will include different logic in different table definitions. I might include a simple text search but not a filter. The table data may be updated but I expect this to be infrequent (days apart, mostly never).

What I can't decide on is the best way to store this information. I am using a relation db (postgres). Since each row will be made up of various different column types I can't store the data in separate database rows with relevant field types for each column.

On the web side I want the users to be able to view paged data. Users that don't have JavaScript enabled can put up with a basic table of paged data without sort options. Users with JavaScript enabled should have options to sort data.

Storage

Option 1

Create an XML doc containing all the data and store in one row of the database. This will be easy to read and write but means the entire web table must be loaded into memory even if only delivering a few rows to the browser.

Option 2

Create XML fragment for each row and store in separate database rows. Since data will be sorted by the application the order must either be calculated when the first page is displayed and then for further pages only the required rows returned, or when data is updated a predefined index is created for each sort option. The predefined index seems like the better option as it won't change often but will be read numerous times.

Delivery of data to the browser

Option 1

For JS enabled browsers get all the data using AJAX/JSON. The response would be cached on the browser and using JS populate a table with data. Further trips to the server shouldn't be required unless the data is updated (only detected when page is refresh using a last updated time embedded in the page). Subsequent visits to the page should use the cached copy of the data.

Option 2

Embed paged data in html. If JS is enabled then further updates using AJAX.

I don't want to use HTML 5 offline storage to support older browsers.

I think I have to go for both Option 2s to accommodate non JS browsers and to minimize the memory usage.

Are there any other possible solutions?

答:
Alright, first of all, this sounds dangerously as if you're building an Inner platform: a poorly reimplemented user-visible version of the tool you're also using for developing the system. But if those really are the requirements, then fine, let's talk about how you're going to store such data.

There's no reason you should switch from a data base to XML to store user data unless there is a specific reason to do so. "each row will be made up of various different column types" isn't a good enough reason. You could still simply have a DB table whose rows store the user-defined tables and another DB table that stores the columns of the user-defined tables. In general, relational data bases can deal with complicated, even recursive user data quite well, even if the user data themselves constitute a data base of sorts.

But it cold be even easier. Why not map the user-defined tables to actual tables and their columns to actual columns? Most database engines allow you to set aside a schema, namespace etc. so that you can use any name in it without clashing with your own existing names used by your program, so you could simply implement creation of a user table as an actual CREATE and deletion as an actual DROP. There is nothing inherently dangerous about executing DROP statements as  result of user input, if the affected tables were also created by the user in the first place.


答:
I like some thing that Ian Cooper says "test things you want to preserve". If you don't want to preserve the A's class don't unit test individually, try to move your test one level of abstraction.

An option can test your System via a facade or something similar (i don't understand enough your system), test your system (not your classes) expected behavior and when you have this test that check your system you can change the implementation and refactor this A classes without breaking the test.


问:
Interface (contract), Generics (universality), and extension methods (ease of use). Is it a right design?
I'm trying to design a simple conversion framework based on these requirements:

All developers should follow a predefined set of rules to convert from the source entity to the target entity

Some overall policies should be able to be applied in a central place, without interference with developers' code

Both the creation of converters and usage of converter classes should be easy

To solve these problems in C# language, A thought came to my mind. I'm writing it here, though it doesn't compile at all. But let's assume that C# compiles this code:

I'll create a generic interface called IConverter

```<code>public interface IConverter<TSource, TTarget>
    where TSource : class, new()
    where TTarget : class, new()
{
    TTarget Convert(TSource source);

    List<TTarget> Convert(List<TSource> sourceItems);
}
</code>```

Developers would implement this interface to create converters. For example:

```<code>public class PhoneToCommunicationChannelConverter : IConverter<Phone, CommunicationChannle>
{
    public CommunicationChannel Convert(Phone phone)
    {
        // conversion logic
    }

    public List<CommunicationChannel> Convert(List<Phone> phones)
    {
        // conversion logic
    }
}
</code>```

And to make the usage of this conversion class easier, imagine that we add static and this keywords to methods to turn them into Extension Methods, and use them this way:

```<code>List<Phone> phones = GetPhones();
List<CommunicationChannel> channels = phones.Convert();
</code>```

However, this doesn't even compile. With those requirements, I can think of some other designs, but they each lack an aspect. Either the implementation would become more difficult or chaotic and out of control, or the usage would become truly hard. Is this design right at all? What alternatives I might have to achieve those requirements?

答:
You could just define an explicit operator to the do the conversion right on the Phone class like so:

```<code>public class Phone
{
     // your Phone props here

     public static explicit operator CommunicationChannel(Phone phone)
     {
          return new CommunicationChannel { PropQ = phone.PropZ };
     }
}
</code>```

To use the operator, just cast Phone as CommunicationChannel:

```<code>List<Phone> phones = GetPhones();
List<CommunicationChannel> channels = phones.Select(phone => (CommunicationChannel)phone).ToList();
</code>```

Body:
You could just define an explicit operator to the do the conversion right on the Phone class like so:

public class Phone
{
     // your Phone props here

     public static explicit operator CommunicationChannel(Phone phone)
     {
          return new CommunicationChannel { PropQ = phone.PropZ };
     }
}

To use the operator, just cast Phone as CommunicationChannel:

List<Phone> phones = GetPhones();
List<CommunicationChannel> channels = phones.Select(phone => (CommunicationChannel)phone).ToList();


问:
Would this be considered Single Tenant or Multi-Tenant?
As a company, we lease a managed server from a provider.  In that sense, our server is a single tenant server.  On this server, we have multiple customer databases.  Each customer has its own database.

We have been asked by a customer if we are a single tenant or a multi-tenant solution.  From our perspective, we are the sole tenant of the server.  But, what is the correct answer to the customer?

答: The answer is single tenant since a multi tenant setup would involve putting multiple customers in the same db. Rule of thumb. If you have a tenantId column all over your database you are probably multi tenant. </p>


问:
Finding the shortest path through a digraph that visits all nodes
I am trying to find the shortest possible path that visits every node through a graph (a node may be visited more than once, the solution may pick any node as the starting node.). The graph is directed, meaning that being able to travel from node A to node B does not mean one can travel from node B to node A. All distances between nodes are equal. I was able to code a brute force search that found a path of only 27 nodes when I had 27 nodes and each node had a connection to 2 or 1 other node. However, the actual problem that I am trying to solve consists of 256 nodes, with each node connecting to either 4 or 3 other nodes. The brute force algorithm that solved the 27 node graph can produce a 415 node solution (not optimal) within a few seconds, but using the processing power I have at my disposal takes about 6 hours to arrive at a 402 node solution.

What approach should I use to arrive at a solution that I can be certain is the optimal one? For example, use an optimizer algorithm to shorten a non-optimal solution? Or somehow adopt a brute force search that discards paths that are not optimal?

EDIT: (Copying a comment to an answer here to better clarify the question) To clarify, I am not saying that there is a Hamiltonian path and I need to find it, I am trying to find the shortest path in the 256 node graph that visits each node AT LEAST once. With the 27 node run, I was able to find a Hamiltonian path, which assured me that it was an optimal solution. I want to find a solution for the 256 node graph which is the shortest.

答:
This is NP-hard. If you have a solution for this problem, then you can use it on a graph with all edge weights set to 1. Then the resulting path will have the same number of nodes as the graph if and only if there is a Hamiltonian path. Since determining the existence of a Hamiltonian path is NP-hard even without finding specific solutions, any solution to this problem is at least as hard.

Wikipedia page:
http://en.wikipedia.org/wiki/Hamiltonian_path

Edit: You might want to look at approximate solutions, but I have little experience with those. The wiki page tells you a lot more than I can:
http://en.wikipedia.org/wiki/Approximation_algorithm


问:
Should I sacrifice code succintness to ensure the narrowest variable scope?
In many languages (e.g. both Perl and Java - which are the two languages I work most with) it is possible to narrow the scope of local variables by declaring them within a block.

Although it adds extra code length (the opening and closing block braces), and possibly reduces readability, should I create blocks purely to narrow the scope of variables to the statements that use the variables and to uphold the principle of narrowest scope or does this sacrifice succinctness and readability just to unnecessarily uphold an agreed 'best practice' principle?

I usually declare local variables to functions/methods at the start of the function to aid readability, but I could not do this, and just create blocks throughout the function and declare the variables throughout the code - within those blocks - to narrow their scope.

答:
In layman's terms:

You don't have to sacrifice succintness to narrow scope

You keep functions/methods short

With short methods/functions you don't need to use blocks for narrowing scope of variables

Using blocks for narrowing scope of variables is an indicator that your functions/methods are too long.

Functions/methods so long that they require blocks for narrowing scope of variables, are the opposite of succint.


答:
If you want to visit all nodes then you have a variation of the traveling salesman problem.

given that you are allowed to visit a node multiple times you can generate any missing with a cost of the shortest path between the 2 nodes.

For example to get to V3 from V1 you need to pass V2, you can add an edge between V1 and V3 with a cost of (V1,V2)+(V2,V3).

This way you can solve it like a traveling salesman problem and the optimum route won't make any unnecessary trips. In the above example if the constructed edge is taken then the other visit to V2 is part of the optimum path otherwise the path through V2 would have been taken.

Title: Finding the shortest path through a digraph that visits all nodes

Body:
I am trying to find the shortest possible path that visits every node through a graph (a node may be visited more than once, the solution may pick any node as the starting node.). The graph is directed, meaning that being able to travel from node A to node B does not mean one can travel from node B to node A. All distances between nodes are equal. I was able to code a brute force search that found a path of only 27 nodes when I had 27 nodes and each node had a connection to 2 or 1 other node. However, the actual problem that I am trying to solve consists of 256 nodes, with each node connecting to either 4 or 3 other nodes. The brute force algorithm that solved the 27 node graph can produce a 415 node solution (not optimal) within a few seconds, but using the processing power I have at my disposal takes about 6 hours to arrive at a 402 node solution.

What approach should I use to arrive at a solution that I can be certain is the optimal one? For example, use an optimizer algorithm to shorten a non-optimal solution? Or somehow adopt a brute force search that discards paths that are not optimal?

EDIT: (Copying a comment to an answer here to better clarify the question) To clarify, I am not saying that there is a Hamiltonian path and I need to find it, I am trying to find the shortest path in the 256 node graph that visits each node AT LEAST once. With the 27 node run, I was able to find a Hamiltonian path, which assured me that it was an optimal solution. I want to find a solution for the 256 node graph which is the shortest.


问:
Is COBOL still worth learning?
Does learning COBOL still make sense?</p>

答:
I would not spend time over it.

Anyway, COBOL is the building blocks of many legacy application programs that are mission critical for several Big Company started 20\30 years ago.

So, if you are hired for a company that has part of its core business in COBOL, there are chances that you have to start to learn it.

Title: Is COBOL still worth learning?


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
It would seem that perfection is attained not when no more can be added, but when no more can be removed.

Antoine de Saint-Exupery

LastEditorDisplayName: Roger Pate


问:
Reason to use mingw win32 headers and libs with LLVM/Clang
Is there any good reason (except "GCC is better") to use the MinGW win32api/headers/libs with LLVM/Clang. Suppose that in two to three years, Clang has matured enough (in C++0x and performance) that it's a competitor/replacement and has its advantages over MSVC like GCC does on some accounts. Why on earth would one want to avoid using the MS library and header implementations of the win32 API, which is freely available in the form of the Windows SDK?</p>

答:
The only real reason I can think of is to adopt a purely "Microsoft-free" philosophy.

You can ask the writers of the mingw win32 headers, but I suspect that there might also be some copyright concerns as well.


答:
To answer a question with a question... are you talking about mutable or immutable variables?

The value of reducing scope for mutables is much higher - it reduces what the reader/maintainer needs to examine to determine what modifications are safe - or where a bug may be coming from.

The only time I worry much about intra-function scope for immutables is when they are instantiated based on other data that may be changing state within the execution of the function.

Title: Should I sacrifice code succintness to ensure the narrowest variable scope?

Body:
In many languages (e.g. both Perl and Java - which are the two languages I work most with) it is possible to narrow the scope of local variables by declaring them within a block.

Although it adds extra code length (the opening and closing block braces), and possibly reduces readability, should I create blocks purely to narrow the scope of variables to the statements that use the variables and to uphold the principle of narrowest scope or does this sacrifice succinctness and readability just to unnecessarily uphold an agreed 'best practice' principle?

I usually declare local variables to functions/methods at the start of the function to aid readability, but I could not do this, and just create blocks throughout the function and declare the variables throughout the code - within those blocks - to narrow their scope.


问:
In MVC, why can't a model create a view?
I have a web application written in Perl with a controller, some "views" and some "Models".  Each "Model" is corresponding to one "View".  The controller (one file) creates an Model object corresponding to each view (view is a CGI argument) then retrieve the view from the module it has just created.

Indeed, this should be bad thing but can you  argue a bit more about it.

My first idea was that since the object "Model" depends upon the "view", then the "model" is actually a view.

But also the fact that ALL the cgi parameters are passed to the Model causes the "Model" to become not truelly a view but to loose all interest, since it is only related to the current implementation of the web apps.  On other words, that the "Model" keep model but loose its "comprehensiveness" ("Model" is not easily understandable).

I'm am quite new in project analysis, so please do not be too harsh.  Why is this bad?

I have made a prototype with the main structures I have understood of this web application, made as short as possible.

```<code>#Model.pm
package Model;
import {
    # this requires an attribute called "view"
    # and this require an argument which is the cgi params
}
...

#View1.pm
package View1;
...

#Model1.pm
package ModelView1 ;
base Model;
use View1;

sub new {
    my $class = shift;
    my $arg   = shift;
    Model::DoSomething($arg);
    $self->view = new View1($arg);
    ...
}

#controller.cgi
my $model = 0;
...
     $model = new Model1( cgi_param => params() );
     #there is severall models here
...
print $model->get_view()->get_html();
</code>```

答:
Consider the model being just data. It doesn't make choices, and it doesn't know how to render.

A product can be a model.

A list of products can be a model.

A bundle containing the list of products, the cart and the information about the current user is a model.

The last model from the list corresponds to the data you need to render the page, but it shouldn't know how to render itself, because it's not the task of the model.

In order to render it, a view is used, given that the controller may pick different views depending on the context. It will use for example a view to render data to an ordinary guest visitor, a different view for an authenticated user, and a third view if the user is an administrator. Same data, different modes of displaying it.


问:
What would you call the concept of CofeeScript or Sass to be?
There is this rising trend with web development of making new pseudo languages to extend the functionality of JavaScript, CSS and HTML given that those are static and their metamorphosis or evolution is painfully slow due to the variety of browser providers.

So I am currently having a concept dilema on how to categorize them for a book I was made to write by my employer as no one seems to have a name for these pseudo languages.

A tiny list of them :

JavaScript: LiveScript, Metalua, Uberscript, EmberScript.

HTML: Razor, Java Scriptlets.

CSS : LESS, Sass.

I believe the concept of these pseudo languages and a language or an extension of a language is quite different.

First these languages do not extend any functionality currently existing on HTML or CSS or JavaScript, they simply work around it.

And also they do not "compile" to an intermediate language, they are merely 1-1 translated to something that only then can be compiled.

What would you call them?

答:
There are two categories here: preprocessors and programming languages. The first is a subgroup of the second.

LESS and Sass, for example, are called preprocessors, but they are also dynamic stylesheet languages.

LiveScript is a language.

The fact that they are compiled, i.e. subject to a process which "transforms source code written in a programming language (the source language) into another computer language (the target language)" to a high-level language rather than Assembler doesn't make them "specific":

Some, like C, are compiled to Assembler,

Others, like C#, are compiled to IL,

Others, like LiveScript, are compiled to JavaScript.


答:
Derived Language or Extension Language appear to be common and well-fitting descriptors. From the Ember.js homepage:

EmberScript is a CoffeeScript derived language

and from the SASS homepage:

Sass is the most mature, stable, and powerful professional grade CSS extension language in the world.

Title: What would you call the concept of CofeeScript or Sass to be?

Body:
There is this rising trend with web development of making new pseudo languages to extend the functionality of JavaScript, CSS and HTML given that those are static and their metamorphosis or evolution is painfully slow due to the variety of browser providers.

So I am currently having a concept dilema on how to categorize them for a book I was made to write by my employer as no one seems to have a name for these pseudo languages.

A tiny list of them :

JavaScript: LiveScript, Metalua, Uberscript, EmberScript.

HTML: Razor, Java Scriptlets.

CSS : LESS, Sass.

I believe the concept of these pseudo languages and a language or an extension of a language is quite different.

First these languages do not extend any functionality currently existing on HTML or CSS or JavaScript, they simply work around it.

And also they do not "compile" to an intermediate language, they are merely 1-1 translated to something that only then can be compiled.

What would you call them?


问:
Checking negative of a condition
What is the (slightly pejorative) term for checking the negative of a condition (rather than the positive which is often more readable):

e.g.

```<code>if(!someVar) {
  return null;
} else {
  return doSomethingInteresting();
}
</code>```

instead of doing this (which is arguably more readable)

```<code>if(someVar) {
  return doSomethingInteresting();
} else {
  return null;
}
</code>```

I vaguely remember there being a term for this; something in the same spirit as the term Yoda conditions.

答:
The general term is "negative logic."

Circuit designers use it frequently as negative logic can lead to simpler circuit design than the comparable positive logic design.

But be forewarned that trying to pin down the semantics of negation can be a slippery slope.

No agreement exists as to the possibility of defining negation, as to its logical status, function, and meaning, as to its field of applicability..., and as to the interpretation of the negative judgment, (F.H. Heinemann 1944)

Title: Checking negative of a condition


问:
Augmenting functionality of subclasses without code duplication in C++
I have to add common functionality to some classes that share the same superclass, preferably without bloating the superclass. The simplified inheritance chain looks like this:

Element -> HTMLElement -> HTMLAnchorElement
Element -> SVGElement -> SVGAlement
```

<p>The default <code>doSomething()</code> method on <code>Element</code> is no-op by default, but there are some subclasses that need an actual implementation that requires some extra overridden methods and instance members. I cannot put a full implementation of <code>doSomething()</code> in <code>Element</code> because 1) it is only relevant for some of the subclasses, 2) its implementation has a performance impact and 3) it depends on a method that could be overridden by a class in the inheritance chain between the superclass and a subclass, e.g. <code>SVGElement</code> in my example.</p>

<p>Especially because of the third point, I wanted to solve the problem using a template class, as follows (it is a kind of decorator for classes):</p>

<pre class="lang-cpp prettyprint-override"><code>struct Element {
    virtual void doSomething() {}
};

// T should be an instance of Element
template<class T>
struct AugmentedElement : public T {
    // doSomething is expensive and uses T
    virtual void doSomething() override {}
    // Used by doSomething
    virtual bool shouldDoSomething() = 0;
};

class SVGElement : public Element { /* ... */ };
class SVGAElement : public AugmentedElement<SVGElement> {
    // some non-trivial check
    bool shouldDoSomething() { /* ... */ return true; }
};
// Similarly for HTMLAElement and others
</code>```

I looked around (in the existing (huge) codebase and on the internet), but didn't find any similar code snippets, let alone an evaluation of the effectiveness and pitfalls of this approach.

Is my design the right way to go, or is there a better way to add common functionality to some subclasses of a given superclass?

答:
You are doing it correctly. The thing is called a mixin and is rather common.

Quick search shows e.g. What are Mixins (as a concept) or What is C++ Mixin-Style?. They are a case of the Curiously Recurring Template Pattern, name of which even comes from the fact that it is, well, recurring.

In your case actually using full CRTP would let you avoid the virtual:

```<code>template<typename BaseT, typename DerivedT>
struct AugmentedElement : public BaseT {
    // doSomething is expensive and uses T
    virtual void doSomething() override {
        // do stuff
        static_cast<DerivedT *>(this)->shouldDoSomething();
        // do more stuff, etc.
    }
};
</code>```

Body:
You are doing it correctly. The thing is called a mixin and is rather common.

Quick search shows e.g. What are Mixins (as a concept) or What is C++ Mixin-Style?. They are a case of the Curiously Recurring Template Pattern, name of which even comes from the fact that it is, well, recurring.

In your case actually using full CRTP would let you avoid the virtual:

template<typename BaseT, typename DerivedT>
struct AugmentedElement : public BaseT {
    // doSomething is expensive and uses T
    virtual void doSomething() override {
        // do stuff
        static_cast<DerivedT *>(this)->shouldDoSomething();
        // do more stuff, etc.
    }
};


问:
Strategy to use two different measurement systems in software
I have an application that needs to accept and output values in both US Custom Units and Metric system.

Right now the conversion and input and output is a mess.  You can only enter in US system, but you can choose the output to be US or Metric, and the code to do the conversions is everywhere.

So I want to organize this and put together some simple rules.  So I came up with this:

Rules

user can enter values in either US or Metric, and User Interface will take care of marking this properly

All units internally will be stored as US, since the majority of the system already has most of the data stored like that and depends on this.  It shouldn't matter I suppose as long as you don't mix unit.

All output will be in US or Metric, depending on user selection/choice/preference.

In theory this sounds great and seems like a solution.  However, one little problem I came across is this:

There is some data stored in code or in the database that already returns data like this:  4 x 13/16" screws, which means "four times  screws".  I need the  to be in either US or Metric.  Where exactly do I put the conversion code for doing the conversion for this unit?

The above already mixing presentation and data, but the data for the field I need to populate is that whole string.  I can certainly split it up into the number 4, the 13/16", and the " x " and the " screws", but the question remains... where do I put the conversion code?

Different Locations for Conversion Routines

1)  Right now the string is in a class where it's produced.  I can put conversion code right into that class and it may be a good solution.  Except then, I want to be consistent so I will be putting conversion procedures everywhere in the code at-data-source, or right after reading it from the database.  The problem though is I think that my code will have to deal with two systems, all throughout the codebase after this, should I do this.

2)  According to the rules, my idea was to put it in the view script, aka last change to modify it before it is shown to the user.  And it may be the right thing to do, but then it strikes me it may not always be the best solution.  (First, it complicates the view script a tad, second, I need to do more work on the data side to split things up more, or do extra parsing, such as in my case above).

3) Another solution is to do this somewhere in the data prep step before the view, aka somewhere in the middle, before the view, but after the data-source.  This strikes me as messy and that could be the reason why my codebase is in such a mess right now.

It seems that there is no best solution.  What do I do?

Question

My goal is to figure out how to structure and where to place my unit conversion code within the system.  Software system in question is MVC-like (Zend Framework 2 - like) LAMP system.

Specific Example

Right now I have some class that given an id at creation time, has a method getValue(), which returns 4 x 13/16" screws.  Depending on id, different numbers can be produced, but they are still in inches.  I should note that some numbers are written with the dividing bar (13/16") and some use decimal notation (0.8125").  How could I set up my framework so that I can display such values in millimeters as well?

答:
The best way to handle multiple conversions like that is to create a Unit of Measurement type class for your application.  The UoM class will allow you to encapsulate all of those intricacies within a single area, and the rest of the code can simply call in and specify the units they need the value to come back in.

Essentially, what that does is it transforms a unit of measure into a first class object within your system.  You'll store the value as well as the units associated with the value.  If you need to convert the original units to another type, then you make a conversion call against the UoM class.

One big benefit of this is approach is that all of the ugliness of parsing and converting is handled in one place, and it sets you up for the ability to use existing external libraries where someone has already done all of the hard work for you.

For a units heavy application with a lot of unit conversions, "base classes" like this belong in their own layer and not within an MVC structure.  You are in essence creating a new fundamental type or primitive for your application.

But if you're really bound to using MVC or your app just doesn't have that many unit conversions, then the Controller would be your best bet as it can converse with both Model and View.  You could also justifiably argue that the Model would be a good area if that's where you're putting business logic.


问:
Which Continuous Integration framework do you use and why?
There are quite a few different Continuous Integration (CI) frameworks out there and I'm wondering which is the most popular.  Which frameworks have you used at firms where you work?

Is there any reason one CI framework is more popular than another - perhaps this is to do with the features it offers, things that integrate into it or maybe its just marketing?

It seems like continuous integration is used more in the Java and .net worlds than say ruby or python.  Why is this?

答: Our team works mainly in Python, C++ and Java. We use Buildbot for CI. We initially got started with it because it integrates with Trac and because it seemed simple and straightforward. I believe it is the CI framework of choice in the Python world.</p>

OwnerDisplayName: Buildbot


问:
C# inherit from a class in a different DLL
I need to make an application that needs to be highly modular and that can easily be expanded with new functionality.

I've thought up a design where I have a main window and a list of actions that are implemented using a strategy pattern.

I'd like to implement the base classes/interfaces in a DLL and have the option of loading actions from DLL's which are loaded dynamically when the application starts. This way the main window can initiate actions without having to recompile or redistribute a new version. I just have to (re)distribute new DLL's which I can update dynamically at runtime. This should enable very easy modular updating from a central online source.
The 'action' DLL's all inherit their structure from the code defined in the the DLL which defines the main strategy pattern structure and it's abstract factory.

I'd like to know if C# /.Net will allow such a construction.

I'd also like to know whether this construction has any major problems in terms of design.

答:
Sure, C# will support that.  Take a look at this example that uses the System.Collections.Generic.Dictionary as the base class.

```<code>public class MyDictionary : Dictionary<string, int> { }

public class MyMain
{
    public MyMain()
    {
        MyDictionary dictionary = new MyDictionary();
        dictionary.Add("hello", 1);
    }
}
</code>```

There are some potential problems.  Any inheriting class will be subject to changes within the base class.  So you don't want to use this approach with a base class that is likely to be changing on a frequent basis.

The biggest challenge I have seen is when the base class changes function signatures.  That wreaks havoc upon almost all of the inheriting classes.

Body:
Sure, C# will support that.  Take a look at this example that uses the System.Collections.Generic.Dictionary as the base class.

public class MyDictionary : Dictionary<string, int> { }

public class MyMain
{
    public MyMain()
    {
        MyDictionary dictionary = new MyDictionary();
        dictionary.Add("hello", 1);
    }
}

There are some potential problems.  Any inheriting class will be subject to changes within the base class.  So you don't want to use this approach with a base class that is likely to be changing on a frequent basis.

The biggest challenge I have seen is when the base class changes function signatures.  That wreaks havoc upon almost all of the inheriting classes.


答:
Surely this is a smell? Using 'OR true' in a conditional statement is jarring to read and of no functional value.

if(statement OR true) { ... } would be better written as statement; { ... } ?

Body:
I got lost in the opening of this post on reddit.

How can if (sscanf(buf, "%i", &mode) != 1 || TRUE) be rewritten to if (TRUE)?  Does this assume that the sscanf never fails?


问:
Questioning one of the arguments for dependency injection frameworks: Why is creating an object graph hard?
Dependency injection frameworks like Google Guice give the following motivation for their usage (source):

To construct an object, you first build its dependencies. But to build each dependency, you need its dependencies, and so on. So when you build an object, you really need to build an object graph.

Building object graphs by hand is labour intensive (...) and makes testing difficult.

But I don't buy this argument: Even without a dependency injection framework, I can write classes which are both easy to instantiate and convenient to test. E.g. the example from the Guice motivation page could be rewritten in the following way:

class BillingService
{
    private final CreditCardProcessor processor;
    private final TransactionLog transactionLog;

    // constructor for tests, taking all collaborators as parameters
    BillingService(CreditCardProcessor processor, TransactionLog transactionLog)
    {
        this.processor = processor;
        this.transactionLog = transactionLog;
    }

    // constructor for production, calling the (productive) constructors of the collaborators
    public BillingService()
    {
        this(new PaypalCreditCardProcessor(), new DatabaseTransactionLog());
    }

    public Receipt chargeOrder(PizzaOrder order, CreditCard creditCard)
    {
        ...
    }
}
```

So there may be other arguments for dependency injection frameworks (which are out of scope for this question!), but easy creation of testable object graphs is not one of them, is it?

答:
There is an old, old ongoing debate about the best way to do dependency injection.

The original cut of spring instantiated a plain object, and then injected dependencies though setter methods.

But then a large contingency of folks insisted that injecting dependencies through constructor parameters was the correct way to do it.

Then, lately, as using reflection became more common, setting the values of private members directly, without setters or constructor args, became the rage.

So your first constructor is consistent with the second approach to dependency injection. It allows you to do nice things like inject mocks for testing.

But the no-argument constructor has this problem. Since it's instantiating the implementation classes for PaypalCreditCardProcessor and DatabaseTransactionLog, it creates a hard, compile-time dependency on PayPal and the Database. It takes responsibility for building and configuring that entire dependency tree correctly.

Imagine that the PayPay processor is a really complicated subsystem, and additionally pulls in a lot of support libraries. By creating a compile-time dependency on that implementation class, you are creating an unbreakable link to that entire dependency tree. The complexity of your object graph has just jumped up by an order of magnitude, maybe two.

A lot of those items in the dependency tree will be transparent, but a lot of them will also need to be instantiated. Odds are, you won't be able to just instantiate a PaypalCreditCardProcessor.

In addition to instantiation, each of the objects will need properties applied from configuration.

If you only have a dependency on the interface, and allow an external factory to build and inject the dependency, they you chop off the entire PayPal dependency tree, and the complexity of your code stops at the interface.

There are other benefits, as being to specify implementations classes at in configuration (i.e. at runtime rather than compile time), or having more dynamic dependency specification that varies, say, by environment (test, integration, production).

For example, let's say that the PayPalProcessor had 3 dependent objects, and each of those dependencies had two more. And all those objects have to pull in properties from configuration. The code as-is would assume the responsibility of building all that out, setting properties from configuration, etc. etc. -- all concerns that the DI framework will take care of.

It may not seem obvious at first what you're shielding yourself from by using a DI framework, but it adds up and becomes painfully obvious over time. (lol I speak from the experience of having tried to do it the hard way)

...

In practice, even for a really tiny program, I find I end up writing in a DI style, and break up the classes into implementation / factory pairs. That is, if I'm not using a DI framework like Spring, I just throw together some simple factory classes.

That provides the separation of concerns so that my class can just do it's thing, and the factory class takes on the responsibility of building & configuring stuff.

Not a required approach, but FWIW

...

More generally, the DI / interface pattern reduces the complexity of your code by doing two things:

abstracting downstream dependencies into interfaces

"lifting" upstream dependencies out of your code and into some sort of container

On top of that, since object instantiation and configuration is a pretty familiar task, the DI framework can achieve a lot of economies of scale through standardized notation & using tricks like reflection. Scattering those same concerns around classes ends up adding a lot more clutter than one would think.

ContentLicense: CC BY-SA 4.0


答:
When you swim at the shallow end of the pool, everything is "easy and convenient". Once you get past a dozen or so objects, it is no longer convenient.

In your example, you have bound your billing process forever and a day to PayPal. Suppose you want to use a different credit card processor? Suppose you want to create a specialty credit card processor that is constrained on the network? Or you need to test credit card number handling? You have created non-portable code: "write once, use only once because it depends on the specific object graph for which it was designed."

By binding your object graph early in the process, i.e., hardwiring it into the code, you require both the contract and the implementation to be present. If someone else (maybe even you) wants to use that code for a slightly different purpose, they have to recalculate the entire object graph and reimplement it.

DI frameworks allow you to take a bunch of components and wire them together at runtime. This makes the system "modular", composed of a number of modules that work to each others' interfaces instead of to each others' implementations.

Title: Questioning one of the arguments for dependency injection frameworks: Why is creating an object graph hard?

Body:
Dependency injection frameworks like Google Guice give the following motivation for their usage (source):

To construct an object, you first build its dependencies. But to build each dependency, you need its dependencies, and so on. So when you build an object, you really need to build an object graph.

Building object graphs by hand is labour intensive (...) and makes testing difficult.

But I don't buy this argument: Even without a dependency injection framework, I can write classes which are both easy to instantiate and convenient to test. E.g. the example from the Guice motivation page could be rewritten in the following way:

class BillingService
{
    private final CreditCardProcessor processor;
    private final TransactionLog transactionLog;

    // constructor for tests, taking all collaborators as parameters
    BillingService(CreditCardProcessor processor, TransactionLog transactionLog)
    {
        this.processor = processor;
        this.transactionLog = transactionLog;
    }

    // constructor for production, calling the (productive) constructors of the collaborators
    public BillingService()
    {
        this(new PaypalCreditCardProcessor(), new DatabaseTransactionLog());
    }

    public Receipt chargeOrder(PizzaOrder order, CreditCard creditCard)
    {
        ...
    }
}
```

So there may be other arguments for dependency injection frameworks (which are out of scope for this question!), but easy creation of testable object graphs is not one of them, is it?


问:
How can I make sense of the word "Functor" from a semantic standpoint?
When facing new programming jargon words, I first try to reason about them from an semantic and etymological standpoint when possible (that is, when they aren't obscure acronyms). For instance, you can get the beginning of a hint of what things like Polymorphism or even Monad are about with the help of a little Greek/Latin. At the very least, once you've learned the concept, the word itself appears to go along with it well. I guess that's part of why we name things names, to make mental representations and associations more fluent.

I found Functor to be a tougher nut to crack. Not so much the C++ meaning -- an object that acts (-or) as a function (funct-), but the various functional meanings (in ML, Haskell) definitely left me puzzled.

From the (mathematics) Functor Wikipedia article, it seems the word was borrowed from linguistics. I think I get what a "function word" or "functor" means in that context - a word that "makes function" as opposed to a word that "makes sense". But I can't really relate that to the notion of Functor in category theory, let alone functional programming. I imagined a Functor to be something that creates functions, or behaves like a function, or short for "functional constructor", but none of those seems to fit...

How do experienced functional programmers reason about this ? Do they just need any label to put in front of a concept and be fine with it ? Generally speaking, isn't it partly why advanced functional programming is hard to grasp for mere mortals compared to, say, OO -- very abstract in that you can't relate it to anything familiar ?

Note that I don't need a definition of Functor, only an explanation that would allow me to relate it to something more tangible, if there is any.

答:
As far as I know, they are just math words you need to memorize, akin to "hypotenuse."  They didn't click for me until I stopped thinking of them as a standalone abstract concept with names that surely make sense to someone, and started thinking of them as badly-named interfaces that types implement.

Without the historical baggage of category theory, programmers would call a Functor a Mappable or something like that.  Alas, they didn't ask us, so we're stuck with names that mathematicians made up.


答:
What you are describing is an add-in or plug-in architecture. In C# it is easy to load types from DLLs dynamically. Usually you would have a separate class library (DLL) containing only interface declarations that will be referenced by the main application as well as by the add-ins. Of course you can also inherit from base classes, but you should preferably program against interfaces (where any base classes implement the interfaces). This gives you the option to inherit from an existing implementation or to provide a completely new, independent implementation.

In C# it makes no difference, whether a class inherits from a class in the same assembly or a class in another assembly. Types and members must however be public, in order to be accessible from another assembly (EXE, DLL). Types and members declared as internal are only visible within their own assembly.

In your project you must add a reference to the other assembly or project in order to use its public types. In the solution explorer right click your project and select "Add Reference... " In the "Browse" tab select another DLL or EXE. If you are referencing a project within the same solution, select the other project from the "Projects" tab. Alternatively, you can "Copy As Project Reference" in the project's context menu and in the other project "Paste Reference" in the context menu of the project/References folder. Project references automatically switch the reference between Debug/Release as you change the configuration. If you reference a DLL directly, you would typically reference the "Release" version.

It is a good idea to have an IAddIn interface which has to be implemented by all the add-ins. You can place whatever you want in this interface (add-in name, initialization method, etc.). Additional interfaces that can be implemented optionally are a good idea. Examples are interfaces allowing add-ins to provide menu entries, to consume user settings, to provide user controls that will be presented in tab pages by the main application etc.

```<code>public interface IAddIn
{
    // Allows you to list the loaded add-ins in an "About" dialog.
    string Name { get; }
    string Version { get; set; } // Set by the add-in loader.
}

public interface IMenuItemProvider
{
    IEnumerable<ToolStripMenuItem> MenuItems { get; }
}

public interface IContent
{
    string Name { get; }
    Control Content { get; } // Usually a UserControl containing other controls
}

public interface IContentProvider
{
    IEnumerable<IContent> Contents { get; }
}
</code>```

This is the add-in loader that I am using in one of my applications. It scans all DLLs found in a directory for classes implementing the IAddIn interface and returns instantiated add-in objects in a list.

```<code>public class AddInLoader
{
    public IList<IAddIn> Load(string folder)
    {
        var addIns = new List<IAddIn>();
        string[] files = Directory.GetFiles(folder, "*.dll");
        foreach (string file in files) {
            addIns.AddRange(LoadFromAssembly(file));
        }
        return addIns;
    }

    private static IEnumerable<IAddIn> LoadFromAssembly(string fileName)
    {
        Assembly asm = Assembly.LoadFrom(fileName);
        string addInInterfaceName = typeof(IAddIn).FullName;
        foreach (Type type in asm.GetExportedTypes()) {
            Type interfaceType = type.GetInterface(addInInterfaceName);
            if (interfaceType != null && (type.Attributes & TypeAttributes.Abstract) != TypeAttributes.Abstract) {
                IAddIn addIn = (IAddIn)Activator.CreateInstance(type);
                addIn.Version = asm.GetName().Version.ToString();
                yield return addIn;
            }
        }
    }
}
</code>```

The main application can then load the add-ins and test whether they implement interfaces and act accordingly.

```<code>var loader = new AddInLoader();
IList<IAddIn> addIns = loader.Load(myAddInFolder);
foreach (IAddIn addIn in addIns) {
    var menuProvider = addIn as IMenuItemProvider;
    if (menuProvider != null) {
        foreach (ToolStripMenuItem menuItem in menuProvider.MenuItems) {
            //TODO: Add menu item to application menu
        }
    }

    var contentProvider = addIn as IContentProvider;
    if (contentProvider != null) {
        foreach (IContent content in contentProvider.Contents) {
            //TODO: Add content to new tab pages
        }
    }
}
</code>```

Title: C# inherit from a class in a different DLL

Body:
I need to make an application that needs to be highly modular and that can easily be expanded with new functionality.

I've thought up a design where I have a main window and a list of actions that are implemented using a strategy pattern.

I'd like to implement the base classes/interfaces in a DLL and have the option of loading actions from DLL's which are loaded dynamically when the application starts. This way the main window can initiate actions without having to recompile or redistribute a new version. I just have to (re)distribute new DLL's which I can update dynamically at runtime. This should enable very easy modular updating from a central online source.
The 'action' DLL's all inherit their structure from the code defined in the the DLL which defines the main strategy pattern structure and it's abstract factory.

I'd like to know if C# /.Net will allow such a construction.

I'd also like to know whether this construction has any major problems in terms of design.

Body:
What you are describing is an add-in or plug-in architecture. In C# it is easy to load types from DLLs dynamically. Usually you would have a separate class library (DLL) containing only interface declarations that will be referenced by the main application as well as by the add-ins. Of course you can also inherit from base classes, but you should preferably program against interfaces (where any base classes implement the interfaces). This gives you the option to inherit from an existing implementation or to provide a completely new, independent implementation.

In C# it makes no difference, whether a class inherits from a class in the same assembly or a class in another assembly. Types and members must however be public, in order to be accessible from another assembly (EXE, DLL). Types and members declared as internal are only visible within their own assembly.

In your project you must add a reference to the other assembly or project in order to use its public types. In the solution explorer right click your project and select "Add Reference... " In the "Browse" tab select another DLL or EXE. If you are referencing a project within the same solution, select the other project from the "Projects" tab. Alternatively, you can "Copy As Project Reference" in the project's context menu and in the other project "Paste Reference" in the context menu of the project/References folder. Project references automatically switch the reference between Debug/Release as you change the configuration. If you reference a DLL directly, you would typically reference the "Release" version.

It is a good idea to have an IAddIn interface which has to be implemented by all the add-ins. You can place whatever you want in this interface (add-in name, initialization method, etc.). Additional interfaces that can be implemented optionally are a good idea. Examples are interfaces allowing add-ins to provide menu entries, to consume user settings, to provide user controls that will be presented in tab pages by the main application etc.

public interface IAddIn
{
    // Allows you to list the loaded add-ins in an "About" dialog.
    string Name { get; }
    string Version { get; set; } // Set by the add-in loader.
}

public interface IMenuItemProvider
{
    IEnumerable<ToolStripMenuItem> MenuItems { get; }
}

public interface IContent
{
    string Name { get; }
    Control Content { get; } // Usually a UserControl containing other controls
}

public interface IContentProvider
{
    IEnumerable<IContent> Contents { get; }
}

This is the add-in loader that I am using in one of my applications. It scans all DLLs found in a directory for classes implementing the IAddIn interface and returns instantiated add-in objects in a list.

public class AddInLoader
{
    public IList<IAddIn> Load(string folder)
    {
        var addIns = new List<IAddIn>();
        string[] files = Directory.GetFiles(folder, "*.dll");
        foreach (string file in files) {
            addIns.AddRange(LoadFromAssembly(file));
        }
        return addIns;
    }

    private static IEnumerable<IAddIn> LoadFromAssembly(string fileName)
    {
        Assembly asm = Assembly.LoadFrom(fileName);
        string addInInterfaceName = typeof(IAddIn).FullName;
        foreach (Type type in asm.GetExportedTypes()) {
            Type interfaceType = type.GetInterface(addInInterfaceName);
            if (interfaceType != null && (type.Attributes & TypeAttributes.Abstract) != TypeAttributes.Abstract) {
                IAddIn addIn = (IAddIn)Activator.CreateInstance(type);
                addIn.Version = asm.GetName().Version.ToString();
                yield return addIn;
            }
        }
    }
}

The main application can then load the add-ins and test whether they implement interfaces and act accordingly.

var loader = new AddInLoader();
IList<IAddIn> addIns = loader.Load(myAddInFolder);
foreach (IAddIn addIn in addIns) {
    var menuProvider = addIn as IMenuItemProvider;
    if (menuProvider != null) {
        foreach (ToolStripMenuItem menuItem in menuProvider.MenuItems) {
            //TODO: Add menu item to application menu
        }
    }

    var contentProvider = addIn as IContentProvider;
    if (contentProvider != null) {
        foreach (IContent content in contentProvider.Contents) {
            //TODO: Add content to new tab pages
        }
    }
}


答:
I've not used Google Guice, but I've taken a great deal of time migrating old legacy N-tier applications in .Net to IoC architectures like Onion Layer that depend on Dependency Injection to decouple things.

Why Dependency Injection?

The purpose of Dependency Injection isn't actually for testability, it's actually to take tightly coupled applications and loosen the coupling as much as possible. (Which has the desirable by product of making your code a lot easier to adapt for proper unit testing)

Why should I worry about coupling at all?

Coupling or tight dependencies can be a very dangerous thing. (Especially in compiled languages) In these cases you could have a library, dll, etc that is very rarely used that has an issue that effectively takes the entire application offline. (Your entire application dies because an unimportant piece has an issue... this is bad... REALLY bad) Now when you decouple things you can actually setup your application so it can run even if that DLL or Library is missing entirely! Sure that one piece that needs that library or DLL won't work, but the rest of the application chugs on happy as can be.

Why do I need Dependency Injection for proper testing

Really you just want loosely coupled code, the Dependency Injection just enables that. You can loosely couple things without IoC, but typically it's more work and less adaptable (I'm sure someone out there has an exception)

In the case you've given I think it would be a great deal easier to just setup dependency injection so I can mock code I'm not interested in counting as part of this test. Just tell you method "Hey I know I told you to call the repository, but instead here's the data it "should" return winks" now because that data never changes you know you're only testing the part that uses that data, not the actual retrieval of the data.

Basically when testing you want Integration(functionality) Tests which test a piece of functionality from start to finish, and full unit testing which test each and every piece of code (typically at the method or function level) independently.

The idea is you want to make sure the entire functionality is working, if not you want to know the exact piece of the code that isn't working.

This CAN be done without Dependency Injection, but usually as your project grows it becomes more and more cumbersome to do so without Dependency Injection in place. (ALWAYS assume your project will grow! It's better to have needless practice of useful skills than find a project ramping up fast and requires serious refactoring and reengineering after things are already taking off.)


答: I usually see it called a transpiled language, but according to wikipedia, it's also called a source-to-source compiled language or a transcompiled language.  They mainly differ from compilers in that the destination language is on the same level of abstraction as the source language, not like a high-level language to assembly.</p>


答:
As I mention in another answer, the issue here is that you want class A to depend on some class B without hard-coding which class B is used into the source code of A. This is impossible in Java and C# because the only way to import a class is to refer to it by a globally-unique name.

Using an interface you can work-around the hard-coded class dependency, but you still need to get your hands on an instance of the interface, and you can't call constructors or you're right back in square 1. So now code that could otherwise create its dependencies pushes off that responsibility to somebody else. And its dependencies are doing the same thing. So now every time you need an instance of a class you end up building the entire dependency tree manually, whereas in the case where class A depends on B directly you could just call new A() and have that constructor call new B(), and so on.

A dependency injection framework attempts to get around that by letting you specify the mappings between classes and building the dependency tree for you. The catch is that when you screw up the mappings, you'll find out at runtime, not at compile time like you would in languages that support mapping modules as a first-class concept.


答:
In category theory Functors describe relationships between categories by describing some, or all, mappings from one category to another. There are so many philosophical ideas wrapped up in this (all beautiful) it's difficult to say much that relates this to programming or other real world things that doesn't rob it of some of its intrinsic completeness, but here goes.

Imagine a dataset, and a set of functions that you could perform on that dataset. Now imagine another dataset (maybe looking or feeling very different from the first) and a set of functions you could perform on that dataset. A functor between the two dataset+function 'things' would map the dataset+function thing 1 to dataset+function thing 2 in a meaningful way i.e. would relate functions to functions so as to preserve some properties of the functions between things. Functors therefore express relationships between 'meanings' expressed by the functions in each 'thing'.

It's almost like patterns in programming - the first dataset and function 'thing' might be 'people registered to vote' and functions like 'voting history and likelihood to vote for different parties functions/mappings', the second dataset and function 'thing' might be 'quark groupings in atoms' and functions 'spin interaction prediction under different gravitational influences' and 'total quark breakdown likelihood' or some such weird stuff. A functor would map between one 'world' (dataset and functions on it) and another in a way that allowed you to talk about how you test/express truths about functional outcomes in one world and transfer the results in another because you know how the functions and datasets are related in a specific way.

Functors maps relationships between semantics i.e. are higher-order mechanisms for expressing commonalities between meanings of functional systems.

Sorry, that's as clear as I can express category theoretic functors in a 'real world' summary.

Title: How can I make sense of the word "Functor" from a semantic standpoint?

Body:
When facing new programming jargon words, I first try to reason about them from an semantic and etymological standpoint when possible (that is, when they aren't obscure acronyms). For instance, you can get the beginning of a hint of what things like Polymorphism or even Monad are about with the help of a little Greek/Latin. At the very least, once you've learned the concept, the word itself appears to go along with it well. I guess that's part of why we name things names, to make mental representations and associations more fluent.

I found Functor to be a tougher nut to crack. Not so much the C++ meaning -- an object that acts (-or) as a function (funct-), but the various functional meanings (in ML, Haskell) definitely left me puzzled.

From the (mathematics) Functor Wikipedia article, it seems the word was borrowed from linguistics. I think I get what a "function word" or "functor" means in that context - a word that "makes function" as opposed to a word that "makes sense". But I can't really relate that to the notion of Functor in category theory, let alone functional programming. I imagined a Functor to be something that creates functions, or behaves like a function, or short for "functional constructor", but none of those seems to fit...

How do experienced functional programmers reason about this ? Do they just need any label to put in front of a concept and be fine with it ? Generally speaking, isn't it partly why advanced functional programming is hard to grasp for mere mortals compared to, say, OO -- very abstract in that you can't relate it to anything familiar ?

Note that I don't need a definition of Functor, only an explanation that would allow me to relate it to something more tangible, if there is any.


答:
The "instantiate my own collaborators" approach may work for dependency trees, but it certainly won't work well for dependency graphs which are general directed acyclic graphs (DAG). In a dependency DAG, multiple nodes can point to the same node - which means that two objects use the same object as collaborator. This case can in fact not be constructed with the approach described in the question.

If some of my collaborators (or collaborator's collaborators) should share a certain object, I'd need to instantiate this object and pass it to my collaborators. So I in fact would need to know more than my direct collaborators, and this obviously doesn't scale.


问:
Need to organize words based on their components, any other way aside from brute force?
I'm not sure if this process has a name.

I have some words (about 9,000). They are in Japanese, but I'll try to explain this using English words. I want to categorize the words by the components (in English, letters).

A

B

C

act bar play

This should create:

A: play

B: bar

C: act

Now, 'a' appears in all 3 words, but I want to make sure that each category (letter) has at least word. Now, it would make sense to delete a word after it's used, but there are a few cases where 2 letters make up one word and that's each letter's only word--so I'd like to account for that somehow.

Is there an approach for solving this aside from brute force? Dynamic programming perhaps? Even a name for this process (if it exists) would be great.

答: Lucene is a powerful library used to do a variety of text searching and stemming and it might be worth taking a look at. The typical use case is full-text search but it is pretty component based under the hood so you could certainly build a custom analyizer or stemmer to get to where you wanted to be.</p>


问:
clone() only partially doable; how to react?
Suppose we have a class-hierarchy whose base class B requires a clone() method to be defined in its derivations. Whilst this works perfectly for most of them there is this one derivation X that holds an optional reference to a resource/object that can only be referenced from one instance of X. Whilst the rest of X can be cloned without problems this reference would have to be set to null/nil/nullptr.

What is the correct way to handle this situation?

X::clone() could throw an UncloneableException. Though this would be correct, it is not satisfying.

Set the reference to null/nil/nullptr and leave no notice of it. The user of X has to know about Xs "particularities".

Require derivations of B to define B::nearestClone(): the user of B has to be aware that the return value might not be a 1:1 clone.

Something else?

答:
You don't specify the language you're using, but I would suggest that one approach would be to have the base class should have a protected method cloneBase, and then for each class which could support cloning have a sealed concrete derivative which implements a covariantly-generically-typed cloning interface, with itself as the generic type parameter.  It may be useful to have this interface also include a method which implementations will use to return themselves, typed according to the generic parameter.

If AnimalBase would have no difficulty supporting cloning, but some derived classes may have non-cloneable objects, then Animal should be a sealed class which derives from AnimalBase and implements ICloneable<Animal>.  If BirdBase derives from animal, Bird would be a derivative of that which implements ICloneable<Bird>.  If Phoenix derives from Bird but can't support cloning, neither it nor any derivative would implement any ICloneable interface.

Using this approach, code which needs something that is cloneable and derives from AnimalBase could accept a parameter of type ICloneable<AnimalBase>; such a type could accept either Animal or Bird, even though those types are unrelated.  Code which needs to use an ICloneable<AnimalBase> as an AnimalBase could use its Self member.

Alternatively, one could implement an IsCloneable property/method and then have a Clone method which is only guaranteed to work if IsCloneable returns true.  Such an approach would provide no way for a type to indicate at compile time that it needed something that can be cloned, but it would avoid the need for extra sealed "leaf" types.  While there is some benefit to having methods express their requirements via their parameters, there is also benefit to avoiding the creation of otherwise-unnecessary types.


问:
How to avoid being forked into oblivion by a more powerful contributor?
As recently reported here:

Xamarin has forked Cocos2D-XNA, a 2D/3D game development framework,
  creating a cross-platform library that can be included in PCL
  projects.

However the founder of the project that was forked says:

The purpose of the MIT license is to unencumber your fair use. Not to
  encourage you to take software, rebrand it as your own, and then "take
  it in a new direction" as you say.

While not illegal, it is unethical.

It seems that the GitHub page of the new project doesn't even indicate that it's a fork in a typical GitHub manner, opting for an easily-removable History section instead (see bottom).

So my questions are:

Was Xamarin's action and the way the action was done ethical or not?

Is it possible to avoid such a situation if you are a single
developer or a small unfunded group of developers?

I am hoping this could be either a wiki question or there will be some objective answers grounded on modern OSS ethics/philosophy.

答:
What Xamarin did is legal and ethical... almost.

Let's have a look at the commit fixup of the license and misc typo fixes in the readme:

LicenseAndCredit.txt (diff)

```<code>-Copyright (c) 2010-2012 cocos2d-x.org
-
-Copyright (c) 2008-2010 Ricardo Quesada
-Copyright (c) 2011      Zynga Inc.
-Copyright (c) 2011-2012 openxlive.com
-Copyright (c) 2012      Totally Evil Entertainment, LLC
-Copyright (c) 2012      Gena Minchuk
-Copyright 2012 Xamarin Inc
+Copyright (c) The Cocos2D-XNA Team
</code>```

There's only one requirement in the whole MIT License:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

And Xamarin did exactly the forbidden thing. Xamarin may think that it makes the license "prettier" to have less copyright notices at the top, but they don't have permission (legal or ethical) to remove the "redundancy".

Of course, if they fix the license file, they will again be in the legal area. The original library's author may not agree, but he made the choice of the license and he can't blame anyone that they did what the license explicitly permits.

Body:
What Xamarin did is legal and ethical... almost.

Let's have a look at the commit fixup of the license and misc typo fixes in the readme:

LicenseAndCredit.txt (diff)

-Copyright (c) 2010-2012 cocos2d-x.org
-
-Copyright (c) 2008-2010 Ricardo Quesada
-Copyright (c) 2011      Zynga Inc.
-Copyright (c) 2011-2012 openxlive.com
-Copyright (c) 2012      Totally Evil Entertainment, LLC
-Copyright (c) 2012      Gena Minchuk
-Copyright 2012 Xamarin Inc
+Copyright (c) The Cocos2D-XNA Team

There's only one requirement in the whole MIT License:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

And Xamarin did exactly the forbidden thing. Xamarin may think that it makes the license "prettier" to have less copyright notices at the top, but they don't have permission (legal or ethical) to remove the "redundancy".

Of course, if they fix the license file, they will again be in the legal area. The original library's author may not agree, but he made the choice of the license and he can't blame anyone that they did what the license explicitly permits.


问:
Would this be considered Single Tenant or Multi-Tenant?
As a company, we lease a managed server from a provider.  In that sense, our server is a single tenant server.  On this server, we have multiple customer databases.  Each customer has its own database.

We have been asked by a customer if we are a single tenant or a multi-tenant solution.  From our perspective, we are the sole tenant of the server.  But, what is the correct answer to the customer?

答:
You offer a multi-tenant solution.

You place multiple customers' (aka tenants') data and applications on a single
server. They share core infrastructure. If that server went down, it would take
them all down. Therefore, multi-tenant.

Do not feel bad about this. Essentially all service providers are
multi-tenant, by design and necessity. Every organization has some level of
shared infrastructure. If your Internet connection, network routers, email
system, or phone system went down, multiple customers would still be negatively
affected.

Diving Deeper

The issue is not whether you are the only user of your leased server. To be
sure, if you were sharing your server with other companies, or if you are/were
running on cloud instances from the likes of AWS, Heroku, or Rackspace that are
themselves fundamentally multi-tenant, that would move you deeper into
"multi-tenant" territory.

As Esben Skov
Pedersen
suggests, if you dumped all customers' information in a single database
separated only by customerId or tenantId columns, that would clearly,
unequivocally be multi-tenant.

But consuming your full leased server and separating your customer databases,
while good and proper, do not make you a truly single-tenant solution.

The core issue is how much infrastructure your multiple clients' share, how
deeply and closely they share it, and what degree of isolation and separation
from one another they enjoy. As in the real-estate concept it appropriates,
tenancy in IT is a continuum, not a binary single/multiple condition.

Even if you own your own house, pretty much everyone who lives there will have
access to all the parts of the house; they probably share meals and watch TV
together. In a large apartment building, there are lots of individual units, but
the tenants in #231 aren't free to come eat food out of #232's fridge, nor,
absent a specific invitation, come plop down on #232's couch to watch Law and
Order reruns. While families in their apartments may share exactly like
single-tenant houses, it isn't a free-for-all for all tenants; sharing the same
roof, parking lot, mail area, and hallways is expected, but apartments are still
individual spaces. And there are even more-shared examples, such as boarding
houses and shopping malls, where individual tenants may have their own spaces,
but there are large public spaces for eating, restrooms, and gathering that are
shared communally by everyone. In each of these points along the single/multi
continuum, there is some sharing, but with varying scope of what is shared, by
whom, with what restrictions.

In your case, all your tenants share a single server. Is each run in its own
virtual machine or system partition? You separate the databases for each, but
are they managed by a common DBMS engine?

The underlying issue here is isolation. The less isolation and the more
sharing, the deeper into multi-tenancy you've delved. So: How separate are one
customer's data from anther's? Could a virus, rogue program, or rogue user of
one customer's data or apps somehow view or change the data belonging to another
customer? If there were a runaway query or infinite loop running in one
customer's app, would all the performance in the system be sucked into it,
denying other customers quality access to their data/apps?

How much isolation is required will vary by customer. Some will accept deeply
multi-tenant services like Google Mail and Google Apps without any qualms.
Others balk at anything less than their services running on distinct, unshared
hardware and infrastructure--the closest to a pure "single tenant" scenario. For
them, even running each customer's apps and data in separate virtual machines
(VMs) or hardware partitions (like IBM LPARs) will not be "good enough"
separation and isolation.

The reality is that most services today are run with some degree of
multi-tenancy. That true even among individual enterprises, where datacenters
are increasingly run with high degrees of server consolidation and
virtualization. Cloud and other external service providers are fundamentally
multi-tenant. And the typical degree of multi-tenancy is increasing. More
services are being shared, more intimately, across multiple tenants. Which is
why infrastructure providers such as
Oracle
and
NetApp
make a special point to offer features aiming to support multiple customers'
data under the care of the same storage manager.

To really answer your customer's question, you need to explain what components
are shared. If you run every customer in their own unique virtual machine, with
their own distinct database engine, but those VMs run on shared hardware--that
is probably good enough, these days, to be a credible "primarily single tenant"
answer. You still need to disclose your shared infrastructure. Depending on how
it's configured, it might also be fair to characterize your solution as "multi-instance"--admitting that there's
shared infrastructure, but suggesting more isolation. But if you're
running under a single server without each customer in its own VM, or with all
customers' individual databases managed by a common database engine or on a
common storage farm--then "multi-tenant" is the only possible honest answer.