问:
Ignoring the generic part of a type while an object is being passed
I have a message class that holds the name of a destination, and a generic variable acting as the message payload

```<code>public class Message<T> {
    public string Destination
    public T Payload

    // ... constructors, functions, etc. ...
}
</code>```

This way, I should be able to create messages of any type (without needing to explicitly list the types that are valid) and still have the compiler test the type-safety.

I want to create a method that generates a message. The problem is I don't want to return a specific kind of message, I just want to return any message, or perhaps an array/List of messages with different types. I.e. instead of explicitly returning Message<String> or Message<int> I just want it to return Message. That way I can pass the message to the destination, then the destination can figure out what the type is and consume the payload.

The problem is, if I do that, it'll involve a lot of typecasting and kinda defeats the point of using generics. I might as well just make Payload an object then typecast it in the destination. Or just use dynamic. Should I or shouldn't I use object or dynamic in this case, and why?

This is actually a rephrasing of a previous poorly-phrased question that I asked. Previously, instead of using a generic type, I would use dynamic for the message, but answers kept saying that using dynamic was unsuitable except for things like Python interop, and many were referring to the use of generics which at the time I didn't think was suitable because of the above reason. My previous question is here:
When to not use dynamic in C#

EDIT: As suggested by Benjamin, here's what I'd like to happen

I have a "manager" that has a bunch of model objects in a dictionary. In it there's a function that goes like this:

```<code>void ManagerFunction()
{
    Message m = getMessage();
    objects[m.Destination].handleMessage(m)
}
</code>```

Notice that the manager doesn't care about the payload.

This have a function generating a message and returning it.

```<code>Message getMessage()
{
    Message m;

    if(x)
        m = new Message<String>();
    else if(y)
        m = new Message<int>();
    // ... some more else-if's here ...
    else
        m  = new Message<double>();

    return m;
}
</code>```

Notice how the message generating function can send a message of any type

Let's say that the destination all consist of objects that implement the following interface

```<code>interface DestinationInterface{
    void HandleMessage(Message m)
}
</code>```

I would like it so that one object might handle the interface in the following way

```<code>void HandleMessage(Message m)
{
    if(m.Payload is String){
        String s = (String) m.Payload
        // ...
    } else throw Exception();
}
</code>```

And another object that implements the interface might handle the interface in a different way

```<code>void HandleMessage(Message m)
{
    if(m.Payload is int)
    {
        int i = (int) m.Payload
        // ...
    } else throw Exception();
}
</code>```

Because of the typecasting, a generic type wouldn't be useful. So should I just use object for the payload? Why not use dynamic and get rid of all the typecasting in the first place?

答:
You could skip using generic messages and instead use generic handlers.

Here is how we do it:

```<code>public interface IMessage
{
}

public interface IHandle<in T> where T : IMessage
{
    void Handle(T message);
}
</code>```

Implement IMessage with "payload properties" that actually describes the payload.

```<code>public class ConcreteMessage : IMessage
{
    ...
    public int BetterNameThanPayload { get; private set; }
}
</code>```

Implement a message handler:

```<code>public class ConcreteHandler : IHandle<ConcreteMessage>
{
    public void Handle(ConcreteMessage message)
    {
        var foo = message.BetterNameThanPayload;
        ...
    }
}
</code>```

Use dynamic keyword when calling the handler (this should be the only place to use 'dynamic'):

```<code>void ManagerFunction()
{
    IMessage m = getMessage();
    var messageHandlerType = typeof(IHandle<>).MakeGenericType(m.GetType());
    var messageHandler = [resolve message handler];
    ((dynamic)messageHandler).Handle((dynamic)message);
}
</code>```

You could use a "destination" string to resolve the handler, but if using an IOC container it's simpler to resolve it by type (and it's type-safe). Also, skipping "destination" will decouple the message from the handler.

Body:
You could skip using generic messages and instead use generic handlers.

Here is how we do it:

public interface IMessage
{
}

public interface IHandle<in T> where T : IMessage
{
    void Handle(T message);
}

Implement IMessage with "payload properties" that actually describes the payload.

public class ConcreteMessage : IMessage
{
    ...
    public int BetterNameThanPayload { get; private set; }
}

Implement a message handler:

public class ConcreteHandler : IHandle<ConcreteMessage>
{
    public void Handle(ConcreteMessage message)
    {
        var foo = message.BetterNameThanPayload;
        ...
    }
}

Use dynamic keyword when calling the handler (this should be the only place to use 'dynamic'):

void ManagerFunction()
{
    IMessage m = getMessage();
    var messageHandlerType = typeof(IHandle<>).MakeGenericType(m.GetType());
    var messageHandler = [resolve message handler];
    ((dynamic)messageHandler).Handle((dynamic)message);
}

You could use a "destination" string to resolve the handler, but if using an IOC container it's simpler to resolve it by type (and it's type-safe). Also, skipping "destination" will decouple the message from the handler.


问:
Does phpDocumentor tags order matter?
When we document our class, method and/or function with phpDocumentor, is there any specific order I should follow according to the standards?

I know it doesn't matter for output the document. Since it is outputting the order what I have written.

This is for my knowledge and understanding if there is any order standards for it.

答:
Not as such... At least, none that I can find/think of. However, docblocks commonly follow a distinct format/pattern:

```<code>/**
 * Summary
 * [optional blank line]
 * Description
 * [optional blank line]
 * @see Optional, but more documentation can be added here
 * [optional blank line]
 * @todo: Development docs here
 * [optional blank line]
 * @api indicator of expected/intended usage of code
 * @uses Use-cases of code
 * @property* property-access
 * @deprecated
 * [optional blank line]
 * @param <type> $name [ = default value]
 * @return <return type, if any>
 * @throws <ExceptionType> [optionally explain when and why]
 * @throws <ExceptionType>
 */
</code>```

The logical order here is:

Summary

Description

Annotations documenting the code even more, examples, files, links etc...

Annotations that document behavior and usage of code ( (like @see)

Annotations regarding ungoing development

Annotations indicating visibility and expected usage (@api or @internal) Structural

Annotations indicating internals (dependencies on methods/properties) Structural

Annotations regarding availability (deprecation, preferably mentioning alternatives) Structural

Annotations regarding the function/method's signature (@param, then @return)

Annotations covering unexpected behaviour (ie @throws)

Some might say that the @throws annotation should precede the @returns, seeing as the last thing a function should do is return something. It is common, though, to put the @throws in last. That, to me, makes more sense: the documentation covers the flow of the method you're commenting. If something (an exceptional case) disrupts the flow, an exception is thrown, hence the @throws annotation shouldn't be part of the "normal" description of the method.

Either way, the simple rule of thumb here is:

IDE tooltip info comes first (summary, description, @see)

Additional documentation

Development info (@todo, @example, possibly @version)

Structural elements (the ones that apply)

The expected parameters info comes next (@param)

The result (@return)

In case of errors (@throws)

Note that the annotations listed here as Structural elements require you to document the classes and properties, too: /** @var <type> */ and, perhaps include @version and @license tags, too

ContentLicense: CC BY-SA 3.0

Title: Does phpDocumentor tags order matter?

Body:
Not as such... At least, none that I can find/think of. However, docblocks commonly follow a distinct format/pattern:

/**
 * Summary
 * [optional blank line]
 * Description
 * [optional blank line]
 * @see Optional, but more documentation can be added here
 * [optional blank line]
 * @todo: Development docs here
 * [optional blank line]
 * @api indicator of expected/intended usage of code
 * @uses Use-cases of code
 * @property* property-access
 * @deprecated
 * [optional blank line]
 * @param <type> $name [ = default value]
 * @return <return type, if any>
 * @throws <ExceptionType> [optionally explain when and why]
 * @throws <ExceptionType>
 */

The logical order here is:

Summary

Description

Annotations documenting the code even more, examples, files, links etc...

Annotations that document behavior and usage of code ( (like @see)

Annotations regarding ungoing development

Annotations indicating visibility and expected usage (@api or @internal) Structural

Annotations indicating internals (dependencies on methods/properties) Structural

Annotations regarding availability (deprecation, preferably mentioning alternatives) Structural

Annotations regarding the function/method's signature (@param, then @return)

Annotations covering unexpected behaviour (ie @throws)

Some might say that the @throws annotation should precede the @returns, seeing as the last thing a function should do is return something. It is common, though, to put the @throws in last. That, to me, makes more sense: the documentation covers the flow of the method you're commenting. If something (an exceptional case) disrupts the flow, an exception is thrown, hence the @throws annotation shouldn't be part of the "normal" description of the method.

Either way, the simple rule of thumb here is:

IDE tooltip info comes first (summary, description, @see)

Additional documentation

Development info (@todo, @example, possibly @version)

Structural elements (the ones that apply)

The expected parameters info comes next (@param)

The result (@return)

In case of errors (@throws)

Note that the annotations listed here as Structural elements require you to document the classes and properties, too: /** @var <type> */ and, perhaps include @version and @license tags, too


问:
What is the point of link rel="self" in a REST API?
I often see the following in HTML documents

```<code><link rel="self" href="http://example.com/something">
</code>```

or like this in JSON

```<code> link: {
     rel="self",
     href="http://example.com/something"
 }
</code>```

or in XML

```<code> <atom:link rel="self" href="http://example.com/something" />
</code>```

So I had some questions:

Why include this link?  What advantage does it bring? (Please tell me there is a reason to it and its not just a "good practice" talisman)

How should I exploit this link in my clients? What are the use case for this link?

When shouldn't I use this link? When is it pointless to include it?

答:
It is a self reference, so the client will know that the IRI (http://example.com/something) is an identifier of the resource the representation is about.

It can be important when your resource can have multiple identifiers, for example http://example.com/users/1 and http://example.com/users/1?fields="name" can identify the same resource, but a GET on them can result different representations.

By media types like HAL you use this to identify embedded resources as well. For example:

```<code>{
    "nick": "John",
    "_embedded": {
        "cars": {
            "items": [
                //...
            ],
            "_links": {
                "self": {
                    "href": "http://example.com/users/john/cars"
                }
            }
        }
    },
    "_links": {
        "self": {
            "href": "http://example.com/users/john"
        }
    }
}
</code>```

Body:
It is a self reference, so the client will know that the IRI (http://example.com/something) is an identifier of the resource the representation is about.

It can be important when your resource can have multiple identifiers, for example http://example.com/users/1 and http://example.com/users/1?fields="name" can identify the same resource, but a GET on them can result different representations.

By media types like HAL you use this to identify embedded resources as well. For example:

{
    "nick": "John",
    "_embedded": {
        "cars": {
            "items": [
                //...
            ],
            "_links": {
                "self": {
                    "href": "http://example.com/users/john/cars"
                }
            }
        }
    },
    "_links": {
        "self": {
            "href": "http://example.com/users/john"
        }
    }
}


问:
Manually scanning log files for exceptions/errors - is it a valid user story?
We've just deployed a new system for our users. The product owner asked us to check the log files every day in the next iteration for error messages and exceptions. We have written the following user story:

As a [web system] user I want that developers to check log files every day in the next iteration for errors so I don't have to file bug tickets for trivial bugs/get better service.

Is it a valid user story? If not, could it be rewritten to be a valid user story? How? (We had some debate about that with the product owner whether it is worth story points or not.)

答:
I would focus more on the "developers" than the users at first, but justify the work as a benefit to users. Something like:

As a developer I want to check the log files every day for errors so I can investigate and fix problems before users notice them, and to decrease outages.

There are actually three parties who benefit from this:

Users - They get an application that seems reliable

Business - They get happy users, and production problems get fixed in a timely manner.

Developers - They don't have to get woken up at 3 a.m. to fix a production problem that began at 2 a.m. the previous day


问:
URLs with variable query strings and cache
I am developing a media server, the basic functionality is to serve an image, which is done the following way

```<code>/media/:id
</code>```

where :id is the id of the image.

You may want to ask for a specific size, with some rules I will provide.

Eg:

```<code>/media/:id/50x50
/media/:id?witdh=50&height=50
</code>```

Question: Which option do you think is better? I believe the second one to be more RESTful and beautiful, but we will be using a CDN and varnish for cache, so if we get

```<code>/media/:id?width=50&height=50
</code>```

or

```<code>/media/:id?height=50&width=50
</code>```

we will have 2 hits when we should have 1

Any advice?

答:
According to URI standard the path should contain the hierarchical components and the query should contain the non-hierarchical components of the URI. But it can be subjective what is hierarchical and what non-hierarchical.

By developing a REST client these URLs mean nothing, because they follow hyperlinks and check link relations or other additional meta-data. (aka uniform interface / HATEOAS constraint)

If you cannot cache one of them, then you should choose the other one. Note: you always have to send cache headers. (aka cache constraint)


问:
Is there a need to comment obvious parameters?
Most of the time, when I comment a method, I'll follow this structure.

```<code>/**
 * Short description of what the method does
 *
 * @param {Type} name. Description of the variable.
 *
 * @return {Type}. What the return is.
 */
</code>```

Now if I have a method called uploadData, which takes one parameter, data, is it still necessary to give this parameter a description?

I realize necessary is kind of subjective in this case, but I'm curious as to what the general consensus is. For the time being I've been giving them all descriptions just to keep the consistency of the comments, but it does seem like it's a very unneeded.

If it makes any difference, the languages I use are Javascript, Java and PHP.

答:
The fact that the only parameter to an upload function is to do with the upload data is not noteworthy. What is worth mentioning is e.g. what format this is in (is it a String giving the name of a local file? a string constituting the data itself? a byte stream?), what restrictions it is subject to (unlimited? no more than 10MB? only 10 per day?), whether all of the values technically allowed by the type are okay (is NULL okay? is the empty array okay? does it have to be a valid UTF8 byte sequence?), etc.

If all of these issues are obviously clear to any caller of the method (e.g. if the parameter is a specifically constructed upload object which ensures that only valid data can go in), then go ahead and leave the parameter undocumented. But often it turns out there are additional preconditions, and it is almost always a good idea to make these explicit.


答:
I only describe parameters when I'm actually providing the reader with information. The definition of information is "adding to someone's knowledge". If the description is not adding to someone's knowledge, then it is not information and I leave it out.

```<code>/**
* @param string username. The username. <--not providing information
*/
</code>```

Also Martin Fowler says if you need to add a comment, you probably need to use a better name for the parameter. That should apply to Javadoc too.

Title: Is there a need to comment obvious parameters?

Body:
Most of the time, when I comment a method, I'll follow this structure.

```<code>/**
 * Short description of what the method does
 *
 * @param {Type} name. Description of the variable.
 *
 * @return {Type}. What the return is.
 */
</code>```

Now if I have a method called uploadData, which takes one parameter, data, is it still necessary to give this parameter a description?

I realize necessary is kind of subjective in this case, but I'm curious as to what the general consensus is. For the time being I've been giving them all descriptions just to keep the consistency of the comments, but it does seem like it's a very unneeded.

If it makes any difference, the languages I use are Javascript, Java and PHP.

Body:
I only describe parameters when I'm actually providing the reader with information. The definition of information is "adding to someone's knowledge". If the description is not adding to someone's knowledge, then it is not information and I leave it out.

/**
* @param string username. The username. <--not providing information
*/

Also Martin Fowler says if you need to add a comment, you probably need to use a better name for the parameter. That should apply to Javadoc too.


问:
Web-services REST security clarification
I'm newbie of web services programming and I have some problem to understand how to work authentication/security for REST WS pattern.

I had read about OAuth but I haven't understand how it work in detail, however I think I don't need it because only my app use the API.

I need authenticate the users that need to use the "privates" APIs, can you explain me the correct way for implement a REST WS authentication, or give me a good guide or flowchart?

答:
According to the stateless constraint of REST, you cannot maintain sessions on server side. You have to authenticate every request instead.

There are 2 kind of clients:

trusted clients developed by you (the web service developer)

3rd party clients developed by anybody else

By a trusted client the simplest solution to send the username and password with every single request. For example by basic HTTP auth in a HTTP header. (Ofc. with encrypted connection.)

Since your user cannot trust 3rd party clients with her password, you have to find out something else by there. A typical solution (e.g. facebook) to add a unique API key to each of the 3rd party clients. After that when the user wants to use one of them, she gets a prompt. Using that prompt she can grant access to the 3rd party client to use some part of her account. During this process the accessToken, userId, apiKey, permissions are saved on the server and the 3rd party client gets an access token for the user. After that the 3rd party client can use the access token (along with the API key and user id) to use the web service utilizing the account of the user.


问:
Link relation values and REL attribute - edited

In REST, do we always use link relation values to convey semantics/role of a linked resource?

I assume link relation value is always specified using rel attribute?

Should rel attribute only be specified within a hypermedia control?

I assume for an element to be considered a hypermedia control it must provide a linking functionality and must also contain a rel attribute?

答:
In REST, do we always use link relation values to convey
  semantics/role of a linked resource?

Using link relations is just one way to add semantics to links. The other standard solution to use RDF vocabs, for example hydra or schema.org.

I assume link relation value is always specified using rel attribute?

This depends on the media type, for example by HAL+JSON you do something like this:

```<code>{
    "nick": "John",
    "_links": {
        "self": {
            "href": "http://example.com/users/john"
        }
    }
}
</code>```

Should rel attribute only be specified within a hypermedia control?
  I assume for an element to be considered a hypermedia control it must
  provide a linking functionality and must also contain a rel attribute?

That again depends on the media type. For example by HTML only LINK elements can have relations, so you can add semantics only to GET requests. Other elements which use hyperlinks as well - for example FORM, IMG, etc. - cannot have relations as far as I know. By them you can use RDFa to add link relation. Btw. HTML is not the best hypermedia type for REST, since it is about machine to machine communication and HTML is for building GUIs for humans...

Body:
In REST, do we always use link relation values to convey
  semantics/role of a linked resource?

Using link relations is just one way to add semantics to links. The other standard solution to use RDF vocabs, for example hydra or schema.org.

I assume link relation value is always specified using rel attribute?

This depends on the media type, for example by HAL+JSON you do something like this:

{
    "nick": "John",
    "_links": {
        "self": {
            "href": "http://example.com/users/john"
        }
    }
}

Should rel attribute only be specified within a hypermedia control?
  I assume for an element to be considered a hypermedia control it must
  provide a linking functionality and must also contain a rel attribute?

That again depends on the media type. For example by HTML only LINK elements can have relations, so you can add semantics only to GET requests. Other elements which use hyperlinks as well - for example FORM, IMG, etc. - cannot have relations as far as I know. By them you can use RDFa to add link relation. Btw. HTML is not the best hypermedia type for REST, since it is about machine to machine communication and HTML is for building GUIs for humans...


问:
Falsy values vs null, undefined, or empty string
I've worked with jQuery over the years. However, recently, I've found myself getting deeper into the JavaScript language. Recently, I've heard about "truthy" and falsey values. However, I don't fully understand them. Currently, I have some code that looks like this:

```<code>var fields = options.fields || ['id', 'query'];
</code>```

I need to identify if fields is null, undefined, or has a length of 0. I know the long way is to do:

```<code>if ((fields === null) || (fields === undefined) || (fields.length === 0)) {
 ...
}
</code>```

My question is, is the following the same:

```<code>if (!fields)  {
 ...
}
</code>```

答:
The set of "truthy" and "falsey" values in JavaScript comes from the ToBoolean abstract operation defined in the ECMAScript spec, which is used when coercing a value to a boolean:

```<code>+--------------------------------------------------------------------------+
| Argument Type | Result                                                   |
|---------------+----------------------------------------------------------|
| Undefined     | false                                                    |
|---------------+----------------------------------------------------------|
| Null          | false                                                    |
|---------------+----------------------------------------------------------|
| Boolean       | The result equals the input argument (no conversion).    |
|---------------+----------------------------------------------------------|
| Number        | The result is false if the argument is +0, −0, or NaN;   |
|               | otherwise the result is true.                            |
|---------------+----------------------------------------------------------|
| String        | The result is false if the argument is the empty String  |
|               | (its length is zero); otherwise the result is true.      |
|---------------+----------------------------------------------------------|
| Object        | true                                                     |
+--------------------------------------------------------------------------+
</code>```

From this table, we can see that null and undefined are both coerced to false in a boolean context. However, your fields.length === 0 does not map generally onto a false value. If fields.length is a string, then it will be treated as false (because a zero-length string is false), but if it is an object (including an array) it will coerce to true.

If fields should be a string, then !fields is a sufficient predicate. If fields is an array, your best check might be:

```<code>if (!fields || fields.length === 0)
</code>```

Body:
The set of "truthy" and "falsey" values in JavaScript comes from the ToBoolean abstract operation defined in the ECMAScript spec, which is used when coercing a value to a boolean:

+--------------------------------------------------------------------------+
| Argument Type | Result                                                   |
|---------------+----------------------------------------------------------|
| Undefined     | false                                                    |
|---------------+----------------------------------------------------------|
| Null          | false                                                    |
|---------------+----------------------------------------------------------|
| Boolean       | The result equals the input argument (no conversion).    |
|---------------+----------------------------------------------------------|
| Number        | The result is false if the argument is +0, −0, or NaN;   |
|               | otherwise the result is true.                            |
|---------------+----------------------------------------------------------|
| String        | The result is false if the argument is the empty String  |
|               | (its length is zero); otherwise the result is true.      |
|---------------+----------------------------------------------------------|
| Object        | true                                                     |
+--------------------------------------------------------------------------+

From this table, we can see that null and undefined are both coerced to false in a boolean context. However, your fields.length === 0 does not map generally onto a false value. If fields.length is a string, then it will be treated as false (because a zero-length string is false), but if it is an object (including an array) it will coerce to true.

If fields should be a string, then !fields is a sufficient predicate. If fields is an array, your best check might be:

if (!fields || fields.length === 0)


问:
What exactly are Link Relation Values?
From REST in Practice: Hypermedia and Systems Architecture:

For computer-to-computer interactions, we advertise protocol
  information by embedding links in representations, much as we do with
  the human Web. To describe a link's purpose, we annotate it.
  Annotations indicate what the linked resource means to the current
  resource: “status of your coffee order” “payment” and so on. We call
  such annotated links hypermedia controls, reflecting their enhanced
  capabilities over raw URIs.

... link relation values, which describe the roles of linked resources ...
  Link relation values help consumers understand why they might want to
  activate a hypermedia control. They do so by indicating the role of
  the linked resource in the context of the current representation.

I interpret the above quotes as saying that Hypermedia control contains both a link to a resource and an annotation describing the role of linked resource in the context of the current representation. And we call this annotation ( which describes the role of linked resource )  a link relation value.

Is my assumption correct or does the term link relation value actually describe something different?

Thank you

答: You call it link relation, and not link relation value. :-) There is a registry for standard link relations, but you can use custom ones as well, or use any other vocab, which defines link metadata. The client utilizes this metadata to choose link.

Title: What exactly are Link Relation Values?


问:
Access Token Verification
I have spent quite a few days reading up on Oauth and token based security measures for REST API's and I am currently looking at implementing an Oauth based authentication approach almost exactly like the one described in this post (OAuth alternative for a 2 party system).

From what I understand, the token is to be verified upon each request to the resource server.  This means the resource server would need to retrieve the token from a datastore to verify the clients token.  Given this would have to happen upon every request I am concerned about the speed implications of hitting a datastore like MySQL or NoSQL upon every request just to verify the token.

Is this the standard way to verify tokens by having them stored in a RDBMS or NoSQL database and retrieved upon each request?  Or is it a suitable solution to have them cached (baring in mind that we are talking millions of users)?

答:
From what I understand, the token is to be verified upon each request
  to the resource server. This means the resource server would need to
  retrieve the token from a datastore to verify the clients token. Given
  this would have to happen upon every request I am concerned about the
  speed implications of hitting a datastore like MySQL or NoSQL upon
  every request just to verify the token.

Yes this is true, but you can use an in-memory cache for these tokens if the database is slow for you. Anyways I suggest you to find the bottlenecks with tools instead of making theories.

Title: Access Token Verification


问:
How to translate SQL query into REST API requests?
Let's say I have a machine-readable description (such as in WADL, Swagger or RAML) of a REST API that provides interface to a database.

My users submit queries about underlying database in form of SQL or similar query language. However, I cannot access the database directly, only through the REST API.

What approach would you choose to build (preferably semi-automatically from description) a system that translates such SQL queries into a sequence of requests to given REST API?

How would you represent such problem? Are there any algorithms, theoretical frameworks or tools that can help?

The REST API supports:

read-only operations, i.e. only SELECT SQL queries

XPartial projections (e.g. /persons?fields=firstname,lastname)

RSQL constraints (/persons?query=firstname==John;department.code==42, see another examples).

Some references between tables (foreign keys) are represented as attributes in the REST API (such as Person.department in above constraints example), but some references are represented as subresource (e.g. /persons/{userName}/projects). This means that some queries requires to devise "a plan" to be answered in terms of REST requests.

E.g.: Query for "names of active projects of Chuck Norris" would translate to:

/persons?query=firstname==Chuck;lastname==Norris

Get userName from result

/projects/{userName}?fields=name&query=state==ACTIVE

答:
Technically the query language is just another standard the REST service should understand. It does not necessary map to query params. For example by Hydra it is possible to define a single query param which contains for example an SQL. All you need is a vocab in which you can describe SQLs, and ofc a client which can build SQL and a server which can understand SQL. The common vocab is the contract between the client and the server in this case. Some talk about this. So you don't have to create an own query language, you can reuse any existing query language...

WADL and other REST description languages are a bad start, because REST have an uniform interface / HATEOAS constraint which states that the clients have to use hyperlinks in order to change their state. The clients should decide which hyperlink to chose by checking their semantics. The link metadata (for example link relation) contains that semantics... By languages like WADL there are no links, link metadata, or semantics, and so the REST client cannot be reused, since is not decoupled from the REST service. :S


问:
Breaking a function into smaller ones is great... except for what about code-folding?
I'm currently reading Robert Martin's Clean Code book. So far I'm enjoying it.

Martin talks a lot about separating long functions into short functions, each doing exactly one thing at one level of abstraction.

Generally I like the idea and I understand the concept and the benefits. But I have a simple question to ask:

How is taking a logical piece of code an extracting it to a new method, different than simply 'folding' it? Most modern IDEs feature code-folding.

The advantage of code-folding is that when you need to look at that logical piece of code, you don't have to scroll up and down to find it. You just press a button and it's right there in front of you, in it's linear place.

Extracting small logical pieces of code to new methods, means that when a programmer wants to look at the method you extracted, they usually have to go scrolling up and down the page for it. That's very annoying and makes it harder to concentrate.

I agree with most of what Uncle Bob writes in his book, and I really want to agree with this point. But with code-folding a part of most modern IDEs, I can't find a real reason for this idea.

Please explain the advantages of extracting small logical pieces of code to new methods, as opposed to simply code-folding them.

(I remember there was another question on this site regarding this, but it was less focused, and the answers havn't satisfied me).

答:
The point of having smaller methods is not to save scrolling effort. The point is to be able to abstract completely from what a block of code does, because that makes reasoning about the superordinate routine easier. (And to foster reuse of that small block, but here I'm talking about the aid to reasoning.)

If you feel the need of checking what it really is that the factored-out method does, then the refactoring has failed. The name of the refactored method should tell you all you need to know; if there is doubt, then we've failed to achieve the effect we wanted.


问:
REST and RPC in multi-tier API
My team is developing a multi-tier API with scalability and modularity in mind. The public access point of the API is fully REST. However, we are splitting the data access layer as another tier in our architecture and this layer will be on another physical server. We decided that RPC would be a good communication protocol between the public facing API and the private data access layer.

We decided to use RPC over REST for the private communication between our tiers because:

Avoid REST routes duplication between each tier

Transparency in executing code/functions on different servers

The communication is private. With good documentation there shouldn't be any problems for the team to understand the communication protocol.

My question are:

Did we miss advantages or disadvantages in the choice of communication protocol for the  private communication between tiers?

What is normally use to communication between tiers in a multi-tier architecture, especially for web APIs?

答:
I am not an expert of scaling applications, but I'll try to answer your question at least partially.

REST has 3 constraints which are about scalability:

stateless constraint

You have to maintain sessions on the client side and on server side you have to authenticate every single request. So you can easily use multiple servers, because you don't need a shared session storage.

cache constraint

You have to send cache headers with every request. So your clients can cache the cacheable responses and so they send less requests.

layered system constraint

Your system components cannot see through the boundaries of the single layer they are in. The upper layer uses the services of the current layer, and the current layer uses the services of the bottom layers, and so on... So you can add load balance, cache, etc... between the client and the service, they won't recognize the existence of those components.

I think by translating REST to RPC the advantages of the layered system constraint are lost for nothing.

Title: REST and RPC in multi-tier API


答:
Code folding doesn't say anything about scope.  If you have a 2,000 line function1 that folds nicely into 200 10-line blocks, you still don't know what sort of dependencies those blocks might have with each other.

If you factor that function into lots of little sub functions (even if each sub function is only used once), you can see at a glance what variables are used where, what the dependencies are, what can be easily changed, etc.

In short, it's a lot easier to think about little functions where you can see the dependencies than it is to think about an apparently small code block that may depend on a LOT of variables defined hundreds of lines away.

1: yes, I'm exaggerating to make a point

Title: Breaking a function into smaller ones is great... except for what about code-folding?

Body:
I'm currently reading Robert Martin's Clean Code book. So far I'm enjoying it.

Martin talks a lot about separating long functions into short functions, each doing exactly one thing at one level of abstraction.

Generally I like the idea and I understand the concept and the benefits. But I have a simple question to ask:

How is taking a logical piece of code an extracting it to a new method, different than simply 'folding' it? Most modern IDEs feature code-folding.

The advantage of code-folding is that when you need to look at that logical piece of code, you don't have to scroll up and down to find it. You just press a button and it's right there in front of you, in it's linear place.

Extracting small logical pieces of code to new methods, means that when a programmer wants to look at the method you extracted, they usually have to go scrolling up and down the page for it. That's very annoying and makes it harder to concentrate.

I agree with most of what Uncle Bob writes in his book, and I really want to agree with this point. But with code-folding a part of most modern IDEs, I can't find a real reason for this idea.

Please explain the advantages of extracting small logical pieces of code to new methods, as opposed to simply code-folding them.

(I remember there was another question on this site regarding this, but it was less focused, and the answers havn't satisfied me).


问:
Are there any actual examples of profitable programmer's "worker's cooperatives"?
http://en.wikipedia.org/wiki/Worker_cooperative

I'm curious whether there are, anywhere in the world, worker's cooperatives that center on a technology business that involves either programming, IT, or some sort of IT or programming related consulting or services.

The wikipedia link above is an overview of the concept. The short form explanation is that a co-op is a worker-owned business. Also there is the notion that every worker owns shares in the business.

I am interested in knowing whether an example of a "programmer's/IT co-op" even exists.

Note: I am not talking about nor asking about a government-funded incubator nor any other socialized, state supported group. I also don't mean "co-working", which is renting an office with other self employed people doing their own thing.

I mean a going, profitable IT business operating in a competitive environment that is worker-owned and run.

答:
Motion-Twin in France, it's a small company (more than 10 employees) wich make on-line games, some of them like "www.hordes.fr" have relatively a lot of players.
Every employee share the same part of the company and profit is equally redistributed.
You can read an interview (sorry, automatic translation from French) where they talk about cooperative : techcrunch.fr</p>

ContentLicense: CC BY-SA 2.5


问:
Designing the bridge between REST layer to service layer

I am working on a project and would like to expose some REST services. The technologies used are RestEasy, EJB and JPA/Hibernate. I have structured my app so that there is a clear delimitation between the service layer and model layer. A typical service that retrieves data from the database have a signature like this: getWhateverList(idForWhichTheListWillBeRetrieved, start) - so pretty basic.

What I'm having a hard time wrapping my head around is how to bring together the stiffness of the service layer with the flexibility of the REST layer. Say for example that I would like a typical GET method producing a JSON array support operations like:

filtering - use a query param to get, for example items that have a property of type date greater/lower than the param that I provide

sorting - REST API should support asc or desc

limiting the fields that are returned from the GET operation

How would one go about designing this?

答:
filtering - use a query param to get, for example items that have a
property of type date greater/lower than the param that I provide

For that you need a query language. You can use any existing query language as long as you describe it with metadata in your links. So your clients and server can have a common contract which is described by that metadata. For example GET /users?q="statement using a standard query language".

You can describe simple queries using URI templates. For example GET /users?firstName={firstName}

sorting - rest api should support asc or desc

You can use the same links described above with additional query params. For example GET /users?sortBy="name"&direction="asc".

limiting the fields that are returned from the GET operation

You can use the same links described above with additional query params. For example GET /users?fields="firstName,secondName,age".

note: According to the uniform interface / HATEOAS constraint you have to send links to your clients. According to the uniform interface / self-descriptive messages constraint, these links have to contain meta-data (for example link relation) about what they are. So the clients can check that meta-data and chose the proper link to reach their goal.


答:
While reading the answers and comments to this question, and also while arguing with someone over this topic, I can now see two clear benefits of method-extraction over code folding:

1- As @DanPichelman and @Doval said, if you have a 200 line long function with lots of folded blocks, you have no way to see what the dependencies between them are. They can have lots of tangled dependencies.

Functions, however, define explicit in-parameters and return-value, thus making the depenendencies between the functions much more explicit. Functions can also read class-members and global state, but since the functions are small it will be visible to the programmer.

That's the most important point.

2- Also, since in ecnourages creating methods where each one does one thing, it allows for code reuse in the future. Right now you might make that new method private, but later you might need this functionality somewhere else, so you might extract this method to a shared utility-class or something. This would be easy if it's an extracted method, and much more dangerous if it's a folded-block: again, because of the implicit dependencies between blocks.

Thanks for helping me understand


问:
how should I change the representation (not mimetype) of a resource?
I'm looking at how I can change the representation of a payload at runtime for varied potential advantages, but I'm not sure how to do it. Specifically collections.

Array of Pairs

```<code>[{ <resource_uri> : { <entity> }, ...}]
</code>```

Array of Objects

```<code>[<entity>,...]
</code>```

Array of Resources

```<code>[<resource_uri>]
</code>```

Map of entities

```<code>{ <resource_uri> : { <entity> }, ... }
</code>```

My problem is, I'm not sure if I should put these different representations of the sets at different URI's, give them slightly varied mime types, e.g. application/foomap+json or perhaps use an optional query parameter ?format=map, or resource /entities/map. The UI is going to hide this, this is for programmatic web service access only (which the "UI's JS will have to call).

答:
The simplest way to use different URIs. You can use optionally the prefer header if you want.

I suggest you to use standard generic MIME types, like HAL, JSON-LD, etc... instead of creating custom ones, so your clients won't need to write custom parsers...


答: In addition to the other answers, one word: DRY. With a long folded method, there is no way to easily see if a fix you need to make in one place also needs to be made elsewhere - possibly many times - other than unfolding the lot and wading through it. Your maintenance programmers will like you better if the code is structured so that they can be confident they only have to make a change once.</p>


问:
Onshore / Offshore (Team and Testing)
Can anyone describe to me what Onshore / Offshore team is and what Onshore / Offshore testing is? Because i am studying this article and I can't find anywhere the specific meanings about the above phrases.

答:
First you need to start with the terms "in-house" and "outsourced" with respect to development.

In-house means software development performed by employees of the company that is paying for development.

Outsourced means software development performed by employees of a different company that is paying for development.  Outsourced development frequently stills requires an in-house employee to oversee the outsourced development.

With those two concepts, you can extend to the geographic location of the developers.

On-shore development means that the developers are located in the same geography of the company that is paying for the development.

Off-shore development means that the developers are located in a different geography, and more specifically in a different country, than the company that is paying for the development.

Note that you can have in-house development that is also off-shore.  Large multinational development firms (IBM, Microsoft, various consulting agencies, etc...) have branches in multiple countries and can share development tasks across those different teams.

More often than not though, off-shore generally refers to outsourced development.

As far as on-shore and off-shore testing, it's the same model as development.  The on | off shore aspect refers to the geographic location of the testing with regards to the company paying for the project.

It's not uncommon to see hybrid combinations of those teams.  For example, there may be a smaller, core development team that is in-house and on-shore that guides the work of a larger off-shore team that may or may not be out-sourced.  Some of the testing may be handled by the off-shore team, with key tests handled by the in-house, on-shore team as a means of additional QA on the work being done.

Title: Onshore / Offshore (Team and Testing)


答:
There are two main reasons to put code into multiple functions:

Abstraction/Encapsulation

Reusability

Reusability is of course the simplest to explain.  If I have a function:

```<code>int do_QWERTYalgo(int data1, int data2)
{ /*do stuff*/ }
</code>```

Then obviously, if I need to do that workagain, I can just call the function from elsewhere , and "tada!" it's done, and I don't need to write it again.

Of course you know that, but have you thought about implementing a program where you need to do it multiple times with different intermediate steps?

```<code>//...
a1 = 5;
a2 = 7;
a = do_QWERTYalgo (a1, a2);
b1 = a;
b2 = 8;
b = do_QWERTYalgo (b1, b2);
c = do_QWERTYalgo (a, b);
</code>```

Suddenly, we've cut down a lot on the amount of code we need to write.

Additionally, if do_QWERTYalgo was implemented incorrectly, we only need to change it in one single location now, which brings us nicely to our other point:

do_QWERTYalgo is abstracted and encapsulated from the rest of the code.

The algorithm running above has no need to know how the do_QWERTYalgo algorithm works, it just plugs in the inputs and recieves the output.

Also, should do_QWERTYalgo need to change, as long as the inputs and outputs don't change, nothing else needs to change in the code.

To explain how this is meant to help you:
lets say you are using a library to provide encrypted communication between yourself and a friend. Suddenly, there is news that the encryption method used is extremely vunerable to a new type of hack.  Suddenly, there is a problem with your chat program.  What do you do?
Well, you grab an updated version of the library. Done.  There may be dozens of places in your code where you use functionality provided by the library, but because the encryption functions are not embedded in your application code, you don't need to hunt down every single use and change it manually.

Another way of thinking about this:
the function you are writing is a person. Said person wants to drive from A to B. So the person gets into the car and puts input into the car via the push_pedals and turn_wheel methods.  With the correct inputs, the person gets to where they want to go.

Writing all your code in one big super method is like getting your person to implement the fuel_injection functionality, the ignite_fuel functionality, the gearboxand clutch functionalities, the turn_wheels_on_road_when_steering_wheel_turned functionality, the push_pedals, accellerate, brake functionalities, while also having to drive the car...

everything still happens as before, but there is a lot more work going on.

All code-folding does is hide some of that from your view, it's no better than giving your navigator a blindfold.

Body:
There are two main reasons to put code into multiple functions:

Abstraction/Encapsulation

Reusability

Reusability is of course the simplest to explain.  If I have a function:

int do_QWERTYalgo(int data1, int data2)
{ /*do stuff*/ }

Then obviously, if I need to do that workagain, I can just call the function from elsewhere , and "tada!" it's done, and I don't need to write it again.

Of course you know that, but have you thought about implementing a program where you need to do it multiple times with different intermediate steps?

//...
a1 = 5;
a2 = 7;
a = do_QWERTYalgo (a1, a2);
b1 = a;
b2 = 8;
b = do_QWERTYalgo (b1, b2);
c = do_QWERTYalgo (a, b);

Suddenly, we've cut down a lot on the amount of code we need to write.

Additionally, if do_QWERTYalgo was implemented incorrectly, we only need to change it in one single location now, which brings us nicely to our other point:

do_QWERTYalgo is abstracted and encapsulated from the rest of the code.

The algorithm running above has no need to know how the do_QWERTYalgo algorithm works, it just plugs in the inputs and recieves the output.

Also, should do_QWERTYalgo need to change, as long as the inputs and outputs don't change, nothing else needs to change in the code.

To explain how this is meant to help you:
lets say you are using a library to provide encrypted communication between yourself and a friend. Suddenly, there is news that the encryption method used is extremely vunerable to a new type of hack.  Suddenly, there is a problem with your chat program.  What do you do?
Well, you grab an updated version of the library. Done.  There may be dozens of places in your code where you use functionality provided by the library, but because the encryption functions are not embedded in your application code, you don't need to hunt down every single use and change it manually.

Another way of thinking about this:
the function you are writing is a person. Said person wants to drive from A to B. So the person gets into the car and puts input into the car via the push_pedals and turn_wheel methods.  With the correct inputs, the person gets to where they want to go.

Writing all your code in one big super method is like getting your person to implement the fuel_injection functionality, the ignite_fuel functionality, the gearboxand clutch functionalities, the turn_wheels_on_road_when_steering_wheel_turned functionality, the push_pedals, accellerate, brake functionalities, while also having to drive the car...

everything still happens as before, but there is a lot more work going on.

All code-folding does is hide some of that from your view, it's no better than giving your navigator a blindfold.


问:
Is this a secure solution for RESTful authentication?
I need to quickly implement a RESTful authentication system for my JavaScript application to use. I think I understand how it should work, but I just want to double check. Here's what I'm thinking -- what do you guys think?

Database schema

users

id : integer

first_name : varchar(50)

last_name : varchar(50)

password : varchar(32) (MD5 hashed)

etc.

user_authentications

id : integer

user_id : integer

auth_token : varchar(32) (AES encrypted, with keys outside database)

access_token : varchar(32) (AES encrypted, with keys outside database)

active : boolean

Steps

The following happens over SSL. I'm using Sinatra for the API.

JavaScript requests authentication via POST to /users/auth/token.

The /users/auth/token API method generates an auth_token hash, creates a record in user_authentications, and returns auth_token.

JavaScript hashes the user's password and then salts it with auth_token -- SHA(access_token + MD5(password))

POST the user's username and hashed+salted password to /users/auth/authenticate.

The /users/auth/authenticate API method will verify that SHA(AES.decrypt(access_token) + user.password) == what was received via POST.

The /users/auth/authenticate will generate, AES encrypt, store, and return an access token if verification is successful; otherwise, it will return 401 Unauthorized.

For any future requests against the API, JavaScript will include access_token, and the API will find the user account based on that.

答: As Donal Fellows said, this is just wasting time. If you don't have a secure channel, you should get one instead of reinventing the wheel. If you already have a secure channel, then you don't need another (inferior) encryption mechanism...</p>


问:
Why does changing from one language to another make a programmer fresher?
Right now I have been working on language X for the last 2 years. I am very good at it, but language X is not popular so jobs are not readily available for it. Consequently, I am thinking to change from language X to language Y. But that means I'll be a fresher again. Is making the change worth it? Even if it means losing all the experience I have in the other language? </p>

答: I don't understand what's the problem. You will still be proficient in it while learning a new language (which can only be taken as an advantage).</p>


问:
How to predict a future simulation state
We have a program that combines the simulation of an aircraft system and predefined pedagogical scenarios for trainee pilots to learn how to use this system.

When we follow the normal scenario, chapter after chapter, everything goes smoothly.

Now, when the trainee skips the chapter N and goes directly to the chapter N+1, the simulation goes snafu because the chapter N was not executed by the simulation, resulting in an incoherent state.

As a remedy, we write the desired simulation state in the scenario file, just after the chapter entry point.

The problem is it's not possible to predict the simulation state for chapter N if we don't know the scenario first by heart. And some scenarios are very complex. A developer has to spend a long time studying the scenario to get an accurate picture of what is expected by the trainee then he jumps to chapter N.

The software doesn't need persistence. That is, we don't have to save the simulation state when the program is not running.

The simulation state is managed by ~200 000 variables. It is not possible for us to make a snapshot of the simulation state at every step because it would be highly impracticable, and each time the scenario is updated, the snapshot would be out of date.

We also don't have access externally to all variables since some are private and are out of bounds (And even if we had access, it would be a bad idea, given the sheer amount of data).

Is it a common problem and are there best practices and known solutions to tackle this issue ?

答: Run the simulator through every step to N+1, and then record the state.  When you want to jump to N+1, just restore the state you recorded.


问:
When I create an object, is fresh memory allocated to both instance fields and methods or only to instance fields
I have a following class

```<code>class Student{

int rollNumber;
int marks;

public void setResult(int rollNumber, int marks){

    this.rollNumber=rollNumber;
    this.marks=marks;
}

public void displayResult(){

    System.out.println("Roll Number= "+this.rollNumber+"   Marks= "+this.marks);

}
}
</code>```

Now I create two objects of type Student as follows

```<code>Student s1=new Student();
Student s2=new Student();
</code>```

Now two different sets of memory is allocated for instance fields. Now my question is whether memory is allocated for methods (setResult and displayResult) twice or once?

Please see the following figure and can you help me saying which figure gives correct information.

答:
The code for methods is part of the Class (more concisely, Class<Student>) and it is loaded into memory when the class is first loaded.

That said, when you execute any method additional memory is used, to allocate memory to parameters, local variables, temporary expression results, return values and so on. But such memory is allocated in the stack (the memory used when creating a new instance is allocated in the heap.

As per your question, it should be clear now that figure B is correct (although it does not reflect what happens when you actually call the method).


问:
REST API concepts
I have three questions about REST API design that I'm hoping someone can shed some light on. I've searched relentlessly for many hours but haven't found answers to my questions anywhere (maybe I just don't know what to search for?).

Question 1

My first question has to do with actions/RPC. I've been developing a REST API for a while and I'm used to thinking of things in terms of collections and resources. However, I've come across a couple cases where the paradigm doesn't seem to apply and I'm wondering if there is a way to reconcile this with the REST paradigm.

Specifically, I have a case where modifying a resource causes an email to be generated. However, at a later point the user can specifically indicate that they want to resend the email that was sent earlier. When resending the email no resource is modified. No state is changed. It's simply an action that needs to occur. The action is tied to the specific resource type.

Is it appropriate to mix some sort of action call with a resource URI (e.g. /collection/123?action=resendEmail)? Would it be better to specify the action and pass the resource id to it (e.g. /collection/resendEmail?id=123)? Is this the wrong way to be going about it? Traditionally (at least with HTTP) the action being performed is the request method (GET, POST, PUT, DELETE), but those don't really allow for custom actions with a resource.

Question 2

I use the querystring portion of the URL to filter the set of resources returned when querying a collection (e.g. /collection?someField=someval). Within my API controller I then determine what kind of comparison it is going to do with that field and value. I've found this really doesn't work. I need a way to allow the API user to specify the type of comparison they want to perform.

The best idea I've come up with so far is to allow the API user to specify it as an appendage to the field name (e.g. /collection?someField:gte=someval - to indicate that it should return resources where someField is greater than or equal to (>=) whatever someval is. Is this a good idea? A bad idea? If so, why? Is there a better way to allow the user to specify the type of comparison to perform with the given field and value?

Question 3

I often see URI's that look something like /person/123/dogs to get the persons dogs. I generally have avoided something like that because in the end I figure that by creating a URI like that you are actually just accessing a dogs collection filtered by a specific person ID. It would be equivalent to /dogs?person=123. Is there ever really a good reason for a REST URI to be more than two levels deep (/collection/resource_id)?

答:
Is it appropriate to mix some sort of action call with a resource URI
  (e.g. /collection/123?action=resendEmail)? Would it be better to
  specify the action and pass the resource id to it (e.g.
  /collection/resendEmail?id=123)? Is this the wrong way to be going
  about it? Traditionally (at least with HTTP) the action being
  performed is the request method (GET, POST, PUT, DELETE), but those
  don't really allow for custom actions with a resource.

Not, it is not appropriate, since IRIs are for identifying resources and not operations (however ppl use this method override approach for a while, in cases when using non POST and GET methods is not supported). What you can do is looking for an appropriate HTTP method, or create a new one. POST can be your friend in these cases (ppl use it if they cannot find an appropriate method and the request is not retrieval). Another approach to make resources from email sending and so POST /emails can send the mails without creating a real resource. Btw. URI structure does not carry semantics, so from a REST perspective it does not really matter what kind of URIs you use. What matters is the meta-data (e.g. link relation) assigned to the links you sent to the clients.

The best idea I've come up with so far is to allow the API user to
  specify it as an appendage to the field name (e.g.
  /collection?someField:gte=someval - to indicate that it should return
  resources where someField is greater than or equal to (>=) whatever
  someval is. Is this a good idea? A bad idea? If so, why? Is there a
  better way to allow the user to specify the type of comparison to
  perform with the given field and value?

You don't have to create an own query language. I would rather use an already existing one and add some query description to the link meta-data. You should use probably an RDF media type (e.g. JSON-LD) to do that or use a custom MIME type (afaik there is no non-RDF format which supports this). Using existing standards decouple your client from the server, that's what the uniform interface constraint is about.

It would be equivalent to /dogs?person=123. Is there ever really a
  good reason for a REST URI to be more than two levels deep
  (/collection/resource_id)?

As I previously mentioned, the URI structure does not matter from a REST perspective. You could use /x71fd823df2 for example. It still would make sense to the clients because they check meta-data assigned to the links and not the URI structure. The main purpose of URI is identifying resources. In the URI standard they state that the path contains hierarchical data and the query contains non-hierarchical data. But it can be very subjective what is hierarchical. That's why you meet multiple levels deep URIs and URIs with long queries either.

I've searched relentlessly for many hours but haven't found answers to
  my questions anywhere (maybe I just don't know what to search for?).

You should read at least the REST constraints from the Fielding dissertation, the HTTP standard, and probably 3rd generation web APIs from Markus.

Title: REST API concepts


答:
Instance fields (including property backing fields) get N-copies for N-objects.

Static fields get a single copy per class.

Methods are blocks of bytecode (or after JIT, blocks of native instructions) that are part of the program "image" or executable code segment. Methods are already part of the program image as it sits on disk. Once the image is loaded by the OS (or CLR), there is a single shared copy of the method code.

They aren't part of "heap" or runtime allocation in general, except in cases where you may use the hostable compiler to compile new methods on the fly. Methods don't get "allocated" like objects and they aren't "allocated" relative to the object creation. They merely exist as part of the program before a single object is ever instantiated. Even lambdas / delegates aren't allocated on the fly. The compiler creates classes on-demand to implement these other seemingly dynamic code objects, and they also exist as part of the bytecode image on disk.

UPDATES per comments:

The JVM standard has this to say:

2.5.4. Method Area

The Java Virtual Machine has a method area that is shared among all
  Java Virtual Machine threads. The method area is analogous to the
  storage area for compiled code of a conventional language or analogous
  to the "text" segment in an operating system process. It stores
  per-class structures such as the run-time constant pool, field and
  method data, and the code for methods and constructors, including the
  special methods (§2.9) used in class and instance initialization and
  interface initialization.

The method area is created on virtual machine start-up. Although the
  method area is logically part of the heap, simple implementations may
  choose not to either garbage collect or compact it. This version of
  the Java Virtual Machine specification does not mandate the location
  of the method area or the policies used to manage compiled code. The
  method area may be of a fixed size or may be expanded as required by
  the computation and may be contracted if a larger method area becomes
  unnecessary. The memory for the method area does not need to be
  contiguous.

So it is clear that (1) yes the spec does not dictate how this is done, but (2) it is analogous to the storage area for compiled code of a conventional language, ie. the text segment. This is the point I'm making.

Title: When I create an object, is fresh memory allocated to both instance fields and methods or only to instance fields

Body:
I have a following class

```<code>class Student{

int rollNumber;
int marks;

public void setResult(int rollNumber, int marks){

    this.rollNumber=rollNumber;
    this.marks=marks;
}

public void displayResult(){

    System.out.println("Roll Number= "+this.rollNumber+"   Marks= "+this.marks);

}
}
</code>```

Now I create two objects of type Student as follows

```<code>Student s1=new Student();
Student s2=new Student();
</code>```

Now two different sets of memory is allocated for instance fields. Now my question is whether memory is allocated for methods (setResult and displayResult) twice or once?

Please see the following figure and can you help me saying which figure gives correct information.


问:
Should I use a single platform for common services or modularize them?
I am designing a suite of web applications that have the same base functionality. That is, they all will know how to create and operate on widgets. The differences will be in their target audience and how a user will interact with a widget. Essentially, if these applications were developed independently, there would be a lot of duplicated effort.

To simplify this I have thought of two solutions. I would like all of your feedback on the pros and cons for each solution, and which you would prefer.

"Platform" -- The idea is that there is an independent service layer, a la web services. It wouldn't be a web service, but simply a back-end for all the applications. The platform would talk to the applications via messaging or object serialization.

I would want to write the platform with Java, but the intention would be that the applications could be written with any web framework such as Rails, Django, Flex, or just something in Java.

The platform would abstract the database, so all interaction with the back-end would be done via the platform. One potential problem with this is that updating the platform will entail taking down all the applications. But at least all the applications will be consistent in regards with the back-end.

I like how this is cut horizontally, and that the application really only has to focus on the front-end, rather then worrying about how to organize the back-end.

"Modules" -- The idea is that I just write everything with Java and develop modules which would live in their own jars. Each module would represent a Guice module and each application would just include the modules they want, and create their own Injectors.

This approach would make each application completely independent from each other, aside of sharing a common database. So, theoretically, it would be much easier to deploy an application in a different environment with out worrying about the platform. I would be stuck in one language environment, Java. Although, JRuby and Jython would be available. So maybe that isn't much of a concern.

Also, I foresee it being easier to customize an application with out effecting the platform. The one con is that if I update a module, I would want to redeploy each application using that module. This would be easy with continuous integration, though.

Thank you for your time.

In regards to Gary's answer, I've decided to take a hybrid approach.

I'm going to develop a platform, which will be the access point for the web applications to data and services. I will then modularize the platform, but all the modules will remain under a single repository with a parent POM. While I could just keep them all in a single JAR, I would like the classpath separation for development purposes, to make me/others think before requiring a module to depend on another.

答:
Platform

I like the idea of the platform approach, but there are a couple of points you mention that give me cause for concern.

Why not make the back-end entirely stateless and RESTful? You know, have a bunch of web services that provide the necessary JSON or XML to drive the front end clients. These clients could be written in any language you like, so long as they can consume/produce the necessary intermediate representation. Implementing RESTful web services these days is trivial with JAX-RS implementations like RESTEasy just a Maven dependency away.

Having the platform abstract the database away is good practice simply because you want your client and your services to be as independent of each other as possible.

You mention that updates to the platform would mean taking down the whole system. Why? If you're serious about it, you'll have your live and fail-over clusters running in parallel. You upgrade your fail-over cluster and run your verification test suite on it to ensure it's up to scratch. Then you switch your load balancer to use the fail-over cluster instead of the live one (the live becoming fail-over). If your platform is truly stateless your clients operations will be uninterrupted since the DNS of your services remains the same.

I'd caution against using Java object serialization (e.g. RMI) just because of the binary API restrictions you may encounter if you decide to update the objects.

Modules

Sharing common code between modules is trivial with a build system like Maven (or Ivy if you can't leave Ant). Having a common back-end language will also reduce the learning curve for new developers. Also you'd doubtless have a large collection of template base classes to support common functions in the different back-end layers (DAOs, DTOs, BOs etc). (This is also true of the platform approach).

Given that each module is separate and independent of each other you may find that if developers don't communicate effectively, code duplication will likely occur within modules. Also, bugs will be fixed in one module, but missed in another. This is especially true if you're creating multiple variations of a module to look after different clients.

Obviously, dependency injection and good design will go a long way to mitigate this, but you may find the solution more complex than if you go the platform route.


问:
How much pair programming is ideal?
I think pair programming can be incredibly effective, and I don't mind doing it every now and then, but a company I've interviewed with states they pair program "95% of the time" (they're a consulting shop, so they do this on client sites).

This worries me because it sounds very demanding/exhausting. I realize it increases productivity, but to do it all day, every day, may actually decrease my morale and ability to think. I wonder if they sell this idea to clients to assure them of greater productivity...

答:
The idea behind pair programming is that you back each other up and bounce ideas off each other in real time. If one of the two of you gets hits by a bus, the project still goes on with little to no interruption. If both of you got hit by the same bus, well ... :)

The idea behind pair programming is not that you are going faster, but that you and your partner in crime, working as a team, go faster as a team as a result of your effectiveness in thinking out how to resolve issues and your efficiency in implementing your thoughts without making major mistakes. In other words, speed is a by-product and consequence of the process of pair programming not its primary or secondary goal. The primary goal of pair programming is clean, reliable, maintainable code not a faster way to write crappy code.

OwnerDisplayName: J L

Title: How much pair programming is ideal?

OwnerDisplayName: Vietnhi Phuvan


问:
Is this a valid design pattern for a Haskell main function?
After developing several Haskell applications I've found myself rigorously segregating impure code and failable (partial) functions from their pure & total counterparts. These efforts have noticeably reduced maintenance cost associated with the applications. I have found myself over time relying on the same high level main structure to enforce this segregation.

In general, my main will have the following structure:

import System.Environment

data ProgramParameters = P ()
data ComputationResult = I ()

main :: IO ()
main = getArgs                           -- Collect arguments
   >>= andOrGetUserInput                 -- Collect user input
   >>= impureOrFailableComputations      -- Possible non-recoverable error(s)
   >>= either                            -- "Branch"
         putStrLn                        -- Print Any Failure(s)
         pureNotFailableComputations     -- Finish the work

andOrGetUserInput :: [String] -> IO ProgramParameters
andOrGetUserInput = undefined

impureOrFailableComputations :: ProgramParameters -> IO (Either String ComputationResult)
impureOrFailableComputations = undefined -- a composition of partial functions
                                         -- made total by catching exceptions & input errors
                                         -- in the short-circuiting ErrorT/EitherT monad

pureNotFailableComputations :: ComputationResult -> IO ()
pureNotFailableComputations = undefined  -- a composition of total functions
```

The goal is to coalesce partial computations in a monad, creating a total monadic computation.

This has become a pattern in the code base, and I would like feedback on whether this is a design pattern or an anti-pattern.

Is this an idiomatic way to segregate & catch partial computations?

Are there notable drawbacks to this high level segregation?

Are there better abstraction techniques?

答:
This design makes several non-trivial assumptions:

The user's input will not depend on the results of pure or impure computations.

The impure computations will not depend on the result of pure computations.

The program logic will not loop; it will run only once.

My other comment on your structure is that you do not need to separate the pure and impure calculations. Haskell's type system already does that for you.

That said, this structure certainly looks useful for certain classes of programs, especially if you're sure the assumptions I outlined above actually hold true for your program. It's not something every program should use, though.

OwnerDisplayName: awashburn


问:
IOC Containers break OOP Principles
What is the purpose of IOC Containers?  The combined reasons for it can be simplified to the following:

When using OOP/SOLID Development principles, Dependency Injection gets messy.  Either you have the top-level entry points managing dependencies for multiple levels below themselves and passing dependencies recursively through construction, or you have somewhat duplicate code in factory/builder patterns and interfaces that build dependencies as you need them.

There is no OOP/SOLID way to perform this AND have super pretty code.

If that previous statement is true, then how do IOC Containers do it?  As far as I know, they aren’t employing some unknown technique that can't be done with manual D.I.  So the only explination is that IOC Containers break OOP/SOLID Principles by using static objects private accessors.

Do IOC Containers break the following principles behind the scenes?  This is the real question since I have a good understanding, but have a feeling somebody else has a better understanding:

Scope control.  Scope is the reason for nearly every decision I make on my code design.  Block, Local, Module, Static/Global.  Scope should be very explicit, as much at block-level and as few at Static as possible.  You should see declarations, instantiations, and lifecycle endings.  I trust the language and GC to manage scope as long as I’m explicit with it.  In my research I’ve found that IOC Containers set up most or all dependencies as Static and control them through some AOP implementation behind the scenes.  So nothing is transparent.

Encapsulation.  What is the purpose of encapsulation?  Why should we keep private members so?  For practical reasons it is so implementors of our API can’t break the implementation by changing the state (which should be managed by the owner class).  But also, for security reasons, it’s so injections can’t occur that overtake our member states and bypass validation and class control.  So anything (Mocking frameworks or IOC frameworks) that somehow injects code before compile time to allow external access to private members is pretty huge.

Single Responsibility Principle.  On the surface, IOC Containers seem to make things cleaner.  But imagine how you would accomplish the same thing without the helper frameworks.  You would have constructors with a dozen or so dependencies being passed in.  That doesn’t mean cover it up with IOC Containers, it is a good thing!  It’s a sign to re-factor your code and follow SRP.

Open/Closed.   Just like SRP isn’t Class-Only (I apply SRP down to single-responsibility lines, let alone methods).  Open/Closed is not just a high level theory to not alter the code of a class.  It’s a practice of understanding the configuration of your program and having control over what gets altered and what gets extended.  IOC Containers can change the way your classes work altogether partially because:

a.   The main code isn’t making the determination of switching out
dependencies, the framework configuration is.

b.   The scope could be altered at a time that isn’t controlled by the
calling members, it is instead determined externally by a static
framework.

So the configuration of the class isn’t really closed is it, it alters itself based on the configuration of a third party tool.

The reason this is a question is because I am not necessarily a master of all IOC Containers.  And while the idea of an IOC Container is nice, they appear to just be a façade that covers up poor implementation.  But in order to accomplish external Scope control, Private member access, and Lazy loading, a lot of non-trivial questionable things have to go on.  AOP is great, but the way it is accomplished through IOC Containers is also questionable.

I can trust C# and the .NET GC to do what I expect it to.  But I can’t put that same trust in a third party tool that is altering my compiled code to perform workarounds to things I wouldn’t be able to do manually.

E.G.: Entity Framework and other ORMs create strongly Typed objects and map them to database entities, as well as provide boiler-plate basic functionality to perform CRUD.  Anybody could build their own ORM and continue to follow OOP/SOLID Principles manually.  But those frameworks help us so we don’t have to re-invent the wheel every time.  Whereas IOC Containers, it seems, help us purposely work around OOP/SOLID Principles and cover it up.

答:
Don't IOC containers break a lot of these principles?

In theory? No. IoC containers are just a tool. You can have objects that have a single responsibility, well separated interfaces, can't have their behavior modified once written, etc.

In practice? Absolutely.

I mean, I've heard not a few programmers say that they use IoC containers specifically to allow you to use some configuration to change the behavior of the system - violating the Open/Closed Principle. There used to be jokes made about coding in XML because 90% of their job was fixing Spring configuration. And you're certainly correct that hiding the dependencies (that admittedly, not all IoC containers do) is a quick and easy way to make highly coupled and very fragile code.

Let's look at it a different way. Let's consider a very basic class that has a single, basic dependency. It depends on an Action, a delegate or functor that takes no parameters and returns void. What is this class' responsibility? You can't tell. I could name that dependency something clear like CleanUpAction which makes you think it does what you want it do. As soon as IoC comes into play it becomes anything. Anyone can go into the configuration and modify your software to do pretty much arbitrary things.

"How is that different from passing in an Action to the constructor?" you ask. It's different because you can't change what's being passed into the constructor once the software is deployed (or at runtime!). It's different because your unit tests (or your consumers' unit tests) have covered the scenarios where the delegate is passed into the constructor.

"But that's a bogus example! My stuff doesn't allow changing behavior!" you exclaim. Sorry to tell you, but it does. Unless the interface you're injecting is just data. And your interface isn't just data, because if it were just data you'd be building a simple object and using that. As soon as you have a virtual method in your injection point, the contract of your class using IoC is "I can do anything".

"How is that any different from using scripting to drive things? That's perfectly fine to do." some of you ask. It isn't different. From a program design perspective, there's no difference. You're calling out of your program to run arbitrary code. And sure, that's been done in games for ages. It's done in tons of systems administration tools. Is it OOP? Not really.

There's no excuse for their current ubiquity. IoC containers have one solid purpose - to glue together your dependencies when you have so many combinations of them, or they shift so rapidly that it is impractical to make those dependencies explicit. So very few businesses actually fit that scenario though.

Title: IOC Containers break OOP Principles


问:
RESTful composition/inclusion of other resources
I have a few HTTP resources, and i'm wondering if including the models of one in the other is acceptable or if there is a cleaner method.

In this example, we have a ton of "news" resources, and users can subscribe via a resource called "subscription":

```<code>==>/news-items/{id}/
{
    "id": 987,
    "url": "http://example.com/foo/bar",
    "title": "Wow! A Headline",
}
</code>```

And

```<code>==> /users/{user-id}/subscriptions/
[
    {
         "id" : 123
         "keywords": "Mr Celebrity"
    },
    ...
]
</code>```

And then the endpoint that includes the models of both resources ...

```<code>==> /users/{user-id}/my-news/
[
    {
        "id": 987,
        "url": "http://example.com/foo/bar",
        "title": "Wow! A Headline",
        "matched_by": [
            {
                "id": 123,
                "keywords": "Wow",
            },
            ...
        ]
    },
    ...
]
</code>```

The usecase is fairly self explanatory for this: A feed of news with 'matched by "Mr Celebrity"' next to it. It feels a bit weird to have an endpoint that consists only of nested/composite models from other endpoints ... Is this acceptable practice or problematic?

The endpoint will be read-only, and the other options seem to be:

HATEOAS-style: "matched_by" and the news item are URLs pointing to a news item and subscription. Would require more HTTP requests.

Some kind of multi-payload response with a HATEOAS primary payload then 'related' payload of the referenced resources. Not seen this done before.

??? some other options?

If my approach is sound, great, but I want to hear what others would do if there is a better alternative.

Thanks :)

答:
A feed of news with 'matched by "Mr Celebrity"' next to it. It feels a
  bit weird to have an endpoint that consists only of nested/composite
  models from other endpoints ... Is this acceptable practice or
  problematic?

Having embedded resource representations is perfectly valid, since you describe a resource graph in where every resource can be connected to another resources...

If I were you I'd check some standard hypermedia type instead of creating an own. For example: JSON-LD, HAL, Collection+JSON, etc...

HATEOAS-style: "matched_by" and the news item are URLs pointing to a
  news item and subscription. Would require more HTTP requests.

HATEOAS is about using hyperlinks, not plain URLs. Don't confuse these terms... A hyperlink consists of at least a HTTP method (calling an operation) and an URL (on a resource). By REST you have to add some meta-data to it, for example link relation or Hydra:Operation (if you prefer RDF).

Just a copy-paste HAL example from one of the linked sites:

```<code>{
    "_links": {
        "self": { "href": "https://api.example.com/player/1234567890/friends" },
        "next": { "href": "https://api.example.com/player/1234567890/friends?page=2" }
    },
    "size": "2",
    "_embedded": {
        "player": [
            {
                "_links": {
                    "self": { "href": "https://api.example.com/player/1895638109" },
                    "friends": { "href": "https://api.example.com/player/1895638109/friends" }
                },
                "playerId": "1895638109",
                "name": "Sheldon Dong",
                "alternateName": "sdong",
                "image": "https://api.example.com/player/1895638109/avatar.png"
            },
            {
                "_links": {
                    "self": { "href": "https://api.example.com/player/8371023509" },
                    "friends": { "href": "https://api.example.com/player/8371023509/friends" }
                },
                "playerId": "8371023509",
                "name": "Martin Liu",
                "alternateName": "mliu",
                "image": "https://api.example.com/player/8371023509/avatar.png"
            }
        ]
    }
}
</code>```

As you can see this defines one size property and two embedded players for a collection resource. Every representation contains links. You can find the main resource identifier (URI) under the links having self link relation. This is just one example. Most of the generic hypermedia types use similar approaches. Btw. this is just the GET part of the story. (HAL does not support POST, PUT, DELETE links, you have to use an extension to describe them.)

Understanding a better solution, like RDF with JSON-LD and Hydra would be a longer story...

Body:
A feed of news with 'matched by "Mr Celebrity"' next to it. It feels a
  bit weird to have an endpoint that consists only of nested/composite
  models from other endpoints ... Is this acceptable practice or
  problematic?

Having embedded resource representations is perfectly valid, since you describe a resource graph in where every resource can be connected to another resources...

If I were you I'd check some standard hypermedia type instead of creating an own. For example: JSON-LD, HAL, Collection+JSON, etc...

HATEOAS-style: "matched_by" and the news item are URLs pointing to a
  news item and subscription. Would require more HTTP requests.

HATEOAS is about using hyperlinks, not plain URLs. Don't confuse these terms... A hyperlink consists of at least a HTTP method (calling an operation) and an URL (on a resource). By REST you have to add some meta-data to it, for example link relation or Hydra:Operation (if you prefer RDF).

Just a copy-paste HAL example from one of the linked sites:

{
    "_links": {
        "self": { "href": "https://api.example.com/player/1234567890/friends" },
        "next": { "href": "https://api.example.com/player/1234567890/friends?page=2" }
    },
    "size": "2",
    "_embedded": {
        "player": [
            {
                "_links": {
                    "self": { "href": "https://api.example.com/player/1895638109" },
                    "friends": { "href": "https://api.example.com/player/1895638109/friends" }
                },
                "playerId": "1895638109",
                "name": "Sheldon Dong",
                "alternateName": "sdong",
                "image": "https://api.example.com/player/1895638109/avatar.png"
            },
            {
                "_links": {
                    "self": { "href": "https://api.example.com/player/8371023509" },
                    "friends": { "href": "https://api.example.com/player/8371023509/friends" }
                },
                "playerId": "8371023509",
                "name": "Martin Liu",
                "alternateName": "mliu",
                "image": "https://api.example.com/player/8371023509/avatar.png"
            }
        ]
    }
}

As you can see this defines one size property and two embedded players for a collection resource. Every representation contains links. You can find the main resource identifier (URI) under the links having self link relation. This is just one example. Most of the generic hypermedia types use similar approaches. Btw. this is just the GET part of the story. (HAL does not support POST, PUT, DELETE links, you have to use an extension to describe them.)

Understanding a better solution, like RDF with JSON-LD and Hydra would be a longer story...


问:
Dealing with browser cache in single-page apps
I'm trying to figure out how to properly handle the web browser cache for single page apps.

I have a fairly typical design: several HTML, JS and CSS files implementing the SPA, and a bunch of JSON data that's consumed by the SPA. Problems arise when I want to push an update: I update the static portion of the site and the code that generates the JSON at the same time, but client browsers often have the static portion cached, so old code tries to process the new data and may (depending on changes made) run into problems. (In particular, IE seems more aggressive than Chrome or Firefox about using cached JS without revalidating.)

What's the best way to handle this?

Make sure my JSON changes are backwards-compatible, and assume browser caches will expire in a reasonable timeframe.

Embed some sort of version number in both the static JS and the JSON, then execute window.location.reload(true); if they don't match.

Figure out the appropriate combination of headers (must-revalidate or no-cache or whatever; sources vary on how to do this) to ensure that browsers always revalidate all resources on every load, even if it means a few extra round trips to load the site.

Micro-manage my cache-control and expires headers so that static content expires when I want to push an update.

Something else?

答:
You need a cache busting solution. The role of cache busting is:

Rename resources to a unique name depending on their content.

Update all references to those resources.

In a Grunt-based project it's common to use grunt-rev to ensure that all files that need to be refreshed are given unique names, based on their content.

If you ensure that your JSON files get cachebusting filenames along with the references to them in your Javascript, clients will always load the JSON files that the Javascript expects.

The advantage of hash-based file naming is that files that have not changed will get the same filenames after cache-busting, so browsers can continue to safely use cached content when it has not changed.

Obviously this is the kind of thing you want to be automated as part of your project's production build so you don't have to keep track of changing file names & references manually.


问:
Declaring many times: script type="text/javascript"
Trying to clear my HTML code, is it correct if in my web page I declare many blocks of

<script type="text/javascript">
  ...
  ...
</script>

<script type="text/javascript">
  ...
  ...
</script>
```

I mean, I do this in order to group jquery functions and allow to declare variables inside each

答:
Your script blocks are not likely having the effect you are expecting, since javascript scope rules do not work that way. Scripts in one block can absolutely affect scripts in another block, if the variables and functions are not scoped properly. Javascript variables and functions are globally scoped unless you follow specific procedures to encapsulate them, and script blocks do not accomplish this.

You should read up on scope in javascript, perhaps a good article or two, and consider why it's best to not embed your javascript functionality in script blocks, but instead place them in well-defined files following common javascript patterns such as the javascript module pattern.


答:
You can use if-modified-since + last-modified or if-none-match + etag headers along with the proper cache-control header. (There can be browser bugs, but nothing you cannot manage in recent browsers.)

If the files are static, then I suggest you to use if-modified-since, because it can be done automatically with a well configured HTTP server. It should send back 304 if the file is not modified since the last download.

I don't think your #1 and #2 would work in long term. The #3 or #4 can work. The #3 is simpler, but you have to learn how to deal with this problem only once. So I'd try the #4 if I were you, but the solution might depend on what browsers your customers use... For example IE8 has problems by updating ajax cache, etc...

Title: Dealing with browser cache in single-page apps

Body:
I'm trying to figure out how to properly handle the web browser cache for single page apps.

I have a fairly typical design: several HTML, JS and CSS files implementing the SPA, and a bunch of JSON data that's consumed by the SPA. Problems arise when I want to push an update: I update the static portion of the site and the code that generates the JSON at the same time, but client browsers often have the static portion cached, so old code tries to process the new data and may (depending on changes made) run into problems. (In particular, IE seems more aggressive than Chrome or Firefox about using cached JS without revalidating.)

What's the best way to handle this?

Make sure my JSON changes are backwards-compatible, and assume browser caches will expire in a reasonable timeframe.

Embed some sort of version number in both the static JS and the JSON, then execute window.location.reload(true); if they don't match.

Figure out the appropriate combination of headers (must-revalidate or no-cache or whatever; sources vary on how to do this) to ensure that browsers always revalidate all resources on every load, even if it means a few extra round trips to load the site.

Micro-manage my cache-control and expires headers so that static content expires when I want to push an update.

Something else?