答:
CustomerService is coupled to three interfaces (ValidationService, Repository and CustomerDTO) and basically orchestrates a validation before saving.

Best option is to take a step back, and consider different instances of CustomerService, one for each type of customer and already injected with the appropriated services. You can use the strategy pattern to switch between CustomerService instances, changing the caller of CS instances.

Using this approach, you don't need to change CustomerService, only the its caller. Such impact is consistent with the change: the new requirement suggests new type of customers, but does not change the way they are validaded and persisted.


问:
What is the common definition of a Hacker?
I'm wondering if the term Hacker means different things to different people.  When most people hear the word hacker what are the first things that come to mind?</p>

答:
In the programming sense, someone who is willing to go deep into the complexity of the system that they use to gain a greater understanding.

In the life sense, someone who approaches life from an unexpected and usually creative angle to achieve their objectives.

In the spiritual sense, someone who is taking a practical approach to enlightenment.

ContentLicense: CC BY-SA 2.5


问:
Freelancing - Getting paid for the quote or estimate
It is often necessary to spend time designing a solution, breaking down the design into tasks and sub tasks and estimating the time it will take to complete each task in order to produce a reasonable estimate or quote for a programming task.  This process can be a serious investment of time, often without any guarantee that the estimate/quote will be acceptable to the potential client and more often that not the time was 'wasted' with no hope of getting paid for it (in the event of not winning the job).

Is it the case that this is a cost of doing business and what can be done to minimise this unpaid time?

答:
Charge for the consult.  That's all.

Of course, you will need to have developed a sufficiently good reputation that someone will be willing to pay for your advice.  You can get referrals from satisfied customers, or develop a portfolio of satisfied customers to make your case.

Alternatively, notify your clients up front that, if they accept you as a vendor, the consult will be built into the quote.  You should sell the fact that money spent this way is money saved in the long term by having a better solution.

ContentLicense: CC BY-SA 3.0


答:
Unfortunately, getting paid for an RFP or RFQ is mostly a thing of the past. The last time I got paid for a proposal was in the late 90's, and even then it was a dying concept. In some cases you can try to roll the proposal cost into the total project cost (assuming you win), but many customers have taken to assuming that it is their due to have you spend all of that time on their problem for free.

Your best defense is to tune your estimating skills so that you can quickly get to a ballpark figure. For example, assume you are quoting on a website. Do very quick sketches of each major page type and identify the source of the content for each component on the page. Make an estimate of the time for the frontend work, and a separate estimate for the backend necessary to generate the content. Lather. Rinse. Repeat. Oh, and don't forget to confirm with the client about who is responsible for the actual input of the content!

If the client is more than a bit fuzzy about exactly what they need, offer to do a paid consulting session (or two) to work them through the creation of User Stories. Explain that you (and anyone else bidding on the project) will need this level of detail in order to properly estimate the scope and complexity. Sometimes this can get you in the door for a few billable hours, and it also lets them see how you think/work.

Note bene: unless you are a true God of Programming, any time you identify something you have not done before, be honest and at least double your initial estimate for that component. Or be really honest and triple or quadruple it.

Title: Freelancing - Getting paid for the quote or estimate

Body:
It is often necessary to spend time designing a solution, breaking down the design into tasks and sub tasks and estimating the time it will take to complete each task in order to produce a reasonable estimate or quote for a programming task.  This process can be a serious investment of time, often without any guarantee that the estimate/quote will be acceptable to the potential client and more often that not the time was 'wasted' with no hope of getting paid for it (in the event of not winning the job).

Is it the case that this is a cost of doing business and what can be done to minimise this unpaid time?


问:
Standard -server to server- and -browser to server- authentication method
I have server with some resources; until now all these resources were requested through a browser by a human user, and the authentication was made with an username/password method, that generates a cookie with a token (to have the session open for some time).

Right now the system requires that other servers make GET requests to this resource server but they have to authenticate to get them. We have been using a list of authorized IPs but having two authentication methods makes the code more complex.

My questions are:

Is there any standard method or pattern to authenticate human users and servers using the same code?

If there is not, are the methods I'm using now the right ones or is there a better / more standard way to accomplish what I need?

Thanks in advance for any suggestion.

答: Make your servers impersonate users, your authentication system doesn't need to know they are servers or other users, you just need to ensure that authentication never fails for the users that are actually servers.</p>


答:
If you are responding to an RFP, you will probably have to accept that everyone is taking the cost of doing estimates as part of the cost of doing business. If they respond to enough of them, and charge enough for the ones they win, this can work. If you respond to one every few years you will probably not enjoy this model. I for one tend to ignore RPFs and prefer to get work where the customer has already decided they want me to do it, but needs to know how much it will cost.

When you are starting from a completely blank slate, sell the client a "feasibility study" of two weeks or a month. (No matter how little you know about the project, you should be able to guess how long this phase needs, pretty accurately.) You will interview stakeholders, come up with an architecture and a design, perhaps do some preliminary UI design, and produce a document describing the problem and the solution, along with a phasing plan and some firm estimates (quotes even) to actually do the work. The client will own this design and architecture and is free to ask someone else to implement it. (In my experience, they never do.) You are not being "paid to estimate" - you are producing work of value and being paid for it. Everyone's happy.


答:
I don't think there is a single answer for your question because there are a few factors that determine how you'd approach a quote or proposal.

Requirements

Although very rare, if a client has a reasonable grasp and documentation or the project is a very simple one you can usually provide a good estimate to the client. But as everyone knows that's a rarity and scope creep has to be factored in to your cost projects.

In this case the time required for you to prepare the estimate/proposal should be much less than if you have to determine the requirements list and scope of changes. So I'd consider this type of quote the 'cost of doing business'. Unless your quote falls under the LOD caveat below.

You also need to clearly define what is and what is not covered in your original estimate as well as the rate and billing terms of change requests. Obviously there will be some back and forth with the client when these things come up, but a well written proposal/quote gives you something in writing to fall back on in your argument.

Level of Detail of the Proposal

How much detail are you providing the client in your proposal? If you're spelling out anything other than the 40k foot overview you're providing the client with a blueprint of the project requirements. In this case you're putting a great deal of effort and man hours in to your proposal which the client can simply hand to the lowest bidder.

You've done a great deal of the work without any benefit or payment for your services. So charging your customer for the consultation would be perfectly reasonable.

Many clients will balk at this, but I've found that if I tell a client that the estimate is X dollars up front but I'll apply that to the cost of the project if I'm selected they don't seem to have an objection. Obviously you'd need to factor that in to your total project cost so that you're not losing anything.


问:
how to programtically build a grid of interlocking but random sized squares
I want to create a two dimensional layout of rectangular shapes, a grid made up of random sized cubes. The cubed should fit together and have equal padding or margin (space between). Kind of like a comic book layout, or more like the image attached.

How could I do this procedurally?

Practically, I would probably be using Python and some graphic software to render an image, but I don't know the type of algorithm (or whatnot) I would need to use to generate the randomized grid.

答:
Start with a grid of 1x1 cells. Pick a random spot, merge cells a random amount or till it collides with a larger rectangle.

This will get you something similar to the image you provide.

There's a bigger issues if you don't want a number of smaller cells acting as padding between your bigger cells. A comic book for example, wants to minimize the amount of dead space and have at most ~9 cells.  You could pick some points and draw some lines and call those your cells.

```<code>//Philip Haubrich, 2012, public domain
//Build instructions: gcc comicPanels.c

#include <stdio.h>  //entirely for printf()
#include <stdlib.h> //Entirely for rand()
#include <time.h> //Entirely to help srand()

#define PAINTINGSIZE_X 79
#define PAINTINGSIZE_Y 20

#define MYNUMBEROFPOINTS 4

#define MINDISTANCEBETWEENBOXES 2
//Because I suck at naming things. You should really fix this before it gets into your codebase.

#define NORTH 0
#define EAST 1
#define SOUTH 2
#define WEST 3

#define WHITE 0
#define BLACK 1

//Or, you know, a struct with .color, .r .g .b .alpha .editablebydeadpool
char g_paintingArea[PAINTINGSIZE_X][PAINTINGSIZE_Y];

void drawLineUntilBlocked(int x, int y, int direction)
{
  do
  {
    g_paintingArea[x][y] = BLACK;
    switch(direction)
    {
    case NORTH:
      y++;
      break;
    case SOUTH:
      y--;
      break;
    case EAST:
      x++;
      break;
    case WEST:
      x--;
      break;
    default:
      printf("I really need to get away from switch statements...\n");
    }
  } while(g_paintingArea[x][y] == WHITE && x > 0 && y > 0 && x < PAINTINGSIZE_X && y < PAINTINGSIZE_Y);
  //dowhile, when you are too lazy to re-arrange the code
}

//Feel free to sub in something like SDL or openGL here
void paint()
{
  int x,y;
  for(y=0; y<PAINTINGSIZE_Y; y++)
  {
    for(x=0; x<PAINTINGSIZE_X; x++)
    {
      printf("%c",g_paintingArea[x][y]);
    }
    printf("\n");
  }
}

int empty(int origx, int origy)
{
  int x,y;
  for(x=origx-MINDISTANCEBETWEENBOXES; x<origx+MINDISTANCEBETWEENBOXES; x++)
  {
    for(y=origy-MINDISTANCEBETWEENBOXES; y<origy+MINDISTANCEBETWEENBOXES; y++)
    {
      if( x < 0 || y < 0 || x >= PAINTINGSIZE_X || y >= PAINTINGSIZE_Y)
        continue;
      if( g_paintingArea[x][y] == BLACK)
        return 0; //Not empty, there is something nearby
    }
  }
  return 1; //Empty, like my heart
}

void init()
{
  int x,y;
  //initalize to zero
  for(x=0; x<PAINTINGSIZE_X; x++)
  {
    for(y=0; y<PAINTINGSIZE_Y; y++)
    {
      g_paintingArea[x][y] = WHITE;
    }
  }
  //Border, or as I like to call it B-town
  for(x=0; x<PAINTINGSIZE_X; x++)
  {
    g_paintingArea[x][0] = BLACK;
    g_paintingArea[x][PAINTINGSIZE_Y-1] = BLACK;
  }
  for(y=0; y<PAINTINGSIZE_Y; y++)
  {
    g_paintingArea[0][y] = BLACK;
    g_paintingArea[PAINTINGSIZE_X-1][y] = BLACK;
  }

  //oh yeah, this is important
  x = abs(time(NULL));
  srand(x);
}

int main(int argc, char** argv)
{
  int x,y,i;

  init();

  //That part you actually asked about
  for( i=0; i<MYNUMBEROFPOINTS; i++)
  {
    x = rand() % PAINTINGSIZE_X;
    y = rand() % PAINTINGSIZE_Y;

    if(!empty(x,y))
      continue;

    switch(rand()%3)
    {
    case 0: //4 way
      drawLineUntilBlocked(x,y,NORTH);
      drawLineUntilBlocked(x,y,SOUTH);
      drawLineUntilBlocked(x,y,EAST);
      drawLineUntilBlocked(x,y,WEST);
      break;
    case 1: //North/sourth
      drawLineUntilBlocked(x,y,NORTH);
      drawLineUntilBlocked(x,y,SOUTH);
      break;
    case 2: //East/West
      drawLineUntilBlocked(x,y,EAST);
      drawLineUntilBlocked(x,y,WEST);
      break;
    default:
      printf("Oh god wtf, and other useful error messages\n");
    }
  }
  //If I have to explain to you that this next bit will depend on your platform, then programming may not be for you
  paint();
  return 0;
}
</code>```

There are plenty more way to skin a cat.

Body:
Start with a grid of 1x1 cells. Pick a random spot, merge cells a random amount or till it collides with a larger rectangle.

This will get you something similar to the image you provide.

There's a bigger issues if you don't want a number of smaller cells acting as padding between your bigger cells. A comic book for example, wants to minimize the amount of dead space and have at most ~9 cells.  You could pick some points and draw some lines and call those your cells.

//Philip Haubrich, 2012, public domain
//Build instructions: gcc comicPanels.c

#include <stdio.h>  //entirely for printf()
#include <stdlib.h> //Entirely for rand()
#include <time.h> //Entirely to help srand()

#define PAINTINGSIZE_X 79
#define PAINTINGSIZE_Y 20

#define MYNUMBEROFPOINTS 4

#define MINDISTANCEBETWEENBOXES 2
//Because I suck at naming things. You should really fix this before it gets into your codebase.

#define NORTH 0
#define EAST 1
#define SOUTH 2
#define WEST 3

#define WHITE 0
#define BLACK 1

//Or, you know, a struct with .color, .r .g .b .alpha .editablebydeadpool
char g_paintingArea[PAINTINGSIZE_X][PAINTINGSIZE_Y];

void drawLineUntilBlocked(int x, int y, int direction)
{
  do
  {
    g_paintingArea[x][y] = BLACK;
    switch(direction)
    {
    case NORTH:
      y++;
      break;
    case SOUTH:
      y--;
      break;
    case EAST:
      x++;
      break;
    case WEST:
      x--;
      break;
    default:
      printf("I really need to get away from switch statements...\n");
    }
  } while(g_paintingArea[x][y] == WHITE && x > 0 && y > 0 && x < PAINTINGSIZE_X && y < PAINTINGSIZE_Y);
  //dowhile, when you are too lazy to re-arrange the code
}

//Feel free to sub in something like SDL or openGL here
void paint()
{
  int x,y;
  for(y=0; y<PAINTINGSIZE_Y; y++)
  {
    for(x=0; x<PAINTINGSIZE_X; x++)
    {
      printf("%c",g_paintingArea[x][y]);
    }
    printf("\n");
  }
}

int empty(int origx, int origy)
{
  int x,y;
  for(x=origx-MINDISTANCEBETWEENBOXES; x<origx+MINDISTANCEBETWEENBOXES; x++)
  {
    for(y=origy-MINDISTANCEBETWEENBOXES; y<origy+MINDISTANCEBETWEENBOXES; y++)
    {
      if( x < 0 || y < 0 || x >= PAINTINGSIZE_X || y >= PAINTINGSIZE_Y)
        continue;
      if( g_paintingArea[x][y] == BLACK)
        return 0; //Not empty, there is something nearby
    }
  }
  return 1; //Empty, like my heart
}

void init()
{
  int x,y;
  //initalize to zero
  for(x=0; x<PAINTINGSIZE_X; x++)
  {
    for(y=0; y<PAINTINGSIZE_Y; y++)
    {
      g_paintingArea[x][y] = WHITE;
    }
  }
  //Border, or as I like to call it B-town
  for(x=0; x<PAINTINGSIZE_X; x++)
  {
    g_paintingArea[x][0] = BLACK;
    g_paintingArea[x][PAINTINGSIZE_Y-1] = BLACK;
  }
  for(y=0; y<PAINTINGSIZE_Y; y++)
  {
    g_paintingArea[0][y] = BLACK;
    g_paintingArea[PAINTINGSIZE_X-1][y] = BLACK;
  }

  //oh yeah, this is important
  x = abs(time(NULL));
  srand(x);
}

int main(int argc, char** argv)
{
  int x,y,i;

  init();

  //That part you actually asked about
  for( i=0; i<MYNUMBEROFPOINTS; i++)
  {
    x = rand() % PAINTINGSIZE_X;
    y = rand() % PAINTINGSIZE_Y;

    if(!empty(x,y))
      continue;

    switch(rand()%3)
    {
    case 0: //4 way
      drawLineUntilBlocked(x,y,NORTH);
      drawLineUntilBlocked(x,y,SOUTH);
      drawLineUntilBlocked(x,y,EAST);
      drawLineUntilBlocked(x,y,WEST);
      break;
    case 1: //North/sourth
      drawLineUntilBlocked(x,y,NORTH);
      drawLineUntilBlocked(x,y,SOUTH);
      break;
    case 2: //East/West
      drawLineUntilBlocked(x,y,EAST);
      drawLineUntilBlocked(x,y,WEST);
      break;
    default:
      printf("Oh god wtf, and other useful error messages\n");
    }
  }
  //If I have to explain to you that this next bit will depend on your platform, then programming may not be for you
  paint();
  return 0;
}

There are plenty more way to skin a cat.


答:
Determine the size and geometry of the image.  If you want this to be tiled, the underlying geometry is that of a torus.

Maintain a list of the upper left hand corner of all possible shapes.  Initially, this is every possible spot.

Pick a random sized rectangle (within the constraints you have decided - in the example image they are squares and have a maximum size of 4).  Place this rectangle in a random upper left hand corner spot.

If the rectangle is too large (overlaps an existing allocated spot), trim the dimension of the rectangle so that it fits.

Remove all of the locations that are covered by this rectangle from the list of possible upper left hand corners.

Repeat until the upper left hand corner list is empty.

Render the resulting array in your preferred way.  This is where you would introduce a margin.

If you are unfamiliar with any particular graphics library, consider using the ppm format.  The key advantage is that you could write out a text file and then use one of the converters (ppmto___) to convert the image to your chosen format (ppmtogif. ppmtojpeg, ...)

Title: how to programtically build a grid of interlocking but random sized squares

Body:
I want to create a two dimensional layout of rectangular shapes, a grid made up of random sized cubes. The cubed should fit together and have equal padding or margin (space between). Kind of like a comic book layout, or more like the image attached.

How could I do this procedurally?

Practically, I would probably be using Python and some graphic software to render an image, but I don't know the type of algorithm (or whatnot) I would need to use to generate the randomized grid.


问:
What core principles would you want in a library?
Theres talk about what syntax and feature you like in a programming language; i'll now ask what core principles or feature would you like in a library in your favorite (or any) language?

An example is having adding list += anotherList valid as oppose to only allowing list += listElement (although some may see this as a bad idea)

答:
I would follow the best practices you can find in How to design a good API and why it matters by Joshua Blosh (Google). The PDF version can be found here.

According to him, characteristics of a good API are :

Easy to learn

  Easy to use, even without documentation

  Hard to misuse

  Easy to read and maintain code that uses it

  Sufficiently powerful to satisfy requirements

  Easy to extend

  Appropriate to audience


问:
Why does Facebook convert PHP code to C++?
I read that Facebook started out in PHP, and then to gain speed, they now compile PHP as C++ code. If that's the case why don't they:

Just program in c++? Surely there must be SOME errors/bugs when hitting a magic compiler button that ports PHP to c++ code , right?

If this impressive converter works so nicely, why stick to PHP at all? Why not use something like Ruby or Python? Note -- I picked these two at random, but mostly because nearly everyone says coding in those languages is a "joy". So why not develop in a super great language and then hit the magic c++ compile button?

答:
Just program in c++? Surely there must be SOME errors/bugs when
  hitting a magic compiler button that ports PHP to c++ code , right?

Right, but programming in C++ would entail replacing their entire existing codebase- an idea world-renowned for being utterly stupid and devastating.

If this impressive converter works so nicely, why stick to PHP at all?
  Why not use something like Ruby or Python? Note -- I picked these two
  at random, but mostly because nearly everyone says coding in those
  languages is a "joy". So why not develop in a super great language and
  then hit the magic c++ compile button?

Because that would, again, entail replacing their existing PHP codebase.

In an ideal world, they would simply code in C++ from scratch. Unfortunately, because they have a shitload of existing code in PHP, that's not possible. So instead, they hack around the problem. It's just so much cheaper.


答:
I am not at Facebook, but my best guess at the motives would be "to avoid significant risks". At this point, switching to a different language is no longer a technology decision: above all, it is a business decision.

When you are a big company that grew organically to the size of FB, you slowly attract people who then gain expertise in your programming platform (in FB's case, that's PHP). One by one, you get a few thousand employees with great expertise at PHP. At this point, switching to any other language becomes very dangerous: your engineers will not be up to speed on the new ecosystem, and may require a significant time to achieve the level of expertise demanded by their current jobs, let alone improving their skills.

Leaving aside the relative merits of PHP and the alternative languages, with the amount of investment the FB made into PHP technology it would be too arrogant to think that a switch would be painless, and too foolish to give it a try. In business, technology is means to an end, so the "joy" of programming does not even enter discussions.

Title: Why does Facebook convert PHP code to C++?

Body:
I read that Facebook started out in PHP, and then to gain speed, they now compile PHP as C++ code. If that's the case why don't they:

Just program in c++? Surely there must be SOME errors/bugs when hitting a magic compiler button that ports PHP to c++ code , right?

If this impressive converter works so nicely, why stick to PHP at all? Why not use something like Ruby or Python? Note -- I picked these two at random, but mostly because nearly everyone says coding in those languages is a "joy". So why not develop in a super great language and then hit the magic c++ compile button?


问:
Help me understand a phrase from the "Java concurrency in practice"
On a page twelve of "Java concurrency in practice" there is a phrase

"A good specification defines invariants constraining an object's
  state and post - conditions describing the effect of its operation."

More or less I undersand the phrase untill the word "post", then it becomes a garbage.

Can you help please?

答:
Perhaps the spacing is confusing. The last part of the sentence should read "post-conditions describing the effect of its operation", or what must be true about the state of the object following the completion of a method call (or any other code block).

Post-conditions, along with preconditions and invariants, are frequently used in design by contract. Having a formal specification does help in understanding concurrency and the side-effects of a method call. It's also useful in establishing test code and assertions.


答:
Facebook's Senior Engineer Haiping Zhao probably answers your questions best.

HipHop programmatically transforms your PHP source code into highly optimized C++ and then uses g++ to compile it. HipHop executes the source code in a semantically equivalent manner and sacrifices some rarely used features — such as eval() — in exchange for improved performance.

One common way to address these inefficiencies is to rewrite the more complex parts of your PHP application directly in C++ as PHP Extensions. This largely transforms PHP into a glue language between your front end HTML and application logic in C++. From a technical perspective this works well, but drastically reduces the number of engineers who are able to work on your entire application.

The rest of the blog post is a good read, and I recommend it.  It gives some insight into the programming challenges Facebook deals with, and how they are trying to address those problems.


问:
In what stage of development should comments be written?
I'm a student working an internship at a larger company, writing small business apps in C#.  I've noticed that I don't comment my code as I write it.  Rather, I comment my code when I'm in the debugging stage of development.  As I'm tracking down bugs, I'll run across a block that makes me think "hmm...that might confuse someone in the future.  I'd better comment that", and I'll add the appropriate comments.  All of my comments are done this way.

Is this an appropriate way of commenting?  Should comments be written as the code is written?  Or does it really matter when the comments are written, as long as they adequately explain why this block is used?

答:
Your method will work great IFF every piece of code you write gets thoroughly debugged and you have many passes through it to comment it. Hopefully, you will one day write more code that works fine (more-or-less) on the first try. Which means fewer or no long debugging sessions, which means fewer or no or comments, if you strictly follow a "comment only when debugging rule".

I would say write the comments as you write the code. If you write code that you think might require extra explanation, write the comments as soon as you realize they might be needed!!

(and yes, you will need to update your comments if your code changes in such a way that the comments are no longer valid)


答:
Ideally, comments should be written at the same time as the code.

In the real world, those comments are not nearly as often as needed actually written, so if you stumble across a piece of code that, in your opinion, deserves an additional comment, there should be nothing against adding it later (or commenting upon it if you found it during a review).

Title: In what stage of development should comments be written?

Body:
I'm a student working an internship at a larger company, writing small business apps in C#.  I've noticed that I don't comment my code as I write it.  Rather, I comment my code when I'm in the debugging stage of development.  As I'm tracking down bugs, I'll run across a block that makes me think "hmm...that might confuse someone in the future.  I'd better comment that", and I'll add the appropriate comments.  All of my comments are done this way.

Is this an appropriate way of commenting?  Should comments be written as the code is written?  Or does it really matter when the comments are written, as long as they adequately explain why this block is used?


答:
Code should be self-describing, whenever possible.  In other words, if you write clear code, you will need fewer comments.

Comments should include:

A general description of the class/method and what it does,

How objects and methods relate to each other, as an overall architecture.

Anything that is not immediately obvious from reading the code, such as obscure performance optimizations.

In general, comments should be written when they are needed, which ideally is when you write the code that requires them.

Avoid comments that state the obvious, or restate what is already clear in the code.  The more comments you have, the more comments you will have to maintain when you change the code.


答:
Write comments as you write the code.  They're there for your benefit as well as the benefit of anyone who may be subsequently reading the code.

You've got things half right when you talk about "explain why this block is used" but the debugging stage is just going to be too late for that.  If you have to think about why you wrote things a certain way at this later stage, then you're already in a position where a comment written while writing the code would have saved you time and trouble.

They also serve to help you focus your mind while coding; rather than rushing ahead with something they force you to stop for a short while, think a little more about what you're doing now, and can prevent you from going down a wrong track.

None of this is to say that while you're writing the code is the only time you should write comments.  If, during any later stage (not just debugging) it seems appropriate to add a further comment, modify an existing one or add a new one where there wasn't one before (or even remove one that now seems unnecessary), then do so too.


答:
I'd rather suggest anyone writing comments from the beginning of development, since the rationales and the context are fresher in the mind. This will save you a considerable maintenance effort, since recollecting such intents can be exponentially difficult as the time passes on.

There are several rules of thumb for commenting the code, I keep an abbreviated list for practical usage.

be succinct on telling what's being done

leave the how it's being done to the code, only commenting the non-obvious stuff or general methodology (like referencing a well-know solution, algorithm or relationship)

whenever you need to justify a non-idiomatic usage of the language (usually performance tricks require that)

All these items are better noticed by a proper peer-review process.


问:
Designing extensible, interactive systems
Steve Yegge's The Pinoccio Problem describes a very special type of program: one that not only fulfills the original purpose of its creators, but also is capable of performing arbitrary, user-defined computations.

They typically also host a console, by which one can reprogram the software on runtime, maybe persisting the modifications.

I find this problem very hard to reason about - there seems to be a conflict between implementing the 'core modules' of a program, and making the system really implementation-agnostic (i.e. no functionality is hard-coded).

So, how to architecture such a program - what techniques can help? Is it a well-studied topic?

答:
A domain-specific language is usually the best answer to this kind of problem.

Some languages, such as Ruby or Boo, are well-designed to allow you to create DSLs. But this is a large subject, way more than can be covered in one answer here, but there are a couple of good books on the subject:

Martin Fowler's Domain Specific Languages

Ayende Rahien's DSLs in Boo


答:
Most people don't know what they want, and those who do know what they want don't know how to describe it in a way that

a computer can understand,

is user-friendly enough for a mere mortal,

is robust enough that it doesn't crash every 5 minutes, and

is flexible enough to withstand future business changes.

That's why programmers exist.

Since users are not really interested in writing their own programs, what you wind up doing is writing a system that is configurable; that is, it has settings that are already understood by the system that can be manipulated by a user.  If you are lucky, the number of such settings is small enough that the flexibility they provide is sufficient for the problem domain without adding too much complexity.

As pdr points out in his answer, Domain-Specific Languages are a good bridge for those folks who need more power and flexibility than configuration can provide.

Title: Designing extensible, interactive systems

Body:
Steve Yegge's The Pinoccio Problem describes a very special type of program: one that not only fulfills the original purpose of its creators, but also is capable of performing arbitrary, user-defined computations.

They typically also host a console, by which one can reprogram the software on runtime, maybe persisting the modifications.

I find this problem very hard to reason about - there seems to be a conflict between implementing the 'core modules' of a program, and making the system really implementation-agnostic (i.e. no functionality is hard-coded).

So, how to architecture such a program - what techniques can help? Is it a well-studied topic?


答:
This sounds suspiciously like the "inner platform" (anti)pattern.

The basic idea is to write a piece of software that incorporates into itself a free-form means of configuration and/or command specification. This method is usually, as others have correctly pointed out, a "Domain-Specific Language" or DSL, interpreted by your software into more static pieces of code you have written. There are many such languages already out there; VBA, SQL, the scripting behind the Quake and Source engines, etc.

However, the flaw in such a pattern becomes evident when you look at the example DSLs. I doubt there's a DBA on the planet who would trust anyone in Accounting enough to give them a copy of SQL Management Studio and let them run their own reporting queries. On the flip side, I doubt there's any accountant on the planet who thinks that's a valid solution to their need for custom reports. 99% of users have no clue how to write a script to automate something in a Quake or Source-engine game; the ones that do keep finding holes in what those engines don't allow you to do, to do something that gives an unfair advantage.

While we could implement our own DSL (graphical or text-based) that simplifies the creation of custom queries and that does not allow the user to screw up anything beyond their own query, there is a very fine line to tread when designing a DSL that allows the user to do what they need, in a way they understand, without preventing then doing something they'd legitimately need, or allowing them to do something harmful. Often, there is no such solution, and even if it exists, providing a DSL that allows them to do anything they should be able to will not shield you from ever having to change the DSL to allow something new that nobody ever thought about before, that is perfectly acceptable and not harmful. As such, inner platform doesn't really solve the problem it was intended to; letting users do their own "programming", so the real developers can do more interesting things than customizing UI or report layouts/content. The devs will always be called on to "explain" (that is, hold the user's hand) the DSL they gave the user, and to answer the "well why can't I just do it like this" questions that are inevitable.

Even programmers deal with this all the time, in dealing with DSLs designed for interaction with third-party software. "Hey, why can't I do X, it sounds simple enough and I really need it to do this thing my user wants"... "Well if we let you do that then an attacker could do something similar and really screw you up, and us too". We as programmers expect a certain amount of that; end users expect a little more ease of use. That's why we're here.


答:
It is a studied topic, although unfortunately not a well studied one. Such systems are usually called Self-Sustaining Systems, Self-Supporting Systems or (especially in the Smalltalk community) Lively Systems.

Not surprisingly, Smalltalk itself is such a system, and the Smalltalk community (especially Dr. Alan Kay himself) are constantly striving to build ever more powerful and at the same time ever simpler such systems. Dr. Alan Kay's research group is currently working on designing a new language and new system that will provide a full Personal Computing System (i.e. Operating System, Programming Language, Compiler, VM, IDE, Editor, Office Suite, Web Browser, Realtime Collaboration etc.) in less than 20000 SLOC total.


答:
One of my favorite concepts in software engineering is convention over configuration and it came to mind reading your question.  What I like to do is extract as much of app logic definition into some form of data representation, be it XML/json config files or database tables.  I try to avoid hard-coding logic in the app tier and only have it interpret the instructions that are defined (initially by the developer, later modifiable by user) in the data tier.  It is almost like a 4GL that your app controller understands.  The non-technical user then has a friendly interface to manipulate that logic.  This approach comes with a heightened degree of responsibility -- as you are giving the user a socket to change the application's workings inside out.  So things like allowing test runs before the changes are committed, ACL, permissioning etc. are all critical in this approach.

In the future we will see more and more separation between logic definition and compilable code.


问:
What is the difference in a developer's years of experience with a language?
As stated by the title, what is the difference in years of experience in given language in terms of developers? For example, if one developer has had five years working with language A and the other developer has had two years working with language B followed by three years working with language A, would there be perceivable difference between them?</p>

答: Languages aren't the issue. You can learn an entire language in a couple of days. What takes longer to absorb are the conventions, APIs and various third-party frameworks. When people ask for five years of X, they don't care about the language, they want someone that has a lot of experience solving problems in and with that language so that they don't have to pay for any of the learning curve.</p>


答:
They don't.  Not anymore, at least.  Turns out doing it that way causes too many problems, including deployment headaches and nullifying one of the prime advantages of using a scripting language in the first place--being able to change scripts without needing to recompile--so they revamped the HipHop system into a VM architecture with a transparent JIT phase, and deprecated the C++ compiler.

Interestingly enough, apparently doing it this way is also about twice as fast (as in performant) as the original C++ trans-compilation approach.


答:
Most often I write comments before and instead of code. This way I lay out a plan of the future code in high-level terms.

Then, I add code that the comments suggest. Comments describe what and why is done, code adds the how.

After that, some comments may be redacted, if code is transparent enough; some (much fewer) comments need to be expanded.

This way, I rarely have to add comments to existing code.


问:
How to do dependency Injection and conditional object creation based on type?
I have a service endpoint initialized using DI. It is of the following style. This end point is used across the app.

```<code> public class CustomerService : ICustomerService
{
    private IValidationService ValidationService { get; set; }
    private ICustomerRepository Repository { get; set; }

    public CustomerService(IValidationService validationService,ICustomerRepository repository)
    {
        ValidationService = validationService;
        Repository = repository;
    }

    public void Save(CustomerDTO customer)
    {
        if (ValidationService.Valid(customer))
            Repository.Save(customer);
    }
</code>```

Now, With the changing requirements, there are going to be different types of customers (Legacy/Regular). The requirement is based on the type of the customer I have to validate and persist the customer in a different way (e.g. if Legacy customer persist to LegacyRepository).

The wrong way to do this will be to break DI and do somthing like

```<code>  public void Save(CustomerDTO customer)
    {
        if(customer.Type == CustomerTypes.Legacy)
        {
            if (LegacyValidationService.Valid(customer))
                LegacyRepository.Save(customer);
        }
        else
        {
            if (ValidationService.Valid(customer))
                Repository.Save(customer);
        }
    }
</code>```

My options to me seems like

DI all possible IValidationService and ICustomerRepository and switch based on type, which seems wrong.

The other is to change the service signature to Save(IValidationService validation, ICustomerRepository repository, CustomerDTO customer) which is an invasive change.

Break DI. Use the Strategy pattern approach for each type and do something like:

```<code>validation= CustomerValidationServiceFactory.GetStratedgy(customer.Type);
validation.Valid(customer)
</code>```

but now I have a static method which needs to know how to initialize different services.

I am sure this is a very common problem, What is the right way to solve this without changing service signatures or breaking DI?

答:
Add a layer or two of abstraction.

Add an interface to wrap the constrained implementations together; something like:

```<code>public interface IValidatingRepository
{
    public string Key {get; }
    public IValidationService ValidationService {get; }
    public ICustomerRepository Repository {get; }

    //personally, I would prefer to have this operation
    // return bool or bool? or give some kind of feedback
    //Also, this could be genericized to TDto dto vs CustomerDTO customer
    void Save(CustomerDTO customer);
}
</code>```

Implement IValidatingRepository, something like:

```<code>//this could alternately be an abstract base class,
// if you wanted to require custom subclasses for each strategy
public class ValidatingRepository : IValidatingRepository
{
    //these could be backed by readonly fields vs private setters if you prefer.
    public string Key {get; private set;}
    public IValidationService ValidationService {get; private set;}
    public ICustomerRepository Repository {get; private set;}

    public ValidatingRepository(
        string key,
        IValidationService validationService,
        ICustomerRepository repository
    )
    { /* set properties / fields */}

    public virtual void Save(CustomerDTO customer)
    {
        var validationService = ValidationService;
        var repository = Repository;
        if(customer == null || validationService == null || repository == null)
            return; //false? throw? some kind of feedback?

        //optional
        //if(!Preconditions())
        //  return; //false?

        if (validationService.Valid(customer))
            repository.Save(customer); //any return value from repository.Save(...)?

        //optional
        //return //Postconditions(customer);?
    }

    //optional
    protected virtual bool Preconditions(CustomerDTO customer)
    {
        if(customer.Type != Key)
            return false;
        /* any other preconditions */
        return true;
    }

    //optional
    protected virtual bool Postconditions(CustomerDTO customer)
    {
        /* any postconditions */
    }
}
</code>```

Alter the service implementation to have an instance of IValidatingRepository[] (or IEnumerable or other collection of your choice) rather than instances of IValidationService and ICustomerRepository.

Change the ctor to match[1].

```<code>public class CustomerService : ICustomerService
{
    private readonly IValidatingRepository[] ValidatingRepositorySet;

    public CustomerService(IValidatingRepository[] validatingRepositorySet)
    {
        ValidatingRepositorySet = validatingRepositorySet;
    }

    public void Save(CustomerDTO customer)
    {
        if(customer == null)
           return;

        var validatingRepositorySet = ValidatingRepositorySet;
        if(validatingRepositorySet == null)
           return;

        var key = customer.Type;
        var validatingRepository = validatingRepositorySet[key];
        if(validatingRepository == null)
            return;

        validatingRepository.Save(customer);

    }
</code>```

Wherever you are constructing the CustomerService instance, compose together the correct validation service and repository pairs into a collection of IValidatingRepository instances and inject it into the service keyed by Customer.Type or whatever is applicable or works for your usage. If you add more service / repository pairs later no big deal. If you want to put in different / mock sets for testing you can. Etc.

EXTENDED

If your injection mechanism can't handle it or you prefer not to inject in collections directly for some reason, you can add another layer of abstraction by creating another interface to bundle the idea of multiple repositories and a specific corresponding validation service (and potentially other implementation specific concepts later); something like this:

```<code>//you could also make this generic for TDto, and generalize
// away from CustomerDto to make this a more general purpose solution
public interface IValidatingRepositorySet
{
   //IEnumerable<>, or whatever collection you like
   IValidatingRepository[] RepositorySet { get; set; }

   //optional; you could move the strategy detection out of the service
   // and into the IValidatingRepositorySet implementation.
   void Save(CustomerDTO customer);

}
</code>```

And of course alter the service implementation to have an instance of IValidatingRepositorySet, and the ctor to take in an instance of it, and a default implementation somewhere, etc. Personally, I wouldn't do this unless I had one or more other things that applied to the set as a whole or otherwise belonged at a peer level to the set...such as moving the strategy selection logic out of the service (the optional Save method above).

NOTE: I wrote the code in the comment window on the fly; it's broad strokes only.

[1]Alternately, if for legacy support reasons you must retain the original ctor you can just wrap the passed in IValidationService & ICustomerRepository into a concrete default ValidatingRepository (you'll have to decide on a wildcard key, or have a special case implementation of ValidatingRepository that ignores key or supports an alternate key) that provides a simple implementation identical to the current functionality and set the IValidatingRepositorySet field / property to a new collection containing this instance. I would avoid this if you can, but it is an option.

Body:
Add a layer or two of abstraction.

Add an interface to wrap the constrained implementations together; something like:

public interface IValidatingRepository
{
    public string Key {get; }
    public IValidationService ValidationService {get; }
    public ICustomerRepository Repository {get; }

    //personally, I would prefer to have this operation
    // return bool or bool? or give some kind of feedback
    //Also, this could be genericized to TDto dto vs CustomerDTO customer
    void Save(CustomerDTO customer);
}

Implement IValidatingRepository, something like:

//this could alternately be an abstract base class,
// if you wanted to require custom subclasses for each strategy
public class ValidatingRepository : IValidatingRepository
{
    //these could be backed by readonly fields vs private setters if you prefer.
    public string Key {get; private set;}
    public IValidationService ValidationService {get; private set;}
    public ICustomerRepository Repository {get; private set;}

    public ValidatingRepository(
        string key,
        IValidationService validationService,
        ICustomerRepository repository
    )
    { /* set properties / fields */}

    public virtual void Save(CustomerDTO customer)
    {
        var validationService = ValidationService;
        var repository = Repository;
        if(customer == null || validationService == null || repository == null)
            return; //false? throw? some kind of feedback?

        //optional
        //if(!Preconditions())
        //  return; //false?

        if (validationService.Valid(customer))
            repository.Save(customer); //any return value from repository.Save(...)?

        //optional
        //return //Postconditions(customer);?
    }

    //optional
    protected virtual bool Preconditions(CustomerDTO customer)
    {
        if(customer.Type != Key)
            return false;
        /* any other preconditions */
        return true;
    }

    //optional
    protected virtual bool Postconditions(CustomerDTO customer)
    {
        /* any postconditions */
    }
}

Alter the service implementation to have an instance of IValidatingRepository[] (or IEnumerable or other collection of your choice) rather than instances of IValidationService and ICustomerRepository.

Change the ctor to match[1].

public class CustomerService : ICustomerService
{
    private readonly IValidatingRepository[] ValidatingRepositorySet;

    public CustomerService(IValidatingRepository[] validatingRepositorySet)
    {
        ValidatingRepositorySet = validatingRepositorySet;
    }

    public void Save(CustomerDTO customer)
    {
        if(customer == null)
           return;

        var validatingRepositorySet = ValidatingRepositorySet;
        if(validatingRepositorySet == null)
           return;

        var key = customer.Type;
        var validatingRepository = validatingRepositorySet[key];
        if(validatingRepository == null)
            return;

        validatingRepository.Save(customer);

    }

Wherever you are constructing the CustomerService instance, compose together the correct validation service and repository pairs into a collection of IValidatingRepository instances and inject it into the service keyed by Customer.Type or whatever is applicable or works for your usage. If you add more service / repository pairs later no big deal. If you want to put in different / mock sets for testing you can. Etc.

EXTENDED

If your injection mechanism can't handle it or you prefer not to inject in collections directly for some reason, you can add another layer of abstraction by creating another interface to bundle the idea of multiple repositories and a specific corresponding validation service (and potentially other implementation specific concepts later); something like this:

//you could also make this generic for TDto, and generalize
// away from CustomerDto to make this a more general purpose solution
public interface IValidatingRepositorySet
{
   //IEnumerable<>, or whatever collection you like
   IValidatingRepository[] RepositorySet { get; set; }

   //optional; you could move the strategy detection out of the service
   // and into the IValidatingRepositorySet implementation.
   void Save(CustomerDTO customer);

}

And of course alter the service implementation to have an instance of IValidatingRepositorySet, and the ctor to take in an instance of it, and a default implementation somewhere, etc. Personally, I wouldn't do this unless I had one or more other things that applied to the set as a whole or otherwise belonged at a peer level to the set...such as moving the strategy selection logic out of the service (the optional Save method above).

NOTE: I wrote the code in the comment window on the fly; it's broad strokes only.

[1]Alternately, if for legacy support reasons you must retain the original ctor you can just wrap the passed in IValidationService & ICustomerRepository into a concrete default ValidatingRepository (you'll have to decide on a wildcard key, or have a special case implementation of ValidatingRepository that ignores key or supports an alternate key) that provides a simple implementation identical to the current functionality and set the IValidatingRepositorySet field / property to a new collection containing this instance. I would avoid this if you can, but it is an option.


答:
".... the fullness of time, I believe programming fluency will become as ubiquitous as literacy, so it won't matter....."

He believes everyone is destined to become a programmer, I disagree. In the real world, people have become less knowledgeable of the things they do daily as time has moved on. You used to turn a dial to tune a TV channel and understood "Frequency", and knew where each channel was, now you press the "Auto Program" button. You used to change your own oil and fix you own puncture when you owned a car, you had to know how to fix a breakdown, now you rarely have to do any of that, and take it to the garage or call AAA. You used to grow your own veges and cook your own food, now it's McD's and TV Dinners.....

I personally think that in the end programmers will program and users will use. The odd enthusiast will become an amateur programmer - but just like the real world, the tools they use will be substantially similar to what the professionals use. Imagine trying to build your own car with "Domain Specific Tools" that could only do up some of the nuts and bolts, or cook dinner with a "Safe and Easy to use" kitchen that had no knifes or hot surfaces, as they can do a lot of damage if used incorrectly.


答:
Start with a square that describes the entire image.

Add the square to an empty array.

For each square in the array:

Create a boolean with a random true/false value.

If the value is true:

Split the square into into 4 equally-sized sub-squares.

Add them to the end of the array.

Remove the current square from the array.

At the end of the process, you will have an array of randomly-sized squares.  Note that you'll probably want to define a minimum size (at which point no more dividing is done) and a maximum size (if the square is larger, always split regardless of the boolean value).


答:
The answer to your question is bootstrapping.  You first design a very simple, flexible and extensible language.  (Dynamic languages work well.)  You implement that.  Then in that language you write extensions to the language until you've got the language that you want.  Then you write the application itself in that language.  When you're done, you expose the language that you started with.

Since everything is written in that language, and the extensions are available at runtime, you can do anything you want to the application (including unwise things).

For example see how emacs is written in eLisp.  Or look at Smalltalk.  Or Scheme.

That is the principle.  The details tend to be very, very complicated.  Therefore I highly recommend that you study code that seems to do this well.  And read books like On Lisp that demonstrate how a language can be extended from within itself.  If you've got the right kind of recursively twisted mind, eventually you'll be able to build your own system on this principle.  (But good luck explaining to someone else what makes it cool...)


问:
What is the most performant CSS property for transitioning an element?
I'm wondering whether there is a performance difference between using different CSS properties to translate an element. Some properties fit different situations differently.

You can translate an element with following properties: transform, top/left/right/bottom and margin-top/left/right/bottom

In the case where you do not utilize the transition CSS property for the translation but use some form of a timer (setTimeout, requestAnimationFrame or setImmediate) or raw events, which is the most performant–which is going to make for higher FPS rates?

答:
Your milage is always going to vary between different browers. I don't think that you can accurately say one solution is going to always be the best cross browser, but what you can accurately rely on, is that anything that uses your GPU is going to be faster. When you animate using a setTimeout, the browser does all of the crunching in memory and through the CPU. Additionally, it doesn't really know that the intended animation is suposed to be smooth.

Depending on which version of your browser, you will also find that GPU acceleration can be hit or miss. For example, up until last year, a common trick to ensure that webkit based browsers always used GPU accelleration was to do a kind of "type hint" where you would set the property to be -webkit-transform: translateZ(0)

Another point to add however, is what does "performant" actually mean for you? Does it mean visually performant, which means smooth? In which case you wouldn't want to use setTimeout, because you can't realistically get that "smoothness". So where possible, you would want to use transitionining through CSS (and rely on GPU accelleration where avaialble).

But what if you mean "performant" in terms of battery life on your device. In which case you would probably want to use requestAnimationFrame.

Why should I use it?

The browser can optimize concurrent animations together into a single
  reflow and repaint cycle, leading to higher fidelity animation. For
  example, JS-based animations synchronized with CSS transitions or SVG
  SMIL. Plus, if you're running the animation loop in a tab that's not
  visible, the browser won't keep it running, which means less CPU, GPU,
  and memory usage, leading to much longer battery life.

Reference : requestAnimationFrame for smart animating

Next up, "performant" might mean time-spent for you. I know that personally, I can be most performant if I use CSS animations, and use them whereever possible.

This article will be a useful read for you:

http://www.html5rocks.com/en/tutorials/speed/html5/


问:
Regexp or custom parsing algo?
I was trying to parse a java properties file to avoid some Properties loading pitfalls (non ordering, loss of comments).

(Property are of the form 'key = value' where the value can span on multiple lines using the \ special char)

I have tried to get the right regexp to parse the properties but after I gave up after fighting for more than one hour. (a version for groovy found here:

 ~ /^([^#=].*?)=(.+)$/)

I manage to write the same thing using a single loop and very trivial code in 5 minutes...

I'm an average programmer when dealing with regexp: I have to re-read the doc each time I want to use them and advanced feature are still obscure for me.

Often when dealing with regexp I have the feeling that some very skilled developers can produce/decipher very elaborated regexp in seconds, but others have trouble to handle them.

Question: should I take time to deeply learn regexp and produce cryptic and powerful parser, or should I keep using some ugly easy to debug/understand parsing algo ?

答:
For this specific task (parsing java properties file), first look for an existing solution (sounds like someone would have solved this same problem already), and if you can't find one, it's not necessarily bad to create a non-regex parser to do it with - you use the tools you know.

If you do go the regex route, do not be compelled to use a single regex, when two (or more) will often give a much simpler and faster result.

should I take time to deeply learn regexp

YES!

There are a lot of times when knowing regular expressions can greatly speed up your programming - I probably use more regex in the tasks of creating & maintaining code than in actuall code itself.

But perhaps the main reasons for learning regex deeply is so that you can quickly say "this is a job for regex" or "regex is the wrong tool here" - otherwise you can waste a lot of time trying to get regex to do a task it just isn't suited for.

However, it's important to also state that Regex does not need to be crypic - you can write complex regex and format it nicely so that it is just as understandable as any other code.

Title: Regexp or custom parsing algo?


问:
How to discriminate from two nodes with identical frequencies in a Huffman's tree?
Still on my quest to compress/decompress files with a Java implementation of Huffman's coding (http://en.wikipedia.org/wiki/Huffman_coding) for a school assignment.

From the Wikipedia page, I quote:

Create a leaf node for each symbol and add it to the priority queue.

While there is more than one node in the queue:

Remove the two nodes of highest priority (lowest probability) from the queue

Create a new internal node with these two nodes as children and with probability equal to the sum of the two nodes' probabilities.

Add the new node to the queue.

The remaining node is the root node and the tree is complete.

Now, emphasis:

Remove the two nodes of highest priority (lowest probability) from the queue

Create a new internal node with these two nodes as children and with probability equal to the sum of the two nodes' probabilities.

So I have to take two nodes with the lowest frequency. What if there are multiple nodes with the same low frequency? How do I discriminate which one to use?

The reason I ask this is because Wikipedia has this image:

And I wanted to see if my Huffman's tree was the same. I created a file with the following content:

```<code>aaaaeeee       nnttmmiihhssfffouxprl
</code>```

And this was the result:

Doesn't look so bad. But there clearly are some differences when multiple nodes have the same frequency.

My questions are the following:

What is Wikipedia's image doing to discriminate the nodes with the same frequency?

Is my tree wrong? (Is Wikipedia's image method the one and only answer?)

I guess there is one specific and strict way to do this, because for our school assignment, files that have been compressed by my program should be able to be decompressed by other classmate's programs - so there must be a "standard" or "unique" way to do it. But I'm a bit lost with that.

My code is rather straightforward. It literally just follows Wikipedia's listed steps. The way my code extracts the two nodes with the lowest frequency from the queue is to iterate all nodes and if the current node has a lower frequency than any of the two "smallest" known nodes so far, then it replaces the highest one. Just like that.

答:
Simply choose any of the nodes. You must include information how to reconstruct the tree anyway in the compressed file.

Wikipedia says (about decompression):

Before this can take place, however, the Huffman tree must be somehow
  reconstructed. In the simplest case, where character frequencies are
  fairly predictable, the tree can be preconstructed (and even
  statistically adjusted on each compression cycle) and thus reused
  every time, at the expense of at least some measure of compression
  efficiency. Otherwise, the information to reconstruct the tree must be
  sent a priori.


答:
Comments can be written at any stage, comments SHOULD be written when you believe the code needs explanation and you know that you understand it.

Believing the code needs explanation should almost always be based upon your belief about how easy it is to understand the purpose of the code -- if the purpose is clear, then you probably don't need an explanation as to what it is doing.  This is in part the purpose of good naming -- so that given a name of a function and it's input/output, you will understand why the code is needed and why it is doing whatever it is doing.

Comments on the syntax should be extremely rare, pretty much limited to cases where it is BOTH obscure AND possible to misunderstand it to be something else.  If it's simply obscure, then trust that they will look it up if they need it, if it's simply likely to be misunderstood a + b * c then write it so that it's less likely to misunderstand a + (b*c).  If on the other hand the purpose is unclear (working around a framework/compiler bug for an extreme example) then you need a comment so that the next person can understand why you are doing what you are doing.

Adding comments when you debug is fine, debugging naturally brings you back to older code which you may struggle to understand -- and struggling to understand, you know that it needs comments.

This may be why lots of people start off giving comments on syntax -- they haven't yet mastered it, and are still struggling with it a bit, and don't have enough experience to realize that syntax is something that they will learn and understand later.  They expect to have trouble understanding the syntax, and thus provide a comment.

But having this as your normal mode of operation is not ideal, at best it is then helpful the 2nd time you have to debug that code.  You should strive to anticipate where you will have trouble understanding the code, and write the comments explaining it as it is written.  Don't expect to get it right all the time, or even most of the time at first.  Just try to do better.


问:
Converting lib from other language to python and Rights issue
If I take a program, and basically translate its source from some language to python, with some small changes, can I do a entirely my new lib or I have to make a "version" of the old one?

would this be a copy of the first or a new lib based in the ideas of the first?

OBS: Consider the original lib is using Apache License v2

Not sure if well explained, but I can't see for now how to make it more clear.

答:
I am not a lawyer, this is not legal advice.  Which means, if you follow my advice, and it turns out to be wrong, don't sue me for it.

A copyright owner's permission is required for doing anything that is covered under copyright law.  A copyright license gives you that.  Copyright law recognizes copyrights even after every word is replaced.  As might happen if you translate a book from Spanish into English.  Thus your translation of, say, a Java program into Python would still be subject to copyright.

That said, as long as you follow all of the terms of the Apache License v2 (including attribution, etc), you have permission.  That license doesn't say what your library should be called, so your translation can be called anything that you like.

But you're still bound by the author's wishes and copyright.


答: I'm like you, I use regexps so rarely that I have to look in a reference for all but the most trivial examples. I've worked with a couple of developers who were pretty fluent with them though and they could pretty surprising things very quickly. I think it is something that once you know more about it, you will see more and more ways to use it and the investment will pay off. Also it looks like a good way to stretch your mind.</p>

Title: Regexp or custom parsing algo?

Body:
I was trying to parse a java properties file to avoid some Properties loading pitfalls (non ordering, loss of comments).

(Property are of the form 'key = value' where the value can span on multiple lines using the \ special char)

I have tried to get the right regexp to parse the properties but after I gave up after fighting for more than one hour. (a version for groovy found here:

 ~ /^([^#=].*?)=(.+)$/)

I manage to write the same thing using a single loop and very trivial code in 5 minutes...

I'm an average programmer when dealing with regexp: I have to re-read the doc each time I want to use them and advanced feature are still obscure for me.

Often when dealing with regexp I have the feeling that some very skilled developers can produce/decipher very elaborated regexp in seconds, but others have trouble to handle them.

Question: should I take time to deeply learn regexp and produce cryptic and powerful parser, or should I keep using some ugly easy to debug/understand parsing algo ?


问:
Anti Cloud Open Source License
I'm working on a browser based open source monitoring project that I want to be free to the community.

What I'm worried about is someone taking the project, renaming it, deploying it in the cloud and start charging people who don't even know my project exists. I know I maybe shouldn't mind, but it just sticks in my throat a bit if someone took a free ride like that and contributed nothing back.

Is there any common open source license that can prevent this. I know GPL or AGPL don't.

答:
A) you can't stop anyone from making money using open source content. </p>

<p>B) you can force people to contribute back if they use or modify your code. AGPL license will serve this purpose even if your code is used in a cloud. </p>

Title: Anti Cloud Open Source License

Body:
A) you can't stop anyone from making money using open source content.

B) you can force people to contribute back if they use or modify your code. AGPL license will serve this purpose even if your code is used in a cloud.


问:
Should adapters or wrappers be unit tested?
Suppose that I have a class that implements some logic:

```<code>public MyLogicImpl implements MyLogic {
    public void myLogicMethod() {
        //my logic here
    }
}
</code>```

and somewhere else a test class:

```<code>public MyLogicImplTest {
    @Test
    public void testMyLogicMethod() {
        /test my logic
    }
}
</code>```

I also have:

```<code>@WebService
public MyWebServices class {
    @Inject
    private MyLogic myLogic;

    @WebMethod
    public void myLogicWebMethod() {
        myLogic.myLogicMethod();
    }
}
</code>```

Should there be a test unit for myLogicWebMethod or should the testing for it be handled in integration testing.

答: Your web service method almost certainly produces different output than your bare method.  It may be a massive SOAP envelope wrapped around your simple "Hello, World!" response.  It may be a RESTful HTTP response.  But it is almost certainly different.  So yeah, test it differently.


问:
"Programming error" exceptions - Is my approach sound?
I am currently trying to improve my use of exceptions, and found the important distinction between exceptions that signify programming errors (e.g. someone passed null as argument, or called a method on an object after it was disposed) and those that signify a failure in the operation that is not the caller's fault (e.g. an I/O exception).

How should these two kinds of exceptions be treated differently? Do you think that error exceptions need to be explicitly documented, or is it enough to document the relevant preconditions? And can you leave out the documentation of a precondition or error exception if it should be obvious (for example, ObjectDisposedException when calling a method on a disposed object)

答: Even Java doesn't "document" all exceptions.  Despite the requirement that every thrown exception be mentioned in a throws clause, any line of code can throw a RuntimeException without needing to declare it in the method signature.


答:
I can think of only one major website which was implemented in C++. H2G2

Even then the current implement ion is actually an interpreter with a large number of text and database manipulation functions built in (does that not sound a bit like and early PHP :-) ).

Facebook is quite happy with the functionality of their website. They have just grown to the point where vanilla PHP cannot support the volumes they process. Hence the compiling of there PHP into C++ thence machine code. The could have written a full compiler for PHP, but they would have missed out on the 20 years of subtle optimization that have gone into the gcc compiler stack. The point is the "C++" code is not meant to be human readable or maintainable its just an intermediate step on the way to machine code.

Like many programmers on this site I feel you undervalue the amount of work invested in hte business logic and functionality embedded in existing applications, and, value code for its own sake.


问:
How can I make my PHP development environment more efficient?
I want to start a home-brew pet project in PHP.

I've spent some time in my life developing in PHP and I've always felt it was hard to organize the development environment efficiently.

In my previous PHP work, I've used a windows desktop machine and a linux server for development.

This configuration had it's advantages: it's easy to configure Apache (and it's modules)/PHP/MySql on a linux box, and, at the time, this configuration was the same like on production server.

However, I never successfully set up a debug connection between my Eclipse install and X-debug on server. Transferring files from my local workspace to the server was also very annoying (either ftp or Bazaar script moving files from repository to web root).

For my new setup, I'm considering installing everything on my local machine. I'm afraid that it will slow down workstation performance (LAMP + Eclipse), and that compatibility problems will kick-in.

What would you recommend? Should I develop using two separate machines? On one? Do you have experience using one of above configurations in your work?

答:
I suggest WAMP

WAMPServer to be more stable
and is user-friendly. I have been using this for 2 years for PHP development especially in database management and web portal development.

Please note that  XAMPP never ever worked with sessions, always give a lot of errors. Also, it's a bit harder to secure.

In WAMP, you only have to click the wamp icon and chose "put online" to make it available from other computers, or "put offline" if you only want it accessible from the local computer.

You may watch the video here to gain more insights


答: The standard way to do it is with the java approach. Programming errors should be unchecked exceptions and should not be caught to ensure a fast failure. Contract errors are checked exceptions and should be handled appropriately by the client.</p>

Title: "Programming error" exceptions - Is my approach sound?

Body:
I am currently trying to improve my use of exceptions, and found the important distinction between exceptions that signify programming errors (e.g. someone passed null as argument, or called a method on an object after it was disposed) and those that signify a failure in the operation that is not the caller's fault (e.g. an I/O exception).

How should these two kinds of exceptions be treated differently? Do you think that error exceptions need to be explicitly documented, or is it enough to document the relevant preconditions? And can you leave out the documentation of a precondition or error exception if it should be obvious (for example, ObjectDisposedException when calling a method on a disposed object)


问:
Does having a higher paid technical job mean you do not get to code any more?
I work at a large company where technical people fall roughly in one of these categories:

A developer on a scrum team who develops for a single product and maybe works with other teams that are closely related to the product.

An architect who is more of a consultant on multiple teams (5-6) and tries to recognize commonalities between team efforts that could be abstracted into libraries (architects do not write the library code, however). This architect also attends many meetings with management and attempts to set technical direction.

In my company the architect role is where most technical people move into as the next step in their career.

My questions are: Do most companies work such a way that their highest paid technical people are far removed from writing code? Is this a natural tendency for a developer's career? Can a developer have it all (code AND set direction?)

答:
This largely depends on the organization's culture. Many companies don't have real senior technical positions, although they may have some bogus ones.

Some companies do have these positions. One of the reasons that great engineers tend to gravitate to a few big companies (e.g Google) or to startups is that they can keep being developers and work on things they're excited about with high compensation and organizational status. In most companies if they wanted to stay developers they'd be at the low rungs of the ladder.


问:
Python Forgiveness vs. Permission and Duck Typing
In Python, I often hear that it is better to "beg forgiveness" (exception catching) instead of "ask permission" (type/condition checking).  In regards to enforcing duck typing in Python, is this

```<code>try:
    x = foo.bar
except AttributeError:
    pass
else:
    do(x)
</code>```

better or worse than

```<code>if hasattr(foo, "bar"):
    do(foo.bar)
else:
    pass
</code>```

in terms of performance, readability, "pythonic", or some other important factor?

答:
Performance, I feel, is a secondary concern. If it arises, a profiler would help you focus on the real bottlenecks, which may or may not be how you treat possible illegal arguments.

Readability and simplicity, on the other hand, are always a prime concern. There are no hard rules here, just use your judgment.

This is a universal issue, but environment- or language-specific conventions are relevant. For example, in Python it's usually fine to simply use the attribute you expect and let a possible AttributeError reach the caller.


问:
How many lines of code can a C# developer produce per month?
An executive at my workplace asked me and my group of developers the question:

How many lines of code can a C#
  developer produce per month?

An old system was to be ported to C# and he would like this measure as part of the project planning.

From some (apparently creditable) source he had the answer of "10 SLOC/month" but he was not happy with that.

The group agreed that this was nearly impossible to specify because it would depend on a long list of circumstances. But we could tell that the man would not leave (or be very disappointed in us) if we did not come up with an answer suiting him better. So he left with the many times better answer of "10 SLOC/day"

Can this question be answered? (offhand or even with some analysis)

答:
It is generally a bad idea to call your boss an idiot, so my suggestions start with understanding and discussing metrics, rather than rejecting them.

Some people who are not actually considered idiots have used metrics that were based on lines of code.  Fred Brooks, Barry Boehm, Capers Jones, Watts Humphries, Michael Fagan, and Steve McConnell all used them.  You have probably used them even if just to say to a colleague, this God module is 4000 lines, it needs to be broken into smaller classes.

There is specific data related to this question from a source that many of us respect.

http://www.codinghorror.com/blog/2006/07/diseconomies-of-scale-and-lines-of-code.html

http://www.codinghorror.com/blog/2005/08/are-all-programming-languages-the-same.html

http://discuss.joelonsoftware.com/default.asp?joel.3.286106.22

I suspect that the best use of line of code per programmer hour is to show that over the life of the project, this value will start pretty high, but as defects are found and fixed, new lines of code will be added to solve problems that were not part of the original estimates, and lines of code removed to eliminate duplication and improve efficiency will show that LOC/hr indicates things other than productivity.

When code is written fast, sloppy, bloated, and without any attempt at refactoring, the apparent efficiency will be at its highest.  The moral here will be that you must be careful for what you measure.

For a particular developer, if they are adding or touching a high quantity of code this week, next week there may be a technical debt to pay in terms of code review, test, debug, and rework.

Some developers will work at a more consistent rate of output than others.  It may be found that they spend the most time on getting good user stories, turn around very quickly and make corresponding unit tests, and then turn around and quickly make code that is focused on only the user stories.  The take away here is that methodical developers will probably have quick turn around, will write compact code, and have low rework because they understand the problem and the solution very well before they start to code.  It seems reasonable that they will code less because they code only after they think it through, instead of before and after.

When code is evaluated for its defect density, it will be found to be less than uniform.  Some code will account for most of the trouble and defects.  It will be a candidate for rewriting.  When that happens, it will become the most expensive code because by virtue of it high degree of rework.  It will have the highest gross lines of code counts (added, deleted, modified, as might be reported from a tool like CVS or SVN), but the lowest net lines of code per hour invested.  This may end up being a combination of the code either implementing the most complex problem or the most complicated solution.

Regardless how the debate over programmer productivity in lines of code turns out you will find that you need more man power than you can afford and the system will never be completed in time.  You real tools are not metrics.  They are use of superior methodology, the best developers you can hire or train, and the control of scope and risk (probably with Agile methods).


答:
If you're just writing your own encoding and decoding algorithms, it doesn't matter how you distinguish between equal valued nodes, so long as each half of the operation uses the same methodology.

The answer comes from your implementation of the priority queue. When a value that already exists in the queue is added again, is the new item considered lower or higher than the existing item with the same priority value. This is what you need to make sure of to ensure that your algorithm is compatible with those of your classmates.

Title: How to discriminate from two nodes with identical frequencies in a Huffman's tree?

Body:
Still on my quest to compress/decompress files with a Java implementation of Huffman's coding (http://en.wikipedia.org/wiki/Huffman_coding) for a school assignment.

From the Wikipedia page, I quote:

Create a leaf node for each symbol and add it to the priority queue.

While there is more than one node in the queue:

Remove the two nodes of highest priority (lowest probability) from the queue

Create a new internal node with these two nodes as children and with probability equal to the sum of the two nodes' probabilities.

Add the new node to the queue.

The remaining node is the root node and the tree is complete.

Now, emphasis:

Remove the two nodes of highest priority (lowest probability) from the queue

Create a new internal node with these two nodes as children and with probability equal to the sum of the two nodes' probabilities.

So I have to take two nodes with the lowest frequency. What if there are multiple nodes with the same low frequency? How do I discriminate which one to use?

The reason I ask this is because Wikipedia has this image:

And I wanted to see if my Huffman's tree was the same. I created a file with the following content:

```<code>aaaaeeee       nnttmmiihhssfffouxprl
</code>```

And this was the result:

Doesn't look so bad. But there clearly are some differences when multiple nodes have the same frequency.

My questions are the following:

What is Wikipedia's image doing to discriminate the nodes with the same frequency?

Is my tree wrong? (Is Wikipedia's image method the one and only answer?)

I guess there is one specific and strict way to do this, because for our school assignment, files that have been compressed by my program should be able to be decompressed by other classmate's programs - so there must be a "standard" or "unique" way to do it. But I'm a bit lost with that.

My code is rather straightforward. It literally just follows Wikipedia's listed steps. The way my code extracts the two nodes with the lowest frequency from the queue is to iterate all nodes and if the current node has a lower frequency than any of the two "smallest" known nodes so far, then it replaces the highest one. Just like that.


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答: Java is slow. </p>

Body: Java is slow.


问:
Duplication of code (backend and javascript - knockout)
We have a new developer on our team. He seems to be a smart guy (he just came in so I cannot really judge). He started with implementing some small enhancements on the project (MVC3 web application using Javascript with jQuery and Knockout).

Let's say we have two values:

```<code>A - quite complex calculation
C - constant
B = A + C
</code>```

On the screen there is value B and user can change it (normal texbox). When B changes, A changes as well because C is constant. So there is linear dependency between A and B.

Now, all the calculations are done in the back-end, but we need to recalculate A as user changes B (in Javascript, I would use knockout). I thought about storing old A and B and when B changes by 10 then we know that new A will be old A + 10. He says this is dirty, because it's duplication of code (we make use of the fact that they are dependent and according to him that should be only in one place in our app). I understand it's not ideal, but making AJAX request after every key press seems a bit too much.

It's a really small thing and I would not post if we haven't had long discussion about it.

How do you deal with such problems? Also I can imagine that using knockout implies lots of calculations on the client side, which very often leads to duplication of the same calculations from the back-end. Does anyone have links to some articles/thoughts on this topic?

答:
I think real-time, client-side, more responsive interface features sometimes end up being an exception to the DRY rule in cases just like the one you've described. The need for responsiveness merits client-side code, but often one finds themselves calculating these values on the backend before passing them to the front-end; the values are then dynamically recalculated when the user adjusts the interface somehow.

One thing I can say for certain: this is not worth a roundtrip to the server, unless it's ok that your values on the front-end only update only second or more. Any less than that and you may have not only issues with responses returning out of order, but a certain jarring refresh behavior even if the former isn't a problem.

I've always thought that - at some point - this would be the main reason for using Javascript on both the front and backend but I dunno if anyone's ever taken a stab at a common code transport or something like that.

If anything, I would question whether or not it's necessary to have these calculations in your backend model/server-side code at all - perhaps you need to ensure the linear contraints between the variables are met for consistency reasons, ones of security, etc, but - if not, and if you don't explicitly call these calculations from somewhere in your backend - then I would suggest you consider taking them out of there.


问:
How to keep the trunk stable when tests take a long time?
We have three sets of test suites:

A "small" suite, taking only a couple of hours to run

A "medium" suite that takes multiple hours, usually ran every night (nightly)

A "large" suite that takes a week+ to run

We also have a bunch of shorter test suites, but I'm not focusing on them here.

The current methodology is to run the small suite before each commit to the trunk. Then, the medium suite runs every night, and if in the morning it turned out it failed, we try to isolate which of yesterday's commits was to blame, rollback that commit and retry the tests. A similar process, only at a weekly instead of nightly frequency, is done for the large suite.

Unfortunately, the medium suite does fail pretty frequently. That means that the trunk is often unstable, which is extremely annoying when you want to make modifications and test them. It's annoying because when I check out from the trunk, I cannot know for certain it's stable, and if a test fails I cannot know for certain if it's my fault or not.

My question is, is there some known methodology for handling these kinds of situations in a way which will leave the trunk always in top shape? e.g. "commit into a special precommit branch which will then periodically update the trunk every time the nightly passes".

And does it matter if it's a centralized source control system like SVN or a distributed one like git?

By the way I am a junior developer with a limited ability to change things, I'm just trying to understand if there's a way to handle this pain I am experiencing.

答: IMHO this has nothing to do with the VCS you are using. Using an "under test" branch may be solution, which can be realized with centralized or distributed VCS as well. But honestly, I think the best thing in your situation is trying to optimize the medium test suite (seems that it contains the most important tests) so that it runs much faster, so and you can use it for pre-commit-to-trunk tests, just like you do it now with your "small suite". </p>


答:
For SVN, I don't know about such a thing like "pre-commit". I think it's likely to produce commits and rollbacks when the test fails. As doc-brown says, the only way there is to commit on a temporary branch and merge it with trunk later on.

Using a distributed one like git or mercurial, I think it would be possible.
Using a "testing" repository and a "stable" repository. You push on the test rep, test it nightly, and if everything runs fine, you push from test to stable. Otherwise, you rollback the testing rep. I'm a bit unsure how the version history would look like when you push from testing to stable, but I think it's possible to exclude the broken rollbacked stuff when doing so. A bit experimenting first would be the safest.

An alternative would also be to test each person's local trunk nightly. Then, the people with passed tests are allowed to push it to the central server in the morning.

Title: How to keep the trunk stable when tests take a long time?

Body:
We have three sets of test suites:

A "small" suite, taking only a couple of hours to run

A "medium" suite that takes multiple hours, usually ran every night (nightly)

A "large" suite that takes a week+ to run

We also have a bunch of shorter test suites, but I'm not focusing on them here.

The current methodology is to run the small suite before each commit to the trunk. Then, the medium suite runs every night, and if in the morning it turned out it failed, we try to isolate which of yesterday's commits was to blame, rollback that commit and retry the tests. A similar process, only at a weekly instead of nightly frequency, is done for the large suite.

Unfortunately, the medium suite does fail pretty frequently. That means that the trunk is often unstable, which is extremely annoying when you want to make modifications and test them. It's annoying because when I check out from the trunk, I cannot know for certain it's stable, and if a test fails I cannot know for certain if it's my fault or not.

My question is, is there some known methodology for handling these kinds of situations in a way which will leave the trunk always in top shape? e.g. "commit into a special precommit branch which will then periodically update the trunk every time the nightly passes".

And does it matter if it's a centralized source control system like SVN or a distributed one like git?

By the way I am a junior developer with a limited ability to change things, I'm just trying to understand if there's a way to handle this pain I am experiencing.


答:
I know you're trying to avoid this, but the real insight here is to realize that something is seriously wrong with your codebase: you need to run a full suite of tests that takes a week just to be sure your code is stable!

The most advantageous way to fix this problem is to start separating your code base and tests into (independent) sub-units.

There are huge advantages to this:

The tests for each of those units will run faster (there are simply less of them), and they will not break if something goes wrong in one of the independent or downstream units.

A failed test will be pinpointed to a particular unit which will make it much easier to find the source of the problem.

You can separate the VCS locations of the different units so that your "stable" branch can be a pick 'n mix of the latest successfully tested build of each unit, so that a broken unit or two doesn't destabilize your "stable" version.

On the flipside management of your VCS structure will get more complicated, but at a full week for your full test, I think you can take the pain!

I still recommend using a "stable" and "development" branches strategy in some form or other, but there are many ways to go about that and  you can pick the one that works best for your organization (meta-repositories with fixed revisions pointing to separate repositories for each unit, a stable branch and a dev branch, feature branches....)


答:
I believe that you've misunderstood your colleague.

This is not duplication between server-side code and client-side code.

Duplication would be to have code on server-side doing the "quite complex calculation" you're talking about, and code on client-side doing the same calculation: if you're changing one, you should change the second one, unless it is acceptable to get inconsistent results.

Instead, here, client-side code is just remembering the result of the calculation, nothing more. Thus, when changing the calculation, you need to do it on the server-side only.

This being said, what your colleague might have said is that you're reinventing the wheel. GET AJAX queries can be cached by the browser, and there is no need to duplicate in JavaScript the caching feature already implemented in the browser. If for the same parameters, the result of the calculation is the same (not dependent on the system time, application state, database or files), just cache it severely for a long period of time, and ensure that once cached, the request doesn't even reach your server.

Title: Duplication of code (backend and javascript - knockout)

Body:
We have a new developer on our team. He seems to be a smart guy (he just came in so I cannot really judge). He started with implementing some small enhancements on the project (MVC3 web application using Javascript with jQuery and Knockout).

Let's say we have two values:

```<code>A - quite complex calculation
C - constant
B = A + C
</code>```

On the screen there is value B and user can change it (normal texbox). When B changes, A changes as well because C is constant. So there is linear dependency between A and B.

Now, all the calculations are done in the back-end, but we need to recalculate A as user changes B (in Javascript, I would use knockout). I thought about storing old A and B and when B changes by 10 then we know that new A will be old A + 10. He says this is dirty, because it's duplication of code (we make use of the fact that they are dependent and according to him that should be only in one place in our app). I understand it's not ideal, but making AJAX request after every key press seems a bit too much.

It's a really small thing and I would not post if we haven't had long discussion about it.

How do you deal with such problems? Also I can imagine that using knockout implies lots of calculations on the client side, which very often leads to duplication of the same calculations from the back-end. Does anyone have links to some articles/thoughts on this topic?


问:
Inventory Consignment Flow
Not sure whether this is the right place to ask this question, but here goes..

Currently I have requirement to add support for consignment transaction in our inventory module. I have a very limited understanding of what consignment means in inventory, i.e.

Customer get stocks/products from Seller without actually buying them, the product just resides in the Customer's inventory and it's still owned by the Seller. Only when the Customer actually buy the stocks then only will the ownership of the stock is transferred.

The issue is i can't imagine how the data will be presented to both the Customer and the Seller. What i know is that i would need to deduct the stock from the Seller's inventory when the Customer raise a request to get the stock through consignment, but what about the 'ownership' of the stocks/products? Does that mean i would need to create another column in my table to state that for each inventory it is owned by who?

Anywhere i can get information on how i should work out an inventory module like this?

Thanks.

答:
The model is similar to an e-commerce cart. You can add products to the cart, but until you pay, the seller is still the owner of those products.

If I understand well the context, the difference with a cart resides in the fact that the same product can be in one and one only cart. Once the customer adds a product to the inventory, the product is still owned by the seller, but is marked as unavailable, so that the seller doesn't end up explaining to its buyers why they cannot get their product while they added it to the inventory.

As for the ownership, the seller owns the product until payment. Once payed, the buyer becomes the owner.

Title: Inventory Consignment Flow


问:
C++ is easy once you know PHP
I was at work last week and one of our "lead developers" (who said he has programmed C++ before, but I don't believe him) was talking about C++ and how our team of developers who only know PHP would not have a hard time at all learning C++.

My first reaction was pure shock and then I laughed at his comment. He gave me a bad look and i asked if he was serious. Me personally I program a lot of C and C++ for mostly school projects and coding competitions. I don't think it's at all like PHP. I asked him why they were the same and he could not give me an answer (he doesn't know C++ at all I was thinking). Then I said "OK, yeah they both use curly braces and have conditional statements. But C++ you have to worry about memory management and all the easy to use built in functions in PHP, for example the array functions, are non-existent in C++. You actually have to know the algorithms behind them.". There are some great C++ libraries (STL, Boost) that will make your life easier but C++ is like PHP, come on!

If you already know one language it will make it a little easier to learn another because you will already be good at boolean login (if this then that) or looping but there is just so much more to C++ than PHP. Like you have to compile the language and actually have to define what type of variable you are using and returning from functions.

What do you think?

EDIT: Actually what he said was "C++ is not much different than PHP"

答:
As someone who went from PHP to C++ (though only limited C++) when I started writing C++, I often thought "Wow, this is a lot like PHP". When you consider that PHP itself is written in C, and whenever the developers faced a design decision they couldn't resolve internally, the final answer almost always ended up being "Do it like C++" it's really not that absurd a statement.

Your response about Memory Management and Array Sorting/whatever is a non-starter. That's not a PHP/C++ answer, that's a C++ with zero libraries versus just about every other popular language in existence answer. It feels to me like you're asking this question so that you can get people to agree with you -- that people who write C++ are so much better than people who write PHP.

Personally, I think that's a foolish point of view which will lead to nothing but poor decisions on your part.

Title: C++ is easy once you know PHP