问:
How is IntelliJ better than Eclipse?
I know there have been questions like What is your favorite editor/IDE?, but none of them have answered this question: Why spend the money  on IntelliJ when Eclipse is free?

I'm personally a big IntelliJ fan, but I haven't really tried Eclipse. I've used IntelliJ for projects that were Java, JSP, HTML/CSS, Javascript, PHP, and Actionscript, and the latest version, 9, has been excellent for all of them.

Many coworkers in the past have told me that they believe Eclipse to be "pretty much the same" as IntelliJ, but, to counter that point, I've occasionally sat behind a developer using Eclipse who's seemed  comparably inefficient (to accomplish roughly the same task), and I haven't experienced this with IntelliJ. They may be on par feature-by-feature but features can be ruined by a poor user experience, and I wonder if it's possible that IntelliJ is easier to pick up and discover time-saving features.

For users who are already familiar with Eclipse, on top of the real cost of IntelliJ, there is also the cost of time spent learning the new app. Eclipse gets a lot of users who simply don't want to spend $250 on an IDE.

If IntelliJ really could help my team be more productive, how could I sell it to them? For those users who've tried both, I'd be very interested in specific pros or cons either way.

答:
You need to demonstrate vividly and without doubt that for the tasks you need to do on a daily basis, IntelliJ allows for a substantially amount of time and effort saved as opposed to Eclipse (and NetBeans).

This will require you to do some research to find out what that might be, and then construct a demonstration showing this to the people who can decide how to work.

My suspicion is that you will find this a rather hard task to do, as Eclipse these days can do quite a bit, reasonably well.  If you find killer points, please share - I'm sure plenty want to know.

Title: How is IntelliJ better than Eclipse?


问:
How effective are code signing certificates when it comes to customer behavior or acceptance?
Whenever a potential customer downloads a copy of my software they get the "Unknown Publisher" warning message. I understand that if I purchase a code signing certificate this message goes away and the customer does not get the scary warning.

I'd like to know if anyone has information on how effective these code signing certificates are with regard to customer behavior. What difference did you see in customer behavior or acceptance after you signed your code using a certificate?

答:
To me "Unknown Publisher" is a red flag.  It's one more bit of "polish" on your application.

There's a story about a famous rock band that would give the venue a long list of requirements - things like how many electrical connections they needed, the size of the stage, placement of lights, distance to dressing rooms, etc.

Included in that list was a requirement for a bowl of M&M's candies with all the brown ones removed.

The band couldn't care less about the candies, but the chief roadie knew if he saw a brown M&M then he couldn't trust the venue to do anything else right either.

tl;dr

As a customer I'd expect you to remove that scary message by buying and using the certificate.  If you haven't done that yet, I have to wonder what else is incomplete.

ContentLicense: CC BY-SA 3.0


问:
Is it an implementation of a stateful mechanism for Rest API authentication?
In many articles about Rest API's best practices, it is recommended to not depend upon sessions on server side since it leads to a stateful mechanism.

I currently use Play 2.2 framework, with a mechanism that store the data about logged in user in the Play cache (temporary persistent so).

When the user wants to authenticate, it calls a dedicated API that grabs its credentials and if valid, server generates a cookie that will be sent to him. This cookie contains a reference id of the user's data in the Play's cache.

Then, each time a user calls an API requiring user authentication, server grabs the user cookie (if any), asks for the cache and checks in there whether user is well already authenticated regarding the validation duration.

Here a little sample:

```<code>def myApi = userAuthenticatorRequest.securedAction {    //user has to be already logged in
    implicit request =>
      //do something
  }
</code>```

Should I leave from this solution in order to be compliant with best practices, or should I keep it?
Is it really considered as a stateful mechanism?
If I understand, this is stateful since a call to a secured API required actually two calls:

authentication api

secured api

while a stateless would authenticate user directly in the secured api, and thus would be totally independent of any context. Of course, user would have to sent each time its credentials (or API key)

答:
If I understand, this is stateful since a call to a secured API required actually two calls

This is stateful because the information „user X has been authenticated at time T“ is maintained on the server side.

Of course, user would have to sent each time its credentials (or API key)

A user can also sign each request to attest her identity, thus proving the server she can access some private key.


问:
Template Functions and Function templates in C++
I came across a question which asked the difference between Function Templates and Template Functions in C++ and also Template Classes and Class Templates.

I was under the impression that Function Templates and Template Functions were the same thing. Is there any difference between the two, if so what is it?

答:
There is a difference between function template and template function.

```<code>template<class Type>
void Foo(Type tData) {...}
</code>```

if you wanted to pass int to function template Foo, but you also wanted the compiler to instantiate it as if it was passed a double you would call:

```<code>Foo<double> ( 12 );
</code>```

Which instantiates the following template function:

```<code>void Foo(double);
</code>```

With this special syntax Foo<>(), you are demanding compiler to instantiate Foo function for the type being explicitly passed, and asking the compiler not to deduce type by function argument.

A function template is body of a function that is bracketed around template keyword, which is not an actual function, and will not be fully compiled by compiler, and is not accountable by the linker. At least one call, for particular data-type(s) is needed to instantiate it, and be put into accountability of compiler and linker. Therefore, the instance of function template Foo is instantiated as Foo(int) or Foo(double).

A template function is simply an "instance of a function template", which is produced when you call it, or cause it to get instantiated for particular data type. The instance of function-template is actually a valid function.

An instance of a function template (aka template-function) is not a normal function, under the umbrella of name-decoration system of compiler and linker. That means, an instance of function-template:

```<code>template<class T>
void Foo(T data) {...}
</code>```

for template argument double, it is not:

```<code>void Foo(double data) {...}
</code>```

but actually:

```<code>void Foo<double>(double x) {...}
</code>```

You can read more here:

Template terms

Template Tutorial

Body:
There is a difference between function template and template function.

template<class Type>
void Foo(Type tData) {...}

if you wanted to pass int to function template Foo, but you also wanted the compiler to instantiate it as if it was passed a double you would call:

Foo<double> ( 12 );

Which instantiates the following template function:

void Foo(double);

With this special syntax Foo<>(), you are demanding compiler to instantiate Foo function for the type being explicitly passed, and asking the compiler not to deduce type by function argument.

A function template is body of a function that is bracketed around template keyword, which is not an actual function, and will not be fully compiled by compiler, and is not accountable by the linker. At least one call, for particular data-type(s) is needed to instantiate it, and be put into accountability of compiler and linker. Therefore, the instance of function template Foo is instantiated as Foo(int) or Foo(double).

A template function is simply an "instance of a function template", which is produced when you call it, or cause it to get instantiated for particular data type. The instance of function-template is actually a valid function.

An instance of a function template (aka template-function) is not a normal function, under the umbrella of name-decoration system of compiler and linker. That means, an instance of function-template:

template<class T>
void Foo(T data) {...}

for template argument double, it is not:

void Foo(double data) {...}

but actually:

void Foo<double>(double x) {...}

You can read more here:

Template terms

Template Tutorial


问:
Data duplication vs Encapsulating. Which design to use?
The problem that I face is how to combine encapsulating and optimal memory use.

I can't show you my code and therefore explain it on extensive (I hope) example.

Let's say we need to have a database of mans. We want to know only 2 things about those people:

Age of the man (in hours from birth).

Name of the town he lives in.

The convenient and natural way to manage this data is to create an object, which corresponds to a man and store it in an array:

```<code>class OMan1 {
  public:
    OMan( const int &age, const astring &t ): fAge(age), fTown(t) {}
    const int& age() const: { return fAge; }
    const astring& Town() const: { return fTown; }
    astring FullId() const: { return fTown+fAge; }
  private:
    int fAge;
    astring fTown;
}

OMan mans[N];
</code>```

Here our OMans are self-containing object and everything fills nice.

Except of the fact that we clone names of the towns thousands of times, and waste memory and execution time this way.

An improvement we can do is to make an independent array for town names and for each OMan, store only the age, an id of the town and a pointer to towns array:

```<code>class OMan2 {
  // same functionality as for OMan1
    int fAge;
    int fTownId;
    astring* fTowns;
}
</code>```

object is still self-contained, sizeof(int) + sizeof(void*) is much less then sizeof(astring), we win a lot. But still it is factor of 2-3 more than sizeof(fAge) and we repeat fTowns billions of times.

Memory optimisation is crucial for me, therefore what I do is keeping only fAge and fTownId and move such functionality as Town() and FullId() out of the OMan class to some class like OManDataBase:

```<code>class OMan3 {
  public:
    OMan( const int &age, const int &tid ): fAge(age), fTownId(tid) {}
    const int& age() const: { return fAge; }
    const int& TownId() const: { return fId; }
    // const astring& Town() const: { return fTown; }
    // astring FullId() const: { return fTown+fAge; }
  private:
    int fAge;
    int fTownId;
}

class OManDataBase {
  // constructor, destructor
    const int& age( const int& i) const: { return fMans[i].TownId()]; }
    const astring& Town( const int& i) const: { return fTown[fMans[i].TownId()]; }
    const astring& FullId( const int& i) const: { return Town(i)+age(i); }
  private:
    vector<OMan3> fMans;
    vector<astring> fTowns;
}
</code>```

And OMan3 now is not self contained object. It doesn't know it's fullname, for instance. That means that if I need to do some data processing with one man I have to use whole OManDataBase instance:

```<code>OBillType47 NewBillType47( const OManDataBase &db, int i ) { ... }
</code>```

instead of

```<code>OBillType47 NewBillType47( const OMan &m ) { ... }
</code>```

encapsulation has been broken here and the code readability has been clearly decreased. (I put Type47 to emphasise that I can have a lot of functions, which works with Oman-S and can't include all of them into OManDataBase class).

I wonder is there any other way(-s) to solve data duplication problem, keeping objects as self-containing as possible?

答:
Here's some naive advice I hope you find helpful to conserve memory...

Solution 1

Instead of using a C++ class to store the data, use "packed" structures (look at the documentation for your compiler to figure out how to create a packed structure, there's usually a compiler flag involved). Then limit the size of your variables memory footprints, for instance a uint8 should be big enough to store a mans age. Once you've done this store the packed structure in a c style array (for maximum compression) or use std::vector<OManStruct> if you want to make your life easier. Instead of storing the name of the town as a string in the struct, create a std::map<uint32_t, string> that maps townIds to town names. Store the townId in the struct.

Your struct definition might look something like this (if your using GCC):

```<code>typedef struct __attribute__((__packed__)) OManStruct
{
    uint8_t fAge;
    uint32_t fTownId; //maybe you could use uint16_t here but you might be cutting it close
};
</code>```

Architecturally I would wrap the knowledge of these data structures in a class that maintains the array, associated data (number of elements etc), and exposes some nice getters and setters so the outside world doesn't know about this implementation detail. Or better yet create, an OManFactory which can be treated as a singleton in your project and returns OMan objects on request.

Solution 2

You might want to seriously consider databasing your data using SQLite, Postgres etc or some nosql database like Redis.. If the amount of data is going to grow over time there's no guarantee you might not blow through all your ram even if you implement solution 1. A database would also give you the ability to store the data persistently and give you a nice mechanism (if using an sql type database) for doing queries on the data.

Body:
Here's some naive advice I hope you find helpful to conserve memory...

Solution 1

Instead of using a C++ class to store the data, use "packed" structures (look at the documentation for your compiler to figure out how to create a packed structure, there's usually a compiler flag involved). Then limit the size of your variables memory footprints, for instance a uint8 should be big enough to store a mans age. Once you've done this store the packed structure in a c style array (for maximum compression) or use std::vector<OManStruct> if you want to make your life easier. Instead of storing the name of the town as a string in the struct, create a std::map<uint32_t, string> that maps townIds to town names. Store the townId in the struct.

Your struct definition might look something like this (if your using GCC):

typedef struct __attribute__((__packed__)) OManStruct
{
    uint8_t fAge;
    uint32_t fTownId; //maybe you could use uint16_t here but you might be cutting it close
};

Architecturally I would wrap the knowledge of these data structures in a class that maintains the array, associated data (number of elements etc), and exposes some nice getters and setters so the outside world doesn't know about this implementation detail. Or better yet create, an OManFactory which can be treated as a singleton in your project and returns OMan objects on request.

Solution 2

You might want to seriously consider databasing your data using SQLite, Postgres etc or some nosql database like Redis.. If the amount of data is going to grow over time there's no guarantee you might not blow through all your ram even if you implement solution 1. A database would also give you the ability to store the data persistently and give you a nice mechanism (if using an sql type database) for doing queries on the data.


问:
Is it possible to be good at both programming and graphic design?
The stereotypical view of a programmer can't do graphics very well, from what I've read and seen. However, I love programming (preferably OOP, PHP, C++, Objective-C) and can't deny the fact I have a unique taste in web design and others have said I am doing well at it (CSS). I thought to myself "Hey, wait, I'm a programmer - how can I design well?". Question is: is it possible to be good at programming and designing? Does anyone here feel the same?

For the record: actual images I have created have been called programmer art several times before by friends

答:
An area to look to for people who are both technically proficient and good at art is effects work and lighting/compositing in film and commercial visual effects. In a production pipeline, you can very easily find the full spectrum of software developers to Technical Directors to CG artists, all of whom are technically proficient, and have as well the ability to communicate visual ideas, with a sense for color, layout, or timing in use, depending on specialty.

Particular areas that draw people good on both ends: effects TD's (particularly fluids, and cloth/hair), shading TD's, vfx supervisors.

ContentLicense: CC BY-SA 2.5


问:
Does Java development typically involve more subclassing than C#/.NET?
I've recently started looking at Android development. This has brought me back into the world of Java software development. The last time I worked with Java, I'll admit, I didn't understand OOP nearly as much as (I think) I do now.

Having mainly used C# in my career, I'm noticing a startling difference in how inheritance is used Java and C#.

In C# it seemed like inheritance could be avoided in most situations. The task at hand could usually be accomplished by using concrete classes of the .NET framework.

In Java, from what I'm gathering from code samples, it seems like the Java framework supplies many interfaces or abstract classes that are then meant to be implemented/extended by the developer.

This seems to be too big a difference to just boil down to style. What is the reasoning behind this? I feel like I won't be writing clean Java code until I understand this.

Also, is this limited to just the Android SDK or is this a Java-wide approach to OOP?

Or put in another way,

What is it about the design of these two languages that (seems to encourage) more or less inheritance use than the other?

If the languages treat inheritance identically, and assuming my observation is valid, then it means this is related to the design of the frameworks/libraries and not the languages. What would the motivation be for this kind of design?

答:
There is absolutely no difference in the way inheritance is handled between Java and C#. When you will actually use inheritance or composition is definetely a design decision and by no way is something that Java or C# encourages or discourages. I would kindly suggest reading this article.

Hope I helped!


答:
This seems to be too big a difference to just boil down to style. What is the reasoning behind this?

My understanding is that it largely is simply a stylistic decision. Well, perhaps not style, but the idioms of the language/environment. Java standard library developers followed one set of design guidelines and the .NET developers another (though they had the ability to see how Java's approach worked).

There is very little in the actual languages to encourage or dissuade inheritence. Only two things strike me as relevant:

.NET introduced generics earlier in their lifetime, before too much non-generic code was implemented. The alternative is a lot of inheritence to type specialize things.

A larger change was that .NET supported delegates. In Java you're stuck with (anonymous) inheritence to supply the most basic of variable functionality. This leads to a relatively large difference in how code is designed to either take advantage of delegates or to avoid the awkward inheritance structures needed to do it in Java.

Title: Does Java development typically involve more subclassing than C#/.NET?

Body:
I've recently started looking at Android development. This has brought me back into the world of Java software development. The last time I worked with Java, I'll admit, I didn't understand OOP nearly as much as (I think) I do now.

Having mainly used C# in my career, I'm noticing a startling difference in how inheritance is used Java and C#.

In C# it seemed like inheritance could be avoided in most situations. The task at hand could usually be accomplished by using concrete classes of the .NET framework.

In Java, from what I'm gathering from code samples, it seems like the Java framework supplies many interfaces or abstract classes that are then meant to be implemented/extended by the developer.

This seems to be too big a difference to just boil down to style. What is the reasoning behind this? I feel like I won't be writing clean Java code until I understand this.

Also, is this limited to just the Android SDK or is this a Java-wide approach to OOP?

Or put in another way,

What is it about the design of these two languages that (seems to encourage) more or less inheritance use than the other?

If the languages treat inheritance identically, and assuming my observation is valid, then it means this is related to the design of the frameworks/libraries and not the languages. What would the motivation be for this kind of design?


问:
Better style for member variables?
```<code>class awesomeClass {
    std::list<A> myList;
    //...
    void fillList();
};

awesomeClass::awesomeClass() {
    fillList();
}

void awesomeClass::fillList(){
    //...
    foreach(A a, otherList)
        myList.push_back(a); //add to list
}
</code>```

Compared to :

```<code>awesomeClass::awesomeClass() {
    myList = fillList();
}

std::list<A>& awesomeClass::fillList() {
    //...
    std::list<A> ret;
    foreach(A a, otherList)
        ret.push_back(a); //add to list
    return ret;
}
</code>```

This is just a class with an std::list as a member variable and a function which fills this list. The first fills it inside the function and the second one returns a list and assigns it to the member list.

Which of these is better style? The one which fills the list inside the function or the one which returns a list? Or is there an even better solution?

答:
If all you are doing is copying a list, I would use the range constructor.

c++11

```<code>AwesomeClass::AwesomeClass (const std::list &otherList)
: myList (std::begin (otherList), std::end (otherList))
{
}
</code>```

c++

```<code>AwesomeClass::AwesomeClass (const std::list &otherList)
: myList (otherList.begin (), otherList.end ())
{
}
</code>```

OwnerDisplayName: Davlog

Title: Better style for member variables?

Body:
If all you are doing is copying a list, I would use the range constructor.

c++11

AwesomeClass::AwesomeClass (const std::list &otherList)
: myList (std::begin (otherList), std::end (otherList))
{
}

c++

AwesomeClass::AwesomeClass (const std::list &otherList)
: myList (otherList.begin (), otherList.end ())
{
}


问:
Why REST Api do not follow the Facade design pattern
In comparing REST [api] structure with a OO model, I see these similarities:

Both:

Are data oriented

REST = Resources

OO = Objects

Surround operation around data

REST = surround VERBS (Get, Post, ...) around resources

OO = promote operation around objects by encapsulation

However, good OO practices do not always stand on REST apis when trying to apply the facade pattern for instance:
   in REST, you do not have 1 controller to handle all requests AND you do not hide internal object complexity.

On the contrary, REST promotes resources publishing of all relations with a resource and other on at least two forms:

via resource hierarchy relations (A contact of id 43 is composed of an address 453) : /api/contacts/43/addresses/453

via links in a REST json response:

```<code>>> GET /api/contacts/43
<< HTTP Response {
   id: 43, ...
   addresses: [{
      id: 453, ...
   }],
   links: [{
      favoriteAddress: {
          id: 453
      }
   }]
}
</code>```

Coming back to OO, the facade design pattern respect a Low Coupling between an objectA and its 'objectB client' and High Cohesion for this objectA and its internal object composition (objectC, objectD).  With the objectA interface, this allow a developer to limit impact on objectB of the objectA internal changes (in objectC and objectD), as long as the objectA api (operations) are still respected.

In REST, the data (resource), the relations (links), and the behavior (verbs) are exploded in different elements and available to the web.

Playing with REST, I always have an impact on code changes between my client and server:   Because I have High Coupling between my Backbone.js requests and Low Cohesion between resources.

I never figured out how to let my Backbone.js javascript application deal with "REST resources and features" discovery promoted by REST links.  I understand that the WWW is meant to be served by multi servers, and that the OO elements had to be exploded to be serviced by many hosts in there, but for a simple scenario like "saving" a page showing a contact with its addresses, I end up with:

```<code>GET /api/contacts/43?embed=(addresses)
[save button pressed]
PUT /api/contacts/43
PUT /api/contacts/43/addresses/453
</code>```

which lead me to move the saving action atomic transactional responsibility on the browsers applications (since two resources can be addressed separately).

With this in mind, if I cannot simplify my development (Facade design patterns not applicable), and if I bring more complexity to my client (handling transactional atomic save), where is the benefit of being RESTful ?

答:
I think objects are only built correctly around coherent behaviors and not around data. I will provoke and say that data is almost irrelevant in the object oriented world. In fact, it's possible and sometime common to have objects that never return data, for example "log sinks", or objects that never return the data they are passed, for example if they calculate statistical properties.

Let us not confuse the PODS, (which are little more than structures), and the real objects that have behaviors (like the Contacts class in your example)1.

PODS are basically a convenience used to talk to repositories and business objects. They allow the code to be type safe. No more, no less. Business objects, on the other hand, provide concrete behaviors, like validating your data, or storing it, or using it to perform a calculation.

So, behaviors are what we use to measure "cohesion"2, and it's easy enough to see that in your object example there is some cohesion, even though you only show methods to manipulate top level contacts and no methods to manipulate addresses.

Regarding REST, you can see REST services as data repositories. The big difference with object oriented design is that there is (almost) only one design choice: you have four basic methods (more if you count HEAD, for example) and of course you have a lot of leeway with the URIs so you can do nifty stuff like pass many ids and get a larger structure back. Do not confuse the data they pass with the operations they perform. Cohesion and coupling are about code and not data.

Clearly, REST services have high cohesion (every way to interact with a resource is in the same place) and low coupling (every resource repository does not require knowledge of the others).

The basic fact remains, though, REST is essentially a single repository pattern for your data. This has consequences, because it's a paradigm built around easy accessibility over a slow medium, where there is a high cost for "chattiness": clients typically want to perform as few operations as possible, but at the same time only receive the data they need. This determines how deep an data tree you are going to send back.

In (correct) object oriented design, any non-trivial application will do much more complex operations, for example through composition. You could have methods for doing more specialized operations with the data -- which must be so, because while REST is an API protocol, OOD is used to build entire user facing applications! This is why measuring cohesion and coupling is fundamental in OOD, but almost insignificant in REST.

It should be obvious by now that analyzing data design with OO concepts is not a reliable way to measure it: it's like comparing apples and oranges!

In fact, it turns out that the benefits of being RESTful are (mostly) the ones outlined above: it's a good pattern for simple APIs over a slow medium. It is very cacheable, and shardable. It has fine grained control over chattiness, etc.

I hope this answers your (quite multifaceted) question :-)

1 This problem is part of a larger set of problems known as Object-Relational impedance mismatch. Proponents of ORMs are generally in the camp that explores the similarities between data analysis and behavior analysis, but ORMs have fallen under criticism of late because they seem not to really resolve the impedance mismatch and are considered leaky abstractions.

2 http://en.wikipedia.org/wiki/Cohesion_(computer_science)

OwnerDisplayName: Alain


答:
If you understand your REST service, or in general any kind of API, just as an additional interface exposed to clients so they can program your controller(s) through it, it suddenly becomes easy. The service is nothing more than an additional layer on top of your biz logic.

In other words, you don't have to split biz logic between multiple controllers, like you did in your picture above, and more importantly, you shouldn't. The data structures that are used to interchange data do not need to match the data structures you use internally, they can be quite different.

It is state of the art, and widely accepted, that it is a bad idea to put any biz logic into UI code. But every UI is just an kind of interface (the I in UI) to control the biz logic behind. Consequently, it seems obvious that is is also a bad idea to put any biz logic into the REST service layer, or any other API layer whatsoever.

Conceptually speaking, there's not that much of a difference between UI and service API.

Title: Why REST Api do not follow the Facade design pattern

Body:
In comparing REST [api] structure with a OO model, I see these similarities:

Both:

Are data oriented

REST = Resources

OO = Objects

Surround operation around data

REST = surround VERBS (Get, Post, ...) around resources

OO = promote operation around objects by encapsulation

However, good OO practices do not always stand on REST apis when trying to apply the facade pattern for instance:
   in REST, you do not have 1 controller to handle all requests AND you do not hide internal object complexity.

On the contrary, REST promotes resources publishing of all relations with a resource and other on at least two forms:

via resource hierarchy relations (A contact of id 43 is composed of an address 453) : /api/contacts/43/addresses/453

via links in a REST json response:

```<code>>> GET /api/contacts/43
<< HTTP Response {
   id: 43, ...
   addresses: [{
      id: 453, ...
   }],
   links: [{
      favoriteAddress: {
          id: 453
      }
   }]
}
</code>```

Coming back to OO, the facade design pattern respect a Low Coupling between an objectA and its 'objectB client' and High Cohesion for this objectA and its internal object composition (objectC, objectD).  With the objectA interface, this allow a developer to limit impact on objectB of the objectA internal changes (in objectC and objectD), as long as the objectA api (operations) are still respected.

In REST, the data (resource), the relations (links), and the behavior (verbs) are exploded in different elements and available to the web.

Playing with REST, I always have an impact on code changes between my client and server:   Because I have High Coupling between my Backbone.js requests and Low Cohesion between resources.

I never figured out how to let my Backbone.js javascript application deal with "REST resources and features" discovery promoted by REST links.  I understand that the WWW is meant to be served by multi servers, and that the OO elements had to be exploded to be serviced by many hosts in there, but for a simple scenario like "saving" a page showing a contact with its addresses, I end up with:

```<code>GET /api/contacts/43?embed=(addresses)
[save button pressed]
PUT /api/contacts/43
PUT /api/contacts/43/addresses/453
</code>```

which lead me to move the saving action atomic transactional responsibility on the browsers applications (since two resources can be addressed separately).

With this in mind, if I cannot simplify my development (Facade design patterns not applicable), and if I bring more complexity to my client (handling transactional atomic save), where is the benefit of being RESTful ?


问:
What do programmers "micro-optimize" for today?
Back in the "good ol' days," when we would copy shareware onto floppies for friends, we also used a fair bit of assembly. There was a common practice of "micro-optimization," where you would stare and stare at lines of assembly until you figured out a way to express it in one fewer instruction. There was even a saying, which was mathematically impossible, that "You can always remove one more instruction." Given that changing runtime performance by small constant factors isn't a major issue for (most) programming today, are programmers transferring these micro-optimization efforts elsewhere?

In other words, Can a best-practice be taken to an extreme state where it's no longer adding anything of value? And instead is wasting time?

For example: Do programmers waste time generalizing private methods that are only called from one place? Is time wasted reducing test case data? Are programmers (still) overly concerned about reducing lines of code?

There are two great examples of what I'm looking for below: (1) Spending time finding the right variable names, even renaming everything; and (2) Removing even minor and tenuous code duplication.

Note that this is different from the question "What do you optimize for?", because I'm asking what other programmers seem to maximize, with the stigma of these being "micro" optimizations, and thus not a productive use of time.

答:
In the old days when computers had clock times measured in microseconds, memory measured in kilobytes, and primitive compilers, micro-optimization made some sense.

The speed and size of current generation computers and the quality of current generation compilers mean that micro-optimization is usually a total waste of time.  The exceptions tend to be when you absolutely have to get maximum performance out of some computationally intensive code ... or you are writing for an embedded system with extremely limited resources.

but I'm looking for what programmers do to waste time, not to optimize runtime performance.

Twitter and Facebook spring to mind :-)


问:
How do you identify a problem as being suitable for dynamic programming?
I have been reading up on dynamic programming lately. Would like to hear from someone who started from scratch and now is pretty good at identifying and solving DP problems. I am struggling in identifying these problems as DP and framing a concise solution.

I have gone through most of the beginner DP problems and MIT resources etc

答: I'd never implemented a single dynamic programming solver - my background is applied maths/physics/numerical computing, not CS - until a few years ago when I started doing Project Euler problems.  The DP-solvable problems there (e.g 76, 158, 161, 242, but there are many more) turned out to be pretty much my favourite kind.  You do definitely get better at spotting when it'll be a useful technique: basically look for things which seem like they could be solved by some sort of recursive, divide-and-conquer approach where it's also possible to tame the explosion of pathways needing to be explored by recognising recurring subproblems and reusing the previously computed results; being able to identify the minimal state vector to memoise on - and what irrelevant "history" can be erased - is the crucial step.</p>


答:
I come from a physics background, and thus, lots of maths. I find easy to spot problems well suited to recursive/dynamic programming solutions by finding similarities with proof by induction.

In proof by induction you have two parts:

you prove that if something is true for iteration N, it is also true for iteration N+1

you prove that it is true for iteration 1

In recursive programming/dynamic programming:

you identify an exit condition (for example, you hard wire the solution for iteration 1)

you calculate solution for iteration N given the solution for iteration N-1

So, as others answered, it is a matter of experience and picking the hints, but you can re-use other skills to guide you. After that, you need to always have the two parts which I mentioned: if you don't, then it won't work.

For example, to generate all the permutations of a set:

exit condition: if you only have one element, return it

recursion: the permutations of a set of N items are the N sets of permutations you get by choosing each element and combining the with all the N-1 sets of (many) permutations of the subset you get by removing the element.

Title: How do you identify a problem as being suitable for dynamic programming?

Body:
I have been reading up on dynamic programming lately. Would like to hear from someone who started from scratch and now is pretty good at identifying and solving DP problems. I am struggling in identifying these problems as DP and framing a concise solution.

I have gone through most of the beginner DP problems and MIT resources etc


答:
There are couple of points,

Certificate per se does not make code better or safe.

But it is very helpful in determining the authenticity and integrity of the code.

eg if there is some malicious code written by a hacker and he signs it with a certificate that does not make the code safe.

However, if you are downloading code from a known and trusted publisher and it is signed with a certificate from well known authority. It ensures that the source is correct and code has not been tampered with. It is also very effective in case of updates, as they use the same certificate that was used to distribute the software, they are automatically trusted and different operating systems use this mechanism to ensure that no malicious code is distributed as an update.

Title: How effective are code signing certificates when it comes to customer behavior or acceptance?

Body:
Whenever a potential customer downloads a copy of my software they get the "Unknown Publisher" warning message. I understand that if I purchase a code signing certificate this message goes away and the customer does not get the scary warning.

I'd like to know if anyone has information on how effective these code signing certificates are with regard to customer behavior. What difference did you see in customer behavior or acceptance after you signed your code using a certificate?


答:
Yes, C'est Moi. But my dual expertise is the result of inadvertence for the most part. I got side-tracked in high school and ended up going to art school for 4 years instead of a regular university. Then I painted portraits for a living until I decided that my I wanted my artistic side to be an avocation not a vocation, so I went back to school and studied engineering.
  I find it hard to imagine someone starting with the idea of being good at both design and programming.</p>

Title: Is it possible to be good at both programming and graphic design?

Body:
The stereotypical view of a programmer can't do graphics very well, from what I've read and seen. However, I love programming (preferably OOP, PHP, C++, Objective-C) and can't deny the fact I have a unique taste in web design and others have said I am doing well at it (CSS). I thought to myself "Hey, wait, I'm a programmer - how can I design well?". Question is: is it possible to be good at programming and designing? Does anyone here feel the same?

For the record: actual images I have created have been called programmer art several times before by friends


答:
Just from what I've seen with the software I distribute, a code signing certificate doesn't affect customer behavior much, particularly if they are downloading directly from your site and not from a 3rd party.  The customer has purposesly gone to your site, possibly even purchased your softare - they aren't not going to install your software because of an 'unknown publisher' message.

That said, the biggest benefit I've seen from having signed executables is anti-virus software seems less likely to falsly flag signed exe's.  My guess is there's some scoring going on, and a valid signature contributes to it.

So, ultimately, I do recommend getting a code signing cert.  You can get them much less expensively if you go through one of an issueres affiliates.


答:
These are very different languages, particularly in this area.  Let's say you have a class.  In this case, we'll make it a user control, something like a textbox.  Call it UIControl.  Now we want to put this in another class.  In this case, since we're using a UI for our example, we'll call it the CleverPanel class.  Our CleverPanel instance will want to know about things happening to its UIControl instance for various reasons.  How to do this?

In C#, the basic approach is to check for various Events, setting up methods that will execute
when each interesting event is triggered.  In Java, which lacks events, the usual solution is to pass an object with various "event" handling methods to a UIControl method:

```<code>boolean  stillNeedIt =  ... ;
uiControl.whenSomethingHappens( new DoSomething()  {
    public void resized( Rectangle r )  { ... }
    public boolean canICloseNow()  { return !stillNeedIt; }
    public void closed()  { ... }
    ...
} );
</code>```

So far, the difference between C# and Java is not profound.  However, we have the DoSomething interface that is not needed in C#.  Also, this interface might include a lot of methods that are not needed most of the time.  In C#, we just don't handle that Event.  In Java, we create a class that provides a null implementation for all the interface methods, DoSomethingAdapter.  Now we replace DoSomething with DoSomethingAdapter and we don't need to write any methods at all for a clean compile.  We end up just overriding the methods we need to make the program work right.  So we end up needing an interface and using inheritance in Java to match what we did with events in C#.

This is an example, not a comprehensive discussion, but it gives the basics of why there's so much inheritance in Java as opposed to C#.

Now, why does Java work this way?  Flexibility.  The object passed to whenSomethingHappens could have been passed to CleverPanel from somewhere else completely.  It might be something several CleverPanel instances should pass to their UIControl-like objects to aid a CleverWindow object somewhere.  Or the UIControl could hand it off to one of its components.

In addition, instead of an adapter there might be a DoSomething implementation somewhere that has thousands of lines of code behind it.  We could create a new instance of that and pass it.  We might need to override one method.  A common trick in Java is to have a large class with a method like:

```<code>public class BigClass implements DoSomething  {
    ...many long methods...
    protected int getDiameter()  { return 5; }
}
</code>```

Then in CleverlPanel:

```<code>uiControl.whenSomethingHappens( new BigClass()  {
    @Override
    public int getDiameter()  { return UIPanel.currentDiameter; }
} );
</code>```

The open source Java Platform does a lot of this, which tends to push programmers to do more--both because they follow it as an example and simply in order to use it.  I do think the basic design of the language is behind Sun's framework design and behind Java programmer's using the techniques when not using the framework.

It's real easy to create a class on the fly in Java.  The class, anonymous or named, need only be referenced in one small block of code buried deep in one method.  It can be created completely new or by slight modifications to a very large, existing class.  (And the existing class can be top-level in it's own file, or nested in a top-level class, or defined only within a single block of code).  The new class instance can have full access to all the creating object's data.  And the new instance can be passed and used all over the program, representing the object that created it.

(As an aside, note that a big use of inheritance here--as in other places in Java--is simply for DRY purposes.  It lets different classes reuse the same code.  Note also the ease of inheritance in Java that encourages this.)

Again, this is not a comprehensive discussion; I'm just scratching the surface here.  But yes, there is a startling difference in how inheritance is used between Java and C#.  They are, in this respect, very different languages.  It's not your imagination.

Body:
These are very different languages, particularly in this area.  Let's say you have a class.  In this case, we'll make it a user control, something like a textbox.  Call it UIControl.  Now we want to put this in another class.  In this case, since we're using a UI for our example, we'll call it the CleverPanel class.  Our CleverPanel instance will want to know about things happening to its UIControl instance for various reasons.  How to do this?

In C#, the basic approach is to check for various Events, setting up methods that will execute
when each interesting event is triggered.  In Java, which lacks events, the usual solution is to pass an object with various "event" handling methods to a UIControl method:

boolean  stillNeedIt =  ... ;
uiControl.whenSomethingHappens( new DoSomething()  {
    public void resized( Rectangle r )  { ... }
    public boolean canICloseNow()  { return !stillNeedIt; }
    public void closed()  { ... }
    ...
} );

So far, the difference between C# and Java is not profound.  However, we have the DoSomething interface that is not needed in C#.  Also, this interface might include a lot of methods that are not needed most of the time.  In C#, we just don't handle that Event.  In Java, we create a class that provides a null implementation for all the interface methods, DoSomethingAdapter.  Now we replace DoSomething with DoSomethingAdapter and we don't need to write any methods at all for a clean compile.  We end up just overriding the methods we need to make the program work right.  So we end up needing an interface and using inheritance in Java to match what we did with events in C#.

This is an example, not a comprehensive discussion, but it gives the basics of why there's so much inheritance in Java as opposed to C#.

Now, why does Java work this way?  Flexibility.  The object passed to whenSomethingHappens could have been passed to CleverPanel from somewhere else completely.  It might be something several CleverPanel instances should pass to their UIControl-like objects to aid a CleverWindow object somewhere.  Or the UIControl could hand it off to one of its components.

In addition, instead of an adapter there might be a DoSomething implementation somewhere that has thousands of lines of code behind it.  We could create a new instance of that and pass it.  We might need to override one method.  A common trick in Java is to have a large class with a method like:

public class BigClass implements DoSomething  {
    ...many long methods...
    protected int getDiameter()  { return 5; }
}

Then in CleverlPanel:

uiControl.whenSomethingHappens( new BigClass()  {
    @Override
    public int getDiameter()  { return UIPanel.currentDiameter; }
} );

The open source Java Platform does a lot of this, which tends to push programmers to do more--both because they follow it as an example and simply in order to use it.  I do think the basic design of the language is behind Sun's framework design and behind Java programmer's using the techniques when not using the framework.

It's real easy to create a class on the fly in Java.  The class, anonymous or named, need only be referenced in one small block of code buried deep in one method.  It can be created completely new or by slight modifications to a very large, existing class.  (And the existing class can be top-level in it's own file, or nested in a top-level class, or defined only within a single block of code).  The new class instance can have full access to all the creating object's data.  And the new instance can be passed and used all over the program, representing the object that created it.

(As an aside, note that a big use of inheritance here--as in other places in Java--is simply for DRY purposes.  It lets different classes reuse the same code.  Note also the ease of inheritance in Java that encourages this.)

Again, this is not a comprehensive discussion; I'm just scratching the surface here.  But yes, there is a startling difference in how inheritance is used between Java and C#.  They are, in this respect, very different languages.  It's not your imagination.


答:
You should try to use the Flyweight pattern. This means, you will store only the town id in the man object, and the method for getting the Town name will still be part of your "man" object. To make this work, you have to pass the list of all towns as a parameter:

```<code>class OMan1
{
   //..
   const astring& Town( const vector<astring> &allTowns) const:
   {
      return allTowns[fTownId];
   }
   // ...
 }
</code>```

So, you will loose of course some self-containment, since you will have to supply the town list all everywhere where you ask a "man" object for his town, but the Town() method is kept at the place where most people would expect it: in the "man" object, and not in some kind of "god object" (database).

Title: Data duplication vs Encapsulating. Which design to use?

Body:
The problem that I face is how to combine encapsulating and optimal memory use.

I can't show you my code and therefore explain it on extensive (I hope) example.

Let's say we need to have a database of mans. We want to know only 2 things about those people:

Age of the man (in hours from birth).

Name of the town he lives in.

The convenient and natural way to manage this data is to create an object, which corresponds to a man and store it in an array:

```<code>class OMan1 {
  public:
    OMan( const int &age, const astring &t ): fAge(age), fTown(t) {}
    const int& age() const: { return fAge; }
    const astring& Town() const: { return fTown; }
    astring FullId() const: { return fTown+fAge; }
  private:
    int fAge;
    astring fTown;
}

OMan mans[N];
</code>```

Here our OMans are self-containing object and everything fills nice.

Except of the fact that we clone names of the towns thousands of times, and waste memory and execution time this way.

An improvement we can do is to make an independent array for town names and for each OMan, store only the age, an id of the town and a pointer to towns array:

```<code>class OMan2 {
  // same functionality as for OMan1
    int fAge;
    int fTownId;
    astring* fTowns;
}
</code>```

object is still self-contained, sizeof(int) + sizeof(void*) is much less then sizeof(astring), we win a lot. But still it is factor of 2-3 more than sizeof(fAge) and we repeat fTowns billions of times.

Memory optimisation is crucial for me, therefore what I do is keeping only fAge and fTownId and move such functionality as Town() and FullId() out of the OMan class to some class like OManDataBase:

```<code>class OMan3 {
  public:
    OMan( const int &age, const int &tid ): fAge(age), fTownId(tid) {}
    const int& age() const: { return fAge; }
    const int& TownId() const: { return fId; }
    // const astring& Town() const: { return fTown; }
    // astring FullId() const: { return fTown+fAge; }
  private:
    int fAge;
    int fTownId;
}

class OManDataBase {
  // constructor, destructor
    const int& age( const int& i) const: { return fMans[i].TownId()]; }
    const astring& Town( const int& i) const: { return fTown[fMans[i].TownId()]; }
    const astring& FullId( const int& i) const: { return Town(i)+age(i); }
  private:
    vector<OMan3> fMans;
    vector<astring> fTowns;
}
</code>```

And OMan3 now is not self contained object. It doesn't know it's fullname, for instance. That means that if I need to do some data processing with one man I have to use whole OManDataBase instance:

```<code>OBillType47 NewBillType47( const OManDataBase &db, int i ) { ... }
</code>```

instead of

```<code>OBillType47 NewBillType47( const OMan &m ) { ... }
</code>```

encapsulation has been broken here and the code readability has been clearly decreased. (I put Type47 to emphasise that I can have a lot of functions, which works with Oman-S and can't include all of them into OManDataBase class).

I wonder is there any other way(-s) to solve data duplication problem, keeping objects as self-containing as possible?

Body:
You should try to use the Flyweight pattern. This means, you will store only the town id in the man object, and the method for getting the Town name will still be part of your "man" object. To make this work, you have to pass the list of all towns as a parameter:

class OMan1
{
   //..
   const astring& Town( const vector<astring> &allTowns) const:
   {
      return allTowns[fTownId];
   }
   // ...
 }

So, you will loose of course some self-containment, since you will have to supply the town list all everywhere where you ask a "man" object for his town, but the Town() method is kept at the place where most people would expect it: in the "man" object, and not in some kind of "god object" (database).


答:
A micro-optimization: improving single-threaded performance of things that are parallelizable or that can simply be improved with new hardware.

If something is slow on a computer from 10 years ago, a cheaper solution is probably to buy a newer, faster computer, rather than to waste programmer time optimizing.  A big focus of optimizations considered, though, should be finding a way to use the 8 cores you can get today, or the 64 you'll be able to get in a couple years, instead of agonizing about minutia like the extra cost of garbage collection.

Title: What do programmers "micro-optimize" for today?

Body:
Back in the "good ol' days," when we would copy shareware onto floppies for friends, we also used a fair bit of assembly. There was a common practice of "micro-optimization," where you would stare and stare at lines of assembly until you figured out a way to express it in one fewer instruction. There was even a saying, which was mathematically impossible, that "You can always remove one more instruction." Given that changing runtime performance by small constant factors isn't a major issue for (most) programming today, are programmers transferring these micro-optimization efforts elsewhere?

In other words, Can a best-practice be taken to an extreme state where it's no longer adding anything of value? And instead is wasting time?

For example: Do programmers waste time generalizing private methods that are only called from one place? Is time wasted reducing test case data? Are programmers (still) overly concerned about reducing lines of code?

There are two great examples of what I'm looking for below: (1) Spending time finding the right variable names, even renaming everything; and (2) Removing even minor and tenuous code duplication.

Note that this is different from the question "What do you optimize for?", because I'm asking what other programmers seem to maximize, with the stigma of these being "micro" optimizations, and thus not a productive use of time.


问:
Inserting HTML code with jquery
One of our web applications is a page that takes in a serial number and various information is returned and displayed to the user. The serial is passed via AJAX, and based on the response, one of the following can happen -

An error message is shown

A new form replaces the previous form

Now, the way I am handling this is to use jQuery to destroy (using $.remove()) the table that displayed the initial serial form, then I'm appending another html table that contains another form. Right now I am including that additional form as part of the html source, and just setting it to display:none, then using jQuery to show it when appropriate. However, I don't like this approach because if someone views source on the page, they can see that table html code that is not being displayed.

My next thought would be to use AJAX to read in another HTML file, and append it that way. However, I am trying to keep down the number of files this project uses, and since most pages in our project will use AJAX, I could see a case where there are multiple files containing HTML snippets - and that feels sloppy to me.

What is the best way to handle a case where multiple html elements are being shown and removed with jQuery?

答:
using echo and .html() are potential XSS vectors if used with any kind of user input ( like your serial number).

I would recommend using client side templating like mustache js.

```<code>$.ajax({
  url: "foo.php",
  type: "post",
  data: values,
  success: function(data){
      var template = $("#formTemplate");
      var html = Mustache.to_html(template, data);
      $('#myDiv').html(html);
  },
  error: function(error){
      "<p>{{error}}</p>";
       var html = Mustache.to_html(template,
          {'error' : error}
       );
       $('#myDiv').html(html);
  }
}
</code>```

This method requires you to implement "formTemplate" as a mustache template but gives three advantages

Mustache performs escaping to prevent XSS attacks

HTML and templates are now cachable (only foo.php changes)

Separates presentation from data

Title: Inserting HTML code with jquery

Body:
using echo and .html() are potential XSS vectors if used with any kind of user input ( like your serial number).

I would recommend using client side templating like mustache js.

$.ajax({
  url: "foo.php",
  type: "post",
  data: values,
  success: function(data){
      var template = $("#formTemplate");
      var html = Mustache.to_html(template, data);
      $('#myDiv').html(html);
  },
  error: function(error){
      "<p>{{error}}</p>";
       var html = Mustache.to_html(template,
          {'error' : error}
       );
       $('#myDiv').html(html);
  }
}

This method requires you to implement "formTemplate" as a mustache template but gives three advantages

Mustache performs escaping to prevent XSS attacks

HTML and templates are now cachable (only foo.php changes)

Separates presentation from data


问:
Technique to deal with occasionally blocking json api?
I have a web app that occasionally (after some idleness) will block a very simple request for small chunks of data (30~50 kb) up to 20 or so seconds. Assuming I can't refactor or modify the API, is there some pattern in javascript or jquery to accommodate a situation like this?

I'm thinking to set a timeout for 5 seconds or so for the api call and retry the ajax request -- via jquery's $.ajax() with the timeout argument. I imagine this could be the equivalent of the user refreshing a slow-loading page. Thanks for your thoughts.

答:
jQuerys .ajax() mathod is asynchronous by default meaning the user can still use the page. To prevent users from getting confused or impatient, they need to know that the page is loading. jQuery gives us hooks to show a loading message:</p>

```<code>$.ajax({
    url: 'service.php',
    success: function(){
        //display results
    },
    beforeSend: function(){
        // start an unobtrusive progress bar or spinner
    }
    complete: function(){
        // hide the progress bar/spinner
    }
}
</code>```

Body:
jQuerys .ajax() mathod is asynchronous by default meaning the user can still use the page. To prevent users from getting confused or impatient, they need to know that the page is loading. jQuery gives us hooks to show a loading message:

$.ajax({
    url: 'service.php',
    success: function(){
        //display results
    },
    beforeSend: function(){
        // start an unobtrusive progress bar or spinner
    }
    complete: function(){
        // hide the progress bar/spinner
    }
}


问:
Better way to create samples
I've done this piece of code for creating bernulli samples, but I think that it is a so heavy algorithm because every time I call this recursive function I create a new vector that is passed to it. Is there a way for making this algorithm faster?

Here is the algorithm and the description:

As already said, this function creates bernulli samples recursively. If n, that is the number of elements that should be found, is equals 0 I print the sample.

Else to the sample that is passed I add every element of the population (I have to create a vector for everyone of this new samples), and I call the function with this new sample and n(the number of element to be found) decremented.

```<code>private static void distribuzioneBernoulli(int n, Vector<Float> population, Vector<Float> sample){
    // exit condition, when n equals 0 the fuction doesn't self-calls
    if(n==0){
        JOptionPane.ShowMessageDialog(null, campione);
    }

    // Every element of the population is added to the sample,
    // and is recalled the function
    for(int x = 0; x < population.size(); x++){
        Vector<Float> aggiunta = new Vector<Float>(sample);
        aggiunta.add(population.elementAt(x));
        distribuzioneBernoulli(n-1, population, aggiunta);
    }
}
</code>```

答:
You are not calculating any samples. Instead, you are creating all possible sequences out of the elements on population of length n. Consider population = {1, 1, 2, 3} and n = 3. Then you would produce:

```<code>1 1 1    1 1 1    2 1 1    3 1 1
1 1 1    1 1 1    2 1 1    3 1 1
1 1 2    1 1 2    2 1 2    3 1 2
1 1 3    1 1 3    2 1 3    3 1 3
1 1 1    1 1 1    2 1 1    3 1 1
1 1 1    1 1 1    2 1 1    3 1 1
1 1 2    1 1 2    2 1 2    3 1 2
1 1 3    1 1 3    2 1 3    3 1 3
1 2 1    1 2 1    2 2 1    3 2 1
1 2 1    1 2 1    2 2 1    3 2 1
1 2 2    1 2 2    2 2 2    3 2 2
1 2 3    1 2 3    2 2 3    3 2 3
1 3 1    1 3 1    2 3 1    3 3 1
1 3 1    1 3 1    2 3 1    3 3 1
1 3 2    1 3 2    2 3 2    3 3 2
1 3 3    1 3 3    2 3 3    3 3 3
</code>```

The number of sequences is population.sizen (here: 4³ = 64).

A Bernoulli sample would return one of these sequences with equal probability.

If you want to return a Bernoulli sample, then the following code would be better:

```<code>static <T> List<T> bernoulliSample(int size, List<T> population, Random rng) {
  assert population != null;
  assert rng != null;
  List<T> sequence = new ArrayList<T>(size);
  for (int i = 0; i < size; i++) {
    sequence.add(population.get(rng.nextInt(population.size())));
  }
  return sequence;
}
</code>```

If you want to construct all possible sequences (≠ permutations), then we can pre-allocate a data structure that holds all sequences. However, it might be better to return an Iterator or Iterable object that computes the sequences lazily.

Eager solution

```<code>static <T> List<List<T>> allSequences(int size, List<T> population) {
  assert population != null;
  assert size >= 0;
  int sequenceCount = ipow(population.size(), n); // see http://stackoverflow.com/a/10517609/1521179

  List<List<T>> sequences = new ArrayList<List<T>>(sequenceCount);

  for (int i = 0; i < sequenceCount; i++) {
    sequences.add(sequenceAt(i, population));
  }

  return sequences;
}
</code>```

Now what is sequenceAt? Each integer in the range [0, sequenceCount) can be translated into a specific sequence, much like decimal numbers can be translated into octal. The difference here is that instead of digits, we have items in population.

```<code>private static <T> List<T> sequenceAt(int size, int n, List<T> population) {
  List<T> sequence = new ArrayList<T>(size);

  for (int i : asBase(size, n, population.size())) {
    sequence.add(population.get(i));
  }

  return sequence;
}
</code>```

Notice that we don't copy around any half-finished lists here, and we don't rely on recursion.

This method here will transform an integer into a list of digits in another base:

```<code>private static int[] asBase(int size, int n, int base) {
  int digits[] = new int[size];

  for (int i = size - 1, rem = n; i >= 0; i--, rem /= base) {
    digits[i] = rem % base;
  }

  return digits;
}
</code>```

Lazy solution

This can reuse the helper methods from above solution.

```<code>class Sequences<T> implements Iterable<List<T>> {

  private final List<T> population;
  private final int     count;
  private final int     size;

  public Sequences(int size, List<T> population) {
    assert population != null;
    this.population = population;

    assert size >= 0;
    this.size = size:

    this.count = ipow(population.size(), size); // see http://stackoverflow.com/a/10517609/1521179
  }

  public Iterator<List<T>> iterator() {
    return new Iterator<List<T>>() {
      int cursor = 0;

      public boolean hasNext() {
        return cursor < count;
      }

      public List<T> next() {
        if (!hasNext()) throw new NoSuchElementException();
        return sequenceAt(size, cursor++, population);
      }

      public void remove() {
        throw new UnsupportedOperationException();
      }

      // sequenceAt, asBase
    };
  }

  // ipow

}
</code>```

Now we could print out all sequences like

```<code>for (List<Integer> sequence : new Sequences<Integer>(3, Arrays.asList(1, 1, 2, 3))) {
    for (int i : sequence) System.out.print(i + " ");
    System.out.println();
}
</code>```

With both of these solutions we could skip the indirection from translating a number to a specific sequence. Instead, we could maintain an array of indices directly and update it after each sequence. Such a solution could be more efficient, as it results in fewer allocations.

Title: Better way to create samples

Body:
You are not calculating any samples. Instead, you are creating all possible sequences out of the elements on population of length n. Consider population = {1, 1, 2, 3} and n = 3. Then you would produce:

1 1 1    1 1 1    2 1 1    3 1 1
1 1 1    1 1 1    2 1 1    3 1 1
1 1 2    1 1 2    2 1 2    3 1 2
1 1 3    1 1 3    2 1 3    3 1 3
1 1 1    1 1 1    2 1 1    3 1 1
1 1 1    1 1 1    2 1 1    3 1 1
1 1 2    1 1 2    2 1 2    3 1 2
1 1 3    1 1 3    2 1 3    3 1 3
1 2 1    1 2 1    2 2 1    3 2 1
1 2 1    1 2 1    2 2 1    3 2 1
1 2 2    1 2 2    2 2 2    3 2 2
1 2 3    1 2 3    2 2 3    3 2 3
1 3 1    1 3 1    2 3 1    3 3 1
1 3 1    1 3 1    2 3 1    3 3 1
1 3 2    1 3 2    2 3 2    3 3 2
1 3 3    1 3 3    2 3 3    3 3 3

The number of sequences is population.sizen (here: 4³ = 64).

A Bernoulli sample would return one of these sequences with equal probability.

If you want to return a Bernoulli sample, then the following code would be better:

static <T> List<T> bernoulliSample(int size, List<T> population, Random rng) {
  assert population != null;
  assert rng != null;
  List<T> sequence = new ArrayList<T>(size);
  for (int i = 0; i < size; i++) {
    sequence.add(population.get(rng.nextInt(population.size())));
  }
  return sequence;
}

If you want to construct all possible sequences (≠ permutations), then we can pre-allocate a data structure that holds all sequences. However, it might be better to return an Iterator or Iterable object that computes the sequences lazily.

Eager solution

static <T> List<List<T>> allSequences(int size, List<T> population) {
  assert population != null;
  assert size >= 0;
  int sequenceCount = ipow(population.size(), n); // see http://stackoverflow.com/a/10517609/1521179

  List<List<T>> sequences = new ArrayList<List<T>>(sequenceCount);

  for (int i = 0; i < sequenceCount; i++) {
    sequences.add(sequenceAt(i, population));
  }

  return sequences;
}

Now what is sequenceAt? Each integer in the range [0, sequenceCount) can be translated into a specific sequence, much like decimal numbers can be translated into octal. The difference here is that instead of digits, we have items in population.

private static <T> List<T> sequenceAt(int size, int n, List<T> population) {
  List<T> sequence = new ArrayList<T>(size);

  for (int i : asBase(size, n, population.size())) {
    sequence.add(population.get(i));
  }

  return sequence;
}

Notice that we don't copy around any half-finished lists here, and we don't rely on recursion.

This method here will transform an integer into a list of digits in another base:

private static int[] asBase(int size, int n, int base) {
  int digits[] = new int[size];

  for (int i = size - 1, rem = n; i >= 0; i--, rem /= base) {
    digits[i] = rem % base;
  }

  return digits;
}

Lazy solution

This can reuse the helper methods from above solution.

class Sequences<T> implements Iterable<List<T>> {

  private final List<T> population;
  private final int     count;
  private final int     size;

  public Sequences(int size, List<T> population) {
    assert population != null;
    this.population = population;

    assert size >= 0;
    this.size = size:

    this.count = ipow(population.size(), size); // see http://stackoverflow.com/a/10517609/1521179
  }

  public Iterator<List<T>> iterator() {
    return new Iterator<List<T>>() {
      int cursor = 0;

      public boolean hasNext() {
        return cursor < count;
      }

      public List<T> next() {
        if (!hasNext()) throw new NoSuchElementException();
        return sequenceAt(size, cursor++, population);
      }

      public void remove() {
        throw new UnsupportedOperationException();
      }

      // sequenceAt, asBase
    };
  }

  // ipow

}

Now we could print out all sequences like

for (List<Integer> sequence : new Sequences<Integer>(3, Arrays.asList(1, 1, 2, 3))) {
    for (int i : sequence) System.out.print(i + " ");
    System.out.println();
}

With both of these solutions we could skip the indirection from translating a number to a specific sequence. Instead, we could maintain an array of indices directly and update it after each sequence. Such a solution could be more efficient, as it results in fewer allocations.


问:
How to test functions or the code inside $(document).ready() using Jasmine?
I have multiple functions and a lot of code inside $(document).ready(function()). I am using jasmine to test the functions inside the ready function as well as the code inside ready() but when the test cases inside describe are executed it is not able to access the code inside the ready function.

```<code>$(document).ready(function () {
    function testMe(){
        testVar = true;
    }
});
</code>```

Jasmine test suite

```<code>describe("test suite", function(){
    beforeEach(function () {
        testme = false
    });
    it("Test Alert Box Message For Change Modal", function() {
        expect(testme).toEqual(true);
    });
});
</code>```

Kindly suggest what approach needs to be taken for the above approach.

答:
in your code, domready calls an annonymous function. If we had a reference to this function, we could call it.

```<code>var onReady = function(){
   testVar = true;
}

$(document).ready(onReady);
</code>```

and in your tests

```<code>it("Test Alert Box Message For Change Modal", function() {
    var testVar = false;
    onReady() ;
    expect(testVar).toEqual(true);
});
</code>```

your code is now testable :) namespacing and modules are recommended to make it even better.

Body:
in your code, domready calls an annonymous function. If we had a reference to this function, we could call it.

var onReady = function(){
   testVar = true;
}

$(document).ready(onReady);

and in your tests

it("Test Alert Box Message For Change Modal", function() {
    var testVar = false;
    onReady() ;
    expect(testVar).toEqual(true);
});

your code is now testable :) namespacing and modules are recommended to make it even better.


问:
success:/failure: blocks vs completion: block
I see two common patterns for blocks in Objective-C. One is a pair of success:/failure: blocks, the other is a single completion: block.

For example, lets say I have a task that will return an object asynchronously and that task might fail. The first pattern is -taskWithSuccess:(void (^)(id object))success failure:(void (^)(NSError *error))failure. The second pattern is -taskWithCompletion:(void (^)(id object, NSError *error))completion.

success:/failure:

```<code>[target taskWithSuccess:^(id object) {
    // W00t! I've got my object
} failure:^(NSError *error) {
    // Oh noes! report the failure.
}];
</code>```

completion:

```<code>[target taskWithCompletion:^(id object, NSError *error) {
    if (object) {
        // W00t! I've got my object
    } else {
        // Oh noes! report the failure.
    }
}];
</code>```

Which is the preferred pattern? What are the strengths and weaknesses? When would you use one over the other?

答:
I would say, whether the API provides one completion handler or a pair of success/failure blocks, is primarily a matter of personal preference.

Both approaches have pros and cons, although there are only marginally differences.

Consider that there are also further variants, for example where the one completion handler may have only one parameter combining the eventual result or a potential error:

```<code>typedef void (^completion_t)(id result);

- (void) taskWithCompletion:(completion_t)completionHandler;

[self taskWithCompletion:^(id result){
    if ([result isKindOfError:[NSError class]) {
        NSLog(@"Error: %@", result);
    }
    else {
        ...
    }
}];
</code>```

The purpose of this signature is that a completion handler can be used  generically in other APIs.

For example in Category for NSArray there is a method forEachApplyTask:completion: which sequentially invokes a task for each object and breaks the loop IFF there was an error. Since this method is itself asynchronous as well, it has a completion handler as well:

```<code>typedef void (^completion_t)(id result);
typedef void (^task_t)(id input, completion_t);
- (void) forEachApplyTask:(task_t)task completion:(completion_t);
</code>```

In fact, completion_t as defined above is generic enough and sufficient to handle all scenarios.

However, there are other means for an asynchronous task to signal its completion notification to the call-site:

Promises

Promises, also called “Futures”, “Deferred” or “Delayed” represent the eventual result of an asynchronous task (see also: wiki Futures and promises).

Initially, a promise is in the “pending” state. That is, it’s “value” is not yet evaluated and not yet available.

In Objective-C, a Promise would be an ordinary object which will be returned from an asynchronous method as shown below:

```<code>- (Promise*) doSomethingAsync;
</code>```

! The initial state of a Promise is “pending”.

Meanwhile, the asynchronous tasks starts to evaluate its result.

Note also, that there is no completion handler. Instead, the Promise will provide a more powerful means where the call-site can obtain the eventual result of the asynchronous task, which we will see soon.

The asynchronous task, which created the promise object, MUST eventually “resolve” its promise. That means, since a task may either succeed or fail, it MUST either “fulfill” a promise passing it the evaluated result, or it MUST “reject” the promise passing it an error indicating the reason for the failure.

! A task must eventually resolve its promise.

When a Promise has been resolved, it cannot change it's state anymore, including its value.

! A Promise can be resolved only once.

Once a promise has been resolved, a call-site can obtain the result (whether it failed or succeeded). How this is accomplished depends on whether the promise is implemented using the synchronous or the asynchronous style.

A Promise can be implemented in a synchronous or an asynchronous style which leads to either blocking respectively non-blocking semantics.

In a synchronous style in order to retrieve the value of the promise, a call-site would use a method which will block the current thread until after the promise has been resolved by the asynchronous task and the eventual result is available.

In an asynchronous style, the call-site would register callbacks or handler blocks which get called immediately after the promise has been resolved.

It turned out that the synchronous style has a number of significant disadvantages which effectively defeat the merits of asynchronous tasks. An interesting article about the currently flawed implementation of “futures” in the standard C++11 lib can be read here: Broken promises–C++0x futures.

How, in Objective-C, would a call-site obtain the result?

Well, it’s probably best to show a few examples. There are a couple of libraries which implement a Promise (see links below).

However, for the next code snippets, I will use a particular implementation of a Promise library, available on GitHub RXPromise.  I’m the author of RXPromise.

The other implementations may have a similar API, but there can be small and possibly subtle differences in syntax. RXPromise is an Objective-C version of the Promise/A+ specification which defines an open standard for robust and interoperable implementations of promises in JavaScript.

All promise libraries listed below do implement the asynchronous style.

There are quite significant differences among the different implementations. RXPromise internally utilizes dispatch lib, is fully thread safe, extremely lightweight, and also provides a number of additional useful features, like cancellation.

A call-site obtains the eventual result of the asynchronous task through “registering” handlers. The “Promise/A+ specification” defines the method then.

The method then

With RXPromise it looks as follows:

```<code>promise.then(successHandler, errorHandler);
</code>```

where successHandler is a block which gets called when the promise has been “fulfilled” and  errorHandler is a block which gets called when the promise has been “rejected”.

!  then is used to obtain the eventual result and to define a success or an error handler.

In RXPromise, the handler blocks have the following signature:

```<code>typedef id (^success_handler_t)(id result);
typedef id (^error_handler_t)(NSError* error);
</code>```

The success_handler has a parameter result which is obviously the eventual result of the asynchronous task. Likewise, the error_handler has a parameter error which is the error reported by the asynchronous task when it failed.

Both blocks have a return value. What this return value is about, will become clear soon.

In RXPromise, then is a property which returns a block. This block has two parameters, the success handler block and the error handler block. The handlers must be defined by the call-site.

! The handlers must be defined by the call-site.

So, the expression promise.then(success_handler, error_handler); is a short form of

```<code>then_block_t block promise.then;
block(success_handler, error_handler);
</code>```

We can write even more concise code:

```<code>doSomethingAsync
.then(^id(id result){
    …
    return @“OK”;
}, nil);
</code>```

The code reads: “Execute doSomethingAsync, when it succeeds, then execute success handler”.

Here, the error handler is nil which means, in case of an error, it will not be handled in this promise.

Another important fact is that calling the block returned from property then will return a Promise:

! then(...) returns a Promise

When calling the block returned from property then, the “receiver” returns a new Promise, a child promise. The receiver becomes the parent promise.

```<code>RXPromise* rootPromise = asyncA();
RXPromise* childPromise = rootPromise.then(successHandler, nil);
assert(childPromise.parent == rootPromise);
</code>```

What does that mean?

Well, due to this we can “chain” asynchronous tasks which effectively get executed sequentially.

Furthermore, the return value of either handler will become the “value” of the returned promise. So, if the task succeeds with the eventual result @“OK”, the returned promise will be “resolved” (that is “fulfilled”) with value @“OK”:

```<code>RXPromise* returnedPromise = asyncA().then(^id(id result){
    return @"OK";
}, nil);

...
assert([[returnedPromise get] isEqualToString:@"OK"]);
</code>```

Likewise, when the asynchronous task fails, the returned promise will be resolved (that is “rejected”) with an error.

```<code>RXPromise* returnedPromise = asyncA().then(nil, ^id(NSError* error){
    return error;
});

...
assert([[returnedPromise get] isKindOfClass:[NSError class]]);
</code>```

The handler may also return another promise. For example when that handler executes another asynchronous task. With this mechanism we can “chain” asynchronous tasks:

```<code>typedef void (^completion_t)(id result);
typedef void (^task_t)(id input, completion_t);
- (void) forEachApplyTask:(task_t)task completion:(completion_t);
</code>```0

! The return value of a handler block becomes the value of the child promise.

If there is no child promise, the return value has no effect.

A more complex example:

Here, we execute asyncTaskA, asyncTaskB, asyncTaskC and asyncTaskD sequentially - and each subsequent task takes the result of the preceding task as input:

```<code>typedef void (^completion_t)(id result);
typedef void (^task_t)(id input, completion_t);
- (void) forEachApplyTask:(task_t)task completion:(completion_t);
</code>```1

Such a “chain” is also called “continuation”.

Error handling

Promises make it especially easy to handle errors. Errors will be “forwarded” from the parent to the child if there is no error handler defined in the parent promise. The error will be forwarded up the chain until a child handles it. Thus, having the above chain, we can implement error handling just by adding another “continuation” which deals with a potential error which may happen anywhere above:

```<code>typedef void (^completion_t)(id result);
typedef void (^task_t)(id input, completion_t);
- (void) forEachApplyTask:(task_t)task completion:(completion_t);
</code>```2

This akin to the probably more familiar synchronous style with exception handling:

```<code>try {
    id a = A();
    id b = B(a);
    id c = C(b);
    id d = D(c);
    // handle d
}
catch (NSError* error) {
    NSLog(@“”Error: %@“, error);
}
</code>```

Promises in general have other useful features:

For example, having a reference to a promise, via then one can "register" as many handlers as desired. In RXPromise, registering handlers can occur at any time and from any thread since it is fully thread-safe.

RXPromise has a couple more useful functional features, not required by the Promise/A+ specification. One is "cancellation".

It turned out that “cancellation” is an invaluable and important feature. For example a call-site holding a reference to a promise can send it the cancel message in order to indicate that it’s no longer interested in the eventual result.

Just imagine an asynchronous task which loads an image from the web and which shall be displayed in a view controller. If the user moves away from the current view controller, the developer may implement code which sends a cancel message to the imagePromise, which in turn triggers the error handler defined by the HTTP Request Operation where the request will be cancelled.

In RXPromise, a cancel message will only be forwarded from a parent to its children, but not vice versa.  That is, a “root” promise will cancel all children promises. But a child promise will only cancel the “branch” where it is the parent. The cancel message will also be forwarded to children if a promise has been already resolved.

An asynchronous task can itself register handler for its own promise, and thus can detect when someone else cancelled it. It may then prematurely stop performing a possibly lengthy and costly task.

Here are a couple other implementations of Promises in Objective-C found on GitHub:

https://github.com/Schoonology/aplus-objc

https://github.com/affablebloke/deferred-objective-c

https://github.com/bww/FutureKit

https://github.com/jkubicek/JKPromises

https://github.com/Strilanc/ObjC-CollapsingFutures

https://github.com/b52/OMPromises

https://github.com/mproberts/objc-promise

https://github.com/klaaspieter/Promise

https://github.com/jameswomack/Promise

https://github.com/nilfs/promise-objc

https://github.com/mxcl/PromiseKit

https://github.com/apleshkov/promises-aplus

https://github.com/KptainO/Rebelle

and my own implementation: RXPromise.

This list is likely not complete!

When choosing a third library for your project, please check carefully if the implementation of the library follows the prerequisites listed below:

A reliable promise library SHALL be thread safe!

It’s all about asynchronous processing, and we want to utilize multiple CPUs and execute on different threads concurrently whenever possible. Be careful, most of the implementations are not thread safe!

Handlers SHALL be called asynchronously which respect to the call-site! Always, and no matter what!

Any decent implementation should also follow a very strict pattern when invoking the asynchronous functions. Many implementors tend to "optimize" the case, where a handler will be invoked synchronously when the promise is already resolved when the handler will registered. This can cause all sorts of issues. See Don't release Zalgo!.

There should also be a mechanism to cancel a promise.

The possibility to cancel an asynchronous task often becomes a requirement with  high priority in the requirement analysis. If not, for sure there will be filed an enhancement request from a user some time later after the app has been released. The reason should be obvious: any task which may stall or take too long to finish, should be cancelable by the user or by a timeout. A decent promise library should support cancellation.

Body:
I would say, whether the API provides one completion handler or a pair of success/failure blocks, is primarily a matter of personal preference.

Both approaches have pros and cons, although there are only marginally differences.

Consider that there are also further variants, for example where the one completion handler may have only one parameter combining the eventual result or a potential error:

typedef void (^completion_t)(id result);

- (void) taskWithCompletion:(completion_t)completionHandler;

[self taskWithCompletion:^(id result){
    if ([result isKindOfError:[NSError class]) {
        NSLog(@"Error: %@", result);
    }
    else {
        ...
    }
}];

The purpose of this signature is that a completion handler can be used  generically in other APIs.

For example in Category for NSArray there is a method forEachApplyTask:completion: which sequentially invokes a task for each object and breaks the loop IFF there was an error. Since this method is itself asynchronous as well, it has a completion handler as well:

typedef void (^completion_t)(id result);
typedef void (^task_t)(id input, completion_t);
- (void) forEachApplyTask:(task_t)task completion:(completion_t);

In fact, completion_t as defined above is generic enough and sufficient to handle all scenarios.

However, there are other means for an asynchronous task to signal its completion notification to the call-site:

Promises

Promises, also called “Futures”, “Deferred” or “Delayed” represent the eventual result of an asynchronous task (see also: wiki Futures and promises).

Initially, a promise is in the “pending” state. That is, it’s “value” is not yet evaluated and not yet available.

In Objective-C, a Promise would be an ordinary object which will be returned from an asynchronous method as shown below:

- (Promise*) doSomethingAsync;

! The initial state of a Promise is “pending”.

Meanwhile, the asynchronous tasks starts to evaluate its result.

Note also, that there is no completion handler. Instead, the Promise will provide a more powerful means where the call-site can obtain the eventual result of the asynchronous task, which we will see soon.

The asynchronous task, which created the promise object, MUST eventually “resolve” its promise. That means, since a task may either succeed or fail, it MUST either “fulfill” a promise passing it the evaluated result, or it MUST “reject” the promise passing it an error indicating the reason for the failure.

! A task must eventually resolve its promise.

When a Promise has been resolved, it cannot change it's state anymore, including its value.

! A Promise can be resolved only once.

Once a promise has been resolved, a call-site can obtain the result (whether it failed or succeeded). How this is accomplished depends on whether the promise is implemented using the synchronous or the asynchronous style.

A Promise can be implemented in a synchronous or an asynchronous style which leads to either blocking respectively non-blocking semantics.

In a synchronous style in order to retrieve the value of the promise, a call-site would use a method which will block the current thread until after the promise has been resolved by the asynchronous task and the eventual result is available.

In an asynchronous style, the call-site would register callbacks or handler blocks which get called immediately after the promise has been resolved.

It turned out that the synchronous style has a number of significant disadvantages which effectively defeat the merits of asynchronous tasks. An interesting article about the currently flawed implementation of “futures” in the standard C++11 lib can be read here: Broken promises–C++0x futures.

How, in Objective-C, would a call-site obtain the result?

Well, it’s probably best to show a few examples. There are a couple of libraries which implement a Promise (see links below).

However, for the next code snippets, I will use a particular implementation of a Promise library, available on GitHub RXPromise.  I’m the author of RXPromise.

The other implementations may have a similar API, but there can be small and possibly subtle differences in syntax. RXPromise is an Objective-C version of the Promise/A+ specification which defines an open standard for robust and interoperable implementations of promises in JavaScript.

All promise libraries listed below do implement the asynchronous style.

There are quite significant differences among the different implementations. RXPromise internally utilizes dispatch lib, is fully thread safe, extremely lightweight, and also provides a number of additional useful features, like cancellation.

A call-site obtains the eventual result of the asynchronous task through “registering” handlers. The “Promise/A+ specification” defines the method then.

The method then

With RXPromise it looks as follows:

promise.then(successHandler, errorHandler);

where successHandler is a block which gets called when the promise has been “fulfilled” and  errorHandler is a block which gets called when the promise has been “rejected”.

!  then is used to obtain the eventual result and to define a success or an error handler.

In RXPromise, the handler blocks have the following signature:

typedef id (^success_handler_t)(id result);
typedef id (^error_handler_t)(NSError* error);

The success_handler has a parameter result which is obviously the eventual result of the asynchronous task. Likewise, the error_handler has a parameter error which is the error reported by the asynchronous task when it failed.

Both blocks have a return value. What this return value is about, will become clear soon.

In RXPromise, then is a property which returns a block. This block has two parameters, the success handler block and the error handler block. The handlers must be defined by the call-site.

! The handlers must be defined by the call-site.

So, the expression promise.then(success_handler, error_handler); is a short form of

then_block_t block promise.then;
block(success_handler, error_handler);

We can write even more concise code:

doSomethingAsync
.then(^id(id result){
    …
    return @“OK”;
}, nil);

The code reads: “Execute doSomethingAsync, when it succeeds, then execute success handler”.

Here, the error handler is nil which means, in case of an error, it will not be handled in this promise.

Another important fact is that calling the block returned from property then will return a Promise:

! then(...) returns a Promise

When calling the block returned from property then, the “receiver” returns a new Promise, a child promise. The receiver becomes the parent promise.

RXPromise* rootPromise = asyncA();
RXPromise* childPromise = rootPromise.then(successHandler, nil);
assert(childPromise.parent == rootPromise);

What does that mean?

Well, due to this we can “chain” asynchronous tasks which effectively get executed sequentially.

Furthermore, the return value of either handler will become the “value” of the returned promise. So, if the task succeeds with the eventual result @“OK”, the returned promise will be “resolved” (that is “fulfilled”) with value @“OK”:

RXPromise* returnedPromise = asyncA().then(^id(id result){
    return @"OK";
}, nil);

...
assert([[returnedPromise get] isEqualToString:@"OK"]);

Likewise, when the asynchronous task fails, the returned promise will be resolved (that is “rejected”) with an error.

RXPromise* returnedPromise = asyncA().then(nil, ^id(NSError* error){
    return error;
});

...
assert([[returnedPromise get] isKindOfClass:[NSError class]]);

The handler may also return another promise. For example when that handler executes another asynchronous task. With this mechanism we can “chain” asynchronous tasks:

RXPromise* returnedPromise = asyncA().then(^id(id result){
    return asyncB(result);
}, nil);

! The return value of a handler block becomes the value of the child promise.

If there is no child promise, the return value has no effect.

A more complex example:

Here, we execute asyncTaskA, asyncTaskB, asyncTaskC and asyncTaskD sequentially - and each subsequent task takes the result of the preceding task as input:

asyncTaskA()
.then(^id(id result){
    return asyncTaskB(result);
}, nil)
.then(^id(id result){
    return asyncTaskC(result);
}, nil)
.then(^id(id result){
    return asyncTaskD(result);
}, nil)
.then(^id(id result){
    // handle result
    return nil;
}, nil);

Such a “chain” is also called “continuation”.

Error handling

Promises make it especially easy to handle errors. Errors will be “forwarded” from the parent to the child if there is no error handler defined in the parent promise. The error will be forwarded up the chain until a child handles it. Thus, having the above chain, we can implement error handling just by adding another “continuation” which deals with a potential error which may happen anywhere above:

asyncTaskA()
.then(^id(id result){
    return asyncTaskB(result);
}, nil)
.then(^id(id result){
    return asyncTaskC(result);
}, nil)
.then(^id(id result){
    return asyncTaskD(result);
}, nil)
.then(^id(id result){
    // handle result
    return nil;
}, nil);
.then(nil, ^id(NSError*error) {
    NSLog(@“”Error: %@“, error);
    return nil;
});

This akin to the probably more familiar synchronous style with exception handling:

try {
    id a = A();
    id b = B(a);
    id c = C(b);
    id d = D(c);
    // handle d
}
catch (NSError* error) {
    NSLog(@“”Error: %@“, error);
}

Promises in general have other useful features:

For example, having a reference to a promise, via then one can "register" as many handlers as desired. In RXPromise, registering handlers can occur at any time and from any thread since it is fully thread-safe.

RXPromise has a couple more useful functional features, not required by the Promise/A+ specification. One is "cancellation".

It turned out that “cancellation” is an invaluable and important feature. For example a call-site holding a reference to a promise can send it the cancel message in order to indicate that it’s no longer interested in the eventual result.

Just imagine an asynchronous task which loads an image from the web and which shall be displayed in a view controller. If the user moves away from the current view controller, the developer may implement code which sends a cancel message to the imagePromise, which in turn triggers the error handler defined by the HTTP Request Operation where the request will be cancelled.

In RXPromise, a cancel message will only be forwarded from a parent to its children, but not vice versa.  That is, a “root” promise will cancel all children promises. But a child promise will only cancel the “branch” where it is the parent. The cancel message will also be forwarded to children if a promise has been already resolved.

An asynchronous task can itself register handler for its own promise, and thus can detect when someone else cancelled it. It may then prematurely stop performing a possibly lengthy and costly task.

Here are a couple other implementations of Promises in Objective-C found on GitHub:

https://github.com/Schoonology/aplus-objc

https://github.com/affablebloke/deferred-objective-c

https://github.com/bww/FutureKit

https://github.com/jkubicek/JKPromises

https://github.com/Strilanc/ObjC-CollapsingFutures

https://github.com/b52/OMPromises

https://github.com/mproberts/objc-promise

https://github.com/klaaspieter/Promise

https://github.com/jameswomack/Promise

https://github.com/nilfs/promise-objc

https://github.com/mxcl/PromiseKit

https://github.com/apleshkov/promises-aplus

https://github.com/KptainO/Rebelle

and my own implementation: RXPromise.

This list is likely not complete!

When choosing a third library for your project, please check carefully if the implementation of the library follows the prerequisites listed below:

A reliable promise library SHALL be thread safe!

It’s all about asynchronous processing, and we want to utilize multiple CPUs and execute on different threads concurrently whenever possible. Be careful, most of the implementations are not thread safe!

Handlers SHALL be called asynchronously which respect to the call-site! Always, and no matter what!

Any decent implementation should also follow a very strict pattern when invoking the asynchronous functions. Many implementors tend to "optimize" the case, where a handler will be invoked synchronously when the promise is already resolved when the handler will registered. This can cause all sorts of issues. See Don't release Zalgo!.

There should also be a mechanism to cancel a promise.

The possibility to cancel an asynchronous task often becomes a requirement with  high priority in the requirement analysis. If not, for sure there will be filed an enhancement request from a user some time later after the app has been released. The reason should be obvious: any task which may stall or take too long to finish, should be cancelable by the user or by a timeout. A decent promise library should support cancellation.