问:
OAuth alternative for a 2 party system
I'm writing a RESTful service (Java EE, Jersey) and a client application that communicates with it, and I wish to secure it and store any usernames & passwords dedicated in my own database.

I do not want the client to store the username and password locally, not in any form such as base-64 or other encoding at all, I rather have something like the OAuth2 authorization system, where the client app only stores a refresh & access tokens after the resource owner signed-in, but I do not need to provide access to 3rd party services.

Securing my service using Basic auth means the client app has to store the password and send it for each future request, so that's not what I need.

I'm aware that OAuth is intended for different situations, where there are more than just 2 parties involved (see other question).

as mentioned here https://blog.apigee.com/detail/when_to_use_oauth:
OAuth is the only realistic choice for a web application that itself uses another web application's API on behalf of the user. For instance, consider a web application that integrates with Twitter. (Perhaps it's a geolocation app like Foursquare that offers the ability to tweet where you are and what you're doing.)

So what is the correct standardized method to secure my RESTful service if I do not wish to re-invent the wheel and create my own auth method, and if "Basic" is not what I need because it forces me to store the credentials locally on the client, and OAuth is probably an overkill with it's 3rd party access nature.

P.S-
I do wish to provide users with an option to sign-in to my service using facebook or open-id, but that's another story I guess.

答:
You can very well use OAuth 2.0.
OAuth gives you various grant_types to support various use-cases. The use case you have will have grant_type = password, this is a 2 Legged flow, unlike the 3-Legged where there are 3 parties involved, ie.

```<code>resource_owner (enduser)
Client (third party app)
Resource server (Server)
</code>```

as Server & your mobile application belong to same trust group, you should use 2 Legged OAuth (grant_type=password)
general flow is

```<code>POST /oauth/token
Authorization: Basic base64Encoded(<client_id>:<secret>)
username=a&password=b&grant_type=password
</code>```

This shall return you with access_token and refresh_token.

Title: OAuth alternative for a 2 party system

Body:
You can very well use OAuth 2.0.
OAuth gives you various grant_types to support various use-cases. The use case you have will have grant_type = password, this is a 2 Legged flow, unlike the 3-Legged where there are 3 parties involved, ie.

resource_owner (enduser)
Client (third party app)
Resource server (Server)

as Server & your mobile application belong to same trust group, you should use 2 Legged OAuth (grant_type=password)
general flow is

POST /oauth/token
Authorization: Basic base64Encoded(<client_id>:<secret>)
username=a&password=b&grant_type=password

This shall return you with access_token and refresh_token.


问:
How should I mark types in C and C++ programs?
In this answer of mine, I used _t at end of types, which ended at best, controversial. This is the practice I use in my current projects.

```<code>typedef struct {
    int x;
    int y;
} point_t;
</code>```

This was intended to be consistent with C types from stddef.h like size_t or ptrdiff_t. However, according to certain comments in my questions, _t postfix appears to be reserved for POSIX. What should I use instead of _t? Or should I continue using _t anyway?

This question is for both C and C++.  If these languages have different conventions, feel free to answer so.

答: It depends on you. Unless there is a conflict with the reserved words you are good to go. However, consider a scenario where you are working in a company and multiple people are accessing the same code base, and your code gets to a person who is not aware of your habit He/She can then assume that its a reserved type, especially if you write something like point_t. So, keep it simpler e.g. point is simpler than point_t. And if you want to append something to it, append you name initials. </p>

OwnerDisplayName: xfix

ContentLicense: CC BY-SA 3.0


问:
nodejs chaining with async
I'm trying to chain a series of methods that are async. I have heard of promises and futures but what I'm looking for is:

```<code>obj.setup()
    .do_something()
    .do_another_thing()
    .end()
</code>```

and not:

```<code>obj.setup()
    .then(...)
    .then(....)
</code>```

I have come across a tutorial that explains how to do this, but unfortunately the penny hasn't dropped: http://www.dustindiaz.com/async-method-queues/ So I'm looking for a module. This module, https://github.com/FuturesJS/FuturesJS , seems to have chainify in its API but there's no documentation on how to use it. In fact I can't find any documentation on how to use modules to achieve what I'm looking for, but plenty on using promises to get then().then().then() which is not what I need.

Currently my module looks like:

```<code>var obj = function(){
   this.async_method = function(){}
   this.async_method_thingy = function(){}
   this.async_method_foo = function(){}
}
var o = new obj()

var _ = {
   "setup" : function(){
      ...
      return this
   },
   "do_something" : function(){
      o.async_method()
      return this
   },
   "do_another_thing" : function(){
      o.async_method_thingy()
      return this
   },
   "end" : function(){
      o.async_method_foo()
      return this
   }
}

module.exports = _
</code>```

any help is appreciated ;)

答:
I think you are looking for the async module on npm.

Find it on github at https://github.com/caolan/async.

This module supports a lot of utilities for doing things asynchronously that are typically synchronous, like a linear search through an array.

More importantly for you, it allows for chaining asynchronous functions.  It has 2 modes you can use: parallel or serial.  In parallel mode, it runs the async functions in parallel (this is a lie as nothing in parallel in node.js, but it will simply context switch based on I/O calls as any async stuff works in node).  In serial mode, it runs each function after the previous one finishes by chaining the callbacks together.

From the quick examples on their README:

```<code>async.parallel([
    function(){ ... },
    function(){ ... }
], callback);

async.series([
    function(){ ... },
    function(){ ... }
]);
</code>```

So if I understand your question correctly, what you want to do is this:

```<code>async.series([
  obj.setup.bind(obj),
  obj.do_something.bind(obj),
  obj.do_another_thing.bind(obj),
  obj.end.bind(obj)
]);
</code>```

This is how under the hood async will handle this and you could do it yourself if you don't want to use the module:

```<code>obj.setup(function () {
  obj.do_something(function () {
    obj.do_another_thing(function () {
      obj.end();
    });
  });
});
</code>```

As you can see, this gets messy as you add more and more functions to the chain.  That is why the async.series call is more maintainable.

You also need to update your functions to use callbacks.  No matter what tools or frameworks you use, if your async functions don't pass a callback, there is no way to know whey they finished and therefore no way to move to the next function in the chain.

Function changes:

```<code>var _ = {
   "setup" : function(callback){
      ...
      return this
   },
   "do_something" : function(callback){
      o.async_method(callback)
      return this
   },
   "do_another_thing" : function(callback){
      o.async_method_thingy(callback)
      return this
   },
   "end" : function(callback){
      o.async_method_foo(callback)
      return this
   }
}
</code>```

Title: nodejs chaining with async

Body:
I think you are looking for the async module on npm.

Find it on github at https://github.com/caolan/async.

This module supports a lot of utilities for doing things asynchronously that are typically synchronous, like a linear search through an array.

More importantly for you, it allows for chaining asynchronous functions.  It has 2 modes you can use: parallel or serial.  In parallel mode, it runs the async functions in parallel (this is a lie as nothing in parallel in node.js, but it will simply context switch based on I/O calls as any async stuff works in node).  In serial mode, it runs each function after the previous one finishes by chaining the callbacks together.

From the quick examples on their README:

async.parallel([
    function(){ ... },
    function(){ ... }
], callback);

async.series([
    function(){ ... },
    function(){ ... }
]);

So if I understand your question correctly, what you want to do is this:

async.series([
  obj.setup.bind(obj),
  obj.do_something.bind(obj),
  obj.do_another_thing.bind(obj),
  obj.end.bind(obj)
]);

This is how under the hood async will handle this and you could do it yourself if you don't want to use the module:

obj.setup(function () {
  obj.do_something(function () {
    obj.do_another_thing(function () {
      obj.end();
    });
  });
});

As you can see, this gets messy as you add more and more functions to the chain.  That is why the async.series call is more maintainable.

You also need to update your functions to use callbacks.  No matter what tools or frameworks you use, if your async functions don't pass a callback, there is no way to know whey they finished and therefore no way to move to the next function in the chain.

Function changes:

var _ = {
   "setup" : function(callback){
      ...
      return this
   },
   "do_something" : function(callback){
      o.async_method(callback)
      return this
   },
   "do_another_thing" : function(callback){
      o.async_method_thingy(callback)
      return this
   },
   "end" : function(callback){
      o.async_method_foo(callback)
      return this
   }
}


问:
I might be starting to do Arduino development and I would like some advice
So, today I looked at Arduino; seems very interesting. I still don't want to shell out the money just yet, as I have some questions, namely:

Should I learn something about electronics? What and with what resources?

What stuff should I buy? I have a limited, but not that small budget (probably up to 200€, but preferably less). I'm interested in getting a screen (mustn't be complex, but I would prefer one like that), some speaker, some way for it to move and a way to remotely control it. I would also want a battery. I also wan't to be able to use my board for many things in the future, so it shouldn't be too basic, I guess. I think I will go with the MEGA, is that smart?

What resources do you recommend? Any books? Good tutorials besides what you find on their site?

What are really cool extensions (e.g. screens) which I would be adviced to get/try?

Help greatly appreciated. Also, I have never developed for any embedded device, but I know C and computer architecture to some degree; I'm somewhat familiar with low level stuff.

答:
Alright sorry.
I'll just answer your questions number wise.

1)You should know the basics such as what different components do and how to use them.
  - http://www.dummies.com/how-to/content/basic-electronic-components-and-what-they-do.html

2) The mega is a good option but if you want to learn a bit and experiment with the board I'd advise getting an uno simply because its cheaper and then upgrading to a mega later on if you like it and want to do more with it.

3)You can learn pretty much everything on youtube , and once you have a hang of the programming bit and installation you can use the resources and code given at arduino.cc and also the arduino playground :

     ->Youtube lessons : https://www.youtube.com/watch?v=kLd_JyvKV4Y (This is the first lesson , the others are there on his channel.

->Arduino playground : playground.arduino.cc/

->Arduino reference page : arduino.cc/en/Reference/HomePage

4) Alright , this is the exciting one , some cool extensions or components would be :

  -> An LCD screen : You can code this one to display words,numbers and also one of those tickr like updates . www.adafruit.com/products/714

->  Some motors : Both DC normal(brushed) and a servo are cool starters.

-> A bluetooth shield to control your arduino via your phone .

Lastly , you should get a starter kit because they usually have the basic components that you'll need to learn .
Cheers.

ContentLicense: CC BY-SA 2.5


问:
Switching between mobile webapp version using Ionic Framework and Desktop web app version?
I own a web application that make use of Twitter Bootstrap 3.

This eases the design of the mobile version since it brings some responsive features.

However, I would like a really native-mobile aspect for the mobile version, but not a native for the Desktop one.

I searched..and I found this really promising framework: Ionic

It seems that this framework is really only focused on Mobile application and doesn't fit with any other kind of framework like Bootstrap (not mentioned in the documentation).

Therefore, my questions are:

What should be the strategy to keep a desktop version (not using Ionic but bootstrap 3) and a mobile version using Ionic? Making two distinct UI applications? One that would use Bootstrap and the other Ionic? What about duplications??

答:
Have you considered creating your backend as an API?

This way you can focus on building any type of frontend (using Ionic or bootstrap or whatever requirements you have) without worrying what happens to the backend if changes are made.


问:
What do you deliver in the first couple of iterations in Agile?
As I understand, the idea with Agile methodologies is that you deliver something functional and you deliver it often. The application gets into its final shape increment after increment.

But in the early iterations you might build the framework or foundations on which the application will stand so it's something important but not visible to users.

What gets delivered to the client in these first iterations? How do you show progress in the right direction when you build scaffolding code?

答:
It is typical to have 2 week sprints.

For me, the first sprint or 2 will likely have less "visible" features than later sprints for this exact reason (for some tenuous description of "less").

That being said, it certainly should not take you 2 weeks to build your entire scaffold and have nothing in the UI visible to show for it.

Maybe you do not flesh out every scaffold item in the first sprint or 2. Maybe parts can wait and be added later.

Maybe your first sprint has "Create webpage X with dummy data" so that you can get something shiny to show your customer. And then the next sprint has "Change webpage X to use data from the database".


答:
The Agile Manifesto suggests that Working Software is more valuable than comprehensive documentation, and the Scrum framework takes this notion to suggest that delivering tested, working software with business value to be a requirement every sprint.

Why?  Well, among other things, designers and developers often fall victim to spending lots of time on YNNI (you'll never need it) items.  Unfortunately, those frameworks you are talking about are often a big liability in this area.  The developers start building in all the stuff that the framework MIGHT have to support and suddenly you are 3 months in and don't have anything of business value to show for it.  Then it turns out the framework doesn't even really support what they end up needing.

So the suggested approach is to build only what is actually needed now, and deliver it now.

This does NOT mean that you can't build reusable parts and the like, you just always do it in support of building a current need.  Moreover, it does not mean you have to completely wear blinders to what's coming down the road--don't build things so that it's impossible to change/enhance them later.   But the key is to always be delivering business value.

There often are some key things that absolutely need to be established before anything can be delivered, such as setting up environments and the like.  For these things, a lot of teams find it useful to have a "Sprint 0" in which the groundwork is laid.  Sprint 0 can be a bit longer than your other sprints, in that it is not applied to your product backlog or burn-down, but it should still be time-boxed to a reasonable duration.

Title: What do you deliver in the first couple of iterations in Agile?

Body:
As I understand, the idea with Agile methodologies is that you deliver something functional and you deliver it often. The application gets into its final shape increment after increment.

But in the early iterations you might build the framework or foundations on which the application will stand so it's something important but not visible to users.

What gets delivered to the client in these first iterations? How do you show progress in the right direction when you build scaffolding code?


问:
Side Effects Breaking Referential Transparency
Functional Programming in Scala explains a side effect’s impact on breaking referential transparency:

side effect, which implies some violation of referential transparency.

I’ve read part of SICP, which discusses using the “substitution model” to evaluate a program.

As I roughly understand the substitution model with referential transparency (RT), you can de-compose a function into its simplest parts. If the expression is RT, then you can de-compose the expression and always get the same result.

However, as the above quote states, using side effects can/will break the substitution model.

Example:

```<code>val x = foo(50) + bar(10)
</code>```

If foo and bar do not have side effects, then executing either function will always return the same result to x. But, if they do have side effects, they will alter a variable that disrupts/throws a wrench into the substitution model.

I feel comfortable with this explanation, but I don’t fully grok it.

Please correct me and fill in any holes with respect to side effects breaking RT, discussing the effects on the substitution model as well.

答:
Imagine that you are trying to build a wall and you have been given an assortment of boxes in different sizes and shapes.  You need to fill a particular L-shaped hole in the wall; should you look for an L-shaped box or can you substitute two straight boxes of the appropriate size?

In the functional world, the answer is that either solution will work.  When building your functional world, you never have to open the boxes to see what is inside.

In the imperative world, it is dangerous to build your wall without inspecting the contents of every box and comparing them to the contents of every other box:

Some contain strong magnets and will push other magnetic boxes out of the wall if improperly aligned.

Some are very hot or cold and will react badly if placed in adjacent spaces.

I think I'll stop before I waste your time with more unlikely metaphors, but I hope the point is made; functional bricks contain no hidden surprises and are entirely predictable.  Because you can always use smaller blocks of the right size and shape to substitute for a larger one and there is no difference between two boxes of the same size and shape, you have referential transparency. With imperative bricks, it isn't enough to have something the right size and shape - you have to know how the brick was constructed.  Not referentially transparent.

In a pure functional language, all you need to see is a function's signature to know what it does.  Of course, you might want to look inside to see how well it performs, but you don't have to look.

In an imperative language, you never know what surprises might hide inside.


答:
Early iterations, especially the 1st, will contain or should at least plan for architectural spikes, which include a certain amount of discovery time and maybe some architectural prototyping.

Like you said, generally, there are structural requirements which may not mean much to the stakeholder / customer, but are required to form a strong platform or pattern orientation. You cannot get around this as you can't start building B until A is complete.

Part of the Agile approach is to have the customer close so documentation is not needed because all you need to do is pick up the phone / send email, and it's expected. The customers expectations should be set appropriately and any work completed should be very terse and NEEDED. No gold plating, no "You might need it", etc.. Build what you need in A to move onto B.

Depending on how you're attacking the project, you may only build out the required foundation in order to complete a certain module, so during the sprint planning meeting you would lay out the plans for the current sprint based on the priorities set forth by the customer, depending on what is needed for that sprint, there may be some foundational requirements, so that's what goes into sprint 1. After the 1st sprint is complete and A has been built and then plan to complete B.

If you've agreed on a timeline with the customer, as long as you're going to meet that agreement, the customer probably won't care what you do 1st or 2nd. You could always show them the unit test results, but if you say we'll have something for you to see after sprint 2 (or 3), and you deliver, it will set a strong precedence. Customers are expected to be reasonable as much as developers are and both are working towards the same goal. A completed project which meets the needs of the customer and works as expected. So worrying that there's nothing to see after sprint 1 is a moot point because the customer just wants to make sure that after sprint 20, the project will be done(-ish).


问:
Recommended architecture for an interactive table widget with multiple behaviors in Javascript / jQuery
Use case:

For an administration UI, I want an interactive table widget with a number of behaviors:

Collapse / expand (yes, this means the rows are a hierarchy)

Update of data in a child cell based on a parent cell.

Hiding or revealing of a row or an entire sub-tree based on a value update.

Two or more form elements in each row, that may depend on each other. E.g. a checkbox that will mess with the value of a text field in the same row.

DOM manipulation on newly created rows. E.g. the checkbox might be turned into a more visual kind of widget. Or

In another use case, I have the following additional behaviors:

Adding and removing rows, manually or automatically.

Drag and drop of rows. (probably not in combination with the collapse/expand, but who knows)

The problem:

Ideally, we want each of these behaviors to be implemented as a separate and independent module / plugin. BUT

If one behavior changes the DOM, then other behaviors need to know about it. E.g. if you insert a row, then the collapse/expand needs to know, to decide whether the new row should be shown or hidden. And the newly added row needs new event listeners from various other behaviors.

There might be behaviors that are triggered by the state of other behaviors. E.g. each row might contain a text field, and depending on the value, the row must be moved up or down (drag/drop).

The question:

I had to deal with this kind of problem a few times and I generally managed to get it work. However, I always hated the architecture that came out of it.

What I'd like is an approach that allows to create the different behaviors as independent modules, and then somehow plug them together.

Some more specific questions:

Where should each of the behaviors keep its state information

What about state information for a specific table row? Should it be stored as a variable on the DOM element? (e.g. $('tr')[5].isExpanded = true) or rather in a data container in the module itself?

How can modules know about DOM updates?

How should modules talk to each other?

How should the code of each module be structured? What kind of API should it expose?

How to handle multiple instances of this kind of widget on one page? (In this case, global instances don't work)

Example: https://drupal.org/project/multicrud (sorry, all I have atm is Drupal modules)

答:
I recently had to develop something vaguely similar. I ended up using jQuery UI's widget factory, as in, I developed widgets.

You can read a lot about how jQuery UI widgets work. If you want a really complicated example, look at http://silk.codeplex.com/. This is all about a very modern single page interface built on jQuery (and an ASP.NET MVC server backend) and they answer all kinds of architectural questions. Despite of it being ASP.NET MVC, there are lots of cool JavaScript to learn.

Here it is in a few words of my own. A widget is a jQuery plugin, but it has some added jQuery UI functionality. A widget instance cannot be created out of "thin air", it is added on top of a pre-existing DOM element. The widget adds a certain behavior on top of that DOM element. This is a nice two-layer architecture actually: the DOM element is the presentation, the widget instance is the logic behind it.

jQuery UI widgets provide the separation you need. Each widget is a different module, a different class, with its own constructor/destructor lifecycle, custom events, properties, options, etc.

The fact that you want to listen for DOM updates sounds bad. The DOM shouldn't drive your widgets, it should be the other way around. You shouldn't just add new DOM elements, instead you should create a DOM element, add a widget on top of it, and then let the widget do the work: put its element somewhere inside the document, notify other widgets, etc.

jQuery UI widgets support event triggering, DOM events and your custom events as well. It allows you to loosely couple your widgets. For example, when you create widget A, you might want to notify widget B about it, this is tight coupling. Instead, widget A could trigger an event, and if there is a widget B, it will get the message, this is loose coupling. This makes life a lot easier, and it also makes testing easier. There is a similar approach in Silk, they created a very cool event notification system, but I found that it's way too complex for my needs when I have very few events and subscriptions.

A widget instance is also a perfect place to store its state.

I guess that's most if not all of your questions. Please feel free to ask more specific questions. I spent a lot of time thinking about the architecture of my rich application, and I really love what I ended up with.

OwnerDisplayName: donquixote


答:
What gets delivered to the client in these first iterations?

What has highest business value for the user. For example, if the applications has complex business rules, the first iteration(s) will only contain those business rules encoded in the form of code. Customer should be satisfied as long as you have code for those business rules. (The problem of actually persuading customer to accept such a thing is completely different matter.) For example, you might show the customer's business experts your unit/acceptance tests that express what the domain should do and that code passes it with green result. Or even better, make the business experts help create those tests.

There is also question of

you might build the framework or foundations

Which I believe is much more important than what is actually delivered. There is big thing for Evolutionary Design, which says, that you should create the architecture over time instead of trying to create it in the beginning. As for foundation, this usually means some kind of database or UI framework. In which case, there is idea of "Good architecture is one which allows you postpone important decisions." And choosing database or UI is an important decision. For example, you might be fine with just in-memory storage for data instead for trying to use DB from the very first iteration.


问:
How bad can it be to lack teamwork when you are a programmer?
I'm still at school, and I know I have problems dealing with other people.

I'm not an angry or shy or different, I just like to work my way and with my opinions while respecting other's, I have a big curiosity and hunger for knowledge, but I lack practice and I guess people don't want to work with me because they might fear I would talk some kind of morale. (For example I started to learn programming using linux instead of windows, even if I use windows a lot. And I have a mac).

What happens to programmers who lack teamwork? Where does the problems begin? Does being a good programmer compensate at least a little? Is it normal for a programmer to have a vision about his work instead of just doing what he is told?

答:
There is nothing wrong with having strong opinions on how things should be. Any great programmer has plenty of them. However, you need to ask yourself: why am I writing this code?

If it's for your own entertainment, and you can do all the work yourself, then do whatever you please. However, if you're doing it for other people to use, or if you need help, or if you expect that other programmers will maintain it after you grow bored, you'll need to start taking other people's needs and notions into account.

Having a vision is fine. But it really only makes a difference if you can persuade other people to share your vision. Gates, Jobs, and Torvalds all managed to bring their visions to life by making products that served a lot of people, and getting them to buy into their visions.  Working purely your way is more pure and satisfying, but it comes at a cost. You may, as Voltaire said, be letting the perfect be the enemy of the good ("Le mieux est l'ennemi du bien").


问:
Use null object as argument to method
Consider the following piece of code

```<code>class Foo
    {
    public:
    //...
        bool valueFirstGet(int& value) const
            {
            if(this==nullptr)
                {return 0;}
            value=values[0];
            return 1;
            }
    //...

    private:
        int* values;
        size_t n_values;
    };

int main()
    {
    Foo* obj=findObject("key");
    int value;
    if(!obj->valueFirstGet(value))
        {printf("key does not exist\n");}

    return 0;
    }
</code>```

findObject returns nullptr if it cannot find the object. Is it ok to let the member function do the null check instead of its caller. In my code, there are several calls to findObject directly followed by a call to valueFirstGet so leaving the check to the caller makes the code ugly.

EDIT:

Is there a cleaner way to avoid all null checking besides having findObject to throw an exception instead of returning null?

EDIT 2:

What about a static wrapper?

答:
A common and useful way to avoid null pointer checking is by using the Null Object pattern.  Essentially, instead of using the language's built-in definition of a null object as "a null pointer you can't dereference," you create your own definition with useful null behavior appropriate to your situation.  Remember, you're a programmer.  You don't have to settle for whatever limited facilities are built into the language.

Using the null object pattern for your example might look something like this:

```<code>class Foo {
  public:
    int getCount() {
      return n_values;
    }

    int firstValue() {
      return values[0];
    }
}

class NullFoo : public Foo {
  public:
    int getCount() {
      return 0;
    }

    int firstValue() {
      return 0; // Return a useful default if you want, or throw an exception if you want.
    }
}
</code>```

Then if your findObject doesn't find the key, it instantiates and returns a NullFoo (or returns a reference to a static object), which can be dereferenced without undefined behavior, and can provide any kind of default behavior you like, including throwing an exception if the situation calls for it.

The nice thing is your regular Foo can be guaranteed to have at least one element, so you can skip a lot of checks there as well.  All the checks are done at instantiation time, and polymorphism handles the rest.

Title: Use null object as argument to method

Body:
A common and useful way to avoid null pointer checking is by using the Null Object pattern.  Essentially, instead of using the language's built-in definition of a null object as "a null pointer you can't dereference," you create your own definition with useful null behavior appropriate to your situation.  Remember, you're a programmer.  You don't have to settle for whatever limited facilities are built into the language.

Using the null object pattern for your example might look something like this:

class Foo {
  public:
    int getCount() {
      return n_values;
    }

    int firstValue() {
      return values[0];
    }
}

class NullFoo : public Foo {
  public:
    int getCount() {
      return 0;
    }

    int firstValue() {
      return 0; // Return a useful default if you want, or throw an exception if you want.
    }
}

Then if your findObject doesn't find the key, it instantiates and returns a NullFoo (or returns a reference to a static object), which can be dereferenced without undefined behavior, and can provide any kind of default behavior you like, including throwing an exception if the situation calls for it.

The nice thing is your regular Foo can be guaranteed to have at least one element, so you can skip a lot of checks there as well.  All the checks are done at instantiation time, and polymorphism handles the rest.


问:
Phenotropic Program Design
I recently ran across an idea put forth by Jaron Lanier called "phenotropic programming."

The idea is to use 'surface' interfaces instead of single point interfaces in computer programs utilizing statistics to winnow out minor errors that would typically cause a "classical" program to catastrophically crash.

The two-line description is here:

According to Jaron, the 'real difference between the current idea of
  software, which is protocol adherence, and the idea [he is]
  discussing, pattern recognition, has to do with the kinds of errors
  we're creating' and if 'we don't find a different way of thinking
  about and creating software, we will not be writing programs bigger
  than about 10 million lines of code no matter how fast our processors
  become.'

The slightly longer explanation is here.
And the even longer explanation is here.

So, the question, looking past the obvious robot-overlord connotations that people tend to pick out, how would one actually design and write a "phenotropic program?"

答:
Lanier has invented a 50 cent word in an attempt to cast a net around a specific set of ideas that describe a computational model for creating computer programs having certain identifiable characteristics.

The word means:

A mechanism for component interaction that uses pattern recognition or
  artificial cognition in place of function invocation or message
  passing.

The idea comes largely from biology.  Your eye interfaces with the world, not via a function like See(byte[] coneData), but through a surface called the retina.  It's not a trivial distinction; a computer must scan all of the bytes in coneData one by one, whereas your brain processes all of those inputs simultaneously.

Lanier claims that the latter interface is more fault tolerant, which it is (a single slipped bit in coneData can break the whole system).  He claims that it enables pattern matching and a host of other capabilities that are normally difficult for computers, which it does.

The quintessential "phenotropic" mechanism in a computer system would be the Artificial Neural Network (ANN).  It takes a "surface" as input, rather than a defined Interface.  There are other techniques for achieving some measure of pattern recognition, but the neural network is the one most closely aligned with biology. Making an ANN is easy; getting it to perform the task that you want it to perform reliably is difficult, for a number of reasons:

What do the input and output "surfaces" look like? Are they stable, or do they vary in size over time?

How do you get the network structure right?

How do you train the network?

How do you get adequate performance characteristics?

If you are willing to part with biology, you can dispense with the biological model (which attempts to simulate the operation of actual biological neurons) and build a network that is more closely allied with the actual "neurons" of a digital computer system (logic gates).  These networks are called Adaptive Logic Networks (ALN).  The way they work is by creating a series of linear functions that approximate a curve.  The process looks something like this:

... where the X axis represents some input to the ALN, and the Y axis represents some output.  Now imagine the number of linear functions expanding as needed to improve the accuracy, and imagine that process occurring across n arbitrary dimensions, implemented entirely with AND and OR logic gates, and you have some sense of what an ALN looks like.

ALNs have certain, very interesting characteristics:

They are fairly easily trainable,

They are very predictable, i.e. slight changes in input do not produce wild swings in output,

They are lightning fast, because they are built in the shape of a logic tree, and operate much like a binary search.

Their internal architecture evolves naturally as a result of the training set

So a phenotropic program would look something like this; it would have a "surface" for input, a predictable architecture and behavior, and it would be tolerant of noisy inputs.

Further Reading

An Introduction to Adaptive Logic Networks
With an Application to
Audit Risk Assessment

"Object Oriented" vs "Message Oriented," by Alan Kay

Title: Phenotropic Program Design


问:
Clarification about Grammars , Lexers and Parsers
Background info (May Skip): I am working on a task we have been set at uni in which we have to design a grammar for a DSL we have been provided with. The grammar must be in BNF or EBNF. As well as other thing we are being evaluated on the Lexical rules in the grammar and the Parsing rules - such as if rules are suitable for the language subset, how comprehensive these rules are, how clear the rules are ect.

What I don't understand is if these rules are covered in a grammar defined in BNF (it's a new topic for us).

The Question: Does a grammar for a given language that has been defined in either BNF or EBNF contain / provide rules for Lexical Analysis   and/or Parsing?  (or do these have to be specified else-where?)

Also what would be considered a lexical rule? And what would be considered a parsing rule?

答:
Yes, a BNF grammar contains all the rules you need for lexical analysis and parsing.  The difference between the two is a little fuzzy.  A good example of a lexical rule in EBNF would be:

```<code>number = [ "-" ], digit, { digit } ;
digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
</code>```

Usually lexers can be implemented using relatively simple code.  You can search a string for the next space, then see if your result starts with an optional "-", contains at least one digit after that, and contains only digits after that.  Lexers used to almost always be a separate step, but are usually lumped together with the parser nowadays.  Hence the fuzziness.

A parser rule would use the number non-terminal to make something larger, like the following addition expression.

```<code>add = number, "+", number
</code>```

Even though they are mixed up in the same file, your professor is still going to want to see a clear distinction between "lexer" rules and "parser" rules.  For example, don't do this:

```<code>add = {"0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" }, "+",
      {"0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" }
</code>```

Not only is that error prone, it's difficult to read and difficult to implement.

Body:
Yes, a BNF grammar contains all the rules you need for lexical analysis and parsing.  The difference between the two is a little fuzzy.  A good example of a lexical rule in EBNF would be:

number = [ "-" ], digit, { digit } ;
digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;

Usually lexers can be implemented using relatively simple code.  You can search a string for the next space, then see if your result starts with an optional "-", contains at least one digit after that, and contains only digits after that.  Lexers used to almost always be a separate step, but are usually lumped together with the parser nowadays.  Hence the fuzziness.

A parser rule would use the number non-terminal to make something larger, like the following addition expression.

add = number, "+", number

Even though they are mixed up in the same file, your professor is still going to want to see a clear distinction between "lexer" rules and "parser" rules.  For example, don't do this:

add = {"0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" }, "+",
      {"0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" }

Not only is that error prone, it's difficult to read and difficult to implement.


问:
Should cucumber step definitions in Java be static methods or instance methods?
We are new to using cucumber with selenium to write automated test suites.

Our initial approach was to have one java class per feature file.

Now we added instance methods in each class for corresponding step definitions.

Now if we need to re-use a step definition in some other feature file we are facing problems as we can't re-use same annotation with same regex pattern with any other method of other class and neither can we use the existing step definition which is in some other class.

These methods are sharing instance variables like the reference to the driver.

Now to re-use an instance method as a step definition is also a problem because these methods are not re-usable outside the class and I can't put all step definitions inside one class.

I looked at some samples of ruby, I found that they write some sort of blocks that don't have access to shared state.
They just execute steps.

So in Java should I always make static methods that will just execute steps one by one and share no state ?

答:
Define static methods in the following scenarios only:

If you are writing utility classes and they are not supposed to be changed.

If the method is not using any instance variable.

If any operation is not dependent on instance creation.

If there is some code that can easily be shared by all the instance methods, extract that code into a static method.

If you are sure that the definition of the method will never be changed or overridden. As static methods can not be overridden.


答:
The grammar for lexical analysis is typically specified via regular expressions (especially for university-type projects). It accepts a regular language.

A parser usually accepts a context-free language, which may be specified via BNF.

The distinction between a parser and a scanner (or lexical analyzer) is somewhat artificial, but it makes writing parsers easier.

See http://en.wikipedia.org/wiki/Chomsky_hierarchy

Title: Clarification about Grammars , Lexers and Parsers

Body:
Background info (May Skip): I am working on a task we have been set at uni in which we have to design a grammar for a DSL we have been provided with. The grammar must be in BNF or EBNF. As well as other thing we are being evaluated on the Lexical rules in the grammar and the Parsing rules - such as if rules are suitable for the language subset, how comprehensive these rules are, how clear the rules are ect.

What I don't understand is if these rules are covered in a grammar defined in BNF (it's a new topic for us).

The Question: Does a grammar for a given language that has been defined in either BNF or EBNF contain / provide rules for Lexical Analysis   and/or Parsing?  (or do these have to be specified else-where?)

Also what would be considered a lexical rule? And what would be considered a parsing rule?


问:
When should I stop committing to master on new projects?
Whenever a new project starts, it usually makes sense to start by committing straight to master until you've got something "stable", and then you start working in branches.

At least, this is how I normally do it. Is there a way to immediately start branches from second commit? Does it make sense to do it this way? Obviously, "Initial Commit" will always be on master, but after that, when will I know it's the right time to start making branches for new features?

答:
There are mainly two situations where you typically want to start working with branches:

when you or your team has to start a new feature which has the slightest chance not to be added to the next release (which may be the first release ever), then start the development in a separate feature branch

when you have to provide fixes for severe bugs to the latest release, and you want to create a new bugfix release containing only those fixes, but no newly developed (and probably unstable) features

For such kind of decisions, I think its helpful to think always in terms of "new features" or "bugfixes", from the point where you have a first compilable / runnable version of your program.

Michael Feathers lists four reasons to change in his famous book, but I would put "optimize resources" under "new feature branch" (for a non-functional feature) and "improving the design" most times under "new feature branch" as well, since IMHO one should never improve the design when this is not intended for the purpose of making the implementation of a specific feature easier.


答:
Summary:

The design problem you've presented actually deals with two kinds of issues, thus it involves two classes of possible solutions too.

Is it ok to let the member function do the null check instead of its
  caller?

Semantically speaking, it does not make sense. To call an instance method of a null object is logically incorrect because the object does not exist yet.

So that being said, a cleaner solution to this design problem would be to handle the case as clearly as possible by using the exception mechanism available in the language. Let the findObject throw the exception and let the caller routine handles it as needed. This results to a more readable code.

In my code, there are several calls to findObject directly followed
  by a call to valueFirstGet so leaving the check to the caller makes
  the code ugly.

This is where a wrapper method will come in handy to avoid repeating yourself.

Title: Use null object as argument to method

Body:
Consider the following piece of code

```<code>class Foo
    {
    public:
    //...
        bool valueFirstGet(int& value) const
            {
            if(this==nullptr)
                {return 0;}
            value=values[0];
            return 1;
            }
    //...

    private:
        int* values;
        size_t n_values;
    };

int main()
    {
    Foo* obj=findObject("key");
    int value;
    if(!obj->valueFirstGet(value))
        {printf("key does not exist\n");}

    return 0;
    }
</code>```

findObject returns nullptr if it cannot find the object. Is it ok to let the member function do the null check instead of its caller. In my code, there are several calls to findObject directly followed by a call to valueFirstGet so leaving the check to the caller makes the code ugly.

EDIT:

Is there a cleaner way to avoid all null checking besides having findObject to throw an exception instead of returning null?

EDIT 2:

What about a static wrapper?


答:
Immediately.

The key is the question of what the policy for Master is.  With git, typically, the branch policy on Master is the <s>buildable</s> stable release.  Sometimes, Master is the 'mainline' where branches are made from and merged to prior to merging to a Release branch.  These are two different role/policy approaches.

It is often a source of errors for people to change the role or the policy of a branch part way through the project.  It is easier for a solo developer to communicate these changes out to contributors, but trying to get a dozen programmers to all recognize "Master is now at 1.0, please branch features rather than everyone pushing to it"

I touched on the policy approach above.  The policy for Master is that it is the <s>buildable</s> stable release.  Checking in small incremental changes into this means you don't have something <s>buildable</s> stable at all times.  Not checking in small changes goes against the "lots of small (but complete) checkins" that tends to be the best policy (and encouraged by easy branching).

From a role based perspective, you've started out with master being mainline, release, maintenance, and development roles, and then some point down the road the development and maintenance role moves to branches.  This again means a change in what is allowed on master and can confuse contributors as to where things belong.  It can also (slightly) confuse the branch history, encouraging large commits that mean bigger and harder to understand merges.

Key the roles and policies on the branches simple and consistent from the start.

This "branch on policy change" can be seen in the Branching Patterns.  The idea of each branch having roles, can be read in Advanced SCM Branching Strategies.  Both of these are very good reads.

Title: When should I stop committing to master on new projects?

Body:
Whenever a new project starts, it usually makes sense to start by committing straight to master until you've got something "stable", and then you start working in branches.

At least, this is how I normally do it. Is there a way to immediately start branches from second commit? Does it make sense to do it this way? Obviously, "Initial Commit" will always be on master, but after that, when will I know it's the right time to start making branches for new features?


答:
My understanding is that Cucumber in Java uses step files that are POJOs and has the ability to do dependency injection via various cucumber extensions - at least, that's what it says in their documentation.

As such, unless your specs are very simple and always going to remain that way, you really want to use real instances. Static is contagious - if you make your steps static then you'll need to make everything else static, and that's not a good place to be.

Even if you don't use true DI, inheritance can also be very useful in step files, and that's generally a better way to reuse code than a spaghetti mess of statics. If all of your steps need to reference the driver, then put it in the base class, and if you want to be really cheap, use a parameterless constructor with the Service Locator pattern (which is not a great practice in general but very convenient for behaviour tests).

You say that you're concerned that step code isn't reusable outside the class, but it's not supposed to be. Steps should only be referenced by the specs themselves and should (generally) not reference each other. If there's functionality that's common to many different steps or feature groups, you should put it into a Page Object or some kind of helper. That's the reason why most of the Cucumber implementations have DI support; they want you to write your test code to approximately the same level of quality as your system code, because as it turns out, you'll likely spend 30-40% of developer hours maintaining the automated tests, so all the same best practices apply.

Title: Should cucumber step definitions in Java be static methods or instance methods?

Body:
We are new to using cucumber with selenium to write automated test suites.

Our initial approach was to have one java class per feature file.

Now we added instance methods in each class for corresponding step definitions.

Now if we need to re-use a step definition in some other feature file we are facing problems as we can't re-use same annotation with same regex pattern with any other method of other class and neither can we use the existing step definition which is in some other class.

These methods are sharing instance variables like the reference to the driver.

Now to re-use an instance method as a step definition is also a problem because these methods are not re-usable outside the class and I can't put all step definitions inside one class.

I looked at some samples of ruby, I found that they write some sort of blocks that don't have access to shared state.
They just execute steps.

So in Java should I always make static methods that will just execute steps one by one and share no state ?


答:
If you follow git-flow - and, quite frankly, I think you're insane if you use Git and don't use that branching model - then you should never commit to master until you're actually ready for a public release.

Your first commit to master should be an empty repository. Your next commit to master should be a merge commit from the develop branch or a temporary release branch, and it should be stable, tested, and ready for deployment (if it's an application) or public distribution (if it's a library).

There are other branching models for Git, but most of them have are derived from older centralized SCM models and can lead to serious problems in a DVCS environment. You don't have to actually use the git-flow extension, and you don't necessarily need all those release/hotfix/feature branches, but the bare bones is develop and master, and unstable code goes in develop.


答: I am going to take a radical position: branch on every idea. First in git branches are cheap, the main cost of a branch is remembering what is is for. I also agree that the first commit to master is a release candidate. I recommend starting with a proof of concept branch. When you have proven your concept you can merge it with your empty devel branch or rewrite depending on how good your first try is. from this point you branch from devel for every bug, feature, abstraction, etc.</p>


答:
I think we are at the very beginning of one of the steps it will take to get there and that is gathering lots of data in formats that can be analyzed. The Internet, Google searches, Fitbit (Every step you take, every move you make, I'll be watching you.), FourSquare, a smart phone geo location, Facebook posts and SO question data are all being gathered. We're no where near the amount of sensory data the average human is compiling over a life time, but we're getting close.

Start categorizing millions of pictures of birds and getting feedback from people telling you that's not a bird and you can start to create an algorithm. From there a fuzzier impression (I would call it a model, but that's too exact for what we're trying to code.) can be created.

```<code>class Birdish
</code>```

How does a pet dog know so much about the owner? Because it watches her a lot. The dog has listened to cars pulling into the driveway and correlating that with the owner opening the front door that it appears as of the dog can recognize a car by its sound. We could do this too, but we see no reason to attend to this. And that's what's wrong with current software, it doesn't pay attention to what the user is doing. It just waits for the user to do what IT expects the user to do.

Something as simple as setting an alarm clock could be done by a little observation/analysis of my current habits. We gave up on setting VCR timers before the technology was replaced by digital. And would that have happened as fast if we could have interfaced the TV Guide with the VCR? I've watched the same TV show 4 weeks in a row at the same time, but the 5th one I didn't even turn the TV on. Obviously I want it recorded. Can't you tell I'm staying late at work writing this post and with my typical commute won't make it home in time? You've got the data, do the math.

Gather more and more data and then you can come up with better ways to analyze, recognize and covert it. We're going beyond what can be input only from a keyboard with our phone cameras and soon eye glass cameras. It's just the beginning.

Title: Phenotropic Program Design

Body:
I recently ran across an idea put forth by Jaron Lanier called "phenotropic programming."

The idea is to use 'surface' interfaces instead of single point interfaces in computer programs utilizing statistics to winnow out minor errors that would typically cause a "classical" program to catastrophically crash.

The two-line description is here:

According to Jaron, the 'real difference between the current idea of
  software, which is protocol adherence, and the idea [he is]
  discussing, pattern recognition, has to do with the kinds of errors
  we're creating' and if 'we don't find a different way of thinking
  about and creating software, we will not be writing programs bigger
  than about 10 million lines of code no matter how fast our processors
  become.'

The slightly longer explanation is here.
And the even longer explanation is here.

So, the question, looking past the obvious robot-overlord connotations that people tend to pick out, how would one actually design and write a "phenotropic program?"

Body:
I think we are at the very beginning of one of the steps it will take to get there and that is gathering lots of data in formats that can be analyzed. The Internet, Google searches, Fitbit (Every step you take, every move you make, I'll be watching you.), FourSquare, a smart phone geo location, Facebook posts and SO question data are all being gathered. We're no where near the amount of sensory data the average human is compiling over a life time, but we're getting close.

Start categorizing millions of pictures of birds and getting feedback from people telling you that's not a bird and you can start to create an algorithm. From there a fuzzier impression (I would call it a model, but that's too exact for what we're trying to code.) can be created.

class Birdish

How does a pet dog know so much about the owner? Because it watches her a lot. The dog has listened to cars pulling into the driveway and correlating that with the owner opening the front door that it appears as of the dog can recognize a car by its sound. We could do this too, but we see no reason to attend to this. And that's what's wrong with current software, it doesn't pay attention to what the user is doing. It just waits for the user to do what IT expects the user to do.

Something as simple as setting an alarm clock could be done by a little observation/analysis of my current habits. We gave up on setting VCR timers before the technology was replaced by digital. And would that have happened as fast if we could have interfaced the TV Guide with the VCR? I've watched the same TV show 4 weeks in a row at the same time, but the 5th one I didn't even turn the TV on. Obviously I want it recorded. Can't you tell I'm staying late at work writing this post and with my typical commute won't make it home in time? You've got the data, do the math.

Gather more and more data and then you can come up with better ways to analyze, recognize and covert it. We're going beyond what can be input only from a keyboard with our phone cameras and soon eye glass cameras. It's just the beginning.


问:
database replication or custom solution like creating enterprise "bus"
I'd like some input on how to keep databases that are running on different servers throughout our organization synchronized.

We have a registration system of sorts, and when user "John Doe" registers on server 1, this registration information needs to be instantly available on server 2 and 3. Currently, our network administrators have set up postgresql replication to do this, and it seems to be working fine.

When this solution is up and running full scale, we will have 2 databases being replicated to potentially 4 or 5 different servers. Two database because the registration information is saved into two different databases.  One database is a CRM, the other is a reservation application.  (BTW.  This is all on a LAN, vs WAN)

What I'm trying to figure out in my head is whether postgresql replication is the best way to do this or if we should be looking at a software solution.  I saw one post here where someone was asking about ETL vs. REST API.
REST may be a good option I guess.  I'm not sure that it completely suits our needs ... I'll have to think about it some more..

But I'm also thinking about Enterprise integration software ... like iway or something like that where you would identify the source database, identify the taraget database... and then define the interval. The tool would then monitor the source database for changes every X minutes.  Anytime there is a change, it would update the target databases.

But I'm not sure I'm asking myself all the right questions to do a proper evaluation.
Here are some I thought of so far:

How fresh does the data need to be on the servers?  Has to be 'fairly' real-time... I would say within seconds.

What's the volume of information?  several records could be created in the source database every few seconds.

What else should I be considering?

Thanks.

答:
Ask yourself and your business very carefully, sincerely, and repeatedly, if it really needs to be real-time. As in, really instant? Are we talking about atomic, you can never ever have those two servers out of sync, not even for a microsecond? Or is there really some kind of SLA attached and the data can be stale for maybe a few milliseconds, or a few seconds, or even a few minutes?

The only way you can have atomic replication is to use a broker and massive distributed transactions. This is the BizTalk style architecture, and it is painfully, unbearably slow, brittle as year-old soup crackers, and unbelievably difficult to test.

Commercial replication software like Golden Gate is nearly real-time. It's also very expensive. But what you get for that high price is active-active replication - something that very few built-in replication tools support - among many other high-end features that are very important if you're building a high-availability environment (let's say at least four nines, and not just during business hours).

Enterprise Service Bus, at least the ones that aren't selling snake oil, are based on messaging and are the complete opposite of real-time. Frameworks like NServiceBus, Apache Camel, MassTransit, and so on, focus primarily on asynchronous messaging, which means eventual consistency. What this means, which is paradoxical to some, is that it's very fast and generally easier to maintain, but you risk physical or sometimes logical inconsistencies between services. There's no point in adopting one of these if you don't have or plan on building a Service-Oriented Architecture in which services all function independently and without the need for any shared data.

I'm not really sure which of these you want. Many programmers and most non-technical managers say they want real-time integration, but when they really stop to analyze the problem and the business, it turns out that the SLA is far more forgiving than that. For one thing, a user's response time is going to be measured in seconds, so really, who cares if things are inconsistent for a half-second? That only really matters in things like medical equipment or automated trading systems. Moreover, optimistic concurrency has been around forever and it's usually "good enough" for most applications - in other words, you can allow things to become inconsistent 1% of the time because you know that 99% of the time they'll be fine, and for that troublesome 1% you can push the decision back to the user to resolve it.

So, think about what you really need and choose accordingly. ESBs and SOAs are great if you have a solid understanding of the business and stakeholders willing to cooperate. They also require a lot of effort in the analysis and design areas, so if you want a pure infrastructure solution, better to go with a commercial replication tool (or, I suppose, an open-source one if you find one that does everything you need). Only if you're a highly-specialized sector that requires realtime distributed consistency should you even consider a broker-based solution; it's almost never the right choice.

Whether you choice REST, SOAP, AMQP, Protocol Buffers or some other type of messaging is almost entirely irrelevant to your choice of architecture. Those are just TLAs (well, FLAs) used to describe formats. You can use almost any format with almost any architecture. Worry about the architecture first, then choose a format based on how well-supported it is within that architecture and how familiar your team is with it.

Edit: Since you asked for a list of questions to ask, here are mine:

How fast does it need to be?

Does it really need to be real time?

Does it really really need to be real time?

Are you sure it needs to be real time?

What would happen if it isn't real time?

What's the cost or risk associated with whatever those bad things are?

What's the minimum interval you would consider to be real time?

What research is that interval based on?

How was that research validated?

Are you really willing to pay 10x as much in development and maintenance in order to have real time consistency?


问:
How to create a Python method prototype
If I'm giving an interview coding question in Java, I can specify the most of the question just by giving a method signature.  (Made-up example follows.)

```<code>public class Table {
  public String identifier;
  public int seatCount;
}

public static List<String> tablesWithEnoughSeats(List<Table> tables, int minSeats)
</code>```

If the candidate prefers Python, how do I present the problem for them?  The Python method signature doesn't specify the data type.  Is there some standard Python way of doing this?

If I look at Python coding challenges online, they tend to specify the requirements as taking certain input to produce certain output.  I don't want the candidate to waste their time writing code to parse an input file.  (My example has just String and int, but the actual interview problem might contain more complex data.)  What's the best way to express the parameter constraints so that the candidate can implement the algorithm I'm interested in without doing a bunch of plumbing?

答:
Mock your inputs. Say "Assume that this array consists of integers or floats or whatever". You can also annotate things with comments.

I'd write this in Python like so:

```<code>class Table: #identifier: string, seat_count: int
    def __init__(self, identifier, seat_count):
        self.identifier = identifier
        self.seat_count = seat_count
</code>```

I'm prone to writing Python functionally so I'd instantiate a list of tables then call a function that checked each table to see if had enough seats or not. I'd probably use a filter to that. Could also do a list comprehension. The latter is more "Pythonic".

Title: How to create a Python method prototype

Body:
Mock your inputs. Say "Assume that this array consists of integers or floats or whatever". You can also annotate things with comments.

I'd write this in Python like so:

class Table: #identifier: string, seat_count: int
    def __init__(self, identifier, seat_count):
        self.identifier = identifier
        self.seat_count = seat_count

I'm prone to writing Python functionally so I'd instantiate a list of tables then call a function that checked each table to see if had enough seats or not. I'd probably use a filter to that. Could also do a list comprehension. The latter is more "Pythonic".


答:
If the actual syntax doesn't matter to you (which sounds like the case), explain the method signature and allow them to write pseudo-code to fill in the algorithm. Then, it is effectively irrelevant which 'language' they choose to use as long as the interviewee can explain their thinking to you.

There's no harm in guiding them somewhat to; for example explicitly stating that you don't need them to parse an input file. If they go down that route say something like "imagine we already have a function to parse the file and it returns an array of strings, what is your next step?"

Title: How to create a Python method prototype

Body:
If I'm giving an interview coding question in Java, I can specify the most of the question just by giving a method signature.  (Made-up example follows.)

```<code>public class Table {
  public String identifier;
  public int seatCount;
}

public static List<String> tablesWithEnoughSeats(List<Table> tables, int minSeats)
</code>```

If the candidate prefers Python, how do I present the problem for them?  The Python method signature doesn't specify the data type.  Is there some standard Python way of doing this?

If I look at Python coding challenges online, they tend to specify the requirements as taking certain input to produce certain output.  I don't want the candidate to waste their time writing code to parse an input file.  (My example has just String and int, but the actual interview problem might contain more complex data.)  What's the best way to express the parameter constraints so that the candidate can implement the algorithm I'm interested in without doing a bunch of plumbing?


答:
You will end up working alone.

Benefits of working in a team:

1- Interactive Help: you will not stuck in a problem for hours/days.

2- You will learn things that you will not find in books/online tutorials,forums.

3- Competition: will fuel your motivation to overcome teamates.

4- Discussions: which is better than hours reading books and blogs.

Title: How bad can it be to lack teamwork when you are a programmer?

Body:
I'm still at school, and I know I have problems dealing with other people.

I'm not an angry or shy or different, I just like to work my way and with my opinions while respecting other's, I have a big curiosity and hunger for knowledge, but I lack practice and I guess people don't want to work with me because they might fear I would talk some kind of morale. (For example I started to learn programming using linux instead of windows, even if I use windows a lot. And I have a mac).

What happens to programmers who lack teamwork? Where does the problems begin? Does being a good programmer compensate at least a little? Is it normal for a programmer to have a vision about his work instead of just doing what he is told?


答:
Give them the data structure (explain namedtuple if they haven't seen it before):

```<code>from collections import namedtuple
Table = namedtuple('Table', 'name seats')
</code>```

Then show them as sample invocation:

```<code>>>> tables = [
...     Table(name="First", seats=6),
...     Table(name="Second", seats=4)
... ]
>>> tablesWithEnoughSeats(tables, 5)
[Table(name="First", seats=6)]
</code>```

Title: How to create a Python method prototype

Body:
Give them the data structure (explain namedtuple if they haven't seen it before):

from collections import namedtuple
Table = namedtuple('Table', 'name seats')

Then show them as sample invocation:

>>> tables = [
...     Table(name="First", seats=6),
...     Table(name="Second", seats=4)
... ]
>>> tablesWithEnoughSeats(tables, 5)
[Table(name="First", seats=6)]


问:
Payment Gateways and RESTful API
I have a RESTful API that offers eCommerce functionality. One area I'm struggling to decide on the correct implementation is how to process payments.

Lets say I have the following URI GET .../checkout/{id}/payment. This resource provides details to the client application of what details needs to be submitted to make a payment. The specifics of the information in the resource depends on the implementations below

Implementation 1 The resource contains basic payment fields to be filled in like card number, billing address etc. The data is sent to the API using POST .../checkout/{id}/payment. The API then submits a request to the payment gateway (e.g. paypal), waits for the response, and then sends an appropriate response back to the client application.

Implementation 2 The resource contains details of how to submit a request directly to the payment gateway (e.g. paypal). The client submits the payment to the gateway, waits for a response, and then sends the payment reference (normally always provided by a payment gateway) back to the API using POST .../checkout/{id}/payment.

The problem I am having is that both have pros and cons.

Implementation 1 I would say is the more fail safe method as everything is contained in one request to the API. The API can then update backend tables once the payment has been processed, and return success or failure status to the client. Since the API is sending a response to the gateway, it knows the response it receives is genuine.

Implementation 2 frees the API from having to process the payment which is great, but requires the client to make two requests. One to the payment gateway and one to the API with the reference. Additionally, how can I validate the payment reference on the API without calling the gateway? A dishonest client could send any reference back to the API which then may be incorrectly marked as paid.

Just wanted to throw my ideas out there, but if anyone has a really good solution for implementing Payment Gateways and RESTful API web services that would be great.

UPDATE
Just thought of an Implementation 3. I could actually create a separate smaller API to handle the payments. It would work in a similar way to implementation 1 except that the client application doesn't post to api.site.com/.... but posts to gateway.site.com/... This give me a degree of security as I control the code on gateway.site.com and ensures that api.site.com isn't being bogged down by waiting for the payment provider to respond. The gateway api then essentially becomes a client of the main API and posts the payment success details to it.

Any thoughts on this?

答:
A lot depends on wether you are building a platform, for which Implementation 1 is suitable or if it's just your own eCommerce platform, Implementation 2 may suite better.

Implementation 1 allows for scalability if you plan to offer multiple payment gateways. They all offer their own REST APIs and abstraction will provide you the scalability. If you have single gateway, advantage would be flexiblity of changing payment gatewayat a later date, which is becoming a common thing now-a-days. You will also have control in case there are network related glitches or downtimes. If you are storing data in any form, you would have to deal with PCI compliance, which is additional time and money.

Implementation 2 Will get you up and running in fastest possible manner, plus no need to deal with PCI compliance. Agreed you would have to make a second call to gateway, but it provides security on transaction validity, which would be faster compared to processing payment.

Title: Payment Gateways and RESTful API


问:
What popular "best practices" are not always best, and why?
"Best practices" are everywhere in our industry.  A Google search on "coding best practices" turns up nearly 1.5 million results.  The idea seems to bring comfort to many; just follow the instructions, and everything will turn out fine.

When I read about a best practice - for example, I just read through several in Clean Code recently - I get nervous.  Does this mean that I should always use this practice?  Are there conditions attached?  Are there situations where it might not be a good practice?  How can I know for sure until I've learned more about the problem?

Several of the practices mentioned in Clean Code did not sit right with me, but I'm honestly not sure if that's because they're potentially bad, or if that's just my personal bias talking.  I do know that many prominent people in the tech industry seem to think that there are no best practices, so at least my nagging doubts place me in good company.

The number of best practices I've read about are simply too numerous to list here or ask individual questions about, so I would like to phrase this as a general question:

Which coding practices that are popularly labeled as "best practices" can be sub-optimal or even harmful under certain circumstances?  What are those circumstances and why do they make the practice a poor one?

I would prefer to hear about specific examples and experiences.

答:
"Be liberal with comments"

Comments are definitely a good thing, but too many are just as bad if not worse than not enough.  Why?  Well, people tend to tune comments out if they see too many unnecessary ones.  I'm not saying that you can have perfectly self-documenting code, but it is preferable to code that needs comments for explanation.


问:
A good design pattern for a Web API where models/enities are searchable by foreign keys
I was hoping someone might have some ideas on how to create a RESTful web API where models/entities are searchable by a foreign key. I see a a lot of tutorials where the functionality consist of listing all records in the entire model or retrieving a single record from the model by a primary key, but not by an arbitrary/foreign key. It my be as simple as checking for extra conditions in the request but I thought I would get some advice all the same.</p>

答:
First of all, you are going to design a very poor API if you are thinking of "foreign keys" while you design said API. As an API designer, your business is resources, not entities or keys.

If you think in terms of resources then the answer is really pretty obvious. You either have an embedded resource (orders belonging to a customer) or you have a query.

Embedded resources are just like subdirectories. You use the path for that:

```<code>/api/customers/4/orders
</code>```

And a query is, not surprisingly, a query string:

```<code>/api/orders?customerId=4
</code>```

Or, some people feel that this is more RESTful:

```<code>/api/orders?customer=/api/customers/4
</code>```

All of these are fine. It's partly a matter of preference and partly a matter of just how complex your relationships are.

But one thing is for sure, you're on the wrong track talking about things primary keys and foreign keys. Those are database terms and APIs have nothing to do with your database. It's not uncommon at all to have multiple representations of the same resource, for example:

```<code>/api/customers/123/
/api/customers/acme+inc/
/api/customers/123-acme+inc/
/api/customers/123/acme+inc/
/api/customers/me/ (say you are ACME Inc.)
</code>```

The whole idea of a REST API is that these resources identifiers (URIs) are opaque. You don't know what the "primary key" is, and you might not be entirely sure what the "ID" is. So again, just repeating one more time for the record, don't use database terminology when you're reasoning about a Web API, it will lead you to the wrong design.

Body:
First of all, you are going to design a very poor API if you are thinking of "foreign keys" while you design said API. As an API designer, your business is resources, not entities or keys.

If you think in terms of resources then the answer is really pretty obvious. You either have an embedded resource (orders belonging to a customer) or you have a query.

Embedded resources are just like subdirectories. You use the path for that:

/api/customers/4/orders

And a query is, not surprisingly, a query string:

/api/orders?customerId=4

Or, some people feel that this is more RESTful:

/api/orders?customer=/api/customers/4

All of these are fine. It's partly a matter of preference and partly a matter of just how complex your relationships are.

But one thing is for sure, you're on the wrong track talking about things primary keys and foreign keys. Those are database terms and APIs have nothing to do with your database. It's not uncommon at all to have multiple representations of the same resource, for example:

/api/customers/123/
/api/customers/acme+inc/
/api/customers/123-acme+inc/
/api/customers/123/acme+inc/
/api/customers/me/ (say you are ACME Inc.)

The whole idea of a REST API is that these resources identifiers (URIs) are opaque. You don't know what the "primary key" is, and you might not be entirely sure what the "ID" is. So again, just repeating one more time for the record, don't use database terminology when you're reasoning about a Web API, it will lead you to the wrong design.


问:
Which useful alternative control structures do you know?
Similar question was closed on SO.

Sometimes when we're programming, we find that some particular control structure would be very useful to us, but is not directly available in our programming language.

What alternative control structures do you think are a useful way of organizing computation?

The goal here is to get new ways of thinking about structuring code, in order to improve chunking and reasoning.

You can create a wishful syntax/semantic not available now or cite a less known control structure on an existent programming language.

Answers should give ideas for a new programming language or enhancing an actual language.

Think of this as brainstorming, so post something you think is a crazy idea but it can be viable in some scenario.

It's about imperative programming.

答:
It is a fun question, as @Macneil said.

My favorite unusual control structure, which I (humble cough) discovered, is differential execution.

It has certain uses. For me, the overwhelming use is in programming user interfaces, which is an instance of the more general problem of maintaining redundant data in correspondence. On the one hand, there is application data, and on the other, there are UI controls, that need to be kept in agreement. This sounds like "binding" but there's actually a lot more to it.

Usually I implement it by macros in C or C++. In C# I have to do it by hand-expanding statements. That is a pain, but it works.

Once I implemented it in terms of Lisp macros, and then it was very clean. It did not require carefulness on the part of the programmer. I could have done the same thing in any other structured language if I took the trouble to write a complete parser and then generate all the right stuff. That's a big project, and I haven't done it.


答:
I would expect any sufficiently trained and experienced programmer wouldn't even need the method signiature for a mock question (in practise is an entirely different matter).

I am managing a restaurant as a simple list of table objects

Each table has a name and a fixed number of seats.

Given a list of tables and a required number of seats for a given party, write a methods that finds and returns a second list of all tables that could accomodate that party.

As an optional extra, sort the list so as to minimise the number of "wasted seats" at a table.

Now, the names of properties and the class definition can all be abstracted away and they can get to the business of writing the actual code.

Title: How to create a Python method prototype


答:
For most cases, Implementation 1 would be more suitable.  Its easier for you to secure, and probably a lot easier to debug/log.

The big problem I have with Implementation 2 is that you'd have to distribute credentials to the client in order for them to directly connect to the payment gateway.  That may be possible for some systems, but I doubt all.  I suspect it would also be much more difficult to debug where a problem occurs.  What happens, for example, if the payment gets sent to the gateway, but you never receive the 2nd confirmation post?

Title: Payment Gateways and RESTful API

Body:
I have a RESTful API that offers eCommerce functionality. One area I'm struggling to decide on the correct implementation is how to process payments.

Lets say I have the following URI GET .../checkout/{id}/payment. This resource provides details to the client application of what details needs to be submitted to make a payment. The specifics of the information in the resource depends on the implementations below

Implementation 1 The resource contains basic payment fields to be filled in like card number, billing address etc. The data is sent to the API using POST .../checkout/{id}/payment. The API then submits a request to the payment gateway (e.g. paypal), waits for the response, and then sends an appropriate response back to the client application.

Implementation 2 The resource contains details of how to submit a request directly to the payment gateway (e.g. paypal). The client submits the payment to the gateway, waits for a response, and then sends the payment reference (normally always provided by a payment gateway) back to the API using POST .../checkout/{id}/payment.

The problem I am having is that both have pros and cons.

Implementation 1 I would say is the more fail safe method as everything is contained in one request to the API. The API can then update backend tables once the payment has been processed, and return success or failure status to the client. Since the API is sending a response to the gateway, it knows the response it receives is genuine.

Implementation 2 frees the API from having to process the payment which is great, but requires the client to make two requests. One to the payment gateway and one to the API with the reference. Additionally, how can I validate the payment reference on the API without calling the gateway? A dishonest client could send any reference back to the API which then may be incorrectly marked as paid.

Just wanted to throw my ideas out there, but if anyone has a really good solution for implementing Payment Gateways and RESTful API web services that would be great.

UPDATE
Just thought of an Implementation 3. I could actually create a separate smaller API to handle the payments. It would work in a similar way to implementation 1 except that the client application doesn't post to api.site.com/.... but posts to gateway.site.com/... This give me a degree of security as I control the code on gateway.site.com and ensures that api.site.com isn't being bogged down by waiting for the payment provider to respond. The gateway api then essentially becomes a client of the main API and posts the payment success details to it.

Any thoughts on this?


答:
A thought I had recently :

If you used high-level ideas like Haskell's Maybe Monad to wrap remote-procedure calls to other systems. You send a request to the server. But nothing comes back (server is broken). Or a Promise comes back (server is busy) and your programs continue working with those None or Promised values. That's kind of like the fault tolerance Lanier is looking for.

Maybe there are ways of encapsulating other eventualities. For example remote calls which come back with an approximation which is increasingly refined over time by some kind of background negotiation. ie. what comes back is something like a Promise but not just "keep holding on and working with this and a proper value will turn up shortly" but "keep holding on and working with this and a better approximation will turn up shortly". (And again, and again). This would be able to hide a lot of faults from the programmer, just as networking protocols hide a lot low level networking failure from the programmer.

Title: Phenotropic Program Design


问:
How can I move a library inside a project's source tree and compiling static binaries?
How can I move a library inside a project's source tree and compiling static binaries?

I want to use a particular tool that utilizes ANCIENT binaries without upgrading it's API usage. This way I can use the old libraries inside the single binary without wrecking the local host environment. I am on nix with netbeans/eclipse/code::blocks.

I don't have a problem reading, just looking for a starting point. Any thoughts?

答:
You could make a script to compile the lib and modify your project file to use that library's path.
for qmake it would be :

```<code>DEPENDPATH += . oldlib/
INCLUDEPATH += . oldlib/
LIBS += -Wl,-rpath=oldlib-build-path-L. -L../ -Loldlib-build-path -loldlib
</code>```

Note that the rpath part is strictly for gcc, could be different on different compilers.

Body:
You could make a script to compile the lib and modify your project file to use that library's path.
for qmake it would be :

DEPENDPATH += . oldlib/
INCLUDEPATH += . oldlib/
LIBS += -Wl,-rpath=oldlib-build-path-L. -L../ -Loldlib-build-path -loldlib

Note that the rpath part is strictly for gcc, could be different on different compilers.


问:
Help with inheritance hierarchy design
I'm having trouble designing an inheritance hierarchy.

In the figure:

Base class:

This uses the Template Method.

Contains core logic/algorithm that
calls virtual/abstract methods

Derived types:

These classes provides concrete implementation of the virtual/abstract methods expected by the Base.

Conditions:

I have a virtual method (Run).

The default Run method uses another virtual method (Proc).

If a derived class uses the default Run behaviour, they must implement Proc.

If a derived class overrides the Run behaviour, then it shouldn't have to care about the existence of Proc, let alone overriding it.

I've considered making Run() abstract and let each derived class handle their own.
But then I'll end up with duplicate code.

I'm using a simplified example here.

In my actual project, I have several "Run"-typed virtual methods, each calling several "Proc"-typed methods.

Because of that, I have a whole bunch of virtual "Proc" methods with "throw new NotImplementedException()"

Creating a new derived type is also confusing, because the coder may not know which virtual methods must be implemented/can be ignored/etc.

I've considered using a strategy pattern, but since I have several "Run" methods, each one of those would have to be a strategy, which seems like overkill/overengineering.

Is there any way to simplify this?

[Update 1]

Here's an example that's closer to the kind of methods I'm working with

And imagine yet another method:

答:
Why not add one more level into your hierarchy?

```<code>public class Base
{
    public virtual void Run()
    {
        // some code
    }
}

public class ProcBase : Base
{
    public sealed override void Run() // make sure it cannot be overriden
    {
        Proc();
        base.Run();
    }

    public virtual void Proc()
    {
        // some code
    }
}

public class Type1 : Base // same with Type4
{
    public override void Run()
    {
        base.Run();
    }
}

public class Type2 : ProcBase // same with Type3
{
    public override void Proc()
    {
        base.Proc();
    }
}
</code>```

Also, if this hierarchy changes between different Runs, then using strategy pattern becomes inevitable.

Title: Help with inheritance hierarchy design

Body:
Why not add one more level into your hierarchy?

public class Base
{
    public virtual void Run()
    {
        // some code
    }
}

public class ProcBase : Base
{
    public sealed override void Run() // make sure it cannot be overriden
    {
        Proc();
        base.Run();
    }

    public virtual void Proc()
    {
        // some code
    }
}

public class Type1 : Base // same with Type4
{
    public override void Run()
    {
        base.Run();
    }
}

public class Type2 : ProcBase // same with Type3
{
    public override void Proc()
    {
        base.Proc();
    }
}

Also, if this hierarchy changes between different Runs, then using strategy pattern becomes inevitable.


答:
You have created your own, unnecessary problem here.

Everything must be runnable

The default implementation of run requires proc

Anybody implementing their own run can ignore proc (but all that useless code still adorns the class and any descendants).

Your concrete, exception-throwing implementation of proc enables people to set up themselves up for runtime errors.  Why do that?

OK, so you wanted to be helpful by providing a default implementation but you have bolted on implementation details which you know will not always be desired.  You say you want to avoid code duplication but you have encumbered your hierarchy with code which will be obsolete as soon as somebody extends it.

I would strongly urge you to go the interface/abstract-base-class route here:

Abstract base class runnable

Abstract base class proccer

Create proc-calling concrete implementation of runnable.

Wherever possible (even in proc-caller class methods) refer to runnables and not proc-callers).

So your default run implentation can be used where desired but can be dropped without penalty.  Also, this way people are forced to implement proc if they mix in proc-caller but you don't have to write that "Not implemented" version of proc - they can't compile their code if they do not implement proc.  Why create that runtime trap when you can require them to fix things at compile time?

If you think there are other useful behaviours which should be available, you can avoid code duplication by providing "interfaces" in the same way I have shown for proc.  Anybody who wants that can mix it in.

Title: Help with inheritance hierarchy design

Body:
I'm having trouble designing an inheritance hierarchy.

In the figure:

Base class:

This uses the Template Method.

Contains core logic/algorithm that
calls virtual/abstract methods

Derived types:

These classes provides concrete implementation of the virtual/abstract methods expected by the Base.

Conditions:

I have a virtual method (Run).

The default Run method uses another virtual method (Proc).

If a derived class uses the default Run behaviour, they must implement Proc.

If a derived class overrides the Run behaviour, then it shouldn't have to care about the existence of Proc, let alone overriding it.

I've considered making Run() abstract and let each derived class handle their own.
But then I'll end up with duplicate code.

I'm using a simplified example here.

In my actual project, I have several "Run"-typed virtual methods, each calling several "Proc"-typed methods.

Because of that, I have a whole bunch of virtual "Proc" methods with "throw new NotImplementedException()"

Creating a new derived type is also confusing, because the coder may not know which virtual methods must be implemented/can be ignored/etc.

I've considered using a strategy pattern, but since I have several "Run" methods, each one of those would have to be a strategy, which seems like overkill/overengineering.

Is there any way to simplify this?

[Update 1]

Here's an example that's closer to the kind of methods I'm working with

And imagine yet another method:


答:
All code should be commented.

No, it shouldn't be. Some time you have obvious code, for example setters should not be commented, until they do something special. Also, why should I comment this:

```<code>/** hey you, if didn't get, it's logger. */
private static Logger logger = LoggerFactory.getLogger(MyClass.class);
</code>```

Title: What popular "best practices" are not always best, and why?

Body:
"Best practices" are everywhere in our industry.  A Google search on "coding best practices" turns up nearly 1.5 million results.  The idea seems to bring comfort to many; just follow the instructions, and everything will turn out fine.

When I read about a best practice - for example, I just read through several in Clean Code recently - I get nervous.  Does this mean that I should always use this practice?  Are there conditions attached?  Are there situations where it might not be a good practice?  How can I know for sure until I've learned more about the problem?

Several of the practices mentioned in Clean Code did not sit right with me, but I'm honestly not sure if that's because they're potentially bad, or if that's just my personal bias talking.  I do know that many prominent people in the tech industry seem to think that there are no best practices, so at least my nagging doubts place me in good company.

The number of best practices I've read about are simply too numerous to list here or ask individual questions about, so I would like to phrase this as a general question:

Which coding practices that are popularly labeled as "best practices" can be sub-optimal or even harmful under certain circumstances?  What are those circumstances and why do they make the practice a poor one?

I would prefer to hear about specific examples and experiences.

Body:
All code should be commented.

No, it shouldn't be. Some time you have obvious code, for example setters should not be commented, until they do something special. Also, why should I comment this:

/** hey you, if didn't get, it's logger. */
private static Logger logger = LoggerFactory.getLogger(MyClass.class);


问:
Where to place configuration files sources
I am developing a C# windows service application, which have different configuration files for development, for production system, for test system, like:

```<code>Dev.config
Test.config
Prod.config
</code>```

Now we are using SVN version control system, and configuration files stored in projects directories:

```<code>-trunk
  -MyFooService
    -Configs
      Dev.config
      Test.config
      Prod.config
  -MyFooService2
    -Configs
      Dev.config
      Test.config
      Prod.config
</code>```

Prior publishing service to production you should get respective configuration file from that folders. How do you think, it is correct? Or configuration files should be placed in another repository? Or in another folder or should not be placed in VCS?

Or may be it will be better to place files like that:

```<code>-trunk
  -src
    -MyFooService
    -MyFooService2
  -configs
    -MyFooService
      -Configs
        Dev.config
        Test.config
        Prod.config
    -MyFooService2
      -Configs
        Dev.config
        Test.config
        Prod.config
</code>```

答:
What we've come up with is the following. We only place one config file under version control. It contains the settings of the development environment. It serves two purposes. One, if a developer opens a project and runs it, it should just work (see also the Joel test :)). Two, it serves as a template only. You shouldn't actually store actual configuration settings in version control, but these are two very good reasons to make an exception with the development settings, out of necessity.

When we publish a project to a server, we never overwrite configuration files, we only merge changes into it if there were any. The problem you are facing is that environments can change all the time, you can add new environments or modify existing ones, and these environment changes may have nothing to do at all with your development cycle. Even more importantly, we have no control at all over the clients' environments. Why would we want to store those settings in our version control? When we give a published project to our clients, we rename the config files to config.sample, they are forced to edit it according to their needs.