问:
What are the real life use cases for tagged pointers?
What are the real life use cases for tagged pointers?

This is mostly coming from reading about small 64-bit systems and possible uses of 64-bit word pointers.

To my understanding tagged pointers are addresses which can containing extra information in bits due to possible address space on that particular architecture is much smaller.

But then, is it possible to use tagged pointers beyond trivial cases? Any cool ideas / examples?

Are there popular libraries, frameworks taking advantage of 64-bit pointers via tagged pointers? Is that possible on every hardware?

答:
The critbit trie library uses tagged pointers to differentiate between internal and external nodes in the trie. By ensuring that new nodes are allocated aligned to a certain value you are guaranteed that some of the lower bits of the address are zero, the number of which depends on the alignment you require. You can then store other info in these bits... in the case of critbit nodes the LSB is set if the node is external (a leaf). Just remember to untag the address if you intend to use it.

It saves having an extra member variable in the node structure.


问:
New nodes joining distributed genetic algorithm
I'm sort of torn on what to do for implementation of my distributed genetic algorithm problem. I would like to be able to have nodes join and part at will and not take down the whole system. But this introduces the problem of mismatch of generations. Often times a genetic algorithm simulation is capped by a certain amount of generations and if I have a node that is on 75 out of 100 generations and a brand new node joins the cluster I'm not sure if I should fake it and start at 75 and copy one of the other nodes as a starting point or have it start out at 0 and potentially have the results delayed until the end of execution of the new node. I was hoping someone had some input on what they could see as problems in addition to a long wait time with this new node if I start at 0, I am struggling to think of what could go wrong in both approaches other than that.</p>

答:
So... a node is a collection of GA population from another computer, hence the distributed aspect? And you're asking about how to join the populations?

To reap the benefit of distributing the computation you eventually have to merge the populations. You're worried about merging populations with different amount of time and processing power being thrown at them. And yeah, the younger population is probably not going to be as advanced or as fit as the older population. Maybe.

If you add a node with a population that has had zero generations, you've essentially got a collection of random garbage with no selective forces being applies and no evolution. But you also wasted no processing time. You've literally sunk zero time evolving it and having all of them instantly weeded out isn't that big of a loss.

If you add a node with, say, half the generations as your main group then they're (eyeballing it) about half as likely to add something meaningful to the population on the whole. But hey, they might.

You benefit from having separate nodes by having different attempts at solving the same problem. You widen your search, if not adding depth. One of them will hopefully get lucky and supply an insightful boost to the whole. And it protects from monocultures getting stuck on local maxima. You don't want to outbreed and have your entire population be identical. If you have a simple search space and it's all just really hill-climbing, then distributing the GA probably doesn't help all that much. If it's a complex search space and there are a lot of local maxima to GA to get stuck on, then distributed GA can help.

But when they merge, you still select based on their fitness. If you send out a node to that ancient 486 in the corner, and the next day it only cranked through 2 generations while your server farm is on it's 10,000th generation, it probably isn't actually contributing anything of value. All of it's population is going to be thrown out. And rightfully so, all of it's population doesn't do anything to advance the current solution.

ContentLicense: CC BY-SA 3.0


问:
A* search for Sudoku
I have a homework problem for an Artificial Intelligence course that I am having trouble answering.

Consider solving the Sudoku problem using A* search. The start state
  has some number of cells filled in, and the successors of each state
  are all legal ways an additional cell can be filled in. At any time we
  know exactly the number of cells that remain to filled.

Therefore, if K cells remain to be filled at node n, we know that h(n)
  = K. Thus if we set our heuristic function h(n) to be h(n)=K, we will have perfect heuristic knowledge in A.

Explain the mistake in the above statement.

I understand that this heuristic is entirely pointless since if there was some function that could find legal successors you might as well run a depth first search but what exactly is wrong with the above statement.

答:
This does not seem correct:

```<code>Therefore, if K cells remain to be filled at node n, we know that h(n) = K.
</code>```

We don't know that h(n) = K unless we know that the puzzle is solvable from node n.

Title: A* search for Sudoku

Body:
This does not seem correct:

Therefore, if K cells remain to be filled at node n, we know that h(n) = K.

We don't know that h(n) = K unless we know that the puzzle is solvable from node n.


问:
Returning multiple values in Javascript
Often I am writing a function that returns multiple values, such as a pair of coordinates:

```<code>function get_coords() {
  return ???;
}
</code>```

If I was using a language like Python, I would use a tuple:

```<code>return (x, y)
</code>```

Or, in an OOP language like Java, I would create a custom coordinate class:

```<code>class Coordinates {
  public int x;
  public int y;

  public Coordinates(x, y) {
    this.x = x;
    this.y = y;
  }
}
</code>```

Then return like this:

```<code>return new Coordinates(x, y);
</code>```

On to JavaScript.

In JavaScript, we have the option of returning a simple object:

```<code>return {x: x, y: y}
</code>```

or a Java-like approach, with a custom object:

```<code>return new coordinates(x, y)
</code>```

Are there any reasons to use one above the other?

答:
Doing this is the best (and verbose) option right now.

```<code>return {x: x, y: y}
</code>```

Or, less verbose but cleaner

```<code>return {x, y}
</code>```

The caller would have to do this to use the values

```<code>var c = get_coords();
alert(c.x + ' ' + c.y);    // c.x and c.y holds the coordinates
</code>```

If you care to use only single axis you could do -

```<code>alert(get_coords().x);
</code>```

With the ECMAScript 6 you would be able to do destructuring (in caller).

```<code>var { x, y } = get_coords();
</code>```

Too bad that we'll have to wait quite long to use ECMAScript 6 safely in production (in a cross-browser manner).

More info on destructuring - http://fitzgeraldnick.com/weblog/50/

Title: Returning multiple values in Javascript

Body:
Doing this is the best (and verbose) option right now.

return {x: x, y: y}

Or, less verbose but cleaner

return {x, y}

The caller would have to do this to use the values

var c = get_coords();
alert(c.x + ' ' + c.y);    // c.x and c.y holds the coordinates

If you care to use only single axis you could do -

alert(get_coords().x);

With the ECMAScript 6 you would be able to do destructuring (in caller).

var { x, y } = get_coords();

Too bad that we'll have to wait quite long to use ECMAScript 6 safely in production (in a cross-browser manner).

More info on destructuring - http://fitzgeraldnick.com/weblog/50/

ContentLicense: CC BY-SA 4.0


问:
When to use private methods in Python
I have a class, but every method in it should be private (apart form __init__ and __str__). Should I denote every method with a double underscore, or is that deemed bad practice?

答:
True private methods - those that can't be seen or used from outside of a class - do not exist in Python. What we have are conventions that are merely suggestions to not touch things you shouldn't.

The closest you get to privacy is name mangling. An attribute of MyClass named __some_attr will just be renamed to _MyClass__some_attr internally, making it slightly awkward to reference it from outside the class.  This is seldom used.  What most people do is simply prefix a single underscore (_attr) as a notation that something should not be relied upon & is not part of the public interface.

Using double underscores before and after the identifier, while not prohibited, is considered reserved for internal language details (like 'magic' methods).  You shouldn't go around coming up with new __attr__s (unless you're hacking on the interpreter).

OwnerDisplayName: Lewis

Title: When to use private methods in Python


问:
developing an android app that include a C++ toolkit
I'm a java developer and I want to develop an android app that capture a photo and extract its bags of visual words. To extract those bags of words I use the TOP-SURF toolkit which is written in C++

I'm new to C++ development and I want to know how to develop an android app that use this toolkit

I read about the NDK. It's the solution?

答:
The NDK is the solution to all Android problems :)

I noted with interest that all the best performing games I have are all written in the NDK (get Addons Detector - used mainly for seeing which app contains those ** push advert APIs, but it also tells you which dev tools were used for an app).

Writing with the NDK means you won't have any worries about using the C++ library. If you want to keep your Java code, you can just use JNI to call it, or wrap it in a class.


问:
Entity Framework and distributed Systems
I need some help or maybe only a hint for the right direction.

I've got a system that is sperated into two applications.
An existing VB.NET desktop client using Entity Framework 5 with code first approach and a asp.net Web Api client in C# that will be refactored right yet. It should be possible to deliver OData.
The system and the datamodel is still involving and so migrations will happen in undefined intervalls.

So I'm now struggling how to manage my database access on the web api system. So my favourd approch would be us Entity Framework on both systems but I'm running into trouble while creating new migrations. Two solutions I've thought about:

Shared Data Access dll

The first idea was to separate the data access layer to a seperate project an reference from each of the systems. The context would be the same as long as the dll is up to date in each system. This way both soulutions would be able to make a migration.
The main problem ist that it is much more complicate to update a web api system than it is with the client Click Once Update Solution and not every migration is important for the web api. This would couse more update trouble and out of sync libraries

Database First on Web Api

The second idea was just to use the database first approch an on web api side. But it seems that all annotations will be lost by each model update.

Other solutions with stored procedures have been discarded because of missing OData support and maintainability.

Does anyone run into same conflicts or has any advices how such a problem can be solved!

答:
The problem is that even though you're using EF to remove the burden of shuttling data to/from the DB from the rest of your code, your clients are still too dependent on the database schema. Thus changes to the schema impact the clients.

Ideally, you would have an application service layer that exposes a consistent API for the clients, this should be a relatively stable interface. It should expose a simplified version of the Domain Model that might hide some of the details of the Model's relationships for the client.

This gives you room to allow for changes and modifications to the database/domain model without necessarily impacting the clients. Behind the interface, the service layer is responsible to mapping inbound requests to operations on the Domain Layer and for transforming objects from the domain layer into objects that the client can understand.

As a rule of thumb, I do not expose Domain Objects directly to the client. This liberates the domain to change as necessary to support the business.

OwnerDisplayName: Dirk Beckmann


答:
It depends entirely on what the calling code is expected to do with the returned coordinates. If your current code just needs direct access to the x and y properties, use the literal:

```<code>return {x: x, y: y};
</code>```

Or with modern and/or transpiled JavaScript:

```<code>return { x, y };
</code>```

If you need a more sophisticated return value, just change it:

```<code>return new Coordinates(x, y);
</code>```

Or this:

```<code>return BuildCoordinate(x, y);
</code>```

As long as the new return-value has x and y properties (or getters), your legacy code will still work.

As noted in Sayem's answer, you can also "destructure" return values in ECMAScript 6, or if you're using a web-aware transpiler/builder:

```<code>let { x, y } = get_coords();
</code>```

Title: Returning multiple values in Javascript

Body:
Often I am writing a function that returns multiple values, such as a pair of coordinates:

```<code>function get_coords() {
  return ???;
}
</code>```

If I was using a language like Python, I would use a tuple:

```<code>return (x, y)
</code>```

Or, in an OOP language like Java, I would create a custom coordinate class:

```<code>class Coordinates {
  public int x;
  public int y;

  public Coordinates(x, y) {
    this.x = x;
    this.y = y;
  }
}
</code>```

Then return like this:

```<code>return new Coordinates(x, y);
</code>```

On to JavaScript.

In JavaScript, we have the option of returning a simple object:

```<code>return {x: x, y: y}
</code>```

or a Java-like approach, with a custom object:

```<code>return new coordinates(x, y)
</code>```

Are there any reasons to use one above the other?

Body:
It depends entirely on what the calling code is expected to do with the returned coordinates. If your current code just needs direct access to the x and y properties, use the literal:

return {x: x, y: y};

Or with modern and/or transpiled JavaScript:

return { x, y };

If you need a more sophisticated return value, just change it:

return new Coordinates(x, y);

Or this:

return BuildCoordinate(x, y);

As long as the new return-value has x and y properties (or getters), your legacy code will still work.

As noted in Sayem's answer, you can also "destructure" return values in ECMAScript 6, or if you're using a web-aware transpiler/builder:

let { x, y } = get_coords();


问:
Functional Programming - Does Knowing It Help Job Prospects?
The main language that I use at the moment is C# and I am the most comfortable with it. However, I have started dabbling in F# and Haskell and really enjoy those langauges. I would love to improve my skills in either of those languages over time since it truly is fun for me to use them (as opposed to Ruby, which is hyped as "fun", I just don't get where the fun is, but I digress...). My question is directed at those who have hired/interviewed for programming positions (junior/mid-level): if you see a functional programming language on a resume, does it affect your opinion (whether positive or negatively) of that candidate?

My rationale for knowledge of functional programming affecting the view of a candidate is because it can show that the candidate can adapt to different methodologies and take a mulit-dimensional approach to problems rather than the "same old OO approach". (This may be off-base, please let me know if this assumption is as well!)

答:
I was the technical guy helping with interviews for C# / ASP.NET developers recently, and I can tell you that if any of them were dabbling with functional languages - or indeed anything clearly removed from their work experience - that it would have earned them a definite tick from me. I think there's a huge correlation between enjoying learning and dabbling with new things and being one of the upper echelon of naturally talented programmers.

Specifically to functional programming: I think LINQ is one of the most significant additions to the C# language, we use it heavily, and while it doesn't come naturally to everyone, I can't imagine anyone with functional experience finding it difficult to work with.

ContentLicense: CC BY-SA 2.5


问:
If someone changes their license, does it apply to previously forked projects under the prior license?

Say someone puts their code on GitHub, under the MIT license.

Then I forked it and use it in my project.

Then they change the license so that it has a strict license that does not give permission to modify, sell, etc...

Would the new license apply to my code, since the code I have was from before they changed the license?

答: With a typical open source license, the license does not allow the copyright holder to revoke the license, so you can continue to use the code under the original license terms. However, some licenses may allow the copyright holder to revoke the license. You should check with a lawyer if you find yourself in this situation.</p>


答:
Safe answer:

Consult a Lawyer

Unsafe answer:

The last version/commit under the old license is fair game.

Title: If someone changes their license, does it apply to previously forked projects under the prior license?

Body:
Say someone puts their code on GitHub, under the MIT license.

Then I forked it and use it in my project.

Then they change the license so that it has a strict license that does not give permission to modify, sell, etc...

Would the new license apply to my code, since the code I have was from before they changed the license?


答:
I am not a lawyer.  If you have real questions on this, talk to a lawyer.

I am working under the assumption that the individual who has the github repo is the sole copyright owner (be it creator, or assignee) of the code.

Code is licensed as it is published. This is part of contract law.  You have a license to it and that doesn't change.  It has been ruled that that all retroactive copyright transfers and licenses are invalid.

the court found that retroactive transfers violate the basic principles of tort and contract law, and undermine the policies embodied by the Copyright Act.

The license that you have for the code you have you have released to you under that license and may continue to use it under those license terms.  The MIT license has no revocation clause as part of it.

The owner of the source, however, can always change licenses going forward, even if it was under a permissive license before.  The license is about how the owner allows others to use code he or she has copyrighted. The licenses does not restrict how one uses their own copyrights.

Also look at related

Can you change a license once you pick one?

What happens when a project switches to a different license?


问:
efficient way to count number of swaps in insertion sort
I am browsing some online coding challenge online and got struck somewhere .
Objective of program is to find maximum number of swaps required in sorting an array via insertion sort in efficient time

the first approach that is brute force approach gives the O(n^2) complexity

The next i can think of is merge sort algorithm the code i use for that is

```<code>#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int mergesort(int *,int);
int _mergesort(int *,int *,int,int);
int merge(int *,int *,int,int,int);

int mergesort(int arr[],int n)
{
    int temp[n];
    return _mergesort(arr,temp,0,n-1);
}

int _mergesort(int arr[],int temp[],int left,int right)
{
    int mid,count=0;
    if(right>left)
    {
      mid=(left+right)/2;
      count=_mergesort(arr,temp,left,mid);
      count+=_mergesort(arr,temp,mid+1,right);
      count+=merge(arr,temp,left,mid+1,right);
    }
    return count;
}

int merge(int arr[],int temp[],int left,int mid,int right)
{
  int i, j, k;
  int count = 0;
  i = left;
  j = mid;
  k = left;
  while ((i <= mid - 1) && (j <= right))
  {
    if (arr[i] <= arr[j])
    {
      temp[k++] = arr[i++];
    }
    else
    {
      temp[k++] = arr[j++];
      count = count + (mid - i);
    }
  }
  while (i <= mid - 1)
    temp[k++] = arr[i++];
  while (j <= right)
    temp[k++] = arr[j++];
  for (i=left; i <= right; i++)
    arr[i] = temp[i];

  return count;
}

int main()
{
    int n,tc,i;
    cin>>tc;
    while(tc)
    {
      cin>>n;
      int arr[n];
      for(i=0;i<n;i++)
          cin>>arr[i];
      cout<<mergesort(arr,n);
      tc--;
    }
    return 0;
}

The example test case is
Sample Input:
2
5
1 1 1 2 2
5
2 1 3 1 2

Sample Output:
0
4
</code>```

this gives me a complexity of nlogn
Initially the program reads number of test case that is 2 and followed by two test case

the algorithm works fine for small range of values but show time limit exceeded error in some test case .

What is the most efficient way of doing this i cant find out any suggestion or edits would be appreciated.

答:
The key to this problem isn't to try to find the worst case situation, but rather find the pattern to be able to create the function sorts(x) = maximum number of sorts for an array of length x.

The insertion sort is one of the 'easy' forms of a sorting network.  A sorting network for an insertion sort looks like:

(source: wikimedia.org)

Each line is a comparison and possible swap.  Compare the second and first spot.  Possibly swap.  Then compare third and second, and then second and first.  etc...

As an aside, this is what a bubble sort looks like in a sorting network.

And if you can do parallel comparisons (the whole point of the sorting network)... they both look like:

Looking at just the lines, this is a triangle...

```<code>2: .
3: ..
4: ...
5: ....
</code>```

For an array of size 2, you need one comparison.

For an array of size 3, you need to sort an array of size 2, and do two more comparisons.

For an array of size 4, you need to sort an array of size 3, and do 3 more comparisons.

For an array of size X, you need to sort an array of size x-1 and do x-1 more comparisons.

The sequence is:
1, 3, 6, 10, ...

This is a well known sequence - (n * (n+1))/2

Remembering that this starts from 2 rather than 1...

sorts(x) = ((x - 1) * x)/2

Body:
The key to this problem isn't to try to find the worst case situation, but rather find the pattern to be able to create the function sorts(x) = maximum number of sorts for an array of length x.

The insertion sort is one of the 'easy' forms of a sorting network.  A sorting network for an insertion sort looks like:

(source: wikimedia.org)

Each line is a comparison and possible swap.  Compare the second and first spot.  Possibly swap.  Then compare third and second, and then second and first.  etc...

As an aside, this is what a bubble sort looks like in a sorting network.

And if you can do parallel comparisons (the whole point of the sorting network)... they both look like:

Looking at just the lines, this is a triangle...

2: .
3: ..
4: ...
5: ....

For an array of size 2, you need one comparison.

For an array of size 3, you need to sort an array of size 2, and do two more comparisons.

For an array of size 4, you need to sort an array of size 3, and do 3 more comparisons.

For an array of size X, you need to sort an array of size x-1 and do x-1 more comparisons.

The sequence is:
1, 3, 6, 10, ...

This is a well known sequence - (n * (n+1))/2

Remembering that this starts from 2 rather than 1...

sorts(x) = ((x - 1) * x)/2


问:
Do software licenses (ie, MIT) need to be included with the executable?
Whenever a software license reads:

... The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

Does this mean you have to include it with the executable (the version customers get) or just the source code (for the programmers)?

Sorry if this is a silly question, but it doesn't clearly state what "the Software" is referring to, and I can see people maybe wanting credit for it.

If you don't have to include the license with the executable, do you need to give credit in your executable release some other way, like some other kind of copyright notice that just says "Copyright  "? Is there a specific format to that?

答:
"Software" means whatever you attach the license to.  If you include a copy of the executable, the MIT license covers that also, as well as all of the documentation you include with it.

In practice, I don't think this is going to matter.  If you don't provide an executable, the users of your source code will have to compile one themselves, and the MIT license allows them to re-license that executable (and the original source code, for that matter), under a different license anyway, as they see fit.

If it matters, simply add a sentence that defines the term "software."


问:
Optional semicolons
Most often, in a general-purpose imperative language - semicolons as statement-delimiters are either required, or completely disallowed (e.g. C and Python).

However, some languages, like JavaScript, allow you to opt out of delimiting your statements with semicolons, in favor of other delimiters (such as a newline).

What are the design decisions behind this? I understand that semicolons are essential when writing multiple statements on the same line, but is there another reason to make them mandatory (except following C)?

答:
Making them mandatory (or disallowing them completely) reduces the number of corner cases, eliminates a potential source of obscure bugs, and simplifies the compiler/interpreter design.

The language designers who have opted to make them optional have
chosen to live with the ambiguity in return for greater syntactic flexibility.

Title: Optional semicolons


答:
JavaScript has shown us that this is a very bad idea.  For example:

```<code>return
0;
</code>```

In C, this returns a value of 0.  In JavaScript, this returns undefined because a semicolon gets inserted after the return statement, and it's not immediately obvious why your code is breaking unless you happen to know about the details of automatic semicolon insertion.

Title: Optional semicolons

Body:
Most often, in a general-purpose imperative language - semicolons as statement-delimiters are either required, or completely disallowed (e.g. C and Python).

However, some languages, like JavaScript, allow you to opt out of delimiting your statements with semicolons, in favor of other delimiters (such as a newline).

What are the design decisions behind this? I understand that semicolons are essential when writing multiple statements on the same line, but is there another reason to make them mandatory (except following C)?

Body:
JavaScript has shown us that this is a very bad idea.  For example:

return
0;

In C, this returns a value of 0.  In JavaScript, this returns undefined because a semicolon gets inserted after the return statement, and it's not immediately obvious why your code is breaking unless you happen to know about the details of automatic semicolon insertion.


问:
Good Procedure or Function Design
This is in reference to the question posted here.  As I would judge it, the question there should be closed simply because it seems to ask why the Borland developers made one thing a function and another a procedure (function that returns a void result).

Now the example was given there of some string manipulation functions that exist in Borland Pascal or Delphi:

```<code>S2 := Copy(S1,3,2);
</code>```

Copies into S2 from S1 the 2 characters starting from the 3rd
  position.

```<code>Delete(S,3,2);
</code>```

Deletes from S the 2 characters starting from the 3rd position.

Now I thought it might be a good discussion on what would be good design decisions regarding devising these things.  I picked up a few rules of good design on what a function prototype should look like beyond the obvious (name reflects function, function result should be atomic, no extraneous variables), but are there any others that should govern a situation such as this one or others?   I really didn't see a good case in Atwood's code book where it was discussed.

Anyway, are there some good rules on how functions should be designed to work?  Barring the specious naming, would it be better to have

```<code>S2 := Delete(S1,3,2);
</code>```

as opposed to

```<code>Delete(S,3,2);
</code>```

?  Are there any other useful considerations or examples to discuss of good and bad function design?

答: I'm not sure about other languages, but in Ruby the approach they take is to usually implement both types of method, so that the user can choose which one is best for the situation, but the type that modifies the data (rather than leaving the original data unchanged and returning the changed version) is always suffixed with a '!', so it is clear that the function performs a destructive operation.</p>

Title: Good Procedure or Function Design


问:
Managing threads in Java with a good pattern
This morning I began writing a minimal chat using Java socket and threads but it took some minutes for me to experience a lot of problems in the MVC management.

Currently I have 3 classes:

Main, this is just the main class used for starting the Control.

ChatController, I use this for managing Model and View classes (this is a Controller class).

Host, a class containing a Socket attribute and two Scanner and PrintStream attributes for reading and writing to and from the socket.

The problem here is which class extending from Thread to let the program both read and write features concurrently. My professor told me to extend the ChatControl (hence, the Controller) class, but I think it is too much hard-coding (and also, I don't like the method/attributes inherited from Thread to be visible from the ChatController class).

So, is it correct extending the Control class from Thread for managing the thread or should I consider to implement another class for tasking this problem (or even trying some other patterns)?

If you need some source, find it on pastebin.

答:
A Similar Exercise

What I did for an exercise using MVC, Sockets, and multiple threads was to first develop what I called the "models".  This exercise was called Echo Client/Server because all that the server did was echo what each client sent to the server, back to the client that sent up the message.

My exercise was a little simpler than a chat exercise, but the two exercises are very similar in nature.

My classes:

The EchoServer class, the model for the server side with absolutely no user interface.

The EchoServerDaemon class, just a class with a main() method to create an EchoServer object and start a thread for it, one view

The EchoClient class, the model for the client side with absolutely not user interface

The EchoClientConsole, a console view of the client's input/output

The EchoUtils class which contains anything that the EchoServer model and the EchoClient model need, such as the default port number.

I could have added classes such as the following classes without much work because the model classes EchoServer and EchoClient were independent of their user-interfaces:

EchoServerConsole, a server with a console view
EchoServerGUI, a server with a GUI view
or
EchoClientGUI, a client with a GUI view

I got the model done first.

Then, I got the views specified.

I did the controllers last, connecting the model and the view.

I believe that having multiple threads for a server is pretty much mandantory.

On the server, I had a class with one thread which I called the ConnectionListener which is an inner class of EchoServer.  The ConnectionListener mainly calls serverSocket.accept() and creates connections.

I also had a thread for each connection called ConnectionServicer.  Each client connection was serviced by a separate ConnectionServicer thread so that the server as a whole could call read() and write() and if the thread blocked, nothing else would freeze.

I don't think that the client needs a separate thread unless you're doing something time-consuming such as downloading a large file.

If you want me to make my source-code available, let me know.


答:
It simplifies your grammar and parser somewhat to make the semicolons mandatory.  Essentially, it allows the lexer to dump all the whitespace, including newlines, and the parser doesn't have to worry about it at all.

On the other hand, once you start wanting to tell the parser about whitespace anyway, it's not that hard to make the semicolons optional.  You can often just lump them together with a whitespace token and your parser can handle it just fine.

For example, try inserting the semicolons into the following series of C statements.

```<code>functionCall(3, 4) 9 + (3 / 8) variable++ while(1) { printf("Hello, world\n") }
</code>```

While there are some weird things you can no longer do, like while(1);, for the most part, it's relatively easy with modern parsing techniques to determine where the statements end without a specific delimiter.  Even if you still want to allow the weird stuff, it's not that hard to make a newline_or_semicolon non-terminal.

Title: Optional semicolons

Body:
It simplifies your grammar and parser somewhat to make the semicolons mandatory.  Essentially, it allows the lexer to dump all the whitespace, including newlines, and the parser doesn't have to worry about it at all.

On the other hand, once you start wanting to tell the parser about whitespace anyway, it's not that hard to make the semicolons optional.  You can often just lump them together with a whitespace token and your parser can handle it just fine.

For example, try inserting the semicolons into the following series of C statements.

functionCall(3, 4) 9 + (3 / 8) variable++ while(1) { printf("Hello, world\n") }

While there are some weird things you can no longer do, like while(1);, for the most part, it's relatively easy with modern parsing techniques to determine where the statements end without a specific delimiter.  Even if you still want to allow the weird stuff, it's not that hard to make a newline_or_semicolon non-terminal.


问:
Why do books say, "the compiler allocates space for variables in memory"?
Why do books say,  "the compiler allocates space  for variables in memory". Isn't it the executable which does that? I mean, for example, if I write the following program,

```<code>#include <iostream>
using namespace std;

int main()
{
   int foo;
   return 0;
}
</code>```

and compile it, and get an executable (let it be program.exe), now, if I run program.exe, this executable file will itself command to allocate some space for the variable foo. Won't  it ? Please explain why books keep on saying, "the compiler will do this...do that".

答:
It's compiler who decides where to store a variable - can be in stack or a free register. Whatever the storage decision made by compiler, the corresponding machine code to access that variable will be generated and cannot be changed in run time. In this sense, the compiler is in charge of allocating space for variables and the final program.exe is just blindly acting like a zombie in run time.

Now, don't confuse this with different dynamic memory management like malloc, new or may be your own memory management. Compilers are dealing with variable storage and access but it doesn't care what an actual value means in another framework/library. For example:

```<code>byte* pointer = (byte*)malloc(...);
</code>```

In run time, malloc may return an arbitrary number but the compiler doesn't care, all it cares is where to store that number.

Body:
It's compiler who decides where to store a variable - can be in stack or a free register. Whatever the storage decision made by compiler, the corresponding machine code to access that variable will be generated and cannot be changed in run time. In this sense, the compiler is in charge of allocating space for variables and the final program.exe is just blindly acting like a zombie in run time.

Now, don't confuse this with different dynamic memory management like malloc, new or may be your own memory management. Compilers are dealing with variable storage and access but it doesn't care what an actual value means in another framework/library. For example:

byte* pointer = (byte*)malloc(...);

In run time, malloc may return an arbitrary number but the compiler doesn't care, all it cares is where to store that number.


问:
Lucene + Joins == RDBMS?
Now that Lucene supports joins (at indexing time and at querying time) can one use Lucene as a databse (a NoSQL one, with Eventual Consistency)?

Note: I was pondering on that for sometime and this is an idea that comes around again and again from time to time and there are proof that on actually can do that - to some extent (RavenDB). Besides I think referential integrity is over-rated - I never use foreign keys in a RDBMS when I work on a big, fast changing project with a small team; from experience it's pure maintenance headache and kills productivity.

The only thing that seems to me a hurdle in building up this mindset is the lack of transactions - and yes; you can have 2 step transactions (with say MongoDB and Lucene uses that for some internals) but that's lots of work; and I do not know how that would be possible with Lucene.

答: Yes. I've done projects in the past where we essentially used lucene as a data store in lieu of a database. This was long before NoSQL was hot. Really there's no fixed definition of what qualifies as a NoSQL database, so anything that stores and retrieves data is sufficient. Things like dbm files have been around forever.</p>

Title: Lucene + Joins == RDBMS?


问:
How to spread awareness for generic programming among team members?
I am staying in an environment, where people believe:

Java generics are the feature exclusively used for library writing
and not for the real coding.

C++ is an OO programming language; template is an optional and
avoidable feature

Though, these people rely highly on the libraries written using generic programming (e.g. STL, Java containers). If I write a code using templates or generics, the code reviewer is most likely to reject it and will comment to write it in a "proper / understandable / elegant" way.

Such mentality is applicable from normal programmer to senior most manager. There is no way out, because 90% of the time, these people have their lobbying.

What is the best way (not being cut throat) of explaining them, the practical approach of writing code which constitutes OO and generic programming both at the same time ?

答:
What you're dealing with here is a collection of biases. People prefer the status quo, a groupthink has developed, and the argument has been waged a few times so that people have become entrenched in their beliefs.

One of the most effective strategies here is to focus on a tiny victory. I read the following example in a book: the author was a staunch non-Apple user. She didn't like them, and she wanted nothing to do with them. She had many discussions with people with a pro-Apple stance, and each one just pushed her heels deeper into the ground. Then someone bought her an iPod shuffle and like that, her biases disappeared. It didn't make her want to buy only Apple products, but the hard, entrenched anti-Apple stance had been replaced with a more balanced viewpoint. There was room for compromise, and she ended up slowly converting to Apple entirely.

So don't try to convince everybody all at once: it will have the opposite effect. Focus on one little thing, and the rest will happen by itself. Just get rid of the two-sided nature of the argument so that people can cross over bit by bit, instead of all at once.

The specific point to focus on depends on your situation, but here's one idea: The division you sketch between libraries and 'real code' seems very unnatural. In my view, a programmer making an application should spend 80% of his time on a library for the type of application he's making and 20% using that library to build the application. All code worth keeping should be considered a library. I would suggest to your superiors that you generalize some of your code into an in-house library (if you haven't already). By their own logic, they should use generics for this, and by the estimate above, 80% of your code can end up inside the library. Once you get everybody using generics from the other side, they should get used to it, and the biases should fade.


问:
Modeling a Student Application/Committee Relationship
I'm developing an ERD for a graduate student manager program (it's for a university class, so it's a fairly trivial implementation).

In this snippet of the model, I'm trying to work out the 'application' and 'committee' entities/relationships. Basically, a committee - comprised of staff members - can be formed and assigned to review an application. Here are the entities I've come up with:

application: Comprised of a student's application data submitted through a form (student id, date submitted, degree, etc.).

committee: Self-explanatory. Group of staff members that can review applications.

staff_member: Any faculty member.

committee_membership: An associative entity I've created to resolve the many-to-many relationship between committee and staff member since a committee can have many staff members, and a staff member can belong to many committees.

Is this an effective implementation of what I'm trying to do? I'm still trying to wrap my head around associative entities and when they are needed. It seems strange to have the 'committee' table with a single column. Also - and I know I've given you limited information - do my relationships look generally correct?

答: Without any additional columns on the 'committee' table, it's existence can seem strange, but this is correct normal form.  Other information could be added to this table such as a committee's name, creation date, etc... which would make the table more useful and possibly less strange looking.</p>


答:
The main downside I see is updates. The only way to do an update in the Lucene ecosystem was to read the whole document, modify it, delete the original, and write back the contents as a new document. Some syntactic sugar has been added to Solr to make this easier. Lucene itself doesn't support per-field updates, though some stacked update feature appears to be being worked on.

Otherwise, for read-only data, you won't get a better general purposes way of slicing/dicing/analyzing data. We've done a lot of work for clients where they use Lucene (through Solr) just for the fact that every column is indexed, and its easy to lookup/filter/group/facet on anything. That's why tools like kibana (built on ElasticSearch, another service built on top of Lucene) are so powerful even though they have relatively little to do with fulltext search.

Title: Lucene + Joins == RDBMS?

Body:
Now that Lucene supports joins (at indexing time and at querying time) can one use Lucene as a databse (a NoSQL one, with Eventual Consistency)?

Note: I was pondering on that for sometime and this is an idea that comes around again and again from time to time and there are proof that on actually can do that - to some extent (RavenDB). Besides I think referential integrity is over-rated - I never use foreign keys in a RDBMS when I work on a big, fast changing project with a small team; from experience it's pure maintenance headache and kills productivity.

The only thing that seems to me a hurdle in building up this mindset is the lack of transactions - and yes; you can have 2 step transactions (with say MongoDB and Lucene uses that for some internals) but that's lots of work; and I do not know how that would be possible with Lucene.


答:
This is just a quick appraisal of your ERD, so don't take it as a complete list of what may need to be added or changed to make it complete for your needs...

First, I would suggest that your single-column committee entity should have a name, and perhaps a description.  You may also need other information attached to that table, like the date the committee was formed, and when it expired.  But definitely some kind of human-friendly name at the minimum.  If you were tasked with printing out a report on the committees and their work during the past year, you'd certainly want more than just an ID to identify each one, right?

Second - where do you plan to keep the outcome of the committee's deliberations?  You are probably going to want to record somewhere whether the application was approved, not approved, or whether it was sent back for modification/more information. You might also want a notes field on the application to explain the committee's reasons for their decision, whatever that decision may be.

When you do these sorts of exercises, it helps to keep in mind what some likely final uses of the data may be, and then keep asking yourself "what if...?" for a while to try to come up with likely columns for each entity.  Will reports need to be created for this data? What type of reports? What if an application is marked needing further information and resubmission - does it have to go back to the same committee for the second round of approval, or might it fall to a new committee to handle the re-application review?

Title: Modeling a Student Application/Committee Relationship

Body:
I'm developing an ERD for a graduate student manager program (it's for a university class, so it's a fairly trivial implementation).

In this snippet of the model, I'm trying to work out the 'application' and 'committee' entities/relationships. Basically, a committee - comprised of staff members - can be formed and assigned to review an application. Here are the entities I've come up with:

application: Comprised of a student's application data submitted through a form (student id, date submitted, degree, etc.).

committee: Self-explanatory. Group of staff members that can review applications.

staff_member: Any faculty member.

committee_membership: An associative entity I've created to resolve the many-to-many relationship between committee and staff member since a committee can have many staff members, and a staff member can belong to many committees.

Is this an effective implementation of what I'm trying to do? I'm still trying to wrap my head around associative entities and when they are needed. It seems strange to have the 'committee' table with a single column. Also - and I know I've given you limited information - do my relationships look generally correct?


问:
Specifying the format in which I want to get a response through POST
It's a good practice to let a client specify the format in Web REST API:

```<code>GET /api/items/123.csv
</code>```

However, not only GET can return some answer, but POST also can do

```<code>Status: 201 Created

{
  mgs: "Your item has created successfully",
  href: "/example.com/items/123"
}
</code>```

How should URI look like for a POST (PUT or whatever, but not GET) request which returns a response so that a client can specify the format they want the response to be in? Like this?:

```<code>POST /api/items/.csv
</code>```

Or suppose there is an error when a client sends a POST request and the server must inform the client about it:

```<code>Status: 400 Bad Request
{
  mgs: "this is a bad request",
  devMessage: "it's bad because ...."
  friendlyMessage: "something bad happened..."
}
</code>```

What format should it respond in, why and how do I specify it as a client?

P.S. - I'm aware about REST - Tradeoffs between content negotiation via Accept header versus extensions

答:
```<code>POST /api/items/.csv
</code>```

looks logical only if you give '.csv' special meaning. If not, then it should be interpreted as POST /api/items/.csv/ by the server which I don't think it's what you want. I'm just using this as example where using file extension doesn't work.

Regarding what should be returned, the server should look at the Accept header and respond in acceptable format if it returns any entity at all (4xx responses should return explanation why it was an error).

I think it should be like this:

```<code>POST /api/postbox/
Accept: application/json
Content-type: text/csv
</code>```

If success server returns:

```<code>201 Created
Location: /api/items/123.csv
</code>```

or when fail:

```<code>415 Unsupported Media Type
Content-type: application/json
Message-body: { error: "please only post text/csv file." }
</code>```

Body:
POST /api/items/.csv

looks logical only if you give '.csv' special meaning. If not, then it should be interpreted as POST /api/items/.csv/ by the server which I don't think it's what you want. I'm just using this as example where using file extension doesn't work.

Regarding what should be returned, the server should look at the Accept header and respond in acceptable format if it returns any entity at all (4xx responses should return explanation why it was an error).

I think it should be like this:

POST /api/postbox/
Accept: application/json
Content-type: text/csv

If success server returns:

201 Created
Location: /api/items/123.csv

or when fail:

415 Unsupported Media Type
Content-type: application/json
Message-body: { error: "please only post text/csv file." }


答:
The question you linked to addresses what to do when a client GETs from the server, not what to do when the client POSTs to the server.

In your case, the use of the HTTP Accept header won't work as it is the equivilent of a client saying: "Hey give me this resource, but only in these formats."

This is a case where the robustness principle applies:

Be conservative in what you do, be liberal in what you accept from others.

When the client POSTs the data there should be a Content-Type that describes whats being delivered. Where possible, your application should interpret and accept as much as possible before failing. Does it matter if its CSV, JSON, or XML if you application can accept all three?

A single URL for delivery will be easier on your clients, and most likely easier on you. Apart from a slight difference in code to pull the content from the CSV, JSON, XML, whatever, its most likely that once you convert it to a format the application handles internally the data will be treated the same.

Title: Specifying the format in which I want to get a response through POST

Body:
It's a good practice to let a client specify the format in Web REST API:

```<code>GET /api/items/123.csv
</code>```

However, not only GET can return some answer, but POST also can do

```<code>Status: 201 Created

{
  mgs: "Your item has created successfully",
  href: "/example.com/items/123"
}
</code>```

How should URI look like for a POST (PUT or whatever, but not GET) request which returns a response so that a client can specify the format they want the response to be in? Like this?:

```<code>POST /api/items/.csv
</code>```

Or suppose there is an error when a client sends a POST request and the server must inform the client about it:

```<code>Status: 400 Bad Request
{
  mgs: "this is a bad request",
  devMessage: "it's bad because ...."
  friendlyMessage: "something bad happened..."
}
</code>```

What format should it respond in, why and how do I specify it as a client?

P.S. - I'm aware about REST - Tradeoffs between content negotiation via Accept header versus extensions


问:
Is it bad practice to store metadata information in file names? Better solutions?
I have noticed where I work people are keen on storing information in file names, and parsing the file names.

To me this doesn't seem to be especially good practice. I already see the occasional issues with scripts globbing for a file, and getting the wrong one because another file matches first.We are also discussing how to get around problems with separators for the fields.

Is it considered bad practice or not?

What are other accepted solutions for retrieving files from a file system based on some type of metadata?

答:
It sounds like you need a database.

There are lots of security issues with putting user data in file names. Let's say that you have a file for each user ("username.txt"). What happens what someone registers the username "../../../../etc/passwd" depends on how you are filtering user input.

Database frameworks will sometimes assist you with sanitizing user input.


问:
A good name for ValueObject that contains database update/create column values
We all know these fields, database admins so like to add:

UserCreated & DateCreated

UserUpdated & DateUpdated

They need to be displayed in the UI so I want to put them in some ValueObject but I can't come up with a good name to call the class...

答:
Your DBA insists on these fields because he/she wants to ensure that the user and date of the last change is recorded.  This sort of tracking is called audit, and the history of these changes is an audit trail.

So how about AuditInfo?


问:
How does datomic handle "corrections"?
tl;dr

Rich Hickey describes datomic as a system which implicitly deals with timestamps associated with data storage

from my experience, data is often imperfectly stored in systems, and on many occasions needs to retroactively be corrected (ie, often the question of "was a True on Tuesday at 12:00pm?" will have an incorrect answer stored in the database)

This seems like a spot where the abstractions behind datomic might break - do they? If they don't, how does the system handle such corrections?

Rich Hickey, in several of his talks, justifies the creation of datomic, and explains its benefits.

His work, if I understand correctly, is motivated by core the insight that humans, when speaking about data and facts, implicitly associate some of the related context into their work(a date-time). By pushing the work required to manage the implicit date-time component of context into the database, he's created a system which is both much easier to understand, and much easier to program. This turns out to be relevant to most database programmers in practice - his work saves everyone a lot of time managing complex, hard to produce/debug/fix, time queries.

However, especially in large databases, data is often damaged/incorrect (maybe it was not input correctly, maybe it eroded over time, etc...). While most database updates are insertions of new facts, and should indeed be treated that way, a non-trivial subset of the work required to manage time-queries has to do with retroactive updates.

I have yet to see any documentation which explains how such corrections, or retroactive updates, are handled by datomic; from my experience, they are a non-trivial (and incredibly difficult to deal with) subset of time-related data manipulation that database programmers are faced with.

Does datomic gracefully handle such updates? If so, how?

答:
The question the built in time stamp will answer is what did I believe on Tuesday at 12, not what do I now believe the value to be on Tuesday at 12.  If you need a time stamp to tell you when something is true then the time stamp is data, not metadata.  Datomic's built in time stamp is metadata, and should be treated as such.  If you later decide that it should really only be true at 1 instead of 12, then you write an update like you would for any other database.  Datomic will remember both the new time and when you updated it.

Basically treat the built in time stamp like you would an audit log.  It should more or less have zero to do with your application's day to day logic. A couple of scenarios where it might be useful is if you need to undo a bad write or run an analysis how quickly a value is changing.

Title: How does datomic handle "corrections"?


问:
Suggestions designing an XML polling deamon in python
I'm about to take on a new project for a client designing a server-side python program that will poll a number of XML streams at regular intervals and populate a Postgresql database with results. The system will basically act as an XML cacheing daemon and populate a database. That database will then be accessed by a separate program which will serve that data in JSON to a public-facing website.

I'm wondering if anyone has suggestions as to the high-level design of the python caching/polling program. I'm thinking something class-based where a number of classes (one for each XML stream to be polled) descend from a common parent class, check for new content and then grab any if found. I'm thinking to have a table for each of the XML streams on the database, a column for each of the XML fields, and another table to keep track of the "last access" for each stream.

For this I'm planning on using Python 2.7, pyscopg, and ElementTree for XML processing.

Does anyone have any thoughts or criticism on my design or toolchain at this point? Is parsing my XML values to  store in a Postgres database more work than is worthwhile? The front-end program that will be serving that data will be turning it into JSON rather than XML by the way.

答:
I'm not sure why you refer to the daemon as "caching"; it is probably better to think of it as a polling-translation or polling-adaptation daemon. I'm often surprised at how subtle naming differences can change how you think about the problem.

Your desire to get the XML data out of XML is a good one. I've yet to see any case where XML is useful for anything other than well-defined data exchange and then only when XML is expected by one side or the other. Put another way, if I want to look for the average weight of an unladen swallow, digging through a pile of XML is about the worst way I can think to get at that data. This points to another place where your writing is inverted compared to my thinking: the data schema is preeminent, XML is just a container. When you say "column for each of the XML fields", I think "column for each data field". Are these different enough to matter? Probably.

You talk of classes and inheritance. People try to use inheritance far more than is probably worthwhile (which is its own diatribe) but I think you might be over-engineering the adaptation part. I can see no reason to bother constructing a Python class representation of  input items when the next step is to turn it into a SQL statement and send it away. From what little you've given, instantiating a class for each row could be convenient or it could be overkill; I'd assume overkill unless you can demonstrate otherwise.

Your tool choice is obviously correct with one exception: unless there is reason you've not given for preferring Python 2, use Python 3. Your future self will thank you in five years.


问:
Refactoring two classes from third-party library that could have extended a base class
I have two Classes, with very similar behaviors, both from a third party library.
Both needs to be populated with some value object and sent to specific queues in order for logging. Please note both of them does not have a common parent.

I am scratching my head to find out ways to refactor this.
Here is the sceanrio.

Class 1 : Apple
Class 2 : Orange

Unfortunately, Apple and Orange are not child classes of Fruit
And I can not change them to extend a base class.
Constructors of Apple and Orange have different signatures.

Current code:

```<code>if(isApple){
    Apple apple = new Apple(....);
    apple.setColor(Color.RED);
    apple.setPrice(10);
    apple.setCount(1000);

    AppleMQObject applMQObject = new AppleMQObject(apple);
    Producer appleProducer = Factory.create("apple-producer");
    appleProducer.send(applMQObject);
}else{
    Orange orange = new Orange(...);
    orange.setColor(Color.ORANGE);
    orange.setPrice(30);
    orange.setCount(100);
    OrangeMQObject oMQObject = new oMQObject(orange);
    Producer orangeProducer = Factory.create("orange-producer");
    orangeProducer.send(orangeMQObject);
}
</code>```

I can move the MQ code out to a common method. But how to handle the apple/orange situation.

答:
```<code>MyFruitInterface{
setColor();
setPrice;
..
}

MyOrangeImpl{
Orange o;

MyOrangeImpl(Orange o)
{
this.o = o;
}
setColor(Color C){
o.setColor(c);
}
setPrice(int price){
o.setPrice(price);
}
..
}
MyAppleImpl{

Apple a;

MyAppleImpl(Apple a)
{
this.a = a;
}
setColor(Color C){
a.setColor(c);
}
setPrice(int price){
a.setPrice(price);
}
..
}
</code>```

Now you have a common interface;

Body:
MyFruitInterface{
setColor();
setPrice;
..
}

MyOrangeImpl{
Orange o;

MyOrangeImpl(Orange o)
{
this.o = o;
}
setColor(Color C){
o.setColor(c);
}
setPrice(int price){
o.setPrice(price);
}
..
}
MyAppleImpl{

Apple a;

MyAppleImpl(Apple a)
{
this.a = a;
}
setColor(Color C){
a.setColor(c);
}
setPrice(int price){
a.setPrice(price);
}
..
}

Now you have a common interface;


答:
Semicolons are useful in a grammar for 2 reasons. First, it lets you split long statements into multiple lines without having godawful continuation characters (I'm talking about you, Fortran and Basic).  Second, it let's the parser have a way to "give up" parsing when the syntax gets really convoluted because of a typo. Stealing from Karl Bielefeldt's example,

```<code>functionCall(3, 4) 9 + (3 / 8) variable++ while(1) { printf("Hello, world\n") }
</code>```

imagine you typed one extra open paren:

```<code>functionCall((3, 4) 9 + (3 / 8) variable++ while(1) { printf("Hello, world\n") }
</code>```

now where is the mistake?  If you had the semicolons, it is easier for the parser to give up at the first semicolon. It could even continue parsing after the semicolon if it wanted to.

```<code>functionCall((3, 4);  <- something is wrong here. emit error and keep going.
                      9 + (3 / 8); variable++; while(1) { printf("Hello, world\n"); }
</code>```

Now it is easier on the parser to report an error, and easier to locate the line/column where it occurred.

Title: Optional semicolons

Body:
Semicolons are useful in a grammar for 2 reasons. First, it lets you split long statements into multiple lines without having godawful continuation characters (I'm talking about you, Fortran and Basic).  Second, it let's the parser have a way to "give up" parsing when the syntax gets really convoluted because of a typo. Stealing from Karl Bielefeldt's example,

functionCall(3, 4) 9 + (3 / 8) variable++ while(1) { printf("Hello, world\n") }

imagine you typed one extra open paren:

functionCall((3, 4) 9 + (3 / 8) variable++ while(1) { printf("Hello, world\n") }

now where is the mistake?  If you had the semicolons, it is easier for the parser to give up at the first semicolon. It could even continue parsing after the semicolon if it wanted to.

functionCall((3, 4);  <- something is wrong here. emit error and keep going.
                      9 + (3 / 8); variable++; while(1) { printf("Hello, world\n"); }

Now it is easier on the parser to report an error, and easier to locate the line/column where it occurred.


问:
.NET BCL Change Analysis - Uses Beyond Sating Curiosity

This is part of a series of questions which focuses on the Abstraction Project, which aims to abstract the concepts used in language design in the form of a framework.  There is a sister project to Abstraction called OILexer, which aims to construct a parser from grammar files, without the use of code injection on matches.

Some other pages associated to these questions, related to structural typing, can be viewed here, and ease of use, found here, a question on writing the compiler compiler can be found here.  The meta-topic associated to an inquiry about the framework and the proper place to post can be found here.

One of the steps into this process was building my own ECMA-335 Metadata parser.  Since I tend to build tools to build tools, I recently decided to do an analytical top-down on the .NET Base Class Libraries.  The future goal will be utilizing it to construct libraries which represent the BCL to aid in rapid code generation (more on that later if someone cares.)

I wanted to get a basic idea of the overall versions of libraries within the .NET BCL, so I analyzed the Framework folder stored locally.  Doing this per framework version should reflect the end-user's system: right now I'm targeting myself.

The first step in this goal is to construct a class which conceptualizes a multi-versioned library and pulls in each iteration as needed.  The next step is pulling in all the types from each version and comparing the individual lists of types (oddly more work than it should be.)

The result is a fairly straight forward view of the BCL which breaks down the version a library was introduced, and displays which version new types were introduced, grouped by namespace.

This should be an exhaustive list which excludes types which were introduced with the library itself.  You can assume that if it isn't listed, it was there from the library's inception.  The view is very simple: +Type means it was added, -Type means it was removed Type->Assembly means it was relocated at that version.

The objective side of this is: if it's accurate, it gives you a basic breakdown of when a type was introduced, useful for determining the lowest version of .NET needed for a given piece of functionality.  The next step is member analysis which will make the first step look easy (mostly due to method signature comparison, since each parameter type will have to be reversioned and looked up.)

I'm curious if this analysis could later be used for an automated tool which could determine the lowest common framework version for an assembly as a whole (software being written by the compiler framework I'm writing, that is)?

Insight welcome.

PS: To those wondering why I don't use Reflection, attempt using
  Type.GetType(string) on any of these:

```<code>Microsoft.Win32.Registry, mscorlib, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Microsoft.Win32.Registry, mscorlib, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Microsoft.Win32.Registry, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
</code>```

It won't fail, but you also won't get what you would expect, even trying to load the 2.0
  mscorlib by filename yields the 4.0 assembly.

Edit: I should add this analysis purely focuses on the publicly exposed elements.  The rationale for this is you shouldn't ever focus on the dependencies of the internal structure of the BCL since it can change without warning.  If you're writing a code generator and the expressions you synthesize rely on these types, your system is likely to be fragile as glass if something changes in the framework, like a patch that updates the 2.0 version's internal structure.  Due to how .NET binds its members in Common Intermediate Language, this is a very real likelihood.

答:
From what I can tell, this analysis can be used to discern if the target framework has the functionality put forth on a given assembly.  If, for example, you specify version 2 of the framework, but rely on version 4 functionality, a detailed list of what's not valid could be created.  LINQ is a prime example of this, since it was introduced in version 3.5 of the framework.  I'll likely be including processor architecture/platform to the assembly identities so I can compare different platform versions of the .NET BCL to the primary BCL.  The individual changes are listed online but getting a comprehensive list seems difficult.

This can be done similarly to analyze the active intermediate assembly versus the previous build to potentially detect breaking changes (such as adding methods to an interface.)

Could also be used to help automate change logs, and generate an iterable view of a library for analysis tools to build off of.

I mention LINQ as a framework element, because on the compiler level, it could be supported as early as v2.0 of the framework, so long as the method patterns are present on the types involved.  Even things like async are available as early as that so long as the compiler has a means to express this functionality, if the user provided a Task<T> that met the pattern requirements, you should be okay.


答:
First, metadata is a blurry concept.

That said, many cases of metadata in files already exist:

version numbers of libraries

date and time of images, or at least sequence index

file type, which triggers what application should open the file

name of your home directory, which must be your session username

Nevertheless, that short list is not an argument in favor of the practice.

Alternatives are:

handle metadata in the FS level, like Apple old HFS for instance

put metadata in the file itself, like Exif for images or ID3 for sounds

put metadata in another file or in a database, like most media managers.

Title: Is it bad practice to store metadata information in file names? Better solutions?

Body:
I have noticed where I work people are keen on storing information in file names, and parsing the file names.

To me this doesn't seem to be especially good practice. I already see the occasional issues with scripts globbing for a file, and getting the wrong one because another file matches first.We are also discussing how to get around problems with separators for the fields.

Is it considered bad practice or not?

What are other accepted solutions for retrieving files from a file system based on some type of metadata?


答:
A more accurate phrasing would be:-
"the compiler tells the loader to reserve space for the variables"

In a C-ish environment there will be three types of space for variables:-

a fixed block for static variables

A large block for "automatic" variables usually referred to as the "stack". Functions grab a chunk on entry and release it on return.

A large block called the "heap" which is where program managed memory is allocated from (using malloc() or similar memory management API.

On a modern OS heap memory will not actually be reserved but allocated as required.

Title: Why do books say, "the compiler allocates space for variables in memory"?

Body:
Why do books say,  "the compiler allocates space  for variables in memory". Isn't it the executable which does that? I mean, for example, if I write the following program,

```<code>#include <iostream>
using namespace std;

int main()
{
   int foo;
   return 0;
}
</code>```

and compile it, and get an executable (let it be program.exe), now, if I run program.exe, this executable file will itself command to allocate some space for the variable foo. Won't  it ? Please explain why books keep on saying, "the compiler will do this...do that".


问:
Chain-of-Command/Responsibility pattern for my simple API. A good idea?
I need to write a simple API for a project I'm working on. This API will be used internally to perform some server side actions that were triggered by AJAX calls.

To make things easier for me, I thought of using the Chain-of-Command/Responsibility pattern.

Here are more details about what I want to do:

I am creating a "dashboard" where admins of my app will be able to update information (meta data) about items stored in a database.

To make things easy and simple for the admins, I chose to use AJAX. So, if an admin wants to delete an item, (s)he clicks on the "delete button". A POST request is then sent to edit.php page with all the information needed to perform the deletion (action : delete, element : link, id : xx ...). Where action, element and of course id can change.

This is why I opted for a mini-API that will, depending on the action and the element data, call a different function from a different class.

Now, to implement the API, I decided to use Chain-of-Responsibility design pattern. Why? Because I can easily add, delete or update classes without having to modify the API itself.

Is the Chain of Responsibility design pattern good fit for my case?

答:
First of all, note that the question is misspelled, for the chain of command pattern is not related to the public API, but to its internal, server-side implementation.

That said, the chain of command pattern suits well your needs. As the API is extended with new actions and/or elements, so new handlers can be added to the chain to implement new behaviour, without modifying the existing ones.


问:
HasMany RESTfull Implementation
So I've been reading a lot on RESTfull design - specifically dealing with resources.

Taking the canonical example of Users, Posts, and Comments, with relationships as:

Users ---(hasMany)---> Post ---(hasMany)---> Comment

One may initially think to expose something like:

```<code>GET /users               GET /posts               GET /comments
POST /users              POST /posts              POST /comments
GET /users/id            GET /posts/id            GET /comments/id
PUT /users/id            PUT /posts/id            PUT /comments/id
DELETE /users/id         DELETE /posts/id         DELETE /comments/id
</code>```

But then, say I want all Comments of a certain Post made by a particular User. I'd need to do something like:

```<code>GET /users/id
   > someUser
   > var postIds = someUser.posts()
GET /posts?id=<postIds[0]>&id=<postIds[1]>&...
   > somePosts
   >  **application user inspects posts to see which one they care about**
   > var postOfInterest = somePosts[x];
   > var postId = postOfInterest.id;
GET /comments?id=postId
   > someComments (finally)
</code>```

Suppose though I only care about a Post or Comment in the context of it's owner. Suppose a different resource structuring which may (or may not?) be more natural:

```<code>GET /users
POST /users
GET /users/id
PUT /users/id
DELETE /users/id

GET /users/id/posts
POST /users/id/posts
GET /users/id/posts/id
PUT /users/id/posts/id
DELETE /users/id/posts/id

GET /users/id/posts/id/comments
POST /users/id/posts/id/comments
GET /users/id/posts/id/comments/id
GET /users/id/posts/id/comments/id
GET /users/id/posts/id/comments/id
</code>```

Which to me, is probably a better representation of what the resources are. Then all I need is:

```<code>GET /users/id/posts
   > somePosts
   > **application user inspects posts to see which one they care about**
   > var postOfInterest = somePosts[x];
   > var postId = postOfInterest.id;
GET /users/id/posts/postId/comments
   > someComments
</code>```

This just seems more like navigating a file system than the previous method - but I don't know if its RESTfull at all (perhaps this is what REST was trying to get rid of) because in order to access a Comments resource, I need to know which User and which Post it belongs to. But the former requires 3 requests, while the latter requires just 2.

Thoughts?

答:
Colin, I guess the point you're discussing is about nested REST and that is completely possible with the interface.

Users ---(hasMany)---> Post ---(hasMany)---> Comment

This relationship do exist, but how you defined them in next two cleared the purpose of nested representations. I designed this code under REST nested designs in this page as a demo reference, you can check them too.

Title: HasMany RESTfull Implementation


问:
Design pattern for locking asynchronous operations in Objective-C
I'm writing my first Objective-C Class. It's responsible for interaction with an HTTP SSO authentication service.

The process requires multiple HTTP transactions in order to complete. The Class acts as a NSURLConnectionDelegate for its own NSURLConnection object. The NSURLConnectionDelegate object operates asynchronously.

I need to disallow an authentication attempt when another is in progress. I have an idea of how to do that myself, but want to know of design patterns for this situation.

My existing idea is to check an instance variable to see if an authentication is underway and if so simply not start another. However, I'm unsure how to communicate this back to the calling Class. My method presently returns void. Should I use an NSError and return that if another authentication attempt is underway?

答: I decided to use a BOOL as a semaphore on my authentication method. If authentication is already underway, or complete then I return an NSError object.</p>


答:
The idea of the chain-of-command pattern is to build a chain of handlers and pass a command along this chain until one of the handlers handles the command. This behavior is typically found in event processing, where, say, a click event from a UI button bubbles up the hierarchy of UI elements till it reaches an element that has a respective handler attached. This handler can then decided whether it handles the command -- effectively ending the event processing -- or not -- in which case the event is propagated further along the chain.

Let's now assume we use that pattern for you web API. What you describe sounds like a classical CRUD(L) interface to me, where your actions are (a subset of) create, read, update, and delete. You say you have delete requests and I'm assume that you want some kind of update requests, too. Let's assume further that you wrote respective handlers hupd and hdel for these kinds requests. Following the chain-of-command pattern, you then build the chain [hupd,hdel] to handle requests to your API. What happens is that every update request passed into the chain gets immediately handled by hupd, while every delete request is rejected by hupd and passed along to hdel, which handles it. This behavior shows a fixed mapping between actions and handlers that actually makes the chain unnecessary. (In fact, the chain even lowers your system's performance, because of the check and the passing along of every delete request). Why does this happen? Because there are no two handlers responsible for different subsets of requests with the same action type. What you really want to have here is a direct mapping ["update" => hupd, "delete" => hdel] and a dispatcher that takes respective requests and passes them directly to the respective handler. Such a design can still be extendible with regard to new actions, if there is a dynamic registry holding the mapping.

Now you could say, that you want to have different handlers for, say, the deletion of elements of type A and B. What gives you handlers for subsets of requests with the same action type. But once again, you have a direct and fixed mapping between the handlers and the element type, i.e., you can repeatedly dispatch requests based on the target element type. This gives you a two-level dispatch, where with a chain-of-command you would pass the request through number-of-actions times number-of-element-types handlers, in the worst case.

Conclusion: I would not recommend the chain-of-command pattern to implement this kind of API. For the pattern to have value, you need a scenario where you want to dynamically add and remove handlers and where the condition of when a handler actually handles an event is not expressible by a simple mapping from constants.

Title: Chain-of-Command/Responsibility pattern for my simple API. A good idea?

Body:
I need to write a simple API for a project I'm working on. This API will be used internally to perform some server side actions that were triggered by AJAX calls.

To make things easier for me, I thought of using the Chain-of-Command/Responsibility pattern.

Here are more details about what I want to do:

I am creating a "dashboard" where admins of my app will be able to update information (meta data) about items stored in a database.

To make things easy and simple for the admins, I chose to use AJAX. So, if an admin wants to delete an item, (s)he clicks on the "delete button". A POST request is then sent to edit.php page with all the information needed to perform the deletion (action : delete, element : link, id : xx ...). Where action, element and of course id can change.

This is why I opted for a mini-API that will, depending on the action and the element data, call a different function from a different class.

Now, to implement the API, I decided to use Chain-of-Responsibility design pattern. Why? Because I can easily add, delete or update classes without having to modify the API itself.

Is the Chain of Responsibility design pattern good fit for my case?


问:
What's is the point of PImpl pattern while we can use interface for the same purpose in C++?
I see a lot of source code that uses PImpl idiom in C++. I assume Its purpose is to hide the private data/type/implementation, so it can remove dependence, and then reduce compile time and header include issue.

But interface/pure-abstract classes in C++ also have this capability, they can also be used to hide data/type/implementation. And to let the caller just see the interface when creating an object, we can declare a factory method in the interface's header.

The comparison is:

Cost:

The interface way cost is lower, because you don't even need to repeat the public wrapper function implementation void Bar::doWork() { return m_impl->doWork(); }, you just need to define the signature in the interface.

Well understood:

The interface technology is better understood by every C++ developer.

Performance:

Interface way performance is not worse than PImpl idiom, both requires an extra memory access. I assume the performance is same.

Following is the pseudocode to illustrate my question:

```<code>// Forward declaration can help you avoid include BarImpl header, and those included in BarImpl header.
class BarImpl;
class Bar
{
public:
    // public functions
    void doWork();
private:
    // You don't need to compile Bar.cpp after changing the implementation in BarImpl.cpp
    BarImpl* m_impl;
};
</code>```

The same purpose can be implemented using interface:

```<code>// Bar.h
class IBar
{
public:
    virtual ~IBar(){}
    // public functions
    virtual void doWork() = 0;
};

// to only expose the interface instead of class name to caller
IBar* createObject();
</code>```

So what's the point of PImpl?

答:
This page answers your question. Many people agree with your assertion. Using Pimpl has the following advantages over private fields/members.

Changing private member variables of a class does not require recompiling classes that depend on it, thus make times are faster, and
  the FragileBinaryInterfaceProblem is reduced.

The header file does not need to #include classes that are used 'by value' in private member variables, thus compile times are faster.

The Pimpl idiom is a compile-time optimisation, a dependency breaking technique. It cuts down large header files. It reduces your header to only the public interface. Header length is important in C++ when you think about how it works. #include effectively concatenates the header file to the source file - so bear in mind after pre-processed C++ units can be very large. Using Pimpl can improve compile times.

There are other better dependency breaking techniques - that involve improving your design. What do the private methods represent? What is the single responsibility? Should they be another class?


答:
First, PImpl is usually used for non-polymorphic classes. And when a polymorphic class has PImpl, it usually remains polymorphic, that is still implements interfaces and overrides virtual methods from base class and so on. So simpler implementation of PImpl is not interface, it is a simple class directly containing the members!

There are three reasons to use PImpl:

Making the binary interface (ABI) independent of the private members. It is possible to update a shared library without recompiling the dependent code, but only as long as the binary interface remains the same. Now almost any change in header, except for adding a non-member function and adding a non-virtual member function, changes the ABI. The PImpl idiom moves definition of the private members into the source and thus decouples the ABI from their definition. See Fragile Binary Interface Problem

When a header changes, all sources including it have to be recompiled. And C++ compilation is rather slow. So by moving definitions of the private members into the source, the PImpl idiom reduces the compilation time, as fewer dependencies need to be pulled in the header, and reduces the compilation time after modifications even more as the dependents don't need to be recompiled (ok, this applies to interface+factory function with hidden concrete class too).

For many classes in C++ exception safety is an important property. Often you need to compose several classes in one so that if during operation on more than one member throws, none of the members is modified or you have operation that will leave the member in inconsistent state if it throws and you need the containing object to remain consistent. In such case you implement the operation by creating new instance of the PImpl and swap them when the operation succeeds.

Actually interface can also be used for implementation hiding only, but has following disadvantages:

Adding non-virtual method does not break ABI, but adding a virtual one does. Interfaces therefore don't allow adding methods at all, PImpl does.

Inteface can only be used via pointer/reference, so the user has to take care of proper resource management. On the other hand classes using PImpl are still value types and handle the resources internally.

Hidden implementation can't be inherited, class with PImpl can.

And of course interface won't help with exception safety. You need the indirection inside the class for that.

Title: What's is the point of PImpl pattern while we can use interface for the same purpose in C++?

Body:
I see a lot of source code that uses PImpl idiom in C++. I assume Its purpose is to hide the private data/type/implementation, so it can remove dependence, and then reduce compile time and header include issue.

But interface/pure-abstract classes in C++ also have this capability, they can also be used to hide data/type/implementation. And to let the caller just see the interface when creating an object, we can declare a factory method in the interface's header.

The comparison is:

Cost:

The interface way cost is lower, because you don't even need to repeat the public wrapper function implementation void Bar::doWork() { return m_impl->doWork(); }, you just need to define the signature in the interface.

Well understood:

The interface technology is better understood by every C++ developer.

Performance:

Interface way performance is not worse than PImpl idiom, both requires an extra memory access. I assume the performance is same.

Following is the pseudocode to illustrate my question:

```<code>// Forward declaration can help you avoid include BarImpl header, and those included in BarImpl header.
class BarImpl;
class Bar
{
public:
    // public functions
    void doWork();
private:
    // You don't need to compile Bar.cpp after changing the implementation in BarImpl.cpp
    BarImpl* m_impl;
};
</code>```

The same purpose can be implemented using interface:

```<code>// Bar.h
class IBar
{
public:
    virtual ~IBar(){}
    // public functions
    virtual void doWork() = 0;
};

// to only expose the interface instead of class name to caller
IBar* createObject();
</code>```

So what's the point of PImpl?


问:
Making Code Changes While PHP Script Is Running
I have a PHP program running right now that is processing database rows of over 6 million. Considering the speed at which number of records have been processed so far, it looks like the whole process might take few days to complete (due to hardware limitations).

I was thinking if I could make changes in the program to remove unnecessary logging and other things that may be consuming time. Can I do this with the current program still running so that further processing would speed up, or will this cause the PHP script to break ?

答:
You cannot edit your program because it's compiled in memory. Any modification to the source code will be active after you reload the program.

This means that you have to kill the process and reload the script.


问:
How to refer to <% in asp.net
I've realized that I refer to <%@ as 'angle bracket percent at' and <%$ as 'angle bracket percent dollar',

But this is very clumsy. I think <%$ should be referred to as some sort of bind, I'm not 100% sure what <%@ does, and Google doesn't like that as a search term.

How do programmers normal label these terms?

答:
<%@ is called a directive block.  This is documented here: Directives for ASP.NET Web Pages.

<%$ is called an ASP.NET Expression. This is documented here: ASP.NET Expressions Overview

The official generic term for these is Code Render Blocks.  They are colloquially know as Bee Stings or Code Nuggets.

Title: How to refer to <% in asp.net


答:
In addition to what was said before, the intersection table should have both FK columns defined as mandatory (not null) unless you introduce a sequence number column to represent the PK (which is not required by the business here).

The M-M concept is simple. In your case how else could we represent that committee C1 has members M1, M2, ..., Mn? We can't create a fixed number of columns (against normalization) and we don't even know how many will there be. So we need to represent each member's relationship to a committee in a separate row. The same is true if you look at it from the member's side. We need to store information like M1, C1, C2, C3,...,Cn. The same argument holds. As a result you came up with the intersection table.

Many resources exist that show M-M - Here M-M Pattern


答:
This is a refinement of @user2670177 answer:

If the function signatures of both are nearly the same it might be easier to use inheritance instead of composition.

Given you have Oranges and Appels you want to process

```<code>class Orange {
    public void setColor(Color color){}
    public void setPrice(int euroCents){}
    public void setCount(int numberOfItems){}
}

class Apple {
    public void setColor(Color color){}
    public void setPrice(int euroCents){}
    public void setCount(int numberOfItems){}
}
</code>```

You can define a common interface for both

```<code>interface MyFruitInterface{
    void setColor(Color color);
    void setPrice(int euroCents);
    void setCount(int numberOfItems);
}
</code>```

and attach the interface to the inherited class

```<code>class MyOrangeImpl extends Orange implements MyFruitInterface {
}

class MyAppleImpl extends Apple implements MyFruitInterface {
}
</code>```

Now your common code MQObject can handle both:

```<code>class MQObject {
    private MyFruitInterface fruit;
    MQObject(MyFruitInterface fruit) {
        this.fruit = fruit;
    }

    void setPriceColorCount(int euroCents, Color color, int numberOfItems) {
        fruit.setPrice(euroCents);
        fruit.setColor(color);
        fruit.setCount(numberOfItems);
    }
}

void testMQ() {
    MQObject applMQObject = new MQObject(new MyAppleImpl());
    MQObject orangeMQObject = new MQObject(new MyOrangeImpl());
}
</code>```

Title: Refactoring two classes from third-party library that could have extended a base class

Body:
I have two Classes, with very similar behaviors, both from a third party library.
Both needs to be populated with some value object and sent to specific queues in order for logging. Please note both of them does not have a common parent.

I am scratching my head to find out ways to refactor this.
Here is the sceanrio.

Class 1 : Apple
Class 2 : Orange

Unfortunately, Apple and Orange are not child classes of Fruit
And I can not change them to extend a base class.
Constructors of Apple and Orange have different signatures.

Current code:

```<code>if(isApple){
    Apple apple = new Apple(....);
    apple.setColor(Color.RED);
    apple.setPrice(10);
    apple.setCount(1000);

    AppleMQObject applMQObject = new AppleMQObject(apple);
    Producer appleProducer = Factory.create("apple-producer");
    appleProducer.send(applMQObject);
}else{
    Orange orange = new Orange(...);
    orange.setColor(Color.ORANGE);
    orange.setPrice(30);
    orange.setCount(100);
    OrangeMQObject oMQObject = new oMQObject(orange);
    Producer orangeProducer = Factory.create("orange-producer");
    orangeProducer.send(orangeMQObject);
}
</code>```

I can move the MQ code out to a common method. But how to handle the apple/orange situation.

Body:
This is a refinement of @user2670177 answer:

If the function signatures of both are nearly the same it might be easier to use inheritance instead of composition.

Given you have Oranges and Appels you want to process

class Orange {
    public void setColor(Color color){}
    public void setPrice(int euroCents){}
    public void setCount(int numberOfItems){}
}

class Apple {
    public void setColor(Color color){}
    public void setPrice(int euroCents){}
    public void setCount(int numberOfItems){}
}

You can define a common interface for both

interface MyFruitInterface{
    void setColor(Color color);
    void setPrice(int euroCents);
    void setCount(int numberOfItems);
}

and attach the interface to the inherited class

class MyOrangeImpl extends Orange implements MyFruitInterface {
}

class MyAppleImpl extends Apple implements MyFruitInterface {
}

Now your common code MQObject can handle both:

class MQObject {
    private MyFruitInterface fruit;
    MQObject(MyFruitInterface fruit) {
        this.fruit = fruit;
    }

    void setPriceColorCount(int euroCents, Color color, int numberOfItems) {
        fruit.setPrice(euroCents);
        fruit.setColor(color);
        fruit.setCount(numberOfItems);
    }
}

void testMQ() {
    MQObject applMQObject = new MQObject(new MyAppleImpl());
    MQObject orangeMQObject = new MQObject(new MyOrangeImpl());
}


问:
Properly structure an existing project into the MVC architecture
I'm taking a legacy classic asp project up to more modern technology (I've been working with ASP.NET MVC lately so using this concept is stuck in my mind), but I'm trying to think of how to structure the project.

The idea is that the company provides a service to clients, but the service is housed on the company's website (instead of the client's) and has some branding/specifics to the client. Let's say there are 4 or 5 pages/steps for the service, but a few of those pages/steps can be customized for each client. So, what I'd prefer is:

*/step1

*/step2

*/step3

*/step4

*/step5

Where * is the client name but the steps are reusable. This doesn't seem to lend itself to the standard MVC structure, or I can't seem to see the forest for the trees. I wouldn't want a controller for each client and repeat the steps for n clients. I'd rather have 5 steps where step2 or step3 could be expanded upon for client X, expanded upon more for client Y and left alone for client Z.

If the company has 100 clients that want the standard 5 steps (no customization), you wouldn't want 100 controllers serving up 5 steps (500 .cshtml pages in the project)...right? How would one design this properly?

答:
The way I would tackle this problem is by using a ControllerFactory to create the appropriate controller based on both the step and client and hand-off the further processing to that controller.

The controller hierarchy would look like this:

```<code>BaseController
|
+-- Step1Controller
|
+-- Step2Controller
|   |
|   +-- Step2ClientXController
|   +-- Step2ClientYController
|
+-- Step3Controller
|   |
|   +-- Step3ClientXController
|   +-- Step3ClientZController
|
+-- Step4Controller
|
+-- Step5Controller
</code>```

Body:
The way I would tackle this problem is by using a ControllerFactory to create the appropriate controller based on both the step and client and hand-off the further processing to that controller.

The controller hierarchy would look like this:

BaseController
|
+-- Step1Controller
|
+-- Step2Controller
|   |
|   +-- Step2ClientXController
|   +-- Step2ClientYController
|
+-- Step3Controller
|   |
|   +-- Step3ClientXController
|   +-- Step3ClientZController
|
+-- Step4Controller
|
+-- Step5Controller


问:
How many user stories per person should be completed per sprint?
Just ran across this figure, and wondering if there's another well know source than would help confirm these numbers:

Based on data I analyzed on successfully finished sprints, I
determined that a team should average around 1 to 1-1/2 user stories
(product backlog items of any sort, really) per person per sprint.

SOURCE: Mike Cohn's Blog on "Should the Daily Standup Be Person-by-Person or Story-by-Story?"

答:
Daft question, but is not the answer driven out through a) intitial team estimation of story points (or whatever) from any sprint planning session and then b) sprint velocity and/or burndown?

We sometimes reach for the stars in the first sprint then quickly discover not all stories are what they seem (something always hidden). We then readjust our next sprint estimates for the next story pulldown from the backlog.

One or two stories max per dev is kind of where most my team's mobile app projects have landed - across a range of organisations, projects and platform devs.


问:
Making some methods mostly contain method calls, while others doing "the lowest level" work
So I thought about this, and I don't know if it's included or not in any methodology.

I think the advantages of this coding style is that, at the lowest level, the code is extremely testable, and then the integration tests should also be very easy to build.

I also think this would make the code more readable and the UML would be understood faster.

So here's my example:

```<code>class CoolObject{
var member1; //needed for instance in lifecycle events
var member2; //same comment

   //This method could be for instance an event handler
   //Notice this contains only assignments and method calls. No library calls or lower level stuff
   [public] method high_level(params...){
    var local_var1;
    var local_var2;
    local_var1 = call method lower_level1(param1,param2);
    local_var2 = call method lower_level2(param1, local_var1);
    member1 = call method lower_level3(local_var2);
   }

   //Notice this contains only library calls and lower level processing
   [private] method lower_level1(param1, param2){
    return param1 + param2 + libraryXXY123.function142(current_date);
   }

   //Notice this contains only library calls and lower level processing
   [private] method lower_level2(param1, param2){
     var return_value;
     loop over param2{
        if(condition){
           add param1 to return_value;
        }
     }
     return return_value + libraryASDF123.function3132(system_user);

   }

}
</code>```

Please note that this is not written in any specific language, as I only wanted to illustrate the concept.

So do you know some methodologies that use this, or that warn against it?
Please elaborate on the answer, as I think this would be a good idea, and would like this either confirmed, or the opposite.

答:
In layman's words:

That's good structured programming practice.

OOP builds on structured programming, meaning code inside a class is usually structured programming code.

Your sample is not a good or bad OOP idea per se, but rather a good structured programming idea.

Good OOP code usually builds on good structured programming code.

Your code seems OK to me.