问:
Implementing a machine learning algorithm to detect the region of an address
I have 10,000 addresses from a city, which all have a region field in the database.
When a new address is entered, then I want my software to automatically detect the region of the address .

I think it should be implemented with some sort of machine learning algorithm. How can I do this?

And with every newly inserted address, the machine should learn to detect the region of the new address.
Is there any library for machine-Learning algorithms (like aforge.net for neural networks)?

答:
You're trying to classify the addresses, and associate the classification groups with regions.

You could pour your 10,000 addresses + regions into a random forest. Or build several for an ensemble. The trick would be how to build the inputs: you might have to use a "word bag" approach, with a boolean for each street name and a few fields for the discreet values like street address. That would be a big input, but that's OK; sometimes the features of a training set can run into the thousands (or more).

Split your data up into training/testing sets, though. Pour 9,000 of the addresses into the random forest, then use the other 1,000 to test it and see what % accuracy you get. There are fancier ways to split it up, but that's a good start.

In Python, scikit-learn is always a good choice. sci-kit learn will have other classification schemes that might be even better than random forest for this task.


问:
How to get better understanding of the users as a programmer
I work at a company that wants to be agile, but the business analysts often provide us "user stories" that are more solution than problem statement. This makes it difficult to make good design decisions, or in more extreme cases, leaves few design decisions to be made. It does not help the programmers understand the user's needs or make better design decisions in the future. Our product owner makes an effort to provide us with problem statements, but we still sometimes get solution statements, and that tends toward a "code monkey" situation.

An additional challenge is that some (not all) of my teammates do not see a problem with this, and some of them honestly want to be told what to do. Thus, when we receive a solution statement on our backlog, they are eager to jump right in and work on it.

I believe that as a software engineer part of my job is to understand the user's needs so that I can build the right thing for the user. However, within our organization structure, I have zero contact with the user. What kind of things can I do to better understand our users?

答:
This really depends on your management.

What I have found in over 13 years of software engineering is that I need to talk directly to the customers and sometimes even end users (often in software these are separate entities). Business analysts are hit or miss: some of them understand the customer and end users and write really good requirements (not solutions), some of them go too far and assume too much.

I would recommend talking to your management and argue that you need to be involved earlier in the process, ideally right after sales exits the picture and the BAs enter. Do not be just a fly on the wall: you need to assert yourself as a product expert seeking to understand the problem domain (ugh, buzzwords: you know your software, you want to learn what the customer wants you to do with it).

For existing projects, I would work through your project manager and try to cut the BAs out of the picture. You will likely get answers that match what you have already been told. Do not accept this. Try to get in meetings with the customer to discuss requirements. In an Agile environment there should be no problem with this: if you do not understand something, the customer is the final arbiter for requirements (but not necessarily for what your company will authorize you to do in the billable hours paid for).

Essentially, keep asking questions and do not shut your mouth until you fully understand what the customer wants. Just because a BA gave you an odd-sounding requirement does not mean this is what the customer wants, or that it is the best way to accomplish the customer's wishes.

ContentLicense: CC BY-SA 3.0


问:
What happens if computer crashes after giving commit command
If we are updating a field in SQL and ALTER the row also. After giving  the COMMIT command, the system is crashed.

What will happen to the commands given, whether it will UPDATE and ALTER the table or not?

答:
For an ACID transaction, it will either commit or it will not.

The transaction will normally be written to a transaction log. It will then be written to persistent storage, and the log entry erased. If the system crashes in this process, the database server will (upon next startup) check the log for pending transactions. For each transaction it will either remove the log entry, reattempt the transaction, or roll back a partially completed transaction as appropriate depending on whether there is evidence the transaction completed or not.

This is a simplified explanation of ACID, I recommend brushing up on this Wikipedia article.


问:
Regular Expressions and Language Generators
I have few CS textbooks with me which discuss languages, well actually 2 plus old course notes supplied a few years ago. I have been searching the web too any only seem to come up with vague responses just like the text books I have.

My question is about language recognisers verses generators.

I get the overriding principle of a recogniser. That it analyses a language and is able to determine nay or yay if a String belongs to a language. This is at least what I have picked up from the books and notes. However, it's much more complex than that is it not? A tokeniser and syntax analyser (which I assume to be recognisers) do not just say yes or no, they also say where don't they...?

However, language generators. No one seems to be very clear about what they are. The typical description I get is For example Sebasta's Concepts of Programming Languages says 'A language generator is a device that can be used to generate the sentences of a language. We can think of a generator as a push button that produces a sentence of a language every time it is pressed.' Seriously? That's it?? Your kidding right....

I read that Regex is an example of a Generator, then why when people talk of generators do they not talk of the inputs. For example Regex has a target String, and the Regex with defines both the accepted alphabet and it's grammar rules.

Can someone provide for me a clearer distinction of what a recognizer is?

答:
First off, these are not difficult subjects in their general sense, so do not be surprised that generating sentences of a language is it.

There is one concept shared by both a language recognizer, as well as a language generator, and that is a language.

Languages can be defined as simple as L = {a, b, c} where the language L only knows three words/sentences. Regular expressions themselves are neither recognizers nor generators. Instead, a regular expression is a way of defining a language. For example, the regular expression a+ defines the language L' = {a, aa, aaa, aaaa, ... }.

Now if you look into those textbooks of yours, I am sure, there is a section on how to convert a regular expression into a (non-)deterministic finite automaton. Such an automaton is now a language recognizer, that fails to accept a b, but does accept aaa when constructed from the regular expression a+.

On the other hand, a language generator is something that will output one element of L' at a time, eventually, generating all of L'. For example, a generator for L' could give you aaa, then a, then aa, then aaaa, and so on.

Generally, languages are infinitely large, hence, generators need to generate an infinite number of sentences in that language. Consider the language L1 defined by the regular expression a+b+. If you have a generator that outputs ab, aab, aaab, ..., then it can run infinitely long, but you will never ever see a word that has more than one b. Such generators tend to be rather useless due to their biased nature.

Therefore, to reduce the "that's it" effect, we typically demand from a generator, that given any word from the language, the generator eventually produces it. So you could pick aabb and your generator must have a finite number of steps that it needs to produce that word. It cannot just infinitely increase the number of as anymore.

Now, to start making things really complicated, assume a more interesting language like, for example, Java. When you have a Java language generator, then this thing will eventually produce all of the Java classes that you have written and will ever write in your life as a Java programmer. I leave it as an exercise to you to think about how to realize such a thing - and do not forget: only valid Java programs are allowed. It must not output gibberish, but only sentences of the language.

Usage of language generators is primarily in CS theory. For practical purposes their infinite nature makes any kind of meaningful usage rather problematic. Apart from pathological cases, where the language is trivial and finite, one could use these generators for testing tools that are supposed to process sentences of the language. For example, you could test a Java parser against a Java generator by having it continuously parse the generated progarms.

ContentLicense: CC BY-SA 4.0


问:
Basic OOP Question for a Report
I'm in development of a sample project in Android for a friend's phone that keeps track of his sales. At first, one of the requirements was to create yearly reports of this sales data. This would be stuff like most profitable week, total per quarter, total per month, and even yearly total, as well as compares for previous years (about 10 things total).

I created a class called YearlyReport that has all of these properties and they get populated from a database class that makes the appropriate SQL calls.

This data is displayed on a statistics page, but after seeing this my friend asked me to give the viewer the ability to select different weeks and display weekly data too (3 bits of information: the total for the week, the best day in the week, the worst day in the week). So as they change weeks in the year, he wants to see weekly data appear above the yearly data.

So now I need to do specific queries of weekly data, but display yearly data too. I feel really disorganized for some reason! At first I made a WeeklyReport object, and the database will say "ok for a given week W, I'll fill your WeeklyReport object and return it". Then I started wondering if I should do something smarter. Maybe combine something? Should there be inheritance? I'm missing something.

Is it OK to have a WeeklyReport and YearlyReport object? Should I combine them? If I do, it's still strange because the yearly report doesn't change much unless you move to a new year (not often), but the weekly does (depending upon the date).

答:
Why don't you just create one class where you specify the date intervals as a parameter? I don't know your data model, but I guess it won't make any difference in code if you pass start_date=1/1/2014, end_data=31/12/2014 or end_data=07/012014 for the evaluation time?

Fort this approach, you will need an additional parameter list describing for the "aggregate intervals" (for example, if you want information about the best or worst month, your intervals are the 12 months of the year, if you want information about the best or worst day of the week, you just pass the 7 days of the specified week).

What remains is to calculate and pass the correct parameters to the class for a weekly or yearly report, but I guess this could be done by two simple functions, just using that Report class.

Title: Basic OOP Question for a Report


问:
Why are good programmers referred to as Ninjas?
How is a Ninja programmer defined? If it is just an experienced developer, then is there really no better way to describe that? Ninja sounds like a childish marketing ploy designed to attract developers with delusions of self-grandeur. Or am I missing something? In particular I want to know what qualities of a Ninja are desired in programmers that makes the comparison valid (besides the coolness factor)?

I did find this article which makes some good comparisons between Ninja characteristics and Agile development. However, I would like to hear from people who have used the word Ninja for hiring purposes and what their motivation was behind it.

Update: There were several good points raised on both sides of the argument. I've tried to summarize these in my blog post. I've chosen JB's answer as the accepted one because it summarizes all the valid reasons for making the comparison.

答:
In addition to the "Coolness" and "Elite" factors, ninjas are often stealthy and are known to do things like sneak past security to get into places they shouldn't. Because this trait is shared by  Hackers, I think someone thought that "Ninja" would be a good title for them. To a non-IT person, Hackers and Programmers are the same thing, and they think the word "ninja" is very cool, so it kind of stuck

So the logic is:

Ninja = Stealthy Person Who Can Sneak Past Security Into Places They Shouldn't Be

Stealthy Person Who Can Sneak Past Security Into Places They Shouldn't Be = Hacker

Hacker = Programmer

Therefore, Ninja = Programmer

ContentLicense: CC BY-SA 2.5


问:
Partial recovery from an Exception
I have seen Exception Handling blocks that they were throwing the recently caught Exception in the catch block. Something like:

```<code>} catch ( Exception $e ) {
    // Do some recovery here
    callSomeFunction();

    throw $e;
}
</code>```

To me it doesn't make that much sense to throw the exact same Exception like this, but I'm not sure if I'm right or not. Maybe there are situations that that's the only option?

My question is what are the pros and cons of this approach and shouldn't it be totally avoided as much as possible?

答:
Sometimes you have more information right on hand, like intermediate values, that you can do something with. A lot of times you can log that information, if nothing else.

You can also attempt recovery or backout before altering the caller that something went wrong.

But, ultimately, if the code can't complete its use case and needs to halt, then ya performing mitigation or reporting can be useful before re-throwing the error.

The problem is, what if the mitigation fails? The nested exception handling can get hairy. So I'm with you; I'll sometimes handle & re-throw the error, but I will also think hard about my design.

Title: Partial recovery from an Exception


问:
What are the problems of bringing C++-like const into a language?
I am interested in the idea of C++-like const not that particular execution (like casting away const).

Take for example C# -- it lacks C++-like const, and the reason for it is the the usual -- people and time. Here additionally
it seems the C# team looked at the C++ execution of const, marketing CLR and had enough at this point (see why there is no const member method in c# and const parameter ; thank you Svick). Be if we move further than that, is anything else?

Is there something deeper? Take for example multi-inheritance -- it is usually seen as hard to grasp (for the user) and thus not added to the language (like diamond problem).

Is there something in NATURE of const that pose a problem that it is better for language to avoid it? Something like deciding if const should be deep or shallow (having const container does it mean I cannot add new element or alter existing elements as well; what if elements are of reference type)?

UPDATE: while I mention C#, and thus making a historical perspective I am interested in the nature of potential problems of const to the language.

This is not a challenge of the languages. Please ignore such factors as current trends or popularity -- I am interested only in technical issues -- thank you.

答:
I see the drawbacks as:

"const poisoning" is a problem when one declaration of const can force a previous or following declaration to use const, and that can cause its previous of following declarations to use const, etc. And if the const poisoning flows into a class in a library that you don't have control over, then you can get stuck in a bad place.

it's not an absolute guarantee. There are usually cases where the const only protects the reference, but is unable to protect the underlying values for one reason or another. Even in C, there are edge cases that const can't get to, which weakens the promise that const provides.

in general, the sentiment of the industry seems to be moving away from strong compile-time guarantees, however much comfort they may bring you and I. So for the afternoon I spend touching 66% of my code base because of const poisoning, some Python guy has banged out 10 perfectly workable, well-designed, well-tested, fully functional Python modules. And he wasn't even hacking when he did it.

So maybe the question is, why carry forward a potentially controversial feature that even some experts are ambivalent about when you're trying to gain adoption of your spiffy new language?

EDIT: short answer, a new language has a steep hill to climb for adoption. It's designers really need to think hard about what features it needs to gain adoption. Take Go, for example. Google sort of brutally truncated some of the deepest religious battles by making some Conan-the-Barbarian style design choices, and I actually think the language is better for it, from what I've seen.


问:
Best way to make synchronous calls between JEE apps
I have two jee web apps that are going to be published on the same physical server, but on different network addresses.

APP A: Listens to a port on a public IP address and makes synchronous invocations to app B if necessary.

APP B: Listens to a port on a private IP address and makes synchronous invocations to app A if necessary.

For connecting APP A with APP B, I am considering the following alternatives.

RMI

Message Queue

Lightweight ESB

Please tell me if you see any clear advantage supported by facts on any of them, or if there's another technology I should consider.

答:
I've done HTTP/REST-ish using JAX-RS almost exclusively for inter-service communication a while (barring some JMX for monitoring), but here's my memory of the arguments:

EJB is a convenience wrapper for RMI

RMI is a slick, but proprietary Java protocol.

SOAP has some very serious supporters, but is struggling under the weight of XSD strictness, and can create tight coupling between client and server if you're not really, really careful.

Which is why JSON over HTTP has been emerging as a popular choice for inter-service comminication. It's also officially part of JEE with the JAX-RS spec, so that RMI/EJB isn't the only official answer anymore.

EJB has the disadvantage that you need a full-blown enterprise container rather than a smaller, free application container like Jetty or even Tomcat

RMI has the disadvantage that it's a proprietary Java protocol, so you can only talk from Java to Java. I have a memory that you can bridge other technologies using an underlying CORBA implementation, but it's been 15 years since I had that conversation.

Also, since RMI relies on object serialization, it can be prone to really tight coupling between client and server. Meaning that if you compile a new version of the server, you have to compile and deploy a new version of all clients. I could be way off base on that, though.

Since JAX-RS is part of the JEE spec now, and there are nice implementations like Jersey or RestEasy, the shops I've been at for the last decade have just gravitated toward that as the solution (even before it was part of the spec).

In addition, with an standard protocol like OAuth, you can expose the same interface on the public internet as your internal network, so you don't have to provide separate technologies for your internal vs. external APIs.

Also, even before that, I was at a shop that recognized all the benefits of running an application inside a container. So rather than rolling our own application framework, it was  more convenient, standard, and maintainable to just drop our functionality into an application container and let it take care of the system concerns. EJB & and an enterprise container provide the same benefits, but you can pay a lot of $$$$ for licensing compared to what you can download and deploy for free.

Like I say, it's been a long time since I had those conversations, so I might get some downvotes. All due apologies.


问:
What are the advantages of storing xml in a relational database?
I was poking around the AdventureWorks database today and I noticed that a number of tables (HumanResources.JobCandidate and  Sales.Individual for example) have a column which is storing xml data.

What I would to know is, what is the advantage of storing basically a database table row's worth of data in another table's column? Doesn't this make it difficult to query off of this information? Or is the assumption that the data won't need to be queried and just needs to be stored?

答:
I'd say it was bad practice as you're clogging up otherwise efficient storage with inefficient tags which do not need to be there if you take the effort to parse out the information. XML has a hideous storage overhead compared to the data it describes, as you need one tag for each column for each row. By comparison, data parsed out and stored in relational format has its column name stored ONCE. For a dozen rows on a dev. box, big deal, but I've seen developers make the assumption this is scalable to millions of rows. This can represent 100's of GB of overhead for a few dozen GB of data, which creates operational challenges. You're basically abdicating responsibility from yourself and pushing onto the people who have to support the crap you've written.

So, why not store it AWAY from the operational data, in its own database? Or as it's intended - in flat files? It'll probably never be looked at again, so why not remove it from hitting the performance of an operational system? Remember that XML is ONLY there to provide a description of the schema of data that would otherwise not be apparent due to storage protocol differences between systems. That is its entire point, there's nothing clever about it. Storing 10x the amount of overhead for a given amount of data just says you're a sloppy developer who's not thought things through and can't be arsed to process the data you're consuming into a sensible, efficient, fast to query format. Stop pushing your effort onto operational support, and THINK about how you can better handle the data after you've received it would be my call. There's no defence for storing data as XML after it's received, as it's served its purpose.


答:
Document-oriented datastores (aka NoSql) are very popular these days:

http://en.wikipedia.org/wiki/Document-oriented_database

There's no reason you can't employ a document-oriented scheme in a relational database. You might not get all the same benefits compared to something like Mongo, but you won't have the drawbacks, either.

For a long time, if you wanted to use document-oriented storage, your only choice was shoving structured data (like XML) into a big column. The relational databases have been adding features like indexing and matching to support that.

Contrast that with Mongo, where they only thing in the database is documents. But that's another topic.

EDIT: the core idea of document-oriented is: you pull the data out, manipulate it, and shove it back in whole. Sometimes, like when you're transmitting the document to the client, you just want to send the whole thing as a blob and let them deal with it. The benefit (and drawback) is flexibility. Validation and correctness of the document is done outside the database.

EDIT EDIT: Another contrast. Imagine saving JPG images, or Word docs in a database column.

Title: What are the advantages of storing xml in a relational database?

Body:
I was poking around the AdventureWorks database today and I noticed that a number of tables (HumanResources.JobCandidate and  Sales.Individual for example) have a column which is storing xml data.

What I would to know is, what is the advantage of storing basically a database table row's worth of data in another table's column? Doesn't this make it difficult to query off of this information? Or is the assumption that the data won't need to be queried and just needs to be stored?


问:
Whats an Ideal way to pass rules/options to methods that build SQL
We're trying to come up with a way to handle code that builds dynamic SQL for our application, which is very database centric. Things like Linq to SQL and Entity Framework are out of the question, so please no suggestions of that sort, our path has been defined for us.

Our main goal is seperation of the SQL from the rest of the code (business logic etc).

Right now, we're thinking of using extension methods to house the SQL, and coming up with some sort of configuration object that developers can use to define how the query should be built (dictated by business logic, outside of the Extension class)

So for example, I have some prototype code below. The developers would setup the Configuration Struct (as per business rules), and pass that to GetSQL.

```<code>public static class LocationSql2Extension
{

    public enum SelectFields
    {
        Default,
        DefaultAnd_Description_LocationSize
    }

    public enum FilterBy
    {
        Default,
        DefaultAnd_Description
    }

    public enum OrderBy
    {
        Default,
        DefaultAnd_LocationType_LocationID_Description
    }

    public struct Configuration
    {
        public SelectFields SelectFields;
        public FilterBy FilterBy;
        public OrderBy OrderBy;
    }

    public static string GetSQL(this LocationService2 service, Configuration config)
    {

        string sqlSelectFields = string.Empty;
        string sqlWhere = string.Empty;
        string sqlOrderBy = string.Empty;

        if (config.SelectFields == SelectFields.DefaultAnd_Description_LocationSize)
        {
            sqlSelectFields = ", Description, LocationSize";
        }

        if (config.FilterBy == FilterBy.DefaultAnd_Description)
        {
            sqlWhere = "WHERE L.Description = ?";
        }

        if (config.OrderBy == OrderBy.DefaultAnd_LocationType_LocationID_Description)
        {
            sqlOrderBy = ", L.LocationDescription";
        }

        string sql = string.Format(@"
                                       SELECT L.LocationType, L.LocationId
                                              {0}
                                       FROM Location AS L
                                       INNER JOIN GroupLoc AS GL
                                       ON  L.LocationType = GL.LocationType
                                           AND L.LocationId = GL.LocationId
                                           AND GL.SecLocLevel >= 4
                                           AND GL.GroupId = ?
                                       {1}
                                       ORDER BY L.LocationType||L.LocationId
                                       {2}
                                      ", sqlSelectFields, sqlWhere, sqlOrderBy);

        return sql;

    }
}
</code>```

and to call the above code, we have this:

```<code>public class LocationService2
{
    public string BuildSql()
    {
        var config = new LocationSql2Extension.Configuration();

        //TODO: Add Business Logic to drive these values
        config.SelectFields = LocationSql2Extension.SelectFields.Default;
        config.OrderBy = LocationSql2Extension.OrderBy.DefaultAnd_LocationType_LocationID_Description;
        config.FilterBy = LocationSql2Extension.FilterBy.DefaultAnd_Description;

        return this.GetSQL(config);

    }
}
</code>```

Developers would be free to setup the Enum's any way they like, and this is just a simple example. We're not comfortable with this Enum/Struct approach, and are looking for something more generic thats easy for developers to work with, but isn't so generic that it won't catch any errors at design time. This is a simple example, and we have some very large and complex queries in our system. Any suggestions?

答:
I see you using enums, however it would appear you'd be passing collections for things like fields/database columns.

First you will need to define a collection that makes up the view - [database name]. [schema].[table name].[column name], which is condensed as appropriate into an alias at the column name level.  Your class should validate that the alias names are unique.  Since this view has various rules for joins, you'll have a collection of join expressions.  Your class will have to verify that these aren't redundant and validate to actual database objects.

Once your view is defined you'll have a collection of 'where' expressions, which may be nested.  Therefore any given element in the collection may have it's own collection.  You will have to navigate to the terminal nodes and compose the SQL in bits, then assemble them with appropriate parens as you travel back toward the root.

Your 'order by' is a collection with a forced ranking order, listing the aliases according to that order.

This is simplified, at least in the sense that you don't have embedded Selects, and you aren't using Group By or Having. In those situations you would have to make your entire structure recursive.


问:
Java - Use polymorphism or bounded type parameters
Suppose I have this class hierarchy...

```<code>public abstract class Animal {
    public abstract void eat();
    public abstract void talk();
}
class Dog extends Animal {
    @Override
    public void eat() {
    }

    @Override
    public void talk() {
    }
}

class Cat extends Animal {
    @Override
    public void eat() {
    }

    @Override
    public void talk() {
    }
}
</code>```

And then I have....

```<code>public static <T extends Animal> void addAnimal(T animal) {
    animal.eat();
    animal.talk();
}

public static void addAnimalPoly(Animal animal) {
    animal.eat();
    animal.talk();
}
</code>```

What's the difference when using bounded type parameters or polymorphism?

And when to use one or the other?

答:
In your example, you don't (and shouldn't) use bounded type. Only use bounded type parameters when you have to, as they are more confusing to understand.

Here are some situation where you will use bounded type parameters:

Collections parameters

```<code>class Zoo {

  private List<Animal> animals;

  public void add(Collection<? extends Animal> newAnimals) {
    animals.addAll(newAnimals);
  }
}
</code>```

then you can call

```<code>List<Dog> dogs = ...
zoo.add(dogs);
</code>```

zoo.add(dogs) would fail to compile without <? extends Animal>, because generics are not covariant.

Subclassing

```<code>abstract class Warrior<T extends Weapon> {

  public abstract T getWeapon();
}
</code>```

to limit the type subclass can provide.

You can also use multiple bounds <T extends A1 & A2 & A3> to ensure a type is a subtype of all the types in the list.

Body:
In your example, you don't (and shouldn't) use bounded type. Only use bounded type parameters when you have to, as they are more confusing to understand.

Here are some situation where you will use bounded type parameters:

Collections parameters

class Zoo {

  private List<Animal> animals;

  public void add(Collection<? extends Animal> newAnimals) {
    animals.addAll(newAnimals);
  }
}

then you can call

List<Dog> dogs = ...
zoo.add(dogs);

zoo.add(dogs) would fail to compile without <? extends Animal>, because generics are not covariant.

Subclassing

abstract class Warrior<T extends Weapon> {

  public abstract T getWeapon();
}

to limit the type subclass can provide.

You can also use multiple bounds <T extends A1 & A2 & A3> to ensure a type is a subtype of all the types in the list.


答:
Use generics instead of downcasting. "Downcasting" is bad, going from a more general type to a more specific one:

```<code>Animal a = hunter.captureOne();
Cat c = (Cat)a;  // ACK!!!!!! What if it's a Dog? ClassCastException!
</code>```

...you're trusting that a is a cat, but the compiler can't guarantee that. It might turn out to be a dog at runtime.

Here's where you'd use generics:

```<code>public class <A> Hunter() {
    public A captureOne() { ... }
}
</code>```

Now you can specify that you want a cat hunter:

```<code>Hunter<Cat> hunterC = new Hunter<Cat>();
Cat c = hunterC.captureOne();

Hunter<Dog> hunterD = new Hunter<Dog>();
Dog d = hunterD.captureOne();
</code>```

Now the compiler can gurantee that hunterC will only capture cats, and hunterD will only capture dogs.

So just use regular polymorphism if you just want to handle specific classes as their base type. Upcasting is a good thing. But if you get in a situation where you need to handle specific classes as their own type, generically, use generics.

Or, really, if you find you have to downcast then use generics.

EDIT: the more general case is when you want to put off the decision of what kinds of types to handle. So the types become a parameter, as well as the values.

Say I want my Zoo class to handle Cats or Sponges. I don't have a common super class. But I can still use:

```<code>public class <T> Zoo() { ... }

Zoo<Sponge> spongeZoo = ...
Zoo<Cat> catZoo = ...
</code>```

the degree to which you lock that down is depends on what you're trying to do ;)

Title: Java - Use polymorphism or bounded type parameters

Body:
Suppose I have this class hierarchy...

```<code>public abstract class Animal {
    public abstract void eat();
    public abstract void talk();
}
class Dog extends Animal {
    @Override
    public void eat() {
    }

    @Override
    public void talk() {
    }
}

class Cat extends Animal {
    @Override
    public void eat() {
    }

    @Override
    public void talk() {
    }
}
</code>```

And then I have....

```<code>public static <T extends Animal> void addAnimal(T animal) {
    animal.eat();
    animal.talk();
}

public static void addAnimalPoly(Animal animal) {
    animal.eat();
    animal.talk();
}
</code>```

What's the difference when using bounded type parameters or polymorphism?

And when to use one or the other?

Body:
Use generics instead of downcasting. "Downcasting" is bad, going from a more general type to a more specific one:

Animal a = hunter.captureOne();
Cat c = (Cat)a;  // ACK!!!!!! What if it's a Dog? ClassCastException!

...you're trusting that a is a cat, but the compiler can't guarantee that. It might turn out to be a dog at runtime.

Here's where you'd use generics:

public class <A> Hunter() {
    public A captureOne() { ... }
}

Now you can specify that you want a cat hunter:

Hunter<Cat> hunterC = new Hunter<Cat>();
Cat c = hunterC.captureOne();

Hunter<Dog> hunterD = new Hunter<Dog>();
Dog d = hunterD.captureOne();

Now the compiler can gurantee that hunterC will only capture cats, and hunterD will only capture dogs.

So just use regular polymorphism if you just want to handle specific classes as their base type. Upcasting is a good thing. But if you get in a situation where you need to handle specific classes as their own type, generically, use generics.

Or, really, if you find you have to downcast then use generics.

EDIT: the more general case is when you want to put off the decision of what kinds of types to handle. So the types become a parameter, as well as the values.

Say I want my Zoo class to handle Cats or Sponges. I don't have a common super class. But I can still use:

public class <T> Zoo() { ... }

Zoo<Sponge> spongeZoo = ...
Zoo<Cat> catZoo = ...

the degree to which you lock that down is depends on what you're trying to do ;)


答: Well, XML (or JSON) is pretty good to store metadatas with hierarchy. What are the alternatives ? A metadata table with refid/key/value/depth maybe ? It's a bit cumbersome (but probably better for querying if you need to do it). Storing some xml data about a document (a row in a documents table) is pretty convenient when you want to store some hierarchical infos without having to rely on an external table or having to add 1 column per "type" of infos.</p>


问:
Validating objects with each other - Design Pattern needed
I am running a zoo application.

My zoo includes an abstract class of 'animal', and several deriving classes - 'zebra', 'elephant', 'orangutan', 'baboon' and so on. Of each class I have several instances.

My question is: I want to check out if two animal instances can mate.

The business logic is divided to two parts:

I want to check if each mating partner is fit for mating, e.g. not too young or too old or sick etc.

I want to check if the two partners match - e.g. a zebra cannot mate an elephant, but an orangutan can mate with a baboon.

I assume the first requirement would be implemented by an abstract function which would reside under the animal baseclass. But what about the second requirement?

How would you design the classes in the most general matter that adding new types of animals would not require much of an overhead?

答:
Depends on the actual requirements... What do you mean with 'not require much of an overhead'?

Do you want to be able to add animals dynamically, at runtime (in a plugin)?
Add an abstract method to Animal:

```<code>bool acceptsMate(Animal);
</code>```

When checking for possible mates, if one them accepts the other as mate, they can go at it.
Added a new animal in a plugin library means implementing this method, and the other existing animals need not know of this new species to mate with them.

If you do not have this requirement, I would use a lookup table, where pairs of compatible animals are listed.

If this is a school question, I guess they are hinting at the visitor pattern, which imho is a bad fit for this problem. You would need to duplicate code for each match, because there are 2 ways to query if they can mate.

```<code>AnimalA->visitCanMateWith(AnimalB)
</code>```

or

```<code>AnimalB->visitCanMateWith(AnimalA)
</code>```

Body:
Depends on the actual requirements... What do you mean with 'not require much of an overhead'?

Do you want to be able to add animals dynamically, at runtime (in a plugin)?
Add an abstract method to Animal:

bool acceptsMate(Animal);

When checking for possible mates, if one them accepts the other as mate, they can go at it.
Added a new animal in a plugin library means implementing this method, and the other existing animals need not know of this new species to mate with them.

If you do not have this requirement, I would use a lookup table, where pairs of compatible animals are listed.

If this is a school question, I guess they are hinting at the visitor pattern, which imho is a bad fit for this problem. You would need to duplicate code for each match, because there are 2 ways to query if they can mate.

AnimalA->visitCanMateWith(AnimalB)

or

AnimalB->visitCanMateWith(AnimalA)


答:
There are some philosophical problems in adding const to a language. If you declare const to a class, that means that the class cannot change. But a class is a set of variables coupled with methods (or mutators). We achieve abstraction by hiding the state of a class behind a set of methods. If a class is designed to hide state, then you need mutators to change that state from the outside and then it isn't const anymore. So it is only possible to declare const to classes that are immutable. So const seem only possible in scenarios where the classes (or the types you want to declare const) are trivial...

So do we need const anyway? I dont think so. I think that you can easily do without const if you have a good design. What data do you need and where, which methods are data-to-data methods and which abstractions do you need for I/O, network, view etc. Then you naturally split modules and classes arise that deal with state and you have methods and immutable classes that don't need state.

I think most problems arise with big fat data-objects that can save, transform and draw itself and then you want to pass it to a renderer for example. So you cannot copy the contents of the data, because that is too expensive for a big data-object. But you dont want it to change either, so you need something like const you think. Let the compiler figure out your design flaws. However if you split those objects in only an immutable data-object and implement the methods in the responsible module, you can pass around (only) the pointer and do things you want to do with the data while also guaranteeing immutability.

I know that it is possible in C++ to declare some methods const and to not declare on other methods, because they are mutators. And then some time later you need a cache and then a getter mutates an object (because it lazy loads) and it isnt const anymore. But that was the whole point of this abstraction right? You don't know what state gets mutated with each call.

Title: What are the problems of bringing C++-like const into a language?

Body:
I am interested in the idea of C++-like const not that particular execution (like casting away const).

Take for example C# -- it lacks C++-like const, and the reason for it is the the usual -- people and time. Here additionally
it seems the C# team looked at the C++ execution of const, marketing CLR and had enough at this point (see why there is no const member method in c# and const parameter ; thank you Svick). Be if we move further than that, is anything else?

Is there something deeper? Take for example multi-inheritance -- it is usually seen as hard to grasp (for the user) and thus not added to the language (like diamond problem).

Is there something in NATURE of const that pose a problem that it is better for language to avoid it? Something like deciding if const should be deep or shallow (having const container does it mean I cannot add new element or alter existing elements as well; what if elements are of reference type)?

UPDATE: while I mention C#, and thus making a historical perspective I am interested in the nature of potential problems of const to the language.

This is not a challenge of the languages. Please ignore such factors as current trends or popularity -- I am interested only in technical issues -- thank you.


问:
Does tweeting 9 to 5 hurt job applicants?
If you were looking into a job applicant's background and discovered that he or she has 1200 followers on Twitter and averages 50 tweets per day (more than half of which are during business hours), would it affect your hiring decision? How and why?

Personally, I'd be a little worried about the candidate's ability to focus on the job at hand if they're constantly checking in with their 'tweeps' thoughout the day. In non-tech jobs, a lot of companies simply block Twitter as an irrelevant distraction.  But it can be a useful resource---to programmers in particular. I just wonder how much is too much. At what point does it become a red flag?

答:
I would not hold it against them, but I might bring it up during an interview question. Perhaps say you noticed they average X tweets per day during business hours and that your ideal candidate focuses on the job while at work. See what their reaction/excuse to that is.

Personally, if I know my boss is watching my twitter page, I would be sure not to tweet during work hours.


问:
How can I explain the A a = new B();?
Let's say we have some class structure:

```<code>     public interface IA { public void doA(); }
     public class A implements IA { public void doA(){ System.out.println("A class doA");}
     public class B extends A { public void doA(){ System.out.println("B class doA"); }
</code>```

And now in a main I state this:

```<code>     //in a main
     IA ia = new B();
     ia.doA();
</code>```

Am I correct in stating that the the runtime object of ia is a B class and it has inherited all the super classes methods and attributes?

The printout from within the imaginary main is B class doA as the method doA in B will hide the same methods in its super classes?

答:
Yes, you are correct.

ia is of class B

ia is also of class A since B inherits A.

B overrrides A's doA() method.

Title: How can I explain the A a = new B();?


答:
In my understanding, not every good or excellent programmer is a Ninja. Ninjas are a special breed. A Ninja programmer is the one who appears at unusual times (e.g. 3 a.m.), does some hazardous stuff that normal people are reluctant to (like using a hex-editor to fix a highly critical bug in a decade-old, allegedly unmaintainable program directly on the production server) and vanishes unseen.

Obviously, though a Ninja needs excellent technical skills to pull off such stunts regulary and survive, many excellent programmers do not at all fit into that description. With proper methods in place, there is no need for the Ninja. On the other hand, if the impossible happens, it's a good thing to have one.

Title: Why are good programmers referred to as Ninjas?

Body:
How is a Ninja programmer defined? If it is just an experienced developer, then is there really no better way to describe that? Ninja sounds like a childish marketing ploy designed to attract developers with delusions of self-grandeur. Or am I missing something? In particular I want to know what qualities of a Ninja are desired in programmers that makes the comparison valid (besides the coolness factor)?

I did find this article which makes some good comparisons between Ninja characteristics and Agile development. However, I would like to hear from people who have used the word Ninja for hiring purposes and what their motivation was behind it.

Update: There were several good points raised on both sides of the argument. I've tried to summarize these in my blog post. I've chosen JB's answer as the accepted one because it summarizes all the valid reasons for making the comparison.


答:
The main problem is programmers tend not to use it enough, so when they hit a place where it's required, or a maintainer later wants to fix the const-correctness, there is a huge ripple effect.  You can still write perfectly good immutable code without const, your compiler just won't enforce it, and will have a more difficult time optimizing for it.  Some people prefer their compiler not help them.  I don't understand those people, but there are a lot of them.

In functional languages, pretty much everything is const, and being mutable is the rare exception, if it's allowed at all.  This has several advantages, such as easier concurrency and easier reasoning about shared state, but takes some getting used to if you are coming from a language with a mutable culture.  In other words, not wanting const is a people issue, not a technical one.


答:
Note sure if this qualifies for you, but in functional languages like Standard ML everything is immutable by default. Mutation is supported through a generic reference type. So an int variable is immutable, and a ref int variable is a mutable container for ints. Basically, variables are real variables in the mathematical sense (an unknown but fixed value) and refs are "variables" in the imperative programming sense - a memory cell that can be written to and read from. (I like to call them assignables.)

I think the problem with const is two-fold. First, C++ lacks garbage collection, which is necessary to have non-trivial persistent data structures. const must be deep to make any sense, yet having fully immutable values in C++ is impractical.

Second, in C++ you need to opt into const rather than opt out of it. But when you forget to const something and later fix it, you'll end up in the "const poisoning" situation mentioned in @RobY's answer where the const change will cascade throughout the code. If const was the default, you wouldn't find yourself applying const retroactively. Additionally, having to add const everywhere adds a lot of noise to the code.

I suspect the mainstream languages that followed (e.g. Java) were heavily shaped by C and C++'s success and way of thinking. Case in point, even with garbage collection most languages' collection APIs assume mutable data structures. The fact that everything is mutable and immutability is seen as a corner case speaks volumes about the imperative mindset behind popular languages.

EDIT: After reflecting on greenoldman's comment I realized that const isn't directly about the immutability of data; const encodes into the type of the method whether it has side effects on the instance.

It's possible to use mutation to achieve referentially transparent behavior. Suppose you have a function that when called successively returns different values - for example, a function that reads a single character from stdin. We could use cache/memoize the results of this function to produce a referentially transparent stream of values. The stream would be a linked list whose nodes will call the function the first time you try to retrieve their value, but then cache the result. So if stdin constains Hello, world!, the first time you try to retrieve the value of the first node, it'll read one char and return H. Afterwards it'll continue to return H without further calls to read a char. Likewise, the second node would read a char from stdin the first time you try to retrieve its value, this time returning e and caching that result.

The interesting thing here is that you've turned a process that's inherently stateful into an object that's seemingly stateless. However, it was necessary to mutate the object's internal state (by caching the results) to achieve this - the mutation was a benign effect. It's impossible to make our CharStream const even though the stream behaves like an immutable value. Now imagine there's a Stream interface with const methods, and all your functions expect const Streams. Your CharStream can't implement the interface!

(EDIT 2: Apparently there's a C++ keyword called mutable that would allow us to cheat and make CharStream const. However, this loophole destroys const's guarantees - now you really can't be sure something won't mutate through its const methods. I suppose it's not that bad since you must explicitly request the loophole, but you're still completely reliant on the honor system.)

Secondly, suppose you have high-order functions - that is, you can pass functions as arguments to other functions. constness is part of a function's signature, so you wouldn't be able to pass non-const functions as arguments to functions that expect const functions. Blindly enforcing const here would lead to a loss of generality.

Finally, manipulating a const object doesn't guarantee that it's not mutating some external (static or global) state behind your back, so const's guarantees aren't as strong as they initially appear.

It's not clear to me that encoding the presence or absence of side effects into the type system is universally a good thing.


问:
Why do all <algorithm> functions take only ranges, not containers?
There are many useful functions in <algorithm>, but all of them operate on "sequences" - pairs of iterators. E.g., if I have a container and like to run std::accumulate on it, I need to write:

```<code>std::vector<int> myContainer = ...;
int sum = std::accumulate(myContainer.begin(), myContainer.end(), 0);
</code>```

When all I intend to do is:

```<code>int sum = std::accumulate(myContainer, 0);
</code>```

Which is a bit more readable and clearer, in my eyes.

Now I can see that there might be cases where you'd only want to operate on parts of a container, so it's definitely useful to have the option of passing ranges. But at least in my experience, that's a rare special case. I'll usually want to operate on whole containers.

It's easy to write a wrapper function which takes a container and calls begin() and end() on it, but such convenience functions are not included in the standard library.

I'd like to know the reasoning behind this STL design choice.

答:
Adding them would gain you no power (you can already do the entire container by calling .begin() and .end() yourself), and it would add one more thing to the library that has to be properly specified, added to the libraries by the vendors, tested, maintained, etc, etc.

In short, it's probably not there because it's not worth the trouble to maintain a set of extra templates just to save whole-container users from typing one extra function call parameter.


问:
Global variable vs. local-static variable for storing state
I am writing an application for my graduation coursework, in C, using GTK+ UI library. Sometimes I ask for user input, which I need to save for later use.

The doubt comes on how to store this data. I didn't want to create global variables because I was told countless times not to use them. However, I need to interchange data between functions which don't call each other directly (because of slot-signal pattern, I don't have a function that's always accessible after the event loop starts), thus needing some independent storage.

For this purpose I designed a getter-like function which reads similar to this:

```<code>char *store_data(char *data, int clear) {
    static char *stored_data = NULL;

    if(data == NULL) {
        if(clear) {
            stored_data = NULL;
        } else {
            return stored_data;
        }
    } else {
        stored_data = data;
    }

    return NULL;
}
</code>```

Is such a construct OK or should I simply use a global variable instead?

答:
As I already said in the comments, I'd propose using a static global variable:

```<code>// Some *.c file:
static char *stored_data = NULL;
</code>```

This will only be accessible from functions in the same module (.c-file), which is preferable to a truly global variable. If you like, you can still provide "getter" and "setter" functions in the same module, which are non-static and declared in the corresponding header file.

It's still global state, but it's now encapsulated in the relevant module. It's also clearer and cleaner than the "static local" approach, in my eyes.

Body:
As I already said in the comments, I'd propose using a static global variable:

// Some *.c file:
static char *stored_data = NULL;

This will only be accessible from functions in the same module (.c-file), which is preferable to a truly global variable. If you like, you can still provide "getter" and "setter" functions in the same module, which are non-static and declared in the corresponding header file.

It's still global state, but it's now encapsulated in the relevant module. It's also clearer and cleaner than the "static local" approach, in my eyes.


答:
...  it's definitely useful to have the option of passing ranges. But at least in my experience, that's a rare special case. I'll usually want to operate on whole containers

It may be a rare special case in your experience, but in reality the whole container  is the special case, and the arbitrary range is the general case.

You've already noticed that you can implement the whole container case using the current interface, but you can't do the converse.

So, the library-writer had a choice between implementing two interfaces up front, or only implementing one which still covers all cases.

It's easy to write a wrapper function which takes a container and calls begin() and end() on it, but such convenience functions are not included in the standard library

True, especially since the free functions std::begin and std::end are now included.

So, let's say the library provides the convenience overload:

```<code>template <typename Container>
void sort(Container &c) {
  sort(begin(c), end(c));
}
</code>```

now it also needs to provide the equivalent overload taking a comparison functor, and we need to provide the equivalents for every other algorithm.

But we at least covered every case where we want to operate on a full container, right? Well, not quite. Consider

```<code>std::for_each(c.rbegin(), c.rend(), foo);
</code>```

If we want to handle operating backwards on containers, we need another method (or pair of methods) per existing algorithm.

So, the range-based approach is more general in the simple sense that:

it can do everything the whole-container version can

the whole-container approach doubles or triples the number of overloads required, while still being less powerful

the range-based algorithms are also composable (you can stack or chain iterator adaptors, although this is more commonly done in functional languages and Python)

There's another valid reason, of course, which is that it was already a lot of work to get the STL standardized, and inflating it with convenience wrappers before it had been widely used wouldn't be a great use of limited committee time. If you're interested, you can find Stepanov & Lee's technical report here

As mentioned in comments, Boost.Range provides a newer approach without requiring changes to the standard.

Title: Why do all <algorithm> functions take only ranges, not containers?

Body:
There are many useful functions in <algorithm>, but all of them operate on "sequences" - pairs of iterators. E.g., if I have a container and like to run std::accumulate on it, I need to write:

```<code>std::vector<int> myContainer = ...;
int sum = std::accumulate(myContainer.begin(), myContainer.end(), 0);
</code>```

When all I intend to do is:

```<code>int sum = std::accumulate(myContainer, 0);
</code>```

Which is a bit more readable and clearer, in my eyes.

Now I can see that there might be cases where you'd only want to operate on parts of a container, so it's definitely useful to have the option of passing ranges. But at least in my experience, that's a rare special case. I'll usually want to operate on whole containers.

It's easy to write a wrapper function which takes a container and calls begin() and end() on it, but such convenience functions are not included in the standard library.

I'd like to know the reasoning behind this STL design choice.

Body:
...  it's definitely useful to have the option of passing ranges. But at least in my experience, that's a rare special case. I'll usually want to operate on whole containers

It may be a rare special case in your experience, but in reality the whole container  is the special case, and the arbitrary range is the general case.

You've already noticed that you can implement the whole container case using the current interface, but you can't do the converse.

So, the library-writer had a choice between implementing two interfaces up front, or only implementing one which still covers all cases.

It's easy to write a wrapper function which takes a container and calls begin() and end() on it, but such convenience functions are not included in the standard library

True, especially since the free functions std::begin and std::end are now included.

So, let's say the library provides the convenience overload:

template <typename Container>
void sort(Container &c) {
  sort(begin(c), end(c));
}

now it also needs to provide the equivalent overload taking a comparison functor, and we need to provide the equivalents for every other algorithm.

But we at least covered every case where we want to operate on a full container, right? Well, not quite. Consider

std::for_each(c.rbegin(), c.rend(), foo);

If we want to handle operating backwards on containers, we need another method (or pair of methods) per existing algorithm.

So, the range-based approach is more general in the simple sense that:

it can do everything the whole-container version can

the whole-container approach doubles or triples the number of overloads required, while still being less powerful

the range-based algorithms are also composable (you can stack or chain iterator adaptors, although this is more commonly done in functional languages and Python)

There's another valid reason, of course, which is that it was already a lot of work to get the STL standardized, and inflating it with convenience wrappers before it had been widely used wouldn't be a great use of limited committee time. If you're interested, you can find Stepanov & Lee's technical report here

As mentioned in comments, Boost.Range provides a newer approach without requiring changes to the standard.


答:
I feel really disorganized for some reason!

You are feeling disorganised because you are trying to do OO design but constructing your classes around data, not behavior.

What is the behavior of WeeklyReport and YearlyReport? They seem to just hold data, which isn't an object.

Think about the system as a collection of little people talking to each other and telling each other what to do. I don't know the requirements fully, but I would guess if you do that no where will you have a ton of people for each type of report, since they would all do the same thing.

You might though end up with a person called "reporter" or "report constructor" and a "report" who can present themselves. If your software code was a little office with a ton of little people who would make the yearly report? How would she make the yearly report. Who would she talk to to construct the yearly report? How would the person present the yearly report (metaphor for displaying to screen) and to whom?

All these questions will lead you to a proper OO design that is far easier to manage than having a ton of report objects for each type of report you could produce.

Title: Basic OOP Question for a Report

Body:
I'm in development of a sample project in Android for a friend's phone that keeps track of his sales. At first, one of the requirements was to create yearly reports of this sales data. This would be stuff like most profitable week, total per quarter, total per month, and even yearly total, as well as compares for previous years (about 10 things total).

I created a class called YearlyReport that has all of these properties and they get populated from a database class that makes the appropriate SQL calls.

This data is displayed on a statistics page, but after seeing this my friend asked me to give the viewer the ability to select different weeks and display weekly data too (3 bits of information: the total for the week, the best day in the week, the worst day in the week). So as they change weeks in the year, he wants to see weekly data appear above the yearly data.

So now I need to do specific queries of weekly data, but display yearly data too. I feel really disorganized for some reason! At first I made a WeeklyReport object, and the database will say "ok for a given week W, I'll fill your WeeklyReport object and return it". Then I started wondering if I should do something smarter. Maybe combine something? Should there be inheritance? I'm missing something.

Is it OK to have a WeeklyReport and YearlyReport object? Should I combine them? If I do, it's still strange because the yearly report doesn't change much unless you move to a new year (not often), but the weekly does (depending upon the date).


问:
"Property Container" design-pattern in-depth definition
Could anybody, please, explain what is a Property Container or at least where can I get information about that pattern on the Internet?

I've found that it exists as one of the Fundamental patterns in this article.
Unfortunately, it is not described in the corresponding English article.
The only thing is a short description in Wikipedia that I've tried to approximately translate below:

This pattern allows to add additional properties for the class in
  container (inside the class), instead of extending the class with the
  new properties.

If a short example is possible in PHP / C# / C++ or Java, it would be quite useful for understanding.

P.S.: It seems like it has been described in "SanFrancisco(TM) Design Patterns: Blueprints for Business Software", but I don't have access to it. Google does not help or I'm searching with the wrong keywords...

答:
A Property Container is a class whose properties can be customized at runtime without having to edit your class definition.

This article has the only thorough example I could find. In it, they use the example of a customizable Movie class.

The PropertyContainer base class provides methods to add/remove/retrieve properties stored in the class. Basically, it acts a lot like a HashMap:

```<code>PropertyContainer:
   + addPropertyBy()
   + removeProperty()
   + getPropertyBy()
   + getPropertyKeys()
</code>```

Then you have a Movie class that inherits from the PropertyContainer:

```<code>Movie extends PropertyContainer:
   - rating
   - available
   - description
   - title
   - id
   - price

   + [getters and setters for private properties]
</code>```

Later, if you need to add releasedate as a property to the Movie class in one project, you have the ability to add it at runtime instead of updating your class.

```<code>Movie m = new Movie()
m.addPropertyBy("3/5/14", "releasedate")
</code>```

Body:
A Property Container is a class whose properties can be customized at runtime without having to edit your class definition.

This article has the only thorough example I could find. In it, they use the example of a customizable Movie class.

The PropertyContainer base class provides methods to add/remove/retrieve properties stored in the class. Basically, it acts a lot like a HashMap:

PropertyContainer:
   + addPropertyBy()
   + removeProperty()
   + getPropertyBy()
   + getPropertyKeys()

Then you have a Movie class that inherits from the PropertyContainer:

Movie extends PropertyContainer:
   - rating
   - available
   - description
   - title
   - id
   - price

   + [getters and setters for private properties]

Later, if you need to add releasedate as a property to the Movie class in one project, you have the ability to add it at runtime instead of updating your class.

Movie m = new Movie()
m.addPropertyBy("3/5/14", "releasedate")


答:
In my experience, I have seen this applied as generic storage on an object.

An object either has a relationship to other "property" objects which are stored in a hashtable or list, or an object simply has an internal hashtable associating keys to values.

This allows data to be added at runtime that was not considered at design time. This can be really good or really bad.

Good: an object is designed to be extensible, maybe containing arbitrary data defined by customers or users. If that is its purpose in life, this can be powerful.

Bad: an object may take on concerns that it should not. The extra storage may encourage the use of various anti-patterns related to object state and responsibilities.

Java example:

```<code>import java.util.*;

public class Example {
  private Map<String, Object> properties = new HashMap<>();

  public void setProperty(String key, Object value) {
    properties.put(key, value);
  }

  public Object getProperty(String key) {
    return properties.get(key);
  }

  // Might also want to expose other methods such as containsKey() or clear().
}
</code>```

Title: "Property Container" design-pattern in-depth definition

Body:
Could anybody, please, explain what is a Property Container or at least where can I get information about that pattern on the Internet?

I've found that it exists as one of the Fundamental patterns in this article.
Unfortunately, it is not described in the corresponding English article.
The only thing is a short description in Wikipedia that I've tried to approximately translate below:

This pattern allows to add additional properties for the class in
  container (inside the class), instead of extending the class with the
  new properties.

If a short example is possible in PHP / C# / C++ or Java, it would be quite useful for understanding.

P.S.: It seems like it has been described in "SanFrancisco(TM) Design Patterns: Blueprints for Business Software", but I don't have access to it. Google does not help or I'm searching with the wrong keywords...

Body:
In my experience, I have seen this applied as generic storage on an object.

An object either has a relationship to other "property" objects which are stored in a hashtable or list, or an object simply has an internal hashtable associating keys to values.

This allows data to be added at runtime that was not considered at design time. This can be really good or really bad.

Good: an object is designed to be extensible, maybe containing arbitrary data defined by customers or users. If that is its purpose in life, this can be powerful.

Bad: an object may take on concerns that it should not. The extra storage may encourage the use of various anti-patterns related to object state and responsibilities.

Java example:

import java.util.*;

public class Example {
  private Map<String, Object> properties = new HashMap<>();

  public void setProperty(String key, Object value) {
    properties.put(key, value);
  }

  public Object getProperty(String key) {
    return properties.get(key);
  }

  // Might also want to expose other methods such as containsKey() or clear().
}


问:
SQL string field lengths in a db having about 6 different types of addresses, with about 20 markets and environments
I have been advocating lately that all string fields should be ntext / nvarchar(max) - we're using MS SQL Server. The objections seem to be either "it's not a good idea" (without any reason) or "that would allow the customer to send a lot of crap". Since I believe in filtering out the crap before it hits the database, is there a good reason why my idea is bad?

My main argument for not limiting the string fields is that I have discovered that we have about six different types of addresses (customer, reseller and so on), with about 20 markets (each having its own database) and environments. I have spotted at least ten different lengths for say Address1 and the same thing happens for other fields. Instead of "standardizing" them and then discovering that we missed something, I suggested that we go ahead and limit the inputs and let the database handle anything.

Does anyone have a pro/con I don't see?

(I have seen Rule of thumb for field sizes but my focus is "is making everything max sized wrong?")

答:
I suggest you go to https://dba.stackexchange.com/ or the MSDN SQL forums and ask that question.  You might receive physical threats by suggesting such a thing.

From a programming point of view, it makes sense.  Why should you not just let the database hold whatever, and then limit it in the application?  From a data modeling point of view this is like blasphemy.  You should find out what the actual maximum allowed is, and use that, or go through and structure the database so each market has its own specific address tables.  Aside from the performance issue, it is bad database design.  It is bad database design because an Address is an actual thing, and every country has very specific rules about addresses.  In the United States, the documentation is... daunting.  But it exists.

You might also consider that just because the database is not intended to be populated from anywhere except this application, it is possible that it might end up that way later.


答:
Basically a legacy decision. The iterator concept is modeled on pointers, but containers aren't modeled on arrays. Furthermore, since arrays are hard to pass (need a non-type template parameter for length, in general), quite often a function only has pointers available.

But yeah, in hindsight the decision is wrong. We would have been better off with a range object constructible from either begin/end or begin/length; now we have multiple _n suffixed algorithms instead.


答:
While it is tempting to swing for the fence and provide more than enough storage (ever interfaced with a COBOL system with tiny, fixed-width records?), it is not necessarily a good idea.

There is a performance penalty for huge text fields as user1021726 pointed out. You will also likely not be able to create indexes on those fields.

My rule of thumb is I look at some sample data, find the longest reasonable string that could be entered, and add 50%. If an address can be at most 40 characters, make the field 60. This does not apply to fixed-width strings such as an SSN or federal tax ID.

I would also think twice about using Unicode ("N" for "National" character) on every field. While it is certainly a very good idea for something like a name or address which the end user will see, I would avoid it for any internal field that might be used by an index or join and the user cannot directly enter data into it. I know that with at least SQL Server, Unicode makes indexes and joins perform slower. Again in SQL Server, indexes can only be so many bytes too, and NVARCHAR is twice as wide. For these internal fields using shorter VARCHAR fields will definitely help performance.

Title: SQL string field lengths in a db having about 6 different types of addresses, with about 20 markets and environments

Body:
I have been advocating lately that all string fields should be ntext / nvarchar(max) - we're using MS SQL Server. The objections seem to be either "it's not a good idea" (without any reason) or "that would allow the customer to send a lot of crap". Since I believe in filtering out the crap before it hits the database, is there a good reason why my idea is bad?

My main argument for not limiting the string fields is that I have discovered that we have about six different types of addresses (customer, reseller and so on), with about 20 markets (each having its own database) and environments. I have spotted at least ten different lengths for say Address1 and the same thing happens for other fields. Instead of "standardizing" them and then discovering that we missed something, I suggested that we go ahead and limit the inputs and let the database handle anything.

Does anyone have a pro/con I don't see?

(I have seen Rule of thumb for field sizes but my focus is "is making everything max sized wrong?")


答:
You could make everything max, but then you have to test against it.  Performance when every field maxes out at 2 GB of storage?  Probably not good.

Therefore, its always a good idea to put limits on things so you will now how the system will perform and to limit the data the system can accept and transmit.


问:
Reasons for moving from raw JavaScript to a JavaScript library
Being aware of the direct benefits of libraries having things wrapped in a package, making daily work easier, my question is leaning more towards the fact that many features not implemented in HTML/DOM/CSS, has become available using these libraries.

There is everything, from visual effects (13 a dozen) to more functional oriented, to choose from.

As I see it today, 2014, with HTML5 and CSS3, more and more of these libraries seems to have played there role, as a kind of a bridge covering the gap between older browsers non capabilites and the new ones ability to handle it built in.

Whats more, is that these libraries also seems to drop older browser support little by little.

This gives me as a developer a hard decision, if to upgrade to next version with more functionality and lose old browser support, or stay on an older version with less functionality but with old browser support and the need of custom development to achieve new functionality.

So my question is, is there anything else I might have missed, which could affect whether to implement a library as a base or use raw JavaScript and add a library when it is really needed?

答:
from http://youmightnotneedjquery.com -

"At the very least, make sure you know what jQuery is doing for you,
  and what it's not. Some developers believe that jQuery is protecting
  us from a great demon of browser incompatibility when, in truth,
  post-IE8, browsers are pretty easy to deal with on their own."

From a certain standpoint, any given .js file could be counted as a rudimentary library -- not officially a library of course, but one can write a handful of JavaScript functions wrapped up in an object that handle grunt work on the app/site you're working with. That may as well be your 'library' for the purposes of that project, and if you can build against pure JS without, like, missing deadlines or pulling your hair out, it's probably The Right Decision.

The website goes on to showcase JavaScript that will work for all browser up to and including IE8 if need be - but really, it's a good question to ask yourself regardless of the project you're tackling. Are you just toggling classes? Don't have a ton of transformations? No need to rely on someone else's code, even if it is jQuery.

Honestly some things look and read far better in pure JavaScript than jQuery anyway. Look at the aforementioned website's example of comparison via jQuery:

```<code>$(el).is($(otherEl));
</code>```

In JavaScript, this is reduced down to something far more intuitive (that's an opinion, but really == and === show up in enough other languages that a journeyman would recognize this from convention and previous experience, arguably moreso than a function call):

```<code>el === otherEl
</code>```

Now that may be a loaded example, if for no other reason than a common practice with jQuery is to 'pre-grab' and name your jQuery objects like so:

```<code>function(el, otherEl){
    var $el = $(el);
    var $otherEl = $(otherEl);
    return $el.is($otherEl);
}
</code>```

But the point still stands, I think. Building a library on top of another library just to call convenience methods like removeClass() or hide() is taking the long way home.

Body:
from http://youmightnotneedjquery.com -

"At the very least, make sure you know what jQuery is doing for you,
  and what it's not. Some developers believe that jQuery is protecting
  us from a great demon of browser incompatibility when, in truth,
  post-IE8, browsers are pretty easy to deal with on their own."

From a certain standpoint, any given .js file could be counted as a rudimentary library -- not officially a library of course, but one can write a handful of JavaScript functions wrapped up in an object that handle grunt work on the app/site you're working with. That may as well be your 'library' for the purposes of that project, and if you can build against pure JS without, like, missing deadlines or pulling your hair out, it's probably The Right Decision.

The website goes on to showcase JavaScript that will work for all browser up to and including IE8 if need be - but really, it's a good question to ask yourself regardless of the project you're tackling. Are you just toggling classes? Don't have a ton of transformations? No need to rely on someone else's code, even if it is jQuery.

Honestly some things look and read far better in pure JavaScript than jQuery anyway. Look at the aforementioned website's example of comparison via jQuery:

$(el).is($(otherEl));

In JavaScript, this is reduced down to something far more intuitive (that's an opinion, but really == and === show up in enough other languages that a journeyman would recognize this from convention and previous experience, arguably moreso than a function call):

el === otherEl

Now that may be a loaded example, if for no other reason than a common practice with jQuery is to 'pre-grab' and name your jQuery objects like so:

function(el, otherEl){
    var $el = $(el);
    var $otherEl = $(otherEl);
    return $el.is($otherEl);
}

But the point still stands, I think. Building a library on top of another library just to call convenience methods like removeClass() or hide() is taking the long way home.


答:
It really depends on how much DOM manipulation you want to do. The nice thing about jQuery is that it gives you a fluent API for manipulating the document object model. If you don't want something with as much weight, try Zepto, which is a jQuery compatible API that delegates to native browser methods, making it smaller in file size.

If you don't need to do much DOM manipulation, then a JavaScript library might not be of much use anymore.

Title: Reasons for moving from raw JavaScript to a JavaScript library

Body:
Being aware of the direct benefits of libraries having things wrapped in a package, making daily work easier, my question is leaning more towards the fact that many features not implemented in HTML/DOM/CSS, has become available using these libraries.

There is everything, from visual effects (13 a dozen) to more functional oriented, to choose from.

As I see it today, 2014, with HTML5 and CSS3, more and more of these libraries seems to have played there role, as a kind of a bridge covering the gap between older browsers non capabilites and the new ones ability to handle it built in.

Whats more, is that these libraries also seems to drop older browser support little by little.

This gives me as a developer a hard decision, if to upgrade to next version with more functionality and lose old browser support, or stay on an older version with less functionality but with old browser support and the need of custom development to achieve new functionality.

So my question is, is there anything else I might have missed, which could affect whether to implement a library as a base or use raw JavaScript and add a library when it is really needed?


问:
Global vs Individual object event handlers
Lately I've been studying a lot of javascript samples, both with/without libraries, jQuery to mention one.

As an old JavaScript developer, I learned early to make use of unobtrusive javascript where one were adding mouse click events to a global handler using document.onclick = mylib.document_onclick;

Then, by tagging any element with a custom attribute/property/expando, I been able to deal with all kinds of functions in a
very simple way.

```<code>//  HTML

<div class='menulink logout' data-mc='logout'> Logout </div>
Start page 1
Start page 2

// JS

document_onclick: function (e) {
    e = getEvObj(e);                             // custom method to get event object
    var evSrcTag = getSrcObj(e);                 // custom method to get source element

    //mouseclick
    if (evSrcTag.getAttribute('data-mc') != undefined) {
        switch (evSrcTag.getAttribute('data-mc')) {

            case 'logout':
                if (!confirm(myconfig.msg['asklogout'])) {
                    return cancelEv(e);          // custom method to cancel the event
                }
                break;

            case 'ajax':
                //process ajax request as javascript is available, cancel default event (href)

            //case ......
        }
    }
},
</code>```

Today I see a lot solutions where the event is bound/attached straight to a specific element.

It appears to quikly become a long list of handlers to be added, together with individual functions and class names tied/added.

```<code>//  HTML
create link dynamically
create link dynamically
create link dynamically

//  JS
$(function(){

    $("#anchor1").click( function() {
        $("#anchor1").append('test1');
    });

    $("#anchor2").click( function() {
        $("#anchor2").append('test2');
    });

    $("#anchor3").click( function() {
        $("#anchor3").append('test3');
    });

});
</code>```

Referring to the way setting up handlers, is one approach better than the other, and if so, which one is and why?

答:
The problem with your approach is that you are replacing the browser's dispatching mechanism with your own dispatching mechanism. The browser's dispatching is not bad enough to be replaced, and is certainly better than yours:

The browser's mechanism is native to the browser, and therefore faster than your implementation in interpreted language(JavaScript).

Your mechanism uses a big switch statement, which also makes it slower.

To add more handlers to your mechanism you need to edit the giant dispatching function. To add handlers to the browser's mechanism you simply need to set the elements' attributes, which you can do from wherever appropriate - much better than a single gigantic function.

The example you've given, while seems to be very popular nowadays, is not good either since it creates massive amounts of boilerplate code duplication. I simply fail to see the benefit of searching for elements by their unique id to attach handlers to them over writing the handler directly in the element's HTML(the function call! not the implementation!).

Another popular approach is to use the class attribute instead of id - which I believe to be even worse. Why go through all the trouble of separating the logic(JS) from the document structure(HTML), just to couple it with the style(CSS)?

What I usually do is use JQuery's convenient syntax of searching-by-css-selector and attaching-anonymous-function-as-event-handler to "extend HTML" - similar to what you do but without a gloabl handler, but with separate handlers for each type of action:

```<code>//  HTML

<div class='menulink logout' data-mc='logout'> Logout </div>
<a class='menulink' data-mc='ajax' data-target='main-content-div' href='page/'>Start page 1</a>
<a class='menulink' data-mc='ajax' data-target='main-content-div' href='page/'>Start page 2</a>

// JS

$(function(){
        $('[data-mc=logout]').click(function(){
                if (!confirm(myconfig.msg['asklogout'])) {
                    return false;
                }
        });

        $('[data-mc=ajax]').click(function(){
                var target=$(this).data('target'); //retrieve data-target of the clicked tag
                return false;
        });
});
</code>```

That way, I can create separate handlers instead of you giant switch statement, but just like you I can use the elements' attribute to assign handlers to elements dynamically.

Body:
Lately I've been studying a lot of javascript samples, both with/without libraries, jQuery to mention one.

As an old JavaScript developer, I learned early to make use of unobtrusive javascript where one were adding mouse click events to a global handler using document.onclick = mylib.document_onclick;

Then, by tagging any element with a custom attribute/property/expando, I been able to deal with all kinds of functions in a
very simple way.

```<code>//  HTML

<div class='menulink logout' data-mc='logout'> Logout </div>
<a class='menulink' data-mc='ajax' data-target='main-content-div' href='page/'>Start page 1</a>
<a class='menulink' data-mc='ajax' data-target='main-content-div' href='page/'>Start page 2</a>

// JS

document_onclick: function (e) {
    e = getEvObj(e);                             // custom method to get event object
    var evSrcTag = getSrcObj(e);                 // custom method to get source element

    //mouseclick
    if (evSrcTag.getAttribute('data-mc') != undefined) {
        switch (evSrcTag.getAttribute('data-mc')) {

            case 'logout':
                if (!confirm(myconfig.msg['asklogout'])) {
                    return cancelEv(e);          // custom method to cancel the event
                }
                break;

            case 'ajax':
                //process ajax request as javascript is available, cancel default event (href)

            //case ......
        }
    }
},
</code>```

Today I see a lot solutions where the event is bound/attached straight to a specific element.

It appears to quikly become a long list of handlers to be added, together with individual functions and class names tied/added.

```<code>//  HTML
<a id="anchor1" href="#">create link dynamically</a>
<a id="anchor2" href="#">create link dynamically</a>
<a id="anchor3" href="#">create link dynamically</a>

//  JS
$(function(){

    $("#anchor1").click( function() {
        $("#anchor1").append('<a class="myclass" href="page/test1">test1</a>');
    });

    $("#anchor2").click( function() {
        $("#anchor2").append('<a class="myclass" href="page/test2">test2</a>');
    });

    $("#anchor3").click( function() {
        $("#anchor3").append('<a class="myclass" href="page/test3">test3</a>');
    });

});
</code>```

Referring to the way setting up handlers, is one approach better than the other, and if so, which one is and why?

Body:
The problem with your approach is that you are replacing the browser's dispatching mechanism with your own dispatching mechanism. The browser's dispatching is not bad enough to be replaced, and is certainly better than yours:

The browser's mechanism is native to the browser, and therefore faster than your implementation in interpreted language(JavaScript).

Your mechanism uses a big switch statement, which also makes it slower.

To add more handlers to your mechanism you need to edit the giant dispatching function. To add handlers to the browser's mechanism you simply need to set the elements' attributes, which you can do from wherever appropriate - much better than a single gigantic function.

The example you've given, while seems to be very popular nowadays, is not good either since it creates massive amounts of boilerplate code duplication. I simply fail to see the benefit of searching for elements by their unique id to attach handlers to them over writing the handler directly in the element's HTML(the function call! not the implementation!).

Another popular approach is to use the class attribute instead of id - which I believe to be even worse. Why go through all the trouble of separating the logic(JS) from the document structure(HTML), just to couple it with the style(CSS)?

What I usually do is use JQuery's convenient syntax of searching-by-css-selector and attaching-anonymous-function-as-event-handler to "extend HTML" - similar to what you do but without a gloabl handler, but with separate handlers for each type of action:

//  HTML

<div class='menulink logout' data-mc='logout'> Logout </div>
<a class='menulink' data-mc='ajax' data-target='main-content-div' href='page/'>Start page 1</a>
<a class='menulink' data-mc='ajax' data-target='main-content-div' href='page/'>Start page 2</a>

// JS

$(function(){
        $('[data-mc=logout]').click(function(){
                if (!confirm(myconfig.msg['asklogout'])) {
                    return false;
                }
        });

        $('[data-mc=ajax]').click(function(){
                var target=$(this).data('target'); //retrieve data-target of the clicked tag
                return false;
        });
});

That way, I can create separate handlers instead of you giant switch statement, but just like you I can use the elements' attribute to assign handlers to elements dynamically.


问:
Best practice with respect to anonymous classes in UI applications
When working with user interface based Java programs, one way of attaching behaviour to a certain actions (e.g. to a button click) is through the use of anonymous classes. In the example below, the GUI framework is SWT, however I have the same issues with Swing or Android UI components. Namely the structuring of my programs.

MenuItem sampleMenuItem = new MenuItem(popupMenu, SWT.NONE);
sampleMenuItem.addSelectionListener(new SelectionAdapter() {
    public void widgetSelected(SelectionEvent event) {
         doSomething();

         // handle all table entries
         for (int i=0; i<10; i++) {
             doSomething2();
         }

         doSomething3();
         doSomething4();
    }
});
```

Of course, some might argue that the amount of code in the sample above already warrants for the creation of a dedicated class that contains the logic. This is also suggested by Sonar's "Anonymous classes should not have too many lines" rule.

Interestingly, this rule also specifies that:

squid : S1188 - While waiting for support of closure in Java, anonymous classes is the most convenient way to inject a behavior without having to create a dedicated class. But those anonymous inner classes should be used only if the behavior can be accomplished in a few lines. With more complex code, a named class is called for.

However, since closures have not yet arrived in Java, my question is whether there are any more elegant solutions than:

writing a bunch of code within anonymous classes which has all sorts of drawbacks (limited reuse, slower navigating through the code, ...)

creating a huge number of dedicated classes which themselves all might have very limited functionality (i.e.: over-engineering, ...)

To extend my question: I would also like to know what are the best practices with respect to this aspect of Java based UI applications? Are there any well established patterns?

答:
Anonymous inner classes are a purely stylistic thing; they don't exist as such within the containing class at the level of the  .class file which gets created  during compilation; all anonymous inner classes DO create a separate .class file as though they were written as top level classes.

You can see this if you navigate to the output directory (typically named "out")  and look for the inner class by name. You will see a separate class file for your inner class. As I recall its name is OuterClassName$InnerClassName.class. The constructor  of an anonymous inner class (which is created even though you don't write it yourself) is passed a reference to "this" which of course is the containing outer class.

So don't base your decision on any concerns you have over "making a lot of classes". It's purely a  stylistic thing.

When I started Java, anonymous classes looked like a big mess to me just because they violated the rhythm of the class which went something like variable variable  method method  then all of a sudden this pile of code appeared. Actually, they still mildly irritate me.

Their supposed advantage is that they make code comprehension easier- you don't have to go to some other file to see what the method of the anonymous inner  class will do. But that's it.

So the decision is a stylistic one and nothing more.  If you like it, use it, if not, don't.

just wanted to quickly add this- you might revisit your idea that containing limited functionality , say 1 short method, within a dedicated class constitutes over-engineering. The class , at least in Java, is the unit of cohesion. Over-engineering isn't measured in methods per class or even class count. O E is entirely orthogonal  to both of these.


问:
Algorithm to order array
Take for example this input array:

```<code>[2,7,1,4,9]
</code>```

For this input, I need to produce an array of total 23 elements which contains two elements of 2, seven elements of 7, one element of 1, four elements of 4 and nine elements of 9.
Example of output array:

```<code>[2,2,7,7,7,7,7,7,7,1,4,4,4,4,9,...]
</code>```

However, this array needs to be ordered in the way that minimizes the number of same elements appearing next to each other. The example of such array would be something like this:

```<code>[7,2,9,4,9,1,7,...]
</code>```

The primary goal is to minimize the number of the same adjacent elements.

Secondary goal is to distribute elements unbiased across resulting array if possible.

Any pseudo code or C#, java, ... would be helpful.

答:
This can be seen as a traveling salesman problem:

each element is a node of your graph, labled with it's number

there are edges between each pair of nodes

the "distance" of getting from one node to another is 0 if the lables have different numbers, and 1 if the numbers are equal

Now you are looking for a route through this graph minimizing the total distance. Google for

```<code>           traveling salesman <your_favorite_programming_language>
</code>```

and you will find tons of example implementations with heuristic or brute-force approaches.

Title: Algorithm to order array

Body:
This can be seen as a traveling salesman problem:

each element is a node of your graph, labled with it's number

there are edges between each pair of nodes

the "distance" of getting from one node to another is 0 if the lables have different numbers, and 1 if the numbers are equal

Now you are looking for a route through this graph minimizing the total distance. Google for

           traveling salesman <your_favorite_programming_language>

and you will find tons of example implementations with heuristic or brute-force approaches.


问:
Spreading incoming batched data into a real-time stream
I would like to display some events in 'real-time'. However, I must fetch the data from another source. I can request the last X minutes, though the source is updated approximately every 5 minutes. This means that there will be a delay between the most recent data retrieved and the point in time that I make the request.

Second, because I will be receiving a batch of data, I don't want to just fire out all the events down a socket once my fetcher has retrieved it: I would like to spread out the events so that they are both accurately spaced amongst each other and in sync with their original occurrences (e.g. an event is always displayed 6 minutes after it actually happened).

My thought is to fetch the data every 5 minutes from the source, knowing that I won't get the very latest data. The original data would be then queued to be sent down the socket 7.5 minutes from its original timestamp – that is, at least ~2.5 minutes from when its batch was fetched and at most 7.5 minutes since then.

My question is this: is this the best way to approach the problem? Does this problem have any standard approaches or associated literature related to implementation best-practices and edge cases?

I am a bit worried that the frequency of my fetches and the frequency in which the source is updated will get out of sync, leading to points where no data will be retrieved from the source. However, since my socket delay is greater than my fetch frequency, the subsequent fetch should retrieve newer data before the socket queue is empty.

Is that correct? Am I missing something?

Thanks!

答:
This seems similar to something I have been dealing with. In my case: queries that can take minutes before finished (due to complexity) and requests that should get a workable response as soon as possible.

It seems you have a deliberate delay in broadcasting the data. Probably to cater the "real time" situation you have with frequent updates.

We did a "give me what you got" solution where the Server would put the request in a halting state until at least one record was there.

Then we would process the result (one or more records) and poll for the next available set of records that might or might not be streamed from another source to that server.

Problems solved on our side:
1: Slow connections / a lot of time before a connection is actually established
2: Slow response / a lot of time before one or more records are available.

If the time to build a connection is long and the source streamed X amount of records (one to N) we would get whatever is there.

If the time to build a connection is fast, we would get at least one and maybe N records.

In your case, you might like to build an internal timer and an internal Data Store where you can query and then clean the Data Store on "all records older than X minutes".
You fill the Store with whatever your Data Source provides you and then retrieve and clear whatever is complient to your needs.
All objects / records "too fresh" will be ignored and you simply can run this process without hard dependencies on retrieval / broadcasting side.

Simply get what you can get and broadcast anything that applies to your filter (in two separate processes)

Since your records are time-stamped and already provide hard data on their point of creation, you can keep this quite simple.