答:
When reading through your question, I heard a lot of has-a relationships.  A Loan has an application.  A loan has 0 or more offers.  Etc, etc.

I would imagine something like this (Java pseudocode):

```<code>public class Loan {
    private Application application;
    private List<Offers> offers;
    // etc
}
</code>```

In order to minimize duplication, I think I would have each of the child elements point back to the parent:

```<code>public class Application {
    private Loan parent;
    private List<Address> addresses;
    private List<Person> responsibleParties;
    private State currentState;
}
</code>```

This way, elements of a Loan could navigate to related elements to grab data.

There are some definite down sides to this.  For instance, if this is being stored in a database, you may be forced to load the whole Loan graph when all you want is a little bit of information.  Also, some duplication is ok, and even encourage.  Consider a person's address. The current address may not be the address that was used in their application.  In these cases, you may want defensive copies.  The application address should never change, but the current address will.  It's useful to remember that parts of this are a document and that de-duplication is problematic.

Title: How would you model an objects representing different phases of an entity life cycle?

Body:
I believe the scenario is common mostly in business workflows - for example: loan management

the process starts with a loan application, then there's the loan offer, the 'live' loan, and maybe also finished loans.

all these objects are related, and share many fields

all these objects have also many fields that are unique for each entity

the variety of objects maybe large, and the transformation between the may not be linear (for example: a single loan application may end up as several loans of different types)

How would you model this?

some options:

an entity for each type, each containing the relevant fields (possibly grouping related fields as sub entities) - leads to duplication of data.

an entity for each object, but instead of duplicating data, each object has a reference to it's predecessor (the loan doesn't contain the loaner details, but a reference to the loan application) - this causes coupling between the object structure, and the way it was created. if we change the loan application, it shouldn't effect the structure of the loan entity.

one large entity, with fields for the whole life cycle - this can create 'mega objects' with many fields. it also doesn't work well when there's a one to many or many to many relation between the phases.

Body:
When reading through your question, I heard a lot of has-a relationships.  A Loan has an application.  A loan has 0 or more offers.  Etc, etc.

I would imagine something like this (Java pseudocode):

public class Loan {
    private Application application;
    private List<Offers> offers;
    // etc
}

In order to minimize duplication, I think I would have each of the child elements point back to the parent:

public class Application {
    private Loan parent;
    private List<Address> addresses;
    private List<Person> responsibleParties;
    private State currentState;
}

This way, elements of a Loan could navigate to related elements to grab data.

There are some definite down sides to this.  For instance, if this is being stored in a database, you may be forced to load the whole Loan graph when all you want is a little bit of information.  Also, some duplication is ok, and even encourage.  Consider a person's address. The current address may not be the address that was used in their application.  In these cases, you may want defensive copies.  The application address should never change, but the current address will.  It's useful to remember that parts of this are a document and that de-duplication is problematic.


问:
Is there really anything to gain with complex design?
I've been working for a consulting firm for some time, with clients of various sizes, and I've seen web applications ranging in complexity from really simple:

MVC

Service Layer

EF

DB

To really complex:

MVC

UoW

DI / IoC

Repository

Service

UI Tests

Unit Tests

Integration Tests

But on both ends of the spectrum, the quality requirements are about the same.  In simple projects, new devs / consultants can hop on, make changes, and contribute immediately, without having to wade through 6 layers of abstraction to understand what's going on, or risking misunderstanding some complex abstraction and costing down the line.

In all cases, there was never a need to actually make code swappable or reusable - and the tests were never actually maintained past the first iteration because requirements changed, it was too time-consuming, deadlines, business pressure, etc etc.

So if - in the end -

testing and interfaces aren't used

rapid development (read: cost-savings) is a priority

the project's requirements will be changing a lot while in development

...would it be wrong to recommend a super-simple architecture, even to solve a complex problem, for an enterprise client?  Is it complexity that defines enterprise solutions, or is it the reliability, # concurrent users, ease-of-maintenance, or all of the above?

I know this is a very vague question, and any answer wouldn't apply to all cases, but I'm interested in hearing from devs / consultants that have been in the business for a while and that have worked with these varying degrees of complexity, to hear if the cool-but-expensive abstractions are worth the overall cost, at least while the project is in development.

答:
Complicated is relative. When I first started learning to program the concept of pointers especially linked lists was complicated ("How can you have something that has itself as a field"), but once I got my mind around the concept, that was simple.

When I started learning functional programming the concept of a lambda seemed complex. But then I related it to the idea of a Function pointer from C++ and it was simple. And so on with currying, and completions, and so forth and so on.

When I first started learning TDD, I thought it was complex or that it added overhead to the development process. Now I don't feel my code is complete unless I have tests at least covering the happy path. Dependency injection and using interfaces instead of concrete classes seem complex at first. But they allow you to build your code with the assumption that you'll work out the details of the dependencies and focus on the higher level constructs first.

Check out Clean Code and The Clean Coder by "Uncle Bob" Martin. The first talks about how to code better. The second talks about how to be a better coder. There's a difference between the two.

To give an analogy, I'm learning guitar. I'm at the stage where I can play simple melodies and chords. Transitioning between chords and positions is difficult. By practicing more, I'll be able to hit those transitions easier and it'll become second nature to me.

I use the repository/unit of work pattern so that I can use an in-memory repository while I'm building the basic functionality and convert to a "sql lite" or "odata" repository as I get closer to delivery. Note that this allows me to complete more functionality even before the final infrastructure is in place (or even decided on). The abstractions allow me to create mocks and stubs more easily so that I can verify the code that depends on the abstractions works as expected. Again, I can complete features from the top down.

I would say it's wrong to create the infrastructure first. The simple fact is that it is anti-agile. If I spend a sprint on "infrastructure", I'm building stuff that I'm not even certain I will need in the end and the users will have nothing to look at to provide feedback.

That is what the abstractions provide. The more you practice using them, the more they become second nature, and you'll look back at this discussion and marvel how far you've developed. Just like hopefully, I'll wonder in a few years how chord transitions were ever a challenge for me.

ContentLicense: CC BY-SA 3.0


问:
How would you model an objects representing different phases of an entity life cycle?
I believe the scenario is common mostly in business workflows - for example: loan management

the process starts with a loan application, then there's the loan offer, the 'live' loan, and maybe also finished loans.

all these objects are related, and share many fields

all these objects have also many fields that are unique for each entity

the variety of objects maybe large, and the transformation between the may not be linear (for example: a single loan application may end up as several loans of different types)

How would you model this?

some options:

an entity for each type, each containing the relevant fields (possibly grouping related fields as sub entities) - leads to duplication of data.

an entity for each object, but instead of duplicating data, each object has a reference to it's predecessor (the loan doesn't contain the loaner details, but a reference to the loan application) - this causes coupling between the object structure, and the way it was created. if we change the loan application, it shouldn't effect the structure of the loan entity.

one large entity, with fields for the whole life cycle - this can create 'mega objects' with many fields. it also doesn't work well when there's a one to many or many to many relation between the phases.

答:
If I were you, I'd keep my data immutable. It's much safer and simpler to reason about; when you manage money, this feels especially important.

Each phase of the loan application process would be represented by its own class, describing that phase in the most adequate way, and a link to the previous phase.

Where it is cheap, I'd copy data from the previous phase: for instance, numbers. Strings  are probably also easy to 'copy' if you're using a language where strings re immutable and interned, and you just copy a reference.

If a large amount of data has to be shared with a previous phase (a data table, a document scan, etc), these data probably form its own object, referred to from each phase that uses it.

Of course, I'd make every sub-object of these objects immutable, too. If a list of offer changes, it's another object that represents the change and holds both old and new lists, both immutable.

Upsides:

Your data mapping is straightforward so talking to business people becomes easier.

You have a complete picture of how your data evolved, great for bug hunting or testing, troubleshooting, reporting, and auditing.

You'll never be able to lose data through a bug in data modification logic. (If you do multi-threading, whole classes of data race and concurrent modification bugs just go away, too.)

Each phase has the best, no-compromise representation and no extra 'unused' fields.

Your type system helps you to always use a correct phase-of-workflow object, detecting many possible bugs at compile time.

Downsides:

You have many interdependent classes, sometimes deceptively similar.

Changing business logic may take a bit more changes in code.

Here's the key part of an article describing this approach. It uses Scala, but the it explains the rationale in plain English. Feel free to take a look at previous parts that show the downsides of a mutable objects approach.


问:
The keyword const and the linker file
If I declare in a header file, for example, extern unsigned long * Ptr;
and the value of this pointer Ptr in the linker file.
Will this adrress be 'constant'? Can I change its value ?

答:
```<code>extern unsigned long *Ptr;
</code>```

You can write to both Ptr (point to a new object) and *Ptr (update the thing being pointed to).

```<code>extern const unsigned long *Ptr;
extern unsigned long const *Ptr;
</code>```

You can write to Ptr (point to a new object), but you cannot write to *Ptr.

```<code>extern unsigned long * const Ptr;
</code>```

You can write to *Ptr (update the thing being pointed to), but you cannot write to Ptr.

```<code>extern const unsigned long * const Ptr;
extern unsigned long const * const Ptr;
</code>```

You cannot write to either Ptr or *Ptr.

In all cases, the value of &Ptr does not change.

Naturally, this assumes a matching defining declaration for Ptr.

Title: The keyword const and the linker file

Body:
extern unsigned long *Ptr;

You can write to both Ptr (point to a new object) and *Ptr (update the thing being pointed to).

extern const unsigned long *Ptr;
extern unsigned long const *Ptr;

You can write to Ptr (point to a new object), but you cannot write to *Ptr.

extern unsigned long * const Ptr;

You can write to *Ptr (update the thing being pointed to), but you cannot write to Ptr.

extern const unsigned long * const Ptr;
extern unsigned long const * const Ptr;

You cannot write to either Ptr or *Ptr.

In all cases, the value of &Ptr does not change.

Naturally, this assumes a matching defining declaration for Ptr.


问:
Why does the instruction "do" require a "while"?
Since this statement is so common:

while (true) (Java)

or

while (1) (C)

or sometimes

for (;;)

Why is there not a single instruction for this? I could think that an instruction that could do it is just do but do requires a while at the end of the block but it would be more logical to write an infinite loop like this

```<code>do {

//loop forever

}
</code>```

Why not? AFAIK the instruction do always requires a while at the end but if we could use it like above then it would be a clear way to define something like while (true) which I think should not be written like that (or for (;;)).

答:
do/while is semantically different from for and while in that the condition is checked after the loop body has executed, not before.  The do { ... } while(condition) structure makes that behavior clear.  Now, dmr could have used a different method to convey the same semantics, like

```<code>until ( condition ) { ... }
</code>```

but it isn't as clear (to me, anyway) that condition is evaluated at the end of the loop.

For an infinite loop it doesn't matter; just use for(;;) (which I think is more idiomatic than while(1)).

Body:
do/while is semantically different from for and while in that the condition is checked after the loop body has executed, not before.  The do { ... } while(condition) structure makes that behavior clear.  Now, dmr could have used a different method to convey the same semantics, like

until ( condition ) { ... }

but it isn't as clear (to me, anyway) that condition is evaluated at the end of the loop.

For an infinite loop it doesn't matter; just use for(;;) (which I think is more idiomatic than while(1)).


答:
One of the most eye-opening events for me was learning about Color-Based Modeling. It totally transformed my approach to designing systems.

The key idea is that there are four archetypes in object-oriented design:

Moment-Interval represents an event, or a span of time. For instance applying for a loan is a Moment the entire process from application to closure of the loan would be an Interval

Role represents participants in a Moment-Interval. Sticking with the loan, an Applicant would be one role, the loan officer would be another, underwriters would be a third.

Descriptor represents a label or a "class" of objects. For example, you might have a descriptor for Home Loans versus Auto Loans but the loans themselves are fundamentally the same. The Descriptor can also act as a factory. I usually use descriptors where people normally use Enums.

Person/Place/Thing represents a physical, tangible object. Michael Brown is a person, Global Corp. Headquarters is a Place, Dell Precision Laptop with serial number 12345 is a thing. (Note my specific Dell Precision Laptop would possibly have a descriptor attached to it in Dell's E-commerce system).

Those are the 4 basic elements of an O-O model. And here is how it relates to your question.

The very first archetype is the Moment-Interval. If you recall one of the guidelines for basic object-oriented programming "Objects are Nouns, Methods are Verbs" you might be tempted to represent the loan application as a method "ApplyForLoan" on the Applicant object and store all the information about the application on a single Loan object. Then you might be tempted to have a "LoanStatus" enumeration on the Loan that basically lists all the phases the loan goes through as it's being processed.

The better way is to have an Application moment object. And an Applicant role object. Roles are attached to Person/Place/Thing and participate in moments (in practice, I usually give the responsibility for creating a Moment object to a Role that I identify as the "actor". In the case of the loan application the Applicant is the "actor".

Within the book, Coad talks about the concept of Predecessors and Successors. I.e. before a RiskAssessment can be performed, there must be an Application. The Moments form a chain of events that are pertinent to the system being created. For instance the loan approval system would not care about payments on the loan so they wouldn't be mapped as part of the system. Although there might be another system that does deal with these details.

The beautiful part of this approach is that the system becomes very flexible and extensible because rather than sticking new fields and methods on a bloated "LoanCustomer" object (or worse deriving from loan customer to represent different roles the customer might play in the system), we create new roles as the needs of the system grows.

I'd HIGHLY recommend picking the book up and going through it. It's a very powerful technique despite the fact that UML is no longer in favor, the concepts are timeless.


答:
My guess is: for no specific reason other than personal tastes of the language designers.

Some languages, such as PL/SQL, Ada, Common Lisp, Perl6 and Go (as amon and topskip have demonstrated) do have a loop structure that loops infinitely when used by itself, but can be optionally extended with several clauses, such as while, until, initialization, increments, etc.

Most likely the C designers thought that for+while+do/while were the most useful idioms and then C++, Java and others just copied the loop statements, preferring to focus their design efforts on other language features, such as object orientation.

In other words, I don't think language designers think that's a bad feature, it's just that eventually you have to stop adding features, and there's a solid tradition in C-based languages to have for+while+do/while. In other languages, the feature you suggested does exist and it's useful.

Title: Why does the instruction "do" require a "while"?

Body:
Since this statement is so common:

while (true) (Java)

or

while (1) (C)

or sometimes

for (;;)

Why is there not a single instruction for this? I could think that an instruction that could do it is just do but do requires a while at the end of the block but it would be more logical to write an infinite loop like this

```<code>do {

//loop forever

}
</code>```

Why not? AFAIK the instruction do always requires a while at the end but if we could use it like above then it would be a clear way to define something like while (true) which I think should not be written like that (or for (;;)).


问:
How do you share your craft with non programmers?
Sometimes I feel like a musician who can't play live shows. Programming is a pretty cool skill, and a very broad world, but a lot of it happens "off camera"- in your head, in your office, away from spectators.

You can of course talk about programming with other programmers, and there is peer programming, and you do get to create something that you can show to people, but when it comes to explaining to non programmers what is it that you do, or how was your day at work, it's sort of tricky.

How do you get the non programmers in your life to understand what is it that you do?

NOTE: this is not a repeat of Getting non-programmers to understand the development process, because that question was about managing client expectations.

答:
I compare it to building a house, if we lived in a strange universe with exotic particles and anti time:

You have an idea for a really cool house, so you build a rough sketch of what it will look like, and have a general plan of how to proceed. You go to the hardware store and buy some lumber to build the walls, but they keep falling over because the ground is uneven. So you go and buy cement to set the foundation, but the cement won't dry and you can't figure out why. You go back to the hardware store and ask why, but the employee goes catatonic. You go to 8 different hardware stores until one tells you that the cement you used was developed in fall 1989, but you bought your property in the winter of 1989, so they are incompatible, and he sells you the most recent 2013.1.1 cement. You go back to lay the foundation and soon as you do, the cement disappears. This time all employees go catatonic, so you google your house and find that it was once a nuclear testing site. Then you google the effects of nuclear testing on soil and find that it causes free radicals. You google that and start researching electromagnetic radiation, then fermions, then boson, then string theory, and something about a cat. You don't want to give up because you've wasted so much time, so you hit the bottle hard. You come home late and take out your anger on your wife, claiming that she is the reason you can't build the house because her and the kids are taking up all your time...About 3 months in you realize you went from almost finishing the house, to not even knowing why you wanted to build the house in the first place.

ContentLicense: CC BY-SA 2.5


问:
Do you actively think about security when coding?
When you're coding, do you actively think about your code might be exploited in ways it wasn't originally meant to do and thus gain access to protected information, run commands or something else you wouldn't want your users to do?</p>

答:
I'm no security expert, but when I'm coding web applications I always assume that user input may contain all sorts of weirdness and should always be fully escaped and suchlike. Also, I'm careful in making Ajax calls back to the server to check that the user is logged in (if they should be for that particular event) and that they have the permissions to do whatever it is they're trying to do.

The codebase has a set of filters for inputs. I never check PHP's $_GET or $_POST arrays directly. Instead, I query them through a function Request::get('parameter', 'filter') with filters such as int, text, and a few others. (And Request::post() for POST inputs, of course.)


问:
What is MVC, really?
As a serious programmer, how do you answer the question What is MVC?

In my mind, MVC is sort of a nebulous topic — and because of that, if your audience is a learner, then you're free to describe it in general terms that are unlikely to be controversial.

However, if you are speaking to a knowledgeable audience, especially an interviewer, I have a hard time thinking of a direction to take that doesn't risk a reaction of "well that's not right!...".  We all have different real-world experience, and I haven't truly met the same MVC implementation pattern twice.

Specifically, there seem to be disagreements regarding strictness, component definition, separation of parts (what piece fits where), etc.

So, how should I explain MVC in a way that is correct, concise, and uncontroversial?

答:
Here is what I would say about it. I would try to explain it in terms of mobile applications, because it is what I am most familiar with and because I don't think I fully understood it before started doing mobile applications.

Let's take Android for example.

Presentation layer, ie. user interface can (should, most often is) be specified entirely in xml. For simplicity, let's say that one xml file describes one screen in the application. XML file specifies controls, layout of the controls, positioning, colors, size, string labels... everything regarding presentation. Yet it knows nothing about when it will be called, when will it be placed on the screen. Will it be a stand-alone layout or a part of some bigger layout? There you have it: your perfect VIEW.

Now, view obviously needs to be placed on the screen at some point, so how should do it? Your CONTROLLER, in Android called Activity. As the name says, activity does some activity. Even if its sole purpose is to display view defined in step 1, it will perform some action. So, activity fetches a view and displays it on screen. As view does not know nothing about activity, similarly activity knows nothing about the actual presentation. We (the programmers) could rearrange the layout of the view multiple times, without changing even one line of code in our activity.

Now, there is not much use in presenting your nice shiny, well-defined xml layout without actually doing something. Let's say we want to store the data entered by the user. Activity needs to tackle this process from taking the data from the user to passing it on to someone else to handle it (process, store it, delete it). Who will it pass to? Well, to a MODEL. I like to think of a model as a pure .java class that knows nothing about application context it lives in. (In practice that will almost never be the case).

Let's say I have a class Person that has three properties: name, address, age. My XML defined layout has 3 fields for user input: name, address, age. My activity takes the three values from user input, creates a new Person object and invokes some method on it that knows how to handle some Person-specific logic.
There you have it. Model-View-Controller.

Title: What is MVC, really?


问:
Which is the most practical way to add functionality to this piece of code?
I'm writing an open source library which handles hexagonal grids. It mainly revolves around the HexagonalGrid and the Hexagon class. There is a HexagonalGridBuilder class which builds the grid which contains Hexagon objects. What I'm trying to achieve is to enable the user to add arbitrary data to each Hexagon. The interface looks like this:

```<code>public interface Hexagon extends Serializable {

    // ... other methods not important in this context

    <T> void setSatelliteData(T data);

    <T> T getSatelliteData();
}
</code>```

So far so good. I'm writing another class however named HexagonalGridCalculator which adds some fancy pieces of computation to the library like calculating the shortest path between two Hexagons or calculating the line of sight around a Hexagon. My problem is that for those I need the user to supply some data for the Hexagon objects like the cost of passing through a Hexagon, or a boolean flag indicating whether the object is transparent/passable or not.

My question is how should I implement this?

My first idea was to write an interface like this:

```<code>public interface HexagonData {

    void setTransparent(boolean isTransparent);

    void setPassable(boolean isPassable);

    void setPassageCost(int cost);
}
</code>```

and make the user implement it but then it came to my mind that if I add any other functionality later all code will break for those who are using the old interface.

So my next idea is to add annotations like

@PassageCost, @IsTransparent and @IsPassable

which can be added to fields and when I'm doing the computation I can look for the annotations in the satelliteData supplied by the user. This looks flexible enough if I take into account the possibility of later changes but it uses reflection. I have no benchmark of the costs of using annotations so I'm a bit in the dark here.

I think that in 90-95% of the cases the efficiency is not important since most users wont't use a grid where this is significant but I can imagine someone trying to create a grid with a size of 5.000.000.000 X 5.000.000.000.

So which path should I start walking on? Or are there some better alternatives?

Note: These ideas are not implemented yet so I did not pay too much attention to good names.

答:
For as ill-defined a problem as this, I prefer to write an actual application first, without particular reference to what the interface will be.  Of course, you should think about what the interface will be as you go, but there's a single client so you're free to reorganize as necessary.

When you start the second application that would use the interface, start abstracting methods you need for the second application from those provided by the first.
Iterate.  The second application will inevitably force the first one to be changed to support a common interface.  The third will force the second and first to change.  Etc.

When you get to the point where adding a new application no longer requires the interfaces to change, then you are ready to publish your interface.


答:
Try:

```<code>there:
    ........
    goto there;
</code>```

But really "while(true)" is clear and concise.

A naked "while" is ambiguous, why should it mean loop forever. Logically its "while nothing" which  implies you never go there.

Similarly a naked "do" would imply "do once". If someone asks you to "do the dishes" you wash them once, you do not wash them over and over again until someone asks you to stop.

Perhaps more importantly an infinite loop is an important thing to notice if you are trying to understand a programs logic, it should have a noticeable syntax and
not a single word easily passed over.

Body:
Try:

there:
    ........
    goto there;

But really "while(true)" is clear and concise.

A naked "while" is ambiguous, why should it mean loop forever. Logically its "while nothing" which  implies you never go there.

Similarly a naked "do" would imply "do once". If someone asks you to "do the dishes" you wash them once, you do not wash them over and over again until someone asks you to stop.

Perhaps more importantly an infinite loop is an important thing to notice if you are trying to understand a programs logic, it should have a noticeable syntax and
not a single word easily passed over.


问:
Which language features are considered harmful?
Please, explain why and list which languages have the (mis)feature implemented As far you know.

Post what you consider a harmful feature, not what you dislike.

答:
Python 2.x's relative import syntax.  Suppose I have a package x.plugins that adds support for various other libraries for x.  And suppose I have a sqlalchemy module in x.plugins so I can add sqlalchemy support to x.  What do you think will happen if I add the following line to sqlalchemy.py?

```<code>import sqlalchemy
</code>```

The answer is that the module will try to import itself.  What this syntax does is essentially make it impossible to import the actual global sqlalchemy package.  Python 2.5 added a way to specify that this is a relative import:

```<code>from . import sqlalchemy
</code>```

...but it isn't until Python 3 that the first syntax was actually gotten rid of (although it can be disabled in Python 2.6+ with from __future__ import absolute_import).

Body:
Python 2.x's relative import syntax.  Suppose I have a package x.plugins that adds support for various other libraries for x.  And suppose I have a sqlalchemy module in x.plugins so I can add sqlalchemy support to x.  What do you think will happen if I add the following line to sqlalchemy.py?

import sqlalchemy

The answer is that the module will try to import itself.  What this syntax does is essentially make it impossible to import the actual global sqlalchemy package.  Python 2.5 added a way to specify that this is a relative import:

from . import sqlalchemy

...but it isn't until Python 3 that the first syntax was actually gotten rid of (although it can be disabled in Python 2.6+ with from __future__ import absolute_import).


答:
My first idea was to write an interface [...] but then it came to my mind that if I add any other functionality later all code will break for those who are using the old interface.

Use an abstract class instead:

```<code>public interface Hexagon<T extends HexagonData>{
    T getData();
    void setData(T data);
}

public abstract class HexagonData{
    public boolean isTransparent(){ return false; }
    public boolean isPassable(){ return true; }
    public int getPassageCost(){ return 0; }
}
</code>```

Don't use annotations unless you actually need metadata about the member that has been annotated.

Title: Which is the most practical way to add functionality to this piece of code?

Body:
I'm writing an open source library which handles hexagonal grids. It mainly revolves around the HexagonalGrid and the Hexagon class. There is a HexagonalGridBuilder class which builds the grid which contains Hexagon objects. What I'm trying to achieve is to enable the user to add arbitrary data to each Hexagon. The interface looks like this:

```<code>public interface Hexagon extends Serializable {

    // ... other methods not important in this context

    <T> void setSatelliteData(T data);

    <T> T getSatelliteData();
}
</code>```

So far so good. I'm writing another class however named HexagonalGridCalculator which adds some fancy pieces of computation to the library like calculating the shortest path between two Hexagons or calculating the line of sight around a Hexagon. My problem is that for those I need the user to supply some data for the Hexagon objects like the cost of passing through a Hexagon, or a boolean flag indicating whether the object is transparent/passable or not.

My question is how should I implement this?

My first idea was to write an interface like this:

```<code>public interface HexagonData {

    void setTransparent(boolean isTransparent);

    void setPassable(boolean isPassable);

    void setPassageCost(int cost);
}
</code>```

and make the user implement it but then it came to my mind that if I add any other functionality later all code will break for those who are using the old interface.

So my next idea is to add annotations like

@PassageCost, @IsTransparent and @IsPassable

which can be added to fields and when I'm doing the computation I can look for the annotations in the satelliteData supplied by the user. This looks flexible enough if I take into account the possibility of later changes but it uses reflection. I have no benchmark of the costs of using annotations so I'm a bit in the dark here.

I think that in 90-95% of the cases the efficiency is not important since most users wont't use a grid where this is significant but I can imagine someone trying to create a grid with a size of 5.000.000.000 X 5.000.000.000.

So which path should I start walking on? Or are there some better alternatives?

Note: These ideas are not implemented yet so I did not pay too much attention to good names.

Body:
My first idea was to write an interface [...] but then it came to my mind that if I add any other functionality later all code will break for those who are using the old interface.

Use an abstract class instead:

public interface Hexagon<T extends HexagonData>{
    T getData();
    void setData(T data);
}

public abstract class HexagonData{
    public boolean isTransparent(){ return false; }
    public boolean isPassable(){ return true; }
    public int getPassageCost(){ return 0; }
}

Don't use annotations unless you actually need metadata about the member that has been annotated.


问:
What's the difference between simulation and emulation
I frequently see  Simulation and Emulation in computer science. These two terms seem synonymous. Is there any difference between Simulation and Emulation?

答:
Both terms are very much similar in concept - mimicking.

Simulation or Simulators make use of software to produce a replicated system that is very much similar to target model in respect to its underlying core functionality(especially its basic methodology).

Emulators, on the other hand, focus more on exterior similarity when compared to target system. It has minimum concern for "how" the functions are mimicked. Emulators are, in general, used when working in a completely different environment(For example a different Operating system) as compared to the original system.


问:
What is the advantage to using a factor of 1024 instead of 1000 for disk size units?
When considering the disk space of a storage medium, normally the computer or operating system will represent it in terms of powers of 1024 - a kilobyte is 1,024 bytes, a megabyte is 1,048,576 bytes, a gigabyte is 1,073,741,824 bytes, and so on.

But I don't see any practical reason why this convention was adopted. Usually when disk size is represented in kilo-, mega-, or giga-bytes, it has to be converted into decimal first. In places where a power-of-two byte count actually matters (like the block size on a file system), the size is given in bytes anyway (e.g. 4096 bytes).

Was it just a little aesthetic novelty that computer makers decided to adopt, but storage medium vendors decided to disregard? Whenever you buy a hard drive, there's always a disclaimer nowadays that says "One gigabyte means one billion bytes". It would feel like using the binary definition of "gigabyte" would artificially inflate the byte count of a device, making drive-makers have to pack 1.1 terabytes into a drive in order to have it show up as "1 TB", or to simply pack 1 terabyte in and have it show up as "931 GB" (and most of them do the latter).

Some people have decided to use units like "KiB" or "MiB" in favour of "KB" and "MB" in order to distinguish the two. But is there any merit to the binary prefixes in the first place?

There's probably a bit of old history I'm not aware of on this topic, and if there is, I'm looking for somebody to explain it.

(Apologies if this is in the wrong place. I felt that a question on best practice might belong here, but I have faith that it will be migrated to the right place if it's incorrect.)

答:
There is no advantage or disadvantage of using 1024 instead of 1000 for disk size units.
It is just that 8 bit makes 1 byte and the same fashion continues for all other units of computer space.

As you correctly say, KiB and KB should be used appropriately to distinguish them properly.


问:
What are the advantages of using bitwise operations?
Following reading the latest CodeProject newsletter, I came across this article on bitwise operations.  It makes for interesting reading, and I can certainly see the benefit of checking if an integer is even or odd, but testing if the n-th bit is set?  What can possibly be the advantages of this?</p>

答: Packing data, quicker ops (multiplication, division, and modulus are significantly faster if aligned to powers of 2), bit flipping, etc. Learn them and start using them and you'll slowly start to see most of the advantages on your own.</p>


问:
Unit-testing code that relies on untestable 3rd party code
Sometimes, especially when working with third party code, I write unit-test specific code in my production code. This happens when third party code uses singletons, relies on constants, accesses the file-system/a resource I don't want to access in a test situation, or overuses inheritance. The form my unit-test specific code takes is usually the following:

```<code>if (accessing or importing a certain resource fails)
    I assume this is a test case and load a mock object
</code>```

Is this poor form, and if it is, what is normally done when writing tests for code that uses untestable third party code?

答:
Few things before we look into what can be done

-- Testing the code that we author to work as expected is a Must

-- Having test code in production code is IMO a code smell

In reality, the module we author depends on libraries and other components

1> The libraries could be authored by other team within the company

2> The libraries could be authored by 3rd party companies

If the library is authored by 3rd party or other company

Know that the 3rd party is one of the suitable vendors for the library(not the only one)

There may be a better solution provider emerging tomorrow

Hence you must design your dependency such that you can switch between those solutions easily

Hence I would suggest, think about isolating that 3rd party library usage and loosely couple your solution with the 3rd party library

You may do this by introducing a interface to wrap the capabilities of the 3rd party

This will give you a added benefit of making your code testable ie during test you will mock the 3rd party library capability and test various scenarios

If the library is authored by different team within your company

One approach is still isolate the capability of the library by defining interfaces

But i would suggest that this is a FIP (Frog in the pond) approach which would not be beneficial on the long run

In this case i would suggest you to go talk to the other team members and help them see the light

Often when this is not possible the system architects/project leads need to pitch in


答:
10000000000b = 2^10 = 1024

My guess is that they wanted something aligned to a power of 2 and the closest they could get to something beginning with a 1 and ending with a zero (without exceeding technological limits at the time) is 1024. I am probably wrong, as i didn't research this, but it's just my guess.

Title: What is the advantage to using a factor of 1024 instead of 1000 for disk size units?

Body:
When considering the disk space of a storage medium, normally the computer or operating system will represent it in terms of powers of 1024 - a kilobyte is 1,024 bytes, a megabyte is 1,048,576 bytes, a gigabyte is 1,073,741,824 bytes, and so on.

But I don't see any practical reason why this convention was adopted. Usually when disk size is represented in kilo-, mega-, or giga-bytes, it has to be converted into decimal first. In places where a power-of-two byte count actually matters (like the block size on a file system), the size is given in bytes anyway (e.g. 4096 bytes).

Was it just a little aesthetic novelty that computer makers decided to adopt, but storage medium vendors decided to disregard? Whenever you buy a hard drive, there's always a disclaimer nowadays that says "One gigabyte means one billion bytes". It would feel like using the binary definition of "gigabyte" would artificially inflate the byte count of a device, making drive-makers have to pack 1.1 terabytes into a drive in order to have it show up as "1 TB", or to simply pack 1 terabyte in and have it show up as "931 GB" (and most of them do the latter).

Some people have decided to use units like "KiB" or "MiB" in favour of "KB" and "MB" in order to distinguish the two. But is there any merit to the binary prefixes in the first place?

There's probably a bit of old history I'm not aware of on this topic, and if there is, I'm looking for somebody to explain it.

(Apologies if this is in the wrong place. I felt that a question on best practice might belong here, but I have faith that it will be migrated to the right place if it's incorrect.)


问:
Understanding exceptional cases
I've been studying the use of exceptions in various php projects (such as Doctrine and Zend Framework). Exceptions seem to be thrown when unordinary input/state occurs. A perfect example is Doctrine throwing an exception when you try to use a invalid query string.

I think the creators of the doctrine api understood that first, you can't query data by using an invalid DQL statement, and a developer should immediately be warned that an error has occurred, rather then letting execution continue with the possibility of an error code going un-checked. I also bet that this simplifies reading the code. I can't think of a situation where you would want to use an invalid DQL statement, except unit testing. Since this is true, it's better to avoid plaguing a bunch of code with null/error checks and use exceptions.

I've read in books that exceptions shouldn't be thrown when validating dating user input. I've seen examples where of where the guideline is broken. One example is the Zend framework. If supplying an invalid controller or action name, an exception is thrown. Unlike doctrine, the user has more direct control over this sort of input. I know you can configure an error controller and set up a 404 message or what have you, but I'm curious why they have used an exception in this scenario? I guess you can argue the Zend Framework does not know how to continue processing the request.

One last example Is I wrote a function to return some html based on a given resource type. This resource type is hard-coded and sent when a user interacts with a web site (such as clicking a button to display the form to input data). I don't expect users to be mucking around with the request type. Under normal operating conditions, the resource type should be valid. To clean up some logic, I was going to throw an  exception if a particular form wasn't found. This is mainly to find the correct form associated with a resource type so proper validation can occur. Does this sound like a valid use case for an exception? Right now it's pretty trivial, but I do plan to implement a restful consumer and re-using a function to map resources to their validation services would be very useful. I can then catch the exception and based on the consumer, return an error message suitable for the request type...

答:
Exceptions should be thrown in exceptional cases, such as a circumstance where the expected file doesn't exist, or when network is down, or when it takes more than a minute to open the connection to the database.

Wrong user input is not an exceptional case. It may not even be an error. For example, entering "twenty six" in Your age field is not an error from users' point of view, but still most applications wouldn't be able to handle this input as valid.

Instead of throwing an exception, the app should validate the input and, if it really can't be parsed, return either the HTML response indicating what is expected as input, or, in a context of AJAX, a JSON with the details about the invalid input.

This is the theory.

In practice, frameworks such as Zend Framework or ASP.NET MVC recur to exceptions, because there is no elegant way for them to handle invalid input. They are frameworks, not apps. This means that at some point, they should/can/might pass the info such as "Hey, I can't parse the Age field as a number!" to the application. The least ugly way to do it seems to use exceptions.

Title: Understanding exceptional cases


问:
How can I unit test that a class uses a trait in the expected manner?
A class has a trait.

The class is expected to call a function provided by the trait during a certain method invocation.

How do I write a unit test to ensure that that happens?

The difficulty, to me, comes from the fact that a trait is part of the class definition, so I cannot mock the trait in the test, as I could if the trait was instead an object that was passed in to the class constructor.

答:
IMO understanding the UNIT in the unit-testing will provide more light in your case

A class has a trait

The trait is not an object

You need to test this class

To unit test this class the public capabilities of the class are what you need to test

As this is what is promised by the class implementation

This forms the unit in the unit level tests

Essentially it means if the trait of that class

1> Can be public property (promised as a contract by the class)

2> Can be private property (not promised to external world but used solely for internal purpose)

In Case of 1> ie public property

You need to assert the property holds state info as expected by the author in various scenarios, so write tests for the same

In Case of 2> ie private property

IMO it doesnt need tests.

If all public methods, contracts as promised by the class is Asserted to work as expected in all scenarios, i think you should be well covered.

You deliver what you promised to deliver in all scenarios as expected.


问:
Why is it not standard to implement abstraction layers for the file system?
I have been taught to access databases through abstraction layers. I was wondering why it is not also standard practice to access the file system through an abstraction layer? It seems to me unit testing would become much simpler, since mocking the filesystem is often a pain and poorly supported by some languages.</p>

答:
The abstraction seems pragmatically little too heavy for very little we usually we do with fileSystems.

You can do it but when you weigh it against the volume of stuff we do(which i think is minimal) and the value it provides by abstraction.. IMO a little too much for so little


问:
Liskov principle: violation by type-hinting
According to the Liskov principle, a construction like the one below is invalid, as it strengthens a pre-condition.

I know the example is pointless/nonsense, but when I last asked a question like this, and used a more elaborate code sample, it seemed to distract people too much from the actual question.

```<code>//Data models
abstract class Argument
{
    protected $value = null;
    public function getValue()
    {
        return $this->value;
    }
    abstract public function setValue($val);
}
class Numeric extends Argument
{
    public function setValue($val)
    {
        $this->value = $val + 0;//coerce to number
        return $this;
    }
}
//used here:
abstract class Output
{
    public function printValue(Argument $arg)
    {
        echo $this->format($arg);
        return $this;
    }
    abstract public function format(Argument $arg);
}
class OutputNumeric extends Output
{
    public function format(Numeric $arg)//<-- VIOLATION!
    {
        $format = is_float($arg->getValue()) ? '%.3f' : '%d';
        return sprintf($format, $arg->getValue());
    }
}
</code>```

Why would this kind of "violation" be considered harmful? So much so that some languages, like the one I used in this example (PHP), don't even allow this?

I'm not allowed to strengthen the type-hint of an abstract method but, by overriding the printValue method, I am allowed to write:

```<code>class OutputNumeric extends Output
{
    final public function printValue(Numeric $arg)
    {
        echo $this->format($arg);
    }
    public function format(Argument $arg)
    {
        $format = is_float($arg->getValue()) ? '%.3f' : '%d';
        return sprintf($format, $arg->getValue());
    }
}
</code>```

But this would imply repeating myself for each and every child of Output, and makes my objects harder to reuse.

I understand why the Liskov principle exists, don't get me wrong, but I find it somewhat difficult to fathom why the signature of an abstract method in an abstract class has to be adhered to so much stricter than a non-abstract method.

Why I'm not allowed to hind at a child class, in a child class?

The way I see it, the child class OutputNumeric is a specific use-case of Output, and thus might need a specific instance of Argument, namely Numeric. Is it really so wrong of me to write code like this, when I am allowed to write this:

```<code>abstract class Output
{
    public function printValue(Argument $arg)
    {
        echo $this->format($arg);
    }
    public function(Argument $arg)
    {
        throw new RuntimeException(__METHOD__. ' Has to be overridden by child class');
    }
}
class OutputNumeric extends Output
{
    final public function format(Numeric $arg)
    {
        $format = is_float($arg->getValue()) ? '%.3f' : '%d';
        return sprintf($format, $arg->getValue());
    }
}
</code>```

This sort of acchieves the same thing, but it's just hacky and, to my eye, horrid code...

答:
You aren't just breaking LSP here, you're breaking the basic concept of inheritance. If you have a format(Argument $arg) in your base type, then you must have something which can match it in the derived type.

Consider that if your example were allowed, what would happen if you attempted to pass a string to OutputNumeric::format? If you had specific type information and you knew you were passing it to an OutputNumeric, it would be a type error. If you didn't and you were passing it to an Output, it wouldn't be a type error, but where could it dispatch to?

This isn't so much a violation of LSP as it is a violation of the basic contract set out by that superclass, and you can't go around violating those or suddenly your compiler can get into situations where it can't tell you that you're wrong, but it also has nowhere to dispatch the function to!

What could be a violation of LSP in this case would be if you had a NumericOutput which accepted any natural number, but also a subclass which would fail on any number higher than n. The class's contract (or "interface") hasn't changed, but the preconditions have.


问:
How do web servers enforce the same-origin policy?
I'm diving deeper into developing RESTful APIs and have so far worked with a few different frameworks to achieve this. Of course I've run into the same-origin policy, and now I'm wondering how web servers (rather than web browsers) enforce it. From what I understand, some enforcing seems to happen in the browser's end (e.g., honoring an Access-Control-Allow-Origin header received from a server). But what about the server?

For example, let's say a web server is hosting a Javascript web app that accesses an API, also hosted on that server. I assume that the server would enforce the same-origin policy --- so that only the javascript that is hosted on that server would be allowed to access the API. This would prevent someone else from writing a javascript client for that API and hosting it on another site, right? So how would a web server be able to stop a malicious client that would try to make AJAX requests to its API endpoints while claiming to be running javascript that originated from that same web server? What's the way most popular servers (Apache, nginx) protect against this kind of attack? Or is my understanding of this somehow off the mark?

Or is the cross-origin policy only enforced on the client end?

Body:
As others said, it's up to the client. But the server may need to deal with XSS, which bypasses SOP.

Supopse your server allows users to upload content, which is displayed when other users browse your site. This page is a good example - I just uploaded content, and it's displayed to you.

If my content contains the <script> tag, and the server just copies it into the HTML it generates, then the script I uploaded will run.

Since the script was found in HTML from your file, it has all the permissions of your site's script. It can, for example, upvote this answer. And this is why this answer has so many upvotes.

A good web server (like, alas, the one StackExchange uses), won't let this happen. It can remove the <script> tag, or escape it, so it will be seen but not executed (warning - this answer is far from a reliable recipe to prevent XSS).

So it's the client side that enforces SOP, but in some cases the server should work to prevent bypassing it.


问:
History of vendor css prefix
When and how did this process of prefixing css with vendor specific prefix begin.

Which browser/org start this and why was this started. I searched the web but found no details on this.

答:
(From memory) they were doing it way back in the days of the browser wars albeit inconsistently.  I recall a couple of Netscape specific prefixes from my time in the browser wars (usually where IE/Opera had got there first.)  But I don't have a specific reference.

It became standard practice when work began on CSS3.  Vendors proposing a standard needed to demonstrate the property in action to propose it to the W3C.  Since multiple vendors might want a tag implemented differently they used vendor specific names to avoid conflict and properties lose their vendor prefixes once and resolved their differences to reach CR (Candidate Recommendation) status in the standards process.

Title: History of vendor css prefix


问:
How should I make searching a relational database more efficient?
This is in the scope of a web application. I have a database which has a few nested relations. There is a feature which depicts the history of a large chain of relations. It is essentially a data analysis feature. The issue is that in order to search, a large object graph must be loaded - the loading time for this object graph is not quick enough to be viable. The problem is that without loading the whole graph it makes searching from a single string nearly impossible. In order to search, explicit fields must be specified and the search data supplied.

Is there a design pattern for exposing the data in a way which facilitates a single string search instead of having to explicitly define parameters?

答:
I faced somehow the same problem and I came to the conclusion that I was like trying to use the wrong tool to solve it.

Keep in mind that RDBMS have been designed for efficient storage purpose where Search Engines have been designed to search!

Using your DB might not be the good way to go here.

I know about FullText Search, but they have A LOT of limitations compared to what a Search Engine can do:

Tied to the DB schema, tied to structured data

Only character-based columns are searchable

Expensive if you need to scale up

Every search hits the DB (performances, bandwidth, ...)

Search Engines:

Not tied to any schema/structure

Every kind of data is indexable / searchable

Easy to scale up

Facets and other pretty out-of-the-box things

There are a lot of Search Engines, they have all their pros & cons (there are tons of articles and SO questions that will help you out to choose one depending on your existing infrastructure, your programming langage or even your existing DB).

One of them is ElasticSearch. It comes with an an easy way to automatically index data coming from any kind of source (including RDBMS like SQLServer), using what they call a River. ES comes with a Rest API and use its own NoSQL store.

Consider having a look this "ES - Beyond full-text search" presentation that just have been published!


问:
C# vector class - Interpolation design decision
Currently I'm coding a Vector class in C# and I'm coming to the point, where I've to figure out, how I want to implement a function/method to interpolate between two vectors. The (obvious) and also my first solution was to simply implement it as a method in the vector class itself:

```<code>public class Vector3D
{
    public static Vector3D LinearInterpolate(Vector3D vector1,
        Vector3D vector2, double factor) { ... }

    public Vector3D LinearInterpolate(Vector3D other, double factor { ... }
}
</code>```

(I decided to offer both a static method with two vectors as parameters and one non-static, with only one vector as the parameter)

But then I got the idea to use extension methods (defined in a separate class called e.g. Interpolation for example), since interpolation isn't really limited to vectors only. So this might be another approach:

```<code>public class Vector3D { ... }

public static class Interpolation
{
    public static Vector3D LinearInterpolate(this Vector3D vector,
        Vector3D other, double factor) { ... }
}
</code>```

And here is an example showing how one would use the different implementations:

```<code>{
    var vec1 = new Vector3D(5, 3, 1);
    var vec2 = new Vector3D(4, 2, 0);
    Vector3D vec3;

    vec3 = vec1.LinearInterpolate(vec2, 0.5); //1
    vec3 = Vector3D.LinearInterpolate(vec1, vec2, 0.5); //2

    //or with extension-methods

    vec3 = vec1.LinearInterpolate(vec2, 0.5); //3 (same as 1)
    vec3 = Interpolation.LinearInterpolation(vec1, vec2,
    0.5); //4
}
</code>```

I can't really decide on which design is preferable. Is there a rule of thumb on how to implement methods/functions similar to the one above or is it rather a matter of preference? I really would like to hear your opinions on what's better and - if possible - why.

答:
Don't use static classes, static methods (including extension methods) unless you really need them (maybe because of legacy code, or because you extend a .Net framework object).

A in-depth explanation of why static is bad can be found here.

For your Vector3 class, why don't you simply write a (non-static) class?

```<code>public interface ILinearInterpolation
{
     void Interpolate(Vector3 a, Vector3 b, double factor);
}
</code>```

Now you can write an implementation against that interface.

The alternative is to make Interpolate a member method - but you should try to keep the class interface simple, and small. Now, I agree that Vector and Matrix classes are a bit of an exception, because they have a larger inherent feature set than most other classes, as there are a lot of math things that you might need that a vector should be able to do; you mentioned Normalize() as an example in comments. Still, I feel that Interpolate should be in it's own class.

Body:
Don't use static classes, static methods (including extension methods) unless you really need them (maybe because of legacy code, or because you extend a .Net framework object).

A in-depth explanation of why static is bad can be found here.

For your Vector3 class, why don't you simply write a (non-static) class?

public interface ILinearInterpolation
{
     void Interpolate(Vector3 a, Vector3 b, double factor);
}

Now you can write an implementation against that interface.

The alternative is to make Interpolate a member method - but you should try to keep the class interface simple, and small. Now, I agree that Vector and Matrix classes are a bit of an exception, because they have a larger inherent feature set than most other classes, as there are a lot of math things that you might need that a vector should be able to do; you mentioned Normalize() as an example in comments. Still, I feel that Interpolate should be in it's own class.


问:
Searching integer sequences
I have a fairly complex search problem that I've managed to reduce to the following description. I've been googling but haven't been able to find an algorithm that seems to fit my problem cleanly. In particular the need to skip arbitrary integers. Maybe someone here can point me to something?

Take a sequence of integers A, for example (1 2 3 4)

Take various sequences of integers and test if any of them match A such that.

A contains all of the integers in the tested sequence

The ordering of the integers in the tested sequence are the same in A

We don't care about any integers in A that are not in the test sequence

We want all matching test sequences, not just the first.

An example

```<code>A = (1 2 3 4)
B = (1 3)
C = (1 3 4)
D = (3 1)
E = (1 2 5)
</code>```

B matches A

C matches A

D does not match A as the ordering is different

E does not match A as it contains an integer not in A

I hope that this explanation is clear enough. The best I've managed to do is to contruct a tree of the test sequences and iterate over A. The need to be able to skip integers leads to a lot of unsuccessful search paths.

Thanks

Reading some suggestions I feel that I have to clarify a couple of points that I left too vague.

Repeated numbers are allowed, in fact this is quite important as it allows a single test sequence to match A is multiple ways

A = (1234356), B = (236), matches could be either -23---6 or -2--3-6

I expect there to be a very large number of test sequences, in the thousands at least and sequence A will tend to have a max length of maybe 20. Thus simply trying to match each test sequence one by one by iterating becomes extremely inefficient.

Sorry if this wasn't clear.

答:
Hmm, I can think of two possible algorithms: A linear scan through the A sequence, or building a dictionary with constant-time lookup of the indices.

If you are testing many potential subsequences B against a single larger sequence A, I'd suggest you use the variant with the dictionary.

Linear Scan

Description

We maintain a cursor for the sequence A. Then we iterate through all items in the subsequence B. For each item, we move the cursor forward in A until we have found a matching item. If no matching item was found, then B isn't a subsequence.

This always runs in O(seq.size).

Pseudocode

Imperative style:

def subsequence? seq, subseq:
  i = 0
  for item in subseq:
    i++ while i < seq.size and item != seq[i]
    return false if i == seq.size
  return true
```

<p>Functional style:</p>

<pre class="lang-ml prettyprint-override"><code>let rec subsequence? = function
| _ [] -> true
| [] _ -> false
| cursor::seq item::subseq ->
  if   cursor = item
  then subsequence? seq subseq
  else subsequence? seq item::subseq
</code>```

Example implementation (Perl):

use strict; use warnings; use signatures; use Test::More;

sub is_subsequence_i ($seq, $subseq) {
  my $i = 0;
  for my $item (@$subseq) {
    $i++ while $i < @$seq and $item != $seq->[$i];
    return 0 if $i == @$seq;
  }
  return 1;
}

sub is_subsequence_f ($seq, $subseq) {
  return 1 if @$subseq == 0;
  return 0 if @$seq == 0;
  my ($cursor, @seq) = @$seq;
  my ($item, @subseq) = @$subseq;
  return is_subsequence_f(\@seq, $cursor == $item ? \@subseq : $subseq);
}

my $A = [1, 2, 3, 4];
my $B = [1, 3];
my $C = [1, 3, 4];
my $D = [3, 1];
my $E = [1, 2, 5];

for my $is_subsequence (\&is_subsequence_i, \&is_subsequence_f) {
  ok $is_subsequence->($A, $B), 'B in A';
  ok $is_subsequence->($A, $C), 'C in A';
  ok ! $is_subsequence->($A, $D), 'D not in A';
  ok ! $is_subsequence->($A, $E), 'E not in A';
  ok $is_subsequence->([1, 2, 3, 4, 3, 5, 6], [2, 3, 6]), 'multiple nums';
}

done_testing;
```

<h2>Dictionary lookup</h2>

<h3>Description</h3>

<p>We map the items of the sequence <em>A</em> to their indices. Then we look up suitable indices for each item in <em>B</em>, skip those indices that are to small, and pick the smallest possible index as a lower limit. When no indices are found, then <em>B</em> isn't a subsequence.</p>

<p>Runs in something like <em>O(subseq.size · k)</em>, where <em>k</em> describes how many duplicate numbers there are in <code>seq</code>. Plus an <em>O(seq.size)</em> overhead</p>

<p>The advantage of this solution is that a negative decision can be reached much faster (down to constant time), once you have paid the overhead of building the lookup table.</p>

<h3>Pseudocode:</h3>

<p>Imperative style:</p>

<pre class="lang-python prettyprint-override"><code># preparing the lookup table
dict = {}
for i, x in seq:
  if exists dict[x]:
    dict[x].append(i)
  else:
    dict[x] = [i]

def subsequence? subseq:
  min_index = -1
  for x in subseq:
    if indices = dict[x]:
      suitable_indices = indices.filter(_ > min_index)
      return false if suitable_indices.empty?
      min_index = suitable_indices[0]
    else:
      return false
  return true
</code>```

Functional style:

let subsequence? subseq =
  let rec subseq-loop = function
  | [] _ -> true
  | x::subseq min-index ->
    match (map (filter (_ > min-index)) data[x])
    | None -> false
    | Some([]) -> false
    | Some(new-min::_) -> subseq-loop subseq new-min
  in
    subseq-loop subseq -1
```

<p>Example implementation (Perl):</p>

<pre class="lang-perl prettyprint-override"><code>use strict; use warnings; use signatures; use Test::More;

sub build_dict ($seq) {
  my %dict;
  while (my ($i, $x) = each @$seq) {
    push @{ $dict{$x} }, $i;
  }
  return \%dict;
}

sub is_subsequence_i ($seq, $subseq) {
  my $min_index = -1;
  my $dict = build_dict($seq);
  for my $x (@$subseq) {
    my $indices = $dict->{$x} or return 0;
    ($min_index) = grep { $_ > $min_index } @$indices or return 0;
  }
  return 1;
}

sub is_subsequence_f ($seq, $subseq) {
  my $dict = build_dict($seq);
  use feature 'current_sub';
  return sub ($subseq, $min_index) {
    return 1 if @$subseq == 0;
    my ($x, @subseq) = @$subseq;
    my ($new_min) = grep { $_ > $min_index } @{ $dict->{$x} // [] } or return 0;
    __SUB__->(\@subseq, $new_min);
  }->($subseq, -1);
}

my $A = [1, 2, 3, 4];
my $B = [1, 3];
my $C = [1, 3, 4];
my $D = [3, 1];
my $E = [1, 2, 5];

for my $is_subsequence (\&is_subsequence_i, \&is_subsequence_f) {
  ok $is_subsequence->($A, $B), 'B in A';
  ok $is_subsequence->($A, $C), 'C in A';
  ok ! $is_subsequence->($A, $D), 'D not in A';
  ok ! $is_subsequence->($A, $E), 'E not in A';
  ok $is_subsequence->([1, 2, 3, 4, 3, 5, 6], [2, 3, 6]), 'multiple nums';
}

done_testing;
</code>```

Dictionary Lookup Variant: Encoding as a Finite State Machine

Description

We can further reduce algorithmic complexity down to O(subseq.size) if we trade in more memory. Instead of mapping elements to their indices, we create a graph where each node represents an element at its index. The edges show possible transitions, e.g. the sequence a, b, a would have the edges a@1 → b@2, a@1 → a@3, b@2 → a@3. This graph is equivalent to a finite state machine.

During lookup we maintain a cursor which initially is the first node of the tree.  We then walk the edge for each element in the sublist B. If no such edge exists, then B is no sublist. If after all elements the cursor contains a valid node, then B is a sublist.

Pseudocode

Imperative style:

# preparing the graph
graph = {}
for x in seq.reverse:
  next_graph = graph.clone
  next_graph[x] = graph
  graph = next_graph

def subseq? subseq:
  cursor = graph
  for x in subseq:
    cursor = graph[x]
    return false if graph == null
  return true
```

<p>Functional style:</p>

<pre class="lang-ml prettyprint-override"><code>let subseq? subseq =
  let rec subseq-loop = function
  | [] _ -> true
  | x::subseq graph -> match (graph[x])
    | None -> false
    | Some(next-graph) -> subseq-loop subseq next-graph
  in
    subseq-loop subseq graph
</code>```

Example implementation (Perl):

use strict; use warnings; use signatures; use Test::More;

sub build_graph ($seq) {
  my $graph = {};
  for (reverse @$seq) {
    $graph = { %$graph, $_ => $graph };
  }
  return $graph;
}

sub is_subsequence_i ($seq, $subseq) {
  my $cursor = build_graph($seq);
  for my $x (@$subseq) {
    $cursor = $cursor->{$x} or return 0;
  }
  return 1;
}

sub is_subsequence_f ($seq, $subseq) {
  my $graph = build_graph($seq);
  use feature 'current_sub';
  return sub ($subseq, $graph) {
    return 1 if @$subseq == 0;
    my ($x, @subseq) = @$subseq;
    my $next_graph = $graph->{$x} or return 0;
    __SUB__->(\@subseq, $next_graph);
  }->($subseq, $graph);
}

my $A = [1, 2, 3, 4];
my $B = [1, 3];
my $C = [1, 3, 4];
my $D = [3, 1];
my $E = [1, 2, 5];

for my $is_subsequence (\&is_subsequence_i, \&is_subsequence_f) {
  ok $is_subsequence->($A, $B), 'B in A';
  ok $is_subsequence->($A, $C), 'C in A';
  ok ! $is_subsequence->($A, $D), 'D not in A';
  ok ! $is_subsequence->($A, $E), 'E not in A';
  ok $is_subsequence->([1, 2, 3, 4, 3, 5, 6], [2, 3, 6]), 'multiple nums';
}

done_testing;
```

Title: Searching integer sequences

Body:
Hmm, I can think of two possible algorithms: A linear scan through the A sequence, or building a dictionary with constant-time lookup of the indices.

If you are testing many potential subsequences B against a single larger sequence A, I'd suggest you use the variant with the dictionary.

Linear Scan

Description

We maintain a cursor for the sequence A. Then we iterate through all items in the subsequence B. For each item, we move the cursor forward in A until we have found a matching item. If no matching item was found, then B isn't a subsequence.

This always runs in O(seq.size).

Pseudocode

Imperative style:

def subsequence? seq, subseq:
  i = 0
  for item in subseq:
    i++ while i < seq.size and item != seq[i]
    return false if i == seq.size
  return true

Functional style:

let rec subsequence? = function
| _ [] -> true
| [] _ -> false
| cursor::seq item::subseq ->
  if   cursor = item
  then subsequence? seq subseq
  else subsequence? seq item::subseq

Example implementation (Perl):

use strict; use warnings; use signatures; use Test::More;

sub is_subsequence_i ($seq, $subseq) {
  my $i = 0;
  for my $item (@$subseq) {
    $i++ while $i < @$seq and $item != $seq->[$i];
    return 0 if $i == @$seq;
  }
  return 1;
}

sub is_subsequence_f ($seq, $subseq) {
  return 1 if @$subseq == 0;
  return 0 if @$seq == 0;
  my ($cursor, @seq) = @$seq;
  my ($item, @subseq) = @$subseq;
  return is_subsequence_f(\@seq, $cursor == $item ? \@subseq : $subseq);
}

my $A = [1, 2, 3, 4];
my $B = [1, 3];
my $C = [1, 3, 4];
my $D = [3, 1];
my $E = [1, 2, 5];

for my $is_subsequence (\&is_subsequence_i, \&is_subsequence_f) {
  ok $is_subsequence->($A, $B), 'B in A';
  ok $is_subsequence->($A, $C), 'C in A';
  ok ! $is_subsequence->($A, $D), 'D not in A';
  ok ! $is_subsequence->($A, $E), 'E not in A';
  ok $is_subsequence->([1, 2, 3, 4, 3, 5, 6], [2, 3, 6]), 'multiple nums';
}

done_testing;

Dictionary lookup

Description

We map the items of the sequence A to their indices. Then we look up suitable indices for each item in B, skip those indices that are to small, and pick the smallest possible index as a lower limit. When no indices are found, then B isn't a subsequence.

Runs in something like O(subseq.size · k), where k describes how many duplicate numbers there are in seq. Plus an O(seq.size) overhead

The advantage of this solution is that a negative decision can be reached much faster (down to constant time), once you have paid the overhead of building the lookup table.

Pseudocode:

Imperative style:

# preparing the lookup table
dict = {}
for i, x in seq:
  if exists dict[x]:
    dict[x].append(i)
  else:
    dict[x] = [i]

def subsequence? subseq:
  min_index = -1
  for x in subseq:
    if indices = dict[x]:
      suitable_indices = indices.filter(_ > min_index)
      return false if suitable_indices.empty?
      min_index = suitable_indices[0]
    else:
      return false
  return true

Functional style:

let subsequence? subseq =
  let rec subseq-loop = function
  | [] _ -> true
  | x::subseq min-index ->
    match (map (filter (_ > min-index)) data[x])
    | None -> false
    | Some([]) -> false
    | Some(new-min::_) -> subseq-loop subseq new-min
  in
    subseq-loop subseq -1

Example implementation (Perl):

use strict; use warnings; use signatures; use Test::More;

sub build_dict ($seq) {
  my %dict;
  while (my ($i, $x) = each @$seq) {
    push @{ $dict{$x} }, $i;
  }
  return \%dict;
}

sub is_subsequence_i ($seq, $subseq) {
  my $min_index = -1;
  my $dict = build_dict($seq);
  for my $x (@$subseq) {
    my $indices = $dict->{$x} or return 0;
    ($min_index) = grep { $_ > $min_index } @$indices or return 0;
  }
  return 1;
}

sub is_subsequence_f ($seq, $subseq) {
  my $dict = build_dict($seq);
  use feature 'current_sub';
  return sub ($subseq, $min_index) {
    return 1 if @$subseq == 0;
    my ($x, @subseq) = @$subseq;
    my ($new_min) = grep { $_ > $min_index } @{ $dict->{$x} // [] } or return 0;
    __SUB__->(\@subseq, $new_min);
  }->($subseq, -1);
}

my $A = [1, 2, 3, 4];
my $B = [1, 3];
my $C = [1, 3, 4];
my $D = [3, 1];
my $E = [1, 2, 5];

for my $is_subsequence (\&is_subsequence_i, \&is_subsequence_f) {
  ok $is_subsequence->($A, $B), 'B in A';
  ok $is_subsequence->($A, $C), 'C in A';
  ok ! $is_subsequence->($A, $D), 'D not in A';
  ok ! $is_subsequence->($A, $E), 'E not in A';
  ok $is_subsequence->([1, 2, 3, 4, 3, 5, 6], [2, 3, 6]), 'multiple nums';
}

done_testing;

Dictionary Lookup Variant: Encoding as a Finite State Machine

Description

We can further reduce algorithmic complexity down to O(subseq.size) if we trade in more memory. Instead of mapping elements to their indices, we create a graph where each node represents an element at its index. The edges show possible transitions, e.g. the sequence a, b, a would have the edges a@1 → b@2, a@1 → a@3, b@2 → a@3. This graph is equivalent to a finite state machine.

During lookup we maintain a cursor which initially is the first node of the tree.  We then walk the edge for each element in the sublist B. If no such edge exists, then B is no sublist. If after all elements the cursor contains a valid node, then B is a sublist.

Pseudocode

Imperative style:

# preparing the graph
graph = {}
for x in seq.reverse:
  next_graph = graph.clone
  next_graph[x] = graph
  graph = next_graph

def subseq? subseq:
  cursor = graph
  for x in subseq:
    cursor = graph[x]
    return false if graph == null
  return true

Functional style:

let subseq? subseq =
  let rec subseq-loop = function
  | [] _ -> true
  | x::subseq graph -> match (graph[x])
    | None -> false
    | Some(next-graph) -> subseq-loop subseq next-graph
  in
    subseq-loop subseq graph

Example implementation (Perl):

use strict; use warnings; use signatures; use Test::More;

sub build_graph ($seq) {
  my $graph = {};
  for (reverse @$seq) {
    $graph = { %$graph, $_ => $graph };
  }
  return $graph;
}

sub is_subsequence_i ($seq, $subseq) {
  my $cursor = build_graph($seq);
  for my $x (@$subseq) {
    $cursor = $cursor->{$x} or return 0;
  }
  return 1;
}

sub is_subsequence_f ($seq, $subseq) {
  my $graph = build_graph($seq);
  use feature 'current_sub';
  return sub ($subseq, $graph) {
    return 1 if @$subseq == 0;
    my ($x, @subseq) = @$subseq;
    my $next_graph = $graph->{$x} or return 0;
    __SUB__->(\@subseq, $next_graph);
  }->($subseq, $graph);
}

my $A = [1, 2, 3, 4];
my $B = [1, 3];
my $C = [1, 3, 4];
my $D = [3, 1];
my $E = [1, 2, 5];

for my $is_subsequence (\&is_subsequence_i, \&is_subsequence_f) {
  ok $is_subsequence->($A, $B), 'B in A';
  ok $is_subsequence->($A, $C), 'C in A';
  ok ! $is_subsequence->($A, $D), 'D not in A';
  ok ! $is_subsequence->($A, $E), 'E not in A';
  ok $is_subsequence->([1, 2, 3, 4, 3, 5, 6], [2, 3, 6]), 'multiple nums';
}

done_testing;


答:
This algorithm should be quite efficient if getting the length and iterating the sequence is efficient.

Compare the length of both sequences. Store the longer in sequence and the shorter in subsequence

Start at the beginning of both sequences and loop until the end of sequence.

Is the number at the current position of sequence equal to to the number at the current postion of subsequence

If yes, move both positions one further

If not, move only the position of sequence one further

Is the position of subsequence at the end of the sequence

If yes, the two sequences match

If not, the two sequences don't match

Title: Searching integer sequences

Body:
I have a fairly complex search problem that I've managed to reduce to the following description. I've been googling but haven't been able to find an algorithm that seems to fit my problem cleanly. In particular the need to skip arbitrary integers. Maybe someone here can point me to something?

Take a sequence of integers A, for example (1 2 3 4)

Take various sequences of integers and test if any of them match A such that.

A contains all of the integers in the tested sequence

The ordering of the integers in the tested sequence are the same in A

We don't care about any integers in A that are not in the test sequence

We want all matching test sequences, not just the first.

An example

```<code>A = (1 2 3 4)
B = (1 3)
C = (1 3 4)
D = (3 1)
E = (1 2 5)
</code>```

B matches A

C matches A

D does not match A as the ordering is different

E does not match A as it contains an integer not in A

I hope that this explanation is clear enough. The best I've managed to do is to contruct a tree of the test sequences and iterate over A. The need to be able to skip integers leads to a lot of unsuccessful search paths.

Thanks

Reading some suggestions I feel that I have to clarify a couple of points that I left too vague.

Repeated numbers are allowed, in fact this is quite important as it allows a single test sequence to match A is multiple ways

A = (1234356), B = (236), matches could be either -23---6 or -2--3-6

I expect there to be a very large number of test sequences, in the thousands at least and sequence A will tend to have a max length of maybe 20. Thus simply trying to match each test sequence one by one by iterating becomes extremely inefficient.

Sorry if this wasn't clear.


答:
If you want to add dataelements/properties/variables to your Hexagon without changing the other HexagonHandlers like HexagonalGridCalculator you can add dynamic properties like this:

```<code>public class Hexagon implements Serializable {

    // ... other methods not important in this context

    void setProperty(int id, object data);

    object getProperty(int id, object notFoundValue);
}
</code>```

and define constants for the dataelements/properties/variables

```<code>const int SatelliteData = 1;
</code>```

If you later want to have additialal data just define new constants

```<code>const int Transparent = 2;
const int Passable = 3;
const int tPassageCost = 4;
</code>```

which does not affect the other handlers.

Body:
If you want to add dataelements/properties/variables to your Hexagon without changing the other HexagonHandlers like HexagonalGridCalculator you can add dynamic properties like this:

public class Hexagon implements Serializable {

    // ... other methods not important in this context

    void setProperty(int id, object data);

    object getProperty(int id, object notFoundValue);
}

and define constants for the dataelements/properties/variables

const int SatelliteData = 1;

If you later want to have additialal data just define new constants

const int Transparent = 2;
const int Passable = 3;
const int tPassageCost = 4;

which does not affect the other handlers.


答:
I propose faceted approach similar to the one used in C++ standard library.

```<code>interface Hexagon {
  void setData(int id, T data); //these should only be used from Facet class
  Object getData(int id);

  sealed class IFacet<T> {
    private static int count = 0;
    private int _id = count++;
    public T getData(Hexagon hexagon) {
       return (T) hexagon.getData(_id);
    }
    public void setData(Hexagon hexagon, T data) {
       hexagon.setData(_id, data);
    }
  }
}

//Usages:

class CostManager {
  public readonly Facet<int> PASSAGE_COST = new Facet<int>();

  static void incrementCost(Hexagon hex) {
    PASSAGE_COST.setData(hex, PASSAGE_COST.getData(hex)+1);
  }
}

class TransparencyManager {
  public readonly Facet<boolean> TRANSPARENT = new Facet<boolean>();
  static void disable(Hexagon hex) {
    TRANSPARENT.setData(hex, false);
  }

}
</code>```

Each Facet addresses exactly one property of Hexagon (as they use unique _id). If Hexagon.setData() and Hexagon.getData() are always used through a Facet class, the data stored will always have the type of corresponding Facet. This will prevent user from putting trying to write data of wrong type  to any given id.

To illustrate the kind of errors this approach protects from consider an example based on @k3b answer:

```<code>  static void configure(Hexagon hex) {
     hex.setData(DataType.TRANSPARENCY, "very transparent"); // compiler accepts this just fine, strings are objects, aren't they?
  }

  static void processHexagon(Hexagon hex) {
    boolean data = (Boolean)hex.getData(DataType.TRANSPARENCY); // compiler accepts this, Boolean are objects too
  }

  static void doSomeJob(Hexagon hex) {
     configure(hex);
     // working
     // more work
     // ...
     processHexagon(hex); //oops, you've got runtime error
  }
</code>```

Now consider the same code with Facets:

```<code>  static void configure(Hexagon hex) {
     TRANSPARENT.setData(hex, "very transparent"); // compiler slaps you
  }

  static void processHexagon(Hexagon hex) {
    boolean data = TRANSPARENT.getData(hex); // no downcast!
  }

  static void doSomeJob(Hexagon hex) {
     configure(hex);
     // working
     // more work
     // ...
     processHexagon(hex); //no runtime errors, just compile-time ones
  }
</code>```

As you can see, the code is even less verbose, as there is no need for downcasts now.

Body:
I propose faceted approach similar to the one used in C++ standard library.

interface Hexagon {
  void setData(int id, T data); //these should only be used from Facet class
  Object getData(int id);

  sealed class IFacet<T> {
    private static int count = 0;
    private int _id = count++;
    public T getData(Hexagon hexagon) {
       return (T) hexagon.getData(_id);
    }
    public void setData(Hexagon hexagon, T data) {
       hexagon.setData(_id, data);
    }
  }
}

//Usages:

class CostManager {
  public readonly Facet<int> PASSAGE_COST = new Facet<int>();

  static void incrementCost(Hexagon hex) {
    PASSAGE_COST.setData(hex, PASSAGE_COST.getData(hex)+1);
  }
}

class TransparencyManager {
  public readonly Facet<boolean> TRANSPARENT = new Facet<boolean>();
  static void disable(Hexagon hex) {
    TRANSPARENT.setData(hex, false);
  }

}

Each Facet addresses exactly one property of Hexagon (as they use unique _id). If Hexagon.setData() and Hexagon.getData() are always used through a Facet class, the data stored will always have the type of corresponding Facet. This will prevent user from putting trying to write data of wrong type  to any given id.

To illustrate the kind of errors this approach protects from consider an example based on @k3b answer:

  static void configure(Hexagon hex) {
     hex.setData(DataType.TRANSPARENCY, "very transparent"); // compiler accepts this just fine, strings are objects, aren't they?
  }

  static void processHexagon(Hexagon hex) {
    boolean data = (Boolean)hex.getData(DataType.TRANSPARENCY); // compiler accepts this, Boolean are objects too
  }

  static void doSomeJob(Hexagon hex) {
     configure(hex);
     // working
     // more work
     // ...
     processHexagon(hex); //oops, you've got runtime error
  }

Now consider the same code with Facets:

  static void configure(Hexagon hex) {
     TRANSPARENT.setData(hex, "very transparent"); // compiler slaps you
  }

  static void processHexagon(Hexagon hex) {
    boolean data = TRANSPARENT.getData(hex); // no downcast!
  }

  static void doSomeJob(Hexagon hex) {
     configure(hex);
     // working
     // more work
     // ...
     processHexagon(hex); //no runtime errors, just compile-time ones
  }

As you can see, the code is even less verbose, as there is no need for downcasts now.


答:
I would use interface and generics (Vector2, Vector4 etc. should be able to use the same implementation) for the interpolation implementation class and then add an extension method to make the usage more clean.

```<code>public class Vector3
{
    //Implementation
}

public interface IInterpolation<T>
{
    T Interpolate(T first, T second, double factor);
}

public class LinearInterpolation<T> : IInterpolation<T>
{
    T Interpolate(T first, T second, double factor)
    {
        return first + ((second - first) * t);
    }
}

public static Vector3Helper
{
    public static Vector3 LinearInterpolation(this Vector3 vector, Vector3 other, double factor)
    {
        var interpolation = new LinearInterpolation<Vector3>()
        return interpolation.Interpolate(vec1, vec2, 0.5);
    }
}
</code>```

Usage:

```<code>Vector3 vec1 = new Vector3(1, 1, 2);
Vector3 vec2 = new Vector3(3, 1, 2);

var interpolation = new LinearInterpolation<Vector3>()
var result interpolation.Interpolate(vec1, vec2, 0.5);
</code>```

or with the extension method:

```<code>var result = vec1.LinearInterpolation(vec2 0.5);
</code>```

Title: C# vector class - Interpolation design decision

Body:
Currently I'm coding a Vector class in C# and I'm coming to the point, where I've to figure out, how I want to implement a function/method to interpolate between two vectors. The (obvious) and also my first solution was to simply implement it as a method in the vector class itself:

```<code>public class Vector3D
{
    public static Vector3D LinearInterpolate(Vector3D vector1,
        Vector3D vector2, double factor) { ... }

    public Vector3D LinearInterpolate(Vector3D other, double factor { ... }
}
</code>```

(I decided to offer both a static method with two vectors as parameters and one non-static, with only one vector as the parameter)

But then I got the idea to use extension methods (defined in a separate class called e.g. Interpolation for example), since interpolation isn't really limited to vectors only. So this might be another approach:

```<code>public class Vector3D { ... }

public static class Interpolation
{
    public static Vector3D LinearInterpolate(this Vector3D vector,
        Vector3D other, double factor) { ... }
}
</code>```

And here is an example showing how one would use the different implementations:

```<code>{
    var vec1 = new Vector3D(5, 3, 1);
    var vec2 = new Vector3D(4, 2, 0);
    Vector3D vec3;

    vec3 = vec1.LinearInterpolate(vec2, 0.5); //1
    vec3 = Vector3D.LinearInterpolate(vec1, vec2, 0.5); //2

    //or with extension-methods

    vec3 = vec1.LinearInterpolate(vec2, 0.5); //3 (same as 1)
    vec3 = Interpolation.LinearInterpolation(vec1, vec2,
    0.5); //4
}
</code>```

I can't really decide on which design is preferable. Is there a rule of thumb on how to implement methods/functions similar to the one above or is it rather a matter of preference? I really would like to hear your opinions on what's better and - if possible - why.

Body:
I would use interface and generics (Vector2, Vector4 etc. should be able to use the same implementation) for the interpolation implementation class and then add an extension method to make the usage more clean.

public class Vector3
{
    //Implementation
}

public interface IInterpolation<T>
{
    T Interpolate(T first, T second, double factor);
}

public class LinearInterpolation<T> : IInterpolation<T>
{
    T Interpolate(T first, T second, double factor)
    {
        return first + ((second - first) * t);
    }
}

public static Vector3Helper
{
    public static Vector3 LinearInterpolation(this Vector3 vector, Vector3 other, double factor)
    {
        var interpolation = new LinearInterpolation<Vector3>()
        return interpolation.Interpolate(vec1, vec2, 0.5);
    }
}

Usage:

Vector3 vec1 = new Vector3(1, 1, 2);
Vector3 vec2 = new Vector3(3, 1, 2);

var interpolation = new LinearInterpolation<Vector3>()
var result interpolation.Interpolate(vec1, vec2, 0.5);

or with the extension method:

var result = vec1.LinearInterpolation(vec2 0.5);


答: I would build it like a DTO.  Have interfaces with getters and setters for the data you need and do your processing in external systems.  Maybe provide a default Hex they could extend if they wanted to.  The result would be more entity component system than object oriented but that is kind of the point of component systems the flexibility to extend in ways you didn't anticipate up front.</p>


答:
Why can't you just search the appropriate tables one at a time:

```<code>term = "%" + term + "%";

"select * from some_table where first_field like :term or
                                second_field like :term"
</code>```

Then load only the parts of the object graph that actually matched your search terms?

Title: How should I make searching a relational database more efficient?

Body:
This is in the scope of a web application. I have a database which has a few nested relations. There is a feature which depicts the history of a large chain of relations. It is essentially a data analysis feature. The issue is that in order to search, a large object graph must be loaded - the loading time for this object graph is not quick enough to be viable. The problem is that without loading the whole graph it makes searching from a single string nearly impossible. In order to search, explicit fields must be specified and the search data supplied.

Is there a design pattern for exposing the data in a way which facilitates a single string search instead of having to explicitly define parameters?

Body:
Why can't you just search the appropriate tables one at a time:

term = "%" + term + "%";

"select * from some_table where first_field like :term or
                                second_field like :term"

Then load only the parts of the object graph that actually matched your search terms?


答:
The reason is because in any organized file system that is placed on the drive must be able to uniquely identify each spot on the drive,  and those addresses are stored in binary format, because, well, we are using binary computers and not say, analog computers. So to most compactly represent all the addresses on a disk requires a certain minimum number of bits. File directories are basically wasted overhead space so why not make them as small as possible? Thus you actually see manufacturers targeting their physical drive platters toward certain  powers of twos, because more space than that would be wasted unless they changed the directory address length of addresses.

It is a kind of convenience and optimization for getting the most usable and addressable space between the two considerations of addressing and physical platter size.

Remember, there is a table taking up nearly 2% of the disk, and all that table does is show where on the disk each file starts, what the name of the file is, etc. so this table can be made smaller by being smart about the number of bits used for each file's address.

If you make the table address two bits longer, and you only make the drive platter twice as large, you're kind of wasting most of that second bit you added, so why not target the physical platter manufacturing to match what bits you have to create addresses?

And of course, humans wanted some way to understand the magnitude of these numbers in our digital (Powers of Ten fingers) world. Thus, the closest one is 1000.

At this point the whole thing is pretty moot because drive capacities are so huge we don't worry quite as much about the overhead of addressing, but at one point it was important.

ContentLicense: CC BY-SA 4.0


答: The basic unit in disk is not the byte, it is a sector and last time I checked, the sector sizes were a power of two in term of bytes.  If at the lower level it make sense to use a power of two, it makes sense to continue using power of two related prefixes.  (In my experience, it isn't what happens, disk vendors are using strange mixed units making less sense than power of two or power of ten one).</p>


答:
According to Wikipedia:

By the mid-1960s, binary addressing had become the standard architecture in most computer designs, and main memory sizes were most commonly powers of two. This is the most natural configuration for memory, as all combinations of their address lines map to a valid address, allowing easy aggregation into a larger block of memory with contiguous addresses.

Early computer system documentation would specify the memory size with an exact number such as 4096, 8192, or 16384 words of storage. These are all powers of two, and furthermore are small multiples of 210, or 1024. As storage capacities increased, several different methods were developed to abbreviate these quantities.

...

The disk drive industry followed a different pattern. Industry practice, more thoroughly documented at Timeline of binary prefixes and continuing today, is to specify hard drives using SI prefixes and symbols in their SI or "decimal" interpretation. Unlike binary-addressed computer main memory, there is nothing in a disk drive that influences it to have a total capacity easily expressed using a power of 1024.

If you follow up with the linked timeline, you'll see that before RAM came to be measured in powers-of-two, engineers used the SI prefixes in their standard (power-of-ten) usage.  This is the usage which hard drive manufacturers continued.  RAM measurements changed for convenience, although they were apparently standardized that way by Apple on the first Macs.

So there's good reason for RAM to be measured in powers-of-two, but they're misusing SI prefixes to do so.  Hard drives use the prefixes correctly, even though this creates some confusion.


问:
What parts of functionality should be refactored into a directive?
I am creating an application from legacy code using AngularJS.

I wonder what parts of my code should be moved into a directive.

For example, iI had thought of moving a table which is used multiple times across the application into a directive. The tables alter from headings and size.

Is it worth the effort or even a good practice to turn such things into their own directives or should I create each table in a unique way?

答:
If it is reusable and manipulates the DOM, it probably should go into a directive. That allows you to test it once, write it once, and use it multiple places. If you find yourself referencing elements directly in the controller, it's a good sign you should go to a directive because controllers shouldn't have to interact with the DOM directly at all.

The table example sounds fine - for example in our apps we might make a grid directive and reduce the amount of effort it takes to configure settings for a grid because they are managed via defaults in the direective.