问:
Why do class-based OO-languages always use the keyword `new` to create an object?
I do not know much about OO-languages, but from what I have seen, it seems most class-based OO-languages uses a keyword new (or something equivalent) to create an object. Prototype-based OO-languages like JavaScript even fake it.

From a viewpoint of keeping the syntax simple, why not leave out the new keyword and use only the constructor (typically of the same name as the class)?

Is there any semantic consideration involved in prefixing the constructor with a new keyword?

I have noticed that in Scala, if you define a case-class, you can simply use the constructor without a preceding new to create an object, while for other classes, you have to use new. I do not know the reason. I mention it simply because it may be related.

答:
As far as I know, it's simply a question of C++ having this syntax (and it needed some syntax because the language was not strong enough to support implementing new T(); at that time as a library) and then inherited. From memory, Java inherited it from C++, JavaScript picked it up from Java, and so did C#. Since then, it seems to have become pretty standard.

Fundamentally, it's no different to using curly braces to denote scope- it was inherited from a common ancestor.


问:
Solutions To Partial ORM Retrieval
I have read the following question regarding whether it is best to use objects with fully or partially populated data members. The 3 suggestions were:

that perhaps using a fully populated ORM model may not have as much overhead as you might expect (testing requried);

an incorrect model was being used if only a limited number of items were being populated, and;

use a 'lite' function or entire class/model to access the pieces of information that are needed.

I cannot tell whether the following solution is using the second or the third suggestion, or more likely, neither:

Example / Solution: Using a table for user information, with each row being a user and storing their user information. For most page views, only 3 out of 12 columns are needed to customize the page for the user. Does it make sense to copy these pieces of information over to another table which holds other relevant session information and is also accessed during every pageload? In this case, there is data duplication but for most tasks a single row is fetched with all relevant information. At the end of the session, this row is removed.

答:
Resist the urge to pre-optimize.

You say that for most page views only a 3 out of 12 User entity properties are used.  Even if 30 properties were used that's still pretty lightweight.  I wouldn't spend too much time worrying about performance losses due to unused data being pushed around.

It's much more economical in terms of dev effort (read: time and money) to consider performance optimizations near the end of the product's development.  At that time, if there are any serious performance problems, a profiler will quickly identify them.  And with this data, you can make an informed decision on which performance problems to tackle.  You're ROI on dev time vs performance is much higher this way.

Alternatively, you might ask yourself why only a quarter of your entity's fields are required in most cases.  It might be that your domain model is a bit too coarse and that subdividing your User into different aspects (sub-entities) makes sense.

It's all hard to tell without actually looking at your code.

Anyway, the main theme of this answer is:

Don't pre-optimize.  Wait until you have sufficient information before devoting large effort to performance.

ContentLicense: CC BY-SA 3.0

Title: Solutions To Partial ORM Retrieval


问:
Can C++ be used as a server-side web development language?
I'd like to get into web development using C++ as the "scripting language" on the server-side.  My server infrastructure is *nix based, so doing web development in C++ on Azure is not applicable and C++/CLI ASP.NET is also not applicable.

Separate from legacy CGI applications, can web development be done using C++ ?

答:
Yes, it can be used. The others have mentioned various approaches. Here is my own approach. The advantage is that it is totally portable and self-contained, all the picked libraries only depend on ANSI C. Setting it up only requires the Linux Kernel and a C compiler (And the obvious stuff like Busybox, bash, etc) (or Windows and a compiler), no extra libraries are needed, no fancy huge installations.

The result is a single program which is both a web server and a dynamic page generator (Substitutes both "apache" and "php"), it will also have database access via sqlite.

Libraries used:

Mongoose - Http server

Sqlite - SQL Database

MiniXML - Makes dynamic page generation easier. sort of like Javascript's createElement

The rest of this answer is a complete set-up guide for Linux. Both SQlite and MiniXML are optional, but the guide covers the full installation. It is up to you to comment out the non needed parts if you're interested in disabling either sqlite or MiniXML.

1. Download the 3 libraries

Mongoose from Github (Hit the "download ZIP")

Sqlite from sqlite.org (You will need Source code > sqlite-amalgamation-< version >.zip)

MiniXML from msweet.org (mxml-< verison >.tar.gz)

2. Prepare your folder

Create an empty folder (We'll call it the main folder)

Put the following files in it:

From the sqlite tar.gz: sqlite3.c , sqlite3.h

From the Mongoose zip: mongoose.c , mongoose.h

From the mxml tar.gz: mxml.h

3. Compile mxml

You may have noticed mxml.c is missing, this is because we need to create  a static mxml library. Go to the folder where the mxml tar.gz was downloaded and perform:

```<code>tar -xvf mxml-<version>.tar.gz #Extract the tar
cd mxml-<version> #Go to the newly extracted directory
./configure #prepare the compiler
make #compile, you may need to install "make" first.
</code>```

Once the compilation is finished, many files will be generated, the only file of interest to us is libmxml.a, copy that file into the main folder.

3.1 Doublecheck

Check that the main folder has the following:

For mongoose: mongoose.c, mongoose.h

For mxml: libmxml.a, mxml.h

for sqlite: sqlite.c, sqlite.h

4. main.c

Let's create the actual program, create a main.c file in the main folder, here is a skeleton for you to get started.

```<code>#include <string.h>
#include <stdio.h>

#include "mongoose.h"
#include "mxml.h"
#include "sqlite3.h"

/***Sqlite initialization stuff***/
//comment out everything sqlite related if you don't want sqlite, including the callback function and the include "sqlite3.h"
static int callback(void * custom, int argc, char **argv, char **azColName);
char *zErrMsg = 0;
sqlite3 *db;
int rc;

/***Just some laziness shortcut functions I made***/
typedef mxml_node_t * dom; //type "dom" instead of "mxml_node_t *"
#define c mxmlNewElement   //type "c" instead of "mxmlNewElement"
inline void t(dom parent,const char *string) //etc
{
    mxmlNewText(parent, 0, string);
}

//type "sa" instead of "mxmlElementSetAttr"
inline void sa(dom element,const char * attribute,const char * value)
{
    mxmlElementSetAttr(element,attribute,value);
}

//The only non boilerplate code around in this program is this function
void serve_hello_page(struct mg_connection *conn)
{
    char output[1000];
    mg_send_header(conn,"Content-Type","text/html; charset=utf-8");
    mg_printf_data(conn, "%s", "<!DOCTYPE html>");
    //This literally prints into the html document

    /*Let's generate some html, we could have avoided the
     * xml parser and just spat out pure html with mg_printf_data
     * e.g. mg_printF_data(conn,"%s", "<html>hello</html>") */

    //...But xml is cleaner, here we go:
            dom html=mxmlNewElement(MXML_NO_PARENT,"html");
                dom head=c(html,"head");
                    dom meta=c(head,"meta");
                    sa(meta,"charset","utf-8");
                dom body=c(html,"body");
                    t(body,"Hello, world<<"); //The < is auto escaped, neat!
                    c(body,"br");
                    t(body,"Fred ate bred");
                dom table=c(body,"table");
                sa(table,"border","1");

                //populate the table via sqlite
                rc = sqlite3_exec(db, "SELECT * from myCoolTable", callback, table, &zErrMsg);
                if( rc!=SQLITE_OK )
                {
                    fprintf(stderr, "SQL error: %s\n", zErrMsg);
                    sqlite3_free(zErrMsg);
                }

            mxmlSaveString (html,output,1000,  MXML_NO_CALLBACK);
            mg_printf_data(conn, "%s", output);
            mxmlDelete(html);
}

//sqlite callback
static int callback(void * custom, int argc, char **argv, char **azColName)
{
    //this function is executed for each row
    dom table=(dom)custom;

    dom tr=c(table,"tr");
    dom td;
    int i;
    for(i=0; i<argc; i++)
    {
        td=c(tr,"td");
        if (argv[i])
            t(td, argv[i]);
        else
            t(td, "NULL");

        printf("%s == %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
    }
     printf("\n");
     return 0;
}

static int event_handler(struct mg_connection *conn, enum mg_event ev)
{
    if (ev == MG_AUTH)
    {
        return MG_TRUE;   // Authorize all requests
    }
    else if (ev == MG_REQUEST)
    {
        if (!strcmp(conn->uri, "/hello"))
        {
            serve_hello_page(conn);
            return MG_TRUE;   // Mark as processed
        }
    }
    return MG_FALSE;  // Rest of the events are not processed

}

int main(void)
{
    struct mg_server *server = mg_create_server(NULL, event_handler);
    //mg_set_option(server, "document_root", "."); //prevent dir listing and auto file serving
    //TODO can I allow file listing without dir listing in a specified directory?
    mg_set_option(server, "listening_port", "8080");

    rc = sqlite3_open("db.sqlite3", &db);

    if( rc )
    {
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        return(1);
    }

    printf("Server is running on port 8080!\n");
    for (;;)
    {
        mg_poll_server(server, 1000);  // Infinite loop, Ctrl-C to stop
    }
    mg_destroy_server(&server);
    sqlite3_close(db);

    return 0;
}

/*
 * useful stuff:
 * mg_send_file(struct mg_connection *, const char *path); - serve the file at *path*/
</code>```

Finally, compiling!

Let's compile. cd to your main folder and execute these:

```<code>gcc -c main.c
gcc -c mongoose.c
gcc -c sqlite3.c
gcc -o server.out main.o mongoose.o sqlite3.o -ldl -lpthread -lmxml -L .
</code>```

Now, execute server.out with /server.out, and navigate to localhost:8080/hello

Done :)

Body:
Yes, it can be used. The others have mentioned various approaches. Here is my own approach. The advantage is that it is totally portable and self-contained, all the picked libraries only depend on ANSI C. Setting it up only requires the Linux Kernel and a C compiler (And the obvious stuff like Busybox, bash, etc) (or Windows and a compiler), no extra libraries are needed, no fancy huge installations.

The result is a single program which is both a web server and a dynamic page generator (Substitutes both "apache" and "php"), it will also have database access via sqlite.

Libraries used:

Mongoose - Http server

Sqlite - SQL Database

MiniXML - Makes dynamic page generation easier. sort of like Javascript's createElement

The rest of this answer is a complete set-up guide for Linux. Both SQlite and MiniXML are optional, but the guide covers the full installation. It is up to you to comment out the non needed parts if you're interested in disabling either sqlite or MiniXML.

1. Download the 3 libraries

Mongoose from Github (Hit the "download ZIP")

Sqlite from sqlite.org (You will need Source code > sqlite-amalgamation-< version >.zip)

MiniXML from msweet.org (mxml-< verison >.tar.gz)

2. Prepare your folder

Create an empty folder (We'll call it the main folder)

Put the following files in it:

From the sqlite tar.gz: sqlite3.c , sqlite3.h

From the Mongoose zip: mongoose.c , mongoose.h

From the mxml tar.gz: mxml.h

3. Compile mxml

You may have noticed mxml.c is missing, this is because we need to create  a static mxml library. Go to the folder where the mxml tar.gz was downloaded and perform:

tar -xvf mxml-<version>.tar.gz #Extract the tar
cd mxml-<version> #Go to the newly extracted directory
./configure #prepare the compiler
make #compile, you may need to install "make" first.

Once the compilation is finished, many files will be generated, the only file of interest to us is libmxml.a, copy that file into the main folder.

3.1 Doublecheck

Check that the main folder has the following:

For mongoose: mongoose.c, mongoose.h

For mxml: libmxml.a, mxml.h

for sqlite: sqlite.c, sqlite.h

4. main.c

Let's create the actual program, create a main.c file in the main folder, here is a skeleton for you to get started.

#include <string.h>
#include <stdio.h>

#include "mongoose.h"
#include "mxml.h"
#include "sqlite3.h"

/***Sqlite initialization stuff***/
//comment out everything sqlite related if you don't want sqlite, including the callback function and the include "sqlite3.h"
static int callback(void * custom, int argc, char **argv, char **azColName);
char *zErrMsg = 0;
sqlite3 *db;
int rc;

/***Just some laziness shortcut functions I made***/
typedef mxml_node_t * dom; //type "dom" instead of "mxml_node_t *"
#define c mxmlNewElement   //type "c" instead of "mxmlNewElement"
inline void t(dom parent,const char *string) //etc
{
    mxmlNewText(parent, 0, string);
}

//type "sa" instead of "mxmlElementSetAttr"
inline void sa(dom element,const char * attribute,const char * value)
{
    mxmlElementSetAttr(element,attribute,value);
}

//The only non boilerplate code around in this program is this function
void serve_hello_page(struct mg_connection *conn)
{
    char output[1000];
    mg_send_header(conn,"Content-Type","text/html; charset=utf-8");
    mg_printf_data(conn, "%s", "<!DOCTYPE html>");
    //This literally prints into the html document

    /*Let's generate some html, we could have avoided the
     * xml parser and just spat out pure html with mg_printf_data
     * e.g. mg_printF_data(conn,"%s", "<html>hello</html>") */

    //...But xml is cleaner, here we go:
            dom html=mxmlNewElement(MXML_NO_PARENT,"html");
                dom head=c(html,"head");
                    dom meta=c(head,"meta");
                    sa(meta,"charset","utf-8");
                dom body=c(html,"body");
                    t(body,"Hello, world<<"); //The < is auto escaped, neat!
                    c(body,"br");
                    t(body,"Fred ate bred");
                dom table=c(body,"table");
                sa(table,"border","1");

                //populate the table via sqlite
                rc = sqlite3_exec(db, "SELECT * from myCoolTable", callback, table, &zErrMsg);
                if( rc!=SQLITE_OK )
                {
                    fprintf(stderr, "SQL error: %s\n", zErrMsg);
                    sqlite3_free(zErrMsg);
                }

            mxmlSaveString (html,output,1000,  MXML_NO_CALLBACK);
            mg_printf_data(conn, "%s", output);
            mxmlDelete(html);
}

//sqlite callback
static int callback(void * custom, int argc, char **argv, char **azColName)
{
    //this function is executed for each row
    dom table=(dom)custom;

    dom tr=c(table,"tr");
    dom td;
    int i;
    for(i=0; i<argc; i++)
    {
        td=c(tr,"td");
        if (argv[i])
            t(td, argv[i]);
        else
            t(td, "NULL");

        printf("%s == %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
    }
     printf("\n");
     return 0;
}

static int event_handler(struct mg_connection *conn, enum mg_event ev)
{
    if (ev == MG_AUTH)
    {
        return MG_TRUE;   // Authorize all requests
    }
    else if (ev == MG_REQUEST)
    {
        if (!strcmp(conn->uri, "/hello"))
        {
            serve_hello_page(conn);
            return MG_TRUE;   // Mark as processed
        }
    }
    return MG_FALSE;  // Rest of the events are not processed

}

int main(void)
{
    struct mg_server *server = mg_create_server(NULL, event_handler);
    //mg_set_option(server, "document_root", "."); //prevent dir listing and auto file serving
    //TODO can I allow file listing without dir listing in a specified directory?
    mg_set_option(server, "listening_port", "8080");

    rc = sqlite3_open("db.sqlite3", &db);

    if( rc )
    {
        fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
        sqlite3_close(db);
        return(1);
    }

    printf("Server is running on port 8080!\n");
    for (;;)
    {
        mg_poll_server(server, 1000);  // Infinite loop, Ctrl-C to stop
    }
    mg_destroy_server(&server);
    sqlite3_close(db);

    return 0;
}

/*
 * useful stuff:
 * mg_send_file(struct mg_connection *, const char *path); - serve the file at *path*/

Finally, compiling!

Let's compile. cd to your main folder and execute these:

gcc -c main.c
gcc -c mongoose.c
gcc -c sqlite3.c
gcc -o server.out main.o mongoose.o sqlite3.o -ldl -lpthread -lmxml -L .

Now, execute server.out with /server.out, and navigate to localhost:8080/hello

Done :)


答:
I guess that several embedded systems (e.g. routers, printers, ...) have some C++ driven web server.

In particular, you could use some HTTP server library like libonion to add some web capabilities to some C or C++ program, or to develop a light server with some web interface.

Some people are coding their Web server or their HTTP interface in Ocaml using Ocsigen. Not every web thing is PHP. And with FastCGI you could some dynamic web processing in/to your application.

Title: Can C++ be used as a server-side web development language?

Body:
I'd like to get into web development using C++ as the "scripting language" on the server-side.  My server infrastructure is *nix based, so doing web development in C++ on Azure is not applicable and C++/CLI ASP.NET is also not applicable.

Separate from legacy CGI applications, can web development be done using C++ ?


问:
Is it possible to use C++ code in an objective-c iPhone app
I'm thinking about writing an application that will have a web-version and an iPhone version (and perhaps later also an android version).

Since there is some algorithms that are the same on the iPhone and the web versions, I was wondering if it is possible to write that part in c++, while keeping the rest of the application in objective-c?

答: Yes, you can also write Objective-C++ by changing the file extension from .m to .mm. Then you can mix C++ and Objective-C code in the same file. It makes it very easy for your Objective-C UI code to call your C++ backend code.</p>

ContentLicense: CC BY-SA 2.5


问:
how to effectively manage multiple occurrences of one application
I have developed a web application for a client which is live to their customers. Recently, the application has been sold in such as way that it is replicated to other domain names so there are 4+ instances of the application which I am to develop and maintain.

At the moment, each copy of the app has it own SVN repository and when it comes to making changes to the application that effects all instances, I update one and then use Beyond Compare to merge changes over to the other copies.

Would it be a better solution to use svn branches to maintain a core system and to merge out to sub branches and visa versa for bugs? Each application may have changes made to it that are client specific, such as logos, colours etc.

Are Branches the best way to go or continue to have each in their own repository and use BC to merge where necessary?

答:
Its going to depend on the specifics of course, but ideally you'd want a single source code base with extensions for the client specific code.  For example, you might organize the client specific code into plugins the way a content management system would.  Or use a templating system for custom GUIs.  I would try to avoid maintaining 4 sets of core code if at all possible as thats just asking for problems.  Especially if a year from now thats 10 sets of code as you add customers.

As another example, the largest PHP app I work on has an administrator interface that lets the admin enable or disable specific features.  Some are designed for single clients only, others are 'premium' features that multiple customers have upgraded to.  But its still all one code base.  During runtime, it checks based on who's logged in, and presents the user with additional functionality where applicable.


问:
What is State, Mutable State and Immutable State?
This is a newbie question, but I couldn't find a newbie-proof enough answer on Google.

What do people mean when they say 'state' - in programming in general, and in OO programming specifically?

Also, what is mutable and immutable state - again, generally in programming and also specifically in OOP?

答:
I think the term "state" (as opposed to a concrete type of state such as "member variable") is most useful when comparing a stateful API to a stateless one. Trying to define "state" without mentioning APIs is a bit like trying to define "variable" or "function" without mentioning programming languages; most of the correct answers only make sense to people who already know what the words mean.

Stateful vs Stateless

A stateful API is one that "remembers" what functions you've called
so far and with what arguments, so the next time you call a function
it's going to use that information. The "remembering" part is often implemented with member variables, but that's not the only way.

A stateless API is one where every function call depends solely on the arguments passed to it, and nothing else.

For example, OpenGL is probably the most stateful API I know of. If I may ludicrously oversimplify it for a moment, we might say it looks something like this:

```<code>glSetCurrentVertexBufferArray(vba1);
glSetCurrentVertexBufferObject(vbo1);
glSetCurrentVertexShader(vert1);
glSetCurrentFragmentShader(frag1);
// a dozen other things
glActuallyDrawStuffWithCurrentState(GL_TRIANGLES);
</code>```

Almost every function is just used to pass in some of the state OpenGL needs to remember, then at the end you call one anticlimactically simple function to do all the drawing.

A stateless version of (oversimplified) OpenGL would probably look more like this:

```<code>glActuallyDrawStuff(vba1, vbo1, vert1, frag1, /* a dozen other things */, GL_TRIANGLES);
</code>```

You'll often hear people say that APIs with less state are easier to reason about. If you can keep the argument count under control, I generally agree with that.

Mutable vs Immutable

As far as I know, this distinction is only meaningful when you can specify an initial state. For example, using C++ constructors:

```<code>// immutable state
ImmutableWindow windowA = new ImmutableWindow(600, 400);
windowA = new ImmutableWindow(800, 600); // to change the size, I need a whole new window

// mutable state
MutableWindow windowB = new MutableWindow(600, 400);
windowB.width = 800; // to change the size, I just alter the existing object
windowB.height = 600;
</code>```

It would be hard to implement a window class that doesn't "remember" what size it is, but you can decide whether the user should be able to change a window's size after creating it.

P.S. In OOP it's true that "state" usually means "member variables", but it can be a lot more than that. For instance, in C++, a method can have a static variable, and lambdas can become closures by capturing variables. In both cases those variables persist across multiple calls to the function and thus probably qualify as state. Local variables in a regular function may also be considered state depending on how they're used (the ones I have up in main() often count).

Body:
I think the term "state" (as opposed to a concrete type of state such as "member variable") is most useful when comparing a stateful API to a stateless one. Trying to define "state" without mentioning APIs is a bit like trying to define "variable" or "function" without mentioning programming languages; most of the correct answers only make sense to people who already know what the words mean.

Stateful vs Stateless

A stateful API is one that "remembers" what functions you've called
so far and with what arguments, so the next time you call a function
it's going to use that information. The "remembering" part is often implemented with member variables, but that's not the only way.

A stateless API is one where every function call depends solely on the arguments passed to it, and nothing else.

For example, OpenGL is probably the most stateful API I know of. If I may ludicrously oversimplify it for a moment, we might say it looks something like this:

glSetCurrentVertexBufferArray(vba1);
glSetCurrentVertexBufferObject(vbo1);
glSetCurrentVertexShader(vert1);
glSetCurrentFragmentShader(frag1);
// a dozen other things
glActuallyDrawStuffWithCurrentState(GL_TRIANGLES);

Almost every function is just used to pass in some of the state OpenGL needs to remember, then at the end you call one anticlimactically simple function to do all the drawing.

A stateless version of (oversimplified) OpenGL would probably look more like this:

glActuallyDrawStuff(vba1, vbo1, vert1, frag1, /* a dozen other things */, GL_TRIANGLES);

You'll often hear people say that APIs with less state are easier to reason about. If you can keep the argument count under control, I generally agree with that.

Mutable vs Immutable

As far as I know, this distinction is only meaningful when you can specify an initial state. For example, using C++ constructors:

// immutable state
ImmutableWindow windowA = new ImmutableWindow(600, 400);
windowA = new ImmutableWindow(800, 600); // to change the size, I need a whole new window

// mutable state
MutableWindow windowB = new MutableWindow(600, 400);
windowB.width = 800; // to change the size, I just alter the existing object
windowB.height = 600;

It would be hard to implement a window class that doesn't "remember" what size it is, but you can decide whether the user should be able to change a window's size after creating it.

P.S. In OOP it's true that "state" usually means "member variables", but it can be a lot more than that. For instance, in C++, a method can have a static variable, and lambdas can become closures by capturing variables. In both cases those variables persist across multiple calls to the function and thus probably qualify as state. Local variables in a regular function may also be considered state depending on how they're used (the ones I have up in main() often count).


问:
Effect of denormalizing
Here's a scenario where I'm wondering whether to denormalize a relational database (MS SQL).

Text description of the requirement

I have users (stored in a users table).

Users belong to Accounts:

An account is created before its users are created

Every user must belong to exactly one account (neither no account, nor more than one account)

Any account may contain many users

A user's assignment to an account is permanent: users are never moved from one account to another

The Users table is predefined so I can't add an "accountId" column to the Users table; so to implement accounts I have:

A Users table, with a userId key

An Accounts table, with an accountId key

A UserAccounts table, with userId and accountId columns (to identify the account associated with each user);
the UserAccounts table is constrained:

Foreign key relations to Users and Accounts table

Uniqueness constraint to ensure that a userId appears no more than once

Because I can't modify the Users table to insert and accountId column in it, I can't ensure that every user has an accountId. And in fact I will insert into the
UserAccounts table after inserting into the Users table, though probably in the same transaction.

I have a dozen other tables (e.g. Sales) which define various types of thing which belong to users

These tables have a userId column (to identify which user each row belongs to)

The problem is that I also need to know what account each thing belongs to

Graphic description of the requirement

Here's a reworded version of the same problem (thanks to MichaelT who suggested this rewording).

```<code>   +-----------+    +--------------+      +--------------+
   | Users     |    | UserAccount  |      | Account      |
   +-----------+    +--------------+      +--------------+
+--> userId pk <----+ userId (uniq)|   +--> accountId pk |
|  |           |    | accountId    +---+  |              |
|  +-----------+    +--------------+      +--------------+
|
|
|  +-----------+
|  | Sales     |
|  +-----------+  (and several other tables like this)
|  | saleId pk |
+--+ userId fk |
   |           |
   +-----------+
</code>```

I can't modify the Users table for various reasons: which is why each user's (single) account is defined using the separate UserAccount table, instead of adding an accountId foreign key to the Users table.

This UserAccount table implements a many-to-one relationship between users and accounts (not a many-to-many relationship). It could be defined using either the following keys:

userId as the primary key

(userId,accountId) as the primary key plus userId as a unique key

The question

Now for the question:

When doing a query against a Sales table that needs to include the Account information, I think there are two ways to implement knowing which account each thing belongs to:

Join the table to the UserAccounts table (to select the accountId for each userId):

```<code>select S.*, UA.accountId
from Sales S
    join UserAccount UA on S.userId = UA.userId
where
    S.something = somethingElse
</code>```

Denormalize the Sales table[s], by storing the accountId in it as well as the userId (the accountId can then be retrieved from Sales without a join to UserAccount):

```<code>|  +--------------+
|  | Sales        |
|  +--------------+  (and several other tables like this)
|  | saleId pk    |
+--+ userId fk    |
   | accountId fk |
   +--------------+
</code>```

If I did the latter I could ensure integrity by defining the userId plus accountId pair/combination as a foreign key constraint into the UserAccounts table (to ensure that the pairing of accountId with userId matches the pairing defined in the UserAccounts table).

```<code>CONSTRAINT Sales_FK FOREIGN KEY (userId,accountId)
    REFERENCES UserAccounts (userId,accountId)
</code>```

I don't have vast experience with database design: I learned it from books (by Joe Celko).

I'm inhibited against denormalizing in general, but denormalizing seems appropriate here: why an extra JOIN in every SELECT statement (to get the accountId), when the same could be obtained by storing the accountId in the table with a (compound or composite) foreign key.

Is there a compelling reason to use (or to not use) either of these two possibilities?

If not then I'm tempted to use the 2nd method:

because it's simpler to define the select statement (without a join)

because it's (presumably) slightly better performance (without a join)

because it ensures that a corresponding row (with an accountId) exists in the UserAccounts table

答:
In this particular case, it doesn't sound like denormalizing to me--there is a 1:1 required relationship and the only piece of lookup information is the User key. Adding another table just to store the relationship doesn't add any value and actually works against you (since as you mentioned, you can't require the field that way).

As for your reasons why, I wouldn't worry about simplicity or performance--with proper indexing, you would never even notice the join. The most important aspect is data correctness, and the second way offers that guarantee for you.

Title: Effect of denormalizing


答:
You should get rid of the UserAccounts table, since the relationship between User and Account is a one-to-many relatioship (given the uniqueness constraint you have on UserAccounts). There's no need for the connection table where the relationship between entities is one-to-many. Such a table is only needed when the relationship is many-to-many.

Let's suposse there's a political reason why you can't get rid of UserAccounts or modify User, then...

I advice you to go with option 1. The specific denormalization you suggest will bring you headaches. Ask yourself: What if a user changes account?. In that case you willl have to update a lot of tables. Not having to do so is preciselly what RDBMS are for.

There are some cases when de-normalization makes sense but not here.

On the argument on join simplicity: some old sage said once: "depend on views, not on tables". Create as many views as needed with the tables already joined. Then program against those views, not tables, that way you don't have to worry about that specific join all the time. There should not be any performance issue if you have indexes and FKs. That's what RDBMS are for.

EDIT: the advantage of the view is that you will no longer have to write the join yourself in every query, which, if I understood well, bothers you, and that, if I understood well, is one of your reasons againts not denormalizing. The view already has the join under the hood, so it will be transparent for you that the AccoountID is in another table. Is has the advantages of normalization but not the disadvantages. One of the advantages of views is offering a denormalize appearance but without denormalizing. You only write the join once (in the view) rather that everytime you want to know the AccoountID, since you will be using the view VSales (which already has an AccoountID column) instead of the table Sale (which doesn't) in queries.

Title: Effect of denormalizing

Body:
Here's a scenario where I'm wondering whether to denormalize a relational database (MS SQL).

Text description of the requirement

I have users (stored in a users table).

Users belong to Accounts:

An account is created before its users are created

Every user must belong to exactly one account (neither no account, nor more than one account)

Any account may contain many users

A user's assignment to an account is permanent: users are never moved from one account to another

The Users table is predefined so I can't add an "accountId" column to the Users table; so to implement accounts I have:

A Users table, with a userId key

An Accounts table, with an accountId key

A UserAccounts table, with userId and accountId columns (to identify the account associated with each user);
the UserAccounts table is constrained:

Foreign key relations to Users and Accounts table

Uniqueness constraint to ensure that a userId appears no more than once

Because I can't modify the Users table to insert and accountId column in it, I can't ensure that every user has an accountId. And in fact I will insert into the
UserAccounts table after inserting into the Users table, though probably in the same transaction.

I have a dozen other tables (e.g. Sales) which define various types of thing which belong to users

These tables have a userId column (to identify which user each row belongs to)

The problem is that I also need to know what account each thing belongs to

Graphic description of the requirement

Here's a reworded version of the same problem (thanks to MichaelT who suggested this rewording).

```<code>   +-----------+    +--------------+      +--------------+
   | Users     |    | UserAccount  |      | Account      |
   +-----------+    +--------------+      +--------------+
+--> userId pk <----+ userId (uniq)|   +--> accountId pk |
|  |           |    | accountId    +---+  |              |
|  +-----------+    +--------------+      +--------------+
|
|
|  +-----------+
|  | Sales     |
|  +-----------+  (and several other tables like this)
|  | saleId pk |
+--+ userId fk |
   |           |
   +-----------+
</code>```

I can't modify the Users table for various reasons: which is why each user's (single) account is defined using the separate UserAccount table, instead of adding an accountId foreign key to the Users table.

This UserAccount table implements a many-to-one relationship between users and accounts (not a many-to-many relationship). It could be defined using either the following keys:

userId as the primary key

(userId,accountId) as the primary key plus userId as a unique key

The question

Now for the question:

When doing a query against a Sales table that needs to include the Account information, I think there are two ways to implement knowing which account each thing belongs to:

Join the table to the UserAccounts table (to select the accountId for each userId):

```<code>select S.*, UA.accountId
from Sales S
    join UserAccount UA on S.userId = UA.userId
where
    S.something = somethingElse
</code>```

Denormalize the Sales table[s], by storing the accountId in it as well as the userId (the accountId can then be retrieved from Sales without a join to UserAccount):

```<code>|  +--------------+
|  | Sales        |
|  +--------------+  (and several other tables like this)
|  | saleId pk    |
+--+ userId fk    |
   | accountId fk |
   +--------------+
</code>```

If I did the latter I could ensure integrity by defining the userId plus accountId pair/combination as a foreign key constraint into the UserAccounts table (to ensure that the pairing of accountId with userId matches the pairing defined in the UserAccounts table).

```<code>CONSTRAINT Sales_FK FOREIGN KEY (userId,accountId)
    REFERENCES UserAccounts (userId,accountId)
</code>```

I don't have vast experience with database design: I learned it from books (by Joe Celko).

I'm inhibited against denormalizing in general, but denormalizing seems appropriate here: why an extra JOIN in every SELECT statement (to get the accountId), when the same could be obtained by storing the accountId in the table with a (compound or composite) foreign key.

Is there a compelling reason to use (or to not use) either of these two possibilities?

If not then I'm tempted to use the 2nd method:

because it's simpler to define the select statement (without a join)

because it's (presumably) slightly better performance (without a join)

because it ensures that a corresponding row (with an accountId) exists in the UserAccounts table


问:
Are noncontiguous arrays performant?
In C#, when a user creates an List<byte> and adds bytes to it, there is a chance it runs out of space and needs to allocate more space. It allocates double (or some other multiplier) the size of the previous array, copies the bytes over and discards the reference to the old array. I know that the list grows exponentially because each allocation is expensive and this limits it to O(log n) allocations, where just adding 10 extra items each time would result in O(n) allocations.

However for large array sizes there can be a lot of wasted space, maybe nearly half the array. To reduce memory I wrote a similar class NonContiguousArrayList which uses List<byte> as a backing store if there were less than 4MB in the list, then it would allocate additional 4MB byte arrays as NonContiguousArrayList grew in size.

Unlike List<byte> these arrays are non-contiguous so there is no copying of data around, just an additional 4M allocation. When an item is looked up, the index is divided by 4M to get the index of the array containing the item, then modulo 4M to get the index within the array.

Can you point out problems with this approach? Here is my list:

Noncontiguous arrays don't have cache locality which results in bad performance. However at a 4M block size it seems like there would be enough locality for good caching.

Accessing an item is not quite as simple, there's an extra level of indirection. Would this get optimized away? Would it cause cache problems?

Since there is linear growth after the 4M limit is hit, you could have many more allocations than you would ordinarily (say, max of 250 allocations for 1GB of memory). No extra memory is copied after 4M, however I'm not sure if the extra allocations is more expensive than copying large chunks of memory.

答:
When memory chunks are allocated at different points in time, as in the sub-arrays within your data structure, they can be located far from each other in memory. Whether this is a problem or not depends on the CPU and is very hard to predict any longer. You have to test it.

This is an excellent idea, and it is one I have used in the past. Of course you should only use powers of two for your sub-array sizes and bit shifting for division (may happen as part of optimization). I found this type of structure slightly slower, in that compilers can optimize a single array indirection more easily. You have to test, as these types of optimizations change all the time.

The main advantage is you can run closer to the upper limit of memory in your system, as long as you use these types of structures consistently. As long as you are making your data structures larger, and not producing garbage, you avoid extra garbage collections that would occur for an ordinary List. For a giant list, it could make a huge difference: the difference between continuing to run, and running out of memory.

The extra allocations are an issue only if your sub-array chunks are small, because there is memory overhead in each array allocation.

I have created similar structures for dictionaries (hash tables). The Dictionary provided by the .net framework has the same problem as List. Dictionaries are harder in that you need to avoid rehashing as well.

Title: Are noncontiguous arrays performant?


问:
Suggestions on refactoring a poorly written ASP.Net MVC web application
I have recently "inherited" a project written in ASP.Net MVC which has quite a few issues
and I'm looking for suggestions on how to go about refactoring the code.

The technical issues found so far are:

All the business logic is written into stored procedures (1000+ SP's).

No unit tests.

View Models are poorly used.

Views are directly dependent upon the database structures.

JQuery is poorly used - No js frameworks (knockoutjs/angularjs/etc..)

Quality is poor.

Performance is poor.

Non-Responsive Design (though it's meant to work on all devices)

No IOC

The other issues:

The application is live and multiple users are using it.

New features are being added to it as we speak and approx 40% of features
still need to be implemented.

The time to refactor is quite limited as the push is on feature release. Rewriting is not an option.

Development team would need to be convinced about the shortcomings.

I would like to start small and make incremental improvements, any suggestions will be most welcome.

答:
Maybe this is somehow useful to you, I will present one way I work on legacy code. There are many more like extracting fields first. It depends, it is different for each piece of legacy code. If it doesn't work the first time, go back one hour (revert changes), try it a second and even a third time, you will get experience at that, under which conditions to start that way or another.

One working way is:

At the first step you should categorize the methods you have, e.g. business, controller, data, ui and sort them within the class to group them. If a method can not be categorized properly, it does to much: Extract smaller methods. categorize these methods too.

At the second step I try to reduce dependencies from the class, where I want to move code away from. You categorized those offending methods, and all these methods should in best case have no dependencies to the class fields or members. This can be done by introducing parameters instead of using class fields into method-signatures. The resulting new method can be potentially moved away.

Third step is to create a new class where one of the categories belong to (in java I'm using inner classes at first and then extract the full class into a separate file, when all depencies are using a public contract)  and to create an instance of the new class in the class to clean up.

Now move the easiest method (lowest hanging fruit) into the new class and replace the invocation with an invocation on the new created object.

All these refactorings are meant to cause no differences in runtime execution order. Only apply those refactorings. Try to rely on IDE-Support and double check any change, since you do not have unit-tests yet. When you do small step refactorings, you can stop whenever you need/have to - and deliver the code as is.

Commit often. I mean all one or two minutes. Keep all changes as little as possible and do not try to be clever - no parallel refactorings - one after the other - write a list of steps down - do not try to remember all of them - all it needs to disturb you is a phone call - and your efford is wasted. Do not refactor 10 minutes without commiting. These refactorings are error-prone. Committing often enables you to find the cause of a refactoring error e.g. via binary search on commits.

Now create unit tests for the one single extracted and moved method.

Now move the next low hanging fruit method to new class, write tests etc.

if you have dependencies to  the previous class, make these dependencies temporarely public, annotate/document them, that this is not the public API, but needeed for refactoring.

now check, if you need interfaces and extract them to reduce the depencencies between the former class and the new extracted class.

This will step by step remove the code safely from the class. But do not move invocations around within method code, only work with/on full methods. (Optimizations will come next when you have more test coverage)

Now you have unit tests for the new extracted methods and the former class code code is less cluttered. Now you will experience more methods which may belong to the extracted class also. Since you see, who is now invoking the new extracted class. Write more tests.

Proceed with other categories. If you get stuck - it is fine, return another time or sleep a night over it. This will improve the code step by step and no step is expensive at all - only one to two minutes. When you get more experience on this, improve the higher hanging fruits. Start with the lowest hanging ones. Before you add a new feature, try to declutter the code, try to identify the code you need to change and separate it from the code you do not need to touch. Then add new methods using a seam and write test for them.

If you might want a suggestion on a book to read - on legacy code: "Working Effectively with legacy code" from Michael C. Feathers. Also do not miss the great youtube video "Practical Refactoring" on refactoring in very small steps. It is somehow eye opening. But you do not have to agree to them fully.

TL;DR: Well after reading this again this is working on SRP (Single Responsibility Principle) first.

hth a bit.


问:
When trying to find out if a number is even or odd: AND 1 or OR 0
I recently learned of the trick for finding out if a binary number is odd or even.

If the last bit in the number is 0, then the number is even. If it ends in a 1, then the number is odd.

In the tutorial in which I read this, is stated that this could be applied to programming if you "AND" the number with the binary number 1.

In another tutorial that I read, they said that is could applied if you "OR" the number with binary 0.

In regards to efficiency, which method would be more efficient for finding out if a number is odd or even?

答:
Ultimately, this depends on the processor or the interpreter you are using. I have not encountered a situation in which these operations differed respectably in execution time.

A GMP developer maintains a paper on x86/amd64 instruction latencies and throughput. This paper shows that both AND and OR instructions have the same timings when both arguments are registers. When one of the operands is a memory address, of course timing might change when that memory is not in cache. But this is not a function of the instruction.

Unfortunately, I can't speak to other processors or whether people have done asinine things in interpreters that would cause a performance disparity.


答:
There is a Bit Test instruction in the x86 instruction set (since 80386):

BT copies a bit from a given register to the carry flag.

As I understand it, you can then execute a JC (jump if carry) instruction to make a decision based on the carry flag.  That's a total of two elemental instructions and uses only one register.

However, I doubt that's more efficient than using AND with 1 and jump if the zero flag is set.  Both alternatives are two elemental CPU instructions.  It's possible the constant to specify the bit in the BT instruction uses fewer bits than the constant operand of the AND instruction, but I'm not going to bother looking it up.  :)

That probably means the OR method is less efficient because you'd have to do the OR, then a compare to the original number and jump if equal or not equal, which at the very least is tying up 2 registers instead of 1.

A slightly better alternative than AND might be the TEST instruction because it performs an AND but throws away the result of the operation and only keeps the flags set.  Since you don't actually want to keep the result, then TEST eax, 1 followed by jump if zero (JZ) might be your best bet (since it's possible you might want to do something else with the original value and this leaves it loaded in the register).

Title: When trying to find out if a number is even or odd: AND 1 or OR 0

Body:
I recently learned of the trick for finding out if a binary number is odd or even.

If the last bit in the number is 0, then the number is even. If it ends in a 1, then the number is odd.

In the tutorial in which I read this, is stated that this could be applied to programming if you "AND" the number with the binary number 1.

In another tutorial that I read, they said that is could applied if you "OR" the number with binary 0.

In regards to efficiency, which method would be more efficient for finding out if a number is odd or even?


问:
Is there a conventional way to combine file path strings?
In an example:

```<code>var assets = "images/"

var sounds = assets+"sounds/"
</code>```

Is it more conventional to put the slash on the back of a file path?

```<code>var assets = "/images"

var sounds = assets+"/sounds"
</code>```

Is there another method that is a good common practice?

答:
In Smalltalk it is straightforward to define the / method in String so that it works like this:

```<code>'assets' / 'sounds' => 'assets/sounds'.
'assets/' / 'sounds' => 'assets/sounds'.
'assets' / '/sounds' => 'assets/sounds'.
'assets/' / '/sounds' => 'assets/sounds'.
</code>```

Here is a simple implementation of the method (you can make it better):

```<code>/ aString
    | slash first second |
    slash := Directory separator.
    first := self.
    (first endsWith: slash) ifTrue: [first := first allButLast].
    second := aString.
    (second beginsWith: slash) ifTrue: [second := second allButFirst].
    ^first , slash , second
</code>```

Note: you might also want to pay better attention to border cases such as '' / '', 'x/' / '', etc., in order to determine the proper behavior.

Body:
In Smalltalk it is straightforward to define the / method in String so that it works like this:

'assets' / 'sounds' => 'assets/sounds'.
'assets/' / 'sounds' => 'assets/sounds'.
'assets' / '/sounds' => 'assets/sounds'.
'assets/' / '/sounds' => 'assets/sounds'.

Here is a simple implementation of the method (you can make it better):

/ aString
    | slash first second |
    slash := Directory separator.
    first := self.
    (first endsWith: slash) ifTrue: [first := first allButLast].
    second := aString.
    (second beginsWith: slash) ifTrue: [second := second allButFirst].
    ^first , slash , second

Note: you might also want to pay better attention to border cases such as '' / '', 'x/' / '', etc., in order to determine the proper behavior.


答:
With a 4M block size, even a single block isn't guaranteed to be contiguous in physical memory; it's larger than a typical VM page size. Locality is not meaningful at that scale.

You will have to worry about heap fragmentation: if the allocations happen such that your blocks are largely non-contiguous in the heap, then when they are reclaimed by the GC, you will end up with a heap that may be too fragmented to fit a subsequent allocation. That's usually a worse situation because failures will occur in unrelated places and possibly force a restart of the application.

Title: Are noncontiguous arrays performant?

Body:
In C#, when a user creates an List<byte> and adds bytes to it, there is a chance it runs out of space and needs to allocate more space. It allocates double (or some other multiplier) the size of the previous array, copies the bytes over and discards the reference to the old array. I know that the list grows exponentially because each allocation is expensive and this limits it to O(log n) allocations, where just adding 10 extra items each time would result in O(n) allocations.

However for large array sizes there can be a lot of wasted space, maybe nearly half the array. To reduce memory I wrote a similar class NonContiguousArrayList which uses List<byte> as a backing store if there were less than 4MB in the list, then it would allocate additional 4MB byte arrays as NonContiguousArrayList grew in size.

Unlike List<byte> these arrays are non-contiguous so there is no copying of data around, just an additional 4M allocation. When an item is looked up, the index is divided by 4M to get the index of the array containing the item, then modulo 4M to get the index within the array.

Can you point out problems with this approach? Here is my list:

Noncontiguous arrays don't have cache locality which results in bad performance. However at a 4M block size it seems like there would be enough locality for good caching.

Accessing an item is not quite as simple, there's an extra level of indirection. Would this get optimized away? Would it cause cache problems?

Since there is linear growth after the 4M limit is hit, you could have many more allocations than you would ordinarily (say, max of 250 allocations for 1GB of memory). No extra memory is copied after 4M, however I'm not sure if the extra allocations is more expensive than copying large chunks of memory.

ContentLicense: CC BY-SA 4.0


问:
Unsure about the decorator design pattern
I'm fairly new at using design patterns and I am currently making a small game for my uni course that I have to use the decorator pattern for creating the different classes of NPC however I think that I have misunderstood how the decorator pattern works.

At the moment all what changes between the classes of NPC's are the attack value, health and speed stats. What I am really unsure of is if there is a way of passing these values into the decorated object from the decorator or do i have the wrong impression of the decorator pattern.

答:
Think of decorator as wrapping up an object with more functionality. Now this new object has an object inside of it, and the outer object gives it more functionality.

Here's a little pseudo representation of it.

```<code>class Watch implements Clock
{
    private Clock clockToBeDecorated;

    public Watch(Clock clock)
    {
        clockToBeDecorated = clock;
    }

    public void StrappToWrist()
    {
        //strap the watch to your wrist
    }

    public DateTime GetTime()
    {
        return clock.GetTime();
    }
}

interface Clock
{
    DateTime GetTime();
}
</code>```

So now we have all the functionality of a Clock but we can also strap it to our wrist (like you'd expect with a wrist). This is good when you wish to dynamically pass the object into another, so we may wish to put that click into a Watch or a PocketWatch etc.

Wikipedia has a good example using Scrolling Windows in Java as well which may help.

Body:
Think of decorator as wrapping up an object with more functionality. Now this new object has an object inside of it, and the outer object gives it more functionality.

Here's a little pseudo representation of it.

class Watch implements Clock
{
    private Clock clockToBeDecorated;

    public Watch(Clock clock)
    {
        clockToBeDecorated = clock;
    }

    public void StrappToWrist()
    {
        //strap the watch to your wrist
    }

    public DateTime GetTime()
    {
        return clock.GetTime();
    }
}

interface Clock
{
    DateTime GetTime();
}

So now we have all the functionality of a Clock but we can also strap it to our wrist (like you'd expect with a wrist). This is good when you wish to dynamically pass the object into another, so we may wish to put that click into a Watch or a PocketWatch etc.

Wikipedia has a good example using Scrolling Windows in Java as well which may help.


问:
Is there a stronger stress on management than on technical education in recent years?
In my working environment, over the past few years I have observed an increasing stress on developer management and self-management over technical education.

For example, at work I hear lots of discussions about software development processes, about ways to handle software specifications, e.g. through automatic tests, and so on. I hear less discussions about programming concepts / techniques like data structures, lazy evaluation, memoization, and so on.

To give another example, if I asked a colleague how he would manage the complexity of a certain problem, I would expect that he'd indicate me some solution approach (try to solve a subproblem first, identify subtasks) instead of suggesting a programming abstraction (try using pattern X).

Is it just something specific to my working environment or there is a general trend towards management / work organization and away from the more conceptual aspects of programming?

To make my question specific (and answerable), are there any authors or modern schools of thought that consider organizational aspects more important than educational ones for improving developer productivity?

答:
Try to think in layers, like, let's say TCP/IP: if you're on the physical layer you need to learn the 'language' of the upper layers :))

A programmer shouldn't NEED to learn Management more than a MANAGER should learn Programming: in other words, as long as you have an idea about what's over the fence you're fine...

The next thing is about methods/standards/frameworks, which are GENERAL guidances: they should be adopted and ADAPTED as suitable to any PARTICULAR situation.
Finally, Software Development being a Human activity is prone to FASHION as any other activity: the nowadays trend is AGILE/Scrum/Kanban! [Instead of 'cascade' management, simply because it looks cheaper in many cases (not always) ...and as any other method it works if applied properly by the right people... Otherwise, please take it from someone who has seen it failing, it can exhaust resources faster than light.]

To resume the above, the answer to your question is another question:
would your (any) CEO (if not of a programming background) learn quicker about programming or about management and fashion?

My personal approach to the above: continuous learning...


问:
Scrum: Is it ok for the design/UX of user story to occur in the same sprint as implementation
I am currently in a sprint (two weeks) where the designer is tasked with defining the requirements and UX of a particular user story.

In the same sprint, I am to implement this design. During sprint planning, I had to take a wild guess as to how long this undefined user story would take.

Today I finally received the design. Unfortunately, the design is incomplete/vague and is more akin to a client's requirements than a design. However, from this, I can still see that I have not nearly estimated enough.

To make matters worse this is not the first time. In the last sprint, the exact same thing happened. I flagged it in our retrospective and the scrum master did not have an answer of how to solve this, instead of saying "that's just development for you". Ironically he gets annoyed if the burn down is not on target...

Now I am going to have to ask/work with the designer to get his job done. This is going to hold me up as I have completed all my other tasks.

So my question is

 A) <s>how do you handle dependencies in sprint planning?</s> EDIT: Is it ok for the design/UX of user story to occur in the same sprint as implementation

 B) how should I now approach the sprint? Re-estimate the current user story and watch the burndown turn into a burn up and be viewed as incompetent/unproductive? Or add a new task to the current sprint along the lines of "help the designer create a suitable design"

答:
A Sprint usually starts when the story is clear - at this stage the Product Backlog is established and prioritized. If you started without having the design than it should have been clear what can be done without the design and what not...

If you have to improvise while the design is 'bumping' between the client and PO than your PO has to inform the team about any new features as soon as they appear: this is the meaning of 'flexibility' in Scrum - adapt to the ongoing situation. The Development Team, the Scrum Master and the Product Owner need to communicate permanently, otherwise there is no real-time reaction to change.

Some more training can't harm...
Perhaps working with the designer would be an opportunity for you to acquire some new UX skills? ...that's observing the glass being half-full instead of half-empty :))


答:
It's worth noting that C++ already has an equivalent structure by Standard, std::deque. Currently, it's recommended as the default choice for needing a random-access sequence of stuff.

The reality is that contiguous memory is nearly completely unnecessary once the data goes past a certain size- a cache line is just 64 bytes and a page size is just 4-8KB (typical values currently). Once you're starting to talk about a few MB it really goes out the window as a concern. The same is true of allocation cost. The price of processing all that data- even just reading it- dwarfs the price of the allocations anyway.

The only other reason to worry about it is for interfacing with C APIs. But you can't get a pointer to the buffer of a List anyway so there's no concern here.

Title: Are noncontiguous arrays performant?


答:
At the scales you mentioned, the concerns are totally different from those you have mentioned.

Cache locality

There are two related concepts:

Locality, the reuse of data on the same cache line (spatial locality) that was recently visited (temporal locality)

Automatic cache prefetching (streaming).

At the scales you mentioned (hundred MBs to gigabytes, in 4MB chunks), the two factors have more to do with your data element access pattern than the memory layout.

My (clueless) prediction is that statistically there might not be much performance difference than a giant contiguous memory allocation. No gain, no loss.

Data element access pattern

This article visually illustrates how memory access patterns will affect performance.

In short, just keep in mind that if your algorithm is already bottlenecked by memory bandwidth, the only way to improve performance is to do more useful work with the data that is already loaded into the cache.

In other words, even if YourList[k] and YourList[k+1] have a high probability of being consecutive (one in four-million chance of being not), that fact will not help performance if you access your list completely randomly, or in large unpredictable strides e.g. while { index += random.Next(1024); DoStuff(YourList[index]); }

Interaction with the GC system

In my opinion, this is where you should focus on most.

At the minimum, understand how your design will interact with:

Generational garbage collection,

Large object heap

I am not knowledgeable in these topics so I will leave others to contribute.

Overhead of address offset calculations

Typical C# code is already doing a lot of address offset calculations, so the additional overhead from your scheme wouldn't be any worse than the typical C# code working on a single array.

Remember that C# code also does array range checking; and this fact does not prevent C# from reaching comparable array processing performance with C++ code.

The reason is that performance is mostly bottlenecked by memory bandwidth.

The trick to maximizing utility from memory bandwidth is to use SIMD instructions for memory read/write operations. Neither typical C# nor typical C++ does this; you have to resort to libraries or language add-ons.

To illustrate why:

Do address calculation

(In OP's case, load chunk base address (which is already in cache) and then do more address calculation)

Read from / write to the element address

The last step still takes the lion's share of time.

Personal suggestion

You can provide a CopyRange function, which would behave like Array.Copy function but would operate between two instances of your NonContiguousByteArray, or between one instance and another normal byte[]. These functions can make use of SIMD code (C++ or C#) for maximizing memory bandwidth utilization, and then your C# code can operate on the copied range without the overhead of multiple dereferencing or address calculation.

Usability and interoperability concerns

Apparently you cannot use this NonContiguousByteArray with any C#, C++ or foreign-language libraries that expect contiguous byte arrays, or byte arrays that can be pinned.

However, if you write your own C++ acceleration library (with P/Invoke or C++/CLI), you can pass in a list of base addresses of several 4MB blocks into the underlying code.

For example, if you need to give access to elements starting at (3 * 1024 * 1024) and ending at (5 * 1024 * 1024 - 1), this means the access will span across chunk[0] and chunk[1]. You can then construct an array (size 2) of byte arrays (size 4M), pin these chunk addresses and pass them to the underlying code.

Another usability concern is that you will not be able to implement the IList<byte> interface efficiently: Insert and Remove will just take too long to process because they will require O(N) time.

In fact, it looks like you can't implement anything other than IEnumerable<byte>, i.e. it can be scanned sequentially and that's it.

Title: Are noncontiguous arrays performant?


问:
Is obsolete to study older versions of Ruby and RoR?
I want to study Ruby and RoR for some things I'll have to make, but almost every book, videos or any kind of source I find is outated, where the most current book I could find (link here) is one of the version 2.1 (latest stable version of Ruby is 2.2.0), and in the case of Rails I only find books about RoR 3.x or at most 4.0 (latest stable version is 4.2.0).

Then I wondered if there are many changes in Ruby and RoR, for example, if I find a good book about Ruby 1.9, should I read it?, are there many changes?, the same in the case of Rails, if I find videos of Rails 3.x, should I see them?.

答:
I would say that it is never 'obsolete' to study outdated software.

For sure, there are changes, but what you learn in the earlier versions will translate pretty well, in newer versions.

When you hit things that are different from an earlier version of the language or framework, then you have the current documentation (and version) to explore those changes that you are using.

A lot of the ideas in the books relate to later versions, though some features and syntax change.

This is pretty normal.

The current language version that you learn today, will undoubtedly help you for tomorrows current language version.


问:
Is seeing loads of merge messages in a git branch standard, or are we working incorrectly?
We're in the process of switching from SVN to git, and I've noticed that we're seeing a lot of these commit messages in git:

Merge branch 'development' of [Url to Origin].

These are coming in where other developers are pulling down changes from remote, into their local repo, before they push their changes back into remote (I think, clarification would be great if not).

I just wanted to check that it's expected to see these messages in the remote, considering there's only 3 of us working on the project at the moment, but it seems like every other commit is one of these messages, making it a bit harder to gleam any useful information from the commit logs?

(Tagged as Visual Studio as I believe the message is auto-generated by VS when you use their IDE?)

答:
Having the merge commits and seeing the merge commits are really different things.

If you only are concerned with reporting, you can use arguments to the git log command.

Having two parents is why they exist.

The workflow is 'correct' in that it is not technically a problem.  But your workflow may change as you become more familiar with the git toolset.  And then you may change your workflow to something more 'correct' for you.


答:
Decorators have many uses but it doesn't mean that decorator is the appropriate pattern to use for every situation. Given the same requirements, a programmer can always try implementing the same requirements in different patterns to see which one fits best.

In OP's example, I think there is one situation in which the attack, health, speed system can be augmented with a decorator pattern.

For OP's benefit, please read the Coffee Condiment decorator pattern example in Head First Design Patterns.

http://www.coderanch.com/t/99387/patterns/HeadFirst-Design-Patterns-Decorator-Chapter

The situation where I would envision it to be useful is:

There is already an underlying NPC class, which provides basic mechanisms for getAttack(), getHealth() and getSpeed().

There are a number of gadgets which could be acquired by an NPC object, and these gadgets would temporarily modify the acquirer's properties.

Sample code

(Disclaimer: sample code in C#, not C++)

```<code>// Just the statistics. We are not claiming that "CaffeinePack" is a character.
interface CharacterStat
{
    int getAttack();
    int getHealth();
    int getSpeed();
}

interface Character : CharacterStat, CharacterPlanner, ...
{
    // a bunch of other stuff
}

class NPC : Character
{
    public int getAttack() { ... concrete implementation ... }
    public int getHealth() { ... concrete implementation ... }
    public int getSpeed() { ... concrete implementation ... }
}

class CaffeinePack : CharacterStat
{
    private CharacterStat realObject;
    public CaffeinePack(CharacterStat realObject) { this.realObject = realObject; }
    public int getAttack()
    {
        return realObject.getAttack();
    }
    public int getHealth()
    {
        return (int)(realObject.getHealth() * 0.8);
    }
    public int getSpeed()
    {
        return (int)(realObject.getSpeed() * 1.2);
    }
}
</code>```

Title: Unsure about the decorator design pattern

Body:
I'm fairly new at using design patterns and I am currently making a small game for my uni course that I have to use the decorator pattern for creating the different classes of NPC however I think that I have misunderstood how the decorator pattern works.

At the moment all what changes between the classes of NPC's are the attack value, health and speed stats. What I am really unsure of is if there is a way of passing these values into the decorated object from the decorator or do i have the wrong impression of the decorator pattern.

Body:
Decorators have many uses but it doesn't mean that decorator is the appropriate pattern to use for every situation. Given the same requirements, a programmer can always try implementing the same requirements in different patterns to see which one fits best.

In OP's example, I think there is one situation in which the attack, health, speed system can be augmented with a decorator pattern.

For OP's benefit, please read the Coffee Condiment decorator pattern example in Head First Design Patterns.

http://www.coderanch.com/t/99387/patterns/HeadFirst-Design-Patterns-Decorator-Chapter

The situation where I would envision it to be useful is:

There is already an underlying NPC class, which provides basic mechanisms for getAttack(), getHealth() and getSpeed().

There are a number of gadgets which could be acquired by an NPC object, and these gadgets would temporarily modify the acquirer's properties.

Sample code

(Disclaimer: sample code in C#, not C++)

// Just the statistics. We are not claiming that "CaffeinePack" is a character.
interface CharacterStat
{
    int getAttack();
    int getHealth();
    int getSpeed();
}

interface Character : CharacterStat, CharacterPlanner, ...
{
    // a bunch of other stuff
}

class NPC : Character
{
    public int getAttack() { ... concrete implementation ... }
    public int getHealth() { ... concrete implementation ... }
    public int getSpeed() { ... concrete implementation ... }
}

class CaffeinePack : CharacterStat
{
    private CharacterStat realObject;
    public CaffeinePack(CharacterStat realObject) { this.realObject = realObject; }
    public int getAttack()
    {
        return realObject.getAttack();
    }
    public int getHealth()
    {
        return (int)(realObject.getHealth() * 0.8);
    }
    public int getSpeed()
    {
        return (int)(realObject.getSpeed() * 1.2);
    }
}


问:
Should I spend time preventing piracy of my app?
The title says it all, the more I do research about piracy and the tools used to crack an app the more I think it is just wasted time.

My biggest threat is that my app is being cracked and uploaded again within minutes after I released it. But I'm not sure how harmful it will be to my revenue, if there even will be revenue. Maybe someone can come up with some experience, it's my first app which I'm going to publish and I have no experience with that. My app is going to be free with ads. I think this is another line of defense because in my opinion, the main focus is on paid Apps due they are not available in a lot of countries..

My current approach is that I will just use proguard not really to make it harder to crack (more likely understand the code), because you don't even need to understand the code if you just simply resign it and upload the same application to the playstore, you will just need to change the package name. My main point of using proguard is just to shrink the app.

Is this a "good" approach?

答:
No.

Most applications from large developers with real, industrial grade copy protection appear in torrents, cracked, within days of release.  It is extremely doubtful that a smaller developer can match that.  Trying to will just waste your time, leaving less time for you to develop features/apps that make money.

You may want to do trivial work to keep "casual" copiers at bay, but by trivial, I mean something you can throw together in a few hours.  (I.e. something like proGuard.)  You will not stop the people with technical knowhow who actively want to crack your app.


问:
Design a Queuing Solution with Clustering and Multiple Consumers
It is a Design Problem which I am listing out here.

I have different set of business operations that are carried out for different business entities.

Operations:

Operation A

Operation B

Operation C

For Example I have an Entity A. Entity A's data could be in parts, for example:

Entity A's (Jan Data)

Entity B's (Feb Data) etc.

To complete a Use Case all Operations (A,B,C) should be performed. Now these operations are performed and are independent of each other and can be performed in parallel, the only condition is that they should be of different Entities. So Entity A can't have all the operations (A, B or C) executing in parallel. And these operations are running on server side.

How to scale this and provide a solution?

I am thinking of following solution and would like to have inputs from the community on this.

I am thinking of three Queues for operations which I mentioned above

Queue A carrying out Operation A

Queue B carrying out Operation B

Queue C carrying out Operation C

And all the Consumers will be listening to these Queues.

Consumer A (or multiple consumers)

Consumer B (or multiple consumers)

Consumer C (or multiple consumers)

And my server would be load balanced, and I will be having a Single Message Queue containing these three queues.

So it is possible that I have 2 servers running and on every server there are for example 5 threads (Consumers) running, so there will be 10 instances of Consumer A running in parallel picking the data from the Message Queue A.

As I stated earlier that for the same entity A(that is the business use case which I have) all these operations (Operation A, Operation B and Operation C) can't be running in parallel, they should be only of them being executed.

So what I am thinking is to have a database entry for the Entity A and all the consumers must check whether there is a Database Entry for Entity A,

if not then

Make an entry to Database for Entity A

Go and execute the Operation

Remove the Entry from the Database for Entity A

if there is an entry in Database found

Enqueue the Data for Entity A again from the Queue where it was picked.

Is there any better solution possible for such a design problem?

答:
You can partition your data easily with consistent hashing, in this case you would use the entity as the hash key.  The consistent hash takes a key and # of "buckets" as input and gives you back the bucket for that key.

With multiple servers in mind, a simple solution would be to pick a number of partitions up front (lets say 6), which means you will have 6 queues.  When producing messages, calculate the bucket [consistentHash(entity.id, 6)] and put the message on the queue (partition) that corresponds to that bucket.  This gives you ordering of messages per entity.

On the consumer side, simply ensure you have exactly one consumer per queue (partition).  You can have as many servers as you want as long as there are no competing consumers.

You can then take this one step further inside each server to improve parallelism.  The consumer of each queue (partition) can be a router, which simply takes each message and does another consistent hash on the entity, to N buckets where N is the number of your worker threads you want for parallelism, then hand off the message to the thread for the calculated bucket.

This setup routes messages for the same entity consistently to the same server, and the server will consistently route the message to the same worker thread.  Assuming the N worker threads is relatively high, you get excellent parallelization of your tasks with message ordering based on any key you want.


答:
Should I spend time preventing piracy of my app?

You are asking the wrong question. Technical safeguards such as proguard are a must but are trying to solve the problem the hard way.

The first question should be "Does my app contain something that really needs protecting?" such as a complex or proprietary algorithm. If so the best solution is to move this out of the app into a server that the app talks to. The app becomes merely a UI layer on top of the server. Of course, this means you need to maintain a server (or servers) and an appropriate authentication mechanism for each user (a whole other post). It is also inappropriate for disconnected or highly responsive apps.

The second question should be "Why would people pirate my app?" If it is a financial motivation, release a free version of the app with a reduced feature set. If it is a game, make the core game and first few levels free then sell additional levels/characters/upgrades/whatever via in-app purchases. Alternatively, release a free version funded in in-app advertising (yes, I know many people hate it but it is the world we live in).

No matter what you do, as Steven implies in his answer, some people will do it for a technical challenge and release the crack to demonstrate their prowess. You cannot stop these so it is not worth worrying about.

Body:
The title says it all, the more I do research about piracy and the tools used to crack an app the more I think it is just wasted time.

My biggest threat is that my app is being cracked and uploaded again within minutes after I released it. But I'm not sure how harmful it will be to my revenue, if there even will be revenue. Maybe someone can come up with some experience, it's my first app which I'm going to publish and I have no experience with that. My app is going to be free with ads. I think this is another line of defense because in my opinion, the main focus is on paid Apps due they are not available in a lot of countries..

My current approach is that I will just use proguard not really to make it harder to crack (more likely understand the code), because you don't even need to understand the code if you just simply resign it and upload the same application to the playstore, you will just need to change the package name. My main point of using proguard is just to shrink the app.

Is this a "good" approach?


答:
If possible you should follow the advice in https://news.ycombinator.com/item?id=2623102 and move the stuff you want paid for to a server.  And then manage access there.  The app itself can be assumed to be stolen and pirated as much as it wants.  Copying your server is harder.

Of course this solution has the downside of not being cool or clever.  But it works.

Title: Should I spend time preventing piracy of my app?


答:
Many many years ago, I bought a book on game development.  It had a chapter on piracy.  It included the following summary:

It is not possible to prevent piracy with technology.  The only way to prevent piracy is to make a game so cool and exciting that the pirates choose to go out and buy a copy.

You can never prevent piracy.  You can curtail piracy, you can monitor piracy, but there are no tools which can truly prevent it.  I stress this because that strong word, "prevent," can make people reach to exorbitant measures thinking "If I just do X, I can prevent piracy."  They are always saddened by the result, and it is all because of a word choice.

To rephrase akton's key points in a terminology traditionally used in Information Security: you need to develop a threat model describing your attackers.  If your attacker is a script-kiddie that downloads a few scripts off of the web, then you can focus your security by looking online at what script-kiddies can find, and defending against those.  If you are really interested in your secrets not falling into Chinese and/or American government hands, you'll find you have to do a wee bit more on the security front.

One nice thing about phrasing it as a "threat model" is that you will also be in an excellent position to correctly handle security issues, such as logins and credit card numbers and what-not.  You will be ahead of the curve.

If all you are worried about is script-kiddies, it would be useful too not only do the Google search for antiLVL you mention in your comments, but play with a few of them.  Learn what they can and cannot do.  Know thy enemy.


答: From my experience: most of people like original software and is very difficult to prevent crack. The best thing to prevent piracy is always to deliver a free version with less features of your software, and warn people that cracked software may threat them (virus, trojans almost by sure). So if people like your software by using the free (clean, no threats) version they will buy it.</p>


问:
Is using generics to indicate some class/method is aware of a type good idea?
I'm going to use Java for code/idea demonstration.

Imagine it's needed to define two interfaces: Observer and Observable (observer pattern). It's a good idea to have two generic interfaces, so there is no restriction on what is being observed, who is observing it (is even using generics about this?).

Java has a concrete (non-final) Observable class and an Observer interface. You have to delegate handling observers and notifying them on update to the concrete Observer class. This is one way of implementing the pattern. I don't know if it's the best approach (probably is), but for the sake of this example let's assume every class/type who wants to be observable, must implement the Observable interface below, and handle everything itself.

We should not forget the original Observer and Observable interface/object were implemented in JDK1.0, when generics were not available.

Now the question: Is this a good idea to merely declare a generic type in an interface to denote that the implementing class needs to be aware of some specific type? Or it is totally wrong way of using generics?

See:

```<code>public interface Observable<T> {
    // Only observers who are aware of type T are allowed.
    // But should really Observable be concerned about it?
    public void registerObserver(Observer<? extends T> o);
}

// The T here denotes that implementing class will be aware of a type called T,
// (not that it can operate on a range of types).
public interface Observer<T> {
    // Observer is not aware of Observable interface directly. But it knows about T.
    public void update(T arg);
}
</code>```

VS

```<code>public interface Observable {
    // Is it an observer? then it is allowed. That's all we need to know.
    public void registerObserver(Observer o);

    // Observers will be passed the instance of observable,
    // then they call this method to fetch arg.
    // something like:
    // for(Observer o: this.observers) o.update(this);
    public <T> T getArg();
}

public interface Observer {
    // Pass me an Observable who returns T and i'll do the rest!
    public void update(Observable o);
}
</code>```

I feel I'm getting generics totally wrong.

P.S: Comparing this way of implementing the observer pattern (asking every type to re-implement these interfaces) vs the original java solution (delegation) we realize it's not really a good idea. It causes a lot of code duplicate. But it helps to understand generics better.

Update The actual problem with java.util.Observer is notifyObservers(Object arg)[link to doc] where arg is cast at runtime by observers. How can we avoid such cast?

答:
There's one very important problem with the design that you've presented, which is caused ny a flaw in how java generics are implemented: a single class can only implement a single version of a generic interface. I think only being able to observe changes in a single type of object would be overly restrictive, and therefore would not usually use this implementation.

Also, I don't see any value in the Observable interface; in order to usefully observe an object, the observer needs to know its type, so the interface isn't necessary. I would simply define one Observer interface per type that can be observed. It's a bit of boilerplate code, but only a handful of lines per type. The implementation of registration and removal of observers is likely to larger.


问:
Tabs versus spaces—what is the proper indentation character for everything, in every situation, ever?
The coding standards for the code hosted in drupal.org suggest to use two spaces to indent the code; other sites suggest to use tabs to indent the code.

What is the proper indentation character for everything, and in every situation? Please explain the answer you give.

答:
Tabs are the natural and orthodox choice, as they are by definition used for indentation.

Unfortunately, tabs are unevenly implemented, so the only real world solution is 4 spaces.


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答:
To make a user manual for an automated process.
The user manual basically say "Double click foo.exe and wait until it's done"</p>

OwnerDisplayName: Jax


问:
How do you respond to a request for 'emergency contact information' for when you are on vacation?
I want to go on vacation and not think about work at all but they want me to provide them a contact number in the event of an emergency (server goes down, web service malfunctions, etc). I am afraid that it will be abused (they will contact me before trying everything for example) but I also think that if I am on vacation I should not be bothered even if there is an outage. Does anyone have experience with situations like this? What's the tactful approach? Any creative solutions?</p>

答:
Hand them a phone number and a quadruple overtime rate.

The goal here is not to make lots of money, the goal is to discourage needless annoyance. You're available, but only if you really need me. The database crashed, the users are compromised, you're getting multiple DDOS waves, that's when you pick up a phone. Can't find the username for some non-critical system? Don't bother.

You have to draw a clear line on what is an emergency and what is not. Go over common cases and solutions prior to taking vacation. Make sure everyone is notified ahead of time so that they can run any critical systems / processes through you before you leave.

Vacation is time off. Make sure it stays that way.


问:
What kind of reputation does Java 8 have among "enterprise" companies?
Are the new, functionally-inspired features of Java 8 well-regarded within the enterprise development community? Have they been adopted by large companies? Have coding standards been updated to account for them?

I'm in the process of completing a programming exercise for an interview. I don't write much Java, and this is my first time playing with the new features (which I think are fantastic). The company seems very "old fashioned" to me. I'm wondering if they'll find code like:

```<code>public String currentInventory() {
    String inventory = prices.entrySet().stream()
            .map(entry -> String.join(",", entry.getKey(), entry.getValue().toString()))
            .collect(Collectors.joining("\n"));

    return inventory;
}
</code>```

to be strange.

答:
There's a survey conducted in September 2014 which shows that Java 8 has already been widely adopted: Survey of More Than 3,000 Developers Reveals Java 8 Adoption Ahead of Previous Forecasts.

The report shows that 27% of those who filled out the survey have already upgraded to Java 8, with a further 36% planning to upgrade within the next 12 months (from the time of taking the survey). Only 23% of respondents were yet to evaluate Java 8.

21% of those who already upgraded to the latest Java version are using it in production, with a further 36% in staging or planning to upgrade their production environment shortly and 40% running pilots or testing with Java 8.

-- Typesafe survey: Java 8 Adoption Strong, Users Anxious for Java 9

The main reported migration problem is legacy architecture:

Of Java 8 "holdouts," 69% are running Java 7 and 26% are running Java 6. For the majority of Java holdouts, the main challenge to migrating to the latest release is their past. 37% cited "hurdles with legacy infrastructure" while 19% cited organizational obstacles. Only 19% called out specific concerns with Java 8.

I've had the exact same experience. Language migration is almost painless, unless there is some old library somewhere in dependencies which refuses to work with Java 8 (I saw this once, library mistakenly detected Java 8 as Java 4 because of incorrect if condition). The problem was (and still is) switching deployment environments to Java 8: bash scripts, OS packages, application servers, etc.

Two main reasons to switch are:

It is easy because of backwards compatibility: Java 7 code will mostly compile fine with JDK 8. You lose nothing and still can write the old-fashioned code if you like.

You get the new features, and those are not just lambdas. For example, if you use Joda-Time, there is a new Time API, which is recommended replacement for Joda-Time.

I'm wondering if they'll find code like: ... to be strange.

I'd ask them if they want to see Java 8 or Java 7 code, if it wasn't stated in requirements for solution.


答:
No, it's pointless.  Ultimately the cost/benefit analysis just doesn't work out.

For a start you need to target a platform that has security built in.  Realistically, irrespective of how much you might like the platform Android is simply not that secure - it is designed to be open.

The cost of implementing any worthwhile security is likely to be more than any profit you might see as Android has the lowest spend per user of all the mobile platforms, the only people it will ever make money for is google.  Those who don't buy the cheap handsets are frequently purists who think that the free (expression of ideas) is also specifically the free (as in beer) part so will do anything they can to avoid paying purely as a challenge.

Anything you need to do to protect your application must affect the core of the user experience and not be bolt-on protection after the fact.  Apps that do well in that regard are the ones where the product purchased is the content, not the app itself.

Since your primary concern (according to comments) is related to authentication (cracked and repackaged versions) of your app on the appstores... that's mostly the appstore's problem to solve and you may be better off looking at ways for an app to automatically register that it has been repackaged rather than deter copying.


答:
...the narrow answer to your question is, when you upcast an object into Object, then necessarily you have to downcast it to the specific type later -- unless you're going to use the Object methods like toString, or else do an end-run around the compiler's type checking with runtime introspection (e.g. Reflection).

When you upcast an object (e.g. something.setAsObject("a string")), you lose type information about that object. You can get it back in various ways, but generics is how to carry the type on for the compiler to know what to expect later, and doesn't require the downcast back to what it was before.

...

Java generics open the door for parametric polymorphism, which is a different type of polymorphism than we usually talk about in OO. It allows for creating "container" or "wrapper" types that add behaviors independent of underlying types. As wikipedia puts it, " a function or a data type can be written generically so that it can handle values identically without depending on their type"

For example, for a List<T>, what the <T> says is that a list works the same regardless of whether it's a List<String> or a List<Integer>. You can perform the same operations, and when you're done you can retrieve objects of whatever type the list contains.

So, in a funny way, generics allow a type to be unaware of the underlying type. A List<T> doesn't know, doesn't care, what type it contains. An Observer<T> doesn't know, doesn't care, what type it's observing. It just provides certain semantics on top of that type.

This allows the code to avoid a downcast. Downcasts are viewed as bad in OO, because they raises the possibility of a runtime class cast exception -- you lose the benefit of type-checking by the compiler.

In your example, making your Observer interfaces generic is saying, "I don't care what type I'm observing, I'm going to provide this Observer mechanism on top of it." Seems like an apt application of generics.

(For what it's worth, when you get into the business of combining parametric polymorphism (i.e. container types that add behaviors) with chained or fluent interfaces, you can create some really powerful and elegant programmatic APIs.)

Title: Is using generics to indicate some class/method is aware of a type good idea?

Body:
I'm going to use Java for code/idea demonstration.

Imagine it's needed to define two interfaces: Observer and Observable (observer pattern). It's a good idea to have two generic interfaces, so there is no restriction on what is being observed, who is observing it (is even using generics about this?).

Java has a concrete (non-final) Observable class and an Observer interface. You have to delegate handling observers and notifying them on update to the concrete Observer class. This is one way of implementing the pattern. I don't know if it's the best approach (probably is), but for the sake of this example let's assume every class/type who wants to be observable, must implement the Observable interface below, and handle everything itself.

We should not forget the original Observer and Observable interface/object were implemented in JDK1.0, when generics were not available.

Now the question: Is this a good idea to merely declare a generic type in an interface to denote that the implementing class needs to be aware of some specific type? Or it is totally wrong way of using generics?

See:

```<code>public interface Observable<T> {
    // Only observers who are aware of type T are allowed.
    // But should really Observable be concerned about it?
    public void registerObserver(Observer<? extends T> o);
}

// The T here denotes that implementing class will be aware of a type called T,
// (not that it can operate on a range of types).
public interface Observer<T> {
    // Observer is not aware of Observable interface directly. But it knows about T.
    public void update(T arg);
}
</code>```

VS

```<code>public interface Observable {
    // Is it an observer? then it is allowed. That's all we need to know.
    public void registerObserver(Observer o);

    // Observers will be passed the instance of observable,
    // then they call this method to fetch arg.
    // something like:
    // for(Observer o: this.observers) o.update(this);
    public <T> T getArg();
}

public interface Observer {
    // Pass me an Observable who returns T and i'll do the rest!
    public void update(Observable o);
}
</code>```

I feel I'm getting generics totally wrong.

P.S: Comparing this way of implementing the observer pattern (asking every type to re-implement these interfaces) vs the original java solution (delegation) we realize it's not really a good idea. It causes a lot of code duplicate. But it helps to understand generics better.

Update The actual problem with java.util.Observer is notifyObservers(Object arg)[link to doc] where arg is cast at runtime by observers. How can we avoid such cast?


问:
What is the purpose of stopwords?
I've just started learning about fulltext indexing and searching in MySQL and I've stumbled upon this list containing all of the "stop words" used in MySQL. I cannot understand what is tue purpose of these stop words, since this list contains a lot of actual words that I may want to search for, such as if I had a post on my blog titled "My first hello", if I searched for any of these words I wouldn't get the post since all of them are in the list. Can you please explain to me why these are what they are and what can I do in this situation because fulltext appears to be so useful but I find these stop words as such a bummer. I must be missing something.</p>

答:
The Stop Words are words which under most circumstances are noise to a full text search.  Indexing them is pointless since they're expected to occur so frequently that they will not help narrow down a result.

You do not have to use the default list, or any list at all if you don't want to.

https://stackoverflow.com/questions/796688/how-to-reset-stop-words-in-mysql has a couple of answers that will help you and links to the MySQL documentation.

The only caveat is that you have to restart and reindex after changing the list.

Title: What is the purpose of stopwords?