问:
What algorithm pairs blocks so that the weighted average of the two blocks falls within an upper and lower bound?
What algorithm would pair parcels with a high proportion of property x to a parcel with a low proportion of property x so that the  weighted average of the two parcels falls within an upper and lower bound? The algorithm needs to pair a set of parcels to maximise the quantity that fall into the given range. The parcels are of differing size. </p>

<p>For example, suppose I have a table of data that has tonnes of each block and percentage iron in each block. I can process two blocks at the same time to create an average iron percentage. I want to change the sequence of each block to maximise the tonnes that fall inside a percentage iron range. </p>

答:
Create a list of all the parcels sort the list of parcels by weight.

Remove parcels from either the head or the tail of the list until the average weight falls within an acceptable range.

Pair each parcel at the head with a parcel at the tail, moving inwards, to get your pairs of parcels.


问:
What to do when your company doesn't encrypt passwords
Background

I'm been contracted to help a company maintain their server. I work on some minor PHP projects but also look over performance issues and recently, scan logs for hackers.

These guys have been running their server for some time and have what I would call a legacy application on its last legs. It uses magic quotes, global variables (which allows $id to be overwritten by $_GET['id']), use .htaccess as their only security in some instances, you name it. A security and programming nightmare.

We have been hacked in the past, mostly with SQL injections, which would run SLEEP(99999999) commands and act as a DOS-attack. Luckily they didn't run "little bobby tables",

XKCD: http://xkcd.com/327/

So I re-wrote their vulnerable SQL statements from mysql_query() (not mysqli) to PDO transactions. I'm also analyzing the queries for SLEEP and UNION, which we don't use but the injections have. So far, so good.

Latest Issue

Recently we've been told records are changing in the DB for users, such as their e-mail addresses to ones presumably made by spammers.

I noticed their columns didn't have a last_modified column, so we weren't able to even know when they were being changed, let alone by who. I added that column, but that's barely a first step.

When I was looking in to this table, I noticed the passwords weren't salted nor even hashed, just saved as plaintext.

Client Communication

How can I approach them about the entire situation, as a contractor, without flailing my arms like a madman? Any advice? I was thinking a calm approach of,

```
    ISSUE #1
        Synopsis
        Why this is an issue
        What can happen if this is not fixed
        Suggested fix

    ISSUE #2
        Synopsis
        Why this is an issue
        What can happen if this is not fixed
        Suggested fix
        ```

答:
It really depends on the audience in which you are trying to approach with this. I have worked in companies with severe security issues like you are stating yet they refused to hear it until I showed it to them.

One approach, if feasible, is to put together basically what you are intending to do as will as itemizing what has already possibly happened in these hacks. If your audience is non technical you probably need to point out the business cost that these compromises can have. Obviously hacked accounts reduces credibility in your system and perceived customer value of your product. Not to mention a compromised system with plain text passwords and email addresses for users can cause a serious rippling effect.

The next thing you should do, if at all possible, is prove it. If you can stand this system up in a test environment do it. Then demonstrate in front of them the kind of impact you can have on the system from the client side of the application. Even with tech people this has proven to be pretty convincing for me (though they still didn't usually act in my cases).

Of course, like you said, you need to explain if anything what measures should be taken and an estimate on the effort to accomplish that. It will help them justify the cost though some places simply just won't care anyway. At least you can clear your conscious and move forward knowing you tried.

OwnerDisplayName: bafromca

ContentLicense: CC BY-SA 3.0


问:
Should a method in a class be aware that the class has "loaded" a variable?
So I have the following code, which connects and then binds to an LDAP server.

The question is in the first method.

```<code>  public function getUsers() // This is the method in question
  {
    if( $this->connect()->bind() ) {
      ldap_query(self::$connection) // Here, should it be aware that class succesfully loaded
         // the connection, or should the bind() method return the resource?
    }
  }

  public function connect()
  {
    self::$connection = ldap_connect($this->host);
    if( ! self::$connection ) {
      throw new \CHttpException(503, 'No se puede establecer una conexión con el servidor '.$this->host);
    }
    foreach( $this->options as $option => $value ) {
      ldap_set_option(self::$connection, constant($option), $value);
    }
    return $this;
  }

  public function bind()
  {
    $ldapbind = ldap_bind(self::$connection, $this->username.'@'.$this->domain, $this->password);
    if( ! $ldapbind ) {
      throw new \CHttpException(503, 'No se puede enlazar con el servidor: '.ldap_error(self::$connection));
    }
    return true;
  }
</code>```

答:
Classes (or objects as instances of classes) create a local scope where member variables serve as "global" within the boundaries of this scope. This is intentional, so it is perfectly ok if one member function initializes a member variable and a second makes use of the fact the first function finished successfully without an exception.

So in your case: if bind() initializes  $ldapbind (and does not throw an exception), there is no reason to return $ldapbind. getUsers can just safely assume $ldapbind to be initialized.


答:
Rather than having to worry about your class successfully creating and binding a connection.  Have the resource passed in to class as part of the constructor.  The connect and bind would be part of their own class that would return the resource that you pass in to the class that calls getUsers.  Then you don't have to worry whether or not a connection was actually made to use as it has to exist for to even use the class.

You could alternatively have a Connection interface that your class expects which wraps the resource and provides a query method that you would use to get the users in your getUsers method.  This way if you decide to change what you connect to get your users, you only need to create a new class that uses the Connection interface and it will work without any problem.

Title: Should a method in a class be aware that the class has "loaded" a variable?

Body:
So I have the following code, which connects and then binds to an LDAP server.

The question is in the first method.

```<code>  public function getUsers() // This is the method in question
  {
    if( $this->connect()->bind() ) {
      ldap_query(self::$connection) // Here, should it be aware that class succesfully loaded
         // the connection, or should the bind() method return the resource?
    }
  }

  public function connect()
  {
    self::$connection = ldap_connect($this->host);
    if( ! self::$connection ) {
      throw new \CHttpException(503, 'No se puede establecer una conexión con el servidor '.$this->host);
    }
    foreach( $this->options as $option => $value ) {
      ldap_set_option(self::$connection, constant($option), $value);
    }
    return $this;
  }

  public function bind()
  {
    $ldapbind = ldap_bind(self::$connection, $this->username.'@'.$this->domain, $this->password);
    if( ! $ldapbind ) {
      throw new \CHttpException(503, 'No se puede enlazar con el servidor: '.ldap_error(self::$connection));
    }
    return true;
  }
</code>```


问:
Finding most Important Node(s) in a Directed Graph
I have a large (≈ 20 million nodes) directed Graph with in-edges & out-edges. I want to figure out which parts of of the graph deserve the most attention. Often most of the graph is boring, or at least it is already well understood. The way I am defining "attention" is by the concept of "connectedness" i.e. How can i find the most connected node(s) in the graph?

In what follows, One can assume that nodes by themselves have no score, the edges have no weight & they are either connected or not.

This website suggest some pretty complicated procedures like n-dimensional space, Eigen Vectors, graph centrality concepts, pageRank etc. Is this problem that complex?

Can I not do a simple Breadth-First Traversal of the entire graph where at each node I figure out a way to find the number of in-edges. The node with most in-edges is the most important node in the graph. Am I missing something here?

答:
Just by sketching this out on a piece of paper, I opted for the depth-first search. Why? Well, by using the idea mentioned above, of traversing the graph by following the directed edges, we can ideally keep track of how many times we visit a particular node by incrementing some stored integer. You could do it just as easily with breadth-first.

```<code>void search(node) {
    nodeInitial = pick a node
    for(nodeInitial:outgoingNodes as node) {
        node:visits++ // this is how you track in-edges
        if(node is unvisited) {
            search(node)
            node:visited = true
        }
    }
}
</code>```

Part of the problem is that with a directed graph, you might have sub-graphs that are connected to themselves, but are not connected externally. Other parts of the graph might connect to these sub-graphs, but there may be no outgoing connections. Think of an island (or group of islands) that has 3 one-way inbound-only highways traveling towards it but no outgoing highways. I think this is the bigger challenge - how to go about selecting parts of the graph that are unvisited. The only way I can think to do this would be if the nodes themselves also keep track of what other nodes are pointing at them (incoming nodes). From there, you would need to modify the algorithm so that it chooses a new node from some incoming node after it's done a complete traversal of an entire sub-graph. Then hop over to that other sub-graph and traverse it until you need to jump to the next sub-graph, etc.

I think it would be easy enough to store the "most important" node with the most in-edges by simply creating a single, separate node object that would be updated as you traverse the graph.

```<code>Node mostImportant = null

void search(node) {
    nodeInitial = pick a node
    if(!mostImportant) {
        mostImportant = nodeInitial
    }

    for(nodeInitial:outgoingNodes as node) {
        node:visits++ // this is how you track in-edges

        if(node.visits > mostImportant.visits)
            mostImportant = node

        if(node is unvisited) {
            search(node)
            node:visited = true
        }
    }
}
</code>```

Body:
Just by sketching this out on a piece of paper, I opted for the depth-first search. Why? Well, by using the idea mentioned above, of traversing the graph by following the directed edges, we can ideally keep track of how many times we visit a particular node by incrementing some stored integer. You could do it just as easily with breadth-first.

void search(node) {
    nodeInitial = pick a node
    for(nodeInitial:outgoingNodes as node) {
        node:visits++ // this is how you track in-edges
        if(node is unvisited) {
            search(node)
            node:visited = true
        }
    }
}

Part of the problem is that with a directed graph, you might have sub-graphs that are connected to themselves, but are not connected externally. Other parts of the graph might connect to these sub-graphs, but there may be no outgoing connections. Think of an island (or group of islands) that has 3 one-way inbound-only highways traveling towards it but no outgoing highways. I think this is the bigger challenge - how to go about selecting parts of the graph that are unvisited. The only way I can think to do this would be if the nodes themselves also keep track of what other nodes are pointing at them (incoming nodes). From there, you would need to modify the algorithm so that it chooses a new node from some incoming node after it's done a complete traversal of an entire sub-graph. Then hop over to that other sub-graph and traverse it until you need to jump to the next sub-graph, etc.

I think it would be easy enough to store the "most important" node with the most in-edges by simply creating a single, separate node object that would be updated as you traverse the graph.

Node mostImportant = null

void search(node) {
    nodeInitial = pick a node
    if(!mostImportant) {
        mostImportant = nodeInitial
    }

    for(nodeInitial:outgoingNodes as node) {
        node:visits++ // this is how you track in-edges

        if(node.visits > mostImportant.visits)
            mostImportant = node

        if(node is unvisited) {
            search(node)
            node:visited = true
        }
    }
}


问:
What development process encourages frequent releases (rolling code to a live site), as well as developer individuality
Some quick background - we don't have PMs or upper management breathing down our necks about status of features, etc, as we almost always deliver ahead of time and have built up a high level of trust with them. In other words, we have a huge amount of flexibility as far as process goes. We do very well with our current process, but we feel there can be some improvement.

We have a small team (3 devs, 1 tester) and everyone on the team is senior level and can deliver large pieces of functionality, and usually does so on an individual basis. Sometimes two people work on the same story/task, but since we are all very familiar with the codebase(s), we typically handle things by ourselves and consult/collaborate when needed.

We roll to a live site and have the ability to roll on a daily basis, which someone on our team typically does.  On average, I'd say an individual developer rolls his own code 3 times a week.

We have been doing scrum with 2 week sprints, but from my experience scrum was more advantageous when we needed the majority of the team to work on the same features at the same time (swarm-type stuff), and when needing to communicate out to external teams. We currently don't have either of those needs, so we're re-evaluating our process.

What it seems like we're moving toward is a model where each team member exists in his/her own sprint (with optional teammates being less common), which lasts anywhere from 1-3 days. We don't have a requirement that all sprints have to end on the same days, etc, so in theory we could pull this off. My question is, is there something better than scrum that models this type of development process?

Oh, I almost forgot. We're moving away from TFS to use Git, and while I have experience with Git, most of the team members don't. Since it's a paradigm shift for some on the team, I'm wondering if we can use the change to our advantage somehow process-wise. Thoughts?

答:
If you take a step back and look at why 'formal' development processes such as Waterfall, Extreme, Scrum evolved, its because many development houses struggle with developing software products (as opposed to 'software programs') that met the business and customers requirements. Every published process is an attempt to provide a framework to help achieve these goals. Some frameworks (e.g. Rational RUP) are large and prescriptive, others (e.g. Agile) a light weight and provide guidelines.

What you have evolved may not be Scrum, but is a form a Agile. It does not need a name to work. It appears to be working for you and does not appear to be broken, do not change what you are doing because someone says they have a different way.

What I suggest you do is look at you process and ensure that it is more than luck that is keeping it working. Document how you work now so its repeatable - pretend anotehr team wants to adopt what you are doing and write it up.

Look for weaknesses - For instance a team of 3 could become a team of two overnight and feasibly a team of one. Is the process robust against this kind of change, can you bring a new member into the team with little process change? Does it scale - can you double the size of the team and still get the same results - if not, ask is it needed, and document the decision.


问:
Algorithm for defragmenting cross-pipe issues in a network for routing signals through?
I have a network I'm responsible for routing signals through.  You can think of the network as a directed graph of nodes (hardware) but each edge is really a pipe capable of fitting a specific bandwidth, I can route signals to any index on that pipe and may have multiple signals of different 'size' going across the pipe.  For what it's worth the signals are predetermined sizes and will not always be simple multiple of twos.

I know how to defragment a single 'pipe' easily enough.  However,  it's theoretically possible that I could have to move signals around across multiple pipes to create enough room to fit a new signal.  In a trivial example I could have two edges from A to B with enough space to fit a signal of size '4' available, and a signal of size '8'.  To fit the signal across I would have to move some signals from pipe 2 to 1 so that 1 is completely freed, living a full '8' slots available for my new signal to routed in.

How to detect and properly defragment these sort of cross-pipe issues?

Of course in the real world I may have to route signals through completely different devices, perhaps having signals take less-direct routes, to free up enough space for my new signal on any given pipe.

So in short across an entire system of these networks I want to

find a method to get a signal from input to destination in a crowded environment where I may have to move multiple signals to take a different path to their destination in order to free up sufficient space on a given pipe

figure out how to do the above with the minimum number of signals physically moved

have an approach that minimizes the need of running the above steps by minimizing fragmentation as much as possible.

This is a complicated series of requirements on their own, and I'm not looking for an answer on how to do it all, though such an answer is welcome.

答:
Per Steve Ever's comments I looked into flow graphs.  I ultimately stumbled upon the concept of multi commodity flows (http://en.wikipedia.org/wiki/Multi-commodity_flow_problem) which basically states that the problem is known to be an NP-complete problem; there is no fancy algorithm to solve the problem as I had defined it apparntly.

However, I refuse to accept the sort of slow down a purely NP-complete approch would take.  Instead I decided to redefine the problem slightly.  By using a rather bastardized version of the buddy approch (http://en.wikipedia.org/wiki/Buddy_memory_allocation) I'm able to get my time allocation down to log(n) for most of my pipes.  I still need an NP complete approch for the final step, but the final step can be limited to a situation with only a few dozen 'flows'/pipes to map, making even an NP approch doable.  However, this approch is depending on specifics of my own system, it doesn't solve the problem as stated above, mearly simplifes the factors to such a small fraction as to make NP complete doable.

Sorry for anyone reading this problem that was hoping for a good solution to the stated problem.  The best I can suggest is Linear Programming.


问:
Why should an "Order" object have a "Status" property?
I always see standard Order classes implemented with a "Status" property, but I don't feel comfortable with that. Isn't the status a property of the fulfillment process instead of the order itself? What about orders that can be subject to different fulfillment processes?</p>

答:
Isn't the status a property of the fulfillment process instead of the order itself?

It is. The Status shouldn't belong to an Order, neither the taxes or other financial details. When modelling the Order concept it should be modelled according to what it is (domain definition) and NOT according to how it's displayed or used by other domain processes.

A customer doesn't order statuses, discounts or taxes. He orders products/services and attaches vouchers or coupons codes. And that's all an Order should contain. Financial details and order fullfilment tracking are use cases of the concept NOT parts of the concept.

What a client or store employee sees is a view model which contains more than the document Order. It contains inventory data or invoice data or shipping data. So the Status is actually a concept of the Order fulfilment process (saga) which can be organized in other processes (product reservations, billing, shipping) each with their very own statuses.

OP, you're right: Status has no place in Order's definition. It's just the easy way out to define an improper model mixing together different subdomains.


问:
Distribution of Event Listeners in a Distributed Service Oriented Architecture
I have a service architecture composed of services that service common areas of the application. Examples of services would be:

AccountService (manages client accounts in the system)

BillingService (bills clients for products that are configured)

UserService (manages user and groups under a given client)

NotificationService (sends notifications via email/SMS/push/any method when certain events happen)

I have an ActiveMQ cluster where I push events to act on...which leads to the question...

Where is the right place to put a message listener that reacts to an event for the purposes of sending a notification? A simple example would be: "I want to notify the account owner via e-mail when a new user is added to their account."

Should this listener be in NotificationService (which is intended to be highly generic), or in UserService (where the action is being performed), or in a separate service entirely which acts as a sort of router?

答: And my opinion is that it belongs to the NotificationService because "I want to notify the account owner via e-mail when a new user is added to their account." It's a notification which happens to be related to an user.


问:
How to shorten the case statement from hades?
I'm refactoring code and have reached a horribly gigantic switch statement.  Every single API method available to end users is represented as an enum and we have a switch statement iterating over the enum and responding to each possible API call.

Each individual enum option has only a few lines of code.  Any sufficiently complicated command gets a method call that is made.  However, with so many different enums ever a half dozen lines per enum grows to be rather huge.

What is the correct approach to make this cleaner?  I could write a unique method for every command, but I already moved all the complicated functionality to their own classes.  Does having a new method for a 4-5 lines of code only ever called once really add that much additional cleaneness to the code as a whole?

It seems rather tedious to create unique methods for all these cases, and the switch would still be a bit ugly even if it only allocated two lines to each enum (method call and break).  Is there a better way to avoid the switch statement entirely?

How would one try to keep this clean?

ps. this is in java, functional programing is clearly not an option.

答:
You say each case in your big switch corresponds to a public (also published?) API method. From this, I deduce that calls to those API methods are, in reality, calls to some common function with the corresponding enum parameter. I also assume you have the capability to change this public API interface.

It doesn't matter the size of those methods; if they are independent, they should be isolated in separate, public functions. This is true for methods implementing unrelated behaviour, and is orthogonal to their implementation in itself (those classes you mention having all the complicated stuff). A different thing is having several methods with similar behaviour, in which case a single, parameterized method maybe could be added instead. The main guideline in order to reduce the quantity of public functions would be avoiding behaviour duplicity on them.

Last, but not least, try to group semantically related methods (perhaps using static classes), in order to bring in some structure to the otherwise flat array of functions.


问:
In iOS, y-axis starts from the top and grows downward. It is the opposite to macOS. What is the rationale and technical advantage behind this change?
In iOS, the coordinate (0, 0) means the top left corner. In macOS it is the bottom left corner.

What is the Apple's rationale or technical advantage of this coordinate system?

答:
There are very specific legacy and mathematical reasons why this is the case. Let's go back in time for a bit. It's the 1980s. The Apple Lisa pioneered a visual system known as LisaGraph. This evolved into QuickDraw which was extended as it became obvious that more colors and resolution were needed. QuickDraw was a 2D raster system that had a fixed number of pixels and used a reflected Cartesian system of coordinate numbering with negative numberings being at the left and top and positive being  right and bottom. (0,0) would have been the center of the screen.

This system got tossed out the Window when Steve Jobs came back to Apple and brought NeXTStep with him. NeXT had used Display PostScript to power NeWS, its windowing system. Display Postscript uses a vector coordinate system with the lower left corner being (0,0) as this is how vectors are commonly referenced in mathematics.

Thus when it came time to build Quartz for Mac OS, they kept the same coordinate system and vector baseline. You can flip Quartz and Cocoa windows on Mac OS X if you want them to be similar to iOS.

The dominate coordinate system is upper left from Windows and it makes sense that Apple wanted to attract as many people as possible to build apps for its hotly selling tablets and phones. Given that the views can rotate with the phone in iOS but not Mac OS X, it stands to reason that they'd want the coordinate model for iOS to be fixed rather than adjustable.

ContentLicense: CC BY-SA 4.0


答:
This is coming from a C# perspective, but what I would do in that case is the following:

Refactor all of the "small bits of code" into separate methods.

Create a dictionary which is keyed on the enum and which contains an Action delegate (a delegate which returns void and is parameterless).

Create a method which adds each enum/delgate pair to the dictionary.

Use the dictionary as a lookup to execute the correct code.

And for more advanced users:

Create an attribute which takes the enum value as a parameter.  On load, reflect over the assembly and automatically add each enum value/method pair to the dictionary (this will save on all the "adding to dictionary" code).

Title: How to shorten the case statement from hades?

Body:
I'm refactoring code and have reached a horribly gigantic switch statement.  Every single API method available to end users is represented as an enum and we have a switch statement iterating over the enum and responding to each possible API call.

Each individual enum option has only a few lines of code.  Any sufficiently complicated command gets a method call that is made.  However, with so many different enums ever a half dozen lines per enum grows to be rather huge.

What is the correct approach to make this cleaner?  I could write a unique method for every command, but I already moved all the complicated functionality to their own classes.  Does having a new method for a 4-5 lines of code only ever called once really add that much additional cleaneness to the code as a whole?

It seems rather tedious to create unique methods for all these cases, and the switch would still be a bit ugly even if it only allocated two lines to each enum (method call and break).  Is there a better way to avoid the switch statement entirely?

How would one try to keep this clean?

ps. this is in java, functional programing is clearly not an option.


问:
Checking equality of a request parameter
I have a codes table that stores name value pairs and a group name.

So for this example let me demonstrate with two rows, each row would represent one value in the same drop down.

Group Name = 'Drop_Down_1'
Name = 'Value 1'
Value = 'This is my value'

Group Name = 'Drop_Down_1'
Name = 'Value 2'
Value = 'This is my value 2'

This value would be apart of a drop down on a webpage.  When selected and submitted the backend code would get the value 'This is my value', if that value in the drop down was selected.  Now depending on the drop down selection I want to do something.

So now i need to compare the string in the request command to something.

What I do NOT want to do is something like this:

```<code>    if(requestParam.equals('This is my value') {
        do something
    }
    else if(requestParam.equals('This is my value 2') {
        do something else
    }
</code>```

Now I can query the database and get the appropriate codes back and check against those for equality.  But How would i know what action to perform?

答:
Like MikeBabcock indicates, a variant of the Command Pattern is applicable here.

Create a structure that encapsulates the logic that you'll want to execute:

```<code>public interface RequestHandler{
   public void handleRequest();
}

public class RequestHandlerImpl{
   public void handleRequest(){
      //do your thing
   }
}
</code>```

You'll create implementations of RequestHandlerImpl to encapsulate the use-case specific business logic

Hold instances of your handlers in a Map. Here, RequestParam is a hypothetical Enum that corresponds to your dropdown menu's items. I won't recommend using the raw String to handle this

```<code>Map<RequestParam,RequestHandler> handlers = new HashMap<RequestParam, RequestHandler>(); //this is going to hold your handlers
</code>```

Using RequestParam (String arguments from your dropdown), you can pull the desired handler from the map, without an if statement:

```<code> public void execute(){
    handlers.get(MY_VALUE_1).handleRequest();
 }
</code>```

I would only recommend this however, if you have more than 3 possible courses of action, based on your arguments. Any less than that, the above implementation might be overkill; a simple switch statement on enums might be more effective and easier to read

Body:
Like MikeBabcock indicates, a variant of the Command Pattern is applicable here.

Create a structure that encapsulates the logic that you'll want to execute:

public interface RequestHandler{
   public void handleRequest();
}

public class RequestHandlerImpl{
   public void handleRequest(){
      //do your thing
   }
}

You'll create implementations of RequestHandlerImpl to encapsulate the use-case specific business logic

Hold instances of your handlers in a Map. Here, RequestParam is a hypothetical Enum that corresponds to your dropdown menu's items. I won't recommend using the raw String to handle this

Map<RequestParam,RequestHandler> handlers = new HashMap<RequestParam, RequestHandler>(); //this is going to hold your handlers

Using RequestParam (String arguments from your dropdown), you can pull the desired handler from the map, without an if statement:

 public void execute(){
    handlers.get(MY_VALUE_1).handleRequest();
 }

I would only recommend this however, if you have more than 3 possible courses of action, based on your arguments. Any less than that, the above implementation might be overkill; a simple switch statement on enums might be more effective and easier to read


问:
Super Fast File Storage Engine
I basically have one big gigantic table (about 1.000.000.000.000 records) in a database with these fields:

id, block_id, record

id is unique, block_id is not unique, it contains about 10k (max) records with the same block_id but with different records

To simplify my job that deals with the DB I have an API similar to this:

```<code>Engine e = new Engine(...);
// this method must be thread safe but with fine grained locked (block_id) to improve concurrency
e.add(block_id, "asdf"); // asdf up to 1 Kilobyte  max

// this must concatenate all the already added records added block_id, and won't need to be bigger than 10Mb (worst case) average will be <5Mb
String s = e.getConcatenatedRecords(block_id);
</code>```

If I map each block to a file(haven't done it yet), then each record will be a line in the file and I will still be able to use that API

But I want to know if I will have any peformance gain by using flat files compared to a well tunned postgresql database ? (at least for this specific scenario)

My biggest requirement though is that the getConcatenatedRecords method returns stupidly fast (not so with the add operation). I am considering caching and memory mapping also, I just don't want to complicate myself before asking if there is an already made solution for this kind of scenario ?

答:
After some research. I found that these data stores makes for the most part of use cases I have:

MVStore of H2 Database

MapDB

Oracle Bekeley DB Java Edition

And Kyoto Cabinet that seems to have inactive development

The interesting part is that all they mostly back the API of java collections (lists, sets, maps...)

All these projects allow me to open a file as a data store of huge collections and I can reference them by name, and there can be many collections per file. Each of them are indexed. The idea is that these projects are to be used as a foundation for real databases, you can view them as the data store engine of the database (be it SQL or NoSQL).

Because these projects are the foundation for projects like mongodb, h2database and orientdb, then I am sure that if the simplistic datastore approach fits my needs, it will also scale without any problems. Because my partition needs are very simplistic I can also share the load with other nodes.

Title: Super Fast File Storage Engine


问:
What is the general tech news website every programmer should read?
A link and a quick explanation why would be very helpful.

General tech news, I mean not like InfoQ which is too technical. Probably much more like P.SE than SO.

EDIT: site should help developers gain general knowledge about the industry, technologies, inventions, etc. Much like when we listen to the news every morning in our car to know what is happening in our world. But target audience must be either programmmers, geeks or any other persons interested in technology.

答: Smashing Magazine One of the best source for web development.

ContentLicense: CC BY-SA 2.5


问:
Finding minimum path with return?
I'm having trouble understanding a past quiz question I got:

Bobby works at Starbucks in San Mateo (V). He is doing quality assurance testing and needs to visit stores in Palo Alto (B), Tenderloin (C), and San Jose (S) - and then return to San Mateo for a meeting.

The distances between the stores are:

V→B = 2

V→C = 3

V→S = 6

B→C = 1

B→S = 5

C→S = 4

Which is the first store he visits in the optimal solution to this problem?

How would you approach solving this problem? It reminds me a bit of Djistra's algorithm but I suspect there's an easier way other than trying every combination as the time limit is short.

My interpretation:

```<code>  B__1__C
  |     |
2 |     | 4
  |__6__|
  V     S
</code>```

For Bobby to visit all 4 stores and return to V, he simply starts at V and travels the edges of the above box. But the question is asking which is the first store? Either direction will give a total of 13, so how is there a right answer?

答:
The right answer is that path which has the least cost. While this is technically traveling salesman and an exact solution is very difficult to achieve quickly, you can typically achieve an optimal or near optimal route by using a greedy, novelty hungry algorithm.

The algorithm is thus:

For current node pick the path with the least cost provided it leads to a node you've not visited prior. Travel to the new node and repeat until all nodes but the origin have been visited. Then visit origin by min cost path.

We start with an empty graph:

Next we mark the current node as "visited" (bold) and follow the least cost path to an unvisited node:

We continue this pattern for the next two nodes:

Now we have no new nodes to visit but we have the origin node connected so we take that path:

Thus we arrive at our solution. This algorithm is most optimal for fully connected graphs with distinctly weighted edges. We of course have used a form of Dijkstra's algorithm which confirms what you suspected. The best possible cost is 13.

Title: Finding minimum path with return?


问:
Why is it hard to make a Java program 'appear native'?
Most Java applications don't look the same as C/C++ applications. Swing might have been designed on purpose to have a distincitve look, but based on what I've read, SWT for example tried to 'look native', and doesn't completley succeed.

My question is:

Why is it hard for the developers of the Java language to design a GUI system that copies exactly the look of native GUIs? What's different in native GUIs? Isn't it only a matter of designing buttons that look like 'native' buttons? Or does it go deeper than that?

答:
Which operating system do you want to look "native" too?

You just can't be native to all of them 100% of the time.

SWT etc. are the best effort approach to look as native to all of them as it gets when you need to reach some compromise.

And in fact, this compromise starts to become more and more hard to reach; not so much because of operating systems, but because of input devices. For touchscreens, you actually have to design differently, because there is no right mouse button. Therefore, you need to accomodate the same functionality otherwise.

There will never be a magic button that moves functionality "intuitively" from the right mouse button to guestures, without you specifiying every detailed aspect for every single input device (at which point, you are native to every platform you have considered, but nevertheless non-native to any you have not considered).


问:
How do I get a project owner to participate in acceptance testing?
I have started using Pivotal tracker for a project I'm working on.  Conceptually, this seems really cool and I'm interested in using the agile model. However, I have one problem with everything talked about in the video.

At 4:19 in the linked video they talk about story acceptance and how it should be done by the project owner. This concept sounds great on paper but I'm not sure I can actually get the project owner to sit down and try out even half of the new features I create, let alone all of them.

My question is: how do you approach a product owner about the work that this flavor of the Agile Model asks of them? What do you do if they refuse to participate in acceptance testing?

答:
What you are mentioning is a classic problem that many companies have introducing agile development.

Unfortunately, there's no easy solution.

For the specific problem of acceptance, the "standard" workaround is having someone in the team acting as a proxy for the product owner. This is not great but it can work as long as this person takes care to demo regularly to the owner so they maintain the same perception of what is accurate.

Product owners are supposed to work together with the team on a day-to-day basis. This is because typically units of work (i.e. stories) are negotiated during development. E.g. a UI for a story is not designed beforehand. Its design is negotiated during development, so design decisions are validated on a working solution instead of a piece of paper. There's no easy solution here. If everything is decided beforehand, there will be quality issues or inefficiencies, because it's really hard to design everything beforehand.

There's often lack of clarity on what the acceptance tests of a user story are. An absentee product owner often will not provide enough, or any, acceptance tests to make it clear what the final "black and white" objectives of a story are. Unfortunately, this means that someone in the team, possibly a QA person, will gradually replace the PO on this matter and this is not a good solution, since many of these tests are quite arbitrary in nature and teams often end up disagreeing on when a story is complete.

Probably the biggest problem, though, is the lack of agility. Having a set of stories and a "perfect" idea of a product is not a good implementation of agile. If everything you need to do is known in advance, you probably don't need this methodology. The strength of agile is that it maximizes the value delivered by changing the project scope and direction in flight to take advantage of the increased product knowledge that it's acquired during development. If there is no one to guide this process, there is basically no point developing with a methodology only "theoretically" agile.


问:
How to measure that a team is doing Test Driven Development
My team is considering a department goal of doing Test Driven Development next (fiscal) year.

TDD sounds good and my manager is on board.  The only problem is measurement.

Our company rules require that department goals be measurable.

Is there any (sane) way to measure if a team is doing TDD?

Note: We had a goal for writing unit tests already, so a code coverage goal will not work. We write the unit tests but we do it after the fact, not before.

Is there a way to measure that TDD is being done?

(NOTE: We use Visual Studio 2013 and TFS in case it matters)

答:
TDD should generate at least 1 unit test per class. For every class in a project there should be at least 1 unit test that was written for that class, and it tests just that class.

Unit test to class ratios, code coverage, etc.. etc.. seem like things that give a meaningful measurement, but they don't.

What you want to measure is the complexity of classes, and how well those classes are tested. The higher the complexity of a class the greater the risk that class introduces into a system.

You can have 100% test coverage on a highly complex class, but that doesn't mean you've tested it well.

Complexity is the measurement of how many logical decision pathways there are in code. You can have a chunk of code that generates 1 million possible decision combinations and have 100% code coverage. It doesn't mean you tested all 1 million cases.

The other issue is how much of the system uses these complex class?

So this means some unit tests are more important than others, and it's those tests you want done very well.

This is something that is very hard to measure...


问:
Tips for a novice PHP developer to drive down long-term maintenance costs
I'm an experienced Java developer who is just starting up a project for an NGO. I will be working on the project for at least 6 months, following which the NGO will have to pay or find a volunteer to maintain the project. Seeing as they already have people working on their website in PHP, I figured PHP was the obvious choice to make sure the skills are still available (it is webby) - eliminated Java because Java devs are typically expensive. Unfortunately I have next to zero experience with proper PHP development (just a few months spending a small percentage of my time on a Drupal project without any real coding). What are some things I can do to ensure that the code I leave behind is maintainable by a relatively low-skilled PHP developer (eg a teenager wanting to make some holiday cash)? Do I go with a CMS? Are Drupal developers cheap? Any other CMS / Framework I should look at?

Background: the project is a website that people will search for educational information, with some simple user-management to only allow some users to create content, restrictions to specific content-types etc.

The CMS vs write myself question is not the only thing I'm interested in hearing. I'm also interested in any tips about code style, anything you think my Java experience would push me towards that is going to make it difficult for the hypothetical volunteer etc. There's probably things about this scenario that I haven't thought through - so anything related to keeping maintenance costs low would be appreciated.

答:
Definitely go with a well-known CMS like Drupal, Wordpress or Joomla.  They all have very large communities and therefore plenty of developers and developer resources.

Trying to build your own will lead to a good deal of pain :-)


答:
Just like a unit test should test behaviour not implementation your department should measure the anticipated result of the policy, not implementation of the policy.

Your department wants to move to TDD. Why? What is it you're hoping to achieve through TDD? Fewer bugs raised that are regression related? Faster velocity on cases? Then you should measure these things instead of trying to find a way to measure that everyone is using TDD.

If the hoped for results of your push to TDD isn't something externally measurable, such as a more enjoyable developer experience and improved flow (one of the things I like about TDD), then you shouldn't need to change your testing at all because you'd be "refactoring" the department.

Instead I suggest just asking for feedback from the developers on how they think TDD is going. If they don't 'buy-in' to the TDD concept then it doesn't matter how you measure it - it will fail.

Title: How to measure that a team is doing Test Driven Development

Body:
My team is considering a department goal of doing Test Driven Development next (fiscal) year.

TDD sounds good and my manager is on board.  The only problem is measurement.

Our company rules require that department goals be measurable.

Is there any (sane) way to measure if a team is doing TDD?

Note: We had a goal for writing unit tests already, so a code coverage goal will not work. We write the unit tests but we do it after the fact, not before.

Is there a way to measure that TDD is being done?

(NOTE: We use Visual Studio 2013 and TFS in case it matters)


问:
Best way to hide API key in source code
I need some ideas on how to protect a private API key in an application, specifically in a c# .NET application.

Firstly, I understand that it is theoretically impossible to hide anything in the source code, so I came up with another idea, but I'm not sure how plausible it is. Anyway, would it be possible to somehow communicate with a web server to verify the private key and then talk back to the application to confirm that it is a legitimate handshake?

I'm have two keys to work with: a public key (as the name suggests, it doesn't have to be treated with the same care as the private), and a private key, which needs to be kept secure from others.

Any ideas on how I could do this would be greatly appreciated.

答: If you have a key in the object code, it is public by definition. There are hacks around obfuscators that quickly decompile object code. A private key would be outside the object code and in another file. The hard part is providing this private key to the user. Once it is provided, you can use a signature of the private key, tacked onto the end of the file, and a public key within the application, to verify the integrity of the private key. A web server can also do this verification, if you have a secure communication channel.</p>

Title: Best way to hide API key in source code


问:
Creating a online database creator
I've been thinking of creating an online database creator (think DabbleDB, Zoho Creator, Intuit Quickbase, etc.).

I've been thinking of a couple solutions:

Have 4 database tables: Tables, Rows, Columns, Items. To create a database as a user, you'd go to the "Add New Table" page, give a name and type to as many columns as you want, then save. Then you'd be taken to a page which displayed a list of rows that had items inside that corresponded with the columns. The problem with this approach is I can't figure out how to link the item with both the row and the column.

Create an actual database table for each user, and when they insert a new column ( or field), it would just a database INSERT. Cons: I think this would be slow and expensive (correct?), not to mention would make a feature like how DabbleDB did relationships between tables very hard to implement.

So what is the best way to build this? Or is there a better way than even the two I've mentioned.

答:
Doing #1 alone means that when you want to do queries against your tables of tables, you're going to have to develop the code to do it yourself that will result in some very gnarly JOIN and/or UNION clauses.  You will eventually end up implementing a database on top of your database.  This is not a road you want to travel unless you have lots of spare time and money and a burning urge to reinvent the wheel.

If I understand #2 correctly, that has the same problems with each user's data split out into otherwise-identical tables.  This is something that an index on a single table can accomplish with ease.  So you probably don't want to go down this road, either.

What you want is a hybrid approach where you have tables of data about your data ("metadata") and tables that hold the data itself.  When the end user creates or alters a table ("meta table"), your software creates or alters a corresponding database table.  Everything that ends up in your metadata is assigned an identifier that's safe for the underlying database, so tables are named T1, T2, etc. and columns are named C1, C2, etc.

When a query (e.g., "Get me every foo from table bar where the corresponding baz is 5"), look up the bits and pieces in your meta tables and use them to form a query like this:

```<code>SELECT C1 FROM T1234 WHERE C2 = 5
</code>```

This will allow you to take advantage of all of your underlying database's performance-enhancing abilities.  Part of your metadata, for example, could be a list of what columns are going to be queried, and that could in turn be used to create indexes.

Title: Creating a online database creator

Body:
Doing #1 alone means that when you want to do queries against your tables of tables, you're going to have to develop the code to do it yourself that will result in some very gnarly JOIN and/or UNION clauses.  You will eventually end up implementing a database on top of your database.  This is not a road you want to travel unless you have lots of spare time and money and a burning urge to reinvent the wheel.

If I understand #2 correctly, that has the same problems with each user's data split out into otherwise-identical tables.  This is something that an index on a single table can accomplish with ease.  So you probably don't want to go down this road, either.

What you want is a hybrid approach where you have tables of data about your data ("metadata") and tables that hold the data itself.  When the end user creates or alters a table ("meta table"), your software creates or alters a corresponding database table.  Everything that ends up in your metadata is assigned an identifier that's safe for the underlying database, so tables are named T1, T2, etc. and columns are named C1, C2, etc.

When a query (e.g., "Get me every foo from table bar where the corresponding baz is 5"), look up the bits and pieces in your meta tables and use them to form a query like this:

SELECT C1 FROM T1234 WHERE C2 = 5

This will allow you to take advantage of all of your underlying database's performance-enhancing abilities.  Part of your metadata, for example, could be a list of what columns are going to be queried, and that could in turn be used to create indexes.


问:
Why is PHP's method of comparing different types bad?
I'm working on designing a new programming language and trying to decide how I will do variable comparisons.  Along with many different types of languages, I've used PHP for years and personally had zero bugs related to its comparison operations other than situations where 0 = false. Despite this, I've heard a lot of negativity towards its method of comparing types.

For example, in PHP:

```<code> 2  <  100      # True
"2" < "100"     # True
"2" <  100      # True
</code>```

In Python, string comparison goes like this:

```<code> 2  <  100      # True
"2" < "100"     # False
"2" <  100      # False
</code>```

I don't see any value in Python's implementation (how often do you really need to see which of two strings is lexicographically greater?), and I see almost no risk in PHP's method and a lot of value.  I know people claim it can create errors, but I don't see how.  Is there ever really going to be a situation where you are testing if (100 = "100") and you don't want the string to be treated as a number?  And if you really did, you could use === (which I've also heard people complain about but without any substantial reason).

So, my question is, not counting some of PHP's weird conversion and comparison rules dealing with 0's and nulls and strings mixed with characters and numbers, are there any substantial reasons that comparing ints and strings like this is bad, and are there any real reasons having a === operator is bad?

答:
The biggest problem is that an equivalence relationship, the mathy term for things like ==, is supposed to satisfy 3 laws.

reflexivity,   a == a

commutativity  a == b means b == a

transitivity   a == b and b == c means a == c

All of these are very intuitive and expected. And PHP doesn't follow them.

```<code>'0'==0 // true
 0=='' // true
'0'==''// false, AHHHH
</code>```

So it's not actually an equivalence relationship, which is a pretty distressing realization for some mathy people (including me).

It also hints at one of the things that people really hate about implicit casts, they often behave unexpectedly when combined with the mundane. It's basically just an arbitrary set of rules because it's unprincipled in this sense, weird stuff happens and it all needs to be specified case by case.

Basically we sacrifice consistency and the developer has to shoulder the extra burden of making sure there's no funny (and expensive) conversions happening behind the scene's. To quote this article

Language consistency is very important for developer efficiency. Every
  inconsistent language feature means that developers have one more
  thing to remember, one more reason to rely on the documentation, or
  one more situation that breaks their focus. A consistent language lets
  developers create habits and expectations that work throughout the
  language, learn the language much more quickly, more easily locate
  errors, and have fewer things to keep track of at once.

EDIT:

Another gem I stumbled across

```<code>  NULL == 0
  NULL < -1
</code>```

So if you try to sort anything, it's nondetermistic and entirely dependent on the order in which comparisons are made. Eg suppose bubble sort.

```<code>  bubble_sort([NULL, -1, 0]) // [NULL, -1, 0]
  bubble_sort([0, -1, NULL]) // [-1, 0, NULL]
</code>```

Body:
The biggest problem is that an equivalence relationship, the mathy term for things like ==, is supposed to satisfy 3 laws.

reflexivity,   a == a

commutativity  a == b means b == a

transitivity   a == b and b == c means a == c

All of these are very intuitive and expected. And PHP doesn't follow them.

'0'==0 // true
 0=='' // true
'0'==''// false, AHHHH

So it's not actually an equivalence relationship, which is a pretty distressing realization for some mathy people (including me).

It also hints at one of the things that people really hate about implicit casts, they often behave unexpectedly when combined with the mundane. It's basically just an arbitrary set of rules because it's unprincipled in this sense, weird stuff happens and it all needs to be specified case by case.

Basically we sacrifice consistency and the developer has to shoulder the extra burden of making sure there's no funny (and expensive) conversions happening behind the scene's. To quote this article

Language consistency is very important for developer efficiency. Every
  inconsistent language feature means that developers have one more
  thing to remember, one more reason to rely on the documentation, or
  one more situation that breaks their focus. A consistent language lets
  developers create habits and expectations that work throughout the
  language, learn the language much more quickly, more easily locate
  errors, and have fewer things to keep track of at once.

EDIT:

Another gem I stumbled across

  NULL == 0
  NULL < -1

So if you try to sort anything, it's nondetermistic and entirely dependent on the order in which comparisons are made. Eg suppose bubble sort.

  bubble_sort([NULL, -1, 0]) // [NULL, -1, 0]
  bubble_sort([0, -1, NULL]) // [-1, 0, NULL]


问:
What programming language generates fewest hard-to-find bugs?
What language, in your opinion, allows the average programmer to output features with the least amount of hard-to-find bugs? This is of course, a very broad question, and I'm interested in very broad and general answers and wisdoms.

Personally I find that I spend very little time looking for strange bugs in Java and C# programs, while C++ code has its distinct set of recurring bugs, and Python/similar has its own set of common and silly bugs that would be detected by the compiler in other languages.

Also I find it hard to consider functional languages in this regard, because I've never seen a big and complex program written in entirely functional code. Your input please.

Edit: Completely arbitrary clarification of hard-to-find bug: Takes more than 15 minutes to reproduce, or more than 1 hour to find cause of and fix.

Forgive me if this is a duplicate, but I didn't find anything on this specific topic.

答: Ada is designed so that as much as possible is caught at compile-time rather than run-time. What this means is that it often takes about 10x longer to get a program in Ada to compile than the equivalent would in Java say, but when it does compile you can be much more confident that whole classes of bugs will not manifest themselves when the program's run.</p>


答:
Its the old practitioners versus theoreticians conflict.

In Computer Science theory strong typing etc is considered good, and, there are a lot of theoretical (and some practical) ambiguities that arise e.g.  do you really want ("2.000" == "2.0") to evaluate to true?

However in practice its just plain nice to be able to code:

```<code>if (user_choice == 2)
</code>```

rather than the equivalent Java

```<code>try {
    if (Integer.parseInt(user_choice) == 2) {
       isTwo = true;
    } else {
       isTwo = false;
} catch (NumberFormatException nex) {
       isTwo = false;
}
</code>```

Title: Why is PHP's method of comparing different types bad?

Body:
I'm working on designing a new programming language and trying to decide how I will do variable comparisons.  Along with many different types of languages, I've used PHP for years and personally had zero bugs related to its comparison operations other than situations where 0 = false. Despite this, I've heard a lot of negativity towards its method of comparing types.

For example, in PHP:

```<code> 2  <  100      # True
"2" < "100"     # True
"2" <  100      # True
</code>```

In Python, string comparison goes like this:

```<code> 2  <  100      # True
"2" < "100"     # False
"2" <  100      # False
</code>```

I don't see any value in Python's implementation (how often do you really need to see which of two strings is lexicographically greater?), and I see almost no risk in PHP's method and a lot of value.  I know people claim it can create errors, but I don't see how.  Is there ever really going to be a situation where you are testing if (100 = "100") and you don't want the string to be treated as a number?  And if you really did, you could use === (which I've also heard people complain about but without any substantial reason).

So, my question is, not counting some of PHP's weird conversion and comparison rules dealing with 0's and nulls and strings mixed with characters and numbers, are there any substantial reasons that comparing ints and strings like this is bad, and are there any real reasons having a === operator is bad?

Body:
Its the old practitioners versus theoreticians conflict.

In Computer Science theory strong typing etc is considered good, and, there are a lot of theoretical (and some practical) ambiguities that arise e.g.  do you really want ("2.000" == "2.0") to evaluate to true?

However in practice its just plain nice to be able to code:

if (user_choice == 2)

rather than the equivalent Java

try {
    if (Integer.parseInt(user_choice) == 2) {
       isTwo = true;
    } else {
       isTwo = false;
} catch (NumberFormatException nex) {
       isTwo = false;
}


问:
Is it normal to get your software development products critiqued?
I am currently a software developer on coop that was in an interesting situation today. I cannot say too much, as the things I do are under NDA, but I make Grasshopper 3D (which is a Rhino plugin) components.

Our firm has under three software developers including me. We all specialize in different languages. This project I was working on, I was in charge of creating a piece of software that has a very broad general use. It's an extension from typical Grasshopper behavior.

With this said, the other developer I worked with has been in this industry for a good... decade or two. He is very knowledgeable towards the use of Grasshopper. His prior education involved great use of it, and his daily work involves the use of Grasshopper (though not explicitly what I am doing, which is creating C# components for it).

With that said, my final component went through a number of iterations. It seemed each iteration was better than the previous. An interesting point is, the other developer I worked with (I was essentially under his wing) manages to break my component every single time. I don't mean this in a malicious way.

By breaking, I meant, he was able to overflow particular lists. He was able to, after almost every iteration, find ways that my component could be improved on. Honestly, I really feel grateful for his suggestions and critique, because these were honestly things that either I overlooked, or did not know could happen.

My question is are three-fold:

Is it normal in software development practices/companies to have someone critique and improve your code? There was no code review. It was simply ways improving the tool through either UX improves or back-end improvements. And honestly, even though there was no code review, I learned so much from his suggestions which I always found success in implementing.

Are there any suggestions for a more "formal" testing procedure? I am relatively new to the software development world, and thus am interested in software dev testing procedures.

How can I improve on my way to "predict" issues?

At one side, I feel like there are issues that I cannot normally find out myself because everyone uses a piece of software differently. On another side, I feel it may be my oversight or incompetence that's causing this.

I'm reading up on this thread, and it seems in a way, we have a loose testing procedure, though it's all dependent on me to ask for critique.

答:
yes, it's called QA

When anybody discovers a bug, create a test that reproduces it, then fix the code so the test passes.  That way, this specific issue should never appear again.

practice, practice, practice.

To reduce your dependency on outside testing, make sure you incorporate as much testing as possible in the coding process itself.  Consider every requirement specification as a source of tests.  Then write the code to make those tests pass.


问:
Need an optimization algorithm
I need this algorithm for one of my projects. I will paraphrase the problem.

There are 'n' ropes that have different colored rings on them. (The colors might repeat on the same rope or across different ropes).

My job is to pick a few of these ropes and join them such that all the colors in the n ropes are included in that joined rope. I should get the smallest rope size possible. I am allowed to cut each rope once and discard the end part if needed. There is one pre-defined end for each rope which should be used as the starting point incase that rope is included in the solution.

It will be nice to have exact solution for this.(This gives us something like a goal that our project is aiming to achieve). Can someone tell me how I might approach this? The n is about 10^5 for my work.

The total number of colors is also of the order of 10^5. The number of distinct colored rings on each rope ranges from 0 to about 10^3 at most.

答:
(In this answer, I'm going to replace “rope” by “string”. I will use the made-up term “xfix” to mean “either a prefix or a suffix”.)

There is of course the brute force solution where we define an arbitrary ordering between the strings and then write a simple search over all possible combinations of string parts. The problem with this is that a naive implementation operates in O((2·l)n), where l is the average length of a string. With your magnitude for n, this is not feasible although memoization could make the pain bearable: The problem can be defined recursively, with a set of missing colors and a list of available strings being passed to each invocation. As the same input will be specified very often in the search tree, the optimal answer can be cached.

```<code>def optimal_combination(strings, colors):
  string = strings[0]
  remaining_strings = strings[1, ...]
  solution = None
  foreach xfix in string:
    remaining_colors = colors except colors in xfix
    possible_solution = xfix + optimal_combination(remaining_strings, remaining_colors)
    solution = possible_solution if solution.length < possible_solution.length
  return solution
</code>```

Before we fall back to such brute force methods, we might want to limit the search space. Especially, I am going to assume that the number of colors is much smaller than the number of strings. We can now consider two trivial solutions:

One rope contains an xfix that contains each color exactly once. This xfix is then the solution.

Each color occurs at the end of a string, so that the solution is a sequence of substrings of length 1.

… and all the variants in between, i.e. the solution is made up of substrings which each contain all their colors exactly once.

However it may occur that such a minimal-length solution is not possible, and that a color must occur repeatedly in the output. We can make the search easier by choosing an appropriate data structure. For each xfix, we can record the following metrics:

its length

the set of colors contained in the xfix

which string it originally belonged to

We can now iterate through all xfixes, and build a data structure that maps sets of colors to the shortest xfix containing all these colors. This operation takes only Oa = O(2 · l · n).

```<code>color_map = dict()

foreach string in strings:
  foreach xfix in string:
    colors = colors in xfix
    if color_map[colors].xfix.length > xfix.length:
      color_map[colors] = {
        xfix: xfix,
        string: string,
      }
</code>```

At this point, it may still be possible to assemble a shorter string for a certain color set. We remove this possibility by iterating through all entries. An entry may either already be optimal (if the length is the same as the size of the color set, or if it was assembled). Otherwise, if it isn't optimal, we try assemble a shorter string from the smaller color sets, optimizing them as well if necessary (color sets of size 1 are always optimal). When combining two xfixes, care must be taken that they're not from the same string (but note that never will two prefixes or two suffixes of the same string be combined, as their color sets overlap). It may be sensible to sort the entries before iteration, thus guaranteeing that all smaller color sets are already optimal when they're used in a combination. When the data structure contains m entries (with m <= 2 · l · n), then sorting takes less than Ob = O(m · log m). I am not sure about the complexity class of this combination operation, as I'm not sure about the exact algorithm needed to combine smaller entries into that of a given color set.

Unresolved issue: I'm not quite sure how to make sure that no postfix and suffix of the same string can be used together – this might require tracking the set of all used strings in each data structure entry, and forbidding to combine those where the string sets overlap.

Depending on how the xfixes are combined exactly, it may be sensible to maintain a dictionary of sets of sets, which maps colors to all color sets that contain this color. This could be easily built alongside combining the xfixes if they're combined strictly bottom-up.

The data structure now only contains optimal xfixes, and we can assemble our target string from them, following the same rules as during combination. This may require a tiny bit of brute forcing, but most of the work should already have been done.

So far, this is more of an idea dump than a well-structured answer. I'll try to evolve these concepts during the day, and update when I have more insight.

Title: Need an optimization algorithm

Body:
(In this answer, I'm going to replace “rope” by “string”. I will use the made-up term “xfix” to mean “either a prefix or a suffix”.)

There is of course the brute force solution where we define an arbitrary ordering between the strings and then write a simple search over all possible combinations of string parts. The problem with this is that a naive implementation operates in O((2·l)n), where l is the average length of a string. With your magnitude for n, this is not feasible although memoization could make the pain bearable: The problem can be defined recursively, with a set of missing colors and a list of available strings being passed to each invocation. As the same input will be specified very often in the search tree, the optimal answer can be cached.

def optimal_combination(strings, colors):
  string = strings[0]
  remaining_strings = strings[1, ...]
  solution = None
  foreach xfix in string:
    remaining_colors = colors except colors in xfix
    possible_solution = xfix + optimal_combination(remaining_strings, remaining_colors)
    solution = possible_solution if solution.length < possible_solution.length
  return solution

Before we fall back to such brute force methods, we might want to limit the search space. Especially, I am going to assume that the number of colors is much smaller than the number of strings. We can now consider two trivial solutions:

One rope contains an xfix that contains each color exactly once. This xfix is then the solution.

Each color occurs at the end of a string, so that the solution is a sequence of substrings of length 1.

… and all the variants in between, i.e. the solution is made up of substrings which each contain all their colors exactly once.

However it may occur that such a minimal-length solution is not possible, and that a color must occur repeatedly in the output. We can make the search easier by choosing an appropriate data structure. For each xfix, we can record the following metrics:

its length

the set of colors contained in the xfix

which string it originally belonged to

We can now iterate through all xfixes, and build a data structure that maps sets of colors to the shortest xfix containing all these colors. This operation takes only Oa = O(2 · l · n).

color_map = dict()

foreach string in strings:
  foreach xfix in string:
    colors = colors in xfix
    if color_map[colors].xfix.length > xfix.length:
      color_map[colors] = {
        xfix: xfix,
        string: string,
      }

At this point, it may still be possible to assemble a shorter string for a certain color set. We remove this possibility by iterating through all entries. An entry may either already be optimal (if the length is the same as the size of the color set, or if it was assembled). Otherwise, if it isn't optimal, we try assemble a shorter string from the smaller color sets, optimizing them as well if necessary (color sets of size 1 are always optimal). When combining two xfixes, care must be taken that they're not from the same string (but note that never will two prefixes or two suffixes of the same string be combined, as their color sets overlap). It may be sensible to sort the entries before iteration, thus guaranteeing that all smaller color sets are already optimal when they're used in a combination. When the data structure contains m entries (with m <= 2 · l · n), then sorting takes less than Ob = O(m · log m). I am not sure about the complexity class of this combination operation, as I'm not sure about the exact algorithm needed to combine smaller entries into that of a given color set.

Unresolved issue: I'm not quite sure how to make sure that no postfix and suffix of the same string can be used together – this might require tracking the set of all used strings in each data structure entry, and forbidding to combine those where the string sets overlap.

Depending on how the xfixes are combined exactly, it may be sensible to maintain a dictionary of sets of sets, which maps colors to all color sets that contain this color. This could be easily built alongside combining the xfixes if they're combined strictly bottom-up.

The data structure now only contains optimal xfixes, and we can assemble our target string from them, following the same rules as during combination. This may require a tiny bit of brute forcing, but most of the work should already have been done.

So far, this is more of an idea dump than a well-structured answer. I'll try to evolve these concepts during the day, and update when I have more insight.


问:
Limitations of UML?
I'm currently studying for an examination and one of the sample paper questions is to discuss the limitations of UML. Most of the material I'm finding on the net is relating to a specific UML implementation or language. I'm wondering from a generalists point of view what would you consider the limitations of UML to be? </p>

答:
The problem I have using UML is it's complexity. Even with the 800 page standard (which is clearly a sign of a severe problem), I find wildly different interpretations of use from one developer to another.  So much so, that it can take significant time to comprehend precisely what resultant code or process is modelling. Often a much simpler diagram with comments is better as others have indicated.

Also there are some fundamental things I dislike like association in class diagram. It's often not clear what the association represents in code because people will omit them from the list of attributes. This is because the link is supposed to imply this. However,I always put list the attributes specified by the association to avoid potential confusion.

The other problem is that often the very people one might share UML with, customers and managers are not going to understand or appreciate its more esoteric features anyway. Particularly working in the mobile application development industry that was very much the case.

However, like others have said in simple form I really find class diagrams useful especially CASE tools that can generate basic structure from a class diagram. This has saved me many hours and some potential back peddling.

Title: Limitations of UML?


问:
How do you unit test private methods?
I am working on a java project. I am new to  unit testing. What is the best way to unit test private methods in java classes?</p>

答:
Unit test case means testing the unit of code. It does not mean testing the interface because if you are testing the interface, that does not mean you are testing the unit of code. It becomes kind of a black box testing. Also, it is better to find issues on the smallest unit level than determining the issues on the interface level and then trying to debug that which piece was not working.
Therefore, unit test case should be tested irrespective of their scope. Following is a way to test private methods.

If you are using java, you can use jmockit which provides Deencapsulation.invoke to call any private method of the class under testing. It uses reflection to call it eventually but provides a nice wrapper around it. (https://code.google.com/p/jmockit/)

Title: How do you unit test private methods?


问:
What are the essential mathematics topics that a programmer should know in order to learn algorithms?
Being a electronics engineer, I was never exposed to any algorithms. Now I am a experienced programmer and want to learn Algorithms. I started with CLRS. But I was overwhelmed by the maths in the book. So which are the minimum maths topics should I know before I start Algorithms? </p>

<p>Are there any good tutorials or books on this? I did find one book on maths by Donald Knuth, but i guess its too details and tough for beginners. </p>

答:
I suggest you narrow down your approach. There are so many algorithms, which are heavily reliant on various mathematical aspects, that you essentially will run into a huge time problem when you try to learn all those things.

Instead, think a little bit more about why you want to learn algorithms. What is it that you want to use them for? What are the problem domains you want to tackle?

For example, let's just consider three almost totally different mathematical branches: discrete and non-discrete mathematics, and stochastics.

Discrete mathematics is very good for programmers, as it can mostly be represented naturally on a machine due to its discrete different states. Major examples in the area of related algorithms are graph algorithms, number theory algoritms, etc.

Non-discrete mathematics is allowing for infinitesimal differences in values, which you cannot track on a machine exactly. Therefore, one abstracts over functions and is interested in finding certain points like maxima, minima, intersection points etc. Algorithms in this area range from the area of operations research, with mostly optimization algorithms, all the way to algorithms of a more geometrical nature, like tesselations.

Stochastics on the other hand deals with randomness, and hence, a whole new world of algorithms is based on that. From simple shotgun approaches to more or less involved random walk algorithms. But the distinction is getting harder here, because you can for example find a lot of randomized algorithms in graph theory and number theory as well.

These are just tiny little examples. There are many more interesting areas in maths, just as well as for algorithms, which do not fit into the above.

So in essence, my answer is that your question is misleading. Unless you want to dedicate your whole life to algorithms, you almost always focus on algorithms in a certain area that is most important to you or your work. Some need next to no mathematical background (f.ex., dynamic programming algorithms), whereas others require you to study a lot of mathematics first (easily seen in computer graphics algorithms). So I suggest you to first decide on the direction you want to go, then learn that part (usually hard enough), and if you find it an intriguing enough subject, you can still expand in any other direction later. But do not try to learn all of mathematics just so you can eventually come around to learning algorithms later. You won't ever get there.

A final piece of advice: if you do not yet have a clear enough understanding of the field of algorithms to make these decisions, it may pay off for you to visit one of the "Introduction to Algorithms" (or similar) lectures offered by any number of universities, books, online courses, etc. It doesn't matter if you understand it all. If you miss the required maths, you can still understand the gist of what sort of problems the algorithm could help you with.


问:
DDD and the persistence of value objects; must we denormalize?
I've been reading up a lot on Domain-Driven Development, and I came to the question of how to preserve lack of distinct identity with value objects (VOs). While in the DDD world, this is a requirement (yet I'm not sure I understand the full power of this) it poses problems for the lower ORM layers in terms of persistence.

Tables, for the most part, like to be normalized. It makes life easy in terms of having no delete or insertion anomalies. My concern comes when implementing VOs; they do have primary keys - identities by definition (and foreign keys to their parent). Making them entities is violating DDD in favor of persistence. Instead, I could make a wrapper class that accepts a "bag" of parameters, and then attaches them to each parent's foreign key. While mechanically messy, it sounds like it will work.

I've read a lot of responses on the internet (Stack Overflow also) about denormalizing tables. This concerns me, as now we're violating persistence for DDD.

How to allow VOs to exist by their proper definition without a denormalization?

答:
I really don't think there is problem of VOs having an identity in database, as long as this identity remains hidden and transparent in domain layer itself. I would be data layer's responsibility to keep track of those identities so the domain doesn't have to care about it.

But VOs still give you ability to denormalize. Denormalization can have it's advantages, usually for performance reasons. So you can use this to your advantage.


问:
Is Pre-Order traversal same as Depth First Search?
It seems to me like pre-order traversal and DFS are same as in both the cases we traverse from root till the left branch and back to root and then to the right branch recursively. Could any please correct me if I am wrong?

Thanks in advance!

答:
To traverse a binary tree in Preorder, following operations are carried-out

Visit the root

Traverse the left subtree

Traverse the right subtree

That is in the below image the pre order traversal would be, 1,2,3,6,4,5,7,8,9,10,11,12

In the same image 1,2,3,4,5,6,7,8,9,10,11,12 would be for DFS

DFS Source : http://datastructuresnotes.blogspot.in/2009/02/binary-tree-traversal-preorder-inorder.html

Pre Order Source : Wiki


答:
pre order traversal is a traversal, it visits every node in a binary tree

Depth First Search is a search, it goes around an arbitrary graph looking for a certain node (that it works best in a non cyclic graph (a.k.a. tree) is irrelevant)

this alone is a large enough difference to call them difference names

Title: Is Pre-Order traversal same as Depth First Search?

Body:
It seems to me like pre-order traversal and DFS are same as in both the cases we traverse from root till the left branch and back to root and then to the right branch recursively. Could any please correct me if I am wrong?

Thanks in advance!


答:
My two limitations would be:-

Its not abstract enough --
Class diagrams are basically a list of fields and methods in a class
and its probably more effort to code the class diagram than to code the class.
It does highlight the relationships between classes -- but with not much more detail than reading the "import" statements from the code.

They me in great detail stuff I am not interested in but miss out interesting stuff like  purpose of a relationship, or, vital pieces of logic. Another poster pointed this out as the "everything is equal" problem -- you cannot highlight the important stuff.

(I know I said two!) It makes developers think of "Use Cases" as diagrams of stick figures with a few labels attached, whereas real Use Cases --> free format text descriptions of what the system is supposed to do are the most useful single tool in requirements gathering.

Title: Limitations of UML?

Body: I'm currently studying for an examination and one of the sample paper questions is to discuss the limitations of UML. Most of the material I'm finding on the net is relating to a specific UML implementation or language. I'm wondering from a generalists point of view what would you consider the limitations of UML to be? </p>


答:
Another point is this. When I have

```<code>"x" == "x"
"2" < "100"
</code>```

I'd expect also that

```<code>"x2" < "x100"
"2x" < "100x"
</code>```

In other words, comparision result should remain the same when I append the same string on the front or the end. This is the same with numbers:

```<code>if a < b then so is 2*a < 2*b and 2+a < 2+b and a-2 < b-2
</code>```

=== EDIT ===

It looks like I got downvoted because people read the above in the following way:

String operations must behave like numerical ones.

or

String operations must behave like I said because numerical ones do.

And then give the "counterexample" of

2+a == a+2 therefore "2x" == "x2"??

No, that's not what I said.

Here it is more formal:

If e and § form a Monoid on some type T, then we should have it that, for any x,y,z of type T the following holds:

```<code>(z § x) < (z § y) <=> x < y
(x § z) < (y § z) <=> x < y
</code>```

Since

```<code>0 and + form a Monoid on Integers
1 and * form a Monoid on Integers
"" and append form a Monoid on Strings
[] and list concatenation form a Monoid on lists, ...
</code>```

we could expect the above general laws to hold. They don't in PHP, so that's why we say PHP string comparision is broken.

Observe that

```<code>a § b == b § a
</code>```

is not a requirement for Monoids, though it is true for addition and multiplication of numbers. Specifically, it is invalid to conlude that string append must be commutative because integer addition is commutative.

Body:
Another point is this. When I have

"x" == "x"
"2" < "100"

I'd expect also that

"x2" < "x100"
"2x" < "100x"

In other words, comparision result should remain the same when I append the same string on the front or the end. This is the same with numbers:

if a < b then so is 2*a < 2*b and 2+a < 2+b and a-2 < b-2

=== EDIT ===

It looks like I got downvoted because people read the above in the following way:

String operations must behave like numerical ones.

or

String operations must behave like I said because numerical ones do.

And then give the "counterexample" of

2+a == a+2 therefore "2x" == "x2"??

No, that's not what I said.

Here it is more formal:

If e and § form a Monoid on some type T, then we should have it that, for any x,y,z of type T the following holds:

(z § x) < (z § y) <=> x < y
(x § z) < (y § z) <=> x < y

Since

0 and + form a Monoid on Integers
1 and * form a Monoid on Integers
"" and append form a Monoid on Strings
[] and list concatenation form a Monoid on lists, ...

we could expect the above general laws to hold. They don't in PHP, so that's why we say PHP string comparision is broken.

Observe that

a § b == b § a

is not a requirement for Monoids, though it is true for addition and multiplication of numbers. Specifically, it is invalid to conlude that string append must be commutative because integer addition is commutative.


答:
The less powerful a language is, the less options it gives you to shoot your own foot.

High-level languages like Java and C# will produce less bugs than low-level languages like C++.

Having said that I believe Java is more secure than C#. Java is artificially limited so that an average programmer without advanced knowledge can master it and produce stable programs.

Title: What programming language generates fewest hard-to-find bugs?

Body:
What language, in your opinion, allows the average programmer to output features with the least amount of hard-to-find bugs? This is of course, a very broad question, and I'm interested in very broad and general answers and wisdoms.

Personally I find that I spend very little time looking for strange bugs in Java and C# programs, while C++ code has its distinct set of recurring bugs, and Python/similar has its own set of common and silly bugs that would be detected by the compiler in other languages.

Also I find it hard to consider functional languages in this regard, because I've never seen a big and complex program written in entirely functional code. Your input please.

Edit: Completely arbitrary clarification of hard-to-find bug: Takes more than 15 minutes to reproduce, or more than 1 hour to find cause of and fix.

Forgive me if this is a duplicate, but I didn't find anything on this specific topic.


问:
copyleft licensing question
I'm writing an app and referring to some open source, source code (copyleft licensed.)

I am not using the original source code because it's for a completely different operating system using a different language, and as far as I am aware, no-one has ported that source into the language I am using nor my target operating system.

Am I still covered by the original copyleft license?

答:
The main question here is: Are you copying the code, or are you copying the underlying algorithm.

Porting code to a different (programming) language is a gray area in copyright law and it will depend for a large part on how mechanical the transformation is whether your version will be seen as a derived work of the original or as a separate work.

On the other hand, algorithms are not subject to copyright, only the way they are expressed. This means that if you only look at the original code to determine how it works and you try to recreate that same behavior, you are one step further away from having created a derived work. The biggest problem might be in proving that the similarities between the two versions are not the result of you having seen the original.

The above does not only apply to copyleft licenses, but it applies to any copyright license that requires a derived work to be released under the same license. For all those licenses, the safest option when porting a work is to release your port under the same license or to get agreement from the maintainers of the original to use a different license for your port.

Title: copyleft licensing question


问:
What's the first thing you write when trying out a new language?
I think everyone has their own program or set of features beyond "Hello World!", that they use when trying out a new language.

Mine is a guessing game:

```<code>I'm thinking of a number 1-10, guess what it is!
Guess: 3
Nope, too low!
Guess: 7
Nope, too high!
Guess: 5
Yes, You win!
Play again (Y/N)? N
</code>```

What do you write?

答:
I'll often try to write a Tetris clone.  It touches on a bunch of things, including performance, UI, and synchronization/timers/etc.

Any language that can't make that simple is just a toy.


问:
Object-Oriented design and proper Java architecture for my program
This is the very first time that I think I want to create a program which really uses OOP principles and I want to do it in the most effective and efficient way.

First of all we are given this (great) riddle :

100 prisoners are imprisoned in solitary cells. Each cell is windowless and soundproof. There's a central living room with one light bulb; the bulb is initially off. No prisoner can see the light bulb from his or her own cell. Each day, the warden picks a prisoner equally at random, and that prisoner visits the central living room; at the end of the day the prisoner is returned to his cell. While in the living room, the prisoner can toggle the bulb if he or she wishes. Also, the prisoner has the option of asserting the claim that all 100 prisoners have been to the living room. If this assertion is false (that is, some prisoners still haven't been to the living room), all 100 prisoners will be shot for their stupidity. However, if it is indeed true, all prisoners are set free and inducted into MENSA, since the world can always use more smart people. Thus, the assertion should only be made if the prisoner is 100% certain of its validity.

Before this whole procedure begins, the prisoners are allowed to get together in the courtyard to discuss a plan. What is the optimal plan they can agree on, so that eventually, someone will make a correct assertion?

So I've got a solution and I want to create a program to run it. I want my program to be as modular as possible, meaning that if I find a better solution, I don't to have to rewrite all of my code. I think OOP is really suited for this.

Here's what I've done so far:

A Main class : where I just run several games to test solutions

A Game class : which just runs one 'attempt'. It has a 'jail' (which is just an array of prisoners), a day counter and other useful stuffs.

And a Prisoner class : which just represent one single prisoner.

After thinking this through, the only things that one prisoner can do are changing the light where they're picked and stating (or not) that everyone has come in the room.

In the solution I've come up with, I have two types on Prisoner. What I've done is that I just implemented my Prisoner class with the most classic type of Prisoner and created a subclass which simply overrides methods from the Prisoner class.

Right now, I see two possible improvements if I want to reuse my code :

make the Prisoner class a Java interface, so that when I want to create a new type, I'd just have to implement a Prisoner. But the main issue is that I mostly have 'typical prisoners', a lot of people having the same pattern. Do I just create a implementation 'Classic_Prisoner' ?

creating a Behaviour class which handles what behaviour one Prisoner have given a single situation. But isn't just the same problem ? I mean I would also have to create one Behaviour subclass for each type of Prisoner I'm considering.

What to do to have the cleanest code there and be able to reuse it when the time comes?

答:
I'll try to give you a quick and efficient answer. I will not help you solve the problem but rather be purely technical about your OOP.

About the Prisonner class being an interface : no. You should consider inheritance. If some prisoners are "like prisoners" but with some new features, make a WithSuchFeaturePrisoner class which you can also store in your jail array thanks to polymorphism.

Behaviour however sounds like a typical interface name. If the behaviour is dependent on the type of prisoner then it belongs to the Prisoner class as a method.
Just to give you an idea:

```<code>enum Situation {
  A,
  B,
  C
}

interface Behaviour {

  public void whatToDoWhen(Situation happens);

}

class LazyPrisoner implements Behaviour {

  public void whatToDoWhen(Situation happens) {
    // I do nothing
  }

}
</code>```

I have not thought the entire problem through — and made abstraction of it — because I want to leave you the satisfaction of solving it yourself (and heck, I too am a LazyStackExchangeUser), but I hope this helps.

Body:
I'll try to give you a quick and efficient answer. I will not help you solve the problem but rather be purely technical about your OOP.

About the Prisonner class being an interface : no. You should consider inheritance. If some prisoners are "like prisoners" but with some new features, make a WithSuchFeaturePrisoner class which you can also store in your jail array thanks to polymorphism.

Behaviour however sounds like a typical interface name. If the behaviour is dependent on the type of prisoner then it belongs to the Prisoner class as a method.
Just to give you an idea:

enum Situation {
  A,
  B,
  C
}

interface Behaviour {

  public void whatToDoWhen(Situation happens);

}

class LazyPrisoner implements Behaviour {

  public void whatToDoWhen(Situation happens) {
    // I do nothing
  }

}

I have not thought the entire problem through — and made abstraction of it — because I want to leave you the satisfaction of solving it yourself (and heck, I too am a LazyStackExchangeUser), but I hope this helps.


问:
Names for generic classes - how to avoid naming them just "object"? Use synonyms?
When programming, I often end up naming some generic class (think of an abstract base class for stuff you manage in your project) something like FooObject, FooComponent or FooItem (where Foo is an abreviation of project name). The problem is, that these names are used so often, they become meaningless - I mean, when I'm talking about an "object", no-one knows whether I mean "a subclass of FooObject", or an ordinary object.

I think that a good list of synonyms for "object", "component", "callback", "handler", "action" and so on would help, because we could just redefine these world on a per-project basis. You could even make up some totally nonsense word and define your meaning in documentation. I think it would be clearer than naming stuff "objects".

Here's what I mean by "nonsense" (taken from Alice in Wonderland):

Twas brillig, and the slithy toves

Did gyre and gimble in the wabe:

All mimsy were the borogoves,

And the mome raths outgrabe.

Maybe you can have some nice words you use in such cases?

How do you deal with similar situations in your projects?

[ Related: How to avoid general names for abstract classes? ]

答:
On the matter, Kent Beck said:

"[...] The names should be short and punchy. However, to make the
  names precise sometimes seems to require several words. A way out of
  this dilemma is picking a strong metaphor for the computation. With a
  metaphor in mind, even single words bring with them a rich web of
  associations, connections, and implications. For example, in the
  HotDraw drawing framework, my first name for an object in a drawing
  was DrawingObject. Ward Cunningham came along with the typography
  metaphor: a drawing is like a printed, laid-out page. Graphical items
  on a page are figures, so the class became Figure. In the context of
  the metaphor, Figure is simultaneously shorter, richer, and more
  precise than DrawingObject."

(From Marcio Aguiar's answer in https://stackoverflow.com/questions/38019/whats-the-best-approach-to-naming-classes)