问:
Move semantics in C++ - Move-return of local variables
My understanding is that in C++11, when you return a local variable from a function by value, the compiler is allowed to treat that variable as an r-value reference and 'move' it out of the function to return it (if RVO/NRVO doesn't happen instead, of course).

My question is, can't this break existing code?

Consider the following code:

```<code>#include <iostream>
#include <string>

struct bar
{
  bar(const std::string& str) : _str(str) {}
  bar(const bar&) = delete;
  bar(bar&& other) : _str(std::move(other._str)) {other._str = "Stolen";}
  void print() {std::cout << _str << std::endl;}

  std::string _str;
};

struct foo
{
  foo(bar& b) : _b(b) {}
  ~foo() {_b.print();}

  bar& _b;
};

bar foobar()
{
  bar b("Hello, World!");
  foo f(b);

  return std::move(b);
}

int main()
{
  foobar();
  return EXIT_SUCCESS;
}
</code>```

My thoughts were that it would be possible for a destructor of a local object to reference the object that gets implicitly moved, and therefore unexpectedly see an 'empty' object. I tried to test this (see http://ideone.com/ZURoeT ), but I got the 'correct' result without the explicit std::move in foobar(). I'm guessing that was due to NRVO, but I didn't try to rearrange the code to disable that.

Am I correct in that this transformation (causing a move out of the function) happens implicitly and could break existing code?

UPDATE
Here is an example which illustrates what I'm talking about. The following two links are for the same code.
http://ideone.com/4GFIRu - C++03
http://ideone.com/FcL2Xj - C++11

If you look at the output, it's different.

So, I guess this question now becomes, was this considered when adding implicit move to the standard, and it was decided that it was OK to add this breaking change as this kind of code is rare enough? I also wonder if any compilers will warn in cases like this...

答:
Scott Meyers posted to comp.lang.c++ (August 2010) about a problem where implicit generation of move constructors could break C++03 class invariants:

```<code>struct X
{
  // invariant: v.size() == 5
  X() : v(5) {}

  ~X() { std::cout << v[0] << std::endl; }

private:
  std::vector<int> v;
};

int main()
{
    std::vector<X> y;
    y.push_back(X()); // X() rvalue: copied in C++03, moved in C++0x
}
</code>```

Here the problem is that in C++03, X had an invariant that its v member always had 5 elements. X::~X() counted on that invariant, but the newly-introduced move constructor moved from v, thereby setting its length to zero.

This is related to your example since the broken invariant is only detected in the X's destructor (as you say it's possible for a destructor of a local object to reference the object that gets implicitly moved, and therefore unexpectedly see an empty object).

C++11 try to achieve a balance between breaking some of existing code and providing useful optimizations based on move constructors.

Committee initially decided that move constructors and move assignment operators should be generated by the compiler when not provided by the user.

Then decided that this was indeed cause for alarm and it restricted the automatic generation of move constructors and move assignment operators in such a way that it is much less likely, though not impossible, for existing code to break (e.g. explicitly defined destructor).

It’s tempting to think that preventing the generation of implicit move constructors when a user-defined destructor is present is enough but it's not true (N3153 - Implicit Move Must Go for further details).

In N3174 - To Move or not to Move Stroupstrup says:

I consider this a language design problem, rather than a simple backwards
  compatibility problem. It is easy to avoid breaking old code (e.g. just
  remove move operations from C++0x), but I see making C++0x a better language
  by making move operations pervasive a major goal for which it may be worth
  breaking some C++98 code.

Body:
Scott Meyers posted to comp.lang.c++ (August 2010) about a problem where implicit generation of move constructors could break C++03 class invariants:

struct X
{
  // invariant: v.size() == 5
  X() : v(5) {}

  ~X() { std::cout << v[0] << std::endl; }

private:
  std::vector<int> v;
};

int main()
{
    std::vector<X> y;
    y.push_back(X()); // X() rvalue: copied in C++03, moved in C++0x
}

Here the problem is that in C++03, X had an invariant that its v member always had 5 elements. X::~X() counted on that invariant, but the newly-introduced move constructor moved from v, thereby setting its length to zero.

This is related to your example since the broken invariant is only detected in the X's destructor (as you say it's possible for a destructor of a local object to reference the object that gets implicitly moved, and therefore unexpectedly see an empty object).

C++11 try to achieve a balance between breaking some of existing code and providing useful optimizations based on move constructors.

Committee initially decided that move constructors and move assignment operators should be generated by the compiler when not provided by the user.

Then decided that this was indeed cause for alarm and it restricted the automatic generation of move constructors and move assignment operators in such a way that it is much less likely, though not impossible, for existing code to break (e.g. explicitly defined destructor).

It’s tempting to think that preventing the generation of implicit move constructors when a user-defined destructor is present is enough but it's not true (N3153 - Implicit Move Must Go for further details).

In N3174 - To Move or not to Move Stroupstrup says:

I consider this a language design problem, rather than a simple backwards
  compatibility problem. It is easy to avoid breaking old code (e.g. just
  remove move operations from C++0x), but I see making C++0x a better language
  by making move operations pervasive a major goal for which it may be worth
  breaking some C++98 code.


问:
What can slow a developer down?
What things tend to slow a developer down?

Please try to refrain from posting answers that:

are slow now but useful in the feature. (TDD, Refactoring, ...)

list a distraction.

答:
The Much That Slows You Down is a good blog post for this.

...

Many projects repeat core infrastructure-level features over and over, slowing that business down in delivering features that differentiate the business from its competitors.

...

It is inevitable that products and innovations will help reduce the time developers spend on non-differentiating tasks. The question is what form those services and tools will take.

...

ContentLicense: CC BY-SA 2.5

Title: What can slow a developer down?


问:
Best way to handle delimited files
So typically a CSV file uses a comma and the return character as it's field and line delimiters.

This runs into obvious problems with text which can contain both these characters.

Obviously there are options there (escaping them) but how do people handle this?  Use different characters - pipes or tildas?  Escape them?  Not use delimited files, after all it's 2010 and we have XML now?

Looking at least effort for a decent chance of not seeing problems.

(Just to be clear, this is a question out of curiosity rather than something more solid - it's something I've come up against time and time again playing with data, always got round it but it normally feels a bit, well, dirty, and wondered what other people's experience was).

答:
According to Wikipedia:

Fields with embedded commas must be enclosed within double-quote characters.

And furthermore:

Fields with embedded double-quote characters must be enclosed within double-quote characters, and each of the embedded double-quote characters must be represented by a pair of double-quote characters.

I don't know who invented that, but it effectively shows that eventually you have to escape. It's the only solid solution. Everything else is just duct tape on top of duct tape: maybe works for now, but eventually you'll bump on a case where you need an exception to the exception of an exception, and it doesn't take long before your mudball of rules is way more complex than a simple escape character solution had been.

It seems that CSV creators first tried to avoid escaping commas by coming up with double-quoted special syntax, which allowed saving commas, but then someone wanted to save double-quote characters too, so they had to escape at that point - funnily using the double-quote as an escape character. Had they decided to escape properly in the first place, the syntax would be simpler now.

Title: Best way to handle delimited files


问:
Setting fields of a base class when using the constructor is not an option
I am refactoring  a base class, implementations of which are plug-ins, loaded at runtime by another class using reflection.

The class I am refactoring uses a user ID of the form domain\user.  I need to extend it to also work with domain email addresses.

To do this, I have introduced an enum of user identifier types, e.g UserIdentifierType.DomainUser, UserIdentifierType.SmtpAddress, UserIdentifierType.SomeFutureType.

In order for the class to work, the user identifier type must be set.

My usual approach would be to create a constructor which takes the required identifier type as an argument but the problem I have is that the class consuming it only knows how to call the empty constructor.  It is not feasible to change the consuming class.

Instead, I have implemented an initialising method:

```<code>public void Initialise(UserIdentifierType userIdentifierType)
{
    _initialised = true;
}
</code>```

Each method of the base class checks that the initialiser has been called and throws an exception if not.

```<code>if(!_initialised){throw new Exception("The Initialise() method must be called before using any other methods of this class");}
</code>```

To me, that smells worse than my socks!  It's not transparent, it's not self documenting and doesn't fit the principles of OOP.

Is there some neater way to accomplish setting the identifier type in the base instance without using a constructor or an initialiser?

答:
It sounds like your problem, in short, is that you have to make a backwards-incompatible change to a public class with multiple clients which you do not control.

The usual way to deal with such backwards compatibility issues is not to change the existing code at all. Instead, you provide an entirely new API which implements the new backwards-incompatible functionality and announce that the old class is deprecated.

Now you can gradually cajole your clients into changing their code to use your new class. Once all your users (or at least all the users you care about) are using the new and improved API, you can revoke support for the old class and/or delete it.

This sounds like a lot of work, and indeed it is. For code with lots of clients (frameworks and platforms in particular) it can even take years. But the alternative is breaking all your API clients with no warning, pissing everyone off, losing their business and going bust.

ContentLicense: CC BY-SA 3.0


问:
RESTful API: HTTP verbs with shared or specific URLs?
While creating a RESTful API, should I use HTTP Verbs on the same URL (when it's possible) or should I create an specific URL per action?

For example:

```<code>GET     /items      # Read all items
GET     /items/:id  # Read one item
POST    /items      # Create a new item
PUT     /items/:id  # Update one item
DELETE  /items/:id  # Delete one item
</code>```

Or with specific URLs like:

```<code>GET     /items            # Read all items
GET     /item/:id         # Read one item
POST    /items/new        # Create a new item
PUT     /item/edit/:id    # Update one item
DELETE  /item/delete/:id  # Delete one item
</code>```

答:
In your latter scheme, you keep verbs in the URLs of your resources. This should be avoided as the HTTP verbs should be used for that purpose. Embrace the underlying protocol instead of ignoring, duplicating or overriding it.

Just look at DELETE  /item/delete/:id, you place the same information twice in the same request. This is superfluous and should be avoided. Personally, I'd be confused with this. Does the API actually support DELETE requests? What if I place delete in the URL and use a different HTTP verb instead? Will it match anything? If so, which one will be chosen? As a client of a properly designed API, I shouldn't have to ask such questions.

Maybe you need it to somehow support clients that cannot issue DELETE or PUT requests. If that's the case, I'd pass this information in an HTTP header. Some APIs use an X-HTTP-Method-Override header for this specific purpose (which I think is quite ugly anyway). I certainly wouldn't place the verbs in the paths though.

Go for

```<code>GET     /items      # Read all items
GET     /items/:id  # Read one item
POST    /items      # Create a new item
PUT     /items/:id  # Update one item
DELETE  /items/:id  # Delete one item
</code>```

What's important about the verbs is that they are already well-defined in the HTTP specification and staying in line with these rules allows you to use caches, proxies and possibly other tools external to your application that understand the semantics of HTTP but not your application semantics. Please note that the reason you should avoid having them in your URLs is not about RESTful APIs requiring readable URLs. It's about avoiding unnecessary ambiguity.

What's more, a RESTful API can map these verbs (or any subset thereof) to any set of application semantics, as long as it doesn't go against the HTTP specification. For example, it is perfectly possible to build a RESTful API that only uses GET requests if all operations that it allows are both safe and idempotent. The above mapping is just an example that fits your use case and is compliant with the spec. It doesn't necessarily have to be like this.

Please also mind that a truly RESTful API should never require a programmer to read extensive documentation of available URLs as long as you conform to the HATEOAS (Hypertext as the Engine of Application State) principle, which is one of the core assumptions of REST. The links can be utterly incomprehensible to humans as long as the client application can understand and use them to figure out possible application state transitions.

Body:
In your latter scheme, you keep verbs in the URLs of your resources. This should be avoided as the HTTP verbs should be used for that purpose. Embrace the underlying protocol instead of ignoring, duplicating or overriding it.

Just look at DELETE  /item/delete/:id, you place the same information twice in the same request. This is superfluous and should be avoided. Personally, I'd be confused with this. Does the API actually support DELETE requests? What if I place delete in the URL and use a different HTTP verb instead? Will it match anything? If so, which one will be chosen? As a client of a properly designed API, I shouldn't have to ask such questions.

Maybe you need it to somehow support clients that cannot issue DELETE or PUT requests. If that's the case, I'd pass this information in an HTTP header. Some APIs use an X-HTTP-Method-Override header for this specific purpose (which I think is quite ugly anyway). I certainly wouldn't place the verbs in the paths though.

Go for

GET     /items      # Read all items
GET     /items/:id  # Read one item
POST    /items      # Create a new item
PUT     /items/:id  # Update one item
DELETE  /items/:id  # Delete one item

What's important about the verbs is that they are already well-defined in the HTTP specification and staying in line with these rules allows you to use caches, proxies and possibly other tools external to your application that understand the semantics of HTTP but not your application semantics. Please note that the reason you should avoid having them in your URLs is not about RESTful APIs requiring readable URLs. It's about avoiding unnecessary ambiguity.

What's more, a RESTful API can map these verbs (or any subset thereof) to any set of application semantics, as long as it doesn't go against the HTTP specification. For example, it is perfectly possible to build a RESTful API that only uses GET requests if all operations that it allows are both safe and idempotent. The above mapping is just an example that fits your use case and is compliant with the spec. It doesn't necessarily have to be like this.

Please also mind that a truly RESTful API should never require a programmer to read extensive documentation of available URLs as long as you conform to the HATEOAS (Hypertext as the Engine of Application State) principle, which is one of the core assumptions of REST. The links can be utterly incomprehensible to humans as long as the client application can understand and use them to figure out possible application state transitions.


问:
Client vs Creator in Factory Method and Abstract Factory patterns
This page descibes one important difference between Factory Method and Abstract Factory:

http://architects.dzone.com/articles/factory-method-vs-abstract

The difference, according to this page, is that in Factory Method pattern the Creator (i.e. the entity creating new objects) and the Client (i.e. the entity using the Creator) are the same class. More precisely, this pattern only defines a method, so the rest of the class is the Client. In Abstract Factory however, the Creator and the Client are separate classes. The Creator's only purpose is to create objects so only a separate class can be the Client.

Is this distinction correct? If so, why can't the Creator method in the Factory Method be put in a separate class? Would it create any problems? Similarly, why can't the Creator class in the Abstract Factory be the same class as the Client? Would this create any problems?

Update:

Just as a side note: it's SHOCKING to me too see that when I ask about such well known and (what should be) well defined design patterns I get actually contradictory answers. And it's not just this thread - the more and more I ask people (or search online resources) about the basic design patterns the more I start to think that people don't actually TRULY understand them even though they're using them on a daily basis and they believe they understand them.

答:
This Client vs Consumer is core defining feature whenever creation pattern is Factory Method or Abstract Factory. If Client and Consumer are same class, then it is Factory method, if they are different, it is an Abstract factory.

If so, why can't the Creator method in the Factory Method be put in a separate class?

You just created Abstract Factory pattern.

Similarly, why can't the Creator class in the Abstract Factory be the same class as the Client?

Then you reduced the whole Abstract Factory into a Factory Method.


问:
DAL / Model / Application-Design Question for a MVC Application
I have a device that stores raw binary log data as a BLOB in a MySQL DB. That process is a blackbox to me (closed source) which I cannot change. I know, however, how to decode that BLOB and transform it into some human readable data.
Inside that BLOB data stream various information is stored, such as dates, text messages, severity, errors, and so on I later want to present to the user calling my ASP.NET MVC application.

The way I'm doing it now is on the fly, meaning that the data is converted into a human readable format in my DAL layer of the ASP.NET application whenever the data is requested. The DAL layer in turn is consumed by the Model of the MVC application.

As the log data DB gets larger and larger I'm not sure if this is the right approach for a couple of reasons:
For example, as the log data is binary, all sorting / filtering / etc. has to be done by querying ALL the records, converting it to a human readable format, and perform the sorting / filtering / ... on the converted in-memory dataset.

I thought about the alternatives and came to the following conclusion:

1.) Run a cron / scheduled / whatever job every n minutes and convert the new binary log data to something human readable and store that in the DB. I would have to keep track of the already converted rows, but that's easy. This intermediate layer however would not be part of my ASP.NET application and as such would have to be maintained and tested separately. This is not that important. However, going that route would mean that the user would always miss the log data that accumulated between the last transformation run and now, in the worst case n minutes. A possible workaround would be to run that cronjob within a very tight schedule (like every 10 seconds or so).

2.) Use an insert trigger on the MySQL DB that immediately converts the data. Unfortunately, I'm afraid that I cannot use SQL/PSM to convert the data so I'd need a custom UDF written in C. Unfortunately, I'm not much of a C programmer and I'm lacking the fundamentals on how to write custom UDFs for MySQL.

3.) Keep things the way the are now, which will surely degenerate performance over time as I cannot use efficient indices on the raw BLOB data or perform any filtering / sorting operations on the DB side.

So that's where I'm standing right now. The question is are there any OTHER approaches that come to your mind I haven't thought of? Has anybody ever done something similar, and if so, what approach did you take?

答:
Your first option -- write something to convert it into normal DB data -- is the right way to go here for a few reasons. It makes development easier as you have a clean demarcation of roles and you can get a functioning data processing app on one hand and test the front-end against test data on the other hand.

This code can be in C# and can even be in the same solution as the web app so you can work on them in concert if need be. They could even share some library level code if necessary opening things up to having some live decoding in the web app.


答:
The first one.

A URI/URL is a resource identifier (hint in the name: uniform resource identifier). With the first convention, the resource being talked about when you do "GET /user/123" and the resource being talked about when you do "DELETE /user/123" is clearly the same resource because they have the same URL.

With the second convention, you cannot be sure that "GET /user/123" and "DELETE /user/delete/123" actually are the same resource, and it seems to imply that you're deleting a related resource rather than the resource itself, so it would be rather surprising that deleting /user/delete/123 actually deletes /user/123. If you have every operations work on different URLs, the URI is no longer working as a resource identifier.

When you say DELETE /user/123, you are saying "delete 'user record with id 123'". While if you say DELETE /user/delete/123, what you seem to be implying is to "delete 'user deletor record with id 123'", which is probably not what you want to say. And even if you use the more correct verb in this situation: "POST /user/delete/123" which says "do the operation attached to 'user deletor with id 123'", it is still a roundabout way to say delete a record (this is akin to nounification of a verb in English).

One way you can think about URL is to treat it like pointers to objects and resources as objects in object-oriented programming. When you do GET /user/123, DELETE /user/123, you can think think of them as methods in the object: [/user/123].get(), [/user/123].delete() where the [] is like a pointer dereferencing operator but for URLs (if you know a language that have pointers). One of the underlying principle of REST is uniform interface, i.e. to have a small and limited set of verbs/methods that works for everything in a vast network of resources/objects.

Therefore, the first one is better.

PS: of course, this is looking at REST in the purest manner. Sometimes practicality beats purity, and you need to make concessions for brain-dead clients or framework that makes it hard to do proper REST.

Title: RESTful API: HTTP verbs with shared or specific URLs?

Body:
While creating a RESTful API, should I use HTTP Verbs on the same URL (when it's possible) or should I create an specific URL per action?

For example:

```<code>GET     /items      # Read all items
GET     /items/:id  # Read one item
POST    /items      # Create a new item
PUT     /items/:id  # Update one item
DELETE  /items/:id  # Delete one item
</code>```

Or with specific URLs like:

```<code>GET     /items            # Read all items
GET     /item/:id         # Read one item
POST    /items/new        # Create a new item
PUT     /item/edit/:id    # Update one item
DELETE  /item/delete/:id  # Delete one item
</code>```


答:
(sorry, my first time through I missed the /edit/ and /delete/ in (2)... )

The idea of the URI is that it is an identifier of an addressable resource, rather than a method invocation. So the URI should point to a specific resource. And if you deference the URI, you should always get the same resource.

That is, you should think about URIs in the same way you think about the Primary Key of a row in a database. It uniquely identifies something: Universal Resource Identifier.

So whether you use plural or singular, the URI should be an identifier rather than an invocation. What you're trying to do goes in the method, namely: GET (get), PUT (create/update), DELETE (delete) or POST (everything else).

So "/item/delete/123" breaks REST because it doesn't point to a resource, it's more of a method invocation.

(Also, just semantically, you should be able to GET a URI, decide it's outdated, and then DELETE the same URI -- because it is an identifier. If the GET URI doesn't have "/delete/" and DELETE does, then that goes against HTTP semantics. You're broadcasting 2 or more URIs per resource where 1 will do.)

Now, the cheat is this: there's no real clear definition of what is and isn't a resource, so the common dodge in REST is to define a "processing noun" and point the URI to that. That's pretty much a word game, but it satisfies the semantics.

So if, for example, you really couldn't use this for some reason:

```<code>DELETE /items/123
</code>```

you could declare to the world you have a "deletor" processing resource and use

```<code>POST /items/deletor  { id: 123 }
</code>```

Now, that looks a lot like RPC (Remote Procedure Call), but it falls through the vast loophole of the POST specification's "data processing" clause named in the HTTP spec.

However, doing that is kind of exceptional, and if you can use the common PUT for create / update, DELETE for delete, and POST for append, create, and everything else, then you should, because it's a more standard use of HTTP. But if you have a tricky case like "commit" or "publish" or "redact", then the case for using a processor noun satisfies the REST purists and still gives you the semantics you need.

Body:
(sorry, my first time through I missed the /edit/ and /delete/ in (2)... )

The idea of the URI is that it is an identifier of an addressable resource, rather than a method invocation. So the URI should point to a specific resource. And if you deference the URI, you should always get the same resource.

That is, you should think about URIs in the same way you think about the Primary Key of a row in a database. It uniquely identifies something: Universal Resource Identifier.

So whether you use plural or singular, the URI should be an identifier rather than an invocation. What you're trying to do goes in the method, namely: GET (get), PUT (create/update), DELETE (delete) or POST (everything else).

So "/item/delete/123" breaks REST because it doesn't point to a resource, it's more of a method invocation.

(Also, just semantically, you should be able to GET a URI, decide it's outdated, and then DELETE the same URI -- because it is an identifier. If the GET URI doesn't have "/delete/" and DELETE does, then that goes against HTTP semantics. You're broadcasting 2 or more URIs per resource where 1 will do.)

Now, the cheat is this: there's no real clear definition of what is and isn't a resource, so the common dodge in REST is to define a "processing noun" and point the URI to that. That's pretty much a word game, but it satisfies the semantics.

So if, for example, you really couldn't use this for some reason:

DELETE /items/123

you could declare to the world you have a "deletor" processing resource and use

POST /items/deletor  { id: 123 }

Now, that looks a lot like RPC (Remote Procedure Call), but it falls through the vast loophole of the POST specification's "data processing" clause named in the HTTP spec.

However, doing that is kind of exceptional, and if you can use the common PUT for create / update, DELETE for delete, and POST for append, create, and everything else, then you should, because it's a more standard use of HTTP. But if you have a tricky case like "commit" or "publish" or "redact", then the case for using a processor noun satisfies the REST purists and still gives you the semantics you need.


问:
Is there a good way (pattern) for adding a state to a finite state machine
So I'm working on a roguelike, and planning to represent the monsters using a finite state machine

```<code>          spot PC
wander------------------->move
  ^   ^                    |
  |      \                 |
  |         \ killed PC    |
  |evaded       \          | close
  |                 \      |
  |         hurt        \  V
 flee<-------------------attack
</code>```

However, I wanted to be able to change the monsters FSM, as the monster is modified.  For example, in the game, it is possible the monster may have a health potion.  In that case, the FSM should look like this:

```<code>wander------------------->move
                            |
                            |
                            |
                            | close
            used potion     |
       ,-----------------V  V
 use potion              attack
       ^-------------------'
              hurt
</code>```

And then, once the potion is used up, return to the previous FSM.  My thought is that I should change the FSM at the time the potion is given to the monster, so potion.give(monster) modifies the FSM at that time, and potion.use() unmodifies it.  But I'm not sure how to implement this?  How can the potion object know what states it should bind to, or transition back to?

One possible thought was to have the FSM state transition binding be a stack.  So picking up a potion adds use potion to the attack['hurt'] transition stack.

Is there a best practice, or can someone link to an example of how to modify a FSM at runtime?

答:
Lets assume we have a class that looks something like this:

```<code>class State {
  String description;
  List triggerStateTuple;
  Action onEnter;
}
</code>```

Then you've got a list of (Trigger, State) tuples which you walk the list, select one, move to the next state and invoke the onEnter.

One approach to this is to avoid trying to do the 'this is getting inserted or removed' and instead build up the huge state table of all possible events with a more complex Trigger.  Instead of working off of 'all items in the list are valid' it would instead have to do a 'check if this can be triggered'.  The advantage here is that you build it once and its done rather than having to rebuild it on the fly.

That rebuild on the fly is where it is likely getting tricky for you.  You need to know where to put the trigger (what states is it valid in?).  What happens after the potion is drunk? Well, you would need to remove it from all the associated states.  This gets rather messy too.  The logic gets more complex... what happens if you have two health potions and your monster drinks one - gotta make sure you don't remove both of the triggers.

As you can see, this can get complex.  When an item is added (or removed) from the inventory, it needs to add (or remove) itself from the different states that it can hook into.  One could see modifying the tuple to also contain the object (for easy removal from the state).

When an object is added to the inventory, the list of states that it can hook into is pulled from the object and then all the states with a matching description have the trigger added.  This involves some choreography of events.  You're going to likely want a 'use' state that the object can link to that then when the action is triggered, invokes the action back in the object.

Though, I will also point out that 'use' isn't really a state.  It's a one off event that doesn't change the state from 'attack'.

When reading through this, this becomes something that feels more like a rules engine than a simple FSM.  The logic is getting more complex and you can start to suffer with difficulties debugging it.  Instead, you might want to look at an embedded rules engine of some sort and then coding against that.

In Java, the rules engines are things that you can find looking for JSR 94.  Other systems have their own ways to implement rules engines (DTRules has its own DSL).  Some approaches are straight up implementations of prolog.

The approach that nethack has for the 'can a monster use this' is in Muse.c which is a huge, hard coded decision tree.

So... your alternatives:

Lots of hooks and book keeping on the finite state machine

A large, hard coded FSM (build it all out up front)

Using a rules engine or rules oriented language

A large, hard coded rules engine (nethack)

Body:
Lets assume we have a class that looks something like this:

class State {
  String description;
  List triggerStateTuple;
  Action onEnter;
}

Then you've got a list of (Trigger, State) tuples which you walk the list, select one, move to the next state and invoke the onEnter.

One approach to this is to avoid trying to do the 'this is getting inserted or removed' and instead build up the huge state table of all possible events with a more complex Trigger.  Instead of working off of 'all items in the list are valid' it would instead have to do a 'check if this can be triggered'.  The advantage here is that you build it once and its done rather than having to rebuild it on the fly.

That rebuild on the fly is where it is likely getting tricky for you.  You need to know where to put the trigger (what states is it valid in?).  What happens after the potion is drunk? Well, you would need to remove it from all the associated states.  This gets rather messy too.  The logic gets more complex... what happens if you have two health potions and your monster drinks one - gotta make sure you don't remove both of the triggers.

As you can see, this can get complex.  When an item is added (or removed) from the inventory, it needs to add (or remove) itself from the different states that it can hook into.  One could see modifying the tuple to also contain the object (for easy removal from the state).

When an object is added to the inventory, the list of states that it can hook into is pulled from the object and then all the states with a matching description have the trigger added.  This involves some choreography of events.  You're going to likely want a 'use' state that the object can link to that then when the action is triggered, invokes the action back in the object.

Though, I will also point out that 'use' isn't really a state.  It's a one off event that doesn't change the state from 'attack'.

When reading through this, this becomes something that feels more like a rules engine than a simple FSM.  The logic is getting more complex and you can start to suffer with difficulties debugging it.  Instead, you might want to look at an embedded rules engine of some sort and then coding against that.

In Java, the rules engines are things that you can find looking for JSR 94.  Other systems have their own ways to implement rules engines (DTRules has its own DSL).  Some approaches are straight up implementations of prolog.

The approach that nethack has for the 'can a monster use this' is in Muse.c which is a huge, hard coded decision tree.

So... your alternatives:

Lots of hooks and book keeping on the finite state machine

A large, hard coded FSM (build it all out up front)

Using a rules engine or rules oriented language

A large, hard coded rules engine (nethack)


问:
local communications between two apps
To make a platform-independent program in C++ I want to separate the GUI (separate for each OS, using native libraries/APIs) and the actual program. Obviously those two need to communicate with each other.

Doing that by saving and reading XML files would be one solution. As it is kind of slow/always needs to be checked for changes, I would rather prefer a solution where the processing part of the program offers a "server" on localhost and the GUI communicates with that "server". What do you think of this approach? And how would I do it technically?

答:
You are dealing with a problem of inter-process communication with the constraint that this needs to be platform independent and with the other constraint (that frees up more design options) that its on the same machine.

There is nothing inherently wrong with this approach.  I recall Mathematica uses this approach (the calculation engine ('kernel') and the gui are two separate parts - this allowed you to run it on the same machine, or put the calculation engine on a headless unix box out there and display the gui on your desktop).  There are many reasons why this structure works and works nicely.

On the other hand, you are adding complexity to the system by separating the two parts so strictly.  This can be a good, or it might not.  Another bit with such a structure is that the arms length distance between the two parts can allow for some easier licensing options (the gui has a GPL library in it, but you don't want to GPL the backend).

Similar things are also done with other client/server systems.  Perforce (a version control system) has a server and clients (custom build for each platform) - keeping the client and the server as very distinct programs helps maintain a separation of concerns rather than having a giant application that can be harder to maintain.

Straight up linking of the application as one application can be the simplest approach with the fewest design issues... but since you don't want to do that...

The shared resource

The shared file

The simplest is that of a shared file (or files) that each write to and read from.  Thats really easy (I recall a game from the early days - Spaceward Ho that used a shared file for a local area game).  It works, though it is kind of clunky.

The shared fifo

A variation on this is a named pipe which looks like a file, but isn't.  Well, it is a file, in that it's a file, but it's actually the output (or input) of a program that can be accessed as if it was a file.

The shared memory

You could also go with a segment of memory that multiple processes can write to. A nice bit about shared memory is that it is harder to eavesdrop on its communication (if that is an issue).  It can also be rather fast.  This does take appropriate synchronization of the resource.  With files and fifos, the OS often has a little bit of safety to prevent you from stepping on your toes too hard (the file is locked, you an't write to it).  Shared memory doesn't have as strong protections from shooting yourself in the foot.

Signals

Most systems have some sort of signals.  This works, but isn't able to carry data.  Its more like "hey, wake up!" type information.  So, while I am listing it here, it isn't what you are looking for at all.

Sockets

You are likely working on a system that allows for socket based communication.  You can open up a socket (listening on localhost) and put data in it.  It's really quite straight forward.  It works nicely for 1:1 communication... though if you have multiple clients possibly running things could get a bit hairy if you aren't expecting it.

Messages

Message queues

You can fire up (or embed) one of an enormous list of message queues.  The names you'll hear most often are ActiveMQ, ZeroMq, and RabbitMQ.  They all are worth looking into.  If you are open to other options, there are a number of commercial entries into this area.  These have the advantage that if you wanted to do something other than C++ as a client language (say, you find that your front end would be better served with .Net on a windows box), it is still easy to use this.

Message passing (remote method invocation / remote procedure call)

Staying within a language framework gives you some other options.  Within Java, for example, there's Java's RMI which allows you to call one a method in one JVM from another another JVM.

C++ doesn't have RPC or RMI build in, but there are numerous libraries out there that provide this.  Options like XML-RPC.  I'll make mention of thrift as something and that its also cross language.

Title: local communications between two apps


答:
One way you could implement this:

```<code>          spot PC
wander------------------->move
  ^   ^                    |
  |      \                 |
  |         \ killed PC    |
  |evaded       \          | close
  |                 \      |
  |  hurt and no potion \  V
 flee<-------------------attack
                         ^ |
                         | |
             potion used | | hurt and have potion
                         | |
                         | v
                      use potion
</code>```

Although you probably would want to separate between strategy and tactics. Strategy can be modelled as a state machine, while the tactical parts of the monster can be modelled with a rules table as described in another answer. The monster strategy is basically the monster's "mood", either the monster is in a "fight" mood or "flight" mood. A monster may switch to "fight" mood when he's healthy or just recovered, while they can get into "flight" mood when they're low on health or when they encounter an opponent far above their own level. When the monster's strategy changes, then the rules table also changes.

Title: Is there a good way (pattern) for adding a state to a finite state machine

Body:
So I'm working on a roguelike, and planning to represent the monsters using a finite state machine

```<code>          spot PC
wander------------------->move
  ^   ^                    |
  |      \                 |
  |         \ killed PC    |
  |evaded       \          | close
  |                 \      |
  |         hurt        \  V
 flee<-------------------attack
</code>```

However, I wanted to be able to change the monsters FSM, as the monster is modified.  For example, in the game, it is possible the monster may have a health potion.  In that case, the FSM should look like this:

```<code>wander------------------->move
                            |
                            |
                            |
                            | close
            used potion     |
       ,-----------------V  V
 use potion              attack
       ^-------------------'
              hurt
</code>```

And then, once the potion is used up, return to the previous FSM.  My thought is that I should change the FSM at the time the potion is given to the monster, so potion.give(monster) modifies the FSM at that time, and potion.use() unmodifies it.  But I'm not sure how to implement this?  How can the potion object know what states it should bind to, or transition back to?

One possible thought was to have the FSM state transition binding be a stack.  So picking up a potion adds use potion to the attack['hurt'] transition stack.

Is there a best practice, or can someone link to an example of how to modify a FSM at runtime?

Body:
One way you could implement this:

          spot PC
wander------------------->move
  ^   ^                    |
  |      \                 |
  |         \ killed PC    |
  |evaded       \          | close
  |                 \      |
  |  hurt and no potion \  V
 flee<-------------------attack
                         ^ |
                         | |
             potion used | | hurt and have potion
                         | |
                         | v
                      use potion

Although you probably would want to separate between strategy and tactics. Strategy can be modelled as a state machine, while the tactical parts of the monster can be modelled with a rules table as described in another answer. The monster strategy is basically the monster's "mood", either the monster is in a "fight" mood or "flight" mood. A monster may switch to "fight" mood when he's healthy or just recovered, while they can get into "flight" mood when they're low on health or when they encounter an opponent far above their own level. When the monster's strategy changes, then the rules table also changes.


问:
How should I remember what I was doing and why on a project three months back?
I was working on a project three months back, and then suddenly another urgent project appeared and I was asked to shift my attention.

Starting tomorrow, I'll be heading back to the old project. I realize that I do not remember what exactly I was doing. I don't know where to begin.

How can I document a project such that anytime I look back it shouldn't take me more than a few minutes to get going from wherever I left. Are there best practices?

答:
I keep a daily journal of the work I do. What did I do today, what was difficult today, what is the next step, what ideas did I have today for the future. I also add a bit of narrative about what the day was like: was there an interesting conversation or meeting? Did something anger or delight? This helps to put things into perspective when I later read my journal.

When I come back to a project after a while, I read the last few entries in the journal to get up to speed with the project. All those little day to day details are incredibly important for remembering the development process. They really make lot of difference compared to a todo list or regular project documentation, since they remind you of what it was like to work on the project, and not just how to use the product.


问:
How to handle configuration of Python modules, especially when used standalone and in frameworks like Django
I am trying to package a Python module for pip, following the guide here.

One area I would like feedback on is best practices or convention for making my module configurable. The module is a library for talking to federated RESTful services / local datastores, and we use it both as a command-line library as well as a Django app. So I would like it to be manually configurable as well as configurable from Django's settings.py file.

Our current method of doing this is horrible -- it relies on a set of settings.py files inside of the library, which are overwritten whenever we pull from git, not changeable during runtime, etc.

My idea for a solution is to wrap the entire library in its own class, and in the __init__ method, do something like:

```<code>try:
    from django.conf import settings
    self._remote_host = settings.REMOTE_HOST
except:
    self._remote_host = DEFAULT_HOST
</code>```

But that only seems to take care of Django and seems cumbersome -- what if someone wants to use our library with Flask, or something else? Is there a more universal way to make a Python module configurable by external tools plus have a default? Or is this a lost cause, and I should stick to configuration on init via arguments?

答:
TL;DR: Pass as args in init.  Balance the use of libraries against the limiting factor they may represent to others who don't use those libraries and don't want to.

There is a general rule of thumb that there is an inverse correlation between number libraries a project uses (especially those that dictate policy like config or db) and the population of people that can/want to use your library.

For example, if you make a library that only work with Django, you are limiting yourself to only Django users.  Same with config, specific database, etc.

Dependent libraries that don't dictate policy are not as impactful, but that doesn't mean there is no impact.  Reasons around not wanting to use these kinds of dependent libraries will probably run the gambit:

minimizing program size (rightly or wrongly this can be a reason)

security issues

compliance issues

have to use another dependent library that conflicts

have to use a different version of the dependent library

etc

For these reasons I would suggest you always go with the minimal dependence on other libraries.  In this case that would mean passing the args in init and allowing the consumer of your library to decide how and which config they want to use.


答:
How can I document a project such that anytime I look back it
  shouldn't take me more than a few minutes to get going from wherever I
  left.

First off, this implies there is some high-level description and code structure in the project that you can easily grasp in a few minutes -- as opposed to a zillion lines of code with no apparent structure and no comments.

Are there best practices?

The following are best practices I adopted throughout a 20+ years career in very small to very large projects and they have served me and my teams well. Apply in the order listed as your project grows:

Use version control this gives you a free track record of what happened, when and who applied the changes. It also gives you easy fall back to an earlier version at any time.

Modularize your code (depending on the language and programming environment, use classes, modules, packages, components).

Document your code. This includes summary documentation at the top of each file (what does this do? why? how to use it?), and specific comments at the level of functions, procedures, classes and methods (what does it do? arguments and return values/types? side-effects?).

Add TODO and FIXME comments while you are coding. This helps to remember the whys and whats of quirks that will inevitably enter your code base and that later on will have you asking WTF?!. E.g.:

```<code>//TODO shall actually compute X and return it
... some code that does not compute X yet (maybe returns a fixed value instead)

//FIXME make this constant time instead of n^2 as it is now
... some code that works but is not efficient yet
</code>```

Make a habit of drawing diagrams to document structure and complex behavior such as sequences of calls between modules/objects/systems etc.  Personally I prefer UMLet as it is quick to use, creates nice graphics, and most importantly doesn't get in your way. But of course you should use any drawing tool that you find does the job. Remember that the purpose of any such drawings is to communicate succinctly, not to specify a system in minute detail (!!).

Add unit tests early on. Unit tests are not only great for regression testing, but are also a form of usage documentation for your modules.

Add code-external documentation early on. Start off with a README that describes the required dependencies to run and develop the project, how to install it, how to run it.

Make a habit of automating repetitive tasks. E.g. compile/build/test cycles should be scripted by some form (e.g. in JavaScript use grunt, in Python fabric, in Java Maven). This will help you get up to speed quickly when you come back.

As your project grows, add more documentation by generating source-code docs (using some form of JavaDoc-style comments and an appropriate tool to generate HTML or PDF from it).

If your project grows beyond a single component and has some more complex deployment to it, be sure to add design and architecture documentation. Again note that the purpose of this is to communicate structure and dependencies rather than minute details.

Title: How should I remember what I was doing and why on a project three months back?

Body:
I was working on a project three months back, and then suddenly another urgent project appeared and I was asked to shift my attention.

Starting tomorrow, I'll be heading back to the old project. I realize that I do not remember what exactly I was doing. I don't know where to begin.

How can I document a project such that anytime I look back it shouldn't take me more than a few minutes to get going from wherever I left. Are there best practices?

Body:
How can I document a project such that anytime I look back it
  shouldn't take me more than a few minutes to get going from wherever I
  left.

First off, this implies there is some high-level description and code structure in the project that you can easily grasp in a few minutes -- as opposed to a zillion lines of code with no apparent structure and no comments.

Are there best practices?

The following are best practices I adopted throughout a 20+ years career in very small to very large projects and they have served me and my teams well. Apply in the order listed as your project grows:

Use version control this gives you a free track record of what happened, when and who applied the changes. It also gives you easy fall back to an earlier version at any time.

Modularize your code (depending on the language and programming environment, use classes, modules, packages, components).

Document your code. This includes summary documentation at the top of each file (what does this do? why? how to use it?), and specific comments at the level of functions, procedures, classes and methods (what does it do? arguments and return values/types? side-effects?).

Add TODO and FIXME comments while you are coding. This helps to remember the whys and whats of quirks that will inevitably enter your code base and that later on will have you asking WTF?!. E.g.:

//TODO shall actually compute X and return it
... some code that does not compute X yet (maybe returns a fixed value instead)

//FIXME make this constant time instead of n^2 as it is now
... some code that works but is not efficient yet

Make a habit of drawing diagrams to document structure and complex behavior such as sequences of calls between modules/objects/systems etc.  Personally I prefer UMLet as it is quick to use, creates nice graphics, and most importantly doesn't get in your way. But of course you should use any drawing tool that you find does the job. Remember that the purpose of any such drawings is to communicate succinctly, not to specify a system in minute detail (!!).

Add unit tests early on. Unit tests are not only great for regression testing, but are also a form of usage documentation for your modules.

Add code-external documentation early on. Start off with a README that describes the required dependencies to run and develop the project, how to install it, how to run it.

Make a habit of automating repetitive tasks. E.g. compile/build/test cycles should be scripted by some form (e.g. in JavaScript use grunt, in Python fabric, in Java Maven). This will help you get up to speed quickly when you come back.

As your project grows, add more documentation by generating source-code docs (using some form of JavaDoc-style comments and an appropriate tool to generate HTML or PDF from it).

If your project grows beyond a single component and has some more complex deployment to it, be sure to add design and architecture documentation. Again note that the purpose of this is to communicate structure and dependencies rather than minute details.


答:
In addition to the exhaustive answer already given:

If you look for an platform independent approach, a framework like Apache Thrift or similar might be worth a look, as they are designed especially for that purpose of platform-agnostic and language-agnostic communication.

It is even possible to combine such an framework with Message Queues or a Service Bus, if you really need that for your particular application. The latter looks a bit like overkill to me, given the scope outlined in the question, but it may pay when you are already planning to scale the thing to something bigger.

Title: local communications between two apps

Body:
To make a platform-independent program in C++ I want to separate the GUI (separate for each OS, using native libraries/APIs) and the actual program. Obviously those two need to communicate with each other.

Doing that by saving and reading XML files would be one solution. As it is kind of slow/always needs to be checked for changes, I would rather prefer a solution where the processing part of the program offers a "server" on localhost and the GUI communicates with that "server". What do you think of this approach? And how would I do it technically?


答:
For me, I find the simplest method of resuming projects is just to keep a constant record of notes on your work. I find that Microsoft's 'OneNote' is particularly good for keeping and grouping pages of notes. In particular, the search bar makes it extremely easy to quickly find your notes on something.

Here are some things I do within OneNote which help me to resume progress on projects:

Daily/Weekly Logs  - Keep a daily or weekly log of progress to help you figure out the progress that you've already made with a project.

To-do list - I have a general to-do list, but I also keep a separate to-do list for the projects I'm working on so that I remember what things I have yet to do for a project. I sometimes also leave //TODO: items in my code.

Project Notes - Things I note include links to issue/project tracking items, snippets of code, issues encountered, decisions made, plans and descriptions of potential solutions, list of code changes, links to code repository directory, emails for the project and links to project documentation.

So, whenever I go back to a project I can open up my notes and almost instantly I can see how much progress was made on the project, how much work is left to do and even see my train of thought.


问:
Git and merge commits
We have three branches:

master

staging

dev

We branch per issue and each issue needs to go through testing and staging before being merged to master.

We branch feature branches from master and work on that feature.

When ready for testing, we merge the feature branch into dev branch and TeamCity deploys to test environment.

When ready for staging, we merge the feature branch into staging branch and TeamCity deploys to staging environment.

This involves a lot of merge commits on dev/staging branches, but very few on master, because the feature branches are always branched from master.

It's always a merge commit merged with a feature branch, so this is a merge from a merge, from a merge, from a merge, etc... So at any time TeamCity has 100+ pending changes, even though there is only 1 changed file when doing:

```<code>git diff dev~1...dev
</code>```

Is there some way to minimize these merge commits?

Are we doing Git wrong?

答:
Merging multiple times should not be a problem, and that's actually a normal way of working with Git.

Your team agreed to have a specific workflow. For small fixes, that may induce some overhead, compared to, e.g., merging directly on master. But this is okay, at least you have a process to perform continuous integration.

Now, I don't know TeamCity, but maybe you should focus on why it  has 100+ pending changes when the diff is actually small.

ContentLicense: CC BY-SA 4.0

Title: Git and merge commits


问:
Why 'List<E>' is an 'interface' but not 'abstract class'?
Amidst defining the hierarchy, firstly,  one can think to embed the abstract method(behavior) in abstract class only because the derive concrete class possess that behavior as core behavior with it's specific implementation, secondly, one can think to embed the abstract method(behavior) in interface only because derived concrete class possess that behavior as non-core behavior(peripheral) having it's specific implementation.

As I would not rely on this example which supports above point, below are the two references, I would rely on.

1) First reference that supports this point:

Interfaces are ideal for defining mixins.  Loosely speaking, a mixin is a type that a class can implement in addition to its "primary type" to declare that it provides some optional behavior.  For example, Comparable is a mixing interface that allows a class to declare that its instances are ordered with respect to other mutually comparable objects.  Such an interface is called a mixin because it allows the optional functionality to be "mixed in" to the type's primary functionality.  Abstract classes can't be sued to define mixins for the same reason that they can't be retrofitted onto existing classes: a class cannot have more than one parent, and there is no reasonable place in the class hierarchy to insert a mixin.

2) Second reference that support this point:

In UML sketch, the relation between interface model and concrete class model is named Realisation, where as, the relation between abstract class model and concrete class model is named is-a relation. Here is-a can be told, when concrete class has core behavior unlike realisation relation.

So, with these two references, It looks list<E> and Collection<E> are abstract class but not interface.

With this above explanation, I would like to understand,

Why Collection<E> and List<E> is designed to be interface in  java.util package?

Is my understanding correct?

答:
Collection types using interface instead of abstract class is a mistake. Indeed, such a huge mistake that the Java SE 8 language has had bizarre extensions grafted onto it so that interfaces could have implementation methods.

So why the mistake? Ideally you want to define an interface (general definition of "interface", not the Java keyword) without depending on implementation. The Java 2 collections framework was developed with the arguably arrogant assumption that all the methods that you would ever want for the type could be determined upfront. This attitude has led to hacks to support collections in almost every major revision of Java.

There is the odd advantage of List being an interface. AbstractCollection is used for common implementation of both List and Set but you wouldn't want it to subtype those. Though, more often than not, such subtyping is inappropriate.


问:
How to do Test Driven Development
I have just 2+ years of experience in application development. In those two years my approach towards development was as following

Analyze requirements

Identity Core component/Objects, Required functions, Behavior, Process and their constraints

Create classes, relation between them, constraints on objects behavior & states

Create functions, process with behavioral constraints as per requirements

Manually test application

If requirement changes modify component/functions, then manually test application

Recently I got Introduced to TDD and feel that this is very good way to do development as developed code has strong reason to exists and lot of post deployment issues are mitigated.

But my problem is I am not able to do create tests first, Rather I am identifying components and just writing test for them before I actually write components. my question is

Am I doing it is right? If not what exactly I have to change

Is there any way you can identify whether test you have written are enough?

Is it good practice to writing test for very simple functionality which might be equivalent to 1+1 = 2 or is it just an overplay?

Is it good to change functionality and accordingly test if requirement changes?

答:
Am I doing it is right? If not what exactly I have to change

You're doing just fine.

Is there any way you can identify whether test you have written are enough?

Yes, use a test/code coverage tool. Martin Fowler offers some good advice on test coverage.

Is it good practice to writing test for very simple functionality which might be equivalent to 1+1 = 2 or is it just an overplay?

In general, any function, method, component etc. that you expect to yield some result given some inputs is a good candidate for a unit test. However, as with most things in (engineering) life, you need to consider your trade-offs: Is the
effort offset by writing the unit test resulting in a more stable code-base in the long-run? In general, opt to write test code for crucial/critical functionality first. Later if you find there are bugs associated with some untested part of the code, add more tests.

Is it good to change functionality and accordingly test if requirement changes?

The good thing about having automated tests is that you will immediately see if a change breaks previous assertions. If you expect this because of changed requirements, yes it is ok to change the test code (in fact, in pure TDD you would change the tests first according to requirements, then adopt the code until it meets the new requirements).

Title: How to do Test Driven Development


答:
You describe your development approach as a "top-down-only" process - you start from a higher abstraction level and go more and more into the details. TDD, at least in the form as it is popular, is a "bottom-up" technique. And for someone who is working mostly "top-down" it can be indeed very unusal to work "bottom-up".

So, how can you bring more "TDD" into your development process? First, I assume your actual development process is not always so "top-down" as you described it above. After step 2, you will probably have identified some components which are independent from other components. Sometimes you decide to implement those components first. The details of the public API of those components probably does not follow your requirements alone, the details also follow your design decisions. This is the point where you can start with TDD: imagine how you are going to use the component, and how you actually will use the API. And when you start coding such an API usage in form of a test, you just started with TDD.

Second, you can do TDD even when you are going to code more "top-down", starting with components which are dependent on other, non-existing components first. What you have to learn is how to "mock out" these other dependencies first. That will allow you to create and test high-level components before going to the lower-level components. A very detailed example on doing TDD in a top-down-manner can be found in this blog post of Ralf Westphal.

Title: How to do Test Driven Development

Body:
I have just 2+ years of experience in application development. In those two years my approach towards development was as following

Analyze requirements

Identity Core component/Objects, Required functions, Behavior, Process and their constraints

Create classes, relation between them, constraints on objects behavior & states

Create functions, process with behavioral constraints as per requirements

Manually test application

If requirement changes modify component/functions, then manually test application

Recently I got Introduced to TDD and feel that this is very good way to do development as developed code has strong reason to exists and lot of post deployment issues are mitigated.

But my problem is I am not able to do create tests first, Rather I am identifying components and just writing test for them before I actually write components. my question is

Am I doing it is right? If not what exactly I have to change

Is there any way you can identify whether test you have written are enough?

Is it good practice to writing test for very simple functionality which might be equivalent to 1+1 = 2 or is it just an overplay?

Is it good to change functionality and accordingly test if requirement changes?


问:
How to construct a cubie representation of a rubik's cube, given an array
Just to get this out of the way, I have seen this, and it is not what I'm looking for.

So, let's say you are programming a Rubik's Cube. (I know, very unoriginal, but bored programmers have to do something..) This Rubik's Cube is defined by an array of six 2-D arrays (one for each face,) and these 2-D arrays' sizes vary, based on the size of the cube. For instance, if I had a 3x3x3 cube, the array would be 6x3x3. That is, it would have 6 3x3 arrays.

Now, let's say I wanted to get an array of the cubies which make up this cube. Each cubie is defined by two things (I think..): the colors of it and its location on the cube. For example, if you had a solved cube, one of the cubies would be the red, green, and yellow cubie, and, assuming yours is sitting in the same orientation as mine, that cubie would be the front, right, up cubie.

However, none of this answers my question: how do I go about defining a set of these cubies, given an array of variable sizes. I know, for instance, that the cubie previously mentioned could be defined as cube[0][0][dimension-1], cube[2][0][0], cube[4][dimension-1][dimension-1]. (For a bit of reference, the order in which I define my faces is front, back, right, left, up, down. Hence the 0, 2, and 4, making front, right, and up.)

Anyway, with that said, I'd rather not hard-code all of this and was wondering if there was a simpler way. So, what's the best way to do something like what I was just describing?

Edit: For clarification, I am trying to get the separate, individual, smaller cubes which make up the Rubik's Cube as a whole. For instance, the piece with the red, green, and white stickers on it.

答:
It sounds like you might like my answer here: https://softwareengineering.stackexchange.com/a/262847/156217

The basic idea is:

Address the cube in an x-y-z coordinate system, with a center at (0, 0, 0).

A Piece class stores a position (x, y, z) and colors (cx, cy, cz). The Piece knows which sticker colors are on which axis (x, y, or z) but doesn't know which direction the sticker is facing.

The Cube stores an unordered list of Pieces.

Rotations are done by updating the position and colors of the relevant Pieces.

This is nice because all rotation logic is confined to the Piece class. A Piece doesn't know its orientation, but it doesn't need to. The orientation of a Piece is strictly dependent on its position: the corner at (-1, -1, -1) is the LEFT-UP-BACK corner.


答:
Your workflow seems similar to the “Git Flow”, except that you start feature branches from master, whereas the Git Flow recommends branching from dev.

The idea is that dev closely reflects the current development state. Feature branches are supposed to be very short-lived (at most a couple of days of development). So when a feature is branched from dev and merged back into dev a day later, there will be very few conflicts. The dev branch would be used for Continuous Integration.

Git Flow then suggest branching a release branch (your staging) from the dev branch with multiple new features for QA and release preparation. On release, the code is merged into master so that master only contains fully tested published versions.

If we were to branch new features off master (i.e. the last published version), this would ignore all other features that have been merged into dev in the meanwhile. Although the diff between dev^ and dev might be rather clean, there would be vast differences in the history:

```<code>             Am                                    B..Zm
  master ----x------------------------------------x
            / \                  \               /
 staging --x---|------------------|-------------x B..Zs
          /As  |         B  C..Y  |          Z /
     dev x-----|---------x--x--x--|-----------x
         A      \       /  /  /   |          /
featureB         x--x--x  .....   |         |
                 B1 B2 B3         |         |
  ...                             |         |
                                   \       /
featureZ                            x--x--x
                                    Z1 Z2 Z3
</code>```

At merge B into dev (A) from featureB (A As Am B1 B2 B3), the merge is rather clean. We then add a couple of other features C through Y into dev. After that, the history of dev looks like A As Am B1 B2 B3 C1 C2 C3 ... Y1 Y2 Y3. That still looks reasonable. Finally, we have the featureZ branch with the history A As Am Z1 Z2 Z3 – note that Am is the nearest common ancestor commit of dev and featureZ.

The result is that at merge Z, we do not only test the effect of the commits Z1 Z2 Z3, but the effect of combining all the features B1 B2 B3 C1 C2 ... Y2 Y3 Z1 Z2 Z3.

The impact of this problem is reduced by frequent releases, so that the difference between dev and master is not that pronounced. However, this only makes the problem smaller, and does not solve it. TeamCity seems to realise that it's actually testing all the changes you made since you last merged into master, although these are not obvious in the branch history (since dev only contains merge commits).

I recreated the above branching example as an actual git repo, which is available as latk/Git-Branching-Madness on GitHub. You can look at the branch graph online, or clone the repo and inspect it yourself, e.g.:

```<code>                          # tip: use "git log" with "--pretty=oneline"
$ git log featureZ        # history of featureZ
$ git log dev^            # complete history of dev before featureZ merge
$ git log dev^..dev       # what commits were added during the featureZ merge
$ git log master --graph  # display complete branching history
</code>```

Title: Git and merge commits

Body:
We have three branches:

master

staging

dev

We branch per issue and each issue needs to go through testing and staging before being merged to master.

We branch feature branches from master and work on that feature.

When ready for testing, we merge the feature branch into dev branch and TeamCity deploys to test environment.

When ready for staging, we merge the feature branch into staging branch and TeamCity deploys to staging environment.

This involves a lot of merge commits on dev/staging branches, but very few on master, because the feature branches are always branched from master.

It's always a merge commit merged with a feature branch, so this is a merge from a merge, from a merge, from a merge, etc... So at any time TeamCity has 100+ pending changes, even though there is only 1 changed file when doing:

```<code>git diff dev~1...dev
</code>```

Is there some way to minimize these merge commits?

Are we doing Git wrong?

Body:
Your workflow seems similar to the “Git Flow”, except that you start feature branches from master, whereas the Git Flow recommends branching from dev.

The idea is that dev closely reflects the current development state. Feature branches are supposed to be very short-lived (at most a couple of days of development). So when a feature is branched from dev and merged back into dev a day later, there will be very few conflicts. The dev branch would be used for Continuous Integration.

Git Flow then suggest branching a release branch (your staging) from the dev branch with multiple new features for QA and release preparation. On release, the code is merged into master so that master only contains fully tested published versions.

If we were to branch new features off master (i.e. the last published version), this would ignore all other features that have been merged into dev in the meanwhile. Although the diff between dev^ and dev might be rather clean, there would be vast differences in the history:

             Am                                    B..Zm
  master ----x------------------------------------x
            / \                  \               /
 staging --x---|------------------|-------------x B..Zs
          /As  |         B  C..Y  |          Z /
     dev x-----|---------x--x--x--|-----------x
         A      \       /  /  /   |          /
featureB         x--x--x  .....   |         |
                 B1 B2 B3         |         |
  ...                             |         |
                                   \       /
featureZ                            x--x--x
                                    Z1 Z2 Z3

At merge B into dev (A) from featureB (A As Am B1 B2 B3), the merge is rather clean. We then add a couple of other features C through Y into dev. After that, the history of dev looks like A As Am B1 B2 B3 C1 C2 C3 ... Y1 Y2 Y3. That still looks reasonable. Finally, we have the featureZ branch with the history A As Am Z1 Z2 Z3 – note that Am is the nearest common ancestor commit of dev and featureZ.

The result is that at merge Z, we do not only test the effect of the commits Z1 Z2 Z3, but the effect of combining all the features B1 B2 B3 C1 C2 ... Y2 Y3 Z1 Z2 Z3.

The impact of this problem is reduced by frequent releases, so that the difference between dev and master is not that pronounced. However, this only makes the problem smaller, and does not solve it. TeamCity seems to realise that it's actually testing all the changes you made since you last merged into master, although these are not obvious in the branch history (since dev only contains merge commits).

I recreated the above branching example as an actual git repo, which is available as latk/Git-Branching-Madness on GitHub. You can look at the branch graph online, or clone the repo and inspect it yourself, e.g.:

                          # tip: use "git log" with "--pretty=oneline"
$ git log featureZ        # history of featureZ
$ git log dev^            # complete history of dev before featureZ merge
$ git log dev^..dev       # what commits were added during the featureZ merge
$ git log master --graph  # display complete branching history


问:
Why do code-bases in n-tier development have an equal amount of, if not more, JavaScript code now?
I've been doing web programming for a long time now, and somewhere, I lost track of why we are doing what we are doing today (or how did we come to do things this way)?

I started out with basic ASP web development, and very early on, display and business logic were mixed on the page. Client-side development varied wildly (VBScript, different flavors of JavaScript), and we had plenty of warning about server-side validations (and so I stayed away from client-side logic).

I then moved to ColdFusion for a while. ColdFusion was probably the first web development framework that separated display and business logic using their tags. It seemed very clear to me, but very verbose, and ColdFusion was not in high market demand, and so I moved on.

I then jumped on the ASP.NET band wagon and started using their MVC approach. I also realized Java seemed to be an ivory tower language of enterprise systems, and also tried their MVC approach. Later on, ASP.NET developed this MVVM design pattern, and Java (precisely, J2EE or JEE) also struggled and came out with its MVC2 approaches.

But today, what I have discovered is that backend programming is not where the excitement and progress is anymore. Also, server-side based MVC practices seem to be obsolete (do people really use JSTL anymore?). Today, in most projects that I am on, I found out that JavaScript frameworks and client-side development is where all the exciting and innovative progresses are being made.

Why has this movement from server to client-side development taken place? I did a simple line count of one of my JEE projects, and there are more lines of code in JavaScript than Java (excluding third-party libraries). I find that most backend development using programming languages such as Java or C# is simply to produce a REST-like interface, and that all the hard effort of display, visualization, data input/output, user interactions, etc... are being addressed via client-side framework like Angular, Backbone, Ember, Knockout, etc...

During the pre-jQuery era, I saw plenty of diagrams where there was a clear, conceptual line between the M, V, and C in MVC in n-tier development. Post-jQuery, where are these lines drawn? It seems MVC and MVVM are all right there in JavaScript code, client-side.

What I want to know is, why did we make such a transition (from the emphasis of server-side programming to client-side, from favoring compiled languages to scripting languages, from imperative to functional programming, all of these seem to have occurred simultaneously) and what problems did this transition/shift solve?

答:
You asked several questions, some of which have good answers already. A few have not yet had their answers:

What I want to know is, why did we make such a transition (from the emphasis of server-side programming to client-side, ... all of these seem to have occurred simultaneously) and what problems did this transition/shift solve?

Robert Harvey gave an excellent answer.

... from favoring compiled languages to scripting languages,

Scripting languages offer many advantages (also) over compiled languages, e.g.:

are easier to learn and use

eliminate compile time (faster development)

provide more features (higher-end application control)

allow quick changes to running code

etc.

... from imperative to functional programming,

Here's a good comparison, but I would sum it up by saying that in distributed software (think cloud computing), managing state changes (synchronization across many nodes) can be a huge problem. In functional programming, the need to deal with state changes is a lot lower.


问:
Do I have to distribute my code if I use GPL based jquery controls in my commercial application
I have been thinking about using 3rd party GPL based jQuery controls in our in-house ASP.NET project. As far as the 3rd party license is concerned,  I think I can use any jQuery controls in my application as long as they are compatible with the GPL license.

jQuery itself is released under the MIT license.  The 3rd party library is what introduces the GPL (not LGPL) license concerns.

Do I need to mention any where in my application saying that we have been using GPL licensed controls?  License information is already there in the .js files.

Do I need to give the source code of my software away?  This is an in house ASP.NET web application; published on our own server; and only for internal users.

答:
No.  You are not distributing your software, as you control the only server it will be installed on, and the GPL only places any requirements on you if you distribute to a third party.

If you were to use AGPL components, that may require you to distribute the source code, but as it is only to your company's employees that you would be required to distribute it, this is unlikely to be too onerous.


答:
As jquery is a Javascript library that gets executed on the client machines, using it in a public-facing website can be seen as distribution of the code.

When you distribute GPL licensed code, you must make the entire application open-source under the GPL or a compatible license.

If my assessment of the Javascript code being distributed when used in a website is wrong, then there is definitely no problem with using it in a closed-source web-app, but I would recommend consulting a lawyer before depending on it.

Anyway, your situation is different. As your web-app is an in-house application that you are developing on behalf of your employer, giving the code to fellow employees is not considered distribution under any circumstance, as the code doesn't leave the organisation.

For that reason, using the GPL controls in your in-house application is fine, as long as the application remains in-house.

Title: Do I have to distribute my code if I use GPL based jquery controls in my commercial application

Body:
I have been thinking about using 3rd party GPL based jQuery controls in our in-house ASP.NET project. As far as the 3rd party license is concerned,  I think I can use any jQuery controls in my application as long as they are compatible with the GPL license.

jQuery itself is released under the MIT license.  The 3rd party library is what introduces the GPL (not LGPL) license concerns.

Do I need to mention any where in my application saying that we have been using GPL licensed controls?  License information is already there in the .js files.

Do I need to give the source code of my software away?  This is an in house ASP.NET web application; published on our own server; and only for internal users.


问:
Is C# development effectively inseparable from the IDE you use?
I'm a Python programmer learning C# who is trying to stop worrying and just love C# for what it is, rather than constantly comparing it back to Python.

I'm caught up on one point: the lack of explicitness about where things are defined, as detailed in this Stack Overflow question. In short: in C#, using foo doesn't tell you what names from foo are being made available, which is analogous to from foo import * in Python -- a form that is discouraged within Python coding culture for being implicit rather than the more explicit approach of from foo import bar.

I was rather struck by the Stack Overflow answers to this point from C# programmers, which was that in practice this lack of explicitness doesn't really matter because in your IDE (presumably Visual Studio) you can just hover over a name and be told by the system where the name is coming from. E.g.:

Now, in theory I realise this means when you're looking with a text editor, you can't tell where the types come from in C#... but in practice, I don't find that to be a problem. How often are you actually looking at code and can't use Visual Studio?

This is revelatory to me. Many Python programmers prefer a text editor approach to coding, using something like Sublime Text 2 or vim, where it's all about the code, plus command line tools and direct access and manipulation of folders and files. The idea of being dependent on an IDE to understand code at such a basic level seems anathema. It seems C# culture is radically different on this point. And I wonder if I just need to accept and embrace that as part of my learning of C#.

Which leads me to my question here: is C# development effectively inseparable from the IDE you use?

答:
Not anymore:

http://www.omnisharp.net/

OmniSharp is a family of Open Source projects, each with one goal - To
  enable great .NET development in YOUR editor of choice.

It’s fun to say Cross Platform .NET. But is it reasonable for someone
  to develop .NET without Visual Studio and Windows?

Is it fun to do .NET on a Mac in Sublime? Ubuntu and Emacs? Windows
  and Atom? You can use your editor PLUS get to use great features like
  Intellisense (not just Autocomplete), Add Reference, Format Document,
  and lots more. Develop anywhere, deploy anywhere (and to Azure!)

I have tested this with subime3 and osx

More samples at

http://blog.jonathanchannon.com/2014/11/12/csharp-first-class-citizen-sublime-text/


答:
I think that historically the answer is pretty much, yes - getting C# development up and running effectively in anything outside of Visual Studio, Xamarin, or SharpDevelop was just too much an unpleasant experience.

But recently a lot of projects have emerged that makes it easier, e.g.:

OmniSharp, provides a foundation for intellisense and refactoring, along with vim, emacs, atom, and sublime plugins. I haven't actually used it, so I don't know how well it works, but it does look promising.

Yeoman ASP.NET MVC generators, helps bootstrap a new MVC project (maybe other generators exist).

paket, an alternative to NuGet where you can actually add NuGet packages to your project from the command line, and have your .csproj files updated (although there was a NuGet command line tool, actually updating projects to use the packages was part of the IDE integration, not command line tools).

Paket has the implication that you have to adapt your source code to using it - so if you sit as the single member in a team and wants to use a text editor for coding, and everybody else uses Visual Studio, you would have to convince everybody else to adapt the solution to your needs :(

So you should be able to get up and running, but there is comparably more work to do to get your toolchain up and running efficiently.

Title: Is C# development effectively inseparable from the IDE you use?

Body:
I'm a Python programmer learning C# who is trying to stop worrying and just love C# for what it is, rather than constantly comparing it back to Python.

I'm caught up on one point: the lack of explicitness about where things are defined, as detailed in this Stack Overflow question. In short: in C#, using foo doesn't tell you what names from foo are being made available, which is analogous to from foo import * in Python -- a form that is discouraged within Python coding culture for being implicit rather than the more explicit approach of from foo import bar.

I was rather struck by the Stack Overflow answers to this point from C# programmers, which was that in practice this lack of explicitness doesn't really matter because in your IDE (presumably Visual Studio) you can just hover over a name and be told by the system where the name is coming from. E.g.:

Now, in theory I realise this means when you're looking with a text editor, you can't tell where the types come from in C#... but in practice, I don't find that to be a problem. How often are you actually looking at code and can't use Visual Studio?

This is revelatory to me. Many Python programmers prefer a text editor approach to coding, using something like Sublime Text 2 or vim, where it's all about the code, plus command line tools and direct access and manipulation of folders and files. The idea of being dependent on an IDE to understand code at such a basic level seems anathema. It seems C# culture is radically different on this point. And I wonder if I just need to accept and embrace that as part of my learning of C#.

Which leads me to my question here: is C# development effectively inseparable from the IDE you use?


答: One option is to frequently git fetch and git merge / git rebase master during development and qa in order to keep up with the changes and resolve conflicts as they happen.  I prefer git rebase which replays your changes on top of the lastest master

Title: Git and merge commits


问:
How can I avoid the "global $dbh" anti-pattern?
This is what most of my database-related library code looks like:

lib.php

```<code><?php

$dbh = new PDO(...);

function doSomeDatabaseThing() {
    global $dbh;
    return $dbh->doStuff();
}

function doSomeOtherThing() {
    global $dbh;
    return $dbh->doSomeOtherStuff();
}
</code>```

index.php

```<code><html>
    <head>...</head>
    <body>
        <?php
        require_once('lib.php');
        echo doSomeDatabaseThing();
        ?>
    </body>
</html>
</code>```

I keep reading that globals in PHP are generally bad. Of course, this doesn't mean that I should never use globals, but it seems wrong to repeatedly use this pattern in almost all database code I write.

So, how should I do this without globals? I could try something like

lib.php

```<code>$dbh = new PDO(...);
function doSomeDatabaseThing($dbh) { ... }
</code>```

index.php

```<code>doSomeDatebaseThing($dbh);
</code>```

but it looks ugly to have to write "($dbh)" every single time I call a database function.

Is there a better way to solve this?

答:
Object-oriented design + Dependency Injection (DI)

You should consider using object-oriented design together with Dependency Injection container. I recommend Symfony specifically because it has a great DI container component.

Instead of having a bunch of DB-related functions, consider grouping them into classes which deal with particular types of domain objects, like so:

```<code>// repository interface
interface Repository
{
    public function findById($id);
}

// specific repository dealing with user objects
class UserRepository implements Repository
{
    private $dbh;

    function __construct(PDO $dbh)
    {
        $this->dbh = $dbh;
    }

    public function findById($id)
    {
        // just an example, should use at least prepared statement here
        $userRow = $this->dbh->query("...");
        // ...
        return $user;
    }
}
</code>```

Instead of having global $dbh you now inject it into constructor of SomethingRepository as a dependency, hence the name of the pattern. That is called constructor injection, and there are other types.

Injection is basically instantiating all the dependencies and passing them into constructors/setters. That's what DI containers do. You provide a configuration describing how objects depend on each other, framework builds them.

Why is global $x considered anti-pattern?

Name of $x can be a subject to change => happy time renaming

Any object using $x can overwrite it => happy time debugging

Can cause security issues in case you have register_globals enabled or if you including third-party source files => happy time dealing with hacker attacks

Of course, this doesn't mean that I should never use globals

That means you should avoid using global $x construct at all costs. You can totally build any application without it, unless you stuck with some legacy code or prehistoric version of PHP.

Body:
Object-oriented design + Dependency Injection (DI)

You should consider using object-oriented design together with Dependency Injection container. I recommend Symfony specifically because it has a great DI container component.

Instead of having a bunch of DB-related functions, consider grouping them into classes which deal with particular types of domain objects, like so:

// repository interface
interface Repository
{
    public function findById($id);
}

// specific repository dealing with user objects
class UserRepository implements Repository
{
    private $dbh;

    function __construct(PDO $dbh)
    {
        $this->dbh = $dbh;
    }

    public function findById($id)
    {
        // just an example, should use at least prepared statement here
        $userRow = $this->dbh->query("...");
        // ...
        return $user;
    }
}

Instead of having global $dbh you now inject it into constructor of SomethingRepository as a dependency, hence the name of the pattern. That is called constructor injection, and there are other types.

Injection is basically instantiating all the dependencies and passing them into constructors/setters. That's what DI containers do. You provide a configuration describing how objects depend on each other, framework builds them.

Why is global $x considered anti-pattern?

Name of $x can be a subject to change => happy time renaming

Any object using $x can overwrite it => happy time debugging

Can cause security issues in case you have register_globals enabled or if you including third-party source files => happy time dealing with hacker attacks

Of course, this doesn't mean that I should never use globals

That means you should avoid using global $x construct at all costs. You can totally build any application without it, unless you stuck with some legacy code or prehistoric version of PHP.


答:
Writing tests first is a completely different approach to writing software. Tests are not only a tool of proper code functionality verification (they all pass) but the force that defines the design. While test coverage might be a useful metric, it must not be the goal in itself - the goal of TDD is not to get to a good % of code coverage, but to think about testability of your code before writing it.

If you have troubles with writing tests first, I would highly recommend doing a session of pair-programming with someone who is experienced in TDD, so that you get a hands on experience of "the way to think" about the whole approach.

Another good thing to do is to watch online video where software is being developed using TDD from the very first line of it. Good one that I once used to introduce myself to TDD was Let's Play TDD by James Shore. Take a look, it will illustrate how emergent design works, what questions should you ask yourself while writing tests and how new classes and methods are created, refactored and iterated upon.

Is there any way you can identify whether test you have written are
  enough?

I believe this is the wrong question to ask. When you do TDD, you chose to do TDD and emergent design as the way to write software. If any new functionality you need to add always starts with a test, it will always be there.

Is it good practice to writing test for very simple functionality
  which might be equivalent to 1+1 = 2 or is it just an overplay?

Obviously it depends, use your judgement. I prefer not to write tests on parameters null checks, if the method is not part of public API, but otherwise, why would you not confirm that method Add(a,b) returns a+b indeed?

Is it good to change functionality and accordingly test if requirement
  changes?

Again, when you change or add new functionality to your code, you start with a test, whether it's adding new test or changing existing one when requirements change.

Title: How to do Test Driven Development


问:
Original GLUT library was open source, but license prevented releasing any changes to it. What could be the rationale behind such license?
Original GLUT library is open source, even on GitHub, yet the license doesn't allow any changes to be released publicly (but you can change it for use in your own projects, as is often exercised in various tutorials still using GLUT itself). Most files contain this notice:

```<code>/* This program is freely distributable without licensing fees and is
provided without guarantee or warrantee expressed or implied. This
program is -not- in the public domain. */
</code>```

It's not maintained anymore, and because of this, freeGLUT exists, which implements GLUT interfaces and adds some features to work around its limitations.

Why would anyone want such a license for any open source project?

答:
Why would anyone want such a restricted license?
Quite simply,
control. And possibly, ego, positioning, financial, and
other advantages that derive
from control.

Over the last twenty years, numerous organizations have offered access to
code on generous, "please use it, learn from it,
enhance it, and pass it on!"
terms. The GNU Public Licence,
Apache, and other open source
licences have been part and parcel of this.

But a lot of code has been, and still is, offered on terms that, despite
a dollop of generosity (e.g. monetarily free to use, or free to
use under some conditions) and thus not being
completely proprietary, have key limitations
on how one can use, modify, and share it. They do not enjoy a full measure
of "free" in the sense of liberty.

Even within today's evolved "open source
community," it's very common for developers to
reserve rights
(e.g. to
use of a trademark or validation suite, or the
unique ability to issue separate commercial
licences),
in order to retain control
and economic advantages for the originator.

If GLUT were a brand new open source project,
the limitations on its terms and
conditions
might be a little more surprising. But
it arrives from a very different time. Starting
twenty years ago, it predates
both The Internet and today's open source culture.
The
GPL existed
at the time, but neither it nor its "share and share alike!" philosophy
were particularly widespread then. It was very rare
for software originating from commercial entities
like Silicon Graphics
(where GLUT, and GL overall, started).
Copyright statements offering
limited sharing with rights reserved
were much more common at the time.