答:
Schema Changes

Fetch by order --- If the code is fetching column # as the way to get the data, a change in the schema will cause the column numbers to readjust.  This will mess up the application and bad things will happen.

Fetch by name --- If the code is fetching column by name such as foo, and another table in the query adds a column foo, the way this is handled may cause problems when trying to get the right foo column.

Either way, a schema change can cause problems with the extraction of the data.

Further consider if a column that was being used is removed from the table.  The select * from ... still works but errors out when trying to pull the data out of the result set.  If the column is specified in the query, the query will error out instead giving a clear indiciation as to what and where the problem is.

Data overhead

Some columns can have a significant amount of data associated with them.  Selecting back * will pull all the data.  Yep, here's that varchar(4096) thats on 1000 rows that you've selected back giving you an additional possible 4 megabytes of data that you're not needing, but is sent across the wire anyways.

Related to the schema change, that varchar might not exist there when you first created the table, but now its there.

Failure to convey intent

When you select back * and get 20 columns but only need 2 of them, you are not conveying the intent of the code.  When looking at the query that does a select * one doesn't know what the important parts of it are.  Can I change the query to use this other plan instead to make it faster by not including these columns?  I don't know because the intent of what the query returns isn't clear.

Lets look at some SQL fiddles that explore those schema changes a bit more.

First, the initial database: http://sqlfiddle.com/#!2/a67dd/1

DDL:

```<code>create table one (oneid int, data int, twoid int);
create table two (twoid int, other int);

insert into one values (1, 42, 2);
insert into two values (2, 43);
</code>```

SQL:

```<code>select * from one join two on (one.twoid = two.twoid);
</code>```

And the columns you get back are oneid=1, data=42, twoid=2, and other=43.

Now, what happens if I add a column to table one? http://sqlfiddle.com/#!2/cd0b0/1

```<code>alter table one add column other text;

update one set other = 'foo';
</code>```

And my results from the same query as before are oneid=1, data=42, twoid=2, and other=foo.

A change in one of the tables disrupts the values of a select * and suddenly your binding of 'other' to an int is going to throw an error and you don't know why.

If instead your SQL statement was

```<code>select
    one.oneid, one.data, two.twoid, two.other
from one join two on (one.twoid = two.twoid);
</code>```

The change to table one would not have disrupted your data.  That query runs the same before the change and after the change.

Indexing

When you do a select * from you are pulling all the rows form all the tables that match the conditions.  Even tables you really don't care about.  While this means more data is transferred there's another performance issue lurking further down the stack.

Indexes.  (related on SO: How to use index in select statement?)

If you are pulling back lots of columns the database plan optimizer may disregard using an index because you are still going to need to fetch all those columns anyways and it would take more time to use the index and then fetch all of the columns in the query than it would be just to do a complete table scan.

If you are just selecting the, say, last name of a user (which you do a lot and so have an index on it), the database can do an index only scan (postgres wiki index only scan, mysql full table scan vs full index scan, Index-Only Scan: Avoiding Table Access).

There is quite a bit of optimizations about reading only from indexes if possible.  The information can be pulled in faster on each index page because you're pulling less of it also - you're not pulling in all those other columns for the select *.  It is possible for an index only scan to return results on the order of 100x faster (source: Select * is bad).

This isn't saying that a full index scan is great, its still a full scan - but its better than a full table scan.  Once you start chasing down all the ways that that select * hurts performance you keep finding new ones.

Related reading

Confusion about proper use of * wildcard in SQL

(Stack Overflow): select * vs select column

(Stack Overflow): Why is SELECT * considered harmful?

Body:
Schema Changes

Fetch by order --- If the code is fetching column # as the way to get the data, a change in the schema will cause the column numbers to readjust.  This will mess up the application and bad things will happen.

Fetch by name --- If the code is fetching column by name such as foo, and another table in the query adds a column foo, the way this is handled may cause problems when trying to get the right foo column.

Either way, a schema change can cause problems with the extraction of the data.

Further consider if a column that was being used is removed from the table.  The select * from ... still works but errors out when trying to pull the data out of the result set.  If the column is specified in the query, the query will error out instead giving a clear indiciation as to what and where the problem is.

Data overhead

Some columns can have a significant amount of data associated with them.  Selecting back * will pull all the data.  Yep, here's that varchar(4096) thats on 1000 rows that you've selected back giving you an additional possible 4 megabytes of data that you're not needing, but is sent across the wire anyways.

Related to the schema change, that varchar might not exist there when you first created the table, but now its there.

Failure to convey intent

When you select back * and get 20 columns but only need 2 of them, you are not conveying the intent of the code.  When looking at the query that does a select * one doesn't know what the important parts of it are.  Can I change the query to use this other plan instead to make it faster by not including these columns?  I don't know because the intent of what the query returns isn't clear.

Lets look at some SQL fiddles that explore those schema changes a bit more.

First, the initial database: http://sqlfiddle.com/#!2/a67dd/1

DDL:

create table one (oneid int, data int, twoid int);
create table two (twoid int, other int);

insert into one values (1, 42, 2);
insert into two values (2, 43);

SQL:

select * from one join two on (one.twoid = two.twoid);

And the columns you get back are oneid=1, data=42, twoid=2, and other=43.

Now, what happens if I add a column to table one? http://sqlfiddle.com/#!2/cd0b0/1

alter table one add column other text;

update one set other = 'foo';

And my results from the same query as before are oneid=1, data=42, twoid=2, and other=foo.

A change in one of the tables disrupts the values of a select * and suddenly your binding of 'other' to an int is going to throw an error and you don't know why.

If instead your SQL statement was

select
    one.oneid, one.data, two.twoid, two.other
from one join two on (one.twoid = two.twoid);

The change to table one would not have disrupted your data.  That query runs the same before the change and after the change.

Indexing

When you do a select * from you are pulling all the rows form all the tables that match the conditions.  Even tables you really don't care about.  While this means more data is transferred there's another performance issue lurking further down the stack.

Indexes.  (related on SO: How to use index in select statement?)

If you are pulling back lots of columns the database plan optimizer may disregard using an index because you are still going to need to fetch all those columns anyways and it would take more time to use the index and then fetch all of the columns in the query than it would be just to do a complete table scan.

If you are just selecting the, say, last name of a user (which you do a lot and so have an index on it), the database can do an index only scan (postgres wiki index only scan, mysql full table scan vs full index scan, Index-Only Scan: Avoiding Table Access).

There is quite a bit of optimizations about reading only from indexes if possible.  The information can be pulled in faster on each index page because you're pulling less of it also - you're not pulling in all those other columns for the select *.  It is possible for an index only scan to return results on the order of 100x faster (source: Select * is bad).

This isn't saying that a full index scan is great, its still a full scan - but its better than a full table scan.  Once you start chasing down all the ways that that select * hurts performance you keep finding new ones.

Related reading

Confusion about proper use of * wildcard in SQL

(Stack Overflow): select * vs select column

(Stack Overflow): Why is SELECT * considered harmful?


问:
Are monads a viable (maybe preferable) alternative to inheritance hierarchies?
I'm going to use a language-agnostic description of monads like this, first describing monoids:

A monoid is (roughly) a set of functions that take some type as a parameter and return the same type.

A monad is (roughly) a set of functions that take a wrapper type as a parameter and returns the same wrapper type.

Note those are descriptions, not definitions. Feel free to attack that description!

So in an OO language, a monad permits operation compositions like:

Flier<Duck> m = new Flier<Duck>(duck).takeOff().flyAround().land()

Note that the monad defines and controls the semantics of those operations, rather than the contained class.

Traditionally, in an OO language we'd use a class hierarchy & inheritance to provide those semantics. So we'd have a Bird class with methods takeOff(), flyAround() and land(), and Duck would inherit those.

But then we get into trouble with flightless birds, because penguin.takeOff() fails. We have to resort to Exception throwing and handling.

Also, once we say that Penguin is a Bird, we run into problems with multiple inheritance, for example if we also have a hierarchy of Swimmer.

Essentially we're trying to put classes into categories (with apologies to the Category Theory guys), and define semantics by category rather than in individual classes. But monads seem like a much clearer mechanism for doing that than hierarchies.

So in this case, we'd have a Flier<T> monad like the example above:

Flier<Duck> m = new Flier<Duck>(duck).takeOff().flyAround().land()

...and we would never instantiate a Flier<Penguin>. We could even use static typing to prevent that from happening, maybe with a marker interface. Or runtime capability-checking  to bail out. But really, a programmer should never put a Penguin into Flier, in the same sense they should never divide by zero.

Also, it's more generally applicable. A flier doesn't have to be a Bird. For example Flier<Pterodactyl>, or Flier<Squirrel>, without changing the semantics of those individual types.

Once we classify semantics by composable functions on a container -- instead of with type hierarchies -- it resolves the old problems with classes that "kind of do, kind of don't" fit into a particular hierarchy. It also easily & clearly allows multiple semantics for a class, like Flier<Duck> as well as Swimmer<Duck>. It seems like we've been struggling with a impedance mismatch by classifying behavior with class hierarchies. Monads handle it elegantly.

So my question is, in the same way that we've come to favor composition over inheritance, does it also make sense to favor monads over inheritance?

(BTW I wasn't sure if this should be here or in Comp Sci, but this seems more like a practical modelling problem. But maybe it's better over there.)

答:
So my question is, in the same way that we've come to favor composition over inheritance, does it also make sense to favor monads over inheritance?

In non-OO languages, yes. In more traditional OO languages, I would say no.

The issue is that most languages don't have type specialization, meaning you can't make Flier<Squirrel> and Flier<Bird> have different implementations. You have to do something like static Flier Flier::Create(Squirrel) (and then overload for each type). Which in turn means you have to modify this type whenever you add a new animal, and likely duplicate quite a bit of code to make it work.

Oh, and In not a few languages (C# for example) public class Flier<T> : T {} is illegal. It won't even build. Most, if not all OO programmers would expect Flier<Bird> to still be a Bird.

ContentLicense: CC BY-SA 3.0


问:
Relevance of HTML5: Is now the time?
It seems like most of the jobs I'm receiving, and most of the Internet, is still using standard HTML (HTML 4, let's say) + CSS + JS. Does anyone have any vision on where HTML5 is as a standard, particularly regarding acceptance and diffusion? It's easy to find information about inconsistencies between implementations of HTML5 and so forth. What I want to know about is relevance of HTML5.

答:
I'd say definitely get in there and start learning some of the technologies involved.  Just be aware that 'HTML 5' right now is actually really a marketing term!

HTML 5 has not been ratified as a standard yet and although all of the major players are throwing their support behind 'HTML 5' they're all actually just implementing bits a pieces of various specs including ECMA script (Java script), CSS, HTML and a whole lot more that I'm not qualified to talk about.

MS for example released IE9 beta to great fanfare in San Fran, highlighting their awesome HTML 5 support.  Naturally their IE/GPU enhanced lovely demos didn't quite work so nice on other 'HTML 5' browsers such as the latest Chrome of FF Beta or Opera.

So, um yeah, don't delay in starting to investigate - MS is banking on it heavily (even though they have their Silverlight platform) and I bet you'll see Adobe hedging their bets in the next few years as well.

For production websites that users will use tomorrow?  Um don't use 'HTML 5' yet.

ContentLicense: CC BY-SA 2.5

Title: Relevance of HTML5: Is now the time?


问:
Is there a specific term for the variable in a `foreach` construct?
Does the variable used for iteration in a foreach loop have a more specific term than simply 'the foreach variable?' Especially to differentiate it from the collection variable?

E.g. item in foreach (item in collection)

Edit: Loop variant was suggested (wiki):

In computer science, a loop variant is a mathematical function defined
  on the state space of a computer program whose value is monotonically
  decreased with respect to a (strict) well-founded relation by the
  iteration of a while loop under some invariant conditions, thereby
  ensuring its termination.

To me this sounds similar to 'iteration variable.' Is this strictly speaking correct? I would have assumed that 'loop variant' refers to the internal integer (or similar) that the collection enumerator uses for its internal state- not the variable that is set to the Current value on each iteration.

Also, an enumerator of a linked list or a dummy enumerator that never terminates do not have monotonically decreasing variables, while at the same time the foreach loop does have its item variable.

Edit 2:
The motivation of this question is to find a descriptive name for a parameter in a bytecode emitting API. This parameter is a number that refers to the local that will be set on each generated foreach iteration. It's not an iterationLocal, that would be misleading. currentLocal may be the most helpful name.

答:
I checked 5.3.3.16 the C# 5.0 spec, but all it gave me was foreach ( type identifier in expr ) embedded-statement.  While embedded-statement works well to identify the statement block of the foreach, I don't think identifier is specific enough to be helpful.

The IEnumerator interface calls it the Current item.


答:
I believe the term you're looking for is the loop variant.

UPDATE

It's been a long time since college, but if I remember correctly, loops are composed of loop variants and loop invariants. Put simply, loop variants change in each iteration where as loop invariants do not. A relationship between the loop variants and loop invariants determine the termination condition of the loop.

In my view, for a foreach the loop invariant is the enumerable object itself and the loop variant is the variable which holds each value.

When looking under the hood at the implementation details, yes the invariant is one past the last item in the enumerable and the variant is the enumerator, but they are not represented in the foreach loop. In fact, lots of work has gone into hiding those details.

All you are left with in this loop construct is the variable and the container. It is appropriate to call the variable the variant and the container the invariant, because that is how they function within the context of the construct.

Title: Is there a specific term for the variable in a `foreach` construct?

Body:
Does the variable used for iteration in a foreach loop have a more specific term than simply 'the foreach variable?' Especially to differentiate it from the collection variable?

E.g. item in foreach (item in collection)

Edit: Loop variant was suggested (wiki):

In computer science, a loop variant is a mathematical function defined
  on the state space of a computer program whose value is monotonically
  decreased with respect to a (strict) well-founded relation by the
  iteration of a while loop under some invariant conditions, thereby
  ensuring its termination.

To me this sounds similar to 'iteration variable.' Is this strictly speaking correct? I would have assumed that 'loop variant' refers to the internal integer (or similar) that the collection enumerator uses for its internal state- not the variable that is set to the Current value on each iteration.

Also, an enumerator of a linked list or a dummy enumerator that never terminates do not have monotonically decreasing variables, while at the same time the foreach loop does have its item variable.

Edit 2:
The motivation of this question is to find a descriptive name for a parameter in a bytecode emitting API. This parameter is a number that refers to the local that will be set on each generated foreach iteration. It's not an iterationLocal, that would be misleading. currentLocal may be the most helpful name.


问:
Lazy Loading, DAL and BLL abstraction
I'm asking myself a question to code the right way on a new fresh project.

I have a designed database and I mapped tables to equivalent POCO classes using Entity Framework 6 Code First.

Then, I thought "wait, if some day I want to switch from EF to another Framework for whatever reasons, or even say let's go for direct coding because of performance reasons, I must NOT use EF directly in the BLL. So, EF is NOT a DAL.

I started implementing a DAL that encapsulates EF calls. Then, I implemented a BLL consoming the DAL. For some tables this is like a direct mapping because these are "parameters tables" (countries, currencies and so on). But for others there is a good part of business logic, which is fine.

BUT

Then it comes to Lazy Loading, attaching entities etc.

Let's talk only about Lazy Loading.

1) Use Lazy Loading : when I'm so far in the BLL, I don't know any more about the underlying DAL internals. I just consume my objects, and I think "hey, every property will come just when I need it". But OMG! I'm outside the DAL, the Datacontext is not there anymore, so nothing can load anymore. Should I keep the EF data context open for the whole life of the application ? I've read it's not a good practice, even more when it comes to a eBusiness website keeping alive forever...

2) Don't use Lazy Loading but eager loading. Right, I load all the properties of my object, so every data is available for my consuming BLL. Ahem, do I really need, when loading a customer, to load all his orders, comments, addresses, countries and properties of the countries, currencies etc.etc.etc... This seems really overkill and can't live in a web application...

But, the DAL should NOT know about what the BLL needs. The DAL is here to provide data access, then the BLL will do what it needs to load just what it needs. So should I provide DAL methods to include/not include any combination possible of foreignkeys ? Seems not possible ... Should I wait for the BLL developper to tell me what methods he needs for each of his requirements? Seems too much coupled... Should the BLL be able to tell the DAL exactly what it needs? How to do that without being too much coupled?

Seems like Lazy Loading is not applicable in a multi-layer application...

答:
wait, if some day I want to switch from EF to another Framework for whatever reasons

No, you wont.

There are two reasons why what you are doing is bad idea.
First. Changing ORM is extremely rare and building all your abstractions around something like that is not a good idea. Abstractions should first and foremost be build around things that change often, so you can add those changes without having to change the code. And in data-access layer, things that change most often are the entities, how you query those entities and how you persist them. Compare that to the extra slim possibility of completely replacing your data access layer and you are going to spend changing lots of code for things that really matter and just adding code for things that don't matter. Which is opposite to how it is supposed to be.

Second is the fact that ORMs, and data access in general are complex. Sometimes even more complex than applications that use them. Also, there are huge differences between them. Even thought they might seem same, the details make them behave differently at many corner cases.  Trying to build abstractions around things so complex will inevitably result in both non-abstracting and leaky abstractions. So even if you are going to change persistence framework, you will have to change many things in business layer or implement behavior so it is same as previous framework. This is actually what you are encountering. You are trying to abstract something that is too complex to be properly abstracted away without reimplementing the whole thing.

I would highly recommend you rethinking your design without the "can't use EF directly" mentality.

Title: Lazy Loading, DAL and BLL abstraction


问:
What are the hardest parts of the C++/C#/Java programming languages?
Just wondered what are the features of the three main programming languages which show you are an 'expert'? Please exclude 'practical' skills such as indenting.

Am I right in saying for C++ the most difficult aspect to master is STL/generics? Java seems much easier as memory is handled for you. I'm not entirely sure on C# either?

I'm trying to use this to guage my current level of ability and what i wish to aim for.

ps this was posted on stackoverflow but got binned due to arguing, please do try to keep it civil as I am really interested in the answers from everyone :)

答:
In C#, the hardest feature is easily generic covariance and contravariance. Go here, scroll down and read the blog posts one by one from bottom to top. Make sure you understand every word of it, in particular all the examples. Warning: your brain will hurt.

Once you understand all that, then try to an understanding for it in practice. Understand why you can make a covariant stack (source code is given on one of the posts on the page I linked), but not a covariant queue (at least, not without a significant speed hit).

Finally, try to find a use for them (not trivial ^^), and then try to implement it yourself. I'll give you bonus kudos if you use it in a recursive structure, and figure out you have to 'hide' the generics from the compiler to get it all working.

If you do all that, congratulations! You've managed to acquire skill at a highly complicated piece of the C# language that you will probably never use again.

OwnerDisplayName: tom

ContentLicense: CC BY-SA 4.0


问:
Is there a problem holding large numbers of open socket connections for lengthy periods of time?
The application we have in mind is a relay server. The aim is to accept large numbers of incoming socket connections (at least thousands) that will stay open for lengthy periods (hours or maybe days). They will exchange modest quantities of data and they need reasonably low latency.

The technical design is straightfoward and we have a test implementation. Our preference is to use Windows hosting and .NET, because that's the technology we know. However, this kind of usage is well outside what we are familiar with.

The question is whether there are specific limits or constraints to be aware of that are inherent in or common to software that does this, and that we should allow for in our design and/or test for before a roll-out.

I found this question (Handling large amounts of sockets) and this link (http://www.metabrew.com/article/a-million-user-comet-application-with-mochiweb-part-1), which tend to suggest that our solution should work.

--

Commenters have suggested opening and closing ports, or using some kind of protocol, without suggesting how. The problem is that at any time a message might be relayed to an individual known destination with the expectation that it be received quickly (say 1 second at most, preferably sooner). The destination is (in general) behind a firewall with unknown properties, so cannot (in general) run a server or accept incoming connections. It can only make outgoing connections. We think it needs a persistent outgoing connection in order to receive packets at any time without notice. Alternative suggestions would be of interest, although strictly off topic for this question.

Other commenters have suggested there are OS limits, but not specified any. Assuming that this is some version of Windows server and some (perhaps large) amount of memory, are the limits likely to be a problem? Roughly what will they be? Is Windows a bad idea?

答:
I think you're looking for a protocol: something that can handle errors, retransmissions, etc. For example, what happens if one of the socket is dropped because the underlying network had a problem? Or if your messages are received twice because of a faulty switch along the line? Or if they arrive in the wrong order?

Given that you're planning for a large number of connections, you'll also have to consider the increase in probability that something will malfunction.

Also, what happens if you want to scale your architecture horizontally, i.e. adding more servers? You can't load-balance open sockets and seamlessly transfer them across nodes.

In the end I'd recommend using a more robust message-passing protocol, designed expecting failures. In simpler terms, consider each communication atomic, where the worst case is a new connection every time. More or less along the lines of the C10K problem.

If you still need more convincing, try to test your architecture with a mock up: see how it reacts to ten thousands client connecting at the same time (it's easier in a LAN). Then imagine adding network latency, errors, etc.


答:
Experience suggests that there is a better and probably fairly different solution for your problem.

However, it is possible to create and maintain substantial numbers of socket connections for a long period of time with a less than 100% reliability.

A robust design would be done very differently.

The problem is what happens when your relay server crashes.  If you only have one server, then your service is 100% lost.  If you have multiple servers, then the clients can reconnect and be connected to a different server - but any messages being relayed back to them during the disconnect and reconnect will have been lost. Depending on your product, this may be important.

If your 'relay' was actually implemented as a distributed message queue service, then it provides a tool set that solves most of these issues for you and provides a mechanism for implementing the level of robustness and availability that suits your application.

This is not a recommendation, but RabbitMQ is one example of a product that may perform the relay function for you.  There are others, and you will need to review a selection to decide which is most appropriate for your product.

Title: Is there a problem holding large numbers of open socket connections for lengthy periods of time?

Body:
The application we have in mind is a relay server. The aim is to accept large numbers of incoming socket connections (at least thousands) that will stay open for lengthy periods (hours or maybe days). They will exchange modest quantities of data and they need reasonably low latency.

The technical design is straightfoward and we have a test implementation. Our preference is to use Windows hosting and .NET, because that's the technology we know. However, this kind of usage is well outside what we are familiar with.

The question is whether there are specific limits or constraints to be aware of that are inherent in or common to software that does this, and that we should allow for in our design and/or test for before a roll-out.

I found this question (Handling large amounts of sockets) and this link (http://www.metabrew.com/article/a-million-user-comet-application-with-mochiweb-part-1), which tend to suggest that our solution should work.

--

Commenters have suggested opening and closing ports, or using some kind of protocol, without suggesting how. The problem is that at any time a message might be relayed to an individual known destination with the expectation that it be received quickly (say 1 second at most, preferably sooner). The destination is (in general) behind a firewall with unknown properties, so cannot (in general) run a server or accept incoming connections. It can only make outgoing connections. We think it needs a persistent outgoing connection in order to receive packets at any time without notice. Alternative suggestions would be of interest, although strictly off topic for this question.

Other commenters have suggested there are OS limits, but not specified any. Assuming that this is some version of Windows server and some (perhaps large) amount of memory, are the limits likely to be a problem? Roughly what will they be? Is Windows a bad idea?


问:
Why can't a User Story be attached to more than one Feature?
I'm using Features to document the features as we originally communicated them to our client at proposal stage. I now want to create User Stories that relate to the features so that I can  easily map our stories back to the proposal.

Many of the stories naturally map across features, but Team Foundation Server (TFS) doesn't let me give a Story more than one Parent feature. Is this because I'm "doing it wrong" or is it more a limitation of TFS at the moment?

答:
In my opinion, there's no reason a user story can't be attached to more than one feature. However, most people seem to agree that's a bad idea. Best practice is to limit a story to a single feature -- it makes the story smaller, and thus easier to estimate, build and test. Perhaps that's why TFS is the way it is, to force you to stick to best practices. </p>

<p>Your goal shouldn't be to do what someone else says you should do, you should do what makes your particular team as effective as possible. If attaching two features to a story does that, then do it. That being said, unless you have a specific reason to do so, I encourage you to stick with the best practice and only associate a single feature with a story. </p>

Body:
In my opinion, there's no reason a user story can't be attached to more than one feature. However, most people seem to agree that's a bad idea. Best practice is to limit a story to a single feature -- it makes the story smaller, and thus easier to estimate, build and test. Perhaps that's why TFS is the way it is, to force you to stick to best practices.

Your goal shouldn't be to do what someone else says you should do, you should do what makes your particular team as effective as possible. If attaching two features to a story does that, then do it. That being said, unless you have a specific reason to do so, I encourage you to stick with the best practice and only associate a single feature with a story.


问:
PHP coding practice
I'm a self taught PHP programmer. Because I have no formal training in PHP, I often find my coding style to be considerably different than example code I find on the Internet. I've slowly started adapting some of the more common practices I find. However, before changing my habits, I try to find a good reason to use the new style. I just don't see much reason to change my habit if it isn't actually advantageous.

I see a lot of people write PHP code such as :

```<code><h1><?php echo $cTitle; ?></h1>
<div><?php print $cContent; ?></div>
</code>```

Whereas I generally write :

```<code><?php
    echo "<h1>", $cTitle, "</h1>";
    print("<div>" . $cContent . "</div>");
</code>```

What I'm seeing is that people are commonly going in-and-out of PHP, while I'll just use PHP to print/echo the html content along with the PHP variables.

Is there a measurable difference between these two methods? Is there a good reason for me to change my ways?

答:
I am no fan at all of embedding PHP inside HTML (like your first example).  That just makes a huge mess of things and makes it difficult to separate the code from display.  Some systems are set up to use PHP as a template engine so there's no avoiding it inside of views.  But in systems I build from scratch, I never do the former, and don't do a lot of the latter of your examples, preferring to use templates.

So basically, no, don't go a'changing.  Remember, a large chunk of the PHP code you see online either comes from really old tutorials back from the days where one php file = one page, or from people who learned PHP from said tutorials.

Title: PHP coding practice


问:
Pros and Cons of RESTful architecture
The most common discussion I've seen regarding the pros and cons of REST tends to frame that discussion relative to SOAP. I have no experience in either. I am currently faced with a decision which my lack of experience is making hard for me to evaluate.
I am beginning to develop an application that has several components - primarily an administrative aspect that allows the owner to administer several sites - and a public facing user interface that allows the user to interact with data held on the host.
I need to evaluate the implications of allowing the latter part to be hosted anywhere and communicate with the former via a RESTful architecture - or demanding that both components reside on the same host.
What are the key implications of developing RESTful architecture, particularly with regards to it's capacity in the following areas:

1: Security
2: Performance
3: Interface complexity

EDIT: Looking at some of the answers to this question - I should clarify. I'm not looking for a comparison to SOAP - rather an overview of REST applications vs applications where all components reside on one host. (thanks for those answers though!)

答:
The WS-* standards really are mostly about running RPC over SOAP/HTTP. So, all the thinking that went into CORBA and J2EE and their predecessors have mostly moved to doing the same sort of things in XML. This means things like type declarations and service contracts, metadata exchange, declarative security etc. All that real "enterprisey" stuff. Its over-used even in the enterprise, frankly.

People building an internet web application such as yourself, would almost certainly be better off using a RESTful architecture. Almost any platform can consume it and do so simply and without worrying about which version of which spec you are using and a myriad of tool-specific type conversion quirks etc.

Title: Pros and Cons of RESTful architecture


问:
Abstraction concept in OOP
I hear that Abstraction is a technique that helps us identify which specific information should be visible, and which information should be hidden.
Encapsulation is then the technique for packaging the information in such a way as to hide what should be hidden, and make visible what is intended to be visible.

I understand Encapsulation well... A simple example would be a Method that calculates calories based on the parameters we provide. CalculateCalories(x,y,z) Here I don't know how this method calculates calories but I can call it to calculate the calories.

Abstraction is what I am confused about. What are those techniques that Abstraction uses to help identify which specific information should be visible, and which information should be hidden? Or am I misunderstanding the concept?

Could anyone give an intuitive example?

答:
In functional programming, there is a concept called Map.  Map is a higher-order function that applies a function to each element in a list.

In ordinary code, you would do something like:

```<code>var list = new List<int> { 1,2,3,4,5,6 };

var newList = new List<int>();

foreach(var item in list)
{
    newList.Add(item * 2);
}

// newList --> { 2,4,6,8,10,12 }
</code>```

Rather than writing a loop each time, you create a Map method:

```<code>public List<T> Map<T>(this List<T> list, Func<T,TResult> function)
{
    var newList = new List<T>()

    foreach(T item in enumeration)
    {
        newList.Add(function(item));
    }

    return newList;
}
</code>```

Now, instead of writing a loop each time, you can simply write:

```<code>var list = new List<int>() { 1,2,3,4,5,6 };

var modifiedList = Map(list, x => x * 2); // { 2,4,6,8,10,12 }
</code>```

and get the same result.

The Map method is an abstraction over writing a loop to modify each member of a list.

I haven't mentioned it yet, but the <T> syntax is also an abstraction.  It's called generics; it means that you can write a function that can operate on different data types, instead of writing functions for each data type.

All abstraction is a form of generalization: writing code that applies to more than one specific situation.

Title: Abstraction concept in OOP

Body:
In functional programming, there is a concept called Map.  Map is a higher-order function that applies a function to each element in a list.

In ordinary code, you would do something like:

var list = new List<int> { 1,2,3,4,5,6 };

var newList = new List<int>();

foreach(var item in list)
{
    newList.Add(item * 2);
}

// newList --> { 2,4,6,8,10,12 }

Rather than writing a loop each time, you create a Map method:

public List<T> Map<T>(this List<T> list, Func<T,TResult> function)
{
    var newList = new List<T>()

    foreach(T item in enumeration)
    {
        newList.Add(function(item));
    }

    return newList;
}

Now, instead of writing a loop each time, you can simply write:

var list = new List<int>() { 1,2,3,4,5,6 };

var modifiedList = Map(list, x => x * 2); // { 2,4,6,8,10,12 }

and get the same result.

The Map method is an abstraction over writing a loop to modify each member of a list.

I haven't mentioned it yet, but the <T> syntax is also an abstraction.  It's called generics; it means that you can write a function that can operate on different data types, instead of writing functions for each data type.

All abstraction is a form of generalization: writing code that applies to more than one specific situation.


问:
Segregating interfaces/concerns to a tree
When working with a single object there are a number of ways to segregate interfaces to it.

Breaking it into smaller components that can be treated independently.

Breaking it into simpler interfaces.

Both of these seem challenging to do with a tree. I think it would be nice to be able to do the following.

```<code>class Node : INodeData, INodePresentation { ... }

class Program
{
    static void Main()
    {
        var node = new Node();
        ManipulateNode(node);
        PresentNode(node);
    }

    void ManipulateNode(INodeData nodeData)
    {
        foreach (INodeData child in nodeData.GetChildren())
             nodeData.AddVertices(...);
        nodeData.Rotate(...);
    }

    void PresentNode(INodePresentation nodePresentation)
    {
        nodePresentation.Color = Color.Blue;
        nodePresentation.Size = 15;
        nodePresentation.Paint();
        foreach (INodePresentation child in nodePresentation.GetChildren())
            PresentNode(child);
    }
}
</code>```

In this way different parts of the program could use the node according to a concise interface. But each interface I add will require more methods in the Node class which could be unmaintainable. It seems like the presentation and data should be defined in separate classes, but I can't think of a good way to do this while maintaining the ability to traverse the tree. Any suggestions?

答:
It seems like the presentation and data should be defined in separate classes, but I can't think of a good way to do this while maintaining the ability to traverse the tree. Any suggestions?

The thing about interfaces is that you have to know them all up front. If you want to add new interfaces, you'll need to use the Decorator pattern. But I think maybe you should re-evaluate your approach. Do you really need an interface for every new node manipulation? You can just add a function/static method that takes the tree as an argument and does whatever manipulation you need.


问:
Is hierarchical product backlog a good idea in TFS 2012-2013?
I'd like to validate I'm not in the wrong way.

My team project is using Visual Studio Scrum 2.x. Since each area/product has a lot of kind of requirements (security, user interface, HTTP/REST services...), I tried to manage this creating "parent backlogs" which are "open forever" and they contain generic requirements.

Those parent backlogs have other "open forever" backlogs, and/or sprint backlogs.

For example:

HTTP/REST Services (forever)

Profiles API (forever)
*POST profile (forever)

We need a basic HTTP/REST profiles' API to register new user profiles (sprint backlog)

Is it the right way of organizing the product backlog?

Note: I know there're different points of view and that would be right for some and wrong for others. I'm looking for validation about if this is a possible good practice on TFS with Visual Studio Scrum.

答:
The idea of having a "bucket" backlog is something my organization started with but moved away from.  We resolved this problem by moving to Area Paths by module.  For example, we have a Web Services, Web Interface, and Data Access area path for one of our team projects. </p>

<p>You could also consider using TFS 2013's Initiative and Feature work items, but as far as I know those are intended to be finite work items as well. </p>

Body:
The idea of having a "bucket" backlog is something my organization started with but moved away from.  We resolved this problem by moving to Area Paths by module.  For example, we have a Web Services, Web Interface, and Data Access area path for one of our team projects.

You could also consider using TFS 2013's Initiative and Feature work items, but as far as I know those are intended to be finite work items as well.


问:
Python sorted iterable set, modifiable during iteration
I am looking for a datastructure to handle cycling through a large number of ordered subroutines, some of which are active, most of which are not.

I am thinking I need an implementation of a python set like object which remains ordered when modified, can be easily iterated over (I don't care if an actual for loop works, as long as there is a simple and efficient way to read each element in order). And most notably can be modified while being iterated over.

This is to allow an implementation of a very specific form of subroutine program (unfortunately I cannot use the built in subroutine modules as my python program is emulating the behaviour of a legacy system precisely so I need finer control.)

Effectively I have a list of subroutines which are referenced by an index number in a dictionary, the subroutines are iterated over in ascending order until the last is reached at which point we return to the lowest number one. However there are a large number of subroutines and only a few at any time will be 'active' and ones which are not active are skipped in the order for running. I considered simply giving each routine an active flag which would be tested before running however the enormous number of potential routines compared to the tiny number of active ones makes this method much to slow. Subroutines are only occasionally activated or deactivated but running them must be very fast. As such I have been looking to keep a list of the keys of the active ones and iterate through that, adding or removing them as they are activated or deactivated but am looking for a reasonably efficient way of maintaining this list.

The main two systems which seem feasible to me are blist sorted sets, however I am not sure if they support being modified while iterated over, and using two heapq and shifting the items between them in order, this will definitely support modification at any time but would require a lot more manual work, and would probably be slower.

However somebody may have a much better answer than either of those so I will appreciate any ideas on how to achieve this with reasonable efficiency and ideally in a 'pythonic' way, though I can deal with it being a little ugly if it does the job.

答:
There's a new Python module called sortedcontainers that would meet your needs. It's designed as a nearly drop-in replacement for blist but is pure-Python and faster in most cases. The built-in iteration support is extremely fast but doesn't allow modifying elements. Instead, I would use the built-in indexing which is also fast.

Something like this:

```<code>from sortedcontainers import SortedSet
ss = SortedSet(...)
pos = 0
while pos < len(ss):
    item = ss[pos]

    # ... do something with item ...
    # ... possibly insert or delete items ...

    pos += 1
</code>```

You'll need to decide what happens if you insert an item such that pos += 1 winds up referencing the same item on successive iterations.

You could also queue the insertions/deletions until after iterating the sorted set.

Disclaimer: I am the author of the sortedcontainers module.

OwnerDisplayName: Vality

Body:
There's a new Python module called sortedcontainers that would meet your needs. It's designed as a nearly drop-in replacement for blist but is pure-Python and faster in most cases. The built-in iteration support is extremely fast but doesn't allow modifying elements. Instead, I would use the built-in indexing which is also fast.

Something like this:

from sortedcontainers import SortedSet
ss = SortedSet(...)
pos = 0
while pos < len(ss):
    item = ss[pos]

    # ... do something with item ...
    # ... possibly insert or delete items ...

    pos += 1

You'll need to decide what happens if you insert an item such that pos += 1 winds up referencing the same item on successive iterations.

You could also queue the insertions/deletions until after iterating the sorted set.

Disclaimer: I am the author of the sortedcontainers module.


答:
I hear that Abstraction is a technique that helps us identify which specific information should be visible, and which information should be hidden.

Wrong. Thats still part of encapsulation.

Abstraction is when you have multiple interchangeable behaviors that are manipulated through common interface. The multiple thing is the most important thing. In OOP, abstractions are primarily achieved through inheritance with virtual methods or interfaces and their realization.

Title: Abstraction concept in OOP

Body:
I hear that Abstraction is a technique that helps us identify which specific information should be visible, and which information should be hidden.
Encapsulation is then the technique for packaging the information in such a way as to hide what should be hidden, and make visible what is intended to be visible.

I understand Encapsulation well... A simple example would be a Method that calculates calories based on the parameters we provide. CalculateCalories(x,y,z) Here I don't know how this method calculates calories but I can call it to calculate the calories.

Abstraction is what I am confused about. What are those techniques that Abstraction uses to help identify which specific information should be visible, and which information should be hidden? Or am I misunderstanding the concept?

Could anyone give an intuitive example?


答: Only big advantage of SOAP over the current REST implementations is that SOAP is more easily tooled -- most RESTful clients require me to understand the interface and write a client of some sort. For SOAP, I just point wsdl.exe at it and it generates classes for me.</p>

Title: Pros and Cons of RESTful architecture

Body:
The most common discussion I've seen regarding the pros and cons of REST tends to frame that discussion relative to SOAP. I have no experience in either. I am currently faced with a decision which my lack of experience is making hard for me to evaluate.
I am beginning to develop an application that has several components - primarily an administrative aspect that allows the owner to administer several sites - and a public facing user interface that allows the user to interact with data held on the host.
I need to evaluate the implications of allowing the latter part to be hosted anywhere and communicate with the former via a RESTful architecture - or demanding that both components reside on the same host.
What are the key implications of developing RESTful architecture, particularly with regards to it's capacity in the following areas:

1: Security
2: Performance
3: Interface complexity

EDIT: Looking at some of the answers to this question - I should clarify. I'm not looking for a comparison to SOAP - rather an overview of REST applications vs applications where all components reside on one host. (thanks for those answers though!)


问:
Why is "Select * from table" considered bad practice
Yesterday I was discussing with a "hobby" programmer (I myself am a professional programmer). We came across some of his work, and he said he always queries all columns in his database (even on/in production server/code).

I tried to convince him not to do so, but wasn't so successful yet. In my opinion a programmer should only query what is actually needed for the sake of "prettiness", efficiency and traffic. Am I mistaken with my view?

答:
IMO, its about being explicit vs implicit.  When I write code, I want it to work because I made it work, not just because all of the parts just happen to be there.  If you query all records and your code works, then you'll have the tendency to move on.  Later on if something changes and now your code doesn't work, its a royal pain to debug lots of queries and functions looking for a value that should be there and the only values reference are *.

Also in an N-tiered approach, its still best to isolate database schema disruptions to the data tier.  If your data tier is passing * to the business logic and most likely on the the presentation tier, you are expanding your debugging scope exponentially.


答: Think of it this way...  if you query all columns from a table that has just a few small string or numeric fields, that total 100k of data.  Bad practice, but it will perform.  Now add a single field that holds, say, an image or a 10mb word document.  now your fast performing query immediately and mysteriously start performing poorly, just because a field was added to the table... you may not need that huge data element, but because you've done Select * from Table you get it anyway.

Title: Why is "Select * from table" considered bad practice

Body:
Yesterday I was discussing with a "hobby" programmer (I myself am a professional programmer). We came across some of his work, and he said he always queries all columns in his database (even on/in production server/code).

I tried to convince him not to do so, but wasn't so successful yet. In my opinion a programmer should only query what is actually needed for the sake of "prettiness", efficiency and traffic. Am I mistaken with my view?


问:
What is "train" based development?
I ran across yet another new term in development methodology, and I haven't been able to find a definition for it.  Specifically, it's called "train based development."

Here are some examples of where I have seen this term.

Earlier this week, I asked our engineering leads and release managers to take the Windows Metro version of Firefox off the trains. (Johnathan Nightingale)

https://blog.mozilla.org/futurereleases/2014/03/14/metro/

From the Mozilla careers web-site:

Experience working with both agile development methodology, and train-based development/QA teams.

I have heard of "train" before and not just in the context of Mozilla.  But I haven't managed to find any good information about it on the net.

When I googled "train based software development", I found very little information in the search results. The closest that I could dig out that separates the train from the wagons is that "train" is about making releases at regular intervals according to a schedule.  But it also seems that "train" is a sort of concrete QA setup.

So, what is "train based development"?

答:
Summing up information from this blog :

The analogy is trains are releases, passengers are features

Trains are planned at regular intervals, without knowing what they will contain

If features aren't ready for departure train, they can go on the next one

Once a version is shipped, the development splits between support/patching shipped code and developing the next train

This development is mostly aimed at large client softwares, rich in features, and broadly distributed such as a web browser or an OS, where old versions may stay active for a long time.

Title: What is "train" based development?


答:
Probably the most common way is to create a Node<T> with just the structure stuff and pass that into other functions that can use a T to do the presentation stuff.

If you're having difficulty inverting control when doing a recursive traversal, try passing a function into a traversal method, something like (forgive syntax as I don't know C#):

```<code>void DepthFirstTraversal(Node<T> node, Function func)
{
    func(node);
    foreach (Node<T> child in node.GetChildren())
        DepthFirstTraversal(child, func);
}
</code>```

Another useful method to add functionality to a class, but somewhat less familiar depending on what languages you know, is using a mixin.  It may or may not be useful in your case.

You can implement mixins in C# 3.0 using extension methods, and I believe there are third-party libraries to help.  Mixins basically let you add functionality to a class without requiring it to implement an interface.  The implementation is mixed in with the existing implementation of the class.

Title: Segregating interfaces/concerns to a tree

Body:
When working with a single object there are a number of ways to segregate interfaces to it.

Breaking it into smaller components that can be treated independently.

Breaking it into simpler interfaces.

Both of these seem challenging to do with a tree. I think it would be nice to be able to do the following.

```<code>class Node : INodeData, INodePresentation { ... }

class Program
{
    static void Main()
    {
        var node = new Node();
        ManipulateNode(node);
        PresentNode(node);
    }

    void ManipulateNode(INodeData nodeData)
    {
        foreach (INodeData child in nodeData.GetChildren())
             nodeData.AddVertices(...);
        nodeData.Rotate(...);
    }

    void PresentNode(INodePresentation nodePresentation)
    {
        nodePresentation.Color = Color.Blue;
        nodePresentation.Size = 15;
        nodePresentation.Paint();
        foreach (INodePresentation child in nodePresentation.GetChildren())
            PresentNode(child);
    }
}
</code>```

In this way different parts of the program could use the node according to a concise interface. But each interface I add will require more methods in the Node class which could be unmaintainable. It seems like the presentation and data should be defined in separate classes, but I can't think of a good way to do this while maintaining the ability to traverse the tree. Any suggestions?

Body:
Probably the most common way is to create a Node<T> with just the structure stuff and pass that into other functions that can use a T to do the presentation stuff.

If you're having difficulty inverting control when doing a recursive traversal, try passing a function into a traversal method, something like (forgive syntax as I don't know C#):

void DepthFirstTraversal(Node<T> node, Function func)
{
    func(node);
    foreach (Node<T> child in node.GetChildren())
        DepthFirstTraversal(child, func);
}

Another useful method to add functionality to a class, but somewhat less familiar depending on what languages you know, is using a mixin.  It may or may not be useful in your case.

You can implement mixins in C# 3.0 using extension methods, and I believe there are third-party libraries to help.  Mixins basically let you add functionality to a class without requiring it to implement an interface.  The implementation is mixed in with the existing implementation of the class.


答:
In layman's words:

Writing a solution with OOP is like creating a model of the problem, making the problem look easier, thus allowing to write good enough solutions.

But we don't need to model the whole thing down to the most minute details, because the model would be as complex as the problem itself. That would be like creating a map with a scale of 1:1. Such a map would be as big as the real thing.

We create a simplified model with the things that are crucial to the solution. Abstracting ourselves from the minutiae, not unlike a vehicle's suspension abstracts the driver from the unevenness of the road.

That's called generalization, or abstracion.

When you really need to make something very specific you do the opposite: you get the general solution and built on it. That's called specialization.

Don't write code that sorts an array of people's names.

Write code that sorts an array of strings. That is generic enough to sort people names, country names and animals scientific names.

Concrete-man (fictional character) would have written diffent sorting methods that do almost the same.

Abstraction usually takes place on a whiteboard, a napkin or the mind of the designer.

When you write the code the abstraction process already happened.

Abstraction is the process of deciding what classes have in common.

Most of the time it doesn't even have to do with code.

Title: Abstraction concept in OOP


问:
Sprite Sheets in PyGame?
So, I've been doing some googling, and haven't found a good solution to my problem. My problem is that I'm using PyGame, and I want to use a Sprite Sheet for my player.

This is all well and good, and it would be too, if I wasn't using a Sprite Sheet strip. Basically, if you don't understand, I have a strip of 32x32 'frames'. These frames are all in an image, along side each other. So, I have 3 frames in 1 image. I'd like to be able to use them as my sprite sheet, and not have to crop them up.

I have used an awesome, popular and easy-to-use game framework for Lua called LÖVE. LÖVE has these things called "Quads". They are similar to texture regions in LibGDX, if you know what they are. Basically, quads allow you to get parts of an image. You define how large a quad is, and you define parts of an image that way, or 'regions' of an image.

I would like to do something similar to this in PyGame, and use a "for" loop to go through the entire image width and height and mark each 32x32 area (or whatever the user defines as their desired frame width and height) and store that in a list or something for use later on. I'd define an animation speed and stuff, but that's for later on.

I've been looking around on the web, and I can't find anything that will do this. I found 1 script on the PyGame website, but it crashed PyGame when I tried to run it. I tried for hours trying to fix it, but no luck. So, is there a way to do this? Is there a way to get regions of an image? Am I going about this the wrong way? Is there a simpler way to do this?

Thanks! :-)

答:
Since you are obviously programming your game in Python, you can use the Pillow module (doc/tutorial here) to use sprite strips (or grids, as is common practice) exactly as you describe.

Specifically, check the section about cutting, pasting, and merging images.

You can open your sprite strip image file

strip = Image.open("sprites")

then crop it to retrieve the Nth sprite (assuming 32x32 size, starting at 0) with

sprite = strip.crop( (N*32, 0, 32, 32) )

Of course the sprite strip image remains intact -- crop() only extracts a copy of the specified region. (It is the paste() function allows modifying the original, by pasting into a region precisely.)

If you want an array of sprites (a list, strictly speaking) then you can do something like

[strip.crop( (N*32, 0, 32, 32) ) for n in range(nb_of_sprites)]

Pretty easy, isn't it?

Title: Sprite Sheets in PyGame?


问:
Python - Is this a bad strategy pattern?
I've got a Python project wherein a basic object is created and various different attributes are modified/given to it via what I thought was a good example of a strategy pattern.

In this silly game there are enemies with multiple different potential patterns of movement. The Enemy class has a basic pattern of movement it defaults to; otherwise, a strategy pattern is implemented to randomly choose different ones as the game progresses.

The Enemy's obj.update() is something like this:

```<code>def update(self):
    self.unique_action()
    self.check_if_shooting()
    self.find_new_rect()
</code>```

So I'd been replacing self.unique_action on the fly with a strategy pattern using what I think are called 'higher-order functions'.

```<code>def new_pattern_of_movement(obj, func):
    def inner(*args, **kwargs):
        ##code for doing different stuff
        ##intentionally NOT returning the function -
        ##the idea is to replace the default unique_action
    return inner

…
##eventually when generating bad guys for the level…
newEnemy = Enemy()
new_AI = random.choice([new_pattern_of_movement, other_pattern, some_other_pattern]) #etc etc
newEnemy.unique_action = new_AI(newEnemy, newEnemy.unique_action)
</code>```

After a while, I thought, "self, why not change their attributes as part of the wrapper as well? you change their methods, just set their point_value and graphics and all that dumb stuff too" and I was like "welp I can do that"

```<code>def alt_action(obj):
    def inner(*args, **kwargs):
        ##code for their unique_action
        ##again, not returning obj.unique_action
    obj.point_value += 100
    obj.color = colors.YELLOW
    obj.speed -= 1
    return inner
</code>```

Evidently, this is regarded as "very JavaScript-y". I find it terribly simple though, and preferable to stringing along a bunch of objects that inherit from a long chain of ancestors.

My job isn't on the line or anything here, but in such a situation is it really that critical to split these up into separate classes? The first example, at the least, seems fine because it really is just replacing one method with another, but in the second example, I'm definitely redefining object attributes, and I go a bit further than depicted here (replacing the object's self.draw() methods and that if it's necessary).

It might be bad, but it's so stupidly easy.

Is this a good example of how not to implement a strategy pattern?

答:
Does enemy change their behavior post-initialisation ? If not, then your objects are inheriting from a base class, and you shouldn't implement inheritance with a strategy pattern, for several reasons :

Code readability. When you move function pointers around, execution path made less clear. How to know which function will be indeed called, given an instance ?

Initialization logic re-use. If you intend to call overriding logic every time you call Enemy(), there is a problem

Performance, although this doesn't matter much

Also, I personally I hope I never have to maintain code that would contain similar patterns than alt_action. Calculating an attribute from a base value is pushing code obscurity and instability to a whole new level, because now, not only correct initialization isn't guaranteed, but it's not even idempotent (e.g. initializing twice doesn't make it initialized correctly...).

In my opinion, you think too much about coding to do the job, while your code is much more than that. Code describe a structure of how things are and interact with each other. Code is also meant to be read and changed more than once. It should make you inclined to choose simple solutions with well-established conventions, over what you find easy.


问:
Neural network input preprocessing
It's clear that the effectiveness of a neural network depends strongly on the format you give it to work with.  You want to pre-process it into the most convenient form you can algorithmically get to, so that the neural network doesn't have to account for that itself.

I'm working on a little project that is going to be using neural networks.  My future goal is to eventually use NEAT, which I'm really excited about.  Anyway, one of my ideas involves moving entities in continuous 2D space, from a top-down perspective (this would be a really cool game AI).  Of course, unless these guys are blind, they're going to be able to see the world around them.

There's a lot of different ways this information could be fed into the network.  One interesting but expensive way is to simply render a top-down "view" of things, with the entities as dots on the picture, and feed that in.  I was hoping for something much simpler to use (at least at first), such as a list of the x (maybe 7 or so) nearest entities and their position in relative polar coordinates, orientation, health, etc., but I'm trying to think of the best way to do it.

My first instinct was to order them by distance, which would inherently also train the neural network to consider those more "important".  However, I was thinking- what if there's two entities that are nearly the same distance away? They could easily alternate indexes in that list, confusing the network.

My question is, is there a better way of representing this?  Essentially, the issue is the network needs a good way of keeping track of who's who, while knowing (by being input) relevant information about the list of entities it can see.

Thanks!

答:
Unless I misunderstand the problem (which could be stated more clearly IMO), you absolutely do not want to order entities by distance. It is critical that each input to the neural network denotes the same physical entity throughout - or else nothing will make sense.

You need to specify your problem more precisely, and devise your network inputs accordingly. For instance, if your game agents are tracking N objects and can sense 4 parameters for each (e.g., the position, x-y, orientation, a, and health, h) then each neural network will have exactly 4N inputs. It does not matter in which order you feed these into a network, so long as the order remains the same! (The implicit ordering is what defines "who is who".)

If, on the other hand, the agents are only equipped with M distance sensors - so they know about the environment but cannot track other entities explicitly - (which is a more realistic scenario anyway) then the measured distances will be the M distance inputs. (In that case though it is impossible to know "who is who".)

Another issue is, how are you going to train the network? I assume supervised learning, which means you need to provide training data where the desired network output is provided for specific input values. For instance you might want to train the game agent to avoid collisions by teaching it to move away from other objects...

Title: Neural network input preprocessing


问:
Why do concurrent languages tend to have more complicated syntax?
This is a question that's been on my mind for a while.
Recently I've been checking out concurrent languages like Haskell or Go or Erlang.

From my point of view, they have huge benefit in performance as opposed to languages like C++ or Python because of the way they handle functions in parallel.

My question is: Why is the syntax for languages like C++ or Python so much different (and IMO simpler) from those of concurrent languages, even though most concurrent languages are executed on runtime (and therefore they have more possibility in simplifying the syntax)?

Here is an example, consider Go's sqrt:

```<code>// Package newmath is a trivial example package.
package newmath

// Sqrt returns an approximation to the square root of x.
func Sqrt(x float64) float64 {
    z := 1.0
    for i := 0; i < 1000; i++ {
        z -= (z*z - x) / (2 * z)
    }
    return z
}
</code>```

Now for the Python counterpart (ported this myself based on the Sqrt example from Go):

```<code>def Sqrt(x):
 z = 1.0
 for i in Range(0, 1000):
  z -= (z*z-x/2*z)
  return z
</code>```

Now as you can see go has a syntax like ":=" for assignment,
If you take a more complicated examples, the syntax will look more like what I am trying to point out.

And Go is just the least "weird-looking" language.
If you consider Erlang it's looking even weirder:

```<code>%% qsort:qsort(List)
%% Sort a list of items
-module(qsort).     % This is the file 'qsort.erl'
-export([qsort/1]). % A function 'qsort' with 1 parameter is exported (no type, no name)

qsort([]) -> []; % If the list [] is empty, return an empty list (nothing to sort)
qsort([Pivot|Rest]) ->
    % Compose recursively a list with 'Front' for all elements that should be before 'Pivot'
    % then 'Pivot' then 'Back' for all elements that should be after 'Pivot'
    qsort([Front || Front <- Rest, Front < Pivot])
    ++ [Pivot] ++
    qsort([Back || Back <- Rest, Back >= Pivot]).
</code>```

Parts that caught my eye were "++ [] ++", '<-' and '->'

I am convinced these languages look like this for a reason, but I can't help but think: Can't it be simpler? Why are concurrent languages like this? Why if they use a runtime like Python and JavaScript, are they still type-safe?

I know type-safe languages have an advantage of their own to not mix up variable types, but still, there's gotta be somebody who made a concurrent language that didn't have type-safety, if possible right?

It seems like almost all concurrent languages have one thing in common: a bigger list of possible / valid syntax.

I hope I've explained my question well enough.

答:
It sounds like your observations about syntax are merely preferences, so let me make some observations of my own.

First of all, let me state equivocally that syntax does matter.  The simplest syntax of all is Lisp:

```<code>(defun fib (n)
  (if (< n 2)
    n
    (+ (fib (- n 1)) (fib (- n 2)))))
</code>```

Because code is essentially data in Lisp, lisp can understand code written in lisp, which makes writing a parser for Lisp in Lisp (or in any other language, for that matter) an almost trivial exercise.  Lisp is widely regarded as a language where problems can be solved from the ground-up, in problem domains that would ordinarily be resistant to coding solutions (especially in domains where requirements are constantly changing).  Lisp is a very expressive language, and at the end of the day, syntax is the way we express ourselves in a language.  It is not, however, regarded as the most readable of languages (all those parentheses).

Programmers typically fall into one of two camps, syntax-wise: those that prefer a more English-like code representation, and those that prefer a more symbolic, mathematic-style code representation.  The syntax of the language itself will be shaped, in large part, by the goals of the language.

For example, C is basically a high-level assembly language.  It uses the syntax that it does, in large part, because it maps well to underlying assembly instructions.  It has no need for lofty concepts like natural-language translation, preferring to map closer to the metal.  Many languages that came after C adopted the brace structure and other syntax idiosyncracies because C had already done it.  C is in the "symbolic" camp.

```<code>unsigned int fib_rec(unsigned int n) {
    if (n == 0) {
        return 0;
    }
    if (n == 1) {
        return 1;
    }
    return fib_rec(n - 1) + fib_rec(n - 2);
}
</code>```

Some languages, however, like Python, prefer to work at higher levels of abstraction and seek to be closer to the language used by humans.  These languages will prefer things like significant whitespace, because it produces less clutter between the words than braces. Python is in the "English-like" camp.

```<code>def F(n):
    if n == 0: return 0
    elif n == 1: return 1
    else: return F(n-1)+F(n-2)
</code>```

I was a Visual Basic programmer for years, and so was in the English-like camp, until I learned C#.  I now prefer the better precision and less ambiguity that C# offers; I think in terms of what I need the computer to do, and C# seems to maps more closely to that.  I like the fact that you can line up blocks of code in braces.  I like that certain things are expressed more succinctly in C#.  But the capabilities of VB.NET and C# are nearly identical, so the choice between those two languages really does come down to personal preference.

Body:
It sounds like your observations about syntax are merely preferences, so let me make some observations of my own.

First of all, let me state equivocally that syntax does matter.  The simplest syntax of all is Lisp:

(defun fib (n)
  (if (< n 2)
    n
    (+ (fib (- n 1)) (fib (- n 2)))))

Because code is essentially data in Lisp, lisp can understand code written in lisp, which makes writing a parser for Lisp in Lisp (or in any other language, for that matter) an almost trivial exercise.  Lisp is widely regarded as a language where problems can be solved from the ground-up, in problem domains that would ordinarily be resistant to coding solutions (especially in domains where requirements are constantly changing).  Lisp is a very expressive language, and at the end of the day, syntax is the way we express ourselves in a language.  It is not, however, regarded as the most readable of languages (all those parentheses).

Programmers typically fall into one of two camps, syntax-wise: those that prefer a more English-like code representation, and those that prefer a more symbolic, mathematic-style code representation.  The syntax of the language itself will be shaped, in large part, by the goals of the language.

For example, C is basically a high-level assembly language.  It uses the syntax that it does, in large part, because it maps well to underlying assembly instructions.  It has no need for lofty concepts like natural-language translation, preferring to map closer to the metal.  Many languages that came after C adopted the brace structure and other syntax idiosyncracies because C had already done it.  C is in the "symbolic" camp.

unsigned int fib_rec(unsigned int n) {
    if (n == 0) {
        return 0;
    }
    if (n == 1) {
        return 1;
    }
    return fib_rec(n - 1) + fib_rec(n - 2);
}

Some languages, however, like Python, prefer to work at higher levels of abstraction and seek to be closer to the language used by humans.  These languages will prefer things like significant whitespace, because it produces less clutter between the words than braces. Python is in the "English-like" camp.

def F(n):
    if n == 0: return 0
    elif n == 1: return 1
    else: return F(n-1)+F(n-2)

I was a Visual Basic programmer for years, and so was in the English-like camp, until I learned C#.  I now prefer the better precision and less ambiguity that C# offers; I think in terms of what I need the computer to do, and C# seems to maps more closely to that.  I like the fact that you can line up blocks of code in braces.  I like that certain things are expressed more succinctly in C#.  But the capabilities of VB.NET and C# are nearly identical, so the choice between those two languages really does come down to personal preference.


答:
You're a little confused about terminology and what factors are relevant, as people mentioned in the comments.  Let me just address the syntax of Erlang, which is a functional language.

It has more operators because it does more.  It needs a ++ because it was already using + for something else.  It uses ++ instead of a word like concat because the language was intended to favor conciseness.  For example, the code:

```<code>[Front || Front <- Rest, Front < Pivot]
</code>```

Requires the following code in C++ (copied from here):

int partition(int* input, int p, int r)
{
    int pivot = input[r];

    while ( p < r )
    {
        while ( input[p] < pivot )
            p++;

        while ( input[r] > pivot )
            r--;

        if ( input[p] == input[r] )
            p++;
        else if ( p < r )
        {
            int tmp = input[p];
            input[p] = input[r];
            input[r] = tmp;
        }
    }

    return r;
}
```

<p>Although the same code in python using list comprehensions is just barely longer:</p>

<pre class="lang-py prettyprint-override"><code>[front for front in rest if front < pivot]
</code>```

Because of immutability and lack of side effects in functional programming, certain methods of processing lists have been adopted which make it easier.  This includes pattern matching and destructuring.  You might want to do some research on those, but my point is in order to gain the expressiveness and conciseness that things like pattern matching provide, you have to accept more complexity in your syntax.

Also keep in mind that C++ and python seem more natural largely because you learned them first.  If you had learned erlang first, then C++ and python's syntax would seem limiting and excessively verbose.

Title: Why do concurrent languages tend to have more complicated syntax?

Body:
This is a question that's been on my mind for a while.
Recently I've been checking out concurrent languages like Haskell or Go or Erlang.

From my point of view, they have huge benefit in performance as opposed to languages like C++ or Python because of the way they handle functions in parallel.

My question is: Why is the syntax for languages like C++ or Python so much different (and IMO simpler) from those of concurrent languages, even though most concurrent languages are executed on runtime (and therefore they have more possibility in simplifying the syntax)?

Here is an example, consider Go's sqrt:

```<code>// Package newmath is a trivial example package.
package newmath

// Sqrt returns an approximation to the square root of x.
func Sqrt(x float64) float64 {
    z := 1.0
    for i := 0; i < 1000; i++ {
        z -= (z*z - x) / (2 * z)
    }
    return z
}
</code>```

Now for the Python counterpart (ported this myself based on the Sqrt example from Go):

```<code>def Sqrt(x):
 z = 1.0
 for i in Range(0, 1000):
  z -= (z*z-x/2*z)
  return z
</code>```

Now as you can see go has a syntax like ":=" for assignment,
If you take a more complicated examples, the syntax will look more like what I am trying to point out.

And Go is just the least "weird-looking" language.
If you consider Erlang it's looking even weirder:

```<code>%% qsort:qsort(List)
%% Sort a list of items
-module(qsort).     % This is the file 'qsort.erl'
-export([qsort/1]). % A function 'qsort' with 1 parameter is exported (no type, no name)

qsort([]) -> []; % If the list [] is empty, return an empty list (nothing to sort)
qsort([Pivot|Rest]) ->
    % Compose recursively a list with 'Front' for all elements that should be before 'Pivot'
    % then 'Pivot' then 'Back' for all elements that should be after 'Pivot'
    qsort([Front || Front <- Rest, Front < Pivot])
    ++ [Pivot] ++
    qsort([Back || Back <- Rest, Back >= Pivot]).
</code>```

Parts that caught my eye were "++ [] ++", '<-' and '->'

I am convinced these languages look like this for a reason, but I can't help but think: Can't it be simpler? Why are concurrent languages like this? Why if they use a runtime like Python and JavaScript, are they still type-safe?

I know type-safe languages have an advantage of their own to not mix up variable types, but still, there's gotta be somebody who made a concurrent language that didn't have type-safety, if possible right?

It seems like almost all concurrent languages have one thing in common: a bigger list of possible / valid syntax.

I hope I've explained my question well enough.

Body:
You're a little confused about terminology and what factors are relevant, as people mentioned in the comments.  Let me just address the syntax of Erlang, which is a functional language.

It has more operators because it does more.  It needs a ++ because it was already using + for something else.  It uses ++ instead of a word like concat because the language was intended to favor conciseness.  For example, the code:

[Front || Front <- Rest, Front < Pivot]

Requires the following code in C++ (copied from here):

int partition(int* input, int p, int r)
{
    int pivot = input[r];

    while ( p < r )
    {
        while ( input[p] < pivot )
            p++;

        while ( input[r] > pivot )
            r--;

        if ( input[p] == input[r] )
            p++;
        else if ( p < r )
        {
            int tmp = input[p];
            input[p] = input[r];
            input[r] = tmp;
        }
    }

    return r;
}

Although the same code in python using list comprehensions is just barely longer:

[front for front in rest if front < pivot]

Because of immutability and lack of side effects in functional programming, certain methods of processing lists have been adopted which make it easier.  This includes pattern matching and destructuring.  You might want to do some research on those, but my point is in order to gain the expressiveness and conciseness that things like pattern matching provide, you have to accept more complexity in your syntax.

Also keep in mind that C++ and python seem more natural largely because you learned them first.  If you had learned erlang first, then C++ and python's syntax would seem limiting and excessively verbose.


问:
Dealing with co-workers who do not have a consistent coding style?
What do you when you're working with someone who tends to write stylistically bad code? The code I'm talking about is usually technically correct, reasonably structured, and may even be algorithmically elegant, but it just looks ugly. We've got:

Mixture of different naming conventions and titles (underscore_style and camelCase and UpperCamel and CAPS all applied more or less at random to different variables in the same function)

Bizarre and inconsistent spacing, e.g. Functioncall  (arg1 ,arg2,arg3 );

Lots of misspelled words in comments and variable names

We have a good code review system where I work, so we do get to look over and fix the worst stuff. However, it feels really petty to send a code review that consists of 50 lines of "Add a space here. Spell 'itarator' correctly. Change this capitalization. etc."

How would you encourage this person to be more careful and consistent with these kinds of details?

答:
We have a good code review system
  where I work, so we do get to look
  over and fix the worst stuff. However,
  it feels really petty to send a code
  review that consists of 50 lines of
  "Add a space here. Spell 'itarator'
  correctly. Change this capitalization.
  etc."

I'd change it myself and then add a polite comment in the code.

this assumes that there is already a style guide as the question stated :

We have a good code review system

So my suggestion is a last resort, I figure its just as quick to change it yourself and leave a comment, as it is to send an e-mail or whatever.


问:
Backing up messages in S3 within a Storm topology
In my project we are trying to build up a KIND-of-a-lambda storm based architecture. The component would be responsible for indexing the site usage events so we expect a quite massive random load. The solution for real-time processing of the messages seems fine, but in parallel to the "speed layer" we want to back up the messages in a raw form (just as they are coming down from the queue) in Amazon S3. Since writing a file per message is obviously out of the question, we need to somehow buffer/aggregate the messages before posting to S3 - and here is where the problems begin. We have two concurrent approaches and none seems perfect:

We used Redis as a buffer. Basically messages coming down from a queue (RabbitMQ) are buffered in Redis and once some preconfigured batch size (say 1000) is reached the buffer is flushed and stored to S3. The whole message proccesing cycle is not transactional. Once message is stored to Redis it is acknowledged in the queue. This means that if Redis dies the whole batch gets lost and this is not acceptable. We can think of Redis cluster to make the thing more bullet proof but... doesn't it seem like going in a wrong direction?

The second approach would be to use Trident Topology. Changing the input queue to Kafka makes things looking more or less straightforward. The message processing cycle can be transactional. HOWEVER, there is this one annoying keyword that keeps beeing repeated in the Trident documentation - small batches - that Trident assumes small batches. For example the TransactionalTridentKafkaSpout batches the messages into 2 seconds chunks. This is much too little for us. I'm not sure why the batches should be small, but if it's really required maybe the first approach is better?

Which one from above is better? Maybe somoeone would come up with a "third" idea?

答: My confusion was actually caused by not understanding the Rabbit MQ publish/subscribe concept well enough. The solution is - create two queues in RabbitMQ (bind to one exchange). One queue will be for the real time processing, the second one for the batch processing. Now the batch layer should not be storm at all, instead it should be some scheduled process that just wakes up periodically and collects all the messages that got queued in the meantime.</p>


问:
What are the valid reasons to use ContentPresenter outside of template?
I stumbled upon an article by Den Delimarsky on What is a ContentPresenter? which says:

In WPF there is an element called ContentPresenter, that is often used inside control templates, as well as inside the root application markup.

I don't understand the "inside the root application markup" part, because I thought that ContentPresenter can only used inside of a ControlTemplate.

The role of the ContentPresenter is quite clear when used in a ControlTemplate, but what are the valid reasons to use ContentPresenter outside of a template's markup?

答:
(This seems to be a quite outdated reply.)

There are valid uses of ContentPresenter everywhere. My primary use of it is to dispatch the view by the runtime type of the content.

Let me explain: imagine that you have a property of type Animal in your VM, so you'd like to display it somewhere in your UI. If you have a single UI for any kind of Animal, you can put it into a UserControl, and use a construct like

```<code><AnimalControl DataContext="{Binding Animal}"/>
</code>```

However imagine that you've got a bunch of different animals, say, Toads, Humans and Unicorns. So you'd like to differentiate between them (maybe you've developed several UserControls for them). You do it in the following way:

```<code><ContentPresenter Content="{Binding Animal}"/>
</code>```

In order for the correct view to be used, you need the following DataTemplates to be in scope:

```<code><DataTemplate TargetType="{x:Type vm:Unicorn}">
    <UnicornControl/>
</DataTemplate>
</code>```

etc. Usually people get such a functionality using TemplateSelector/ContentTemplateSelector, but this way is valid, too, and seems to be simpler (you can shuffle template scopes with custom styles, a la CSS).

Body:
(This seems to be a quite outdated reply.)

There are valid uses of ContentPresenter everywhere. My primary use of it is to dispatch the view by the runtime type of the content.

Let me explain: imagine that you have a property of type Animal in your VM, so you'd like to display it somewhere in your UI. If you have a single UI for any kind of Animal, you can put it into a UserControl, and use a construct like

<AnimalControl DataContext="{Binding Animal}"/>

However imagine that you've got a bunch of different animals, say, Toads, Humans and Unicorns. So you'd like to differentiate between them (maybe you've developed several UserControls for them). You do it in the following way:

<ContentPresenter Content="{Binding Animal}"/>

In order for the correct view to be used, you need the following DataTemplates to be in scope:

<DataTemplate TargetType="{x:Type vm:Unicorn}">
    <UnicornControl/>
</DataTemplate>

etc. Usually people get such a functionality using TemplateSelector/ContentTemplateSelector, but this way is valid, too, and seems to be simpler (you can shuffle template scopes with custom styles, a la CSS).


问:
Relevance of HTML5: Is now the time?
It seems like most of the jobs I'm receiving, and most of the Internet, is still using standard HTML (HTML 4, let's say) + CSS + JS. Does anyone have any vision on where HTML5 is as a standard, particularly regarding acceptance and diffusion? It's easy to find information about inconsistencies between implementations of HTML5 and so forth. What I want to know about is relevance of HTML5.

答:
Because of Mac/Steve Jobs, "HTML5" is a public term.  Meaning, that non-programmers (AKA clients) can recall it, and are often asking for it.  So, in that sense, even though it doesn't really exist in a standardized form, but rather WebKit and Firefox's own versions, it already is relevant.

Unfortunately, the inconsistencies you mentioned become our problem.  There's also a major lack of software to develop common HTML5 elements. (We have to do everything by hand.)

What it comes down to is this: what do the people with the money want you to do?

Here's a real situation I've run into:
98.5% of the users of my clients website are on PCs running IE (This is actual usage stats here, this is a site for a certain niche market) and .02% of their users were on a mobile device.  And within that .02%, 90% where blackberries (Not HTML5-enabled iPhone or Android). BUT, the client owns an iPad.  So, naturally after explaining that our clients users would not benefit from the technology... I'm converting Flash content into HTML5.

Why? Because they'll pay hundreds of thousands to be able to show off the website on their iPad.

With a totally different client I'm currently converting Flash animations/UI into WebKit animations with Javascript because they took a "website" class where they were told that Flash is dead and HTML5 is the future.  Meanwhile, they don't use any HTML5 compliant browsers or have any iPhones/iPads.

I know you say you don't want to here about the inconsistencies between implementations of HTML5, but that's a major part of the issue.  What ever you create needs to work for your client's users.  Often, that means using Flash.  And now that Flash is going on more and more mobile devices, having many different versions of HTML5 is only going to be another stepping stone.

At the end of the day, HTML5 is something you should know, but you should never put your eggs in one basket.

Title: Relevance of HTML5: Is now the time?


问:
Test Doubles, Mocks and Stubs - when not to use & why, for Ruby, Rspec
I've learned about mocking and stubbing and I've seen how they can help me create great test suites that run blindingly fast and thus speed up my development process hugely.

However I've also seen the downside when there is an issue that is database centred and wasn't tested for (test doubles or not).

So should I have a subset of tests that do test such connectivity at least and some simple operations, for example creating a record in the primary transaction detail table, even if most of the foreign keys are stubbed out?

What experience have people found with this issue and what balance has worked in various situations?

I normally post on Stack Overflow but this seemed much more conceptual.  It might still be a bit subjective so maybe the question can be improved.

The closest similar question I could find was When should I use mock objects? but it didn't feel like it was really the same question and the answers felt further off.  Perhaps my question is more about when NOT to mock.  ...yeah, so I've updated my title.

I also found this helpful: TDD: Mocking out tightly coupled objects

答:
It boils down to the simple fact that you have to decide which cases you need to cover.

If you need to be sure of the database connection, you have to test it.

Tests are separated in groups based on what they test (unit, integration and system), where only system tests would make real calls to a database (or other external services).

Each type of test covers specific parts of the system, and ignores (or stubs out) the other parts.

I have put a simplified schematic illustration below. components inside the green box are tested, whereas components outside the green box are stubbed (faked, mocked, etc.)

for ruby/rspec there are tools (e.g. capybara) to assist with system tests, frequently called acceptance tests, when they are used to demonstrate a system does what it is supposed to.


问:
PHP coding practice
I'm a self taught PHP programmer. Because I have no formal training in PHP, I often find my coding style to be considerably different than example code I find on the Internet. I've slowly started adapting some of the more common practices I find. However, before changing my habits, I try to find a good reason to use the new style. I just don't see much reason to change my habit if it isn't actually advantageous.

I see a lot of people write PHP code such as :

```<code><h1><?php echo $cTitle; ?></h1>
<div><?php print $cContent; ?></div>
</code>```

Whereas I generally write :

```<code><?php
    echo "<h1>", $cTitle, "</h1>";
    print("<div>" . $cContent . "</div>");
</code>```

What I'm seeing is that people are commonly going in-and-out of PHP, while I'll just use PHP to print/echo the html content along with the PHP variables.

Is there a measurable difference between these two methods? Is there a good reason for me to change my ways?

答:
Template are always shitty in the end, they are all HTML which is being modified to function in the system:

```<code><h1><?php echo $cTitle; ?></h1>
echo "<h1>", $cTitle, "</h1>";
print("<div>" . $cContent . "</div>");
<h1>{{cTitle}}</h1>
<h1 data-content="cTitle"></h1>
</code>```

etcetera etcetera.

In the end something has to be identified as the place where you should put content in. Nothing to be done about it. So what is better? None of them, it's a matter of details and a matter of taste and depends on your project. I think templates are one of the oldest active discussions among php developers with no answer to it.

There is another reason why there is no solution, it's: separation of concerns. The view (if you use MVC or something like that) is the place where you define which content gets somewhere. That is because for example the controller does not know that. There is also a reason for that: The controller has a choice, you give a simple example now, but in the real world there might be a HTML and a XML view:

```<code>//HTML:
<h1><?=$cTitle;?></h1>

//XML:
<xml>
  <title><?=$cTitle;?></title>
</xml>
</code>```

So, you have to do it somewhere. No real other options are available. If you really don't want the templates with tags you could only split out the view layer in 2 separate layers which could give for example:

```<code>//template (a new layer below the view)
<h1>This is a demo title</h1>

//view code
$this->h1($cTitle);
</code>```

Then you could use something like a jQuery style to find the right tags to assign content to. That way you can use a static HTML design and just fill in the gaps though it will still break when someone changes the format of the template.

So, in the end, yes we still need some kind of tags inside the templates to get things really functional.

Not very relevant as answer but informative: When you work with a lot of developers there are always preferences on templating. In the end we decided to go for PHP in the templates with the developer letting choose their preferred way. Whether they do echo or embed the php tags doesn't make a lot of difference. Anybody with good PHP knowledge can read both. So there is a bit of freedom but it's clear which options to choose from. In the end it does not make a lot of difference with experienced developers as long as work is being done well and structured.

Title: PHP coding practice

Body:
Template are always shitty in the end, they are all HTML which is being modified to function in the system:

<h1><?php echo $cTitle; ?></h1>
echo "<h1>", $cTitle, "</h1>";
print("<div>" . $cContent . "</div>");
<h1>{{cTitle}}</h1>
<h1 data-content="cTitle"></h1>

etcetera etcetera.

In the end something has to be identified as the place where you should put content in. Nothing to be done about it. So what is better? None of them, it's a matter of details and a matter of taste and depends on your project. I think templates are one of the oldest active discussions among php developers with no answer to it.

There is another reason why there is no solution, it's: separation of concerns. The view (if you use MVC or something like that) is the place where you define which content gets somewhere. That is because for example the controller does not know that. There is also a reason for that: The controller has a choice, you give a simple example now, but in the real world there might be a HTML and a XML view:

//HTML:
<h1><?=$cTitle;?></h1>

//XML:
<xml>
  <title><?=$cTitle;?></title>
</xml>

So, you have to do it somewhere. No real other options are available. If you really don't want the templates with tags you could only split out the view layer in 2 separate layers which could give for example:

//template (a new layer below the view)
<h1>This is a demo title</h1>

//view code
$this->h1($cTitle);

Then you could use something like a jQuery style to find the right tags to assign content to. That way you can use a static HTML design and just fill in the gaps though it will still break when someone changes the format of the template.

So, in the end, yes we still need some kind of tags inside the templates to get things really functional.

Not very relevant as answer but informative: When you work with a lot of developers there are always preferences on templating. In the end we decided to go for PHP in the templates with the developer letting choose their preferred way. Whether they do echo or embed the php tags doesn't make a lot of difference. Anybody with good PHP knowledge can read both. So there is a bit of freedom but it's clear which options to choose from. In the end it does not make a lot of difference with experienced developers as long as work is being done well and structured.