答:
Caleb's answer, while he is on the right track, is actually wrong. His Foo class acts both as a database facade and factory. Those are two responsibilities and should not be put into a single class.

This question, especially in the database context, has been asked too many times. Here I will try to thoroughly show you the benefit of using abstraction (using interfaces) to make your application less coupled and more versatile.

Before reading further, I recommend you to read and get a basic understanding of Dependency injection, if you do not know it yet. You might also want to check the Adapter design pattern, which is basically what hiding implementation details behind interface's public methods means.

Dependency injection, coupled with Factory design pattern, is the foundation stone and an easy way to code the Strategy design pattern, which is a part of IoC principle.

Don't call us, we will call you. (AKA the Hollywood principle).

Decoupling an application using abstraction

1. Making the abstraction layer

You create an interface - or abstract class, if you are coding in a language like C++ - and add generic methods to this interface. Because both interfaces and abstract classes have the behaviour of you not being able to use them directly, but you have to either implement (in case of interface) or extend (in case of abstract class) them, the code itself already suggests, you will need to have specific implementations to fullfil the contract given by either the interface or the abstract class.

Your (very simple example) database interface might look like this (the DatabaseResult or DbQuery classes respectively would be your own implementations representing database operations):

```<code>public interface Database
{
    DatabaseResult DoQuery(DbQuery query);
    void BeginTransaction();
    void RollbackTransaction();
    void CommitTransaction();
    bool IsInTransaction();
}
</code>```

Because this is an interface, it itself does not really do anything. So you need a class to implement this interface.

```<code>public class MyMySQLDatabase : Database
{
    private readonly CSharpMySQLDriver _mySQLDriver;

    public MyMySQLDatabase(CSharpMySQLDriver mySQLDriver)
    {
        _mySQLDriver = mySQLDriver;
    }

    public DatabaseResult DoQuery(DbQuery query)
    {
        // This is a place where you will use _mySQLDriver to handle the DbQuery
    }

    public void BeginTransaction()
    {
        // This is a place where you will use _mySQLDriver to begin transaction
    }

    public void RollbackTransaction()
    {
    // This is a place where you will use _mySQLDriver to rollback transaction
    }

    public void CommitTransaction()
    {
    // This is a place where you will use _mySQLDriver to commit transaction
    }

    public bool IsInTransaction()
    {
    // This is a place where you will use _mySQLDriver to check, whether you are in a transaction
    }
}
</code>```

Now you have a class which implements the Database, the interface just became useful.

2. Using the abstraction layer

Somewhere in your application, you have a method, let's call the method SecretMethod, just for fun, and inside this method you have to use the database, because you want to fetch some data.

Now you have an interface, which you cannot create directly (uh, how do I use it then), but you have a class MyMySQLDatabase, which may be constructed using the new keyword.

GREAT! I want to use a database, so I will use the MyMySQLDatabase.

Your method might look like this:

```<code>public void SecretMethod()
{
    var database = new MyMySQLDatabase(new CSharpMySQLDriver());

    // you will use the database here, which has the DoQuery,
    // BeginTransaction, RollbackTransaction and CommitTransaction methods
}
</code>```

This is not good. You are directly creating a class inside this method, and if you are doing it inside the SecretMethod, it is safe to assume you would be doing the same in 30 other methods. If you wanted to change the MyMySQLDatabase to a different class, such as MyPostgreSQLDatabase, you would have to change it in all your 30 methods.

Another problem is, if the creation of MyMySQLDatabase failed, the method would never finish and therefore would be invalid.

We start by refactoring the creation of the MyMySQLDatabase by passing it as a parameter to the method (this is called dependency injection).

```<code>public void SecretMethod(MyMySQLDatabase database)
{
    // use the database here
}
</code>```

This solves you the problem, that the MyMySQLDatabase object could never be created. Because the SecretMethod expects a valid MyMySQLDatabase object, if something happened and the object would never be passed to it, the method would never run. And that is totally fine.

In some applications this might be enough. You may be satisfied, but let's refactor it to be even better.

The purpose of another refactoring

You can see, right now the SecretMethod uses a MyMySQLDatabase object. Let's assume you moved from MySQL to MSSQL. You do not really feel like changing all the logic inside your SecretMethod, a method which calls a BeginTransaction and CommitTransaction methods on the database variable passed as a parameter, so you create a new class MyMSSQLDatabase, which will also have the BeginTransaction and CommitTransaction methods.

Then you go ahead and change the declaration of SecretMethod to the following.

```<code>public void SecretMethod(MyMSSQLDatabase database)
{
    // use the database here
}
</code>```

And because the classes MyMSSQLDatabase and MyMySQLDatabase have the same methods, you do not need to change anything else and it will still work.

Oh wait!

You have a Database interface, which the MyMySQLDatabase implements, you also have the MyMSSQLDatabase class, which has exactly the same methods as MyMySQLDatabase, perhaps the MSSQL driver could also implement the Database interface, so you add it to the definition.

```<code>public class MyMSSQLDatabase : Database { }
</code>```

But what if I, in the future, don't want to use the MyMSSQLDatabase anymore, because I switched to PostgreSQL? I would have to, again, replace the definition of the SecretMethod?

Yes, you would. And that does not sound right. Right now we know, that MyMSSQLDatabase and MyMySQLDatabase have the same methods and both implement the Database interface. So you refactor the SecretMethod to look like this.

```<code>public void SecretMethod(Database database)
{
    // use the database here
}
</code>```

Notice, how the SecretMethod no longer knows, whether you are using MySQL, MSSQL or PotgreSQL. It knows it uses a database, but does not care about the specific implementation.

Now if you wanted to create your new database driver, for PostgreSQL for example, you won't need to change the SecretMethod at all. You will make a MyPostgreSQLDatabase, make it implement the Database interface and once you are done coding the PostgreSQL driver and it works, you will create its instance and inject it into the SecretMethod.

3. Obtaining the desired implementation of Database

You still have to decide, before calling the SecretMethod, which implementation of the Database interface you want (whether it is MySQL, MSSQL or PostgreSQL). For this, you can use the factory design pattern.

```<code>public class DatabaseFactory
{
    private Config _config;

    public DatabaseFactory(Config config)
    {
        _config = config;
    }

    public Database getDatabase()
    {
        var databaseType = _config.GetDatabaseType();

        Database database = null;

        switch (databaseType)
        {
        case DatabaseEnum.MySQL:
            database = new MyMySQLDatabase(new CSharpMySQLDriver());
            break;
        case DatabaseEnum.MSSQL:
            database = new MyMSSQLDatabase(new CSharpMSSQLDriver());
            break;
        case DatabaseEnum.PostgreSQL:
            database = new MyPostgreSQLDatabase(new CSharpPostgreSQLDriver());
            break;
        default:
            throw new DatabaseDriverNotImplementedException();
            break;
        }

        return database;
    }
}
</code>```

The factory, as you can see, knows which database type to use from a config file (again, the Config class may be your own implementation).

Ideally, you will have the DatabaseFactory inside your dependency injection container. Your process then may look like this.

```<code>public class ProcessWhichCallsTheSecretMethod
{
    private DIContainer _di;
    private ClassWithSecretMethod _secret;

    public ProcessWhichCallsTheSecretMethod(DIContainer di, ClassWithSecretMethod secret)
    {
        _di = di;
        _secret = secret;
    }

    public void TheProcessMethod()
    {
        Database database = _di.Factories.DatabaseFactory.getDatabase();
        _secret.SecretMethod(database);
    }
}
</code>```

Look, how nowhere in the process you are creating a specific database type. Not only that, you aren't creating anything at all. You are calling a GetDatabase method on the DatabaseFactory object stored inside your dependency injection container (the _di variable), a method, which will return you the correct instance of Database interface, based on your configuration.

If, after 3 weeks of using PostgreSQL, you want to go back to MySQL, you open a single configuration file and change the value of DatabaseDriver field from DatabaseEnum.PostgreSQL to DatabaseEnum.MySQL. And you are done. Suddenly the rest of your application correctly uses the MySQL again, by changing one single line.

If you are still not amazed, I recommend you to dive a bit more into IoC. How you can make certain decisions not from a config, but from a user input. This aproach is called the strategy pattern and although can be and is used in enterprise applications, it is much more frequently used when developing computer games.

Title: How are abstract database interfaces written to support multiple database types?

Body:
How does one begin to design an abstract class for the larger application that can interface with several types of databases, such as MySQL, SQLLite, MSSQL etc?

What is the design pattern called and where exactly does it start?

Let's say you need to write a class that has the following methods:

```<code>public class Database {
   public DatabaseType databaseType;
   public Database (DatabaseType databaseType){
      this.databaseType = databaseType;
   }

   public void SaveToDatabase(){
       // Save some data to the db
   }
   public void ReadFromDatabase(){
      // Read some data from db
   }
}

//Application
public class Foo {
    public Database db = new Database (DatabaseType.MySQL);
    public void SaveData(){
        db.SaveToDatabase();
    }
}
</code>```

The only thing I can think of is an if statement in every single Database method:

```<code>public void SaveToDatabase(){
   if(databaseType == DatabaseType.MySQL){

   }
   else if(databaseType == DatabaseType.SQLLite){

   }
}
</code>```

Body:
Caleb's answer, while he is on the right track, is actually wrong. His Foo class acts both as a database facade and factory. Those are two responsibilities and should not be put into a single class.

This question, especially in the database context, has been asked too many times. Here I will try to thoroughly show you the benefit of using abstraction (using interfaces) to make your application less coupled and more versatile.

Before reading further, I recommend you to read and get a basic understanding of Dependency injection, if you do not know it yet. You might also want to check the Adapter design pattern, which is basically what hiding implementation details behind interface's public methods means.

Dependency injection, coupled with Factory design pattern, is the foundation stone and an easy way to code the Strategy design pattern, which is a part of IoC principle.

Don't call us, we will call you. (AKA the Hollywood principle).

Decoupling an application using abstraction

1. Making the abstraction layer

You create an interface - or abstract class, if you are coding in a language like C++ - and add generic methods to this interface. Because both interfaces and abstract classes have the behaviour of you not being able to use them directly, but you have to either implement (in case of interface) or extend (in case of abstract class) them, the code itself already suggests, you will need to have specific implementations to fullfil the contract given by either the interface or the abstract class.

Your (very simple example) database interface might look like this (the DatabaseResult or DbQuery classes respectively would be your own implementations representing database operations):

public interface Database
{
    DatabaseResult DoQuery(DbQuery query);
    void BeginTransaction();
    void RollbackTransaction();
    void CommitTransaction();
    bool IsInTransaction();
}

Because this is an interface, it itself does not really do anything. So you need a class to implement this interface.

public class MyMySQLDatabase : Database
{
    private readonly CSharpMySQLDriver _mySQLDriver;

    public MyMySQLDatabase(CSharpMySQLDriver mySQLDriver)
    {
        _mySQLDriver = mySQLDriver;
    }

    public DatabaseResult DoQuery(DbQuery query)
    {
        // This is a place where you will use _mySQLDriver to handle the DbQuery
    }

    public void BeginTransaction()
    {
        // This is a place where you will use _mySQLDriver to begin transaction
    }

    public void RollbackTransaction()
    {
    // This is a place where you will use _mySQLDriver to rollback transaction
    }

    public void CommitTransaction()
    {
    // This is a place where you will use _mySQLDriver to commit transaction
    }

    public bool IsInTransaction()
    {
    // This is a place where you will use _mySQLDriver to check, whether you are in a transaction
    }
}

Now you have a class which implements the Database, the interface just became useful.

2. Using the abstraction layer

Somewhere in your application, you have a method, let's call the method SecretMethod, just for fun, and inside this method you have to use the database, because you want to fetch some data.

Now you have an interface, which you cannot create directly (uh, how do I use it then), but you have a class MyMySQLDatabase, which may be constructed using the new keyword.

GREAT! I want to use a database, so I will use the MyMySQLDatabase.

Your method might look like this:

public void SecretMethod()
{
    var database = new MyMySQLDatabase(new CSharpMySQLDriver());

    // you will use the database here, which has the DoQuery,
    // BeginTransaction, RollbackTransaction and CommitTransaction methods
}

This is not good. You are directly creating a class inside this method, and if you are doing it inside the SecretMethod, it is safe to assume you would be doing the same in 30 other methods. If you wanted to change the MyMySQLDatabase to a different class, such as MyPostgreSQLDatabase, you would have to change it in all your 30 methods.

Another problem is, if the creation of MyMySQLDatabase failed, the method would never finish and therefore would be invalid.

We start by refactoring the creation of the MyMySQLDatabase by passing it as a parameter to the method (this is called dependency injection).

public void SecretMethod(MyMySQLDatabase database)
{
    // use the database here
}

This solves you the problem, that the MyMySQLDatabase object could never be created. Because the SecretMethod expects a valid MyMySQLDatabase object, if something happened and the object would never be passed to it, the method would never run. And that is totally fine.

In some applications this might be enough. You may be satisfied, but let's refactor it to be even better.

The purpose of another refactoring

You can see, right now the SecretMethod uses a MyMySQLDatabase object. Let's assume you moved from MySQL to MSSQL. You do not really feel like changing all the logic inside your SecretMethod, a method which calls a BeginTransaction and CommitTransaction methods on the database variable passed as a parameter, so you create a new class MyMSSQLDatabase, which will also have the BeginTransaction and CommitTransaction methods.

Then you go ahead and change the declaration of SecretMethod to the following.

public void SecretMethod(MyMSSQLDatabase database)
{
    // use the database here
}

And because the classes MyMSSQLDatabase and MyMySQLDatabase have the same methods, you do not need to change anything else and it will still work.

Oh wait!

You have a Database interface, which the MyMySQLDatabase implements, you also have the MyMSSQLDatabase class, which has exactly the same methods as MyMySQLDatabase, perhaps the MSSQL driver could also implement the Database interface, so you add it to the definition.

public class MyMSSQLDatabase : Database { }

But what if I, in the future, don't want to use the MyMSSQLDatabase anymore, because I switched to PostgreSQL? I would have to, again, replace the definition of the SecretMethod?

Yes, you would. And that does not sound right. Right now we know, that MyMSSQLDatabase and MyMySQLDatabase have the same methods and both implement the Database interface. So you refactor the SecretMethod to look like this.

public void SecretMethod(Database database)
{
    // use the database here
}

Notice, how the SecretMethod no longer knows, whether you are using MySQL, MSSQL or PotgreSQL. It knows it uses a database, but does not care about the specific implementation.

Now if you wanted to create your new database driver, for PostgreSQL for example, you won't need to change the SecretMethod at all. You will make a MyPostgreSQLDatabase, make it implement the Database interface and once you are done coding the PostgreSQL driver and it works, you will create its instance and inject it into the SecretMethod.

3. Obtaining the desired implementation of Database

You still have to decide, before calling the SecretMethod, which implementation of the Database interface you want (whether it is MySQL, MSSQL or PostgreSQL). For this, you can use the factory design pattern.

public class DatabaseFactory
{
    private Config _config;

    public DatabaseFactory(Config config)
    {
        _config = config;
    }

    public Database getDatabase()
    {
        var databaseType = _config.GetDatabaseType();

        Database database = null;

        switch (databaseType)
        {
        case DatabaseEnum.MySQL:
            database = new MyMySQLDatabase(new CSharpMySQLDriver());
            break;
        case DatabaseEnum.MSSQL:
            database = new MyMSSQLDatabase(new CSharpMSSQLDriver());
            break;
        case DatabaseEnum.PostgreSQL:
            database = new MyPostgreSQLDatabase(new CSharpPostgreSQLDriver());
            break;
        default:
            throw new DatabaseDriverNotImplementedException();
            break;
        }

        return database;
    }
}

The factory, as you can see, knows which database type to use from a config file (again, the Config class may be your own implementation).

Ideally, you will have the DatabaseFactory inside your dependency injection container. Your process then may look like this.

public class ProcessWhichCallsTheSecretMethod
{
    private DIContainer _di;
    private ClassWithSecretMethod _secret;

    public ProcessWhichCallsTheSecretMethod(DIContainer di, ClassWithSecretMethod secret)
    {
        _di = di;
        _secret = secret;
    }

    public void TheProcessMethod()
    {
        Database database = _di.Factories.DatabaseFactory.getDatabase();
        _secret.SecretMethod(database);
    }
}

Look, how nowhere in the process you are creating a specific database type. Not only that, you aren't creating anything at all. You are calling a GetDatabase method on the DatabaseFactory object stored inside your dependency injection container (the _di variable), a method, which will return you the correct instance of Database interface, based on your configuration.

If, after 3 weeks of using PostgreSQL, you want to go back to MySQL, you open a single configuration file and change the value of DatabaseDriver field from DatabaseEnum.PostgreSQL to DatabaseEnum.MySQL. And you are done. Suddenly the rest of your application correctly uses the MySQL again, by changing one single line.

If you are still not amazed, I recommend you to dive a bit more into IoC. How you can make certain decisions not from a config, but from a user input. This aproach is called the strategy pattern and although can be and is used in enterprise applications, it is much more frequently used when developing computer games.


问:
How to handle translations in JSON?
I am wondering what would be the most appropriate method to handle translations in JSON files in terms of arrays and objects.

Considering an object has properties related to itself, is a translation a property or a completely different entity? In which case using an array would be more appropriate.

Let's take a JSON file describing a movie, using objects:

```<code>"title": {
  "en": "The Lord of the Rings: The Fellowship of the Ring",
  "fr": "Le Seigneur des anneaux : la communauté de l'anneau"
}
</code>```

Using arrays:

```<code>"title": [
  {
    "lang": "en",
    "content": "The Lord of the Rings: The Fellowship of the Ring"
  },
  {
    "lang": "fr",
    "content": "Le Seigneur des anneaux : la communauté de l'anneau"
  }
]
</code>```

We should take into account the selected language of the application:

If the user's application language is fr, we have to check if title.fr exists, if it doesn't we'd need a predefined list of language codes to check their existence in the title object.

Using arrays we'd need to loop through all its values to check if one of them is in the desired language, but if it doesn't, the fallback is trivial compared to the previous method.

答:
Consider a situation where some items are available in different languages, and some are not, and different from record to record. And there might be items where different languages don't make sense. For example, if you have author, title, translator, the author is language independent, but there is no English translator in this case.

You might consider this way: You have an array of books. Each book is a dictionary. Each key could be directly a key of the dictionary (for example author). Then you may have more dictionaries per language, in this case "en" and "fr", where "en" has the key "title", while "fr" has the keys "title" and "translator".

The user has a list of languages in order of preference, say "it" and "en". Since "it" is not available, you take the author directly, the "title" from "en" and there is no translator. Note that you pick only one language; english title with french translator would be nonsense.

ContentLicense: CC BY-SA 3.0

Title: How to handle translations in JSON?


问:
Should a REST API be able to convert datetime to appropriate clients timezone?
Whilst implementing our API, the issue of datetime and timezones came up.

All dates are normalized to UTC in the database. Currently, in the non-API application, all datetimes are converted based on users preferences first before presented.

Now the same question came up for the API: should the the API be able to return the datetime appropriate for a timezone based on request semantics?

E.g. GET /posts?timezone=America/Sao_Paulo ?

Or should it still be done on whatever client is accessing the API?

Update: since it came up a few times: currently timestamps with timezone are returned (although it's always TZ offset +00:00). The format is the popular 8601: 2015-10-29T23:00:49+00:00

答:
It's a bad, bad, bad idea. Consider a situation where the client stores responses from the server, and then the user travels to a different time zone. Now you have a situation where this "feature" will at best give you no advantage whatsoever, or create enormous trouble.

BTW. For how many timezones and how many clients are you going to test this? If the server gives the expected reply for America/Sao_Paul, what will it respond for America/Sao_Paulo?


答:
It depends on what you are going to model.

If you take books as an example, each book is uniquely identifyable via ISBN. In this case, the Lord of the rings and its german translation Herr der Ringe are two different entities - and as such have different ISB numbers. Of course you would say, that the german version is only the translation, but it is a separate entity. On the other hand, if you tell someone you read the german edition of a book, and the other read the english version, you read two representations of the "same book" (philosophy aside).

If you are modelling a bookstore it makes totally sense to treat them differently. E.g. you make a "link" to other editions

```<code>{
    "Title":"Lord of the rings",
    "Price":"€ 10.49",
    "Paperback":"529 pages",
    "Language":"English",
    "_links":{
          "self":{
              "href":"/books/123"
          },
          "foreign language editions":[
            {
              "href":"/books/459",
              "title":"Der Herr der Ringe",
              "lang":"de"
            },
            {
              "href":"/books/3232",
              "title":"Le Seigneur des anneaux : la communauté de l'anneau",
              "lang"
            }
          ]
      },
}
</code>```

A different use case would be, if you have the same article with different translations: say, you have screws which are called Schrauben in german. In this case, it would make no sense saying, that the names refer do different things. You would model two different representations of one article in two languages, but referring to the same article. Perhaps your route is /articles/12345 you could add a query parameter to show a different translation: /articles/12345?lang=de which results in  a german representation of the same article. Another possibility is, setting the Accept-Language in the HTTP-Header: Accept-Language: en-US.

is a translation a property or a completely different entity?

A translation is either a different entity or a different representation of an entity.

Title: How to handle translations in JSON?

Body:
I am wondering what would be the most appropriate method to handle translations in JSON files in terms of arrays and objects.

Considering an object has properties related to itself, is a translation a property or a completely different entity? In which case using an array would be more appropriate.

Let's take a JSON file describing a movie, using objects:

```<code>"title": {
  "en": "The Lord of the Rings: The Fellowship of the Ring",
  "fr": "Le Seigneur des anneaux : la communauté de l'anneau"
}
</code>```

Using arrays:

```<code>"title": [
  {
    "lang": "en",
    "content": "The Lord of the Rings: The Fellowship of the Ring"
  },
  {
    "lang": "fr",
    "content": "Le Seigneur des anneaux : la communauté de l'anneau"
  }
]
</code>```

We should take into account the selected language of the application:

If the user's application language is fr, we have to check if title.fr exists, if it doesn't we'd need a predefined list of language codes to check their existence in the title object.

Using arrays we'd need to loop through all its values to check if one of them is in the desired language, but if it doesn't, the fallback is trivial compared to the previous method.

Body:
It depends on what you are going to model.

If you take books as an example, each book is uniquely identifyable via ISBN. In this case, the Lord of the rings and its german translation Herr der Ringe are two different entities - and as such have different ISB numbers. Of course you would say, that the german version is only the translation, but it is a separate entity. On the other hand, if you tell someone you read the german edition of a book, and the other read the english version, you read two representations of the "same book" (philosophy aside).

If you are modelling a bookstore it makes totally sense to treat them differently. E.g. you make a "link" to other editions

{
    "Title":"Lord of the rings",
    "Price":"€ 10.49",
    "Paperback":"529 pages",
    "Language":"English",
    "_links":{
          "self":{
              "href":"/books/123"
          },
          "foreign language editions":[
            {
              "href":"/books/459",
              "title":"Der Herr der Ringe",
              "lang":"de"
            },
            {
              "href":"/books/3232",
              "title":"Le Seigneur des anneaux : la communauté de l'anneau",
              "lang"
            }
          ]
      },
}

A different use case would be, if you have the same article with different translations: say, you have screws which are called Schrauben in german. In this case, it would make no sense saying, that the names refer do different things. You would model two different representations of one article in two languages, but referring to the same article. Perhaps your route is /articles/12345 you could add a query parameter to show a different translation: /articles/12345?lang=de which results in  a german representation of the same article. Another possibility is, setting the Accept-Language in the HTTP-Header: Accept-Language: en-US.

is a translation a property or a completely different entity?

A translation is either a different entity or a different representation of an entity.


问:
How to avoid null in primary key?
I need to make table that seems to require two column primary key with one of the columns nullable.

But according to questions I read on Stack Overflow that is undesirable and even against SQL standards (for example: NULL value in multi-column primary key)

Yet I cannot figure out how to avoid it, and I would appreciate help. Here is the problem:

I need to track performance of various block that can fill space on page on e-commerce site, but some of those blocks have multiple configurations that I need to track separately and some do not.

I thought of using a two column PK, one column would be char(8) with block name, other would be ID of configuration that would contain either null for blocks that are immutable or the ID of the configuration from the respective block's configuration table (FK basically) for others.

How do I do this without a nullable column in PK?

(I already thought about adding config_id column that would be PK but then same two columns would have to be  unique and that seem like getting nowhere to me.)

答:
Use config id=0 instead of NULL as an indicator for "immutable blocks", and make sure each config record has an id>0. If you want to use the id column as a foreign key, create an artificial configuration record with id=0 (which your program interprets as "no configuration").

Technically (and independently from the former suggestion), it may be beneficial not to use the combined two-column key as the primary key directly, but to introduce an additional column "blockId" for your primary key.  In fact, when I design a relational schema, I typically use an integer column of the form "TablenameID" for each table as the primary key, which makes a lot of things easier.

Note that the introduction of a blockId column alone will solve your original problem only on some databases - some db systems allow NULL values as part of a UNIQUE CONSTRAINT, others do not allow this, and some others allow this but do not guarantee uniqueness for records where one columns contain NULL. You might consider to check what your DB system is capable of, but I heavily recommend to use my initial suggestion to solve your problem in a database independent manner.

Title: How to avoid null in primary key?


答:
Difficult to tell from your question, but I usualy find that every table should have a single col primary key.

Perhaps you actualy need to have a third col as a primary key for the table with the two exisiting cols as FKs

When you create a primary key out of multiple FKs you can find that it becomes non unique as your software evolves, or for example your page configuration changes over time.

Title: How to avoid null in primary key?

Body:
I need to make table that seems to require two column primary key with one of the columns nullable.

But according to questions I read on Stack Overflow that is undesirable and even against SQL standards (for example: NULL value in multi-column primary key)

Yet I cannot figure out how to avoid it, and I would appreciate help. Here is the problem:

I need to track performance of various block that can fill space on page on e-commerce site, but some of those blocks have multiple configurations that I need to track separately and some do not.

I thought of using a two column PK, one column would be char(8) with block name, other would be ID of configuration that would contain either null for blocks that are immutable or the ID of the configuration from the respective block's configuration table (FK basically) for others.

How do I do this without a nullable column in PK?

(I already thought about adding config_id column that would be PK but then same two columns would have to be  unique and that seem like getting nowhere to me.)


问:
Automatic namespace resolution in C++
My question is focused on design, and the code included in this question is meant to clarify the problem I'm experiencing.  I'm interested in conceptual level answers and not code in order to answer my question.

Background:

When programming bare-metal systems, one often has to manipulate bits in memory-mapped register controlling the behaviour of on-chip or external peripherals. Usually, there are software libraries defining these bits and registers.
A minimal example might look like this:

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

/* Might be in some library like this: */
#define SOME_PERIPHERAL_BASE_ADDRESS 0x8fce0000
#define SOME_PERIPHERAL_REG1 (*((uint16_t*)(SOME_PERIPHERAL_BASE_ADDRESS + 0x8e)))

#define SOME_PERIPHERAL_REG1_AM  (1 << 3)
#define SOME_PERIPHERAL_REG1_FOO (1 << 4)
#define SOME_PERIPHERAL_REG1_BAR (1 << 5)

/* User code: */
int main()
{
    /* How to use these definitions on a bare metal system: */
    /* SOME_PERIPHERAL_REG1 is initialies to the reset value by hardware, so
     * there is no need to initialise it. */
    /* printf("reg1 = %i\n", SOME_PERIPHERAL_REG1); */
    /* This will of course segfault when not on a bare metal system. */
    /* SOME_PERIPHERAL_REG1 = SOME_PERIPHERAL_REG1_AM | SOME_PERIPHERAL_REG1_BAR; */
    /* printf("reg1 = %i\n", SOME_PERIPHERAL_REG1); */

    /* Ersatz dummy code for testing on a pc: */
    uint16_t value=0;
    printf("reg1 = %i\n", value);

    value = SOME_PERIPHERAL_REG1_AM | SOME_PERIPHERAL_REG1_BAR; /* <- No type-safty! */

    printf("reg1 = %i\n", value);

    return 0;
}
</code>```

Issues with this approach:

While this code is reasonably readable and short, it lacks in certain ways:

A programmer will tediously have to retype the prefix (SOME_PERIPHERAL_REG1_ in the example) for each register value

No type safety: A programmer can easily set a register to a value that was intended for another register (e.g. set reg1 of Some_peripheral to a value intended for the control register of Another_peripheral) or not to a register value at all (e.g. set reg1 to 15 (an integer)).

Another problem with this approach is, that some registers are not accessible with simple assigns. For example, I use an SSD1289 display controller that is connected to the external memory interface of my microcontroller. To set the registers of the SSD1289, I will need to first write the address of the register to a certain address in the memory region followed by a write of the new register value to another address in that region. With plain C, there is no way of encapsulating this except of using a setter function.

Potential Solution:

To overcome this, I tried creating a register object in C++ that is parameterised with an enum containing the bit definitions and a pointer to the address of the register. A minimal example might look like this:

```<code>#include <iostream>
#include "enum_binary_operators.hpp"

// Code that should go in the library:

/**
 * \brief An object ancapsulating a memory-mapped peripheral control register.
 *
 * \param reg_bits      An enum defining the bitfields for that register.
 * \param ret_address   The memory-mapped address where the register lies in
 *                      memory
 */
template < typename reg_bits, uintptr_t reg_address >
class Register
{
    private:
        // On the intended pare metal target, this wouldn't be neccesary, as
        // the value would be stored in the memory-mapped address of the register.
        uint16_t value = 0;
    public:
        // Write a new value to the register
        inline Register& operator= (reg_bits const& val)
        {
            // This is what is intended, but of course segfaults when not on bare metal.
            //*reinterpret_cast<uint16_t*>(reg_address) = static_cast < uint16_t > (val);

            // dummy replacement of the above line.
            value = static_cast < uint16_t > (val);
            // possibly do some more things like send the value to a remote register.
            return *this;
        }
        operator uint16_t()                         // Read register
        {
            // This is what is intended, but of course segfaults when not on bare metal.
            //return *reinterpret_cast<uint16_t*>(reg_address);

            // dummy replacement of the above line.
            return value;
        }
        [[deprecated("Please only use the appropriate register bit enum values to manipulate the register!")]] Register& operator= (int val) {}
};

/**
 * \brief An Object encapsulating a memory-mapped peripheral
 *
 * \param base_address  The base address of the registers belonging to that peripheral.
 */
template < uintptr_t base_address>
class Some_peripheral
{
    public:
        // This enum should not be in global namespace to avoid name conflicts.
        // For example many peripherals might have a register named
        // "control_register".
        enum reg1_bits : uint16_t
        {
            AM  = (1 << 3),
            FOO = (1 << 4),
            BAR = (1 << 5),
        };
        // more register bit definitions

        Register < reg1_bits, base_address + 0x8e > reg1;
        // more registers

    // ...
    // possibly more high-level functions for the peripheral like
    // initialisation routines, transmission routines, etc.
};

// More peripherals

// The base address should be provided by some file defining the peripheral addresses for a given chip.gg
//extern constexpr some_peripheral_base;
constexpr uintptr_t some_peripheral_base = 0x8fce0000;

Some_peripheral<some_peripheral_base> some_peripheral1;
// And some more peripherals

// User code:

int main()
{
    // Get the current value of the register.
    std::cout<<"reg1 = "<<static_cast < uint16_t > (some_peripheral1.reg1)<<std::endl;

    // Each register can only be written with the bits that belong to it.
    some_peripheral1.reg1 = Some_peripheral<some_peripheral_base>::reg1_bits::AM
                          | Some_peripheral<some_peripheral_base>::reg1_bits::BAR;

    // This is the intended usage:
    // Somehow, operator= should be able to deduce the scope resolution automatically at runtime.
    //some_peripheral1.reg1 = AM | BAR;

    std::cout<<"reg1 = "<<static_cast < uint16_t > (some_peripheral1.reg1)<<std::endl;

    return 0;
}
</code>```

With enum_binary_operators.hpp:

```<code>#ifndef ENUM_BINARY_OPERATORS_HPP
#define ENUM_BINARY_OPERATORS_HPP

#include <type_traits>

template < typename T >
inline typename std::enable_if < std::is_enum < T > ::value, const T > ::type
operator|(T const& x, T const& y)       {
    return static_cast < T >   (static_cast < uint16_t > (x) | static_cast < uint16_t > (y));
}

template < typename T >
inline typename std::enable_if < std::is_enum < T > ::value, const T > ::type
operator&(T const& x, T const& y)       {
    return static_cast < T >   (static_cast < uint16_t > (x) & static_cast < uint16_t > (y));
}

template < typename T >
inline typename std::enable_if < std::is_enum < T > ::value, const T > ::type
operator^(T const& x, T const& y)       {
    return static_cast < T >   (static_cast < uint16_t > (x) ^ static_cast < uint16_t > (y));
}

template < typename T >
inline typename std::enable_if < std::is_enum < T > ::value, const T > ::type
operator<<(T const& x, T const& y)       {
    return static_cast < T >   (static_cast < uint16_t > (x) << static_cast < uint16_t > (y));
}

template < typename T >
inline typename std::enable_if < std::is_enum < T > ::value, const T > ::type
operator<<(unsigned int const x, T const& y)       {
    return static_cast < T >   (x << static_cast < uint16_t > (y));
}

template < typename T >
inline typename std::enable_if < std::is_enum < T > ::value, const T > ::type
operator<<(int const x, T const& y)       {
    return static_cast < T >   (x << static_cast < uint16_t > (y));
}

#endif /* ENUM_BINARY_OPERATORS_HPP */
</code>```

Questions:

Now, my questions are:

Am I correct in assuming this should come at negligible run time overhead? Compile time will be increased, of course.

Is there a better way of doing this?

And is there any way of getting rid of the long scope specifiers in the assignment?
The idea here is, that the compiler already knows, where the enum members will have to come from (since the enum is a template argument to the register class), so maybe one could get it to include the proper scope resolution on its own in some way.

答:
One your questions raised has an easy answer: retyping the prefix.

I teach that such prefixes should be a sematic portion not just a concatenation with the name: prefix::x, not prefix_x.

For the flags, put them into their own nested namespace. You can use that within the function or even the specific scope where a bunch of them are used together.  (This is a case where using directives are OK, because it is targeted and local.)

```<code>{ // in some inner scope
    using namespace someperiphial::reg1;
    Blah blah foo, bar, am  // instead of somperiphial::reg1::foo etc.
}
</code>```

Title: Automatic namespace resolution in C++

Body:
One your questions raised has an easy answer: retyping the prefix.

I teach that such prefixes should be a sematic portion not just a concatenation with the name: prefix::x, not prefix_x.

For the flags, put them into their own nested namespace. You can use that within the function or even the specific scope where a bunch of them are used together.  (This is a case where using directives are OK, because it is targeted and local.)

{ // in some inner scope
    using namespace someperiphial::reg1;
    Blah blah foo, bar, am  // instead of somperiphial::reg1::foo etc.
}


答:
I see two potential problems with your design:

Reversing an association b/w blocks and their configurations by putting a foreign key at the wrong side of that association

Having two subtypes of blocks (immutable and the ones with configurations) mixed in a single table - "single table inheritance"

It seems like you're trying to implement a standard 1-to-N association b/w blocks and block_configurations, but for some reason you decided to reverse it by putting the key of config into each block, while you should do the opposite, i.e. you should put block_id into block_configurations instead of putting configuration_id into blocks:

```<code>CREATE TABLE blocks (
  block_id CHAR(10),
  is_immutable BIT(1) NOT NULL,
  PRIMARY KEY (block_id)
);

CREATE TABLE block_configurations (
  configuration_id INT(10) AUTO_INCREMENT,
  block_id CHAR(10) NOT NULL,
  PRIMARY KEY (configuration_id),
  FOREIGN KEY block_id_fk(block_id) REFERENCES blocks(block_id)
    ON UPDATE CASCADE
    ON DELETE RESTRICT
);
</code>```

The only thing that is not enforced by this schema is the fact of immutable blocks must not have associated configuration records. You can do that using triggers, but the better solution is to use separate configurable_blocks and immutable_blocks tables, since in this case there are two subtypes of blocks. There are two ways to do that: "multiple table inheritance" and "class table inheritance". The one I showed above is a "single table inheritance", where two subtypes of blocks are stored within a single table.

Here's an example with multiple table inheritance:

```<code>CREATE TABLE immutable_blocks (
  block_id CHAR(10),
  PRIMARY KEY (block_id)
);

CREATE TABLE configurable_blocks (
  block_id CHAR(10),
  PRIMARY KEY (block_id)
);

CREATE TABLE block_configurations (
  configuration_id INT(10) AUTO_INCREMENT,
  block_id CHAR(10) NOT NULL,
  PRIMARY KEY (configuration_id),
  FOREIGN KEY configurable_block_id_fk(block_id)
    REFERENCES configurable_blocks(block_id)
    ON UPDATE CASCADE
    ON DELETE RESTRICT
);
</code>```

This design has another flaw: if you have common attributes in two subtypes of blocks, you have to duplicate them across two tables. That's where the class table inheritance shines:

```<code>CREATE TABLE blocks (
  block_id CHAR(10),
  description VARCHAR(100), -- common field
  PRIMARY KEY (block_id)
);

CREATE TABLE immutable_blocks (
  block_id CHAR(10),
  FOREIGN KEY block_id_fk(block_id) REFERENCES blocks(block_id)
    ON UPDATE CASCADE
    ON DELETE RESTRICT
);

CREATE TABLE configurable_blocks (
  block_id CHAR(10),
  FOREIGN KEY block_id_fk(block_id) REFERENCES blocks(block_id)
    ON UPDATE CASCADE
    ON DELETE RESTRICT
);

CREATE TABLE block_configurations (
  ... same here, still references only configurable_blocks ...
);
</code>```

This design ensures referential integrity and allows you to separate common and subtype-specific fields.

Related reading:

SQL Antipatterns, "Polymorphic Associations" chapter - solutions in this chapter apply to this case

SQL Antipatterns, "Entity-Attribute-Value" chapter - describes single/multiple/class table inheritance, related to a problem of having subtypes of some entity

Title: How to avoid null in primary key?

Body:
I see two potential problems with your design:

Reversing an association b/w blocks and their configurations by putting a foreign key at the wrong side of that association

Having two subtypes of blocks (immutable and the ones with configurations) mixed in a single table - "single table inheritance"

It seems like you're trying to implement a standard 1-to-N association b/w blocks and block_configurations, but for some reason you decided to reverse it by putting the key of config into each block, while you should do the opposite, i.e. you should put block_id into block_configurations instead of putting configuration_id into blocks:

CREATE TABLE blocks (
  block_id CHAR(10),
  is_immutable BIT(1) NOT NULL,
  PRIMARY KEY (block_id)
);

CREATE TABLE block_configurations (
  configuration_id INT(10) AUTO_INCREMENT,
  block_id CHAR(10) NOT NULL,
  PRIMARY KEY (configuration_id),
  FOREIGN KEY block_id_fk(block_id) REFERENCES blocks(block_id)
    ON UPDATE CASCADE
    ON DELETE RESTRICT
);

The only thing that is not enforced by this schema is the fact of immutable blocks must not have associated configuration records. You can do that using triggers, but the better solution is to use separate configurable_blocks and immutable_blocks tables, since in this case there are two subtypes of blocks. There are two ways to do that: "multiple table inheritance" and "class table inheritance". The one I showed above is a "single table inheritance", where two subtypes of blocks are stored within a single table.

Here's an example with multiple table inheritance:

CREATE TABLE immutable_blocks (
  block_id CHAR(10),
  PRIMARY KEY (block_id)
);

CREATE TABLE configurable_blocks (
  block_id CHAR(10),
  PRIMARY KEY (block_id)
);

CREATE TABLE block_configurations (
  configuration_id INT(10) AUTO_INCREMENT,
  block_id CHAR(10) NOT NULL,
  PRIMARY KEY (configuration_id),
  FOREIGN KEY configurable_block_id_fk(block_id)
    REFERENCES configurable_blocks(block_id)
    ON UPDATE CASCADE
    ON DELETE RESTRICT
);

This design has another flaw: if you have common attributes in two subtypes of blocks, you have to duplicate them across two tables. That's where the class table inheritance shines:

CREATE TABLE blocks (
  block_id CHAR(10),
  description VARCHAR(100), -- common field
  PRIMARY KEY (block_id)
);

CREATE TABLE immutable_blocks (
  block_id CHAR(10),
  FOREIGN KEY block_id_fk(block_id) REFERENCES blocks(block_id)
    ON UPDATE CASCADE
    ON DELETE RESTRICT
);

CREATE TABLE configurable_blocks (
  block_id CHAR(10),
  FOREIGN KEY block_id_fk(block_id) REFERENCES blocks(block_id)
    ON UPDATE CASCADE
    ON DELETE RESTRICT
);

CREATE TABLE block_configurations (
  ... same here, still references only configurable_blocks ...
);

This design ensures referential integrity and allows you to separate common and subtype-specific fields.

Related reading:

SQL Antipatterns, "Polymorphic Associations" chapter - solutions in this chapter apply to this case

SQL Antipatterns, "Entity-Attribute-Value" chapter - describes single/multiple/class table inheritance, related to a problem of having subtypes of some entity


问:
What are the possible/likely pitfalls of having async scrum teams?
In our game project we currently have 2 teams that work in 2 week iterations. In the past we've repeatedly had issues with larger features (bad planning/estimates, unforseen issues before code freeze causing the stories to not getting closed, etc), and we've discussed those problems in many retrospectives.

Since the features we're supposed to implement are not getting any smaller or easier (actually quite the opposite), we've been thinking about ways to help us reduce the risk of each iteration. One such idea I had, was going with a setup similar to what ArenaNet does with Guild Wars 2:

[...] “And they’re all staggered, so even though we ship every two weeks, the development time for any one of these releases is around four months, it’s just that it’s a smaller team working for an extended period of time which allows them to give it the level of polish that players have come to expect. But it is intense!” [...]

The basic idea was to stick with the 2 week release cycle, but move the teams out of phase with each other, so that each individual team would have a total of 4 weeks to work on content. So basically, the setup would change from this:

to this:

Of course, the releases would be bigger than before, but at a first glance it seems at least somewhat beneficial:

More time to react to unforseen issues (bugs, system failures, bus factor, ad-hoc design changes, ...) without endangering the whole sprint

QA could focus on one team/feature/release at a time, instead of having to check everything from both teams at once

Ability to work on larger features without having to chunk/split them into artificial segments to fit the sprints

Now I wonder if this was actually a good idea, or if I'm missing something obvious and it would just screw up everything. Are there any other resources on this topic? Are async scrum teams workable, or is it generally just a bad idea?

答:
In the past we've repeatedly had issues with larger features (bad planning/estimates)

If you encounter planning/estimation problems just for two week sprints in advance, do you really believe this will get better if you now have to estimate your team's work for four weeks instead of two? Honestly, I think this will make things worse, not better (and it does not make a difference if your teams work synchronously or not).

Ability to work on larger features without having to chunk/split them into artificial segments

The need for splitting big features into smaller slices is IMHO a strength of the process - if you sacrifice this, your planning/estimation will become worse, your testing cycles will get longer and your ability to control the process will decrease. Thus I would heavily recommend against this. Better try to make the splitting of features not-so-artificial.

If you have bigger features to work on which cannot be completed in one sprint, split them up into smaller ones, but do not make those partly completed features available to your users immediately at the end of each sprint. Better, learn to utilize "feature branches" and "feature toggles" for your needs.

A better branching/merging strategy might also be an approach to untie your teams from the fixed "two weeks" sprint cycle - if the next feature slice fits better in 9 days instead of 14, whilst the other team needs 16 days, this should be perfectly possible. And your QA team can still get a new version every 14 days. You have to establish a strategy for this which allows you to prohibit the delivery of half-baked features from the development branch to "staging" in the middle of a sprint, without stopping your teams from work. There are different approaches how to accomplish this with Git, and of course, your configuration management effort will probably increase, but that is probably outweight by the benefits you get from this.


答:
Your problem is one of an optional relationship between two entitites.  Some blocks have multiple configurations and some do not.  I'm taking that to mean that blocks that do not have multiple configurations have no configuration at all.  If they have one configuration, your problem disappears.

You need three tables.  One for blocks, one for configurations, and one for block-configurations.  The third table represents the relationship, and contains two foreign keys.  Its PK is the combination of the two foreign keys, taken together, if you want the relationship to be many-to-many.  If not, then the PK can be one of the two fields.

When a given block has no relationship with any configuration, just omit the row in the third table.  No problem!   There aren't any nulls here, there's just an omitted row!

If you want to read more on this, look up "Sixth Normal Form".

Title: How to avoid null in primary key?


问:
How does the Python runtime know which object a method is bound to?
When defining methods in a class we do have an argument for the object on which the method is invoked i.e self.

Say I have a class Foo.

```<code>class Foo:
   def m(self):
      pass
</code>```

now when we have an object of Foo, say foo.

and we do something like this,

```<code>foo_m = foo.m
</code>```

and then try calling foo_m with the same parameters the way would have done with foo.m. It just works.

So How does foo_m knows what should be the value of the self argument when it is not being called in foo.m() fashion ?

on printing the foo.m, the REPL shows that its a bound method to that particular object.

Is it some other function object that keeps track of the self argument and the method to be called ?

答:
A bound method is just a Python object that stores self in one of its slots. Take a look at methodobject.c for the C implementation. In Python the slot is accessible via the __self__ attribute:

```<code>>>> a = [1, 2, 3].append
>>> a
<built-in method append of list object at 0x103b39588>
>>> a.__self__
[1, 2, 3]
</code>```

Body:
A bound method is just a Python object that stores self in one of its slots. Take a look at methodobject.c for the C implementation. In Python the slot is accessible via the __self__ attribute:

>>> a = [1, 2, 3].append
>>> a
<built-in method append of list object at 0x103b39588>
>>> a.__self__
[1, 2, 3]


问:
Why is the Git .git/objects/ folder subdivided in many SHA-prefix folders?
Git internally stores objects (Blobs, trees) in the .git/objects/ folder. Each object can be referenced by a SHA1 hash that is computed from the contents of the object.

However, Objects are not stored inside the .git/objects/ folder directly. Instead, each object is stored inside a folder that starts with the prefix of its SHA1 hash. So an object with the hash b7e23ec29af22b0b4e41da31e868d57226121c84 would be stored at .git/objects/b7/e23ec29af22b0b4e41da31e868d57226121c84

Why does Git subdivide its object storage this way?

The resources I could find, such as the page on Git's internals on git-scm, only only explained how, not why.

答:
It is possible to put all the files in one directory, though sometimes that can become a bit large.  Many file systems have a limit.  You want to put a git repository on a FAT32 formatted drive on a USB stick? You can only store 65,535 files in a single directory.  This means that it is necessary to subdivide the directory structure so that filling a single directory is less likely.

This would even become a problem with other file systems and larger git repositories.  A relatively small git repo that I've got hanging out (about 360MiB) and it has 181,546 objects for 11k files.  Pull the Linux repo and you've got 4,374,054 objects.  If you were to put these all in one directory, it would be impossible to check out and would crash (for some meaning of 'crash') the file system.

So? You split it up by byte.  Similar approaches are done with applications such as FireFox:

```<code>~/Li/Ca/Fi/Pr/7a/Cache $ ls
0/           4/           8/           C/           _CACHE_001_
1/           5/           9/           D/           _CACHE_002_
2/           6/           A/           E/           _CACHE_003_
3/           7/           B/           F/           _CACHE_MAP_
</code>```

Beyond this, it also goes to a question of performance.  Consider NTFS Performance with Numerous Long Filenames:

Windows NT takes a long time to perform directory operations on Windows NT file system (NTFS) formatted drives that contain a large number of files with long file names (names that do not conform to the 8.3 convention) in a single directory.

When NTFS enumerates files in a directory, it has to look up the 8.3 names associated with the long file names. Because an NTFS directory is maintained in a sorted state, corresponding long file names and 8.3 names are generally not next to one another in the directory listing. So, NTFS uses a linear search of the directory for every file present. As a result, the amount of time required to perform a directory listing increases with the square of the number of files in the directory. For small numbers of files (less than a few hundred) the time delay is negligible. But as the number of files in a directory increases to several thousand, the time required to perform a listing can increase to minutes, hours, or even days. The problem is aggravated if the long file names are very similar -- differing only in the last few characters.

With files named after SHA1 checksums, this could be a recipe for disaster and abysmal performance.

While the above is from a tech note from Windows NT 3.5 (and NTFS 1.2 - commonly used from 1995 to the early 2000s) this can also be seen in things such as EXT3 with implementations of the filesystem being linked lists requiring O(n) lookup.  And even with that B-tree change:

While the HTree algorithm significantly improved lookup times, it could cause some performance regressions for workloads that used readdir() to perform some operation of all of the files in a large directory.

  ...

  One potential solution to mitigate this performance issue, which has been suggested by Daniel Phillips and Andreas Dilger, but not yet implemented, involves the kernel choosing free inodes whose inode numbers meet a property that groups the inodes by their filename hash. Daniel and Andreas suggest allocating the inode from a range of inodes based on the size of the directory, and then choosing a free inode from that range based on the filename hash. This should in theory reduce the amount of thrashing that results when accessing the inodes referenced in the directory in readdir order. In it is not clear that this strategy will result in a speedup, however; in fact it could increase the total number of inode blocks that might have to be referenced, and thus make the performance of readdir() + stat() workloads worse. Clearly, some experimentation and further analysis is still needed.

Incidentally, this bit on how to improve performance was from 2005, the same year git was released.

As seen with Firefox and many other applications that have lots of hash cached files, the design of splitting up the cache by byte. It has negligible performance cost, and when used cross platform with systems that may be a bit on the old side, could very well be the difference between the program working or not.

Body:
It is possible to put all the files in one directory, though sometimes that can become a bit large.  Many file systems have a limit.  You want to put a git repository on a FAT32 formatted drive on a USB stick? You can only store 65,535 files in a single directory.  This means that it is necessary to subdivide the directory structure so that filling a single directory is less likely.

This would even become a problem with other file systems and larger git repositories.  A relatively small git repo that I've got hanging out (about 360MiB) and it has 181,546 objects for 11k files.  Pull the Linux repo and you've got 4,374,054 objects.  If you were to put these all in one directory, it would be impossible to check out and would crash (for some meaning of 'crash') the file system.

So? You split it up by byte.  Similar approaches are done with applications such as FireFox:

~/Li/Ca/Fi/Pr/7a/Cache $ ls
0/           4/           8/           C/           _CACHE_001_
1/           5/           9/           D/           _CACHE_002_
2/           6/           A/           E/           _CACHE_003_
3/           7/           B/           F/           _CACHE_MAP_

Beyond this, it also goes to a question of performance.  Consider NTFS Performance with Numerous Long Filenames:

Windows NT takes a long time to perform directory operations on Windows NT file system (NTFS) formatted drives that contain a large number of files with long file names (names that do not conform to the 8.3 convention) in a single directory.

When NTFS enumerates files in a directory, it has to look up the 8.3 names associated with the long file names. Because an NTFS directory is maintained in a sorted state, corresponding long file names and 8.3 names are generally not next to one another in the directory listing. So, NTFS uses a linear search of the directory for every file present. As a result, the amount of time required to perform a directory listing increases with the square of the number of files in the directory. For small numbers of files (less than a few hundred) the time delay is negligible. But as the number of files in a directory increases to several thousand, the time required to perform a listing can increase to minutes, hours, or even days. The problem is aggravated if the long file names are very similar -- differing only in the last few characters.

With files named after SHA1 checksums, this could be a recipe for disaster and abysmal performance.

While the above is from a tech note from Windows NT 3.5 (and NTFS 1.2 - commonly used from 1995 to the early 2000s) this can also be seen in things such as EXT3 with implementations of the filesystem being linked lists requiring O(n) lookup.  And even with that B-tree change:

While the HTree algorithm significantly improved lookup times, it could cause some performance regressions for workloads that used readdir() to perform some operation of all of the files in a large directory.

  ...

  One potential solution to mitigate this performance issue, which has been suggested by Daniel Phillips and Andreas Dilger, but not yet implemented, involves the kernel choosing free inodes whose inode numbers meet a property that groups the inodes by their filename hash. Daniel and Andreas suggest allocating the inode from a range of inodes based on the size of the directory, and then choosing a free inode from that range based on the filename hash. This should in theory reduce the amount of thrashing that results when accessing the inodes referenced in the directory in readdir order. In it is not clear that this strategy will result in a speedup, however; in fact it could increase the total number of inode blocks that might have to be referenced, and thus make the performance of readdir() + stat() workloads worse. Clearly, some experimentation and further analysis is still needed.

Incidentally, this bit on how to improve performance was from 2005, the same year git was released.

As seen with Firefox and many other applications that have lots of hash cached files, the design of splitting up the cache by byte. It has negligible performance cost, and when used cross platform with systems that may be a bit on the old side, could very well be the difference between the program working or not.


答: These 256 bucket allow git to store larger repositories on file systems that limit the number files in a directory and provide descent performance on file systems that become slower with directories containing many files.</p>

Title: Why is the Git .git/objects/ folder subdivided in many SHA-prefix folders?

Body:
Git internally stores objects (Blobs, trees) in the .git/objects/ folder. Each object can be referenced by a SHA1 hash that is computed from the contents of the object.

However, Objects are not stored inside the .git/objects/ folder directly. Instead, each object is stored inside a folder that starts with the prefix of its SHA1 hash. So an object with the hash b7e23ec29af22b0b4e41da31e868d57226121c84 would be stored at .git/objects/b7/e23ec29af22b0b4e41da31e868d57226121c84

Why does Git subdivide its object storage this way?

The resources I could find, such as the page on Git's internals on git-scm, only only explained how, not why.


答: There are some filesystems and/or filesystem implementations and/or libc implementations where performance degrades with large numbers of directory entries.</p>


答:
There are two reasons why this is desirable.

Directories cannot be arbitrarily large. E.g. some (reasonably modern!) filesystems are limited to 32000 entries in a single directory. The number of commits in the Linux kernel is in that order of magnitude. Subdividing the commits by their first two hex digits limits the top-level size to 256 entries. The sub-directories will be much smaller for typical git repos.

Directories are scanned linearly. In some file systems (e.g. the Ext* family), a directory is a linked list or table of entries. To look up a file, the whole list is scanned until a matching file name is found. Clearly, this is undesirable for performance. Many modern file systems additionally use hash tables or B-trees for fast lookup, but not everyone may have those. Keeping each directory small means fast access times.


问:
.NET MVC authentication to AngularJS to .NET web API advice needed
So i am inheriting a team and a large project that should have been built with a restful back end. For the time it is only reporting and we all agree to build out a web API (separate project) with using AngularJS in the current MVC project and slowly migrate everything to the web API back end.

There is a lot of authentication built already in the MVC project, so I was thinking if I generated a token that would indicate the roles the person had and passed it to the AngularJS front end to pivot the screen (such as read vs write capabilities) based on the token and then for authentication for the web API it expects that same token to come through.

What thoughts do you guys have on this?

答:
I think you will fall down on the practicality of this solution.

Embeding the roles in the key can be done no prob, but it will provide no extra security for client side functionality.

If you are retrieving the Data for say a form which may be editiable for example, simply include an IsEditable field in the data and have the server do the hard work rather than trying to code it all in js


问:
Is it a good practice to develop a video game for many platforms at once (using e.g. Unity)?
Multi-platform development tools like Unity offer us an ability to quickly deploy games to many platforms at once. However, I'm concerned about whether the final product will be any worse compared to being developed for single platform in mind.

For example, I'm creating a game with both PC and mobile device in mind. Having to support both platforms, I'll make decisions that will compromise one platform or the other, for example: I want to make a big enviorment, with many detailed objects, but I know that if I make too many objects, the game won't preform well on mobile devices (due to weaker hardware). So then I reduce the detail, but then, when played on PC, the game doesn't look as attractive, and it compromises the overall experience.

So, should one try to make the game identical on both platforms, or should one develop for a single platform at a time, and try to take advantage of the platform's capabilites?

答:
What about developing for PC hardware which is more variable than phone hardware, and certainly more variable than a dedicated gaming system (e.g. PS4)?

The typical way to handle this is to have configurable options. Many PC games allow one to adjust the resolution, detail level, view distance, density of doodads (e.g. tufts of grass), and many others.

I would have a phone or tablet version that is by default configured to have graphics more manageable for that platform, and the PC version would detect the video card and self-configure to something reasonable given its power. Many games have this feature built-in: inspect the system and set the graphics to the best-looking settings that still give a good framerate.


问:
Copyright on a forked GPL project?
I'm working on a fork of a project under the GPL that hasn't been maintained for over a year. How do I handle the copyright notice?

Here is the copyright notice how do I add my copyright?

```<code>Copyright © 2013–2014 Philipp Emanuel Weidmann (pew@worldwidemann.com)

Final Term is free software: you c...
</code>```

I have made a lot of changes and have many new features planed, I'm estimating around 60% of the code base will be different/new.

答:
As long as the tiniest bit of code remains from the original maintainers, you must keep their copyright intact, but you may add your own on a separate line, like so:</p>

```<code>Copyright © 2013–2014 Philipp Emanuel Weidmann (pew@worldwidemann.com)
Copyright © 2015 RedHatter (redhatter@example.com)

Final Term is free software: you c...
</code>```

Title: Copyright on a forked GPL project?

Body:
As long as the tiniest bit of code remains from the original maintainers, you must keep their copyright intact, but you may add your own on a separate line, like so:

Copyright © 2013–2014 Philipp Emanuel Weidmann (pew@worldwidemann.com)
Copyright © 2015 RedHatter (redhatter@example.com)

Final Term is free software: you c...


问:
Is the controller in Angular and ASP.NET MVC aimed to the same?
Is the controller in Angular and ASP.NET MVC aimed to do the same like:

Consume services to shape the data (model) to return to the view.

Modal validation.

答:
When dealing with architectures, it's very important to not confuse architecture with functionality.  The purpose of architecture is to organize your functionality, and that's all it does.  Doing so provides benefits like modularity and separation of concerns.  While these benefits are extremely important, a program that's well-architected but has little functionality invokes complexity for no discernible benefit.  I've seen programs like that: lots of ceremony, organization and structure, but most of the code doesn't do any actual work.  So be cautious about thinking about architecture before you've even decided what your program is supposed to accomplish.

That said, the primary purpose of the controller in any MV* architecture is to separate the functionality from the presentation.  That means you have a data store and your business logic on one side of the controller (your Model), and a user interface on the other side of the controller (your View).  The controller mostly acts as a go-between, a patch panel of sorts, and that's all it really does.  It provides a thin layer of separation between your UI and your functionality.

The way that this separation is provided differs between ASP.NET MVC and Angular.  In ASP.NET MVC, the controller marries an URL with a method call.  In Angular (MVVM), the controller sets up the initial state of the $scope object, and adds behavior to the $scope object.  But there are strict guidelines about what a controller can and cannot do.  The controller provides a mapping function, and that's all it does.  Everything else belongs either in the Model or the View.

You can find out more about how all this works by reading the material I link below.

Further Reading

Understanding Angular Controllers

Understanding ASP.NET MVC Controllers


问:
Does syntax really matter in a programming language?
One of my professors says "the syntax is the UI of a programming language", languages like Ruby have great readability and it's growing, but we see a lot of programmers productive with C\C++, so as programmers does it really matter that the syntax should be acceptable?

I would love to know your opinion on that.

Disclaimer: I'm not trying to start an argument. I thought this is a good topic of discussion.

Update: This turns out to be a good topic. I'm glad you are all participating in it.

答:
I believe your professor is referring to Syntactic sugar.

Syntactic sugar is a computer science term that refers to syntax within a programming language that is designed to make things easier to read or to express, while alternative ways of expressing them exist.

So what your professor is implying, is that whatever code/syntax written in one programming language, can be expressed in other languages just the same-- or even the same language.

Robert Martin, pulling from Structured Programming theorem, abstracted what programmers fundamentally do with programming languages at his keynote at RailsConf 2010: Robert Martin (youTube video, see after 14 minute mark, although I recommend the whole thing):

Sequence (assignment)

Selection (if statements)

Iteration (do-loops)

That is all programmers do, from one programming language to another, just in a different syntax or user interface (UI).  This is what I'm guessing your professor was getting at, if he/she is speaking abstractly about programming languages.

So in essence, syntax doesn't matter.  But if you want to be specific, then obviously certain languages and syntax are better suited for certain tasks than others, whereby you could argue that syntax matters.

ContentLicense: CC BY-SA 2.5


问:
Why (not) segmentation?
I am studying operating systems and the x86 architecture, and while I was reading about segmentation and paging I naturally was curious how modern OSes handle memory management. From what I found Linux and most other operating systems essentially shun segmentation in favor of paging. A few of the reasons for this that I found were simplicity and portability.

What practical uses are there for segmentation (x86 or otherwise) and will we ever see robust operating systems using it or will they continue to favor a paging based system.

Now I know this is a loaded question but I am curious how segmentation would be handled with newly developed operating systems. Does it make so much sense to favor paging that no one will consider a more 'segmented' approach? If so, why?

And when I say 'shun' segmentation I am implying that Linux only uses it as far as it has to. Only 4 segments for user and kernel code/data segments. While reading the Intel documentation I just got the feeling that segmentation was designed with more robust solutions in mind. Then again I was told on many occasions how over complicated the x86 can be.

I found this interesting anecdote after being linked to Linux Torvald's original 'announcement' for Linux. He said this a few posts later:

Simply, I'd say that porting is impossible.  It's mostly in C, but most
  people wouldn't call what I write C.  It uses every conceivable feature
  of the 386 I could find, as it was also a project to teach me about the
  386.  As already mentioned, it uses a MMU, for both paging (not to disk
  yet) and segmentation. It's the segmentation that makes it REALLY 386
  dependent (every task has a 64Mb segment for code & data - max 64 tasks
  in 4Gb. Anybody who needs more than 64Mb/task - tough cookies).

I guess my own experimentation with x86 led me to ask this question. Linus didn't have StackOverflow, so he just implemented it to try it out.

答:
I'm rather stunned that in all the time since this question was posted that nobody has mentioned the origins of segmented memory architectures and the true power that they can afford.

The original system which either invented, or refined into useful form, all the features surrounding the design and use of segmented paged virtual memory systems (along with symmetric multi-processing and hierarchical filesystems) was Multics (and see also the Multicians site).  Segmented memory allows Multics to offer a view to the user that everything is in (virtual) memory, and it allows the ultimate level of sharing of everything in direct form (i.e. directly addressable in memory).  The filesystem becomes simply a map to all the segments in memory.  When properly used in a systematic way (as in Multics) segmented memory frees the user from the many burdens of managing secondary storage, and sharing of data, and inter-process-communications.  Other answers have made some hand-wavy claims that segmented memory is more difficult to use, but this is simply not true, and Multics proved that with resounding success decades ago.

Intel created a hobbled version of segmented memory the 80286 that although it is quite powerful, its limitations prevented it from being used for anything truly useful.  The 80386 improved upon these limitations, but market forces at the time pretty much prevented the success of any system that could truly take advantage of these improvements.  In the years since it seems all too many people have learned to ignore the lessons of the past.

Intel also tried early on to build a more capable super-micro called the iAPX 432 that would have far surpassed anything else at the time, and it had a segmented memory architecture and other features strongly oriented towards object oriented programming.  The original implementation was just too slow though, and no further attempts were made to fix it.

A more detailed discussion of how Multics used segmentation and paging can be found in Paul Green's paper Multics Virtual Memory - Tutorial and Reflections

OwnerDisplayName: Mr. Shickadance

Title: Why (not) segmentation?


答: To put it simply: syntax as such doesn't matter. The semantics you can express through it matter.</p>

Title: Does syntax really matter in a programming language?

Body:
One of my professors says "the syntax is the UI of a programming language", languages like Ruby have great readability and it's growing, but we see a lot of programmers productive with C\C++, so as programmers does it really matter that the syntax should be acceptable?

I would love to know your opinion on that.

Disclaimer: I'm not trying to start an argument. I thought this is a good topic of discussion.

Update: This turns out to be a good topic. I'm glad you are all participating in it.


问:
Using short-lived REST requests to obtain messages from a message queue for clients
I would like to put together a system where clients obtain messages from a REST API, but with the producer being able to use the semantics of a message queue:  e.g. ordering of messages, a destination mailbox, etc.

I figure I can have one message queue per client.

When a client connects to one of N stateless webserver/REST endpoints to GET new messages, any new messages gets dequeued from the client's mailbox on the message queue, packaged up and sent to the client as a response to the GET.

I think there are some problems with this approach, though.

Seems each REST request would make a new connection to the message queue (or possibly there is some pool of connections - but mailboxes would have to be efficiently switchable in the connection)

Furthermore, I am not sure how to handle the case when a client gets a list of messages as a response to a GET, dies halfway through processing them, and has to re-request messages it has already been given.  The queue would have to have some level of persistence, and some ability to rewind.

My questions are:  am I going down the right path here?   What can I do about these issues and am I missing any other pitfalls?   Or maybe there is a completely different way to do this that might be more optimal?

答:
It is not because you use the semantics of a queue that you need an actual queue to back your REST service. It is very possible to create a service that uses queue-like semantics, but that is backed by a database.

In that case, you would not have a new connection per REST request but would take advantage of connection pooling. Using a database also means messages are persistent so a degree of rewinding is possible. As for dying receivers, a request to get messages could send a list of messages to the client in one request and mark these as sent in the database. The receiving application could then acknowledge receipt of a message by individual REST calls. A job running intermittently could re-mark messages to be sent to the client if no acknowledgement was received after an amount of time.


问:
How to find the closest right neighbour in a tree?
Given a class:

```<code>public class Node
{
  public List nodes[];
  public Node right;   //NULL for now
}
</code>```

What's the best way to fill the "right" element of all tree nodes?

```<code>                        N
                        |
                        |
                      / | \
                    /   |   \
                  C1--->C2-->C3
                  / \         \
                 /   \         \
                C11->C12 -----> C31
</code>```

答:
One way to structure this is to use a multi dimensional array. By doing this, one dimension can represent columns, and the other rows. So, array location [11,127] would point to the node at column 11, row 127. This also makes visualising the structure in a 2D space very easy.

To find the node to the right of another, just increment the target nodes' column dimension, e.g:

```<code>var rightNeighbour = nodes[thisNode.Column +1, thisNode.Row]
</code>```

Body:
One way to structure this is to use a multi dimensional array. By doing this, one dimension can represent columns, and the other rows. So, array location [11,127] would point to the node at column 11, row 127. This also makes visualising the structure in a 2D space very easy.

To find the node to the right of another, just increment the target nodes' column dimension, e.g:

var rightNeighbour = nodes[thisNode.Column +1, thisNode.Row]


答: Without syntax, we would not have a common "template" from which to communicate, at a human level, the intent of a block of code. Syntax provides a common framework from which compilers can be standardized; methods can be shared; maintenance can be simplified.


问:
What do SCM tools (Ansible, Puppet, Chef, etc.) provide?
I've read quite a lot about Software Configuration Management (on the Internet and also SWEBOK), but I have no clear what is the purpose of SCM tools. Or, better said, what do these tools provide that other tools do not.

Let's say that I have an environment with the following tools:

Jenkins for continuous integration.

Ant as build tool.

Git as version control system.

GitLab for Git repositories management, and for issue tracking also.

Source code analysis and testing tools, such as Sonar and JUnit.

So, my question is, what would those SCM tools provide? In which way would they be useful?

答:
All the tools that you have mentioned (Jenkins, ant, git )help to actually build and test your artifact. In java world usually this can be war, ear or just zip with the application inside. Sometimes for complicated applications it can be more than one artifact. For other programming platforms it may vary, DLLs, binaries for multiple different platforms and so forth.

Now lets say you want to deploy your application. If you have one server you can do it manually or with some homegrown script. So far so good :)

But what if you have a lot of farms (groups of machines), different farms should have deployments with different configurations (databases, different geographical locations) What if your application may scale horizontally so that adding a couple of new nodes to the farm should be a trivial task. Your QA team may just ask for a new environment to run their tests, your performance team can ask for a new environment  or add nodes to the farm to run stress tests and so on. Now managing all this stuff seems to be complicated. That's where tools like ansible, chef, salt, puppet and others come into play.

These are actually helping to automate deployment. They can provide recipes of deployment, install missing dependencies  (in order to run your project may require jre, tomcat of specific version and nginx for static content ). All this at the level of farm.

I know the answer is too generic and may seem less obvious for java developer (I'm one of those ).
But if you have a team of system/devops guys they should immediately point on benefits of these tools.


问:
IoC container with lifetime attribute
Which ioc frameworks for .net can use concrete type attribute to choose it's lifetime? Here is a simple example</p>

```<code>public interface IService
{}

[Singleton]
public class ServiceImplA : IService
{}

[Transient]
public class ServiceImplB : IService
{}

class Program
{
    static void Main(string[] args)
    {
        //now some pseudocode
        //here choosing ServiceImplA is based on some config file
        container.Register<IService, ServiceImplA>();

        //here i want GetInstance to return the same instance in each call.
        //instanceA should be equal to instanceA2
        var instanceA = container.GetInstance<IService>();
        var instanceA2 = container.GetInstance<IService>();

        //but if do the same for ServiceImplB,
        //i would like to get a new instance after each GetInstance call
    }
}
</code>```

答:
I think that lifetime management should be part of the application itself and not the class libraries. It is up to the application to decide about it in the Composition Root.

Having said that, here is a solution that you can use with the Unity container:

Create some custom attributes for the different lifetime styles that you want to have like this:

```<code>[AttributeUsage(AttributeTargets.Class)]
public class SingletonAttribute : Attribute
{

}

[AttributeUsage(AttributeTargets.Class)]
public class TransientAttribute : Attribute
{

}
</code>```

You can have these attributes in some common library and reference it from your service class libraries.

Then, apply these attributes to your service classes in your class libraries like in your question:

```<code>[Singleton]
public class ServiceImplA : IService
{}

[Transient]
public class ServiceImplB : IService
{}
</code>```

Now, define a helper method that can get the lifetime manager based on reflection like this:

```<code>public static LifetimeManager GetLifeTimeManager<T>()
{
    Type type = typeof (T);

    if(type.GetCustomAttribute(typeof(TransientAttribute)) != null)
        return new TransientLifetimeManager();

    if (type.GetCustomAttribute(typeof(SingletonAttribute)) != null)
        return new ContainerControlledLifetimeManager();

    //Add more cases here

    return new TransientLifetimeManager(); //Default is transient
}
</code>```

And use it like this:

```<code>container.RegisterType<IService, ServiceImplA>(GetLifeTimeManager<ServiceImplA>());
</code>```

By the way, this solution is DI container independent. I mean that the attributes themselves are not specific to any container. It is the GetLifeTimeManager helper method that is specific to the Unity container. But you can use other DI containers and define similar helper methods for them.

You can also create extension methods to hide the invocation of the helper method like this:

```<code>public static IUnityContainer RegisterTypeWithLifeTime<TFrom, TTo>(this IUnityContainer container) where TTo : TFrom
{
    return container.RegisterType<TFrom, TTo>(GetLifeTimeManager<TTo>());
}
</code>```

And use it like this:

```<code>container.RegisterTypeWithLifeTime<IService, ServiceImplA>();
</code>```

Title: IoC container with lifetime attribute

Body:
I think that lifetime management should be part of the application itself and not the class libraries. It is up to the application to decide about it in the Composition Root.

Having said that, here is a solution that you can use with the Unity container:

Create some custom attributes for the different lifetime styles that you want to have like this:

[AttributeUsage(AttributeTargets.Class)]
public class SingletonAttribute : Attribute
{

}

[AttributeUsage(AttributeTargets.Class)]
public class TransientAttribute : Attribute
{

}

You can have these attributes in some common library and reference it from your service class libraries.

Then, apply these attributes to your service classes in your class libraries like in your question:

[Singleton]
public class ServiceImplA : IService
{}

[Transient]
public class ServiceImplB : IService
{}

Now, define a helper method that can get the lifetime manager based on reflection like this:

public static LifetimeManager GetLifeTimeManager<T>()
{
    Type type = typeof (T);

    if(type.GetCustomAttribute(typeof(TransientAttribute)) != null)
        return new TransientLifetimeManager();

    if (type.GetCustomAttribute(typeof(SingletonAttribute)) != null)
        return new ContainerControlledLifetimeManager();

    //Add more cases here

    return new TransientLifetimeManager(); //Default is transient
}

And use it like this:

container.RegisterType<IService, ServiceImplA>(GetLifeTimeManager<ServiceImplA>());

By the way, this solution is DI container independent. I mean that the attributes themselves are not specific to any container. It is the GetLifeTimeManager helper method that is specific to the Unity container. But you can use other DI containers and define similar helper methods for them.

You can also create extension methods to hide the invocation of the helper method like this:

public static IUnityContainer RegisterTypeWithLifeTime<TFrom, TTo>(this IUnityContainer container) where TTo : TFrom
{
    return container.RegisterType<TFrom, TTo>(GetLifeTimeManager<TTo>());
}

And use it like this:

container.RegisterTypeWithLifeTime<IService, ServiceImplA>();


问:
Why not make a language with mixin-only inheritance?
It seems that in all class-based or prototypal OOP languages, mixins are either an afterthought or a secondary feature. However, to me it looks like traditional inheritance is just a specific case of using a single mixin.

I am assuming this is because of historical reasons and familiarity, but maybe there is something else? Problems with sharing encapsulated state safely?

答:
The seminal paper on mixins is Gilad Bracha's PhD thesis The Programming Language Jigsaw: Mixins, Modularity and Multiple Inheritance.

It has answers to all of your questions, like

Why not make a language with mixin-only inheritance?

Jigsaw is such a language, as is Newspeak, Bracha's current language

However, to me it looks like traditional inheritance is just a specific case of using a single mixin.

Indeed, mixin inheritance subsumes all classical forms of single (class-based) inheritance (Simula-/Smalltalk-style inheritance as well as Beta-style prefixing), as well as multiple class-based inheritance with linearization (CLOS, C++, Python, …)

You may want to have a look at Newspeak. Don't be fooled by the fact that it has "classes". They are actually mixins. The Jigsaw paper describes how classes can be elevated to mixins, and that is exactly how it works in Newspeak.

Basically, a mixin is a class that doesn't know its superclass. Therefore, it can appear at multiple places in the inheritance tree. (Note that this is not multiple inheritance! It is, in fact, in some sense exactly the opposite or dual: in multiple inheritance, a class appears at a single place with multiple superclasses, in mixin inheritance, a class appears at multiple places with a single superclass.)

In Newspeak, OO is taken to the extreme: everything is a message send ("virtual method/function call" in Javanese/C++). Even superclass lookup. So, when you declare a class Sub as a subclass of Super, the superclass of Sub is not stored inside some pointer in the internal implementation of Sub, no, whenever you need the superclass (e.g. during message dispatch (virtual method/function lookup/dispatch in Javanese/C++)), the runtime interprets Super as the name of a method to call which returns a class. However, it is not known at runtime which class it returns. In fact, it might return a different class every time! Therefore, classes in Newspeak don't know their superclass, which is the/a definition of a mixin.

Note that in a prototype-based language, the idea of having a dedicated mixin makes no sense. The whole point of a prototype-based language is that there is only one kind of "things" (objects) as opposed to two kinds of "things" (objects and classes, objects and traits, objects and mixins, …). They can be used as a Design Pattern, of course. That's how they were originally invented, after all, in the Flavors object system for Lisp, which had classes with multiple inheritance, but the classes were often used in a peculiar way, which they called mixins (and from which the object system got its name).


答:
In practice I think it does matter. Readability has already been discussed above. Another issue might be how many keystrokes are neded to express an idea/algotithm? Yet another issue is how easy it is for simple typos to be hard for the human eye to catch, and how much mischief they can cause.

I've also found it useful in some contexts to analyze, and/or to generate fragments of code via another computer program. The difficulty of parsing the
language, and/or generating correct code then directly impacts how much effort is required to create/maintain such tools.


问:
Best practice for angular service return value
I have a number of angular services (e.g. a user service) which make various HTTP calls and I'm wondering what the best practice would be for handling errors.  For example, I could do:

```<code>function getAll(success, error) {
    $http.get('/api/users').then(success, error);
}
</code>```

Or I could do:

```<code>function getAll(success) {
    $http.get('/api/users').then(success, function(err) {
        success([]);
    });
}
</code>```

The advantage of the former is it is more configurable in case I wanted to do something special.  However, the advantage of the second is that it keeps the controllers simpler and in the (hopefully rare) case that the server is down it won't simply throw an error but will just display blank/empty data.

Is there any guideline or accepted best practice for this kind of situation?

答:
My preferred pattern is that the api layer returns a promise which is resolved if the call is successful (whether it found any data or not) and rejected only if the call failed.

A call to getCurrentUser for instance is supposed to either return a user or tell me that user doesn't exist or that I don't have adequate permissions or various other things. If it does any of those things it is supposed to do, the api call itself is successful and the result should be passed back to the caller. If instead, I get a 4xx or 5xx error code, then the call itself failed and the caller should be notified.

Let the api layer worry about making the call and returning the data.
Let the data layer worry about interpreting the data and updating models.
Let the UI layer about presenting the data and notifying the user if there was an error.


问:
Service repository and discovery without WSDL
I'm in the very early stages of moving a development team away from large monolithic app development to an SOA approach. One of the things that caught my eye in this article about SOA:

Stevey's Google Platforms Rant

"if you have hundreds of services, and your code MUST communicate with other groups' code via these services, then you won't be able to find any of them without a service-discovery mechanism"

I can see us creating a lot of services because we provide a very wide range of services to the business so service repository / discovery will be important.

I'm also mindful of this quote from an article by David Linthicum on MSDN:

Chapter 1: Service Oriented Architecture (SOA)

"SOAs may be realized via Web services but Web services are not necessarily required to implement SOA"

I'm not sure that I want the endpoint of every service to be available as a web service, some of the end points might be Windows Services, or even simple console apps running for a few seconds in the middle of the night.

Is it frowned upon in SOA to base the service repository / discovery on the actual interfaces that the endpoints will implement? I'm thinking of some way of searching a library of DLLs (we're 100% .NET here) and being able to quickly see the contracts, and also see any concrete implementations of the contracts we have written and the developer notes about each one. Is this an approach that will cause problems as time goes by, we implement more services and the whole thing gets bigger?

答:
Take on a service catalog "service" as a project.  This is where one can retrieve the list of available services, and you can manage which services are available to which types of consumers (internal, external, metered).

If you have any exposure in Azure (you mentioned .NET), you can use API Management to do a lot of this for you.  https://azure.microsoft.com/en-us/services/api-management/