问:
Designing an API with access tokens, how to handle GET requests?
I am building an API that will utilize access tokens so that I can track usage among various departments and for access control. My plan is to utilize the HTTP verbs appropriately - GET will retrieve information, POST will add, DELETE will delete, etc.

My question is, how should I handle access tokens on the GET calls?

Option one:

Is to provide the access token as part of the query string: /api/users/?token=ACCESSTOKEN. The problem I have with this is that the ACCESSTOKEN appears in server logs. This method will also be different than POST or DELETE requests that have the token passed via the body.

Option two:

Provide a body to the request (as you do in a POST request) and one of the parameters is the token. My issue here is that other developers in my company are telling me this isn't a "true GET request" because I'm passing data. The url they call simply looks like this /api/users/ and they provide token=ACCESSTOKEN within the body.

Option three:

Drop using GET and force everything to be a POST. I don't like this idea because for many of these API calls, I'm not creating new resources. I'm simply returning data that just happens to sit behind an API that requires authorization.

Is there an option that I am missing or should refine? I like option 2, but am sensitive to the concerns of other department developers.

答:
Why don't you use request headers?  This separates authentication/authorization data from the actual meaningful data of the request, and it can be used for any type of request (using a request body on a get is typically something you shouldn't do.) </p>

<p>Having authorization in the headers allows you to authenticate the user before parsing the body of the request, which is advantageous when you don't want your system wasting time parsing data from an unauthorized user. </p>

Body:
Why don't you use request headers?  This separates authentication/authorization data from the actual meaningful data of the request, and it can be used for any type of request (using a request body on a get is typically something you shouldn't do.)

Having authorization in the headers allows you to authenticate the user before parsing the body of the request, which is advantageous when you don't want your system wasting time parsing data from an unauthorized user.


问:
Domain Model, validation, and pushing errors to the model
Looking into DDD and something I noticed is that business logic should be in the model, otherwise you just have property bags.  That said how do you handle pieces of validation that require a trip to the database?

For example, you have an domain object that represent categories for a blogging engine.

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}
```

<p>From a developer's perspective, you could create an empty category, but this isn't valid in the business world.  A <code>Category</code> <strong>requires</strong> a Name to be a valid category, therefore we end up with:</p>

<pre class="lang-cs prettyprint-override"><code>public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }

    public Category(string name)
    {
        Name = name;
    }
}
</code>```

Now, a Category can't be created without a name.  But, we can't have duplicate Category names either, that would just cause confusing and redundancy.  I don't want the entity to handle it themselves because this would end up more of an Active Record Pattern and I don't want the model to be "self-aware/persisting" so to speak.

So to this point, where should this validation take place.  It is important that if the user types an duplicate Category, we would notify the user of this.  Should there be a "service" layer that takes a UI model and turns it into the domain model and attempts to validate it, pushing errors back to the UI, or should there be something closer to the data layer that handles this?

Someone please set me straight because I really like where DDD is going, I just can't make all the connections to get there myself.

答:
Why don't you create a service holding a collection of all categories? Then you can do validation very easy. An example:

class BlogCategoryService
{
   private List<Category> _categories = new List<Category>();

   public void AddCategory(string categoryName)
   {
       if (_categories.Any(c => c.Name == categoryName))
           throw new DuplicateCategoryException(categoryName);

       var newId = ...

       _categories.Add(new Category(newId, categoryName));
   }
   ...
}
```

<p>Do the name validation in your Category class:</p>

<pre class="lang-cs prettyprint-override"><code>public class Category
{
    public int Id { get; private set; }
    public string Name { get; private set; }

    public Category(int id, string name)
    {
        ValidateName(name);

        Id = id;
        Name = name;
    }

    private void ValidateName(string name)
    {
       if (string.IsNullOrWhitespace(categoryName))
           throw new ArgumentException('Category name may not be null or whitespace.');
    }

}
</code>```

If you want to change name on a category, you could depend on your service:

public class Category
{
    ...

    public void ChangeName(BlogCategoryService service, string newName)
    {
        if (service == null)
            throw new ArgumentNullException('service');

        ValidateName(newName);

        if (!service.IsUniqueCategoryName(newName))
            throw new DuplicateCategoryException(newName);

        Name = newName;
    }
}

public class BlogCategoryService
{

    ...
    public bool IsUniqueCategoryName(string name)
    {
        return !_categories.Any(c => c.Name == name);
    }
}
```

Also add a unique constraint on the name column of the blog category table to to guard against someone making changes outside of your BlogCategoryService.

ContentLicense: CC BY-SA 3.0

Body:
Why don't you create a service holding a collection of all categories? Then you can do validation very easy. An example:

class BlogCategoryService
{
   private List<Category> _categories = new List<Category>();

   public void AddCategory(string categoryName)
   {
       if (_categories.Any(c => c.Name == categoryName))
           throw new DuplicateCategoryException(categoryName);

       var newId = ...

       _categories.Add(new Category(newId, categoryName));
   }
   ...
}

Do the name validation in your Category class:

public class Category
{
    public int Id { get; private set; }
    public string Name { get; private set; }

    public Category(int id, string name)
    {
        ValidateName(name);

        Id = id;
        Name = name;
    }

    private void ValidateName(string name)
    {
       if (string.IsNullOrWhitespace(categoryName))
           throw new ArgumentException('Category name may not be null or whitespace.');
    }

}

If you want to change name on a category, you could depend on your service:

public class Category
{
    ...

    public void ChangeName(BlogCategoryService service, string newName)
    {
        if (service == null)
            throw new ArgumentNullException('service');

        ValidateName(newName);

        if (!service.IsUniqueCategoryName(newName))
            throw new DuplicateCategoryException(newName);

        Name = newName;
    }
}

public class BlogCategoryService
{

    ...
    public bool IsUniqueCategoryName(string name)
    {
        return !_categories.Any(c => c.Name == name);
    }
}

Also add a unique constraint on the name column of the blog category table to to guard against someone making changes outside of your BlogCategoryService.


问:
Frequent file system writes in PHP when serializing objects
I am building a game based on PHP and MySQL. There is a player-vs-player mode but I figured I should add a player-vs-computer mode as well, since players may not be online at all times, especially in the beginning.

It is a combat type of game where players have up to two characters and can fight each other, taking turns.

I decided to save the computer's units on the filesystem instead of in a database. There are different monster camps which players may attack. If multiple players attack the same camp, separate instances are being created.

However what I'm having my doubts about is whether I should save the full unit information in the instance or just the properties that can change in the course of battle. Let me give an example.

Here's the unit class

```<code>class Unit {
    // Generic
    protected $id = null;
    public function getID(){ return $this->id; }

    public $owner = null;
    public $name;

    // Vitality
    public $HP          = 100;
    public $HPmax       = 100;
    public $energy      = 100;
    public $NRGmax      = 100;

    // Physical
    public $strength    = 0;
    public $endurance   = 0;

    // Psychical
    public $knowledge   = 0;
    public $wisdom      = 0;

   // ...
}
</code>```

And here's how the file structure looks like

```<code>/PvC/prototypes/
/PvC/clones/
</code>```

in prototypes are saved the preset settings of individual units, while in clones are saved the instances that the players are fighting against currently. How it works at the moment is in clones I save serialize($computer->units) which inserts the complete full information of the unit. My concern is that some properties, such as name, owner and others, will never change during the battle, so rewriting those each time is pretty pointless. And the instance file is getting rewritten pretty often I'd say, with almost every single request during battle.

In order to avoid that continuous overwriting I could serialize only the properties that can change during battle and then load the unit from the prototype as is, then overwrite that with the properties from the clone. However the problem with that is that I'm loading two files instead of one, then loading a bunch of data from the first file that I won't use, and is going to get overwritten.

I know this is not really something that would matter, as file size will rarely exceed 10kb. What are your thoughts on this?

答:
I think it is better to put units data into the database and not into files. I would not recommend serializing the objects. Just create a MySQL table with fields like hp, strength, endurance etc. Then you can update only the fields that changed during the given round of the battle. If you don't plan to use any object-relational mapper (like Propel or Doctrine), you can have an array to track the fields that changed. Example code:

```<code>class Unit {
    private $id;

    private $hp;  //sorry, you will have to make it private
    ...

    private $changedFields = array();

    public function setHp($value)
    {
        $this->changedFields['hp'] = true;
        $this->hp = $value;
    }

    //i'm using active record pattern here, which may not be a good idea; this is just an example
    public function save()
    {
        if (empty($this->changedFields)) {
            return; //nothing to save
        }

        //build the MySQL query
        $dataToWrite = array();
        foreach($this->changedFields as $name => $temp) {
            $dataToWrite[] = "$name={$this->$name}"; //TODO: escape
        }
        mysql_query("UPDATE units SET " . implode(',', $dataToWrite) . " WHERE id={$this->id}");
    }
}
</code>```

Then just call save() on every object of the Unit class.

It would be better to use an entity manager that keeps track of changes and writes data to the database in a more optimized query.

Body:
I think it is better to put units data into the database and not into files. I would not recommend serializing the objects. Just create a MySQL table with fields like hp, strength, endurance etc. Then you can update only the fields that changed during the given round of the battle. If you don't plan to use any object-relational mapper (like Propel or Doctrine), you can have an array to track the fields that changed. Example code:

class Unit {
    private $id;

    private $hp;  //sorry, you will have to make it private
    ...

    private $changedFields = array();

    public function setHp($value)
    {
        $this->changedFields['hp'] = true;
        $this->hp = $value;
    }

    //i'm using active record pattern here, which may not be a good idea; this is just an example
    public function save()
    {
        if (empty($this->changedFields)) {
            return; //nothing to save
        }

        //build the MySQL query
        $dataToWrite = array();
        foreach($this->changedFields as $name => $temp) {
            $dataToWrite[] = "$name={$this->$name}"; //TODO: escape
        }
        mysql_query("UPDATE units SET " . implode(',', $dataToWrite) . " WHERE id={$this->id}");
    }
}

Then just call save() on every object of the Unit class.

It would be better to use an entity manager that keeps track of changes and writes data to the database in a more optimized query.


答:
Option 4: Authorization Headers and RFC 6750 (Bearer Tokens)

The solution you are looking for has already been specified as part of the OAuth2 standard, but it stands by itself and will be useful in your scenario.

https://www.rfc-editor.org/rfc/rfc6750

All requests from the client will pass in a bearer token (your access token), and it looks like any other request header to the server. The request itself looks like this:

```<code>GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer mF_9.B5f-4.1JqM
</code>```

Since it's a widely implemented public standard, you don't have to worry about defining behaviour - just point client-side developers at the RFC. You might also consider implementing the rest of the OAuth2 standard as both a resource server and an authorization server, but that is a lot more work.

Title: Designing an API with access tokens, how to handle GET requests?

Body:
I am building an API that will utilize access tokens so that I can track usage among various departments and for access control. My plan is to utilize the HTTP verbs appropriately - GET will retrieve information, POST will add, DELETE will delete, etc.

My question is, how should I handle access tokens on the GET calls?

Option one:

Is to provide the access token as part of the query string: /api/users/?token=ACCESSTOKEN. The problem I have with this is that the ACCESSTOKEN appears in server logs. This method will also be different than POST or DELETE requests that have the token passed via the body.

Option two:

Provide a body to the request (as you do in a POST request) and one of the parameters is the token. My issue here is that other developers in my company are telling me this isn't a "true GET request" because I'm passing data. The url they call simply looks like this /api/users/ and they provide token=ACCESSTOKEN within the body.

Option three:

Drop using GET and force everything to be a POST. I don't like this idea because for many of these API calls, I'm not creating new resources. I'm simply returning data that just happens to sit behind an API that requires authorization.

Is there an option that I am missing or should refine? I like option 2, but am sensitive to the concerns of other department developers.

Body:
Option 4: Authorization Headers and RFC 6750 (Bearer Tokens)

The solution you are looking for has already been specified as part of the OAuth2 standard, but it stands by itself and will be useful in your scenario.

https://www.rfc-editor.org/rfc/rfc6750

All requests from the client will pass in a bearer token (your access token), and it looks like any other request header to the server. The request itself looks like this:

GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer mF_9.B5f-4.1JqM

Since it's a widely implemented public standard, you don't have to worry about defining behaviour - just point client-side developers at the RFC. You might also consider implementing the rest of the OAuth2 standard as both a resource server and an authorization server, but that is a lot more work.


问:
Penny auction concept and how the timer works
I am creating a penny auction site using PHP yii framework. The main consideration of the system is to update the database records of all active auctions (max 15 auctions) with the current ticker timer.

I am seeking for advice on how I should design the system where every auction item will have its own countdown timer stored in the database. When someone bids the auction item, the counter should reset to 2 min. All users who are connected to the system should see the same countdown timer for that particular auction.

I am little confused on how I should design the system. Will there be a performance issue if there are frequent updates to the database (Mysql)? If there are 15 active auctions, and they are updated every second, the countdown timer decreases by a second in the database table for the particular auction.

My first idea for the underlying schema, for a table called auction_lots:

```<code>Auction_id,startdatetime,counter_timer,status
</code>```

I am seeking for advice on how I should design this.

答:
I would not recommend updating the records of all active auctions every second. I think the better way would be to store an expiration time for every auction as date and time (or a timestamp) and modify it only when an event happens (eg. when someone bids the auction item, set it to current_time+2 minutes).

To make everyone see the same value, you should write a simple script that computes the number of seconds to the end of all active auctions:

```<code>$time = time();   //current timestamp from server
//for each active auction:
$secondsToEnd[$auction->id] = $auction->expiration_timestamp - $time;
echo json_encode($secondsToEnd);
</code>```

Then make every client read the $secondsToEnd from the server via an AJAX call every second.

I checked one Polish penny auctions site and I think that is how it works. The real problem I think is when two people click "bid" in a very short period of time. Then one of them should be given an error.

Body:
I would not recommend updating the records of all active auctions every second. I think the better way would be to store an expiration time for every auction as date and time (or a timestamp) and modify it only when an event happens (eg. when someone bids the auction item, set it to current_time+2 minutes).

To make everyone see the same value, you should write a simple script that computes the number of seconds to the end of all active auctions:

$time = time();   //current timestamp from server
//for each active auction:
$secondsToEnd[$auction->id] = $auction->expiration_timestamp - $time;
echo json_encode($secondsToEnd);

Then make every client read the $secondsToEnd from the server via an AJAX call every second.

I checked one Polish penny auctions site and I think that is how it works. The real problem I think is when two people click "bid" in a very short period of time. Then one of them should be given an error.


问:
Best approach for tracking dependent state
Let's pretend I work on a project tracking application.  The application is a database backed, server hosted, web application.  In this application there are Projects which have many Activities which have many Tasks.  A Task has two date fields an originalDueDate and a projectedDueDate.

In addition, there are dynamic fields on the Activities and the Projects which indicate whether the Activity or Project is behind schedule based on the projected due dates of the child tasks and various other variables such as remaining buffer time, etc.

There are a number of things that can cause the projectedDueDate to change.  For example, an employee working on the project may (via a server request) enter in a shipping delay.  Alternatively, a site may (via a server request) enter in an unexpected closure.

When any of these things occur I need to not only update the projectedDueDate of the Task but also trigger the corresponding Project and Activity to update as well.

What is the best way to do this?

I've thought of the observer pattern but I don't keep a single copy of all these objects in memory.  When a request comes in, I query the Task in from the database, at that point there is no associated Activity in memory that would be a listener.  I could remove the ability to query for Tasks and force the application to query first by Project, then by Activity (in context of Project), then by task (in context of Activity) adding the observer relationships at each step but I'm not sure if that is the best way.

I could setup a database event listening system so when a Task modified event is dispatched I have a handler which queries for the Activity at that point.

I could simply setup a two-way relationship between Task and Activity so that the Task knows about the parent Activity and when the Task updates his state the Task grabs his parent and updates state.

Right now I'm stuck considering all the options and am wondering if any single approach (doesn't have to be a listed approach) is jumping out at others as the best approach.

答:
First: never feel bad about storing data in two places.  This is done in "Reporting" / "Warehousing" databases all the time - it's a de-normalization and it's perfectly acceptable.  As long as you have disk space to do it, great!  One less join or query is a lot less load.

Now... architecturally this type of problem happens when you have either:

An Aggregate (which is the combination of objects that aren't directly related but are required for business logic to apply.

An Event (which is the type that happens in Publish and Subscribe models) that needs to be broadcast to one or more subscribers.

Likely you have #2 - and rather than hacking it up in the database, consider a few alternatives.  You're on the right track with Observer pattern.

Solving:

The best thing you can do is create a new object.  Load data from the disparate objects through whatever mechanism(s) via one or more factories then apply your business logic to compute the new resulting date and persist to the database via your normal route which may involve Converters to get back to your standard entities or simply SQL Updates to change the dates.

Sounds like you require an event - when data needs to be shared between two pieces of the system that don't normally talk to each other during the current execution path, events can give you a clean way to communicate.  This is especially true in your scenario when multiple commands (requests) can cause this event.

In #2, you can go the route of "eventual consistency" and process the event asynchronously or you can opt to handle it within the same transaction.  Without knowing more about your architecture, it's hard to say how to make this event mechanism available.

Remember, you don't need one subscriber for every possible Task.  Just one (per type of event) that receives the information required, loads the Activity or Project (if required) and makes the changes needed to keep the system synchronized.

Check out DDD - even if you don't use it, it helps you think about problems in different ways. (also CQRS and Event Sourcing are great topics)


问:
Should all programmers know how to solve algorithms, etc
I'm 15 and have been programming for about 3-4 years. I mostly program in Java as it was my first language.

I would like to be a programmer when I'm older, but I'm not sure about the differences. I've used a website, named hackerrank.com, and struggled immensely on the EASY questions. I can program games, applications, etc. But solving algorithms on this website is extremely difficult for me. If I were to be a programmer, would I have to be able to solve extremely difficult algorithms, or not? I understand Computer Scientists would have to, but a back-end game developer, or application developer for large aviation companies need to?

答:
Yes, many developers, especially in challenging fields such as video games or avionics, have to solve challenging logical and computing problems all day long. If this does not suit your taste or if you tend to have lesser logical capacities than people of your age with equivalent experience, then programming may not be for you. You could still run a modest career on modest/dirty projects but it could be fairly boring and I would exclude challenging fields.

However please note that at 15 your cognition capacities are still incomplete, that experience will help a lot and that programming is difficult anyway. Even more at the beginning. Besides you may be less experienced than you think you are: you claim that you have programmed since a few years but you should better evaluate the number of actual hours spent programming and convert this into weeks of full-time studies/work.


答: I've found that for the most part, in an everyday business setting, the programming you do isn't really complicated.  Usually no where near the difficulty of problems found in text books or competitions.  Most of the complicated algorithms you need are provided for you in libraries.  That being said, it is also true that most generic business problems are not the most interesting.  If you are looking to solve the tough problems, you will need to learn as much math as possible.</p>

Title: Should all programmers know how to solve algorithms, etc

Body:
I'm 15 and have been programming for about 3-4 years. I mostly program in Java as it was my first language.

I would like to be a programmer when I'm older, but I'm not sure about the differences. I've used a website, named hackerrank.com, and struggled immensely on the EASY questions. I can program games, applications, etc. But solving algorithms on this website is extremely difficult for me. If I were to be a programmer, would I have to be able to solve extremely difficult algorithms, or not? I understand Computer Scientists would have to, but a back-end game developer, or application developer for large aviation companies need to?


问:
Why does a bytecode VM use stack or registers opposed to direct operations?
I'm working on a simple bytecode interpreter to learn how virtual machines work. I've read about VMs and it seems that all of them are either stack based or register based. At the time it made sense, but then I started working on my interpreter and realized what am I doing? (I decided on a register machine.) I'm just loading all these values from pointers into these fake registers, doing operations, then putting the result back into the register and copying to a pointer. I thought, why not just do this directly? Why create fake registers that just serve as an overhead. Maybe I don't know enough about VMs yet to fully understand, but it would seem to me like my way would be much faster.</p>

答:
The job of a VM is to execute arbitrary code. (Put aside thoughts of the JIT for a second, we are just talking the pure VM). How do you expect to compile arbitrary programs down to bytecode for your VM? You have to have an instruction set. That intruction set has to work on something. If you are talking about directly operating variables from a high level language, well sure that is possible, but it isn't really a VM. It is just an interpreter. An interpreter can be symbolic (ie. it can work on names), and it can be high level. It can operate on AST nodes, or on pure text. But a VM generally is lower level, emulates a simple CPU, and the bytecode itself is a form of intermediate language. So you can distribute your programs in bytecode form which gives you some level of protection (though in Java and .NET world not as much as it could were the VM a bit lower level).

The downside to high level intepreters is they do a lot of symbolic work every time you execute the program. The strength of a VM comes when combined with the compiler. Take C# for example. Sure you can write a program to interpreter C# at a high level (I did this for the Parrot VM years ago), but the execution is much more efficient if you do some of the work ahead of time like compile variables down to registers or stack operands. Then your program becomes much denser than ASTs, and is again, conveniently represented as dense bytecode.

You define virtual operations that are simpler, or closer to real instructions to be compiled on the fly to real native executable by the JITter, also known as Just In Time Compilation. The simpler, more low level the ops are, the more efficient the JITter implementation is.

Also, in non-JIT mode (pure VM operation) if you compile the symbolic accesses down to registers or stack operands, you can improve the performance of your VM by making sure the core register area is cacheable. If your variables are all over the heap, and you opt to operate on them directly, you lose cache efficiency. With a register VM we might design it with fixed registers, or unlimited virtual registers, but in any case, an allocator will map them to fixed registers that are packed into a contiguous segment of RAM that we hope will fit into less L1 cache lines and gain performance for spatial locality.

But a high level symbolic VM that operates on variables directly is possible. Here are a couple of alternatives.

VM A - Symbolic:

```<code>newglobal "count"
add "count", 1
</code>```

VM B - Register (memory transfer):

```<code>mkglobal "count"
move $R1, "count"
inc $R1
</code>```

The benefit of VM B is the opcodes are very close to or easily translatable to real live processors, because most processors don't allow operations on memory variables and require you to load the variable into a register or onto a stack. The JIT will have much less to do. With VM A, the add operation is really a fat, aggregate operation which has to be compiled into individual native ops.

For a simple comparison to the two approaches study Perl5 and study C#/.NET bytecode. While it is possible to compile Perl5 to a bytecode, it isn't the default form of it. Perl really does more symbolic interpretation of an in-memory AST. That is why it was a major architectural change when we wrote Parrot for Perl6, though I'm not convinced it was the right decision now for that language.

Body:
The job of a VM is to execute arbitrary code. (Put aside thoughts of the JIT for a second, we are just talking the pure VM). How do you expect to compile arbitrary programs down to bytecode for your VM? You have to have an instruction set. That intruction set has to work on something. If you are talking about directly operating variables from a high level language, well sure that is possible, but it isn't really a VM. It is just an interpreter. An interpreter can be symbolic (ie. it can work on names), and it can be high level. It can operate on AST nodes, or on pure text. But a VM generally is lower level, emulates a simple CPU, and the bytecode itself is a form of intermediate language. So you can distribute your programs in bytecode form which gives you some level of protection (though in Java and .NET world not as much as it could were the VM a bit lower level).

The downside to high level intepreters is they do a lot of symbolic work every time you execute the program. The strength of a VM comes when combined with the compiler. Take C# for example. Sure you can write a program to interpreter C# at a high level (I did this for the Parrot VM years ago), but the execution is much more efficient if you do some of the work ahead of time like compile variables down to registers or stack operands. Then your program becomes much denser than ASTs, and is again, conveniently represented as dense bytecode.

You define virtual operations that are simpler, or closer to real instructions to be compiled on the fly to real native executable by the JITter, also known as Just In Time Compilation. The simpler, more low level the ops are, the more efficient the JITter implementation is.

Also, in non-JIT mode (pure VM operation) if you compile the symbolic accesses down to registers or stack operands, you can improve the performance of your VM by making sure the core register area is cacheable. If your variables are all over the heap, and you opt to operate on them directly, you lose cache efficiency. With a register VM we might design it with fixed registers, or unlimited virtual registers, but in any case, an allocator will map them to fixed registers that are packed into a contiguous segment of RAM that we hope will fit into less L1 cache lines and gain performance for spatial locality.

But a high level symbolic VM that operates on variables directly is possible. Here are a couple of alternatives.

VM A - Symbolic:

newglobal "count"
add "count", 1

VM B - Register (memory transfer):

mkglobal "count"
move $R1, "count"
inc $R1

The benefit of VM B is the opcodes are very close to or easily translatable to real live processors, because most processors don't allow operations on memory variables and require you to load the variable into a register or onto a stack. The JIT will have much less to do. With VM A, the add operation is really a fat, aggregate operation which has to be compiled into individual native ops.

For a simple comparison to the two approaches study Perl5 and study C#/.NET bytecode. While it is possible to compile Perl5 to a bytecode, it isn't the default form of it. Perl really does more symbolic interpretation of an in-memory AST. That is why it was a major architectural change when we wrote Parrot for Perl6, though I'm not convinced it was the right decision now for that language.


答:
To be a normal developer (by normal I mean someone who just takes requirement from senior developer/architect, and do according to instruction), you will not need deep knowledge in algorithm.
However to advance further in technical side, I believe (my opinion only) that understanding of various algorithms, data structures is necessary. You may not need to remember how to implement all the algorithms, but at least have ideas of what it is and it is used in what situation, so you can apply it (or look up it in internet) when necessary. E.g. when you optimize the code for faster execution, etc</p>


问:
Ship of Theseus applied to GPL - Can I relicense my program if I replace all of the derivative parts?
I translated a GPLv2 C program to Python, but found it was hard to extend as designed and rewrote significant portions of it. The program is now structurally completely different, but there are several verbatim translated functions in use.

The Ship of Theseus Paradox (as stated from Wikipedia) "raises the question of whether an object which has had all its components replaced remains fundamentally the same object."

If I did manage to write replacements for the verbatim functions, would I be able to relicense to a license I prefer?

Related, would I be able to pull the evolved architecture out and reuse it with a different license? I think it would be very useful on its own, but do not like the idea that it is now "tainted" with the GPL license.

Followup: I decided to contact the copyright holder and received permission to relicense.  Sometimes the best way is to interact socially rather than programmatically!

答:
Yes.

The other answers use far too much text explaining opinions on whether you should or not, but those opinions are not that relevant to the question.

The fact is that you will have a new work once you replaced the last parts, which admittedly was constructed by looking at a GPL'ed work. That's not a major concern in copyright law (patents would be another issue). Everything you distribute will be your creation.

There is plenty of material backing the theory that the copyright in a software program is the sum of partial copyrights. For instance, the MPL explicitly acknowledges this model. The Google/Oracle lawsuit got down to line-level copyrights.


问:
Is staying implementation agnostic really worth it?
I have a project that I'm working on currently using Tomcat, Spring 4, Spring Security, MySQL, and JPA w/ Hibernate.

I picked JPA from the standpoint that it's suppose to make swapping out the underlying implementation of ORM providers seamless, or at least less painful. I would say that this is  mentally using the spec over the implementation (JAX-RS) is the default standpoint of the Java development community.

I'm curious if this is really a task worth doing. I'm sure if I used Hibernate directly I would gain some power because I could use features that are not part of the main JPA specification.

Part of my concern comes from the idea of YAGNI. I'm essentially programming in a specific style and fashion (using JPA instead of Hibernate) so that at some point in the future I can swap out my ORM implementation. I severely doubt that will ever happen over the life of the product, so I'm essentially putting effort into something that I'll probably never reap the benefits of.

What are your thoughts? Is "programming to the interface" worth it when it comes to stuff like JPA? Have you ever actually swapped an entire ORM implementation in a product? Have you ever been able to completely avoid the abstraction from something like JPA leaking anyways? I personally have a single native SQL call already (to clean out the database tables), and there's somethings I'd like to futz with that are built into the JPA spec (get/set prefixes to your methods, and the difference between MEMBER OF/IN, which only binding myself to an underlying implementation will get me any chance of avoiding.

答:
so that at some point in the future I can swap out my ORM
  implementation. I severely doubt that will ever happen over the life
  of the product, so I'm essentially putting effort into something that
  I'll probably never reap the benefits of

In my experience, the typical enterprise project never swaps out:

Database

ORM

Language

I don't know the numbers, but the percentage of 2-tier apps I've seen implement and then change one of those things would probably be less than 10%. If it happens, it is rare, and it usually happens within the first 2-3 months of the project when people are still in discovery mode. Most systems I know are still running on their original platforms 8-10 years later.

More often than swapping out an ORM, do you want to know what I've seen more of? Removing the ORM completely to drop down to SQL due to performance issues. So no matter what, in that case, your gonna be rewriting stuff.

As far as implementation agnostic, its a myth. It really amounts to dumbing down. So my approach is to embrace the data layer. Make it a first class part of your language and design. It makes for happier, more successful projects.


答:
From my experience: no, it is not worth it in case of JPA/Hibernate.

Is "programming to the interface" worth it when it comes to stuff like JPA?

It is, but has nothing to do with JPA specifically. You can do "programming to the interfaces" of the Hibernate. This is not about hiding a framework under a standard, it is about SOLID.

Have you ever actually swapped an entire ORM implementation in a product?

Yes and no. One of our company's products partially migrated from Hibernate to jOOQ (which has nothing to do with JPA). It wasn't exactly a "typical enterprise project" which @codenheim mentioned, so swapping was possible.

I see no point of swapping Hibernate with another JPA-compliant ORM.

Have you ever been able to completely avoid the abstraction from something like JPA leaking anyways?

No. It's impossible because both JPA and Hibernate are very complex. And you have to deal with Hibernate's performance issues and design flaws anyway.

Title: Is staying implementation agnostic really worth it?

Body:
I have a project that I'm working on currently using Tomcat, Spring 4, Spring Security, MySQL, and JPA w/ Hibernate.

I picked JPA from the standpoint that it's suppose to make swapping out the underlying implementation of ORM providers seamless, or at least less painful. I would say that this is  mentally using the spec over the implementation (JAX-RS) is the default standpoint of the Java development community.

I'm curious if this is really a task worth doing. I'm sure if I used Hibernate directly I would gain some power because I could use features that are not part of the main JPA specification.

Part of my concern comes from the idea of YAGNI. I'm essentially programming in a specific style and fashion (using JPA instead of Hibernate) so that at some point in the future I can swap out my ORM implementation. I severely doubt that will ever happen over the life of the product, so I'm essentially putting effort into something that I'll probably never reap the benefits of.

What are your thoughts? Is "programming to the interface" worth it when it comes to stuff like JPA? Have you ever actually swapped an entire ORM implementation in a product? Have you ever been able to completely avoid the abstraction from something like JPA leaking anyways? I personally have a single native SQL call already (to clean out the database tables), and there's somethings I'd like to futz with that are built into the JPA spec (get/set prefixes to your methods, and the difference between MEMBER OF/IN, which only binding myself to an underlying implementation will get me any chance of avoiding.


答:
There is a third type of virtual machine which you may want to investigate. This type uses an execution model called Static Single Assignment, which does away with registers and stack in favor of a more abstract notion of a result that is calculated once and then used one or more times, but the bytecode says nothing about how it is stored.

The best known implementation of this idea is LLVM,  so you may want to look at how they did it.

Title: Why does a bytecode VM use stack or registers opposed to direct operations?

Body: I'm working on a simple bytecode interpreter to learn how virtual machines work. I've read about VMs and it seems that all of them are either stack based or register based. At the time it made sense, but then I started working on my interpreter and realized what am I doing? (I decided on a register machine.) I'm just loading all these values from pointers into these fake registers, doing operations, then putting the result back into the register and copying to a pointer. I thought, why not just do this directly? Why create fake registers that just serve as an overhead. Maybe I don't know enough about VMs yet to fully understand, but it would seem to me like my way would be much faster.</p>


问:
Three-Phase Commit (3PC) question
I've been reading about 3PC in a text book, but there aren't any diagrams or examples, so I found one on wikipedia that I posted below. My question is, what does it mean by "cohorts?" There is no mention of cohorts in the textbook and I don't see anywhere in the wiki page explaining what it is. Is it simply another word for participants?  Thanks for any help.

Here's the wiki page: http://en.wikipedia.org/wiki/Three-phase_commit_protocol

答: The cohorts in this case is the everyone who is not the coordinator. If you had 2 processes (a) and (b) then one would be the cohort and the other the coordinator, if you had (a), (b), and (c) then (c) might be coordinator with (a) and (b) as cohorts.</p>

Title: Three-Phase Commit (3PC) question


问:
Decide the type of an object during runtime
I try to implement a PriorityQueue with C#:

```<code>public class PriorityQueue<T> : Heap<T> where T : IComparable<T> {
    ...
}
</code>```

The Heap is abstract. I have MinHeap and MaxHeap that are derived from Heap.

```<code>public abstract class Heap<T> where T : IComp ...
public class MinHeap<T> : Heap<T> ...
public class MaxHeap<T> : Heap<T> ...
</code>```

Is there a possibility to decide in the constructor of PriorityQueue during runtime, if the PrioQueue becomes a MinHeap or MaxHeap?
Like:

```<code>public PriorityQueue(bool type) {
    if (type = smallestFirst) { this = MinHeap ... }
    else { this = MaxHeap ... }
}
</code>```

If I try like this, then he says that "this" is writeprotected.
Any other ideas?

答: An alternative to Euphoric's suggestion is to use a Factory Method rather than calling new PriorityQueue directly, which is to say have a static method in PriorityQueue that decides which subtype to create and then returns an instance of the appropriate type.</p>


答:
is it worth it?

That would entirely depend on the application.

If you're writing an internal application for a single company, forget it. That database will outlive the application by years, possibly decades.

Unless of course you've been given to understand from the outset that the database is planned to be replaced by something else in the near future.

If you're writing it for sale to customers, who may have different database engines, AND the requirements are such that it's supposed to support multiple database engines, THEN it makes sense.

For most people writing Java applications then, it is largely irrelevant.


问:
Database Design for Inheritance
In my project I have an object Player (attr example: pl_id, pl_data1) that is one of these types:

Its GoalKeeper (attr example: gk_data1)

OR Defender (attr example: df_data1)

OR Forward (attr example: fw_data1)

In mapping this objects to database :

Option 1:
Make a Table Player with columns (pl_id,pl_data1,gk_data1,df_data1,fw_data1)

In this option we have one record for any player. So if an player is a goalkeeper, the column gk_data1 will be filled and other column (df_data1 and fw_data1) will be null.

Option 2:
make

Table Player with columns: (pl_id, pl_data1, type)

Table GoalKeeper
with columns: (pl_id, gk_data1)

Table Defender with columns:
(pl_id, df_data1)

Table Forward with columns: (pl_id,
fw_data1)

and pl_id in child tables (GoalKeeper,Defender and Forward) links to Player.pl_id. relation from child tables to parent is one to one and from parent to childs is one to one_or_zero.

questions:

which is better?

is there any other (and better) options?

and finally what is best practice in this situation?

答:
Best choice depends on the specifics of the situation.

Your two options resemble two techniques known as "Single Table Inheritance" and "Class Table Inheritance".  Click to view Martin Fowler's presentation of these concepts.

In SO, questions about inheritance and table design are grouped under two tags of the same name.  In SE.DBA, there is a single tag called Subtypes.

Title: Database Design for Inheritance


答:
You own the copyright for any code you write.  What the GPL mandates is: any code you contribute or release alongside GPL code, you must also release under a similar license.  However, the copyright is still yours.

So, if you release your software part-way through the re-write (so there's a mixture of your code and old code), then you have to release that part of your code as GPL, and this cannot be revoked.  However, the copyright holder is the one who decides on licensing terms, so you still have the right to essentially "dual-license" that part of the code, including combining it with other code you alone wrote and selling/relicensing, etc.

Caveats:

although the copyright on code you write is yours by default, it can be changed by another contract/agreement, e.g. a CLA that specifies copyright transfer, or a contract with an employer who owns all the work you do on "their time".

whether your re-write constitutes enough of a "derivative work" that you end up sharing the copyright with the original author is a matter of degree.  If you translate the code line-by-line into another language (as your question mentioned), then those parts might well count as derivative.  If you implement an API-compatible replacement without looking at the details, then that probably wouldn't.

(source: a "copyright and open-source" session organised by my company a few weeks ago)

Title: Ship of Theseus applied to GPL - Can I relicense my program if I replace all of the derivative parts?

Body:
I translated a GPLv2 C program to Python, but found it was hard to extend as designed and rewrote significant portions of it. The program is now structurally completely different, but there are several verbatim translated functions in use.

The Ship of Theseus Paradox (as stated from Wikipedia) "raises the question of whether an object which has had all its components replaced remains fundamentally the same object."

If I did manage to write replacements for the verbatim functions, would I be able to relicense to a license I prefer?

Related, would I be able to pull the evolved architecture out and reuse it with a different license? I think it would be very useful on its own, but do not like the idea that it is now "tainted" with the GPL license.

Followup: I decided to contact the copyright holder and received permission to relicense.  Sometimes the best way is to interact socially rather than programmatically!


问:
Are exceptions as control flow considered a serious antipattern? If so, Why?
Back in the late 90's I worked quite a bit with a code base that used exceptions as flow control. It implemented a finite state machine to drive telephony applications.  Lately I am reminded of those days because I've been doing MVC web apps.

They both have Controllers that decide where to go next and supply the data to the destination logic. User actions from the domain of an old-school telephone, like DTMF tones, became parameters to action methods, but instead of returning something like a ViewResult, they threw a StateTransitionException.

I think the main difference was that action methods were void functions.  I don't remember all the things I did with this fact but I've been hesitant to even go down the road of remembering much because since that job, like 15 years ago, I never saw this in production code at any other job. I assumed this was a sign that it was a so-called anti-pattern.

Is this the case, and if so, why?

答:
Using exceptions for control flow is generally considered an anti-pattern, but there are exceptions (no pun intended).

It has been said a thousand times, that exceptions are meant for exceptional conditions. A broken database connection is an exceptional condition. A user entering letters in an input field that should only allow numbers is not.

A bug in your software that causes a function to be called with illegal arguments, e.g. null where not allows, is an exceptional condition.

By using exceptions for something that is not exceptional, you are using inappropriate abstractions for the problem you are trying to solve.

But there can also be a performance penalty. Some languages have more or less efficient exception handling implementation, so if your language of choice does not have efficient exception handling, it can be very costly, performance-wise*.

But other languages, for example Ruby, have an exception-like syntax for control flow. Exceptional situations are handled by the raise/rescue operators. But you can use throw/catch for exception-like control flow constructs**.

So, although exceptions are generally not used for control flow, your language of choice may have other idioms.

* En example of a performance costly use of exceptions: I was once set to optimize a poorly performing ASP.NET Web Form application. It turned out, that the rendering of a large table was calling int.Parse() on approx. a thousand empty strings on an average page, resulting in approx. a thousand exceptions being handled. By replacing the code with int.TryParse() I shaved off one second! For every single page request!

** This can be very confusing for a programmer coming to Ruby from other languages, as both throw and catch are keywords associated with exceptions in many other languages.

ContentLicense: CC BY-SA 4.0


答:
Let's sketch such an Exception usage:

The algorithm searches recursively till something is found. So coming back from recursion one has to check the result for being found, and return then, otherwise continue. And that repeatedly coming back from some recursion depth.

Besides needing an extra boolean found (to be packed in a class, where otherwise maybe only an int would have been returned), and for the recursion depth the same postlude happens.

Such an unwinding of a call stack is just what an exception is for. So it seems to me a non-goto-like, more immediate and appropriate means of coding. Not needed, rare usage, maybe bad style, but to-the-point. Comparable with the Prolog cut operation.

Title: Are exceptions as control flow considered a serious antipattern? If so, Why?

Body:
Back in the late 90's I worked quite a bit with a code base that used exceptions as flow control. It implemented a finite state machine to drive telephony applications.  Lately I am reminded of those days because I've been doing MVC web apps.

They both have Controllers that decide where to go next and supply the data to the destination logic. User actions from the domain of an old-school telephone, like DTMF tones, became parameters to action methods, but instead of returning something like a ViewResult, they threw a StateTransitionException.

I think the main difference was that action methods were void functions.  I don't remember all the things I did with this fact but I've been hesitant to even go down the road of remembering much because since that job, like 15 years ago, I never saw this in production code at any other job. I assumed this was a sign that it was a so-called anti-pattern.

Is this the case, and if so, why?


问:
How to rotate an array of bits

I currently have a PIL Image object which I store as an array of bits (1's and 0's). However I now would like to be able to rotate that image 45 degrees. One way to do it is take the original PIL image, apply a transform matrix on it, then convert that to an array of bits. Problem with this approach is that it's computationally expensive, especially if I want to start doing more than just one rotation. It would be faster to just modify the array of bits directly.

I tried using numpy.roll:

```<code>numpy.roll(bits, 45) # rotate 45 degrees
</code>```

Unfortunately, this just does a circular shift, not an actual angular rotation.

What algorithm can I use on the array of bits to give me the desired output without having to go through the original image? Even though my application is in Python, your answer can be in whatever language you feel comfortable with, I'm more interested in the algorithm itself not the syntax :)

答: If you only want to limit rotation to 45 degrees, you don't need to use sin and cos, for that particular case I would advice you to use a fast isometric diamond drawing algorithm and adapt it to your matrix. Usually a couple nested loops and 4 variables (x, y, width, height) will do it.</p>

Title: How to rotate an array of bits


问:
Whose responsibility is it to create the interface and/or acceptance testing? Developer or QA?
I am a backend developer and always create tests for my applications.
Recently I study and apply the interface tests (using selenium), but I doubted whether I who should create these tests, developer or QA?

How can we decide if automated interface testing should be QA responsibility, or Developer responsibility, or both?

And if both, is there a risk of creating duplicate tests?

答:
This is fully up to the company or organization you are working in, so ask the persons who are responsible for defining the organizational structures. However, there are some rules of thumb which distribution of tasks will work better.

For example, if your QA department consists of people with no programming knowledge, it won't make sense to give them the task to write automated tests. If the "interface tests" you have in mind are not fully "black box" tests and need some knowledge about the internal workings of your program, it won't make much sense either.

If, however, your interface tests are black box tests, and your QA department has some programming knowledge, and they identify tedious, recurrent testing tasks, why shouldn't them automate these tasks by writing automated tests?

In some organizations the QA department focus specificially on hard-to-automate tests and don't need any programming knowledge. In such an organization, the automation of recurrent tests may be delegated back from the QA people to the devs.

Concerning the risk of creating duplicate tests: talking to each other will help! Clarify the responsibilities from time to time. And if a small amount of tests is done twice, that is much less of a problem as if necessary tests are not applied because each group thinks those tests are the responsibility of the other group.


答:
Acceptance tests should be written first, before the code is written. When they pass, you know the feature is complete and does what it is supposed to do. However, most of these tests only follow the happy path. Let's consider two scenarios:

Your QA department is able to handle writing their own automated tests.

In this case, you've saved them the trouble of writing happy path tests, so they can concentrate on edge cases, mutation testing, stress testing, exploratory testing, and regression testing. Also, they can remove your tests from their own test runs if they prefer to have their own acceptance testing. You've produced code that is less likely to be buggy, saved them time, and allowed them to focus on what they're good at... QA isn't about making sure the software does what it should do--you shouldn't ship code to them if there is any question of that--it's about making sure that the software doesn't do what it isn't supposed to do.

Your QA department is not able to handle writing their own automated tests.

In this case, you've written automated tests which they can't write, which is helpful. Perhaps they'll learn to read the automated tests and understand what you are testing, which will help them develop a test plan. You've also shipped software that you know works on the happy path, which means that the QA department has more time to focus on exploratory, regression, etc. Their job is to break your software, not verify that you're minimally competent.

In either case, following a behavior driven development plan saves time and money and produces more robust software.

Title: Whose responsibility is it to create the interface and/or acceptance testing? Developer or QA?

Body:
I am a backend developer and always create tests for my applications.
Recently I study and apply the interface tests (using selenium), but I doubted whether I who should create these tests, developer or QA?

How can we decide if automated interface testing should be QA responsibility, or Developer responsibility, or both?

And if both, is there a risk of creating duplicate tests?


问:
How to describe styles and approaches of C++ programming?
How can I say more than just "C++" on my resume, reports or other writings, to convey clearly what kind of C++ programming I've been doing?

Are there well-defined styles of C++? ("Styles" might not be quite the right word.)  Examples:  using C++ as an "improved C" taking advantage of stronger typechecking, syntactic niceties, but little or lightweight use of classes;  using heavy OO techniques where almost everything is made into a class (and there could be different styles of that) - but staying away from templates and advanced techniques;  and heavy use of metaprogramming and every cutting edge advanced C++ feature.    I've seen code where there's such heavy use of computer science terminology and advanced features only a CS PhD would be able to understand it,  and code so clean and straightforward that EEs and physicists with modest programming skills can understand it.

This isn't about literally coding styles - fussy details about brackets, indentation, commenting and all that - but one's philosophy of what good code is, the approach to organizing it all, and degree of fanaticism or reluctance to use various major techniques, procedural vs OO vs functional and so forth.

Can such variations be categorized in a meaningful way?   How to name these for someone not expert at software development, with an amount of knowledge to be expected of a good executive or recruiter (never mind the PHBs)?

Ideally, there'd be a way anyone can say on their resume "C++ in blah-blah style" or "mumbleific C++" and land jobs or freelance projects in that category/style of C++.  An improved-C++ coder could avoid projects full of heavy template-bloated code.

(To some extent this question may be more general than C++, but C++ being around for years and being multi-paradigm, leads to the most confusion.)

答:
I'd say that the domain might be more important than the coding style. The style is largely subject to convention in the target company anyway (by convention, I mean the lead architects perception of best practice ;)).

So something like "C++ back-end development in a distributed high volume accounting system for a large bank" would already convey a lot of information. You can also include specific libraries, like Qt. But I don't know if something like "strictly object oriented" or the like is actually helpful.

And don't forget the most important rule in software development: Don't be a fanatic, narrowminded twat when it comes to a certain technology/approach. I mean, as a profession, we have been fighting for years now, not to be reduced to the usual alphabet soup recruiters always use. Why limit yourself even more?

ContentLicense: CC BY-SA 2.5


答:
None of the above

GoalKeeper, Defender, and Forward are roles, not subclasses/types of Player. A Player may be a Defender in one game, and a GoalKeeper in another.

Typically one would have a role-map table to assign players to roles. It is difficult to say precisely what to do without more details, particularly the behavioral and data difference between the roles vs the Player class.

Title: Database Design for Inheritance

Body:
In my project I have an object Player (attr example: pl_id, pl_data1) that is one of these types:

Its GoalKeeper (attr example: gk_data1)

OR Defender (attr example: df_data1)

OR Forward (attr example: fw_data1)

In mapping this objects to database :

Option 1:
Make a Table Player with columns (pl_id,pl_data1,gk_data1,df_data1,fw_data1)

In this option we have one record for any player. So if an player is a goalkeeper, the column gk_data1 will be filled and other column (df_data1 and fw_data1) will be null.

Option 2:
make

Table Player with columns: (pl_id, pl_data1, type)

Table GoalKeeper
with columns: (pl_id, gk_data1)

Table Defender with columns:
(pl_id, df_data1)

Table Forward with columns: (pl_id,
fw_data1)

and pl_id in child tables (GoalKeeper,Defender and Forward) links to Player.pl_id. relation from child tables to parent is one to one and from parent to childs is one to one_or_zero.

questions:

which is better?

is there any other (and better) options?

and finally what is best practice in this situation?


问:
Practices for organizing JavaScript AMD imports
Our company has been using newer versions of the Dojo framework, which have progressed to an AMD-based loader format. I'm currently trying to find logical ways to separate layer files, taking a module and all its dependencies, and wrapping them all into single minified files. My goals are generally as follows:

Minimize the number of separate requests made per-page

When possible, make use of cache so that large modules that have already been used are re-retrieved.

Our app consists of many hundreds of pages and dialogs, much of which have their own custom logic and related scripts.

I'm starting to run into more and more complex issues in terms of finding the right way to construct layer files for the best performance. Just recently, I ran into the following type of scenario:

A depends on B, depends on C, depends on D ...etc... depends on Z.

A1 depends on D (which depends on ... Z)

A2 depends on L (which depends on ... Z)

The scenario is mostly just an example - I don't have 24 dependencies in a straight tree. But under our previous method of simply declaring all objects globally under a namespace, this would be a simple matter of minifying everything to one layer file that's included on relevant pages. As it stands now, I'm not sure what I'd gain by making D its own layer, or A, or L. Just to avoid loading the same code twice, we'd be separating it into about 3 or 4 requests. One troublesome fact is the way that the page's script will always immediately put out new script requests for anything in its "require()" block that it hasn't cached just yet. Moreover, it's become very complicated just to comprehend and discuss.

I wanted to know how other people tend to approach this problem, hopefully in a simpler way; the previous version of our product had some significant javascript loading-time issues, so this certainly isn't premature optimization (it could be "past-mature"). We are starting to switch our pages to using asynchronously-loaded script tags now that most of our scripts support it, in case that's any help.

答:
This is not really an answer, it is just a longer comment

For inspiration I'd suggest you to look at (1) the https://github.com/componentjs/component project which aimed to simplify management of dependencies between JavaScript packages (and their packaging and minification). Since being born 2 years ago it somehow settled down and can offer some solution.

Another module management best practices I'd suggest you to look at (2) are those used and recommended for use together with TypeScript. Some discussion of pros/cons of using internal/external modules is available in https://typescript.codeplex.com/discussions/507413

Compile-time creation of 1 minified script per page gets my vote, lazy loading big scripts on-demand possible but rather an exception to the rule.

This is how I tend to approach the problem

Some interesting further reading:

Erich Gamma's build 2014 presentation Microsoft: Surviving Application Scale JavaScript - TypeScript in the Trenches has few chapters devoted to code organization

(Yakov Fain, Victor Rasputnis, Viktor Gamov, and Anatole Tartakovsky)'s online book "Enterprise Web Development. From Desktop to Mobile" discusses module organization in Chapter 6 - Modularizing Large-Scale JavaScript Projects

Axel Rauschmayer in ECMAScript 6 modules: the final syntax shows how modules are supposed to be used in the upcoming JavaScript #6 (highlights: static module structure, support for cyclic dependencies)

Addy Osmani in Scalable JavaScript Design Patterns talks about modules, design patterns and large-scale JavaScript application architecture


问:
An example of a beginner-level Algorithm, intermediate level Algorithm and a complex/expert level Algorithm?
I'd like to get a sense for the range of complexity that algorithms fall into. I think it would be interesting and helpful for those, like me, trying to better understand how algorithms are formulated and how to deconstruct them.

Can you offer a basic algorithm with explanation, an intermediate algorithm with explanation, and maybe an expert level one (with or without) an explanation?

答:
Beginner

Binary Search: Locates the position of an item in a sorted array.

AVL Tree Insertion: Insert an item in a AVL tree maintaining the subtree balancing property.

Depth-first Search, Breadth-first Search: Walk over the nodes of a Graph in DFS or BFS order.

Intermediate

Dijkstra's Algorithm: Graph search algorithm that solves the single-source shortest path problem for a graph with nonnegative edge path costs, producing a shortest path tree.

Longest Common Subsequence: Find the longest subsequence common to all sequences in a set of sequences (often just two).

Convex Hull (Graham Scan): Given a set of points, find the minimum subset of those points to cover with a convex polygon.

Counting Sort: Sorting algorithm of consecutive integers in O(n).

Advanced

Range Minimu Query: Given an array A[1,n] of n ordered objects (such as numbers), a Range Minimum Query (or RMQ) from i to j asks for the position of a minimum element in the sub-array A[i,j]. RMQs can be used to solve the lowest common ancestor problem.


问:
What is the purpose of creating a member function with the same type as its class?
I'm sure I'll botch some of the specific terminology, but what is the difference between object and object2 in this implementation? Is the only purpose of the first method (prototyping the class's function by the same name of the class) just to save typing? At the end of the code, does object==object2?

```<code>//first method
class Class1{
public:
        int i;
        Class1 (parameter);
};
Class1::Class1 (parameter){
        i = 10;
}
Class1 object1(parameter);

//second method
class Class2{
public:
        int i;
        void function (parameter);
};
Class2::function (parameter){
        i = 10;
}
Class2 object2;
object2.function(parameter);
</code>```

(C++11)

答:
I believe I've found the answer at cplusplus.com

It looks like I was correct, but that I should also keep in mind that the 'constructor' is only called at creation of the object and can never be called again per that object, whereas a function within the class can be called repeatedly.


问:
How to move away from hardcoded paths in our build processes
We have a set of Java tools that are built and run locally. Whenever one of the devs commits a change, everyone else (including non-developers) need to do an update and build the tools.

Everyone uses windows machines so whoever designed the build processes decided to place everything in a folder called C:\build and dump all of the class files in the appropriate folders. For example, the folder might look something like

```<code>C:\build\firstTool\
C:\build\secondTool\
C:\build\settings.ini
</code>```

We also have a huge library folder where all the jars go, and it's placed here

```<code>C:\lib\
</code>```

As a result, many classes are simply assuming this is where the files are going to be stored and have hardcoded paths everywhere.

What can I do to clean things up? I don't want users to have to build tools, nor do I want them to have to update any checked out repos on their end.

Personally, I think developers should be the ones maintaining releases.

答:
Relative Paths

You could define some environment variables in windows. For linux users, this should feel familiar.

```<code>C:\> SET VARIABLE_NAME="path\to\dir"
</code>```

sets the environment variable VARIABLE_NAME to that path. Windows will then replace %VARIABLE_NAME% with whatever you put in the quotes, whether it's valid or not. (If it's not, it'll throw an error.) For example, you could list the contents of the path using dir as follows:

```<code>C:\> dir %VARIABLE_NAME%
</code>```

You could create a .bat file that will set these environment variables and then call the appropriate build script. Environment variables are only valid for the life of the script calling them.

But that's really not what you should be doing. You should be using a build tool.

Build Tools

Build tools are going to allow you to have a lot more control over your builds, managing dependencies and project lifecycles. You should consider moving to one to try and ease some of the build related pains you're feeling now. Currently there are 3 big names in the build community. I've included links to the project pages, with a brief description below.

Maven

Apache Maven is a software project management and comprehension tool. Based on the concept of a project object model (POM), Maven can manage a project's build, reporting and documentation from a central piece of information

Ant

Apache Ant is a Java library and command-line tool whose mission is to drive processes described in build files as targets and extension points dependent upon each other. The main known usage of Ant is the build of Java applications. Ant supplies a number of built-in tasks allowing to compile, assemble, test and run Java applications. Ant can also be used effectively to build non Java applications, for instance C or C++ applications. More generally, Ant can be used to pilot any type of process which can be described in terms of targets and tasks.

Gradle

Gradle is build automation evolved. Gradle can automate the building, testing, publishing, deployment and more of software packages or other types of projects such as generated static websites, generated documentation or indeed anything else.

Body:
Relative Paths

You could define some environment variables in windows. For linux users, this should feel familiar.

C:\> SET VARIABLE_NAME="path\to\dir"

sets the environment variable VARIABLE_NAME to that path. Windows will then replace %VARIABLE_NAME% with whatever you put in the quotes, whether it's valid or not. (If it's not, it'll throw an error.) For example, you could list the contents of the path using dir as follows:

C:\> dir %VARIABLE_NAME%

You could create a .bat file that will set these environment variables and then call the appropriate build script. Environment variables are only valid for the life of the script calling them.

But that's really not what you should be doing. You should be using a build tool.

Build Tools

Build tools are going to allow you to have a lot more control over your builds, managing dependencies and project lifecycles. You should consider moving to one to try and ease some of the build related pains you're feeling now. Currently there are 3 big names in the build community. I've included links to the project pages, with a brief description below.

Maven

Apache Maven is a software project management and comprehension tool. Based on the concept of a project object model (POM), Maven can manage a project's build, reporting and documentation from a central piece of information

Ant

Apache Ant is a Java library and command-line tool whose mission is to drive processes described in build files as targets and extension points dependent upon each other. The main known usage of Ant is the build of Java applications. Ant supplies a number of built-in tasks allowing to compile, assemble, test and run Java applications. Ant can also be used effectively to build non Java applications, for instance C or C++ applications. More generally, Ant can be used to pilot any type of process which can be described in terms of targets and tasks.

Gradle

Gradle is build automation evolved. Gradle can automate the building, testing, publishing, deployment and more of software packages or other types of projects such as generated static websites, generated documentation or indeed anything else.


问:
Which design pattern for a single class accessing an object representing a data structure?
Which design pattern should I use when I have a class representing a data structure (aka C-style struct) and I wish to have only a single class to be able to access it.

I was thinking of simply declaring the class that represents a data structure as an inner class but wanted to know if there is a better way to design this.

eg:

```<code>class XXManager{
getXX();
setXXAtrtribute();
}

class XX{
  String name;
  String email;
  String job;
}
</code>```

Here I want to design a class XXManager which will handle the creation and managment of 'XX' objects and no one should be able to access XX other than through the XXManager.

答:
Making XX an inner class, or a base class of XXManager will both work.  If you want to use it as a base class you could mark it abstract to prevent direct instantiation.

You could also combine the two classes--if you really must insist that they work with an XXManager and they do not work with XX then removing XX might be the simplest solution.

In all cases it feels a bit strange and raises the question of "why"?  Perhaps it would be best to leave the classes independent and accessible and to rely on training or understanding enforce the standard.


问:
BloomFilter in ruby should have k hash functions
I am reading the Bloom Filter implementation written in ruby. It should have k hash functions, but it looks like the same hash function is being used with different seed values. Is this a common way to implement this Data Structure, or is this just an exercise in this case?

https://github.com/igrigorik/bloomfilter-rb/blob/master/examples/pure-ruby-bf.rb

```<code>def make_mask(key)
    @__mask.clear
    0.upto(@num_hashes.to_i - 1) do |i|
      hash = Zlib.crc32(key, i + @seed)
      @__mask.set(hash % @size, 1)
    end
    return @__mask
  end
</code>```

答:
Yes, literature indicates that it is ok, and common, to reuse a hash function to produce k hash functions, specifically if the hash function takes a seed value. This is apparently the case in the Ruby sample you provided. For large k, finding unique hash functions can be challenging. Of course, this supposes a good hash function, in the first place.

Not only can a hash function be reused, but a single hash value can be sliced into separate bit fields. This helps runtime efficiency in that it reduces the number of actual hash calls to be made, and since we know that k dominates the performance of the algorithm, this might be a valuable optimization. For a good hash function, the bit regions of a single hash value should be independent hash keys in their own right. In other words, I can call hash(i) to produce a 64-bit result, then slice that into 4 x 16-bit sub-keys which can produce a k of 4. Much more efficient than iterating through 4 hash calls. When you consider we usually mod the hash value by a small bucket size anyway, we are often not using the full potential of a hash key for a hash table, and Bloom filters give us a better way to do that.


问:
What should be in a PIMPL?
I am kinda trying to implement a windowing library in C++, the circumstances are forcing me to implement it all myself, that's not the point of this question however.

My question is: What should be in a PIMPL class? What attributes, to be more accurate.
For instance, as I stated yet, I am implementing an windowing library and I have 2 kind attributes:

These, which describe the window (int Width, char* pTitle ect. )

And those, which are needed by the operating system(HWND, HDC, HGLRC for windows or XEvent, Display, Window for Linux/X11).

My current approach is, that the implementation holds all attributes, the class above, that has the PIMPL, calls getter and setter methods of the implementation in order to retrieve its attributes.

What's the right approach? Put them all in one (PIMPL-) class or split them up?

答:
The purpose of the PIMPL idiom is to provide a more low-level separation between the interface and the implementation* so that you can alter the implementation without affecting the interface.  In particular, this means the library can retain binary compatibility, allowing users to link to a new version of the library without recompiling their executables.

What goes into the PIMPL class depends entirely on what you think is likely to change or not (and also whether binary compatibility matters to you at all).

If you have a member variable that is extremely essential to the class and can never change without a major redesign of the library then you should just leave it in the header to save yourself from the additional complexity (and minor performance cost).

On the other hand, if you want to maximize flexibility and compatibility you should hide as much as you can in the PIMPL class.

Title: What should be in a PIMPL?


问:
Version hash to solve Event Sourcing problems
The basic examples I have seen about Event Sourcing do not deal with out of order events, clock offsets in different systems and late events from system partitions.

I am wondering if more polished Event Sourcing implementations rely on a version stamp of modified objects?

For example, assuming that the system is rendering the entity Client with version id ABCD1234. If the user modifies the entity, the system will create an event with the modified fields AND the version id reference to which version it applies. Later the event responder would detect out of order events and merge them.

答:
I did something similar to an event sourcing system only recently. The domain needs to replay events in the correct order, but the domain model must not write an event to the store if another instance of the domain has just done so. I went with an optimistic concurrency approach. So the domain will retry its command and, if it is still valid, a new event will be created with the version incremented.

You mentioned the event responder detecting out of order events and I think that is perfectly fine. But my event responders actually do not care much for events out of order. I try to keep my data schemas designed to support append only data and if two users "modify" the same piece of data I just accept it and move on. If it's very important I break away from event sourcing.

I'm still trying to find the right balance between event sourcing and traditional operations.


问:
What's the difference between robustness and fault-tolerance?
Systems / programs / distributed algorithms / ... are often described with the predicate robust or fault-tolerant.

What is the difference?

Details:

When I google for +robust +"fault-tolerant", I only get two hits, both unhelpful.

When I googlescholar for the terms, I find a lot of papers that have both terms in their title. Unfortunately, they do not precisely define the terms :( But since they use both terms, it seems that neither implies the other.

答:
I really like @johnnyb's answer and endorse it for its crisp definitions. But having worked in the field for a few decades, I recognize another (much less formal and precise) way that these terms are frequently used:

As informal points along a continuum from "unreliable" to "perfectly reliable."

There is no system, application, or service that can guarantee it will always and forever be at work ("continuously available" or "permanently available"). "Fault tolerant" has long been a stand-in for "we've done everything humanly possible with current technology to make sure this thing keeps running properly."

Words like "robust," "hardened," and "highly available" are used as softer milestones toward that goal of continuous operation. They reflect increasing levels of effort, investment, and confidence.

Because these terms are informally used, there is no entirely canonical ordering. "Highly available" is usually a strong claim, just under "fault resilient" or "fault tolerant." But is "hardened" better than "robust"? Or vice versa? It depends on the context. These are also frequently used as product marketing claims, with all the boasting and intentional imprecision that entails.

Usually organizations working toward these goals have their own internally agreed-upon progression, usually at least roughly linked to project goals/deliverables and external metrics such as "three nines" or "six nines."

@johnnyb also touches on a critical distinction: The difference between platform up/down status (availability) on one hand, and algorithm, application, or service attributes on the other.

I say "attributes" because there are many: performance, correctness, and imperturbability are just a few key ones. Is a system meaningfully available and correct if it's operating at just 10% of rated performance? Not according to business owners if it's the busy season! There's no great virtue in a system that truly never goes down, yet that also gives incorrect answers much of the time. Finally, is a data analytics system running "right" if a 0.2% variation in input gives a 3,400% different answer? Perhaps...but it's going to seem a rather capricious and unsatisfying model to many. I won't go through the extended list of attributes, but data integrity, data safety, data privacy, and other issues of correctness and security are common concerns. (If you're a very large organization or government agency, you increasingly worry about preserving those attributes not just over a few years or product cycles, but over spans of decades or possibly even centuries. There are as yet no proven architectures, processes, or approaches to accomplish this.)

These possible variances between "up and running" and "doing what we want"--and how to specify, measure, and prevent such variances--have long been a challenge, even once the redundancy, hardening, and other steps toward fault-tolerance have been taken. And in informal usage, "running" and various forms of "running like I want it to" are conflated, without all the clear distinctions one would want.


问:
Storing Form Data in a class
I have a form that writes to a database. Other than creating a class handle an external API, this project is done.

However, the processing script is your standard procedural calling of queries using a Database class. Is there any benefit to creating a class to model the data for the processing?

答:
It depends.  Generally speaking enterprise apps are tiered, so if you expect the app to grow, or others in your organization will be working on this app, there's a good chance that you need to introduce at least one tier.  Typically you have a data access tier, which is an API (a set of related classes that share a package) that wraps all your SQL code and has methods along the lines of "create()", "update()", "delete()" and "read()".  Then, there's typically a tier that manages the relationship between your form and this data access tier (a "controller") that has the job of pulling the data out of your form, invoking the data access tier as necessary, and then giving control to some other view (screen, whatever).  Often there's another tier (business rules) that has the job of enforcing rules about what can be done to the data tier, and in which case the controller often delegates much of its behavior to that tier (with the exception of choosing the next view to display).

These are general guidelines, and there are many variants on this approach.  The idea is that each of these areas of focus have a distinct purpose that will grow/change with time, and should therefore be separated from one another.

Title: Storing Form Data in a class


答:
Class1 and Class2 should be something like:

```<code>class Class1 {
public:
  int i;
  Class1(int parameter) : i(parameter) {}  // This is a constructor
};

class Class2 {
public:
  int i;
  void function(int parameter) {i = parameter;} // This is a init function
};
</code>```

and

```<code>Class1 object1(10);
Class2 object2;
object2.function(10);
</code>```

The value of i will be the same: object1.i == object2.i but the purpose of the constructor is NOT to save typing.

as Joel said in a comment , with the constructor it's mandatory to assign a value to i, while with the init function you could use i without a previous explicit assignment.

In properly designed OO-code the constructor is responsible for establishing the class invariants (here i should be a private data member). Without a constructor each use of the class must first ensure that the object has been properly built.

You cannot re-initialize an object of a class using its constructor (*) but you can use operator=.

const objects can be created only via constructor:

```<code>const Class1 object1(10);
</code>```

you cannot write:

```<code>const Class2 object;   // error (uninitialized const object)
object2.function(10);  // error (attempt to change the const object)
</code>```

constructor is always more or equally efficient as having code outside

many other reasons (see references).

Technicalities

it's possible to re-initialize an object of a class using its constructor via placement new. Of course it's ugly beyond description.

there are reasons to prefer init functions.  Init functions are able to call virtual functions on the object. This doesn't always work in a constructor, because in the constructor of the base class, the derived class part of the object "doesn't exist yet", and in particular you can't access virtual functions defined in the derived class. Instead, the base class version of the function is called, if defined (see also Why use an initialization method instead of a constructor?).

References

C++ - Constructor or Initialize Method to Startup

Arguments against “initialize()” method instead of constructors

Title: What is the purpose of creating a member function with the same type as its class?

Body:
I'm sure I'll botch some of the specific terminology, but what is the difference between object and object2 in this implementation? Is the only purpose of the first method (prototyping the class's function by the same name of the class) just to save typing? At the end of the code, does object==object2?

```<code>//first method
class Class1{
public:
        int i;
        Class1 (parameter);
};
Class1::Class1 (parameter){
        i = 10;
}
Class1 object1(parameter);

//second method
class Class2{
public:
        int i;
        void function (parameter);
};
Class2::function (parameter){
        i = 10;
}
Class2 object2;
object2.function(parameter);
</code>```

(C++11)

Body:
Class1 and Class2 should be something like:

class Class1 {
public:
  int i;
  Class1(int parameter) : i(parameter) {}  // This is a constructor
};

class Class2 {
public:
  int i;
  void function(int parameter) {i = parameter;} // This is a init function
};

and

Class1 object1(10);
Class2 object2;
object2.function(10);

The value of i will be the same: object1.i == object2.i but the purpose of the constructor is NOT to save typing.

as Joel said in a comment , with the constructor it's mandatory to assign a value to i, while with the init function you could use i without a previous explicit assignment.

In properly designed OO-code the constructor is responsible for establishing the class invariants (here i should be a private data member). Without a constructor each use of the class must first ensure that the object has been properly built.

You cannot re-initialize an object of a class using its constructor (*) but you can use operator=.

const objects can be created only via constructor:

const Class1 object1(10);

you cannot write:

const Class2 object;   // error (uninitialized const object)
object2.function(10);  // error (attempt to change the const object)

constructor is always more or equally efficient as having code outside

many other reasons (see references).

Technicalities

it's possible to re-initialize an object of a class using its constructor via placement new. Of course it's ugly beyond description.

there are reasons to prefer init functions.  Init functions are able to call virtual functions on the object. This doesn't always work in a constructor, because in the constructor of the base class, the derived class part of the object "doesn't exist yet", and in particular you can't access virtual functions defined in the derived class. Instead, the base class version of the function is called, if defined (see also Why use an initialization method instead of a constructor?).

References

C++ - Constructor or Initialize Method to Startup

Arguments against “initialize()” method instead of constructors


问:
What to do if a feature is not supported natively on a platform?
If a feature is not supported on a platform natively what would a programmer do? For example, when building an iphone app, if you are trying to slide a picture(just as an example- I know you can slide a picture) and it's not supported natively. What would a programmer do? Same thing with a programming language. If something is not supported natively in a java for example what would a programmer do to overcome that? I tried googling it, but I guess either I am not using the right words. Again, this is not an implementation issue. I am not building an application where I ran into this problem. I am just trying to understand the theory behind this. </p>

答:
You have options:

Use a preexisting polyfill. A lot of the JavaScript libraries like jQuery, for example, have historically covered over weak parts in this browser or that browser's JavaScript or DOM capabilities. So, they resemble the putty-like product in the UK that fills a hole or gap in a wall. Frameworks are frequent homes to polyfills.

Build your own shim. A shim is like a polyfill, in that it adjusts what you have to what you want.  It comes from pieces of wood (or other solid material) used to level uneven floors, or fill in gaps. Code the feature yourself, using whatever tools, APIs, or capabilities you find lying about. Sometimes this is feasible, sometimes it is not (based on how hard it is to write, or whether the platform primitives come close to supporting what you want to do).

Go without. There are many cases where building a feature yourself is not feasible, and there are no easy, ready, or affordable alternatives. In which case you make do without, and declare that kind of feature or activity not available on that platform. In some cases, you can design around the gap, in others it's tough luck--just not available on this platform. Web sites that use Adobe Flash long faced this problem on Apple iOS devices. There is no official support for Flash, and Apple worked hard to make sure that there was none, and no easy/good workarounds besides.


问:
How to pick a platform for a new application
What should be taken into account when choosing between desktop and web as a platform for a new application?

There are definitely a lot of arguments for both platforms but what are the most important to consider?

For example:

I think that it is easier to develop a desktop application;

On the other hand it is much easier to distribute an online web application;

Cloud apps are much more popular nowadays;

If the application should interact with physical devices it would be impossible to make it as a web-app

Etc. Sorry for a possible opinion-based question

答:
In general, desktop applications (and some browser applications using executable plugins):

Are intended to run on the corporate intranet

Have better access to the local computer

Are platform-specific

Are highly-interactive, but sometimes not

Can be highly computationally-intensive on the client

May require installation

Are more proprietary

In general, browser applications

Can be run on the intranet or internet

Have limited to little access to the local computer

Are platform agnostic

Can be very interactive, but sometimes not

May be highly computationally-intensive on the client

Seldom require installation, but may require a modern browser

Are less proprietary

As you can see, there aren't that many substantial differences nowadays, but some of them can be stark.  For example, if you can write your app in HTML5 and CSS3, you won't have to write an app for each native platform (i.e. iOS, Android).


问:
Where to load data for things like a sidebar in MVC frameworks?
This seems extremely basic, but I've read a lot of related questions and haven't found a proper answer.

Using Ruby on Rails or other similar MVC framework, how am I supposed to load data that is displayed in sidebars on multiple pages?

Options I know of, with the problems I see:

Load it in every controller method that needs it: causes duplication of code;

Load it in a method on the ApplicationController, which is executed by all controllers: would cause data to be loaded even when not needed;

Load it directly from the model in the view: not MVC?

I've asked this elsewhere and some people told me to "look into [insert another pattern here]" or "use Ajax calls to get the data". Although those might also work, I'm looking for an answer regarding MVC frameworks on the server.

答:
You may be having trouble if you are thinking of all MVC as a 1 to 1 relationship of View to Controller and a View per Page. A view is not necessarily a page and a page is not necessarily a single view. Commonly they are 1 to 1, but often there is more to it. You might have pages made up of a handful of views, though there will usually be one master view that correlates to the current controller.

Rather than make it part of multiple controllers, you can dedicate a new controller to the sidebar and call it SideBarController. It has its own view.

In ASP.NET MVC land, I'd call it a partial view. Basically a fragment of markup that is included in a master page or set of pages. A master page is often a template page with header, footer, left nav, and main content. In RoR land, I think its done using explicit render

Example, my ProductsController returns a view, the Products index page renders, and inside that template page there is a markup tag that calls SideBar.

Not touched Rails in years, but I think:

```<code>render template: "sidebar/show"
</code>```

Or simply:

```<code>render "sidebar/show"
</code>```

Is enough since it Rails knows its a different controller with the embedded slash.

http://guides.rubyonrails.org/layouts_and_rendering.html

Body:
You may be having trouble if you are thinking of all MVC as a 1 to 1 relationship of View to Controller and a View per Page. A view is not necessarily a page and a page is not necessarily a single view. Commonly they are 1 to 1, but often there is more to it. You might have pages made up of a handful of views, though there will usually be one master view that correlates to the current controller.

Rather than make it part of multiple controllers, you can dedicate a new controller to the sidebar and call it SideBarController. It has its own view.

In ASP.NET MVC land, I'd call it a partial view. Basically a fragment of markup that is included in a master page or set of pages. A master page is often a template page with header, footer, left nav, and main content. In RoR land, I think its done using explicit render

Example, my ProductsController returns a view, the Products index page renders, and inside that template page there is a markup tag that calls SideBar.

Not touched Rails in years, but I think:

render template: "sidebar/show"

Or simply:

render "sidebar/show"

Is enough since it Rails knows its a different controller with the embedded slash.

http://guides.rubyonrails.org/layouts_and_rendering.html