问:
Complex iterators in C
note: this was originally asked on SO.

Part of my current project involves iterating over sequences that don't necessarily exist. For example, I have something similar to a relational database in memory, so say I have three arrays

```<code>typedef struct { size_t car_index, size_t part_index } car_part_t;

car_ * cars;
part_t * parts;
car_part * car_parts;
</code>```

I want to be able to iterate over all the parts in a given car, for example. I specifically want the part and not the car_part. My current solution is

```<code>typedef struct {
    size_t car_index;
    size_t part_index;
    size_t m_car_part_index; // keeps progress
} car_part_iterator_t;
</code>```

and to have two functions

```<code>car_part_iterator_t car_part_first(size_t car_index);
</code>```

which returns an iterator set up such that it.part_index is the index of the part in parts, it.car_index is the car selected by the first parameter, and it.m_car_part_index is a 'private' variable used to track progress in the car_parts list.

I then have a similar function for getting the next one

```<code>bool car_part_next(car_part_iterator_t * it);
</code>```

which moves to the next car part, and returns if the iterator is still valid. Finally for completeness I have

```<code>bool car_part_valid(car_part_iterator it);
</code>```

to check if the current iterator is still valid. So it can be used in a for loop like

```<code>for (car_part_iterator_t it = car_part_first(car_index);
    car_part_valid(it); car_part_next(&it))
{
    // use it.part_index ...
}
</code>```

To me, this sounds like a good solution that I came to after some trial and error. I also experimented with a function that returns an iterator before the first result, so the next` function would return the first result, for use in while loops.

Is this a good pattern? I assume a known one. Does it have a name? Are there pitfalls I'm not seeing?

notes:

On SO the generality of this was questioned (ie it can be made more general), but as it stands I'm not too bothered about that.

It was also pointed out that the valid function isn't strictly needed for the loop, but it allows for a more natural for loop, and is also sometimes useful outside of loops.

答:
Yes.. This is good pattern, but you can do something like this:

```<code>typedef struct {
   part_t *i, *end;
} car_part_iterator_t;
</code>```

Then have functions

```<code>car_part_iterator_t car_part_iterator_first(size_t car_index);
void car_part_next(car_part_iterator* iter); // because I don't know why you need bool there
bool car_part_valid(car_part_iterator iter);
</code>```

After that you can use it like this:

```<code>for(car_part_iterator_it it = car_part_iterator_first(index);
    car_part_valid(it); car_part_next(&it)) {
   doSomething(*(it.i));
}
</code>```

And you can actually iterate like this if you want:

```<code>for(part_t *it = car_part_iterator_first(index); it != car_part_iterator_end(index); it++) {
   // do something..
}
</code>```

Then you don't have to create another iterator struct, but still have to create to functions, though you can omit those functions if you want..

Edit: Because this website is not allowing me to comment, I have to embed my reply here. I think the *end in car_part_iterator_t struct is supposed to just check that. We set that *end to point to the part after current car's last part. In C, we can iterate over arrays like this:

```<code>int *array = calloc(sizeof(int), 10);
// we want to iterate over the first 5 elements
int *first = array;
int *end   = array + 5; // the element after the 5th element
for(int *it = first; it != end; it++)
    printf("Hello, %d\n", *it);
free(array);
</code>```

Title: Complex iterators in C

Body:
Yes.. This is good pattern, but you can do something like this:

typedef struct {
   part_t *i, *end;
} car_part_iterator_t;

Then have functions

car_part_iterator_t car_part_iterator_first(size_t car_index);
void car_part_next(car_part_iterator* iter); // because I don't know why you need bool there
bool car_part_valid(car_part_iterator iter);

After that you can use it like this:

for(car_part_iterator_it it = car_part_iterator_first(index);
    car_part_valid(it); car_part_next(&it)) {
   doSomething(*(it.i));
}

And you can actually iterate like this if you want:

for(part_t *it = car_part_iterator_first(index); it != car_part_iterator_end(index); it++) {
   // do something..
}

Then you don't have to create another iterator struct, but still have to create to functions, though you can omit those functions if you want..

Edit: Because this website is not allowing me to comment, I have to embed my reply here. I think the *end in car_part_iterator_t struct is supposed to just check that. We set that *end to point to the part after current car's last part. In C, we can iterate over arrays like this:

int *array = calloc(sizeof(int), 10);
// we want to iterate over the first 5 elements
int *first = array;
int *end   = array + 5; // the element after the 5th element
for(int *it = first; it != end; it++)
    printf("Hello, %d\n", *it);
free(array);


问:
Difference between Consumer/Producer and Observer/Observable
I am working on the design of an application that consists of three parts:

a single thread that watches for certain events happening (file creation, external requests etc.)

N worker threads that respond to these events by processing them (each worker processes and consumes a single event and the processing can take variable time)

a controller that manages those threads and does error handling (restarting of threads, logging of results)

Although this is pretty basic and not difficult to implement, I am wondering what would be the "right" way to do it (in this concrete case in Java, but higher abstraction answers are also appreciated). Two strategies come to mind:

Observer/Observable: The watching thread is observed by the controller. In case of an event happening, the controller is then notified and can assign the new task to a free thread from a reusable cached thread pool (or wait and cache the tasks in FIFO queue if all threads are currently busy). The worker threads implement Callable and either return successfull with the result (or a boolean value), or return with an error, in which case the controller may decide what to to (depending on the nature of error that has happended).

Producer/Consumer: The watching thread shares a BlockingQueue with the controller (event-queue) and the controller shares two with all workers (task-queue and result-queue). In case of an event, the watching thread puts a task object in the event-queue. The controller takes new tasks from the event-queue, reviews them and puts them in the task-queue. Each worker waits for new tasks and takes/consumes them from the task-queue (first come first served, managed by the queue itself), putting the results or errors back into the result-queue. Finally, the controller can retrieve the results from the result-queue and take according steps in case of errors.

The end results of both approaches are similar, but they each have slight differences:

With Observers, the control of threads is direct and each task is attributed to a specific new spawned worker. Overhead for creation of threads may be higher, but not much thanks to the cached thread pool. On the other hand, the Observer pattern is reduced to a single Observer instead of multiple, which is not exactly what it was designed for.

The queue strategy seems to be easier to extend, for example adding multiple producers instead of one is straightforward and does not require any change. The downside is that all threads would run indefinitely, even when not doing any work at all, and error/result handling does not look as elegant as in the first solution.

What would be the most fitting approach in this situation and why? I have found it difficult to find answers to this question online, because most examples only deal with clear cases, like updating many windows with a new value in the Observer case or processing with multiple consumers and producers. Any input is greatly appreciated.

答:
You are quite close to answering your own question. :)

In the Observable/Observer pattern (note the flip), there are three things to bear in mind:

Generally, the notification of the change, i.e. 'payload', is in the observable.

The observable exists.

The observers must be known to the existing observable (or else they have nothing to observe on).

By combining these points, what is implied is that the observable knows what its downstream components, i.e. the observers are. The data flow is inherently driven from the observable - observers merely 'live and die' by what they are observing on.

In the Producer/Consumer pattern, you get a very different interaction:

Generally, the payload exists independently of the producer responsible for producing it.

Producers do not know how or when consumers are active.

Consumers need not need to know the payload's producer.

The data flow is now completely severed between a producer and a consumer - all the producer knows is that it has an output, and all the consumer knows is that it has an input. Importantly, this means that producers and consumers can exist entirely without the presence of the other.

Another not-so-subtle difference is that multiple observers on the same observable usually gets the same payload (unless there is an unconventional implementation), whereas multiple consumers off the same producer may not. This depends if the intermediary is a queue-like or topic-like approach. The former passes a different message for each consumer, while the latter ensures (or attempts to) that all consumers processes on a per-message basis.

To fit them into your application:

In the Observable/Observer pattern, whenever your watching thread is initializing, it must know how to inform the controller. As the observer, the controller is likely waiting for a notification from the watching thread before it lets the threads handle the change.

In the Producer/Consumer pattern, your watching thread only needs to know the presence of the event queue, and interacts solely with that. As the consumer, the controller then polls the event queue, and once it gets a new payload, it lets the threads handle it.

Therefore, to answer your question directly: if you want to maintain some level of separation between your watching thread and your controller such that you can operate them independently, you should tend towards the Producer/Consumer pattern.

ContentLicense: CC BY-SA 3.0


问:
Web apps for enterprise
What are the potential drawbacks of taking a 'web approach' to providing an enterprise-level app (e.g. an ERP system or an app for field staff to complete tasks) and how can these drawbacks be tackled?

What I've Thought of So Far

Offline capability - This doesn't seem to be a problem anymore, as we can use the HTML5 app cache.

Storage - HTML5 localstorage offers us a way of storing data locally whilst checking for a connection to 'sync' it to server.

The reason I ask is because I'm trying to choose the most appropriate route for meeting requirements I have, and I want to make sure I'm not missing something that would push me in the 'native' direction.

答:
UI responsiveness is typically the problem with webapps compared to native, but for the general line-of-business program that doesn't need to handle lots of data, this isn't a problem.

All the other aspects can be handled in a HTML GUI compared to a native GUI. You may find its less maintainable or more difficult to develop, due to the pain of maintaining javascript and/or the cost of handling different browser platforms.

Title: Web apps for enterprise


问:
What are the most used pattern to manage a lot of interconnected parameters?
I recently start to work on an application that drive different measurement device.

Before the user start a measure, she sets the parameters of it.

Actually, considering all measurements type there are 50+ parameters.

The difficulty here is that every settings depends on others for:

Being available

List of available values

so on..

Moreover, some measurement settings depend on previous measure results and settings.

To make it short : we have a lot of stuff that are interconnected.

The actual pattern is to validate everything as soon as a values is changed. It cost a lot (in time) and we are going to add a lot of more parameters : it will break.

We try to implement a pattern where we use ObservableValues and where all parameters register on all values it depend on.

It became hard when the parameters depend on an other reference measure. If the reference change, we have to stop listening on the previous reference and start to listen on the new reference.

Etc...

An other issue is that when we work on our pattern and we had more capabilities (like serialization), or when we had some helper class (like factory), we build big files with 50+ parameters or functions.

Is there any other good pattern or library to do it ?

答:
I would suggest:

divide and conquer the problem

use components and keep each component focused on its main purpose

decouple you system by using an event aggregator (EA)

use interfaces where an EA doesn’t make sense

I would try to split the big problem in smaller problems and then try to solve them by its own.
The smaller problems can be solved easier by specialized components, if they are simple enough.
Each component should keep its focus on its main purpose.

To keep a loose coupling around components I would use an event aggregator (EA) (main purpose: notify listeners). (e.g.: Reactive Extensions, Caliburn Micro, or the Prism EventAggregator, if in .NET)

I would use simple parameter classes to keep values (main purpose: handle values).

I would group parameters in a some kind of tree class (main purpose: provide parameters).

The tree has to be build or updated. For this I would use one tree-builder component (main purpose: build/update tree).

The tree-builder needs to be notified when to react -> EA notification

Some consumer of the tree needs to be notified after the tree has changed -> EA notification

...

If the components are not coupled tightly, then the system can be scaled or changed when necessary. I.e.: If the building process is far too complex, then it is possible to use multiple tree-builder classes instead one. To achive this, an additional component - a tree-builder-factory - would be added. It would react on tree build/update events by providing the adequate tree-builder.


问:
Introducing a version control branching policy to a small team
I'm a contractor that has recently started with a firm.

Team is 3 developers consisting of 2 junior to mid level devs, with another at the same level starting soon, and myself (6 Years xp). For both the existing developers it is their first job out of university/college, and they've never had a senior developer overseeing their work before.

There is no explicit Version control policy. Developers do all the development on the trunk and then deploy to production direct from their development machines. The existing team are not familiar with branching.

I'm changing all this and introducing CI, TDD test/staging/production servers etc, along with a version control policy to compliment this.

Source control system is TFS, which i've never used before. It's configured as one giant repository.

I've written down a few pointers for them, but is there anything else i should be adding/ amending, bearing in mind the experience of the team?

Version Control Policy

Development is done on the trunk

If a change is estimated to take more than a week then it should be
  done on a branch, with regular merges from the trunk into the branch
  to stop the two going out of sync.

Release branches created for production code.  That branch should only
  contain stable code.  We can either have one release branch that gets
  updated from the trunk once per sprint, or we can make a separate
  release branch for each week.

If a urgent bug fix affecting production code needs to be made, then
  it gets made on the release branch, and merged back into the trunk.

If we adopt the one release branch strategy then the trunk gets merged
  into the release branch once per sprint towards the end of the sprint.

If we adopt the seperate branch per release strategy, then the trunk
  NEVER gets merged into the Release branch

In some scenarios it may be necessary to make the bug fix twice on
  different branches, if branches have diverged too much. If we are
  doing short sprints then this shouldn’t happen too often.

I plan to have three servers. Test environment that is always running the latest code in the repo. A staging environment which is running the newest release candidate for staging/testing Release Candidate code and UAT purposes, and the production environment.

The reason why i plan to do this is that so far the client has only done internal software. The newest project is for a high profile media client, and my feeling is that the team need to adopt a more professional development model than what they do at the moment.

For example at the moment, a user may phone up the team with a bug report. The devs locate and fix the bug, do a quick test eyeball test on  their own machines and then deploy straight into production. No automated testing or anything.

In hindsight i think the feature branch is a step too far and i'll remove that.

So essentially it comes down to a) no branching at all) b) a release branch and the trunk, and c) a release branch per release and the trunk.

I was leaning towards the latter. My initial thought would be that i would have both a release candidate and a release to be live on separate servers(UAT/Production) at the same time, but effectively the trunk is the release candidate at any point in time, so a branch per release is leaning towards insane. My only thought would be if we didn't want our stakeholders to see development code then we might need a separate release candidate branch, but YAGNI and all that.....

答:
You've written down a few pointers for them, but you haven't explained why is your approach better than the one they already use. This may be problematic. If you're in a spirit “We'll do it my way, because I have six years of professional experience, and you don't” (and reading your question, it looks exactly this way), be ready to be hated by your team members who will try to do whatever they can not to apply your concepts.

Do they have a problem which needs to be solved? It's crucial to answer this question first, because either they actually do have a problem and will welcome your suggestions, or they are perfectly fine working as they currently do, and you are just pushing at them your way of working, just because you prefer to work this way.

Eventually, forcing them to use branches can have an extremely negative impact. Working with a trunk is easy, especially in Agile environment. A developer commits changes to the trunk, eventually handling small conflicts, and those changes are immediately used by Continuous Integration platform. With branches:

A developer has to think where should the change be located,

Somebody has to manage branches and merges from branches to the trunk,

Merges between branches are done less frequently than commits, which means that somebody has to deal with conflicts which are larger and more difficult to handle than a conflict between two commits,

Every commit doesn't find necessarily its way into Continuous Integration, which delays the information the developers get about the effects a commit can have (especially regressions).

The fact that:

The existing team are not familiar with branching

makes things even worse. I worked in a team of inexperienced programmers, where an inexperienced manager decided to play with branches. This resulted in a lot (a lot) of wasted time and is exactly the thing you want to avoid for a project which has deadlines.


问:
PHP and Ruby: how to leverage both? and, is it worth it?
As you might have noticed from the title, this is not a "PHP or Ruby", or a "PHP vs. Ruby" question. This is a question on how to leverage PHP + Ruby in the same business.

I myself am a PHP developer, I love the language because of its convenience and I specially love the ecosystem of resources that surround it: Joomla, Drupal, Wordpress, Symfony2, Doctrine2, etc. However, the language itself can be a little disappointing sometimes.

OTOH, Ruby looks like a very beautiful language and —from studying it superficially in several aspects— I could say it is leaner than Python as a language per se. However, from what I've seen there is pretty much only RoR making noise, and I don't like RoR so much (mainly because its model layer).

As Co-CEO and CTO at my company I'm trying to think outside of the box since I want to start to focus on the human side of technology and see if its sane to use both PHP and Ruby. Here are some random thoughts:

Ruby folk seem to be generally better suited programmers than PHP folk (in terms of averages), I know the previous statement is somewhat baloney because very good and well architected PHP can be written, but I'd say the Ruby programmer culture is better than PHP's.

The thing about Ruby is that it seems better suited for rapid development, I don't really know if this is only the case for RoR, but I do know that there are certain practices (perhaps not so good) like monkey patching that let business needs be satified quicker.

From a marketing point of view (yep, sometimes you need to leverage the marketing BS for the sake of your company) Ruby seems better while PHP carries some stigmas.

PHP 5.4 is bringing traits, and that is better/cleaner than mixins. That could really make PHP as lean as Ruby —or more— for certain stuff.

Now, concretely, my questions:

Would a PHP programmer want to learn Ruby?, I know I do, but conversely, would a Ruby programmer want to learn PHP?.

What kinds of projects or situations would be better suited for Ruby that are not suited for PHP?.

What is the actual ecosystem of Ruby?, aside from RoR, I have not seen other hyped technologies/frameworks (I've seen RSpec, but I confess being a total noob on what BDD really consists of and its implications).

Supposing there are a certain type of projects ideal for Ruby, would there be a moment that its better to move it to PHP?. I know PHP can handle lots of stuff, but I've read that Ruby has its limitations when scaling (or is that RoR?, or is that baloney for both?).

Finally and most importantly, would it be sane to maintain projects in two languages?, or is that just stupid. As I said, it looks like Ruby is leaner on the short term and that can make a project happen and succeed, but I'm not so sure about that on the long run.

I'm looking for insights mainly from people that know well the strengths and weaknesses of the languages —preferably both of them— and Ruby's ecosystem in real practice, meaning: frameworks and applications like the ones I quoted from PHP's ecosystem.

答:
When reading keep in mind that I am a Ruby on Rails Developer, and answering from that eco-system. My views will be slanted in that direction.

Would a PHP programmer want to learn Ruby?, I know I do, but conversely, would a Ruby programmer want to learn PHP?

Absolutely not, in most cases. Not just because I don't like PHP (I don't, but I use it), but because the tool sets have fundamental ideal differences. There are a lot of tools like rake and rspec that assist with some for of TDD in the ruby world. In most ruby (and certainly rails) tutorials testing comes first. That's not to say you can't do this in PHP, it's just that conventions are different. And the conventional differences between the two languages are, in general, directly opposed.

What kinds of projects or situations would be better suited for Ruby that are not suited for PHP?.

Desktop applications, shell scripts, MVC apps (rails again), and small console applications. Not that any of these can't be done with php, Ruby just has better support. When writing a Rails (sorry) app I often write one off scripts in ruby. This allows my deployment or setup scripts to be in the same language as my application, where with PHP I would never even try to write a shell script in PHP. I would just use bash. I have written Ruby QT apps, and MVC apps (both Rails and not) and ruby and it's surrounding libs just "work better" for those cases.

What is the actual ecosystem of Ruby?, aside from RoR, I have not seen other hyped technologies/frameworks (I've seen RSpec, but I confess being a total noob on what BDD really consists of and its implications).

This is kind of a misconception. RoR is popular because it does it's job well, but there are may other toolsets/stacks that use ruby at their core. They are less popular because the are entering into a space that already has alternatives. I for one like writing quick GUI applications in ruby. But python, C#, VB, LISP, etc etc can already do this. RoR was a game changer. Thus it's popular. The same can be said for PHP, name a popular PHP framework. There are some, but remove products (like wordpress) from the list, and your not left with a whole lot.

Supposing there are a certain type of projects ideal for Ruby, would there be a moment that its better to move it to PHP?. I know PHP can handle lots of stuff, but I've read that Ruby has its limitations when scaling (or is that RoR?, or is that baloney for both?)

This is a tricky question and you have to ask, what language is better for my project? I would never write a blog in Rails. I know that's the standard tutorial example, but if you want a blog then wordpress is the proper tool. The same applies here. If you run into a solid example of needing to switch languages away from ruby, the technical limitations you will face will preclude PHP as well.

Finally and most importantly, would it be sane to maintain projects in two languages?, or is that just stupid. As I said, it looks like Ruby is leaner on the short term and that can make a project happen and succeed, but I'm not so sure about that on the long run.

Ruby is great in the long run. The biggest obstical to long term success is not the language, but the developer. As to maintaining two langues, it depends on how you define a project. I have a few projects that have a heavy application in rails, and a blog or sales site using wordpress/dupral/some php. I consider them separate projects. I will say that the more languages you end up supporting, the harder it is to find a good dev that is good in all the languages. For example, I use and recommend wordpress, but I am no where near as "good" in PHP as I am in RoR. If a client really wanted half of their core product in PHP and half in RoR I would really have to figure out why, and depending on their answer would likely turn down the work.


答:
One more idea:

Keep all your parameters in a big map like:

```<code>class Params
{
   Map<String, Object> map;

   /* fancy helper methods... */
}
</code>```

Add a set of rule objects:

```<code>interface Rule
{
  /* returns "OK" or an error message
   * or use exceptions or whatever you fancy */
  void validate(Params params);

  /* returns the list of params that will trigger the rule */
  String[] triggers();
}

class FancyRule implements Rule
{
  String validate(Params params) {
     if( params.get("foo") <= params.get("bar") )
        return "foo should be greater than bar";
     else
        return "OK";
  }
  String[] triggers() {
     return ["foo", "bar"];
  }
}
</code>```

As last step, you just need to bundle things together:

```<code>class Params
{
   Map<String, Object> map;

   void setParam(key,value) {
      map.put(key,value); // + keep a backup if desired

      // now validate everything depending on it
      for( rule in rules having key as trigger):
           if( rule.validate(this) != "OK" )
                // ...
   }
}
</code>```

Title: What are the most used pattern to manage a lot of interconnected parameters?

Body:
I recently start to work on an application that drive different measurement device.

Before the user start a measure, she sets the parameters of it.

Actually, considering all measurements type there are 50+ parameters.

The difficulty here is that every settings depends on others for:

Being available

List of available values

so on..

Moreover, some measurement settings depend on previous measure results and settings.

To make it short : we have a lot of stuff that are interconnected.

The actual pattern is to validate everything as soon as a values is changed. It cost a lot (in time) and we are going to add a lot of more parameters : it will break.

We try to implement a pattern where we use ObservableValues and where all parameters register on all values it depend on.

It became hard when the parameters depend on an other reference measure. If the reference change, we have to stop listening on the previous reference and start to listen on the new reference.

Etc...

An other issue is that when we work on our pattern and we had more capabilities (like serialization), or when we had some helper class (like factory), we build big files with 50+ parameters or functions.

Is there any other good pattern or library to do it ?

Body:
One more idea:

Keep all your parameters in a big map like:

class Params
{
   Map<String, Object> map;

   /* fancy helper methods... */
}

Add a set of rule objects:

interface Rule
{
  /* returns "OK" or an error message
   * or use exceptions or whatever you fancy */
  void validate(Params params);

  /* returns the list of params that will trigger the rule */
  String[] triggers();
}

class FancyRule implements Rule
{
  String validate(Params params) {
     if( params.get("foo") <= params.get("bar") )
        return "foo should be greater than bar";
     else
        return "OK";
  }
  String[] triggers() {
     return ["foo", "bar"];
  }
}

As last step, you just need to bundle things together:

class Params
{
   Map<String, Object> map;

   void setParam(key,value) {
      map.put(key,value); // + keep a backup if desired

      // now validate everything depending on it
      for( rule in rules having key as trigger):
           if( rule.validate(this) != "OK" )
                // ...
   }
}


问:
Rich object model in the context of a good REST API and of an existing rich object model on the server-side
First off, let's frame this question in the context of a good REST API and an existing rich object model on the server-side, as well as modern web architecture (MVC frameworks like angularjs).

I'm debating whether or not to use a rich object model with my next project. The alternative is just using very light-weight POJO objects (pretty much whatever the API gives me) and using these in a non-persistent (between views) manner, i.e. no "application state". Just load what you need for the current operations and then get rid of it when you don't.

The risks of a rich object model that are giving me pause are:

1. Testability - it could be harder to unit test a complex object model

2. Performance - with a large object graph, the performance of the app could suffer. Contrast that with lightweight POJO's that get created and destroyed as needed, the app stays nimble.

3. Complexity - a complex object model could be orders of magnitude more complex than a lightweight app that just loads what it needs at the moment. This could also make it harder to modify...

4. Harder to modify - a rich object model creates a multitude of dependencies. This makes it harder to change things down the road.

I'm leaning towards a lean, light-weight web app that just loads what it needs at the moment and destroys what it doesn't.

答:
When it come to dealing with a web client side frameworks, best approach is to keep objects simple, because

API Complexity ->  Less complex of API methods

Concurrency -> If a complex object is loaded, and it's life time is apparently longer and when it needed to persist there could higher probability that it might have changed by some other user / process. Which could cause errors. By keeping the lifetime of object lower this can be avoided.

Validations -> when you have a rich object model there are more and more complex validations you need. If the same model spans over multiple views (chances are it will) then showing the messages when persisting the object would be a complex task.

Performance -> Even it is a minor change, if a rich model is used entire model need to be fetched causing access to multiple tables and large amount of data is fetched.

OwnerDisplayName: Richard DesLonde


答:
Like Mainma says, be careful with the branching. You mention branching every few weeks, is it really necessary to have a lot of branches?

Alternatively, you could also have a 'pull' model instead of a push model.
If you were using Git or Mercurial, you could have an integration server validate their changes before pushing to the central server. In TFS, you can do something similar using gated check-ins.
This way, you can have validation and avoid the complexity of branches.

Title: Introducing a version control branching policy to a small team

Body:
I'm a contractor that has recently started with a firm.

Team is 3 developers consisting of 2 junior to mid level devs, with another at the same level starting soon, and myself (6 Years xp). For both the existing developers it is their first job out of university/college, and they've never had a senior developer overseeing their work before.

There is no explicit Version control policy. Developers do all the development on the trunk and then deploy to production direct from their development machines. The existing team are not familiar with branching.

I'm changing all this and introducing CI, TDD test/staging/production servers etc, along with a version control policy to compliment this.

Source control system is TFS, which i've never used before. It's configured as one giant repository.

I've written down a few pointers for them, but is there anything else i should be adding/ amending, bearing in mind the experience of the team?

Version Control Policy

Development is done on the trunk

If a change is estimated to take more than a week then it should be
  done on a branch, with regular merges from the trunk into the branch
  to stop the two going out of sync.

Release branches created for production code.  That branch should only
  contain stable code.  We can either have one release branch that gets
  updated from the trunk once per sprint, or we can make a separate
  release branch for each week.

If a urgent bug fix affecting production code needs to be made, then
  it gets made on the release branch, and merged back into the trunk.

If we adopt the one release branch strategy then the trunk gets merged
  into the release branch once per sprint towards the end of the sprint.

If we adopt the seperate branch per release strategy, then the trunk
  NEVER gets merged into the Release branch

In some scenarios it may be necessary to make the bug fix twice on
  different branches, if branches have diverged too much. If we are
  doing short sprints then this shouldn’t happen too often.

I plan to have three servers. Test environment that is always running the latest code in the repo. A staging environment which is running the newest release candidate for staging/testing Release Candidate code and UAT purposes, and the production environment.

The reason why i plan to do this is that so far the client has only done internal software. The newest project is for a high profile media client, and my feeling is that the team need to adopt a more professional development model than what they do at the moment.

For example at the moment, a user may phone up the team with a bug report. The devs locate and fix the bug, do a quick test eyeball test on  their own machines and then deploy straight into production. No automated testing or anything.

In hindsight i think the feature branch is a step too far and i'll remove that.

So essentially it comes down to a) no branching at all) b) a release branch and the trunk, and c) a release branch per release and the trunk.

I was leaning towards the latter. My initial thought would be that i would have both a release candidate and a release to be live on separate servers(UAT/Production) at the same time, but effectively the trunk is the release candidate at any point in time, so a branch per release is leaning towards insane. My only thought would be if we didn't want our stakeholders to see development code then we might need a separate release candidate branch, but YAGNI and all that.....


问:
If the representation part of type abstraction is declared private, then how does sub-classing violate encapsulation?
Here, I learned that sub-classing violates encapsulation:

it violates encapsulation, since the implementations of the superclass and subclass become tightly coupled

For instance, If we consider below Java syntax, a class has access to all the fields and methods of its super class provided they are not declared private.

```<code>class Person{
    private String name;
    String address;
    //methods of class Person
}

class Employee extends Person{
    float salary;
    private Employee immedateManager;
    private raiseSalary(float raise){...}
}

class Manager extends Employee{
    String department;

    void test(){
        name = "Fred";   //compiler error, could not break encapsulation
        salary = 70000.00f;
        address = "somewhere";
        immediateManager = "Slate"; //compiler error, could not break encapsulation
        raiseSalary(1234.0);    //compiler error, could not break encapsulation
    }
}
</code>```

So, if the representation part of type abstraction (Java class) is declared private, then how does one understand before saying that, sub-classing violate encapsulation?

答:
It has nothing to do with privacy.  An integral part of your class is no longer implemented inside your class.  By definition that's a loss of encapsulation.

However, object-oriented programmers sometimes place an outsized importance on class-level encapsulation.  The other problems with inheritance, such as coupling, are much more important, and the encapsulation loss shouldn't bother you in situations where inheritance is otherwise appropriate.


问:
Is the semantic contract of an interface (OOP) more informative than a function signature (FP)?
It is said by some that if you take SOLID principles to their extremes, you end up at functional programming. I agree with this article but I think that some semantics are lost in the transition from interface/object to function/closure, and I want to know how Functional Programming can mitigate the loss.

From the article:

Furthermore, if you rigorously apply the Interface Segregation Principle (ISP), you'll understand that you should favour Role Interfaces over Header Interfaces.

If you keep driving your design towards smaller and smaller interfaces, you'll eventually arrive at the ultimate Role Interface: an interface with a single method. This happens to me a lot. Here's an example:

```<code>public interface IMessageQuery
{
    string Read(int id);
}
</code>```

If I take a dependency on an IMessageQuery, part of the implicit contract is that calling Read(id) will search for and return a message with the given ID.

Compare this to taking a dependency on its equivalent functional signature,  int -> string. Without any additional cues, this function could be a simple ToString(). If you implemented IMessageQuery.Read(int id) with a ToString() I may accuse you of being deliberately subversive!

So, what can functional programmers do to preserve the semantics of a well-named interface? Is it conventional to, for example, create a record type with a single member?

```<code>type MessageQuery = {
    Read: int -> string
}
</code>```

答:
So, what can functional programmers do to preserve the semantics of a well-named interface?

Use well named functions.

IMessageQuery::Read: int -> string simply becomes ReadMessageQuery: int -> string or something similar.

The key thing to note is that names are only contracts in the loosest sense of the word. They only work if you and another programmer infer the same implications from the name, and obey them. Because of this, you can really use any name that communicates that implied behavior. OO and functional programming have their names in slightly different places and in slightly different shapes, but their function is the same.

Is the semantic contract of an interface (OOP) more informative than a function signature (FP)?

Not in this example. As I explained above, a single class/interface with a single function isn't meaningfully more informative than a similarly well named standalone function.

Once you get more than one function/field/property in a class, you can infer more information about them because you can see their relation. It's arguable if that's more informative than standalone functions that take the same/similar parameters or standalone functions organized by namespace or module.

Personally, I don't think that OO is significantly more informative, even in more complex examples.


答:
For a team of 3-4 devs, you're proposing WAY too many branches.

Every branch you create is additional overhead that comes with a cost (time spent merging, keeping track of what's where, etc).  You need to make sure that the benefit you get from having a branch outweighs the cost.

Keep in mind that the only real benefit to a branch is code isolation.  That means you need a concrete reason to want to have the code isolated.

Having a separate release branch for every sprint is insane.  Why do you need the code from one sprint isolated from the code for the next?  Why not just have a single stable release branch that gets carried forward with each sprint?

If a change is estimated to take more than a week then it should be done on a branch, with regular merges from the trunk into the branch to stop the two going out of sync.

Almost any non-trivial new feature is going to take at least a week in real time after you account for development, developer testing, daily interruptions and other activities, etc.

Also, what's a "regular merge"?  Daily?  Weekly?  Every merge you do takes time - you need to make sure the target merge branch builds & runs after your changes.  On a small team, frequent merging is a lot of overhead.

We have a team of 4 developers working on a 1+ million line codebase and this is how we operate:

Main branch where all development is done

One branch per major release (done about once per year)

The one major rule is:  don't check in code that doesn't build.

That's it.  Simple, easy to understand, gets the isolation we need (at any time we can create a release build for any version).

The upsides to having all development work done on one branch:

Developers are always in-sync with each other.  No painful merges because two developers were off on their own branches for weeks creating incompatible changes.

Broken builds are found on the same day.  We have a nightly build that runs the latest code on main.  If someone does check in code that doesn't build for some reason, we will know right away.

With everyone always working on the same code, in increases the chances of a bug being found sooner rather than later.

No merge overhead other than targeted fixes to release branches.  On a small team, this is the big one.


答:
As Telastyn says, comparing the static definitions of functions:

```<code>public string Read(int id) { /*...*/ }
</code>```

to

```<code>let read (id:int) = //...
</code>```

You haven't really lost anything going from OOP to FP.

However, this is only part of the story, because functions and interfaces aren't only referred to in their static definitions. They're also passed around. So let's say our MessageQuery was read by another piece of code, a MessageProcessor. Then we have:

```<code>public void ProcessMessage(int messageId, IMessageQuery messageReader) { /*...*/ }
</code>```

Now we can't directly see the method name IMessageQuery.Read or its parameter int id, but we can get there very easily through our IDE. More generally, the fact that we're passing an IMessageQuery rather than just any interface with a method a function from int to string means we're keeping that id parameter name metadata associated with this function.

On the other hand, for our functional version we have:

```<code>let read (id:int) (messageReader : int -> string) = // ...
</code>```

So what have we kept and lost? Well, we still have the parameter name messageReader, which probably makes the type name (the equivalent to IMessageQuery) unnecessary. But now we've lost the parameter name id in our function.

There's two main ways around this:

Firstly, from reading that signature, you can already make a pretty good guess what's going to be going on. By keeping functions short, simple and cohesive and using good naming, you make it a lot easier to intuit or find this information. Once we got into reading the actual function itself, it'd be even simpler.

Secondly, it's considered idiomatic design in many functional languages to create small types to wrap primitives. In this case, the opposite is happening- instead of replacing a type name with a parameter name (IMessageQuery to messageReader) we can replace a parameter name with a type name. For example, int could be wrapped in a type called Id:

```<code>type Id = Id of int
</code>```

Now our read signature becomes:

```<code>let read (id:int) (messageReader : Id -> string) = // ...
</code>```

Which is just as informative as what we had before.

As a side note, this also provides us some of the compiler protection we had in OOP. Whereas the OOP version ensured we took specifically a IMessageQuery rather than just any old int -> string function, here we have a similar (but different) protection that we're taking an Id -> string rather than just any old int -> string.

I'd be reluctant to say with 100% confidence that these techniques will always be just as good and informative as having the full information available on an interface, but I think from the above examples, you can say that most of the time, we can probably do just as good a job.

Title: Is the semantic contract of an interface (OOP) more informative than a function signature (FP)?

Body:
It is said by some that if you take SOLID principles to their extremes, you end up at functional programming. I agree with this article but I think that some semantics are lost in the transition from interface/object to function/closure, and I want to know how Functional Programming can mitigate the loss.

From the article:

Furthermore, if you rigorously apply the Interface Segregation Principle (ISP), you'll understand that you should favour Role Interfaces over Header Interfaces.

If you keep driving your design towards smaller and smaller interfaces, you'll eventually arrive at the ultimate Role Interface: an interface with a single method. This happens to me a lot. Here's an example:

```<code>public interface IMessageQuery
{
    string Read(int id);
}
</code>```

If I take a dependency on an IMessageQuery, part of the implicit contract is that calling Read(id) will search for and return a message with the given ID.

Compare this to taking a dependency on its equivalent functional signature,  int -> string. Without any additional cues, this function could be a simple ToString(). If you implemented IMessageQuery.Read(int id) with a ToString() I may accuse you of being deliberately subversive!

So, what can functional programmers do to preserve the semantics of a well-named interface? Is it conventional to, for example, create a record type with a single member?

```<code>type MessageQuery = {
    Read: int -> string
}
</code>```

Body:
As Telastyn says, comparing the static definitions of functions:

public string Read(int id) { /*...*/ }

to

let read (id:int) = //...

You haven't really lost anything going from OOP to FP.

However, this is only part of the story, because functions and interfaces aren't only referred to in their static definitions. They're also passed around. So let's say our MessageQuery was read by another piece of code, a MessageProcessor. Then we have:

public void ProcessMessage(int messageId, IMessageQuery messageReader) { /*...*/ }

Now we can't directly see the method name IMessageQuery.Read or its parameter int id, but we can get there very easily through our IDE. More generally, the fact that we're passing an IMessageQuery rather than just any interface with a method a function from int to string means we're keeping that id parameter name metadata associated with this function.

On the other hand, for our functional version we have:

let read (id:int) (messageReader : int -> string) = // ...

So what have we kept and lost? Well, we still have the parameter name messageReader, which probably makes the type name (the equivalent to IMessageQuery) unnecessary. But now we've lost the parameter name id in our function.

There's two main ways around this:

Firstly, from reading that signature, you can already make a pretty good guess what's going to be going on. By keeping functions short, simple and cohesive and using good naming, you make it a lot easier to intuit or find this information. Once we got into reading the actual function itself, it'd be even simpler.

Secondly, it's considered idiomatic design in many functional languages to create small types to wrap primitives. In this case, the opposite is happening- instead of replacing a type name with a parameter name (IMessageQuery to messageReader) we can replace a parameter name with a type name. For example, int could be wrapped in a type called Id:

type Id = Id of int

Now our read signature becomes:

let read (id:int) (messageReader : Id -> string) = // ...

Which is just as informative as what we had before.

As a side note, this also provides us some of the compiler protection we had in OOP. Whereas the OOP version ensured we took specifically a IMessageQuery rather than just any old int -> string function, here we have a similar (but different) protection that we're taking an Id -> string rather than just any old int -> string.

I'd be reluctant to say with 100% confidence that these techniques will always be just as good and informative as having the full information available on an interface, but I think from the above examples, you can say that most of the time, we can probably do just as good a job.


问:
first time scrum master - need to create product backlog and set up work
I am certified scrum master but never practiced until tomorrow when I have been appointed as a SCRUM Master to a pilot initiative in the company to implement SCRUM in a team of non-software and non project but daily activity. I let you imagine all the politics around this decision.

the work will start on 1st of Aug and the product owner has set up a meeting tomorrow to create the product backlog with me and another person which will not be part of the team.

MY QUESTIONS:

who should propose the structure of the product backlog tomorrow (me or the PO)

should we create directly user stories with the Product owner?

I have a one hour meeting and in my understanding I need more than that? what is your suggestion on how to proceed?

I know all the theory but I miss the very practical steps to start.

thanks for your help :)

here couple of more info:

department: product development (non IT products)

team: 7 people

Product owner: is the manager of the department (the 7 people in the team are his team)

Scrum Master: I do not belong to the team nor to the department, I am working as staff function

beginning of the work: 1st of August (but as you see in the question the PO wants to create the product backlog with me tomorrow (45 days in advance)

company: 100 years old, 25k employees, always used Waterfall methodology only 3-4 SCRUM initiatives ongoing in small IT projects (budget less than 500k €)

答:
IMHO, don't do this. If you want to go Agile Crystal Clear or Kanban would be more appropriate for your company.

Scrum is the worst, and you're already getting it wrong by being scrum master but not part of the team! Typically, in Scrum the PO is the one who assigns the backlog - its his job to make decide what he wants from the product, so its his job to prioritise the features he wants. He should be liaising with the team to do this (as the team will give useful feedback to him as to what can be achieved, or what foundations are needed for the features he wants implemented).

This is key, if you want to be agile, you need to involve the team in this process. Deciding what the initial design will be, and they telling the team "do this work" is, well, very waterfall. (and I know Scrum does tend to degenerate into a series of 2-week waterfalls, that doesn't make it a good thing).

So, in your planning meeting be there with the team. Tell the PO to tell all of you what he wants, and you'll tell him what you can achieve in the time allocated to the sprint. Then he should disappear and not come back until the end of the sprint when you'll show him what you've managed to get done. Then you iterate what extra stuff (or original stuff you didn't have time to do) he wants done.

Your job is to get the meeting going, get the team involved, and get the PO out of there when he has explained what he needs doing. Do not be the 'team manager'. Scrum master is NOT the team lead, team manager or any form of team boss. Your job is to keep the team clear to do their thing.


问:
DDD – duplicity between Aggregates – should I use one table?
I understand that there exists duplicity of data between Bounded Contexts. The thing is that I'm not really sure about duplicity of data between Aggregate roots.

Example:
I have product in Product aggregate and also Product in Cart aggregate. Both are in same BC (ShoppingCart) and share few fields (name, description, ...). MySQL is used as storage. Should product in both aggregates be stored in one table or separately?

I don't mind duplicity, but in this case there would be n products in database for n cart items.

答:
I think you want to go for a design of normalization within one Bounded Context.  If one aggregate is a pure subset of the other (e.g. the product for cart is a subset of the product for product) I'd probably use a single table.  Otherwise, I'd probably use a second table that refers to the first table rather than duplicating columns between two tables.

For what it's worth, I'm not convinced that the two different product items you're describing are both aggregates. One or both may be merely entities or value objects; perhaps there really is only one product aggregate in this BC.

Update

Based on your diagram: in the cart domain, you want a collection of references to products (by Product ID). I wouldn't even call that collection a product table, but instead I'd call that a cart item table. This cart item table would have fields relevant to cart items, such as: the cart table item id, a product table foreign key reference, maybe along with things applicable to cart'ing but not products, like say, a count of the number of this product item being ordered, and even timestamp of when added to the cart (price at the time added to the cart, etc...).

I wouldn't duplicate any product table columns in the cart item table.  When you need a product item column value (such as description), you use a join from the cart item table to get it.

(If/when you find that for performance reasons you want to start making these more independent, then it is worth starting to think of these as different bounded contexts, because decoupling these things for performance introduces new (consistency management) responsibilities.  In between two different contexts, you can use translation, duplication & caching, and eventing, as necessary when you might run multiple databases for performance.)


问:
Where and how should one announce their new open source application
Where and how should someone announce an open source application they would like the wider public to try?

Obviously they can post their code somewhere like Github. There used to be Freshmeat, which has been closed down and superseded, possibly because it wasn't popular?

So where is the best place?

Does Stack Exchange provide a relevant service?

答:
Placing your software on Github makes it visible to other developers who would like to help. But when you are looking for users, you need to go where your users are. So unless your users are other developers, Github is not the right website to attract them.

Define your target audience, find out which websites they meet on, and announce your project there.


答:
who should propose the structure of the product backlog tomorrow (me or the PO)?

Generally it is the Product Owner that creates the product backlog.  The whole point of the product backlog is to be a list of features desired by the business in prioritized order.

should we create directly user stories with the Product owner?

The contents of the backlog are the responsibility of the product owner, both the contents of the user stories and their order.  That said, the creation of user stories is almost always something that involves the technical team.

I have a one hour meeting and in my understanding I need more than that? what is your suggestion on how to proceed?

In classic scrum, you have three meetings:

At the start of the sprint, you have a planning meeting where you decide what stories will be in the sprint, and where you make sure that the stories are well defined enough for developers to code against them.  How long these are depends on the team and the sprint length.  For my team it usually runs a bit over an hour.

During each sprint, you have a daily standup.  This should be short, ideally around ten minutes.  The product owner may not be present.

At the end of each sprint, you have a review where the team demonstrates the software to the product owner.

Title: first time scrum master - need to create product backlog and set up work

Body:
I am certified scrum master but never practiced until tomorrow when I have been appointed as a SCRUM Master to a pilot initiative in the company to implement SCRUM in a team of non-software and non project but daily activity. I let you imagine all the politics around this decision.

the work will start on 1st of Aug and the product owner has set up a meeting tomorrow to create the product backlog with me and another person which will not be part of the team.

MY QUESTIONS:

who should propose the structure of the product backlog tomorrow (me or the PO)

should we create directly user stories with the Product owner?

I have a one hour meeting and in my understanding I need more than that? what is your suggestion on how to proceed?

I know all the theory but I miss the very practical steps to start.

thanks for your help :)

here couple of more info:

department: product development (non IT products)

team: 7 people

Product owner: is the manager of the department (the 7 people in the team are his team)

Scrum Master: I do not belong to the team nor to the department, I am working as staff function

beginning of the work: 1st of August (but as you see in the question the PO wants to create the product backlog with me tomorrow (45 days in advance)

company: 100 years old, 25k employees, always used Waterfall methodology only 3-4 SCRUM initiatives ongoing in small IT projects (budget less than 500k €)


问:
Why check if object is nil
What's the point of the if statement in the following code:

```<code>- (NSArray *)myMethod
{
    NSArray *array = nil;
    if (!array) {
        array = [[NSArray alloc] initWithObjects...]
    }
    return array;
}
</code>```

What's the point of the check if we assigned it to nil and what's the point of assigning it to nil if we didn't put anything inside of it?

答:
In terms of working code, you are correct, there is no point in checking for nil here.  You could rewrite this as:

```<code>- (NSArray *)myMethod
{
    return [[NSArray alloc] initWithObjects...]
}
</code>```

It is hard to know without seeing the entire codebase why this is being done.  One possibility is that the original author expected to eventually replace myMethod with a call that potentially passed in a non-nil array or expected to eventually add more complex logic in the allocation.

The other very real possibility (and the most likely one in my opinion) is that whoever wrote it had an ingrained habit of always checking for nil and just wasn't thinking.  Since this has no effect on the code, no one ever noticed, or could be bothered to fix.

Title: Why check if object is nil

Body:
In terms of working code, you are correct, there is no point in checking for nil here.  You could rewrite this as:

- (NSArray *)myMethod
{
    return [[NSArray alloc] initWithObjects...]
}

It is hard to know without seeing the entire codebase why this is being done.  One possibility is that the original author expected to eventually replace myMethod with a call that potentially passed in a non-nil array or expected to eventually add more complex logic in the allocation.

The other very real possibility (and the most likely one in my opinion) is that whoever wrote it had an ingrained habit of always checking for nil and just wasn't thinking.  Since this has no effect on the code, no one ever noticed, or could be bothered to fix.


问:
ASP.NET user control best practices, programmatically or markup?
I've just started an internship with a company whose main product is an ASP.NET web forms. My related experience so far has been with Java and front end web development. My current task is to make their site responsive and more accessible for various users.

Currently I'm struggling to make sense of how each HTML page is generated. All of the user controls are programmatically generated from code behind .ascx.cs files and there is no markup in any of the .ascx files themselves.

I was wondering if this is standard practice? And are there any tools I can use to get a clearer picture of what each part generates?

答:
***Edited

I am editing here because I did not really answer you question: ASP.NET was created around 14 years ago, when AJAX and DOM manipulation where in their infancy. The idea was to create controls and drag and drop them on a form. The controls would be part of a tree under the web form.

Anyway, At that time, ASP.NET fit the bill for 90% of projects, it had never been easier to create a web app then it had become with ASP.NET. Now it is 2015, and things have changed drastically over the years, namely, AJAX is everywhere.

One of the issues with ASP.NET is that it generates unique IDs for each control based on where the control fit in its page's control hierarchy. It also saves a pages encrypted ViewState, the state of all its controls, in a separate form field. So if you change the DOM drastically, when the pages tries to restore it's view state, it will error out, because the page is no longer the same state as it was when the view state was captured.

For example a generated id of "somepage_control_othercontrol" could be used by the asp.net page to find a control that is nested within its page and and restore its current view state, without having to do it manually. So, to sum it up, the best practice at the time was to reuse nested controls and there xml representations in the markup, for example, <asp:TextBox />.

If you want to use ASP.NET how it was designed to be used, use nested User Controls and Server Controls and try not to mess with the DOM too much.

If you are going do a lot of DOM manipulations via javascript, don't mind pulling post parameters into variables manually, don't care whether a control automatically repopulates with it's last value after a post, want to determine your own input control names, then you can use straight HTML aspx file with no server controls and turn off ViewState on your page, but for most pages you will doing a lot more work that the framework would normally do for you.

***End Edit

I have not done non MVC asp.net development now for several years, but the best way that I know of to understand how User Controls are generated is to understand the Page Execution and Control Execution Lifecycles and the events that render them.

See https://msdn.microsoft.com/en-us/library/ms178472.aspx

https://msdn.microsoft.com/en-us/library/aa719775(v=vs.71).aspx

https://msdn.microsoft.com/en-us/library/ms178472(v=vs.85).aspx

http://www.codeproject.com/Articles/457647/Understanding-ASP-NET-Application-and-Page-Life-Cy

PreInit All the Dynamic Controls, Master pages, Profiles and themes should be set in this event.

Init    This should be used to set the initial value of the Control properties.

InitComplete    This should be used to have custom ViewState data. This is the first place where ViewState has been loaded and can be changed.

Preload This can be used to set the properties of the controls.

Load    All the Database connections and Data Binding can be performed here. Before this event finishes up all the validations will be done. Once the event is finished, the events for all the controls will execute before calling the next event in this list.

LoadComplete    This event can be used for activities on controls that require them to be fully loaded.s

PreRender   This is the last page where the visual properties of the controls can be changed before getting them displayed on the page.

PreRenderComplete   This will be called when the page is ready and no changes in visual elements can be made. All data binding are done at this point.

SaveStateComplete   View State has been saved and from this point onwards changes in ViewState will not be preserved i.e. ViewState has been saved for the page already.

Unload  The Page processing is done now. This is the last event that will be called.

Essentially you need know exactly where you can do a certain types of tasks within the page and control life cycles. Once you understand this, you just need to subscribe to the right event for the task and write the code that's require in the event handler.

Here is a complete list of all the events as the happen in order across all scopes

Page    ProcessRequest

Page    ProcessRequestMain

Page    DeterminePostBackMode

Adapter DeterminePostBackMode

Page    LoadScrollPosition

Page    OnPreInit

Page    ApplyMasterPage

PostBack    ApplyMasterPageRecursive

Control InitRecursive

Control ResolveAdapter

Control ApplySkin

Page    ApplyControlSkin

PostBack    ApplyControlSkin

Page    OnInitComplete

PostBack    LoadAllState

PostBack    LoadPageStateFromPersistenceMedium

PagePersister   Load

Control LoadControlStateInternal

Control LoadControlState

Adapter LoadAdapterControlState

Control LoadViewStateRecursive

Control LoadViewState

Adapter LoadAdapterViewState

PostBack    ProcessPostData

Page    OnPreLoad

Control LoadRecursive

Control OnLoad

Adapter OnLoad

PostBack    ProcessPostData

PostBack    RaiseChangeEvents

PostBack    RaisePostBackEvents

Page    OnLoadComplete

Control PreRenderRecursiveInternal

Control EnsureChildControls

Control ResolveAdapter

Control CreateChildControls

Adapter CreateChildControls

Control OnPreRender

Adapter OnPreRender

Control SaveViewState

Page    SavePageStateToPersistenceMedium

PagePersister   Save

Page    OnSaveStateComplete

Control RenderControl

Control RenderControlInternal

Control Render

Adapter BeginRender

Adapter Render

Adapter EndRender

Control RenderChildren


答:
When doing FP I tend to use more specific semantic types.

For example, your method for me would become something like:

```<code>read: MessageId -> Message
</code>```

This communicates quite a lot more than the OO(/java)-style ThingDoer.doThing() style

Body:
When doing FP I tend to use more specific semantic types.

For example, your method for me would become something like:

read: MessageId -> Message

This communicates quite a lot more than the OO(/java)-style ThingDoer.doThing() style


问:
When is a event listener invoked during program execution?
I am using the Obervable-Observer Pattern.

```<code>MyClass extends Observable{

  invokeListeners(){
     doSomething;
     setChanged();
     notifyListeners();//This invokes onUpdate() in "implements Observer"

     return value;
  }
}

ClassTwo implements Observer{

   onUpdate(){
      //This is called after notifyListeners();
   }
}
</code>```

My question is when will the onUpdate method in the Listener Class get invoked? After the invokeListeners() methods completes, or right after notifyListeners()?

答:
In the Implementation of

notifyListeners();//This invokes onUpdate() in "implements Observer"

is normally a loop over all registered Observers.

In this loop is normally a direct call to

```<code>onUpdate()
</code>```

on each registered Observer.

Be sure not to block the execution in the implementation of

```<code>onUpdate()
</code>```

Body:
In the Implementation of

notifyListeners();//This invokes onUpdate() in "implements Observer"

is normally a loop over all registered Observers.

In this loop is normally a direct call to

onUpdate()

on each registered Observer.

Be sure not to block the execution in the implementation of

onUpdate()


问:
Why would a program use a closure?
After reading many posts explaining closures here I'm still missing a key concept: Why write a closure?  What specific task would a programmer be performing that might be best served by a closure?

Examples of closures in Swift are accesses of an NSUrl and using the reverse geocoder. Here is one such example. Unfortunately, those courses just present the closure; they do not explain why the code solution is written as a closure.

An example of a real world programming problem that might trigger my brain to say, "aha, I should write a closure for this", would be more informative than a theoretical discussion.  There is no shortage of theoretical discussions available on this site.

答:
First of all, there is nothing that is impossible without using closures.  You can always replace a closure by an object implementing a specific interface.  It's only a matter of brevity and reduced coupling.

Second, keep in mind that closures are often used inappropriately, where a simple function reference or other construct would be more clear.  You shouldn't take every example you see as a best practice.

Where closures really shine over other constructs is when using higher-order functions, when you actually need to communicate state, and you can make it a one-liner, as in this JavaScript example from the wikipedia page on closures:

// Return a list of all books with at least 'threshold' copies sold.
function bestSellingBooks(threshold) {
  return bookList.filter(
      function (book) { return book.sales >= threshold; }
    );
}
```

<p>Here, <code>threshold</code> is very succinctly and naturally communicated from where it is defined to where it is used.  Its scope is precisely limited as small as possible.  <code>filter</code> doesn't have to be written to allow for the possibility of passing client-defined data like a threshold.  We don't have to define any intermediate structures for the sole purpose of communicating the threshold in this one small function.  It's entirely self-contained.</p>

<p>You <em>can</em> write this without a closure, but it will require a lot more code, and be harder to follow.  Also, JavaScript has a fairly verbose lambda syntax.  In Scala, for example, the entire function body would be:</p>

<pre class="lang-scala prettyprint-override"><code>bookList filter (_.sales >= threshold)
</code>```

If you can however use ECMAScript 6, thanks to the fat arrow functions even the JavaScript code becomes much simpler and can be actually put on a single line.

const bestSellingBooks = (threshold) => bookList.filter(book => book.sales >= threshold);
```

In your own code, look for places where you generate a lot of boilerplate just to communicate temporary values from one place to another.  These are excellent opportunities to consider replacing with a closure.

Title: Why would a program use a closure?

Body:
First of all, there is nothing that is impossible without using closures.  You can always replace a closure by an object implementing a specific interface.  It's only a matter of brevity and reduced coupling.

Second, keep in mind that closures are often used inappropriately, where a simple function reference or other construct would be more clear.  You shouldn't take every example you see as a best practice.

Where closures really shine over other constructs is when using higher-order functions, when you actually need to communicate state, and you can make it a one-liner, as in this JavaScript example from the wikipedia page on closures:

// Return a list of all books with at least 'threshold' copies sold.
function bestSellingBooks(threshold) {
  return bookList.filter(
      function (book) { return book.sales >= threshold; }
    );
}

Here, threshold is very succinctly and naturally communicated from where it is defined to where it is used.  Its scope is precisely limited as small as possible.  filter doesn't have to be written to allow for the possibility of passing client-defined data like a threshold.  We don't have to define any intermediate structures for the sole purpose of communicating the threshold in this one small function.  It's entirely self-contained.

You can write this without a closure, but it will require a lot more code, and be harder to follow.  Also, JavaScript has a fairly verbose lambda syntax.  In Scala, for example, the entire function body would be:

bookList filter (_.sales >= threshold)

If you can however use ECMAScript 6, thanks to the fat arrow functions even the JavaScript code becomes much simpler and can be actually put on a single line.

const bestSellingBooks = (threshold) => bookList.filter(book => book.sales >= threshold);

In your own code, look for places where you generate a lot of boilerplate just to communicate temporary values from one place to another.  These are excellent opportunities to consider replacing with a closure.


答:
I disagree that a single function can't have a 'semantic contract'.  Consider these laws for foldr:

```<code>foldr f z nil = z
foldr f z (singleton x) = f x z
foldr f z (xn <> ys) = foldr f (foldr f z ys) xn
</code>```

In what sense is that not semantic, or not a contract?  You don't need to define a type for a 'foldrer', especially because foldr is uniquely determined by those laws.  You know exactly what it's going to do.

If you want to take in a function of some type, you can do the same thing:

```<code>-- The first argument `f` must satisfy for all x, y, z
-- > f x x = true
-- > f x y = true and f y x = true implies x = y
-- > f x y = true and f y z = true implies f x z = true
sort :: forall 'a. (a -> a -> bool.t) -> list.t a -> list.t a;
</code>```

You only need to name and capture that type if you need the same contract multiple times:

```<code>-- Type of functions `f` satisfying, for all x, y, z
-- > f x x = true
-- > f x y = true and f y x = true implies x = y
-- > f x y = true and f y z = true implies f x z = true
type comparison.t 'a = a -> a -> bool.t;
</code>```

The type-checker isn't going to enforce whatever semantics you assign to a type, so making a new type for every contract is just boilerplate.

Body:
I disagree that a single function can't have a 'semantic contract'.  Consider these laws for foldr:

foldr f z nil = z
foldr f z (singleton x) = f x z
foldr f z (xn <> ys) = foldr f (foldr f z ys) xn

In what sense is that not semantic, or not a contract?  You don't need to define a type for a 'foldrer', especially because foldr is uniquely determined by those laws.  You know exactly what it's going to do.

If you want to take in a function of some type, you can do the same thing:

-- The first argument `f` must satisfy for all x, y, z
-- > f x x = true
-- > f x y = true and f y x = true implies x = y
-- > f x y = true and f y z = true implies f x z = true
sort :: forall 'a. (a -> a -> bool.t) -> list.t a -> list.t a;

You only need to name and capture that type if you need the same contract multiple times:

-- Type of functions `f` satisfying, for all x, y, z
-- > f x x = true
-- > f x y = true and f y x = true implies x = y
-- > f x y = true and f y z = true implies f x z = true
type comparison.t 'a = a -> a -> bool.t;

The type-checker isn't going to enforce whatever semantics you assign to a type, so making a new type for every contract is just boilerplate.


答:
In general, notifyListeners is implemented as a list of delegates/observers which are just plain old functions that get called in order. So the observer functions will generally be invoked during the notifyListeners call (like your comment implies).

There are different possible implementations, some that run in parallel in background threads, some that send the request off to a queue, but the direct call is the most common.

Title: When is a event listener invoked during program execution?

Body:
I am using the Obervable-Observer Pattern.

```<code>MyClass extends Observable{

  invokeListeners(){
     doSomething;
     setChanged();
     notifyListeners();//This invokes onUpdate() in "implements Observer"

     return value;
  }
}

ClassTwo implements Observer{

   onUpdate(){
      //This is called after notifyListeners();
   }
}
</code>```

My question is when will the onUpdate method in the Listener Class get invoked? After the invokeListeners() methods completes, or right after notifyListeners()?


答:
It seems like a fairly unstandard way of building out of pages, but that doesn't necessarily mean that it's bad. This way it can be fully dynamic without being tied to the markup. I can see advantages in a highly fluid CMS, for example.

In regards to what they generate in an HTML sense, this answer seems to cover most the controls you are asking about.

Panel - Div

Panel -- GroupingText="###" is Fieldset, Legend

Label - Span

Button - Input, Type Button

Link Button - Href with JS Postback Script

Hyperlink - Standard HREF

Image Button - Input, Type Image

Textbox -- Default is Input, Type Text

Textbox -- Mode = Password is Input, type Password

Textbox -- Mode= Multiline is Textarea

DropDownList - Select

Listbox - Select

RadioButton - Input, Radio with GroupName

Checkbox - Input, Checkbox

Repeater/Listview --Complex.

Gridview - Table

Table - Table

File - Input, Type=File

I'm not sure if there are tools for finding this out exactly, but if you are ever in doubt, you can always view the source code that renders within your page for some sort of clue as to how its actually functioning. Just set up a very simple test project and check the output.

Title: ASP.NET user control best practices, programmatically or markup?

Body:
I've just started an internship with a company whose main product is an ASP.NET web forms. My related experience so far has been with Java and front end web development. My current task is to make their site responsive and more accessible for various users.

Currently I'm struggling to make sense of how each HTML page is generated. All of the user controls are programmatically generated from code behind .ascx.cs files and there is no markup in any of the .ascx files themselves.

I was wondering if this is standard practice? And are there any tools I can use to get a clearer picture of what each part generates?


问:
Why are regular expressions so morbidly attractive?
Exhibit 1, Exhibit 2, I guess you won't find it hard to recall other examples.

Thing is: if there is more than one way to solve a problem, the PHP programmer (I usually browse the PHP tag on StackOverflow) will ask for help on the solution involving regular expressions.

Even when it will be less economic, even when the php manual suggests (link) to use str_replace instead of any preg_* or ereg_* function when no fancy substitution rules are required.

Does somebody have a clue about why this happens?

Don't get me wrong, some of my best friends are regular expressions and I don't despise Perl. What I don't get is why there is no looking for alternatives whatsoever, even when the overkill is obvious (regex to switch strings) or the code complexity rises exponentially (regex for getting data from html in PHP)

答:
Regular expressions are very attractive because they are the best tool for parsing a regular language.

They have the following advantages:

They are concise. It generally takes a lot more code to parse a specific regular language using a specific algorithm that you have come up with than with a regexp.

They are quick to use. It generally takes a lot more time to write a parser for a specific regular language using a specific algorithm that you have come up with than with a regexp.

They are easy. Once you learn the set of special characters and their meanings, it is easy to compose a regexp (although a little harder to read them). Regexps are languages themselves - a useful trait because our species has evolved to be very good at language.

They are fast. Once compiled, they can match a string length N in O(N) time.

They are flexible. They can match any regular language and a lot of our data is expressed as a regular language.

They are ubiquitous. Most programming languages have basic regexp support - either through external libraries or embedded into the language itself. There is also not too much variation between the regexp languages themselves.

This makes them attractive for situations to which they are suited, but people may use them in contexts where they are not the best tool, because they:

Don't understand that what they are matching can't be expressed using a regexp (eg. HTML).

Are lazy (in a bad way) - they know a tool and recognise that it isn't the best tool for what they are doing but it will work without problems 95% of the time and takes 95% of the effort of learning a particular parser or writing one from scratch.

They are unaware that better tools exist.

ContentLicense: CC BY-SA 2.5


问:
Get license information for all used NuGet packages
To keep our house in order, I want to automatically assemble licenses for project dependencies in our documentation, rather than having to add them manually.

Does anybody know a simple way to traverse programmatically a set of CSPROJ files and extract the license information for the referenced packages as a link or string?

答:
One way I know to get such information is by using PowerShell in the Package Manager Console, from within Visual Studio.

The Package Manager Console is a PowerShell console within Visual
  Studio used to interact with NuGet and automate Visual Studio.

Basically you can use the Get-Package cmdlet to get a list of packages referenced in a specific project (or in an entire Solution). Regarding the license information for each package, for what I've seen you can only get the license URL and not just a short string representing the license type.

Here's an example for a Solution of mine returning a list of entries, each one consisting of the package identifier and the link to the license:

```<code>Get-Package | Select-Object Id,LicenseUrl
</code>```

The output is something like this:

Other elements that can be returned are documented in the Nuspec reference, in the metadata section (e.g. the version of the package, a short description, etc.).

Body:
One way I know to get such information is by using PowerShell in the Package Manager Console, from within Visual Studio.

The Package Manager Console is a PowerShell console within Visual
  Studio used to interact with NuGet and automate Visual Studio.

Basically you can use the Get-Package cmdlet to get a list of packages referenced in a specific project (or in an entire Solution). Regarding the license information for each package, for what I've seen you can only get the license URL and not just a short string representing the license type.

Here's an example for a Solution of mine returning a list of entries, each one consisting of the package identifier and the link to the license:

Get-Package | Select-Object Id,LicenseUrl

The output is something like this:

Other elements that can be returned are documented in the Nuspec reference, in the metadata section (e.g. the version of the package, a short description, etc.).


问:
How does the Hip hop virtual machine (HHVM) theoretically improve PHP runtime performance?
From a high level, how does Facebook, et. al use to improve PHP performance with the Hip Hop Virtual Machine?

How does it differ from executing code using the traditional zend engine? Is it because types are optionally defined with hack which allow for pre-optimization techniques?

My curiousity arose after reading this article, HHVM adoption.

答:
They replaced TranslatorX64’s tracelets with the new HipHop Intermediate Representation (hhir), and a new indirection layer in which resides the logic to generate hhir, which is actually referred to by the same name, hhir.

From a high level, it is using 6 instructions to do the what required 9 instructions before, as noted here: "It begins with the same typechecks but the body of the translation is 6 instructions, significantly better than the 9 from TranslatorX64"

http://hhvm.com/blog/2027/faster-and-cheaper-the-evolution-of-the-hhvm-jit

"We solved this problem by adding a new layer of indirection. This new
  layer is an SSA form intermediate representation, positioned between
  the bytecodes in TranslatorX64’s tracelets and the x86 machine code we
  want to end up with. It’s strongly typed and designed to facilitate a
  number of optimizations we wanted to port from TranslatorX64 as well
  as new optimizations in the future. This new IR, named hhir (short for
  HipHop Intermediate Representation), completely replaced TranslatorX64
  as hhvm’s JIT in May of 2013. While hhir specifically refers to the
  representation itself, we often use the name to refer to all the
  pieces of code that interact with it. If you’ve looked at our source
  code recently you might have noticed that a class named TranslatorX64
  still exists and contains a nontrivial amount of code. That’s mostly
  an artifact of how the system is designed and is something we plan to
  eventually clean up. All of the code left in TranslatorX64 is
  machinery required to emit code and link translations together; the
  code that understood how to translate individual bytecodes is gone
  from TranslatorX64.

When hhir replaced TranslatorX64, it was generating code that was
  roughly 5% faster and looked significantly better upon manual
  inspection. We followed up its production debut with another
  mini-lockdown and got an additional 10% in performance gains on top of
  that. To see some of these improvements in action, let’s look at a
  function addPositive and part of its translation.

function addPositive($arr) {
      $n = count($arr);
      $sum = 0;
      for ($i = 0; $i < $n; $i++) {
        $elem = $arr[$i];
        if ($elem > 0) {
          $sum = $sum + $elem;
        }
      }
      return $sum;
    }
```

  <p>This function looks like a lot of PHP code: it loops over an array and
  does something with each element. Let’s focus on lines 5 and 6 for
  now, along with their bytecode:</p>

```    $elem = $arr[$i];
    if ($elem > 0) {
  // line 5
   85: CGetM <L:0 EL:3>
   98: SetL 4
  100: PopC
  // line 6
  101: Int 0
  110: CGetL2 4
  112: Gt
  113: JmpZ 13 (126)
```

  <p>These two lines load an element from an array, store it in a local
  variable, then compare the value of that local with 0 and
  conditionally jump somewhere based on the result. If you’re interested
  in more detail about what’s going on in the bytecode, you can skim
  through bytecode.specification. The JIT, both now and back in the
  TranslatorX64 days, breaks this code up into two tracelets: one with
  just the CGetM, then another with the rest of the instructions (a full
  explanation of why this happens isn’t relevant here, but it’s mostly
  because we don’t know at compile time what the type of the array
  element will be). The translation of the CGetM boils down to a call to
  a C++ helper function and isn’t very interesting, so we’ll be looking
  at the second tracelet. This commit was TranslatorX64’s official
  retirement, so let’s use its parent to see how TranslatorX64
  translated this code.</p>

```  cmpl  $0xa, 0xc(%rbx)
  jnz 0x276004b2
  cmpl  $0xc, -0x44(%rbp)
  jnle 0x276004b2
101: SetL 4
103: PopC
  movq  (%rbx), %rax
  movq  -0x50(%rbp), %r13
104: Int 0
  xor %ecx, %ecx
113: CGetL2 4
  mov %rax, %rdx
  movl  $0xa, -0x44(%rbp)
  movq  %rax, -0x50(%rbp)
  add $0x10, %rbx
  cmp %rcx, %rdx
115: Gt
116: JmpZ 13 (129)
  jle 0x7608200
```

  <p>The first four lines are typechecks verifying that the value in $elem
  and the value on the top of the stack are the types we expect. If
  either of them fails, we’ll jump to code that triggers a retranslation
  of the tracelet, using the new types to generate a differently
  specialized chunk of machine code. The meat of the translation
  follows, and the code has plenty of room for improvement. There’s a
  dead load on line 8, an easily avoidable register to register move on
  line 12, and an opportunity for constant propagation between lines 10
  and 16. These are all consequences of the bytecode-at-a-time approach
  used by TranslatorX64. No respectable compiler would ever emit code
  like this, but the simple optimizations required to avoid it just
  don’t fit into the TranslatorX64 model.</p>

  <p>Now let’s see the same tracelet translated using hhir, at the same
  hhvm revision:</p>

```  cmpl  $0xa, 0xc(%rbx)
  jnz 0x276004bf
  cmpl  $0xc, -0x44(%rbp)
  jnle 0x276004bf
101: SetL 4
  movq  (%rbx), %rcx
  movl  $0xa, -0x44(%rbp)
  movq  %rcx, -0x50(%rbp)
115: Gt
116: JmpZ 13 (129)
  add $0x10, %rbx
  cmp $0x0, %rcx
  jle 0x76081c0
```

  <p>It begins with the same typechecks but the body of the translation is
  6 instructions, significantly better than the 9 from TranslatorX64.
  Notice that there are no dead loads or register to register moves, and
  the immediate 0 from the Int 0 bytecode was propagated down to the cmp
  on line 12. Here’s the hhir that was generated between the tracelet
  and that translation:</p>

```  (00) DefLabel
  (02) t1:FramePtr = DefFP
  (03) t2:StkPtr = DefSP<6> t1:FramePtr
  (05) t3:StkPtr = GuardStk<Int,0> t2:StkPtr
  (06) GuardLoc<Uncounted,4> t1:FramePtr
  (11) t4:Int = LdStack<Int,0> t3:StkPtr
  (13) StLoc<4> t1:FramePtr, t4:Int
  (27) t10:StkPtr = SpillStack t3:StkPtr, 1
  (35) SyncABIRegs t1:FramePtr, t10:StkPtr
  (36) ReqBindJmpLte<129,121> t4:Int, 0
```

The bytecode instructions have been broken down into smaller, simpler
  operations. Many operations hidden in the behavior of certain
  bytecodes are explicitly represented in hhir, such as the LdStack on
  line 6 which is part of the SetL. By using unnamed temporaries (t1,
  t2, etc…) instead of physical registers to represent the flow of
  values, we can easily track the definition and use(s) of each value.
  This makes it trivial to see if the destination of a load is actually
  used, or if one of the inputs to an instruction is really a constant
  value from 3 bytecodes ago. For a much more thorough explanation of
  what hhir is and how it works, take a look at ir.specification.

This example showed just a few of the improvements hhir made over
  TranslatorX64. Getting hhir deployed to production and retiring
  TranslatorX64 in May 2013 was a great milestone to hit, but it was
  just the beginning. Since then, we’ve implemented many more
  optimizations that would be nearly impossible in TranslatorX64, making
  hhvm almost twice as efficient in the process. It’s also been crucial
  in our efforts to get hhvm running on ARM processors by isolating and
  reducing the amount of architecture-specific code we need to
  reimplement. Watch for an upcoming post devoted to our ARM port for
  more details!"

Body:
They replaced TranslatorX64’s tracelets with the new HipHop Intermediate Representation (hhir), and a new indirection layer in which resides the logic to generate hhir, which is actually referred to by the same name, hhir.

From a high level, it is using 6 instructions to do the what required 9 instructions before, as noted here: "It begins with the same typechecks but the body of the translation is 6 instructions, significantly better than the 9 from TranslatorX64"

http://hhvm.com/blog/2027/faster-and-cheaper-the-evolution-of-the-hhvm-jit

"We solved this problem by adding a new layer of indirection. This new
  layer is an SSA form intermediate representation, positioned between
  the bytecodes in TranslatorX64’s tracelets and the x86 machine code we
  want to end up with. It’s strongly typed and designed to facilitate a
  number of optimizations we wanted to port from TranslatorX64 as well
  as new optimizations in the future. This new IR, named hhir (short for
  HipHop Intermediate Representation), completely replaced TranslatorX64
  as hhvm’s JIT in May of 2013. While hhir specifically refers to the
  representation itself, we often use the name to refer to all the
  pieces of code that interact with it. If you’ve looked at our source
  code recently you might have noticed that a class named TranslatorX64
  still exists and contains a nontrivial amount of code. That’s mostly
  an artifact of how the system is designed and is something we plan to
  eventually clean up. All of the code left in TranslatorX64 is
  machinery required to emit code and link translations together; the
  code that understood how to translate individual bytecodes is gone
  from TranslatorX64.

When hhir replaced TranslatorX64, it was generating code that was
  roughly 5% faster and looked significantly better upon manual
  inspection. We followed up its production debut with another
  mini-lockdown and got an additional 10% in performance gains on top of
  that. To see some of these improvements in action, let’s look at a
  function addPositive and part of its translation.

function addPositive($arr) {
      $n = count($arr);
      $sum = 0;
      for ($i = 0; $i < $n; $i++) {
        $elem = $arr[$i];
        if ($elem > 0) {
          $sum = $sum + $elem;
        }
      }
      return $sum;
    }

This function looks like a lot of PHP code: it loops over an array and
  does something with each element. Let’s focus on lines 5 and 6 for
  now, along with their bytecode:

    $elem = $arr[$i];
    if ($elem > 0) {
  // line 5
   85: CGetM <L:0 EL:3>
   98: SetL 4
  100: PopC
  // line 6
  101: Int 0
  110: CGetL2 4
  112: Gt
  113: JmpZ 13 (126)

These two lines load an element from an array, store it in a local
  variable, then compare the value of that local with 0 and
  conditionally jump somewhere based on the result. If you’re interested
  in more detail about what’s going on in the bytecode, you can skim
  through bytecode.specification. The JIT, both now and back in the
  TranslatorX64 days, breaks this code up into two tracelets: one with
  just the CGetM, then another with the rest of the instructions (a full
  explanation of why this happens isn’t relevant here, but it’s mostly
  because we don’t know at compile time what the type of the array
  element will be). The translation of the CGetM boils down to a call to
  a C++ helper function and isn’t very interesting, so we’ll be looking
  at the second tracelet. This commit was TranslatorX64’s official
  retirement, so let’s use its parent to see how TranslatorX64
  translated this code.

  cmpl  $0xa, 0xc(%rbx)
  jnz 0x276004b2
  cmpl  $0xc, -0x44(%rbp)
  jnle 0x276004b2
101: SetL 4
103: PopC
  movq  (%rbx), %rax
  movq  -0x50(%rbp), %r13
104: Int 0
  xor %ecx, %ecx
113: CGetL2 4
  mov %rax, %rdx
  movl  $0xa, -0x44(%rbp)
  movq  %rax, -0x50(%rbp)
  add $0x10, %rbx
  cmp %rcx, %rdx
115: Gt
116: JmpZ 13 (129)
  jle 0x7608200

The first four lines are typechecks verifying that the value in $elem
  and the value on the top of the stack are the types we expect. If
  either of them fails, we’ll jump to code that triggers a retranslation
  of the tracelet, using the new types to generate a differently
  specialized chunk of machine code. The meat of the translation
  follows, and the code has plenty of room for improvement. There’s a
  dead load on line 8, an easily avoidable register to register move on
  line 12, and an opportunity for constant propagation between lines 10
  and 16. These are all consequences of the bytecode-at-a-time approach
  used by TranslatorX64. No respectable compiler would ever emit code
  like this, but the simple optimizations required to avoid it just
  don’t fit into the TranslatorX64 model.

Now let’s see the same tracelet translated using hhir, at the same
  hhvm revision:

  cmpl  $0xa, 0xc(%rbx)
  jnz 0x276004bf
  cmpl  $0xc, -0x44(%rbp)
  jnle 0x276004bf
101: SetL 4
  movq  (%rbx), %rcx
  movl  $0xa, -0x44(%rbp)
  movq  %rcx, -0x50(%rbp)
115: Gt
116: JmpZ 13 (129)
  add $0x10, %rbx
  cmp $0x0, %rcx
  jle 0x76081c0

It begins with the same typechecks but the body of the translation is
  6 instructions, significantly better than the 9 from TranslatorX64.
  Notice that there are no dead loads or register to register moves, and
  the immediate 0 from the Int 0 bytecode was propagated down to the cmp
  on line 12. Here’s the hhir that was generated between the tracelet
  and that translation:

  (00) DefLabel
  (02) t1:FramePtr = DefFP
  (03) t2:StkPtr = DefSP<6> t1:FramePtr
  (05) t3:StkPtr = GuardStk<Int,0> t2:StkPtr
  (06) GuardLoc<Uncounted,4> t1:FramePtr
  (11) t4:Int = LdStack<Int,0> t3:StkPtr
  (13) StLoc<4> t1:FramePtr, t4:Int
  (27) t10:StkPtr = SpillStack t3:StkPtr, 1
  (35) SyncABIRegs t1:FramePtr, t10:StkPtr
  (36) ReqBindJmpLte<129,121> t4:Int, 0

The bytecode instructions have been broken down into smaller, simpler
  operations. Many operations hidden in the behavior of certain
  bytecodes are explicitly represented in hhir, such as the LdStack on
  line 6 which is part of the SetL. By using unnamed temporaries (t1,
  t2, etc…) instead of physical registers to represent the flow of
  values, we can easily track the definition and use(s) of each value.
  This makes it trivial to see if the destination of a load is actually
  used, or if one of the inputs to an instruction is really a constant
  value from 3 bytecodes ago. For a much more thorough explanation of
  what hhir is and how it works, take a look at ir.specification.

This example showed just a few of the improvements hhir made over
  TranslatorX64. Getting hhir deployed to production and retiring
  TranslatorX64 in May 2013 was a great milestone to hit, but it was
  just the beginning. Since then, we’ve implemented many more
  optimizations that would be nearly impossible in TranslatorX64, making
  hhvm almost twice as efficient in the process. It’s also been crucial
  in our efforts to get hhvm running on ARM processors by isolating and
  reducing the amount of architecture-specific code we need to
  reimplement. Watch for an upcoming post devoted to our ARM port for
  more details!"