答:
“Binding” refers to the act of resolving a method name to a piece of invocable code. Usually, the function call can be resolved at compile time or at link time. An example of a language using static binding is C:

int foo(int x);

int main(int, char**) {
  printf("%d\n", foo(40));
  return 0;
}

int foo(int x) { return x + 2; }
```

<p>Here, the call <code>foo(40)</code> can be resolved by the compiler. This early allows certain optimizations such as inlining. The most important advantages are:</p>

<ul>
<li>we can do type checking</li>
<li>we can do optimizations</li>
</ul>

<p>On the other hand, some languages defer function resolution to the last possible moment. An example is Python, where we can redefine symbols on the fly:</p>

<pre class="lang-python prettyprint-override"><code>def foo():
    """"call the bar() function. We have no idea what bar is."""
    return bar()

def bar():
    return 42

print(foo()) # bar() is 42, so this prints "42"

# use reflection to overwrite the "bar" variable
locals()["bar"] = lambda: "Hello World"

print(foo()) # bar() was redefined to "Hello World", so it prints that

bar = 42
print(foo()) # throws TypeError: 'int' object is not callable
</code>```

This is an example of late binding. While it makes rigorous type checking unreasonably (type checking can only be done at runtime), it is far more flexible and allows us to express concepts that cannot be expressed within the confines of static typing or early binding. For example, we can add new functions at runtime.

Method dispatch as commonly implemented in “static” OOP languages is somewhere in between these two extremes: A class declares the type of all supported operations up front, so these are statically known and can be typechecked. We can then build a simple lookup table (VTable) that points to the actual implementation. Each object contains a pointer to a vtable. The type system guarantees that any object we get will have a suitable vtable, but we have no idea at compile time what the value of this lookup table is. Therefore, objects can be used to pass functions around as data (half the reason why OOP and function programming are equivalent). Vtables can be easily implemented in any language that supports function pointers, such as C.

#define METHOD_CALL(object_ptr, name, ...) \
  (object_ptr)->vtable->name((object_ptr), __VA_ARGS__)

typedef struct {
    void (*sayHello)(const MyObject* this, const char* yourname);
} MyObject_VTable;

typedef struct {
    const MyObject_VTable* vtable;
    const char* name;
} MyObject;

static void MyObject_sayHello_normal(const MyObject* this, const char* yourname) {
  printf("Hello %s, I'm %s!\n", yourname, this->name);
}

static void MyObject_sayHello_alien(const MyObject* this, const char* yourname) {
  printf("Greetings, %s, we are the %s!\n", yourname, this->name);
}

static MyObject_VTable MyObject_VTable_normal = {
  .sayHello = MyObject_sayHello_normal,
};
static MyObject_VTable MyObject_VTable_alien = {
  .sayHello = MyObject_sayHello_alien,
};

static void sayHelloToMeredith(const MyObject* greeter) {
   // we have no idea what the VTable contents of my object are.
   // However, we do know it has a sayHello method.
   // This is dynamic dispatch right here!
   METHOD_CALL(greeter, sayHello, "Meredith");
}

int main() {
  // two objects with different vtables
  MyObject frank = { .vtable = &MyObject_VTable_normal, .name = "Frank" };
  MyObject zorg  = { .vtable = &MyObject_VTable_alien, .name = "Zorg" };

  sayHelloToMeredith(&frank); // prints "Hello Meredith, I'm Frank!"
  sayHelloToMeredith(&zorg); // prints "Greetings, Meredith, we are the Zorg!"
}
```

This kind of method lookup is also known as “dynamic dispatch”, and somewhere in between of early binding and late binding. I consider dynamic method dispatch to be the central defining property of OOP programming, with anything else (e.g. encapsulation, subtyping, …) to be secondary. It enables us to introduce polymorphism into our code, and even to add new behaviour to a piece of code without having to recompile it! In the C example, anyone can add a new vtable and pass an object with that vtable to sayHelloToMeredith().

While this is late-ish binding, this is not the “extreme late binding” favoured by Kay. Instead of the conceptual model “method dispatch via function pointers”, he uses “method dispatch via message passing”. This is an important distinction because message passing is far more general. In this model, each object has an inbox where other objects can put messages. The receiving object can then try to interpret that message. The most well-known OOP system is the WWW. Here, messages are HTTP requests, and servers are objects.

For example, I can ask the programmers.stackexchange.se server GET /questions/301919/. Compare this to the notation programmers.get("/questions/301919/"). The server can refuse this request or send me back an error, or it can serve me your question.

The power of message passing is that it scales very well: no data is shared (only transferred), everything can happen asynchronously, and objects can interpret messages however they like. This makes a message passing OOP system easily extendable. I can send messages that not everyone may understand, and either get back my expected result or an error. The object need not declare up front which messages it will respond to.

This puts the responsibility of maintaining correctness onto the receiver of a message, a thought also known as encapsulation. E.g. I can't read a file from an HTTP server without asking for it via a HTTP message. This allows the HTTP server to refuse my request, e.g. if I lack permissions. In smaller scale OOP, this means that I don't have read-write access to an object's internal state, but must go through public methods. A HTTP server doesn't have to serve me a file, either. It could be dynamically generated content from a DB. In real OOP, the mechanism of how an object responds to messages can be switched out, without a user noticing. This is stronger than “reflection”, but usually a full meta-object protocol. My C example above cannot change the dispatch mechanism at runtime.

The ability to change the dispatch mechanism implies late binding, since all messages are routed through user-defineable code. And this is extremely powerful: given a meta-object protocol, I can add features such as classes, prototypes, inheritance, abstract classes, interfaces, traits, multiple inheritance, multi-dispatch, aspect-oriented programming, reflection, remote method invocation, proxy objects etc. to a language that does not start out with these features. This power to evolve is completely absent from more static languages such as C#, Java, or C++.

Title: Object Oriented Late Binding

Body:
In the Alan Kays Definition Of Object Oriented there is this definition that partially I don't understand:

OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme LateBinding of all things.

But what does "LateBinding" means? How can I apply this on a language like C#?
And why is this so important?

Body:
“Binding” refers to the act of resolving a method name to a piece of invocable code. Usually, the function call can be resolved at compile time or at link time. An example of a language using static binding is C:

int foo(int x);

int main(int, char**) {
  printf("%d\n", foo(40));
  return 0;
}

int foo(int x) { return x + 2; }

Here, the call foo(40) can be resolved by the compiler. This early allows certain optimizations such as inlining. The most important advantages are:

we can do type checking

we can do optimizations

On the other hand, some languages defer function resolution to the last possible moment. An example is Python, where we can redefine symbols on the fly:

def foo():
    """"call the bar() function. We have no idea what bar is."""
    return bar()

def bar():
    return 42

print(foo()) # bar() is 42, so this prints "42"

# use reflection to overwrite the "bar" variable
locals()["bar"] = lambda: "Hello World"

print(foo()) # bar() was redefined to "Hello World", so it prints that

bar = 42
print(foo()) # throws TypeError: 'int' object is not callable

This is an example of late binding. While it makes rigorous type checking unreasonably (type checking can only be done at runtime), it is far more flexible and allows us to express concepts that cannot be expressed within the confines of static typing or early binding. For example, we can add new functions at runtime.

Method dispatch as commonly implemented in “static” OOP languages is somewhere in between these two extremes: A class declares the type of all supported operations up front, so these are statically known and can be typechecked. We can then build a simple lookup table (VTable) that points to the actual implementation. Each object contains a pointer to a vtable. The type system guarantees that any object we get will have a suitable vtable, but we have no idea at compile time what the value of this lookup table is. Therefore, objects can be used to pass functions around as data (half the reason why OOP and function programming are equivalent). Vtables can be easily implemented in any language that supports function pointers, such as C.

#define METHOD_CALL(object_ptr, name, ...) \
  (object_ptr)->vtable->name((object_ptr), __VA_ARGS__)

typedef struct {
    void (*sayHello)(const MyObject* this, const char* yourname);
} MyObject_VTable;

typedef struct {
    const MyObject_VTable* vtable;
    const char* name;
} MyObject;

static void MyObject_sayHello_normal(const MyObject* this, const char* yourname) {
  printf("Hello %s, I'm %s!\n", yourname, this->name);
}

static void MyObject_sayHello_alien(const MyObject* this, const char* yourname) {
  printf("Greetings, %s, we are the %s!\n", yourname, this->name);
}

static MyObject_VTable MyObject_VTable_normal = {
  .sayHello = MyObject_sayHello_normal,
};
static MyObject_VTable MyObject_VTable_alien = {
  .sayHello = MyObject_sayHello_alien,
};

static void sayHelloToMeredith(const MyObject* greeter) {
   // we have no idea what the VTable contents of my object are.
   // However, we do know it has a sayHello method.
   // This is dynamic dispatch right here!
   METHOD_CALL(greeter, sayHello, "Meredith");
}

int main() {
  // two objects with different vtables
  MyObject frank = { .vtable = &MyObject_VTable_normal, .name = "Frank" };
  MyObject zorg  = { .vtable = &MyObject_VTable_alien, .name = "Zorg" };

  sayHelloToMeredith(&frank); // prints "Hello Meredith, I'm Frank!"
  sayHelloToMeredith(&zorg); // prints "Greetings, Meredith, we are the Zorg!"
}

This kind of method lookup is also known as “dynamic dispatch”, and somewhere in between of early binding and late binding. I consider dynamic method dispatch to be the central defining property of OOP programming, with anything else (e.g. encapsulation, subtyping, …) to be secondary. It enables us to introduce polymorphism into our code, and even to add new behaviour to a piece of code without having to recompile it! In the C example, anyone can add a new vtable and pass an object with that vtable to sayHelloToMeredith().

While this is late-ish binding, this is not the “extreme late binding” favoured by Kay. Instead of the conceptual model “method dispatch via function pointers”, he uses “method dispatch via message passing”. This is an important distinction because message passing is far more general. In this model, each object has an inbox where other objects can put messages. The receiving object can then try to interpret that message. The most well-known OOP system is the WWW. Here, messages are HTTP requests, and servers are objects.

For example, I can ask the programmers.stackexchange.se server GET /questions/301919/. Compare this to the notation programmers.get("/questions/301919/"). The server can refuse this request or send me back an error, or it can serve me your question.

The power of message passing is that it scales very well: no data is shared (only transferred), everything can happen asynchronously, and objects can interpret messages however they like. This makes a message passing OOP system easily extendable. I can send messages that not everyone may understand, and either get back my expected result or an error. The object need not declare up front which messages it will respond to.

This puts the responsibility of maintaining correctness onto the receiver of a message, a thought also known as encapsulation. E.g. I can't read a file from an HTTP server without asking for it via a HTTP message. This allows the HTTP server to refuse my request, e.g. if I lack permissions. In smaller scale OOP, this means that I don't have read-write access to an object's internal state, but must go through public methods. A HTTP server doesn't have to serve me a file, either. It could be dynamically generated content from a DB. In real OOP, the mechanism of how an object responds to messages can be switched out, without a user noticing. This is stronger than “reflection”, but usually a full meta-object protocol. My C example above cannot change the dispatch mechanism at runtime.

The ability to change the dispatch mechanism implies late binding, since all messages are routed through user-defineable code. And this is extremely powerful: given a meta-object protocol, I can add features such as classes, prototypes, inheritance, abstract classes, interfaces, traits, multiple inheritance, multi-dispatch, aspect-oriented programming, reflection, remote method invocation, proxy objects etc. to a language that does not start out with these features. This power to evolve is completely absent from more static languages such as C#, Java, or C++.


问:
How to start using DDD in designing a "library" application
I want to design an online book reader. The first step is describing all the use cases which I have listed below:

I should be able to search a book by title.

I should be able to borrow a book.

I should be able to bookmark a borrowed book.

The system should allow one user per book at a time.

The system should allow to add a new book.

The system should allow to delete an existing book.

That said, I know now I need some Service Objects which would operate on Entities / Value Objects to get the thing done. I am deferring the database design / decision for now as its not considered a good practice. For the similar reasons Delivery mechanisms too is deferred.

After some reading I came to the conclusion that I would need the following:

Services (Algorithms without any states, depends on entities / values)

SearchBook (Takes a title and gives the result back)

BorrowService (Checks if a book can be borrowed)

Member service (Enroll/Unroll members in a library)

Entities (real world mutable objects with unique ID)

Library

Book (ISBN number as a UID)

User (Email as UID, it can be author or reader)

Associations

An author can have many books under his name, a user can only borrow one book at a time. A library can hold many books at a time, it can have many members too.

Notes

For simplicity there will be only single library / store.

No two users can read the same book at a time.

Questions

I am not able to find any value object till now or I am not able to recognize / find it?

I have followed Clean Architecture for some time and helped to build a toy project before. What is the difference between this and DDD?

Am I on the right track?

答:
SearchBook (Takes a title and gives the result back)

Are you sure you need a service for this? It looks like this is a responsibility of a repository, which was given a Specification, containing book title.

BorrowService (Checks if a book can be borrowed)

Are you sure this is not just inStock property of a Book object? Or, if you have some stock quantity calculations, there should be an object, responsible for this.

Member service (Enroll/Unroll members in a library)

What will this service do? Create/delete users is a repository's responsibility.

Book (ISBN number as a UID)

I am not sure this is a good choice of primary key. A book can have two ISBNs or even more. I am not sure you will be able to find a good natural key for books.

User (Email as UID, it can be author or reader)

So, the user will be unable to link secondary email to his account, right? Also, if you choose email as a primary key, linking to the user in other tables will make your indexes grow. Again, I am unsure if you can find a suitable natural key here.

I am not able to find any value object till now or I am not able to
  recognize / find it?
  I haven't find any so far also ;)

ContentLicense: CC BY-SA 3.0


问:
Files included without extensions?
I noticed a long time ago that a number of files included with projects, especially files called README, LICENSE, and so forth, frequently have no filename extension. This is strange to me because it requires the reader of such files to perform some extra commands to open it.

I visited Is it good programming practice to create files with no extension?, but while the answer suggests it's not good to have no filename extension, it doesn't answer my question of whether there is a motive in not including one.

I'd like to know if there are reasons not to include file extensions and what those reasons might be.

答:
It all depends on your operating system of choice and how they implemented metadata to assist with determining the file type.

Unix-based OS's traditionally use the first four bytes of the file to denote its type.The dot character isn't treated as anything special and no file extension is needed for well behaved utilities and apps to read a file correctly.

DOS, and later Windows, traditionally use "." as a special character to denote the end of the file name and the start of the file type metadata (the file extension). Apps in Windows typically rely on the extension to denote the file's type and to read it correctly.

Using the extension, eg README.txt, means the file is more portable, as Linux doesn't care about it and Windows knows what to do with it. That's the reason why it's generally recommended that they be used. If your world is very Linux-orientated and the README file won't typically be read by a Windows user, then there's little point in cluttering the filename with a .txt extension and not putting the extension on it fits better with Linux idioms.

Title: Files included without extensions?


问:
How is spinlock different from polling?
Is spinlock and polling the same thing?

Wikipedia:

a spinlock is a lock which causes a thread trying to acquire it to simply wait in a loop ("spin") while repeatedly checking if the lock is available

This sounds awfully lot like:

```<code>while(!ready);
</code>```

I was taught to avoid polling whenever possible as it was throughly sub-optimal. So, is spinlock a fancy name for bad old polling? How is a spinlock different from polling?

答:
Spinlock is different from polling because it only occurs for a very short period of time, on the order of a few milliseconds or less.  Polling can go on indefinitely.

In parallel programming, a brief episode of spinning is often preferable to blocking, as it avoids the cost of context switching and kernel transitions.

Further Reading

SpinLock and SpinWait in C#

Spinlocks and Read-Write Locks in C

Title: How is spinlock different from polling?


答:
Polling refers to repeatedly checking whether a resource (any kind of resource) is ready.

A spinlock is when the resource you are polling is a lock.

Note that polling is not bad. In particular, polling is efficient when there is usually data ready when you poll. Polling is only inefficient if you do it without then getting any data in return.

On the other hand, interrupts are inefficient if there is so much data that you constantly get interrupted. They are efficient if data arrives rarely enough that you can actually get some useful work done before getting interrupted.

I can give you a real-life example from my own experience: 15 years ago, I had my email program set up to interrupt me every time a new email comes in. Which happened once or twice a week. Constantly checking my inbox would have been a colossal waste of time.

Nowadays, I have all notifications turned off. I know that whenever I look into my inbox, there'll be new emails there. Polling is much more efficient now.

Spinlocks are efficient when a) the likelihood that the lock is taken is low, and b) if the lock is taken, it will only be held for a short time. In other words: it is efficient for mostly uncontended fine-grained locks, but inefficient for highly contended coarse-grained locks.

(And of course, spinlocks only work when there is true parallelism, otherwise the other thread won't have a chance to release the lock. I guess that's kind of obvious, but I wanted to state it anyway.)

Title: How is spinlock different from polling?

Body:
Is spinlock and polling the same thing?

Wikipedia:

a spinlock is a lock which causes a thread trying to acquire it to simply wait in a loop ("spin") while repeatedly checking if the lock is available

This sounds awfully lot like:

```<code>while(!ready);
</code>```

I was taught to avoid polling whenever possible as it was throughly sub-optimal. So, is spinlock a fancy name for bad old polling? How is a spinlock different from polling?


答:
A spinlock is a type of lock, specifically, one achieved via polling.

Polling is a method of checking the status of something (by asking for the status, as opposed to waiting to be told the status).

Not all polling is a spinlock, for example, polling the status of keyboard keys.

Also, polling isn't inherently bad. Very short periods of polling can avoid expensive context shifts that use of interrupts would require, not to mention that polling can sometimes be simpler to implement and thus easier to maintain, especially at lower levels. As usual, absolutes are a terrible thing, and you should use the method that gives the appropriate performance/complexity trade off for your needs as you have measured them, rather than blindly using or discarding options.

Title: How is spinlock different from polling?


问:
How to determine if there's something wrong with my code or a bug in the library
I'm working with Meteor, which is a relatively young Javascript framework. As such, it seems like I often run into problems which haven't been asked on Stackoverflow already.

In one such case, I was agonizing over something that wasn't working, and it turns out it was a bug with Meteor. When I was working through this, I made the assumption that it was a problem with my code, and didn't even consider the possibility of a bug in the framework.

It doesn't help that I'm pretty new with Javascript.

So my question is, in the future, how can I more quickly decide if a bug is mine or the framework's? It's frustrating spending a bunch of time trying to debug something that's undebuggable, especially when I'm not confident in my JS skills.

答:
So my question is, in the future, how can I more quickly decide if a bug is mine or the framework's?

The key is making the bug reproducible and isolated. In general you  want to follow the same process initially whether you suspect the bug is yours or the libraries.

Stack Overflow's MCVE page is a great primer on this. SSCCE also attempts to speak to the same idea. Make an example that is simple and reliably reproduces the error.

As a simple example, imagine you have a an external method that is defined as:

```<code>Meteor.foo(int, int) // returns sum of two ints
</code>```

You are using this method in your code, and suspect it is not working correctly. After following the MCVE process you arrive at the following code:

```<code>print Meteor.foo(0,2) // prints 0
print Meteor.foo(1,2) // prints 3
print Meteor.foo(2,0) // prints 2
</code>```

This is now a compelling reason to believe that the Meteor library is causing the problem (obviously..). In this case it is clear how to write an example that is a "bug is not in my code" MCVE.

The point of all this is to narrow down your usage of your code until you find the minimal amount of code causing the problem. Trimming out extra code until you resolve the bug. If you can't trim anymore because of external library calls... probably found the problem.

Unfortunately, the reality is that nearly all bugs of this sort will not be as simple as that to reproduce. With these (and your MCVE or 'mostly MVCE' example) it's a good idea to:

View release notes / known issues

View open bugs

Ask a question on Stack Overflow or the libraries listserve

View the source code itself or what tests it has

There are other questions one, two about what to do once you arrive at the conclusion the bug is in the external library.

These sorts of problems can be really nasty when working with very expansive and commonly used libraries. We had an instance where multiple people were trying to track down a ship-block bug which ended up being a combination of a mouse driver causing the graphics to not render correctly with an external framework.

Body:
So my question is, in the future, how can I more quickly decide if a bug is mine or the framework's?

The key is making the bug reproducible and isolated. In general you  want to follow the same process initially whether you suspect the bug is yours or the libraries.

Stack Overflow's MCVE page is a great primer on this. SSCCE also attempts to speak to the same idea. Make an example that is simple and reliably reproduces the error.

As a simple example, imagine you have a an external method that is defined as:

Meteor.foo(int, int) // returns sum of two ints

You are using this method in your code, and suspect it is not working correctly. After following the MCVE process you arrive at the following code:

print Meteor.foo(0,2) // prints 0
print Meteor.foo(1,2) // prints 3
print Meteor.foo(2,0) // prints 2

This is now a compelling reason to believe that the Meteor library is causing the problem (obviously..). In this case it is clear how to write an example that is a "bug is not in my code" MCVE.

The point of all this is to narrow down your usage of your code until you find the minimal amount of code causing the problem. Trimming out extra code until you resolve the bug. If you can't trim anymore because of external library calls... probably found the problem.

Unfortunately, the reality is that nearly all bugs of this sort will not be as simple as that to reproduce. With these (and your MCVE or 'mostly MVCE' example) it's a good idea to:

View release notes / known issues

View open bugs

Ask a question on Stack Overflow or the libraries listserve

View the source code itself or what tests it has

There are other questions one, two about what to do once you arrive at the conclusion the bug is in the external library.

These sorts of problems can be really nasty when working with very expansive and commonly used libraries. We had an instance where multiple people were trying to track down a ship-block bug which ended up being a combination of a mouse driver causing the graphics to not render correctly with an external framework.


问:
DDD CQRS - per-query and per-command authorization

Summary

Should authorization in CQRS/DDD be implemented per-command/query or not?

I am developing for the first time an online application using more or less strictly the DDD CQRS pattern. I bumped into some problem, which I can't really get my head around.

The application I am building is a ledger application allowing people to create ledgers, as well as allowing other people to view/edit/delete them, such as employees. The creator of a ledger should be able to edit the access rights of the ledger he created. Could even change ownership. The domain has two aggregates TLedger and TUser.

I read a lot of posts with the DDD / CQRS keyword concerning security, authorization, etc. Most of them stated that authorization was a Generic Subdomain, unless one was building a security application.

In this case, the core domain is a certainly an accounting domain interested with transactions, balancing and accounts. But the functionality of being able to manage fine grained access to the ledgers is also required. I'm wondering how to design this in DDD/CQRS terms.

It's stated in the DDD tutorials all around the place that the commands are part of the ubiquitous language. They're meaningful. They're concrete actions that represent the "real thing".

Because all those commands and queries are actual actions that users would execute in "real life", should the implementation of the authorization be coupled with all these "commands" and "queries" ? A user would have authorization to execute TLedger.addTransaction() but not TLedger.removeTransaction() for example. Or, a user would be allowed to execute the query "getSummaries()" but not "getTransactions()".

A tri-dimensional mapping would exist in the form of user-ledger-command or user-ledger-query to determine the access rights.

Or, in a decoupled way, named "permissions" would be registered for a user. Permissions that would then be mapped for specific commands. For example, permission "ManageTransactions" would allow a user to execute "AddTransaction()", "RemoveTransaction()", etc.

Permissions mapping user -> ledger -> command/query

Permissions mapping user -> ledger -> permission -> command/query

That's the first part of the question. Or in brief, should authorization in CQRS/DDD be implemented per-command or per-query? Or, should authorization be decoupled from the commands?

Secondly, concerning authorization based on permissions. A User should be able to manage the permissions on his Ledgers or on the Ledgers he's been allowed to manage.

Authorization management commands happens in the Ledger

I thought of adding the events/commands/handlers into the Ledger aggregate, such as grantPermission(), revokePermission(), etc. In this case, enforcing those rules would happen into the command handlers. But this would require all commands to include the id of the user who issued that command. Then I would check into the TLedger if the permission exists for that user to execute that command.

For example :

```<code>class TLedger{
    function addTransactionCmdHandler(cmd){
        if (!this.permissions.exist(user, 'addTransaction')
            throw new Error('Not Authorized');
    }
}
</code>```

Authorization management commands in the User

The other way around would be to include the permissions into the TUser. A TUser would have a set of permissions. Then, in the TLedger command handlers, I would retrieve the user and check if he has permission to execute the command. But this would require me to fetch the TUser aggregate for every TLedger command.

```<code>class TAddTransactionCmdHandler(cmd) {
    this.userRepository.find(cmd.userId)
    .then(function(user){
        if (!user.can(cmd)){
            throw new Error('Not authorized');
        }
        return this.ledgerRepository.find(cmd.ledgerId);
    })
    .then(function(ledger){
        ledger.addTransaction(cmd);
    })

}
</code>```

Another domain with service

Another possibility would be to model another authorization domain completely. This domain would be interested in access rights, authorization etc. The accounting subdomain would then use a service to access this authorization domain in the form of AuthorizationService.isAuthorized(user, command).

```<code>class TAddTransactionCmdHandler(cmd) {
    authService.isAuthorized(cmd)
    .then(function(authorized){
        if (!authorized) throw new Error('Not authorized');
        return this.ledgerRepository.find(cmd.ledgerId)
    })
    .then(function(){
        ledger.addTransaction(cmd);
    })

}
</code>```

What decision would be the most "DDD/CQRS" way?

答:
For the first question I've been struggling with something similar.  More and more I'm leaning towards a three-phased authorization scheme:

1) Authorization at the command/query level of "does this user ever have permission to execute this command?"  In an MVC app this could probably be handled at the controller level, but I'm opting for a generic pre-handler that will query the permissions store based on the current user and the executing command.

2) Authorization inside the application service of "does this user "ever* has permission to access this entity?"  In my case this will probably end up being an implicit check simply by means of filters on the repository -- in my domain this is basically a TenantId with a little more granularity of OrganizationId.

3) Authorization that relies on a transient properties of your entities (such as Status) would be handled inside of the domain.  (Ex. "Only certain people can modify a closed ledger.")  I'm opting to put that inside the domain because it it relies heavily on the domain and business logic and I'm not really comfortable exposing that in other places.

I'd love to hear others' responses to this idea -- tear it to shreds if you want (just provide some alternatives if you do :) )


问:
Why would a Rest Api demand a hash of the parameters?
I'm working with a Rest Api that demands to send with any request a hash of the parameters of the request:

Hashkey Calculation This hash key has to be generated by the device
  itself and has to follow strict rules:

Get all request parameters and their values (except hashkey) Order
  theses pairs alphabetically by parameter name Concatenate all pairs
  using = between key and value and & between the pairs. Concatenate the
  resulting string with & and the API Key handed out to you by Fyber.
  Hash the whole resulting string, using SHA1. The resulting hashkey is
  then appended to the request as a separate parameter.

(http://developer.fyber.com/content/current/android/offer-wall/offer-api/index.html)

What's the reason for that?

I would assume it's security related, to prevent a 'man in the middle' to alter the parameters? If so, wouldn't it be easy for the man in the middle to send a re-generated hash with the tampered request?

答: The man in the middle does not have the API Key, so they can not generate the hash.</p>


问:
Advantages and possible drawbacks of using Java for cross-platform development vs. .NET?
If I were to begin writing an application using Java with the intention of porting it to other platforms with little or no modification, would it be wise to consider using the .Net framework instead?

I have no specific targets in mind with respect to platform. At a minimum, Windows/Mac/Linux support would be nice. Also ease-of-use for the end-user is a consideration.

答: I wouldn't go with .Net.  Mono is not bad, but if you use some obscure corner of C# or the .Net library that Mono does not support, then you're screwed.  This is way less likely to happen in Java because Sun stands behind full runtime implementations of Java for Windows, Mac and Linux.</p>

ContentLicense: CC BY-SA 2.5


答:
I'm sorry to say this, but there is no magic bullet.

There is no way in general to easily tell whether:

You have a bug in your code.

You misunderstand what third-party code is supposed to do.

Third-party code is doing the wrong thing.

The only solution is to improve your knowledge of javascript and get better at debugging.

Title: How to determine if there's something wrong with my code or a bug in the library

Body:
I'm working with Meteor, which is a relatively young Javascript framework. As such, it seems like I often run into problems which haven't been asked on Stackoverflow already.

In one such case, I was agonizing over something that wasn't working, and it turns out it was a bug with Meteor. When I was working through this, I made the assumption that it was a problem with my code, and didn't even consider the possibility of a bug in the framework.

It doesn't help that I'm pretty new with Javascript.

So my question is, in the future, how can I more quickly decide if a bug is mine or the framework's? It's frustrating spending a bunch of time trying to debug something that's undebuggable, especially when I'm not confident in my JS skills.


问:
Is it safe to include connection data in token?
When generating a ClaimIdentity for use by oAuth in generating a token, is it safe to include database information as a claim?

My application uses a different database depending on the specific scenario (e.g. A demo user vs a live user).  I need the database connection details on every call in order to hit the correct database for the logged in user.

Is it safe to include this information as part of the identity that is used to generate the token? What is the likelihood that the token could be decrypted and the connection details extracted?

答:
Typically with oAuth, the Realm field would be used for this purpose.  I could see you including a query string parameter which contains a key to point to a specific database connection or some other identifier which would allow you to know where a users data exists.

From https://www.rfc-editor.org/rfc/rfc2617

These realms allow the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme and/or authorization database.

I would not store actual connection string details here though!  That type of data should never leave your application.  You should use a key, hash, or identifier and then use that to look up the connection string details internally.


问:
How do you define stateless methods while keeping them together in Objective-C?
I have a few methods which are stateless:

```<code>loginWithEmail: password: completion:
signUpWithEmail: password: completion:
resetPasswordForUsername: completion:
</code>```

Currently what I do is I create a class which holds these stateless methods:

```<code>@interface KGAccountService : NSObject

+ (void)//method1
+ (void)//method2
+ (void)//method3

@end
</code>```

I then would call the methods from some place like a view controller that a user is using to log in.

```<code>[KGAccountService loginWithEmail:@"email" password:@"password" completion:{
    // user logged in or error
}];
</code>```

A co-worker of mine is pretty adamant that even though the class only houses class methods and does not need any sort of state, it should be implemented using the singleton pattern and be called through that:

```<code>@interface KGAccountService : NSObject

+ (instanceType)sharedInstance;
- (void)//method1
- (void)//method2
- (void)//method3

@end
</code>```

Then:

```<code>[[KGAccountService sharedInstance] loginWithEmail:@"email" password:@"password" completion:{
// user logged in or error
}];
</code>```

I don't see the point in implementing the singleton pattern when it is not needed and my co-worker was not able to get his point of view through to me.  Is there a design pattern which I am missing and is my way of creating a class to house stateless class methods correct?

答:
The singleton pattern may be of advantage. Even though you say the methods are stateless, the implementation isn't necessarily, and then having an object holding the state will be useful.

As a simple example, the loginWithEmail: ... is probably asynchronous and you don't want to have another call while the first one is running. That's difficult without having state around.


问:
Is it bad practice to throw multiple custom exceptions in Java?
I'm developing a Java web application. It is a three layered architecture:

web > service > repository.

I'm thinking of creating many exceptions - each specific to each individual error and in the service layer where my business logic resides I want to throw specific exceptions that is tied to the business error.

And in the web layer (further up the stack where it is closer to the front end) is where I'm catching it and handling with them accordingly.

Someone said to me, don't do it this way because it is bad practice and advised me to just throw one single generic business exception instead - and he was adamant he was right. When I heard this, my reaction was that it goes against all the stuff I learned in university, past experiences, and the stuff I read in common tech books.

答:
I'm looking at the Spring application that I've got sitting here, and there are a few dozen custom exceptions.  Much of this is because with Spring, the exceptions can bubble all the way out to the framework layer and then be nicely translated by the framework into the corresponding HTTP status code.

Missing rows are their own class structure - MissingRowException is an abstract class.  There's also a place for the corresponding wrapped SQLException.

Foo row not found? That's a FooMissingException that becomes a 404.

Bar row not found in the database? That's a BarMissingException that also becomes a 404.

Validation errors are their own exception class structure

System errors are another exception class structure (there's one here named DatabaseBorkedException - that's a 500 error)

And so on

I don't even want to think about how many of the little fiddly exceptions that are private inner classes to the controllers because they're only used within that controller (bail out, there's no reason to go further, send a nice custom page).

You will note that there are trees of exceptions. These do happen to have a common root, and I can just throw the top level GenericBusinessException (which isn't abstract).  Note that doing that exception logs an info message about who did it and also has a pmd warning when you look at it with static analysis - but sometimes you need to cut the corners and take on a bit of technical debt and just throw the simple exception now to get it out the door rather than all the other work for the other exceptions.

If the entirety of the handling of the exception is just log it, one may consider that writing all these exceptions is a waste of time. And in some situations, I'd agree.  However, if you have different handling for each exception at some level, your alternative is tossing an enum in a field of the exception or stringly type the GenericBusinessException and not really doing anything about it.

Custom exceptions add meaning and allow the coder to more clearly express the intent of the code. It allows a maintainer to (if the exceptions are used in a way that can be reasoned about) to more quickly follow the flow of an application. To this extent, they are quite good and beneficial.


问:
Throwing exceptions in application configuration providers
Simple question: What is the best/common practice regarding to throwing errors for application configuration providers?

Given is a simple key/value-based configuration source:

```<code>class Configuration
    string GetValue(key);
    void SetValue(key, value);
</code>```

Or more extended, with the ability to add/remove key/value elements

```<code>class Configuration
    string GetValue(key);
    void SetValue(key, value);
    void AddKeyValuePair(string key, string value);
    void RemoveKeyValuePair(string key);
</code>```

Not throwing exceptions on methods like GetValue() has the benefit of not interrupting the application flow and making code easier to read because of a lack of exception handling etc. It also allows to use null-conditional operators (maybe monads) or null-coalescing operators for e.g. setting defaults:

```<code>var value = configuration.GetValue("myKey") ?? "Hello World";
</code>```

Return null simply tells the user: 'Whoops, got nothing to return since nothing is set/there'.

However..

If I'd avoid throwing exceptions, what would happen if I try to add a key/value pair which is already available? Or set the value with a key that isn't there in the underlying storage? Or removing a key/value pair that isn't available? Would it be obvious for the user that simply nothing happens when we tries to remove a none-existing key pair?

What is the prefered approach for application configuration?

答:
First and foremost: What is a configuration for?

A configuration allows the user to change the behaviour of our application to influence the behavior of your application in some way or the other. Your application behaves in a certain, sane way but the user wants to customize the behaviour.

That said the perspective for your answers is the following:

If I'd avoid throwing exceptions, what would happen if I try to add a key/value pair which is already available?

Your application has a sane default behaviour. If the user decides to overwrite it, this is okay. If the user changes his mind, he should be able to do so without hassle as long as your application is in a sane state.

Or set the value with a key that isn't there in the underlying storage?

If your configutation should only accept certain values, and you should let your users know that.

Or removing a key/value pair that isn't available?

The purose of this action is, that you do not want a customized behaviour and instead want to rely on the defaults. You should handle this case gracefully and accept it in case of you would allow the set-operation in other cases let your user know that this configuration value isn't allowed.

Would it be obvious for the user that simply nothing happens when we tries to remove a none-existing key pair?

No. But would he care?

In case the user wants to get a value, which isn't explicitely set, return the (sane) default.

Regarding exceptions:

Exceptions are just that: exceptional behavior in case you could not handle the situation. Think of a Samurai - accomplish your mission or die trying.

Setting not allowed options is exceptional so it would be okay to throw an exception.


问:
How can we keep track of which version of our code is in each environment?
My team currently uses a fairly simple branching/deployment process that looks like this:

```<code>                ┌────────┐ ┌────┐ ┌──────┐
 Environments:  │  DEV   │ │ QA │ │ PROD │
                └────────┘ └────┘ └──────┘

                     ▲       ▲       ▲
                     │       │       │

                ┌────────┐ ┌────┐ ┌──────┐
 Builds:        │  DEV   │ │ QA │ │ PROD │
                └────────┘ └────┘ └──────┘

                     ▲       ▲       ▲
                     │       │       │

                ┌────────┐ ┌────┐ ┌──────┐
 Branches:      │ master │ │ qa │ │ prod │
                └────────┘ └────┘ └──────┘
</code>```

Each environment has its own branch (we use git) and its own build that uses that branch.  When we want to promote from one environment to another, for example, from DEV to QA, we merge the master branch into qa and kick off a new QA build (which is then automatically deployed to the QA environment).

We're considering moving to a new process that would do away with having a dedicated branch and build for each environment.  Instead, a single release build would create a "deployment package" which could then be deployed to any environment.  We're imagining a typical workflow would look something like this:

```<code>                ┌────────┐     ┌────┐     ┌──────┐
 Environments:  │  DEV   │ ──► │ QA │ ──► │ PROD │
                └────────┘     └────┘     └──────┘

                      ▲
                       \

                        ┌───────────────┐
 Builds:                │ release build │
                        └───────────────┘

                                ▲
                                │

                ┌────────┐ ┌─────────┐
 Branches:      │ master │ │ release │
                └────────┘ └─────────┘
</code>```

Promoting from one environment to another would no longer be handled in source control; rather, we'd just take the already-built binaries (the "deployment package") and drop that on the new environment.

This new system would allow us to deploy any build to any environment, which has several advantages. For example, it's trivial to test PROD bug fixes in DEV and QA.  Our current system doesn't provide an easy way to do this without rolling back a branch, which we'd obviously like to avoid.

The biggest drawback with this new system is that we no longer have an automatic way of tracking what code is in which environment.  If we need to make a fix in PROD, we no longer have a dedicated branch in sync with the current production codebase.  The same goes for QA - if we want to push a quick change to QA without dredging up in-progress work from master, we no longer have a branch that reflects the current state of the QA environment.

How can we keep track of what code is in each environment?

Some options we're considering:

utilizing git tags to keep track of which commit is in which environment

embedding the git commit used by the build into each deployment package

答:
Git tags are what you really want to use to designate releases. The reason is that they have meaning to you and can be used to quickly recognize the linkage between the state deployed code and any information that the build server may have (such as build number).

While that is the answer you are looking for, it only solves half the problem. The other is "hey, here's the deployed .[wje]ar on the server, what build did it come from?"  We know that you'll never have different versions of the application deployed on dev and qa or prod. Right?

The solution to that part of the question is to have the build server put the information into the manifest.  Coming from a maven and svn example that I have in front of me:

```<code><manifestEntries>
    <Specification-Title>${project.name}</Specification-Title>
    <Specification-Version>${project.version}</Specification-Version>
    <Build-Number>${build.number}</Build-Number>
    <Build-Id>${build.id}</Build-Id>
    <Svn-Revison>${svn.revision}</Svn-Revison>
</manifestEntries>
</code>```

That's in the maven-war-plugin archive configuration. But you can find it in other plugins too.  Then in Hudson, part of the maven build invocation is:

```<code>-Dbuild.number=${BUILD_NUMBER}
-Dsvn.revision=${SVN_REVISION}
-Dbuild.id=${BUILD_ID}
</code>```

which sets those defines that then maven picks up.  And then its just a matter of looking in the MANIFEST.MF file that has been deployed on the server to see what version it is.

There's a git plugin, that offers a similar set of environment variables including:

GIT_COMMIT - SHA of the current

GIT_BRANCH - Name of the remote repository (defaults to origin), followed by name of the branch currently being used, e.g. "origin/master" or "origin/foo"

The combination of these two practices allows you to easily identify the build (because build numbers go forward, and have meaning, unlike sha checksums) and the specific git commit that it is built from.

Body:
Git tags are what you really want to use to designate releases. The reason is that they have meaning to you and can be used to quickly recognize the linkage between the state deployed code and any information that the build server may have (such as build number).

While that is the answer you are looking for, it only solves half the problem. The other is "hey, here's the deployed .[wje]ar on the server, what build did it come from?"  We know that you'll never have different versions of the application deployed on dev and qa or prod. Right?

The solution to that part of the question is to have the build server put the information into the manifest.  Coming from a maven and svn example that I have in front of me:

<manifestEntries>
    <Specification-Title>${project.name}</Specification-Title>
    <Specification-Version>${project.version}</Specification-Version>
    <Build-Number>${build.number}</Build-Number>
    <Build-Id>${build.id}</Build-Id>
    <Svn-Revison>${svn.revision}</Svn-Revison>
</manifestEntries>

That's in the maven-war-plugin archive configuration. But you can find it in other plugins too.  Then in Hudson, part of the maven build invocation is:

-Dbuild.number=${BUILD_NUMBER}
-Dsvn.revision=${SVN_REVISION}
-Dbuild.id=${BUILD_ID}

which sets those defines that then maven picks up.  And then its just a matter of looking in the MANIFEST.MF file that has been deployed on the server to see what version it is.

There's a git plugin, that offers a similar set of environment variables including:

GIT_COMMIT - SHA of the current

GIT_BRANCH - Name of the remote repository (defaults to origin), followed by name of the branch currently being used, e.g. "origin/master" or "origin/foo"

The combination of these two practices allows you to easily identify the build (because build numbers go forward, and have meaning, unlike sha checksums) and the specific git commit that it is built from.


答:
Do recall that an exception is after all just a class, that can have instance fields and methods of their own while they extend some flavor of Exception or implement Throwable.

I say this because I think having an exception defined for each and every error condition may be an inappropriate level of specificity for a class, when really what might serve you better is to have a small handful of exceptions that cover distinct categories of failure types, and that let you include details that provide the specificity.

Generally, you create an exception type for each different way that you'll handle thrown exceptions.

Title: Is it bad practice to throw multiple custom exceptions in Java?

Body:
I'm developing a Java web application. It is a three layered architecture:

web > service > repository.

I'm thinking of creating many exceptions - each specific to each individual error and in the service layer where my business logic resides I want to throw specific exceptions that is tied to the business error.

And in the web layer (further up the stack where it is closer to the front end) is where I'm catching it and handling with them accordingly.

Someone said to me, don't do it this way because it is bad practice and advised me to just throw one single generic business exception instead - and he was adamant he was right. When I heard this, my reaction was that it goes against all the stuff I learned in university, past experiences, and the stuff I read in common tech books.


答:
Is it bad practice to throw multiple custom exceptions in Java?

Generally speaking: No. Why should it?

As with everything: Abstraction is your friend.

Is it necessarry to have a CustomerNotFound Exception and a ProductNotFound Exception? Or are your requirements just a more abstract NotFoundException?
The context could help to determine, what was missing. Having different exceptions for the sake of having them is nonsense.

Is it necessary, each layer of your application having custom exceptions?
Exceptions are a way to report, that an intended action failed due to some reason.

Say, you have a controller which asks the service-layer to retrieve data, which in turn asks the DA-layer to read values from the DB. The resultset is empty. The service gets the empty resultset and throws a NotFoundException the service communicates, the failure of the action due to a missing result.

Say, the controller needs the service to do the payrolls for employees. And the service is asked to do the payroll for the employee with ID 123456, and in turn asks a service to retrieve the employee - but no emloyee could be found.

There are two ways to deal with that:

1) You throw a NotFound exception in the DA-Layer, catch it in the payroll-service and rethrow a PayrollServiceException wrapping the NotFoundException with the message Exmployee could not be found

2) You throw a NotFound exception in the DA-Layer and do not catch it in the payroll service and catch it instead a layer above.

I would go for (2), since in (1) the information, that the action failed because of a missing employee is redundant.


答:
Is it bad practice to throw multiple custom exceptions in Java?

No.  It is good practice.

The only situation where multiple exceptions might be a (slightly) bad idea is if there is absolutely no possibility (ever!) of catching individual exceptions; i.e. the fine-grained exceptions won't serve any functional purpose.  However, my opinion is that if you can make that assertion, then there is probably something wrong with the way that you / your team is using Java.  And the counter-argument is that sensible use of multiple custom exceptions will help you to document the APIs ... even if you are never going to do more than catch-log-and-bail-out at runtime.

This is not to say that lots of custom exceptions will always be good:

If you go overboard and create a separate exception for everything, then you are probably adding unnecessary complexity.  (In a lot of cases, different exception messages are sufficient.)

If you don't have a sensible inheritance hierarchy for your custom exceptions, then you may end up regretting it.  (A well-designed hierarchy allows you to catch "classes" of exceptions, or declare methods as throwing them.  It can make your code simpler.)


问:
Entire webpage obfuscation
I want to obfuscate all the webpages of my website. I Googled through some free tools like HTML and Javascript obfuscation but don't know how effective they are.

First of all, does it makes sense to obfuscate a webpage that could comprise of variety of codes like Javascript, PHP etc.

Secondly, how effective is this method?

答: Obfuscating to attempt to hide PayPal button codes is not time well spent. You will not get a return on the time you spend on this so it is not worth the effort. Like others point out it can all be reversed so you will not be limiting those interested in finding out what goes on in your pages.</p>

Title: Entire webpage obfuscation


问:
Split a File into Multiple Objects Functionally
I want to read a file into a collection of objects. The data (it's a Leica PTX file if you're curious) is formatted as follows:

```<code>640 [begin item #1: number of columns]
480 [number of rows]
0 0 0 [position information: 3x3 matrix]
0 0 0 [position ctd]
0 0 0 [position ctd]
1 0 0 0 [calibration information: 3x4 matrix]
0 1 0 0 [calibration ctd]
0 0 1 0 [calibration ctd]
1.1 2.2 3.3 0.5 [point 1: X Y Z I]
-0.2 2.3 1.4 0.2 [point 2: X Y Z I]
...
3.9 1.2 -7.7 0.8 [point n: X Y Z I]
640 [begin item #2: number of columns]
480 [number of rows]
0 0 0 [position information]
0 0 0
0 0 0
1 0 0 0 [calibration information]
0 1 0 0
0 0 1 0
0.2 1.3 -2.1 0.4 [point 1 of item #2]
... [etc]
</code>```

I.e. Two lines each containing a single float/double (as text) signal the beginning of a new item, and no other lines are exactly one number.

It's easy to do if there's only one item per file, it's a simple fold operation. It would also be relatively straightforward to do with a while type loop that keeps state, but I'm new to functional programming and wondering if there isn't a more concise and elegant way to do this functionally with standard tools (like reduce, fold, split/partition, etc). The best solutions I've come up with so far involve "peeking" ahead using lists or arrays, but I'd like something that allows for the possibility of a sequence that is consumed as it iterates for maximum generality. (I'm using F# and .NET but I don't see this as a language-specific problem.)

答:
I'd wager that the most popular tool in the Haskell world for this sort of problem is parser combinators.  The classic library for this is parsec, but for a machine generated file format the attoparsec library is generally a better choice (faster parsing at the cost of less friendly error reporting—a good tradeoff when you're reading large files that were not written by humans).

There is an excellent tutorial demonstrating attoparsec's use by parsing log files.

Attoparsec is popular enough that somebody tried to port it to F#, but I've never even written an F# program, so I definitely don't have any way of judging the quality of that library.  There's also a port of the regular (non-"atto") Haskell parsec library to F#, that might be worth looking at—it also comes with a tutorial.

If you wish to understand a little bit of how parser combinators work under the hood, Graham Hutton and Erik Meijer wrote two simple tutorials showing simplified internals.  The first, I believe, is an abridged version of the second:

http://www.cs.nott.ac.uk/~pszgmh/pearl.pdf

http://www.cs.nott.ac.uk/~pszgmh/monparsing.pdf

These are in Haskell but if you know F# you will likely be able to follow a lot of it.


问:
What licenses restrict distribution, liability, and commercial use?
I have to provide my code to someone to look at and use, but wish to maintain a number of rights. Specifically, I want a license that 1) Limits my liability, 2) prevents commercial use and 3) prevents further distribution, including of modified copies. I have been unable to find anything that covers this. The closest I have found is a Creative Commons license, but distribution is still (obviously) allowed.</p>

答:
Licences like Creative Commons (and others like Apache, BSD, GPL, etc) are meant to be templates. Most people use them as is without modification, but there is nothing to stop you from taking something like Creative Commons, and modifying the "no distribution" clause - you just can't call it Creative Commons.

Organisations write their own licences all the time.


答:
In my experience (I am a Java developer for 10+ years now) it is bad practice. Not that it is a code smell, but it most often hinders you in your daily work.

Think of an application that tries to read a file and probably throws an FileNotReadableException. After a while you realize, that the file may not be readable due to insufficient access-rights. What do you do? Change the name of the exception - no, it may be still in use. Add a subtype FileNotReadableBecauseOfAccessRightsException? Well, this is rather 2 errors - not readable + access rights, but the root cause is the rights thing. So you add an InsufficientAccessRightsException somewhere else in the class tree. When doing so you also need to change the code where the original exception was caught since its 2 different types now (a violation of the open-closed-principle). And so on... And what's the gain? ... in contrast to an exception with a message? Static type safety. In the context of exceptions it is only useful to prevent typos. A developer could still use a wrong exception type (e.g. EntryNotFoundException instead of FileNotReadableException).

As said by dwoz: an exception is just a class.

My experience is that a few exceptions are sufficient. What you want to express are error-messages - for several messages you only need 1 (runtime) exception with a String field. All exceptions should be caught by a default error-handler at the highest possible layer (or earlier if necessary).

Besides the usual message, you sometimes need to store more information, like a filesystem-path, a username, a device-id, a uuid to more easily trace the error in a distributed system, etc. for those purposes I suggest to create custom exception classes.

As said by amon, a rule of thumb should be: for libraries use (some) exceptions, for (web-) applications us as few as possible


问:
In MVC framework, where do we define how data are displayed?
I think that the controller should bring the data to view from model. However, is it controller's duty to tell how view should display the data, or the view should know how the data should be displayed?

To be more specific, I am writing a website, there are several databases as data model, the controller is written in Python, and view is written in AngularJS.

Now, on the view side, where should I code how the data is displayed, on the JavaScript side or on the Python side? E.g. I maintain a JSON file:

```<code>[{
  "key": "name",
  "column": "Name",
  "align": "left"
},{
  "key": "salary",
  "column": "Salary",
  "align": "right",
  "filter": "salaryFilter"
}]
</code>```

Should it be stored in personInfo.js, or personInfo.js should read it from controller via ajax?

答:
The tradition of MVC is that the View decides how data is displayed.

If you are writing view with Angular in a browser then you will need HTML for your view. The view will be a combination of HTML and angular directives. Any decent Angular tutorial will show you this quickly.

Angular is based on the idea that there will also be a controller and model in javascript. It would be typical to have model, view, and controller in javascript and HTML (for the view) on the client side.

You can have a server side MVC framework. There are many. But it would seem odd to have a view on the server side if you are building your UI with Angular.

You might also have a view on the server side if you support some other form of UI, such as voice response, PDF output, virtual reality, character mode terminal, that is not built with angular in the browser.

And you would have a server side view if you dropped Angular and used, say JSP or PHP to produce your UI.


问:
continuous delivery: moving to different versions
lets say:
I have few environments, A, B and C  (or development, staging and production)
I have application X

I have multiple versions of application (X), V1, V2, V3

each version of X has its corresponding configuration (C) {V1->C1, V2->C1, V3->C2}

-by configuration I refer to passwords, key files, etc that is unique per environment

My expectation is to deploy software (each commit) quickly with appropriate config somehow up to staging quickly without any manual intervention but release to production will require release manager pressing a button somewhere.

questions:

do one make associations between app version and config set V->C?

do one persist the association if made?

how do one choose the right combination of (application version, config version/set) when roll back to some earlier version is required in any one environment?

答:
It depends on where you store configuration.

You can store it in version control, side by side with your source code. This makes the pairing question irrelevant, since configuration is necessarily in sync with the source.

When it comes to sensitive data, version control systems such as SVN make it possible (and easy) to define in a granular way who can access what, ensuring that only a team working on the actual project can view and modify private keys and passwords.

The major issue I encountered with this approach is when you need to access configuration from a location where you can't access the version control (especially if you don't like the idea of creating system accounts for your SVN server). I solved it by creating a product which let me to configure and audit the accesses to sensitive information, but simply giving a read-only access to the SVN may be easier in most situations.

You can store it somewhere else—in a MongoDB database, for instance. In this case, you'll need to pair it with the version control yourself. Since you are talking about continuous delivery, I'm not sure why are you talking about versions; in all cases, each document within the database can contain, among the configuration itself, the minimum revision number. This way, if you have configuration for revisions 2789, 2801, 2816 and 2817, you can tell that a revision 2804 should use the configuration associated with revision 2801, not the other three.

It can also be the other way around. You may have an identifier of the configuration version in your database, and use it in the source code to identify which configuration should be applied. This is particularly useful for distributed version control systems, since their revision numbers are not incremental.

The drawback of keeping configuration separately from your source code is that it's very easy to forget to change the revision number/configuration version identifier, introducing bugs which could be difficult to debug. In my opinion, the approach makes sense only if the configuration is managed by persons other than developers—usually system administrators. If this is your case, I would suggest to look into DevOps, where developers are also in charge of the deployment of their app; in this context, storing configuration together with the source in a version control makes perfect sense.


问:
Public and Private Constructors with Equivalent Signatures
Here is the problem illustrated using an example of an immutable class.  A Book must have at least one of a title and an ISBN.

```<code>public class Book
{
    private readonly string _title;
    private readonly int? _isbn;

    public Book(string title)
        : this(title, null, true)
    {
        ... throw exception if title is null
    }

    public Book(int isbn)
        : this(null, isbn, true)
    {
        ... throw exception if isbn < 1
    }

    public Book(string title, int isbn)
        : this(title, isbn, true)
    {
        ... throw exception if title is null
        ... throw exception if isbn < 1
    }

    private Book(string title, int? isbn, bool privateConstructor = true)
    {
        _title = title;
        _isbn = isbn;
        ... more work (beyond the scope of this example)
    }

    ... public properties, etc.
}
</code>```

See that privateConstructor boolean?  I had to throw that in to differentiate between the public Book(string, int) and the private Book(string, int?).  While this is fairly harmless since the extraneous parameter is in a private constructor, its use seems smelly to me.  Reordering the parameters of the private constructor would work but that would make the constructor initializers appear non-intuitive (in my real work, there's more than just two parameters in play).  What is a better way?

答: Is there any reason you cannot use static methods (something like createFromTitle and createFromISBN) + private constructructor for what you are trying to achieve? Just use those static methods as contructors.


问:
Difference between mutex in windows and linux
Is that correct that a mutex object in Linux cannot be used for cross process synchronization as opposed to its Windows counterpart?

If that is true - what was the idea to limit mutex synchronisation functionality on Linux?

答:
Linux Mutexes can be used for cross process synchronization.  Been there, done that, very useful.  The Mutex must be accessible to the processes concerned, such as being in a shared memory block.  The Mutex could also not be shared, and therefore private to the process that created it.  The Mutex functionality in Linux is not limited.

Windows Mutexes are system objects.  Any process can use the Mutex if it knows the name of the Mutex (in the case of a named Mutex), or if it has a handle to it.

Critical Section is functionally equivalent to an unshared Mutex in Linux, but is not a Mutex.  You can use a mutex to do the job of Critical Section, albeit a bit overkill, but you can not get the interprocess capabilities of a Mutex from Critical Section (or can you?).

Mutex is not rarely used; a snapshot of my system (using Sysinternal's WinObj) shows 100 mutexes, 173 critical sections, and only 8 semaphores.  And while using a Mutex to indicate a process is running (and thereby prevent instantiation of another copy of that process) is probably the most widely known usage of a Windows Mutex, and a valid, if course-grained, synchronization techninque, a quick glance at the list of mutexes on my machine reveals other usages, one of the most common being to control access to cache of some sort (browser, SVN, etc.)

I personally disagree with the usage of a port to discover processes.  Just because port 61348 is in use doesn't mean the process I expect to be there is the one holding the port.  Unless the process requires that port, such as server listening on a well known port, there is not enough information to decide whether or not to instantiate.


问:
How to keep a team well-trained?
I'm currently mentoring a small team of 4 junior dev in small software company. They are very smart and often achieve their tasks with a high-quality job but I'm sure they still can do better - actually I have exactly the same feeling for myself :) -. Besides some of them are more "junior" than other.

So I would like to find of a funny way to improve their CS skills (design, coding, testing, algorithmic...) in addition to the experience they acquire in their daily work. For instance, I was thinking of setting up weekly sessions, not longer than 2 hours, where we could get together to work on challenging CS exercises. A bit like a coding dojo.

I'm sure the team would enjoy that but is it really a good idea? Would it be efficient in a professional context? They already spend all their week to code so how should I organize that in order for them to get some benefits?

Any feedback welcome !

答: Another technique I've seen that works is a lunch presentation from a senior developer/consultant once a month or so. And don't forget to provide the lunch. Most devs I know love free grub. You might ask them if they prefer any specific topics.</p>

Title: How to keep a team well-trained?


答:
do people generally make associations between app version and config
  set V->C?

how do people choose the right combination of (application version,
  config version/set) when roll back to some earlier version is required
  in any one environment?

"People" don't do things like this "generally" in software development. There are dozens of ways this can be implemented in software, and the "right" way depends on a hell lot of things. For example,

how many installations do you have for your application?

does each kind of installation have a different config?

will  each kind of installation allow lots of users with different configurations?

what life cycle has your application and how does the config structure change throughout the life cycle (is it backwards or upward compatible?)

what kind of backup/restore infrastructure is available and can configurations easily be backuped together with the application?

Is it a database application, a destop app, a server app, a smartphone app, an embedded app?

can there multiple versions be installed in parallel in one environment?

What happens when a configuration gets lost, can it easily be restored / recreated?

Just to give you one example: MS Office came in versions "2003", "2007, "2010", "2013" etc. You can mostly install them in parallel, each version with a separate configuration, for each user, and probably a machine specific configuration, too. User specific configurations are stored in different folders per version, one could theoretically backup and restore them individually (though I guess the majority of Office users don't do this, if the machine fails, they will install the program again and recreate their original configuration manually). And as you see, for this kind of application both suggestions of @MainMa are fully unsuitable: there is neither a "version control system" nor a database where the user config could be stored.

Other programs might work completely differently, because if a config gets lost, a critical production system might fail, which might have a serious financial impact for their business. So you have to look at your kind of application, switch on your brain and decide under what category it falls.

Title: continuous delivery: moving to different versions

Body:
lets say:
I have few environments, A, B and C  (or development, staging and production)
I have application X

I have multiple versions of application (X), V1, V2, V3

each version of X has its corresponding configuration (C) {V1->C1, V2->C1, V3->C2}

-by configuration I refer to passwords, key files, etc that is unique per environment

My expectation is to deploy software (each commit) quickly with appropriate config somehow up to staging quickly without any manual intervention but release to production will require release manager pressing a button somewhere.

questions:

do one make associations between app version and config set V->C?

do one persist the association if made?

how do one choose the right combination of (application version, config version/set) when roll back to some earlier version is required in any one environment?


问:
What mechanism/protocol transmits non-HTML files when downloaded from the web?
When a non-HTML file such as a PDF, DOCX, EXE, etc is made public to the WWW by an HTTP server, and a client makes a request for said file,

www.example.com/download?=test.doc

what facilitates the file transfer over to the client?

Is it transmitted over HTTP or another protocol? In what format or encoding is the data represented?

I'd also like to know how some file download implementations can transmit the file and simultaneously send a HTTP response back containing just the header (eg, content-disposition) which indicates to me that the empty response body was not the vessel for the file.

答:
Yes it is transferred by HTTP. Your example url kind of obscures the fact because you have left out the scheme (the initial "http:"), but if you enter an url without a scheme in a  web browser, it will default to http, hence the url is actually:

```<code>http://www.example.com/download?=test.doc
</code>```

A HTTP response contains a header and a payload, and the payload can be data in any format - html, javascript, css, images, or any other file format including doc or exe. At the HTTP level, a HTML payload and a DOC payload are treated exactly the same. On the client side they will of course be treated differently - html or images will be rendered in the browser while a doc will (depending on configuration) cause the browser to launch an external application like Word. But this is at the discretion of the client, and is outside the scope of http.

The content disposition header does not really change how the payload is transferred via http, it it just a hint to the client how the handle the payload when received. It can indicate that the user should be prompted to save the payload as a local file, rather then rendering/processing the payload as is the default. But the transfer mechanism is the same.

Body:
Yes it is transferred by HTTP. Your example url kind of obscures the fact because you have left out the scheme (the initial "http:"), but if you enter an url without a scheme in a  web browser, it will default to http, hence the url is actually:

http://www.example.com/download?=test.doc

A HTTP response contains a header and a payload, and the payload can be data in any format - html, javascript, css, images, or any other file format including doc or exe. At the HTTP level, a HTML payload and a DOC payload are treated exactly the same. On the client side they will of course be treated differently - html or images will be rendered in the browser while a doc will (depending on configuration) cause the browser to launch an external application like Word. But this is at the discretion of the client, and is outside the scope of http.

The content disposition header does not really change how the payload is transferred via http, it it just a hint to the client how the handle the payload when received. It can indicate that the user should be prompted to save the payload as a local file, rather then rendering/processing the payload as is the default. But the transfer mechanism is the same.


答:
A completely different approach would be to dismiss the idea of versions completely. You only have "one version" which has a different configurable behaviour. The only difference would be, that you have a common codebase - even in production you would deploy work in progress: but not activated.

The difference only boils down to different sets of features being enabled in your product.

The de-/activation is done via feature toggles.

Upside: the whole release process is simplified: You are always delivering an integrated version of your software. Every feature is always available in master. No additional branches are needed.

There is no pain with merging features together, because: no branches no need for merging. There is no confusion what feature is on which branch and maybe depend or clashes with features from other branches. Every part could be activated at will. Even a rollback is not necessary anymore: it's only a flip of a switch.

I do not know, if that works for your codebase: the prerequisites in terms of code quality and developer discipline are quite high - you have to deal with "cleanup" after a feature becomes a core functionality and you have to manage a bunch of toggles preventing a bigger mess.

Perhaps it works for you.

Title: How can we keep track of which version of our code is in each environment?

Body:
My team currently uses a fairly simple branching/deployment process that looks like this:

```<code>                ┌────────┐ ┌────┐ ┌──────┐
 Environments:  │  DEV   │ │ QA │ │ PROD │
                └────────┘ └────┘ └──────┘

                     ▲       ▲       ▲
                     │       │       │

                ┌────────┐ ┌────┐ ┌──────┐
 Builds:        │  DEV   │ │ QA │ │ PROD │
                └────────┘ └────┘ └──────┘

                     ▲       ▲       ▲
                     │       │       │

                ┌────────┐ ┌────┐ ┌──────┐
 Branches:      │ master │ │ qa │ │ prod │
                └────────┘ └────┘ └──────┘
</code>```

Each environment has its own branch (we use git) and its own build that uses that branch.  When we want to promote from one environment to another, for example, from DEV to QA, we merge the master branch into qa and kick off a new QA build (which is then automatically deployed to the QA environment).

We're considering moving to a new process that would do away with having a dedicated branch and build for each environment.  Instead, a single release build would create a "deployment package" which could then be deployed to any environment.  We're imagining a typical workflow would look something like this:

```<code>                ┌────────┐     ┌────┐     ┌──────┐
 Environments:  │  DEV   │ ──► │ QA │ ──► │ PROD │
                └────────┘     └────┘     └──────┘

                      ▲
                       \

                        ┌───────────────┐
 Builds:                │ release build │
                        └───────────────┘

                                ▲
                                │

                ┌────────┐ ┌─────────┐
 Branches:      │ master │ │ release │
                └────────┘ └─────────┘
</code>```

Promoting from one environment to another would no longer be handled in source control; rather, we'd just take the already-built binaries (the "deployment package") and drop that on the new environment.

This new system would allow us to deploy any build to any environment, which has several advantages. For example, it's trivial to test PROD bug fixes in DEV and QA.  Our current system doesn't provide an easy way to do this without rolling back a branch, which we'd obviously like to avoid.

The biggest drawback with this new system is that we no longer have an automatic way of tracking what code is in which environment.  If we need to make a fix in PROD, we no longer have a dedicated branch in sync with the current production codebase.  The same goes for QA - if we want to push a quick change to QA without dredging up in-progress work from master, we no longer have a branch that reflects the current state of the QA environment.

How can we keep track of what code is in each environment?

Some options we're considering:

utilizing git tags to keep track of which commit is in which environment

embedding the git commit used by the build into each deployment package


问:
How to design class model for specific products, some of which may contain groups of specific product models
Class Design Question

I am trying to figure out a good way to design my class system.

I have a class Product to compute various product specifications.  I have two product model groups, each containing several model numbers:  {10, 20, 30} and {50, 60, 70}.  They share some similar features (i.e. the way weight is computed) but have different product add-on computations (i.e. some features depend on product length and some do not, depending on the model group)

The class model I currently have is main Product for all models (actually originally for 50, 60, 70 only), and a specific model Product10 was added on later and works for model 10 only.   Now, a new addition brought on models 20, and 30, which are similar to model 10.  Instead of adding them as separate classes, nearly identical to 10, I thought it was time to redesign.

Problem

In my current implementation, class Product10 is feeding off the main Product class (responsible for "most models") and Product10 is being the odd one out.  Maybe it is fine, but now I am getting more model numbers similar to Product10 and I am seeking a better way to structure my code.

Currently I see that there are quite a few ways to design this.

create a class for each model (may be wasteful)

create a "god class" that contains code for all models (class may be bloated)

create subgroups for models, i.e. one class that covers a set of models like {10, 20, 30} or {50, 60, 70}

something else.

What I seek

I seek a good way to use OO design for my specific situation...  Namely,

I think it is a good idea to have a generic class of some sort

I am not sure whether I should create a class for to represent "a set of similar models" or whether to treat models separately

My goal is to create an appropriate class based on model number.

What could be a good class decomposition?

答:
If all your classes share the same logic, make a base class for it that contains the methods.  All logic that is similar across all Products goes in this base class. For every group of projects that have similar logic for certain methods (e.g. calculating a feature that is the same across models), create a subclass that implements this logic.

Naturally, this only works if the calculation of features is not structured in such a way that it needs to be duplicated 'across'. For example, you can have two features 'Beta' and 'Gamma' that need to be calculated for three types of models A, B and C. If A and B share some calculation logic for 'Beta' you could create a base class for A and B that implements this logic. However, if your calculation for feature 'Gamma' is the same for A and C but not B this won't work.

In that case, I would recommend that you use the Strategy Pattern. Implement feature calculations in separate calculator classes and simply compose your product models by calling the right calculation classes. All models would then simply extend the single base class which defines all 'feature' calculations so the contract across your domain objects is the same.


问:
How useful are function points?
How useful is it to measure function points?

We use function points at my new job.  I've heard of function points but haven't had any training or experience... but I don't have much confidence in things that cannot be explained succinctly.

答:
The use of function points in favor of lines of code seek to address several additional issues:

•   The risk of "inflation" of the created lines of code, and thus reducing the value of the measurement system, if developers are incentivized to be more productive. FP advocates refer to this as measuring the size of the solution instead of the size of the problem.

•   Lines of Code (LOC) measures reward low level languages because more lines of code are needed to deliver a similar amount of functionality to a higher level language. C. Jones offers a method of correcting this in his work.

•   LOC measures are not useful during early project phases where estimating the number of lines of code that will be delivered is challenging. However, Function Points can be derived from requirements and therefore are useful in methods such as estimation by proxy.

Title: How useful are function points?


答:
I am not aware of any standard license that has those attributes.  The "no redistribution" requirement is antithetical to the principles of open source, so none of the existing Open Source licenses will be applicable.

I suggest that you consult a lawyer and get them to help you draft a license that meets your needs.

Don't just do it yourself.  There is a significant risk that a "DIY" license will not mean what you intend it to mean ... when interpreted by legal professionals.  Or, key aspects of your license may be unenforceable.

In response to a couple of points in other Answers:

Licences like Creative Commons (and others like Apache, BSD, GPL, etc) are meant to be templates.

That is not true.  In fact, they are generally intended to be used as-is ... apart from filling in the details of the license granting organisation or person.  If you treat the standard licenses as a template that you can tailor you risk giving away rights that you didn't intend to; see above.

For example: http://www.gnu.org/licenses/gpl-faq.en.html#ModifyGPL

Organisations write their own licences all the time.

Yes organisations >>do<< write their own software licenses, but only with the help of a qualified legal professional

Title: What licenses restrict distribution, liability, and commercial use?

Body: I have to provide my code to someone to look at and use, but wish to maintain a number of rights. Specifically, I want a license that 1) Limits my liability, 2) prevents commercial use and 3) prevents further distribution, including of modified copies. I have been unable to find anything that covers this. The closest I have found is a Creative Commons license, but distribution is still (obviously) allowed.</p>


问:
Unit test structure focused on responsibilities
I'm not going to ask what is the best unit test structure or how to do it again. There are already enough questions about it. Instead I'd like you to tell me what else I could consider in the structure that I came up with (borrowing from other ideas and adding new ones).

I've been thinking about how can I improve my test structure because after writing a few tests it was becoming harder and harder to see what cases I've already covered and which are still missing. A long list of test methods didn't really show what features they were actually testing. They were testing some cases but what kind of cases? They are mostly too unspecific to me. I wanted them to be a documentation of what is required for a class/method to work and how it works rather then what it does if it doesn't or does if it works.

So I flipped the logic and instead of writing what really happens I write what the class/method must recognize as an incorrect or correct usage.

To implement it I added two new layers to the test structure prerequisite tests and usage tests. This allows me to better keep in mind what I have already tested and what is missing. Let's try it on the following (simplified) example:

```<code>public class Configuration
{
     public static XDocument LoadConfiguration(string fileName)
     {
         if (string.IsNullOrEmpty(fileName)) throw new ArgumentNullException("fileName");

         if (!File.Exists(fileName)) throw new FileNotFoundException(fileName);

         return XDocument.Load(fileName);
     }
}
</code>```

To test it I first define (if necessary) some tests for testing the prerequisites that must be satisfied before it is even possible to work with a class or method.

Then I test the different possible usages of the class or method.

```<code>[TestClass]
public class ConfigurationTests
{
    [TestClass]
    public class LoadConfiguration_TestPrerequisites
    {
        [TestMethod]
        public void FileNameMustNotBeNull()
        {
            // assert that ArgumentNullException is thrown when fileName is null
        }

        [TestMethod]
        public void FileNameMustExist()
        {
            // assert that FileNotFoundException is thrown when file doesn't exist
        }
    }

    [TestClass]
    public class LoadConfiguration_TestUsage
    {
        [TestMethod]
        public void MustImportValidXml()
        {
            // assert that configuration was loaded
        }

        [TestMethod]
        public void MustNotImportInvalidXml()
        {
            // assert that some other exception was thrown on invalid xml
        }
    }
}
</code>```

My question is: What other key responsibilities I might be missing here besides prerequisites and usage? Somehow I'm not yet entirely happy with it and my gut tells me that I've overlooked something.

My goal is also to describe (name) the tests more naturally so they better show class/method's responsibilities and not what happens. I find it's easier to understand FileNameMustNotBeNull than Throws_FileNotFoundException. because the implementation may change (I could decide to return a null value if it the file name was null) but it still cannot be null.

答:
Here are some broad categories of tests that might be what you need:

handling invalid input (what you call prerequisites)

correctness of happy-path logic (what you call usage) - this one may be large enough to be worth of decomposing further, but it's case-specific

handling edge cases (where the input is at the edges of valid range)

handling negative cases (testing that something undesired doesn't happen)

I wouldn't call them responsibilities though. A module should have only one responsibility (it's function).

Validation of prerequisites is not some 'secondary' responsibility of a module; it's only a way to ensure that the module is able to process the input (perform it's function) correctly.


问:
Naming conventions for hierarchical roles in an application
I'm creating an application that internally will have have three totally different separated areas of interfaces.

- One where users create content and interact with each other

- One where one person invites the above users and administers her organization's account

- One where several people are administers the whole application

Is User, Admin and SuperAdmin the convention for the above? I particularly dislike User, as everyone touching the application is a user.

The application will be handed over to other people once in production so I want these roles/user areas to make sense for other programmers aswell.

答:
It is hard to guess your domain where more specific roles can be found. Some generic variants though:

Anonymous

Member or Editor or Content editor or just User (why not?)

Manager or User manager (if restricted only to dealing with users, not content). It may also be Group manager, if restricted to some group of users

Administrator or Superadmin(*)

(*) I'd reserved Superadmin for a multi-tenant system. And superadmin can create organizations and do similar tasks. Maybe it is your case, maybe not.

Do not forget, that role is something, which may be contextual (local roles). Also, user might have several roles at the same time and context. So, User may be the least specific role, while the user may have Editor or Manager role.

It is probably good idea to make role/permission system one bit more flexible than current requirements are.

Edit: Let me stress once more, that naming should come as a result of the domain itself. Domain analysis in some form should be performed for any software project, common names and language established, ideally, same language between developers and other stakeholders. Usually problem domain names are used (because those are more likely to be correctly understood by users). In some cases using solution domain concepts may be inevitable.


问:
What does your Technical Documentation look like?
I'm working on a large project and I would like to put together some technical documentation for other members of the team and for new programmers joining the project.

What sort of documentation should I have? Just /// code comments or some other file(s) explaining the architecture and class design?

I've never really done documentation except the occasional word doc to go with smaller apps, and I think this project is too large to doc in a single word file.

答: For newbies you should also briefly document your source code structure, the check-in/out processes, where to find tools, etc. Then, when a new person comes on board, have them update the doc and add whatever they feel was missing.</p>


问:
Should Git be used for documentation and project management? Should the code be in a separate repository?
I'm starting up a Git repository for a group project. Does it make sense to store documents in the same Git repository as code - it seems like this conflicts with the nature of the git revision flow.

Here is a summary of my question(s):

Is the Git revisioning style going to be confusing if both code and documents are checked into the same repository? Experiences with this?

Is Git a good fit for documentation revision control?

I am NOT asking if a Revision Control System in general should or shouldn't be used for documentation - it should.

Thanks for the feedback so far!

答: In code, thoughts are typically separated line-by-line. I tend to write documentation with soft line wraps. When I commit those files, lines are a whole paragraph long. That's not very useful to read in git diff. That's the problem I was trying to solve when I Googled and found this page. Thanks to Arne Hartherz for introducing me to git diff --word-diff. You might like git diff --color-words even better.

OwnerDisplayName: EmpireJones