问:
Multilevel Queue Scheduling (MQS) with Round Robin
I'm trying to use MQS to create a Gantt chart of 5 processes (P1-P5) as well as their waiting, response, and turnaround times (and averages of those metrics) within a CPU task schedule. Here's the basic table of arrival times and bursts:

Here's my actual work version after ticking off the finished processes.  The time quantum for each time slice is (2 queues) TQ1=4 and TQ2=3. Note that I'm doing MQS and NOT MLFQ:

It just doesn't feel like I'm doing MQS right here, I know this gets a little complex but maybe someone can point out where I'm going totally wrong.

答:
Since you have a Multilevel queue scheduling it would imply that higher priority processes will be handled first in which case P1 will be handled before you have P2 handled. But at 6 slot P3  will request processing which imply that the cpu will round robin between P1 and P3 until both are ready. Once P1 and P3 are ready the CPU will handle the remaining priority one processes according to the fashion of their request for processing.

I think that P1 will continue to execute without interference by P2.  P3 will enter and the cpu will round robin between P1 and P3 until both are ready. Next will be the turn of P2, P4 and P5 to be executed in the same manner since every queue will be execuited in a round robin fashion.

Therefore one needs to take into account priority. The higher the priority will imply that the process will keep the resources for himself until it is ready, or another process with a higher priortity comes in and starts executing ( can lead to starvation) or it needs to share it with another process of similar priority as it happens in this scenario in a round robin fashion


问:
Optimizing code generation for expressions in a compiler
I don't know if this question has a simple answer or not, but I just have to ask.

I'm reading this tutorial (I don't know if this is a well-known series, but it's name is 'Let's build a compiler!' by Jack Crenshaw). It's a nice series where you gradually learn how to construct a compiler (it is a learn-by-doing thing, really).

In the second chapter already, I felt the need to optimize some things. In the series, some concessions are made, in order to keep things simple: there is no difference between lexical scanner (although I believe it is introduced later in the series) and the code generation: they are done in one go. Also, the author heavily relies on the stack to create the code to handle expressions.
(Also, the output is assembly code, I don't know if this is normal for compilers, so I just thought I'd mention it...)

For example, parsing the expression 5 + (7 * 3 - 21 / 3) (and storing the result in eax) results roughly in the following code (I use x86 asm, as opposed to the series, so this is the assembly code my compiler gave):

```<code>    push 5   ; These lines is generated by a simple number parser
    push 7   ; This parser pushes its result to the stack
    push 3   ; (like most other parsing functions)

    pop eax  ; Code for multiplication
    pop ebx
    mul ebx
    push eax

    push 21  ; Result of parsing these numbers
    push 3

    pop ebx  ;  Division code
    pop eax
    div ebx
    push eax

    pop ebx  ; Subtraction code
    pop eax
    sub eax, ebx
    push eax

    pop eax  ; Addition code
    pop ebx
    add eax, ebx
    push eax
</code>```

As you can see, the code for handling the addition, subtraction, multiplication, etc. can stay the same each time the operation is used. This is very convenient, but of course, the assembly code generated is very slow and esoteric. When writing by hand, one would rather write something like:

```<code>    mov eax, 21
    div 3
    mov ebx, eax
    mov eax, 7
    mul 3
    sub eax, ebx
    add 5
</code>```

My question is if there is any way to optimize the compiler output. Of course there is, but is there any specific way to make my code more like the second, ie: not using the stack so intensively, but instead relying on registers to pass values.

I myself have been thinking about parsing the whole expression and representing it internally as a tree-like structure (I supposethis is the kind of thing a lexical parser does) before generating the code, but I'm not entirely sure how to proceed.
On the other hand, there is peephole optimization and the possibility to optimize the assembler code after it has been generated, but I have no idea how effective this will be. Generating better code in the first place seems logical and more feasible to me.

I know there are many techniques available to optimize my code (for example, constant folding, which would reduce the whole expression to 19. I have deliberately not used this kind of optimization to bring my point across better), I am hoping for a single technique that is well-suited for this kind of stuff.

答:
Understand that Jack Crenshaw's tutorial is about the basics of compiler design.  It is not intended to take you all the way to production quality in one swell foop.  There are other basic texts available: the various dragon books are well-known.  I personally like Wirth's text: it is almost as approachable as Crenshaw's.

For production quality code generation, you have to do a lot more.  The canonical reference here is Wulf's "Design of an Optimizing Compiler".  Surprisingly, Amazon lists several used copies available at reasonable prices.

Also note that generating optimal, or even sort-of-optimized, code for the x86 architecture is a lot like breeding elephants: it takes lots of time, lots of noise, lots of effort, lots of bellowing, and there is a real risk of getting crushed underfoot.

ContentLicense: CC BY-SA 3.0


问:
Why do git commits not contain the name of the branch they were created on?
When working with git in a team using feature branches, I often find it
difficult to understand the branch structure in history.

Example:

Let's say there was a feature branch feature/make-coffee, and
bugfixing continued on master in parallel to the feature branch.

History might look like this:

```<code>*     merge feature/make-coffee
|\
| *   small bugfix
| |
* |    fix bug #1234
| |
| *    add milk and sugar
| |
* |    improve comments
| |
* |    fix bug #9434
| |
| *    make coffe (without milk or sugar)
| |
* |    improve comments
|/
*
</code>```

Problem

At first glance, I find it difficult to tell which side is the feature
branch. I usually need to browse several comments on both sides to get
an idea of which is which. This gets more complicated if there are
multiple feature branches in parallel (particularly if they are for
closely related features), or if there was merging in both directions
between feature branch and master.

As a contrast, in Subversion, this is significantly easier because the
branch name is part of the history - so I can tell right away that a
commit was originally made on "feature/make-coffee".

Git could make this easier by including the name of the current branch
in the commit metadata when creating a commit (along with author, date
etc.). However, git does not do this.

Is there some fundamental reason why this is not done? Or is it just
that nobody wanted the feature? If it's the latter, are there other ways
of understanding the purpose of historical branches without seeing the
name?

答:
Track Branch History with --no-ff

In Git, a commit has ancestors, but a "branch" is really just the current head of some line of development. In other words, a commit is a snapshot of the working tree at some point in time, and can belong to any number of branches at once. This is part of what makes Git branching so lightweight when compared to other DVCSes.

Git commits don't carry branch information because they aren't necessary for Git history. However, merges which are not fast-forwards can certainly carry additional information about what branch was merged. You can ensure that your history contains this information by always passing the --no-ff flag to your merges. git-merge(1) says:

```<code>   --no-ff
       Create a merge commit even when the merge resolves as a
       fast-forward. This is the default behaviour when merging an
       annotated (and possibly signed) tag.
</code>```

This will generally create a merge message similar to Merge branch 'foo', so you can typically find information about "ancestor branches" with a line similar to the following:

```<code>$ git log --regexp-ignore-case --grep 'merge branch'
</code>```

Body:
Track Branch History with --no-ff

In Git, a commit has ancestors, but a "branch" is really just the current head of some line of development. In other words, a commit is a snapshot of the working tree at some point in time, and can belong to any number of branches at once. This is part of what makes Git branching so lightweight when compared to other DVCSes.

Git commits don't carry branch information because they aren't necessary for Git history. However, merges which are not fast-forwards can certainly carry additional information about what branch was merged. You can ensure that your history contains this information by always passing the --no-ff flag to your merges. git-merge(1) says:

   --no-ff
       Create a merge commit even when the merge resolves as a
       fast-forward. This is the default behaviour when merging an
       annotated (and possibly signed) tag.

This will generally create a merge message similar to Merge branch 'foo', so you can typically find information about "ancestor branches" with a line similar to the following:

$ git log --regexp-ignore-case --grep 'merge branch'


答:
"Let's build a compiler" is a great series for teaching the principles of parsing, but compiler output is not its strong point.  The way real compilers deal with this is to separate the parser from the code generator.  The parser produces an Abstract Syntax Tree (example), a tree of in-memory objects that represent the meaning of the code.  The AST is passed to a code generator, which produces output from it, but optimizations can be applied, either in between the creation of the AST and the code generation or during the code generation phase.

For example, your code generator could have one or more internal member variables called "current variable" that keeps track of the last variable(s) that the code operated on, and as long as the code continues to work on the same variables, it doesn't need to write out the pops and pushes.

One example of optimization before code generation would be if the tree contains a node for an arithmetic operation, and both operands are constant values, (3 * 5) the compiler could perform the calculation at compile time and then replace the node with a constant value node (15) instead of writing out code to perform the calculation.

Title: Optimizing code generation for expressions in a compiler

Body:
I don't know if this question has a simple answer or not, but I just have to ask.

I'm reading this tutorial (I don't know if this is a well-known series, but it's name is 'Let's build a compiler!' by Jack Crenshaw). It's a nice series where you gradually learn how to construct a compiler (it is a learn-by-doing thing, really).

In the second chapter already, I felt the need to optimize some things. In the series, some concessions are made, in order to keep things simple: there is no difference between lexical scanner (although I believe it is introduced later in the series) and the code generation: they are done in one go. Also, the author heavily relies on the stack to create the code to handle expressions.
(Also, the output is assembly code, I don't know if this is normal for compilers, so I just thought I'd mention it...)

For example, parsing the expression 5 + (7 * 3 - 21 / 3) (and storing the result in eax) results roughly in the following code (I use x86 asm, as opposed to the series, so this is the assembly code my compiler gave):

```<code>    push 5   ; These lines is generated by a simple number parser
    push 7   ; This parser pushes its result to the stack
    push 3   ; (like most other parsing functions)

    pop eax  ; Code for multiplication
    pop ebx
    mul ebx
    push eax

    push 21  ; Result of parsing these numbers
    push 3

    pop ebx  ;  Division code
    pop eax
    div ebx
    push eax

    pop ebx  ; Subtraction code
    pop eax
    sub eax, ebx
    push eax

    pop eax  ; Addition code
    pop ebx
    add eax, ebx
    push eax
</code>```

As you can see, the code for handling the addition, subtraction, multiplication, etc. can stay the same each time the operation is used. This is very convenient, but of course, the assembly code generated is very slow and esoteric. When writing by hand, one would rather write something like:

```<code>    mov eax, 21
    div 3
    mov ebx, eax
    mov eax, 7
    mul 3
    sub eax, ebx
    add 5
</code>```

My question is if there is any way to optimize the compiler output. Of course there is, but is there any specific way to make my code more like the second, ie: not using the stack so intensively, but instead relying on registers to pass values.

I myself have been thinking about parsing the whole expression and representing it internally as a tree-like structure (I supposethis is the kind of thing a lexical parser does) before generating the code, but I'm not entirely sure how to proceed.
On the other hand, there is peephole optimization and the possibility to optimize the assembler code after it has been generated, but I have no idea how effective this will be. Generating better code in the first place seems logical and more feasible to me.

I know there are many techniques available to optimize my code (for example, constant folding, which would reduce the whole expression to 19. I have deliberately not used this kind of optimization to bring my point across better), I am hoping for a single technique that is well-suited for this kind of stuff.


问:
Web App vs. Desktop App Regarding Deployment
I'm taking on an opportunity for a local business to develop a small, simple timesheet manager (they still record time by hand) and am currently in the planning phases. It will include basic functionality such as managing employee information, logging time worked on a weekly basis for payroll, and generating reports for administration.

I've developed Windows Forms applications for a while and am fairly confident my coding skills are where they need to be for this project, but I'm fairly new to both ASP.NET and the concept of developing a full desktop system as opposed to individual applications, so my questions will probably sound very elementary. I'm mainly struggling with understanding how to choose between ASP.NET and Windows Forms with regard to deployment down the road. Hopefully you guys can offer some insight.

I'm still a bit fuzzy on how database/web application hosting works. If I develop for desktop, will the database need a physical server if more than one workstation/client wants access? Could one of the workstations act as a server (there are under 20-30 employees at any given time, so data size shouldn't be an issue)? Would an ASP.NET system require purchasing a web host? Or, can the web files be hosted on a local computer/server with IIS as an intranet? Can virtualization fit somewhere in all this?

I guess it boils down to: Can I get them up and going for free, or is a server/hosting cost implied either way?

Thanks in advance!

答:
For ASP.NET web application, you can have several options:

1-Deploy on a user workstation - This is a bad solution for a serious application. You will get unpredictable performance, problems in debugging and possibly security issues, to name a few of the troubles.

2-Deploy the web server and database server both on a dedicated machine owned by the company - This is what I would go for. The hardware cost is not lost since the server can be re-used or shared by several applications. You can secure the box behind a firewall and configure it easily. You don't need to separate the database server from the web server.
Administration can be conducted by current staff. I am not sure about the cost of the database in this scenario. Some databases may be free (mySQL?). I know that SQLServer Express is free (allows 5 concurrent users). Check on this before you calculate the total solution cost. Also other software cost must be factored in such as firewall, IIS, and the OS.

3-Deploy using a third party hosting company - Very affordable and not difficult to do but not all vendors accept their data to be outside the company. Ease of access to database and server will vary based on the hosting vendor. You will need good vendor support.
The good thing here is you will not pay big for the database but you may pay a bit for storage, etc. In general the cost is very affordable.

4-Deploy on the cloud.

In your case, I would like to suggest that since you are new to web development in ASP, and if you don't have enough time, forget the web solution and build a desktop solution if all the employees are using Windows and are connected to the LAN when they use the system. You could also develop a Desktop application that uses a shared database using web services. Don't under estimate the learning curve for web development especially if interface quality is important. Building an application interface using HTML/CSS is not simple with the tools in the market today unless you are very good at this technology or have a front end developer who can help.


答:
If I develop for desktop, will the database need a physical server if more than one workstation/client wants access?

It would recommend against it as the workstation has to be online 24/7 if the other employees should be able to use the application.

Could one of the workstations act as a server (there are under 20-30 employees at any given time, so data size shouldn't be an issue)?

Technically possible, yes.

Would an ASP.NET system require purchasing a web host?

No. But I would recommend it.

Or, can the web files be hosted on a local computer/server with IIS as an intranet?

Possible. Just keep the computer running.

Can virtualization fit somewhere in all this?

imho that would overcomplicate things if they do not use virtualization today.

As you know Winforms, why don't you just use it together with ClickOnce? Easy deployment for small applications like yours.

Title: Web App vs. Desktop App Regarding Deployment

Body:
I'm taking on an opportunity for a local business to develop a small, simple timesheet manager (they still record time by hand) and am currently in the planning phases. It will include basic functionality such as managing employee information, logging time worked on a weekly basis for payroll, and generating reports for administration.

I've developed Windows Forms applications for a while and am fairly confident my coding skills are where they need to be for this project, but I'm fairly new to both ASP.NET and the concept of developing a full desktop system as opposed to individual applications, so my questions will probably sound very elementary. I'm mainly struggling with understanding how to choose between ASP.NET and Windows Forms with regard to deployment down the road. Hopefully you guys can offer some insight.

I'm still a bit fuzzy on how database/web application hosting works. If I develop for desktop, will the database need a physical server if more than one workstation/client wants access? Could one of the workstations act as a server (there are under 20-30 employees at any given time, so data size shouldn't be an issue)? Would an ASP.NET system require purchasing a web host? Or, can the web files be hosted on a local computer/server with IIS as an intranet? Can virtualization fit somewhere in all this?

I guess it boils down to: Can I get them up and going for free, or is a server/hosting cost implied either way?

Thanks in advance!


答:
The simplest answer is that names of branches are ephemeral. What if you were to, say, rename a branch (git branch -m <oldname> <newname>)?  What would happen to all the commits against that branch?  Or what if two people have branches that have the same name on different local repositories?

The only thing that has meaning in git is the checksum of the commit itself.  This is the basic unit of tracking.

The information is there, you're just not asking for it, and its not exactly there.

Git stores the checksum of head of each branch in .git/refs/heads.  For example:

```
.../.git/refs/heads$ ls test
-rw-rw-r-- 1 michealt michealt   41 Sep 30 11:50 test
.../.git/refs/heads$ cat test
87111111111111111111111111111111111111d4
```

(yes, I'm clobbering my git checksums, its not special, but they're private repositories that I'm looking at that the moment that don't need to have anything accidently leaked).

By looking at this and tracking back every commit that has this as a parent, or the parents parent or the parents parent... you can find out what branches a given commit is in.  Its just a big graph to render.

Storing where specifically the name of a branch (which can change as mentioned above) a commit is in the commit itself is extra overhead on the commit that doesn't help it.  Store the parent(s) of the commit and its good.

You can see the branches by running the git log command with the appropriate flag.

```
git log --branches --source --pretty=oneline --graph
git log --all --source --pretty=oneline --graph
```

There are many different ways to pick what you want for that - look at the git log documentation - the -all section and the few options that follow.

```
*   87111111111111111111111111111111111111d4    test Merge branch 'test1' into test
|\
| * 42111111111111111111111111111111111111e8    test1 update: add stuff
* |   dd11111111111111111111111111111111111159  test Merge branch 'test3' into test
|\ \
```

That 'test', 'test1', and 'test2' are the branches these were committed to.

Note that the git log documentation is huge and it is quite possible to get almost anything you want out of it.

Title: Why do git commits not contain the name of the branch they were created on?

Body:
When working with git in a team using feature branches, I often find it
difficult to understand the branch structure in history.

Example:

Let's say there was a feature branch feature/make-coffee, and
bugfixing continued on master in parallel to the feature branch.

History might look like this:

```<code>*     merge feature/make-coffee
|\
| *   small bugfix
| |
* |    fix bug #1234
| |
| *    add milk and sugar
| |
* |    improve comments
| |
* |    fix bug #9434
| |
| *    make coffe (without milk or sugar)
| |
* |    improve comments
|/
*
</code>```

Problem

At first glance, I find it difficult to tell which side is the feature
branch. I usually need to browse several comments on both sides to get
an idea of which is which. This gets more complicated if there are
multiple feature branches in parallel (particularly if they are for
closely related features), or if there was merging in both directions
between feature branch and master.

As a contrast, in Subversion, this is significantly easier because the
branch name is part of the history - so I can tell right away that a
commit was originally made on "feature/make-coffee".

Git could make this easier by including the name of the current branch
in the commit metadata when creating a commit (along with author, date
etc.). However, git does not do this.

Is there some fundamental reason why this is not done? Or is it just
that nobody wanted the feature? If it's the latter, are there other ways
of understanding the purpose of historical branches without seeing the
name?

Body:
The simplest answer is that names of branches are ephemeral. What if you were to, say, rename a branch (git branch -m <oldname> <newname>)?  What would happen to all the commits against that branch?  Or what if two people have branches that have the same name on different local repositories?

The only thing that has meaning in git is the checksum of the commit itself.  This is the basic unit of tracking.

The information is there, you're just not asking for it, and its not exactly there.

Git stores the checksum of head of each branch in .git/refs/heads.  For example:

.../.git/refs/heads$ ls test
-rw-rw-r-- 1 michealt michealt   41 Sep 30 11:50 test
.../.git/refs/heads$ cat test
87111111111111111111111111111111111111d4

(yes, I'm clobbering my git checksums, its not special, but they're private repositories that I'm looking at that the moment that don't need to have anything accidently leaked).

By looking at this and tracking back every commit that has this as a parent, or the parents parent or the parents parent... you can find out what branches a given commit is in.  Its just a big graph to render.

Storing where specifically the name of a branch (which can change as mentioned above) a commit is in the commit itself is extra overhead on the commit that doesn't help it.  Store the parent(s) of the commit and its good.

You can see the branches by running the git log command with the appropriate flag.

git log --branches --source --pretty=oneline --graph
git log --all --source --pretty=oneline --graph

There are many different ways to pick what you want for that - look at the git log documentation - the -all section and the few options that follow.

*   87111111111111111111111111111111111111d4    test Merge branch 'test1' into test
|\
| * 42111111111111111111111111111111111111e8    test1 update: add stuff
* |   dd11111111111111111111111111111111111159  test Merge branch 'test3' into test
|\ \

That 'test', 'test1', and 'test2' are the branches these were committed to.

Note that the git log documentation is huge and it is quite possible to get almost anything you want out of it.


答:
Probably because branch names are only meaningful within one repository.  If I'm on the make-coffee team and submit all my changes through a gatekeeper, my master branch might get pulled to the gatekeeper's make-coffee-gui branch, which he will merge with his make-coffee-backend branch, before rebasing to a make-coffee branch that gets merged into the central master branch.

Even within one repository, branch names can and do change as your workflow evolves.   master might change later to be called development, for example.

As CodeGnome alluded, git has a strong design philosophy of not baking something into the data if it isn't needed.  Users are expected to use options in git log and git diff to output the data to their liking after the fact.  I recommend trying some out until you find a format that works better for you.  git log --first-parent, for example, won't show the commits from a branch being merged in.


问:
Difficulties With TDD & Refactoring (Or - Why Is This More Painful Than It Should Be?)
I wanted to teach myself to use the TDD approach and I had a project I had been wanting to work on for a while. It wasn't a large project so I thought it would be a good candidate for TDD. However, I feel like something has gone awry. Let me give an example:

At a high level my project is an add-in for Microsoft OneNote that will allow me to track and manage Projects more easily. Now, I also wanted to keep the business logic for this as decoupled from OneNote as possible in-case I decided to build my own custom storage and back end some day.

First I started with a basic plain words acceptance test to outline what I wanted my first feature to do. It looks something like this (dumbing it down for brevity):

User clicks create project

User types in title of project

Verify that the project is created correctly

Skipping over the UI stuff and some intermediary planning I come to my first unit test:

```<code>[TestMethod]
public void CreateProject_BasicParameters_ProjectIsValid()
{
    var testController = new Controller();
    Project newProject = testController(A.Dummy<String>());
    Assert.IsNotNull(newProject);
}
</code>```

So far so good. Red, green, refactor, etc. Alright now it needs actually save stuff. Cutting out some steps here I wind up with this.

```<code>[TestMethod]
public void CreateProject_BasicParameters_ProjectMatchesExpected()
{
    var fakeDataStore = A.Fake<IDataStore>();
    var testController = new Controller(fakeDataStore);
    String expectedTitle = fixture.Create<String>("Title");
    Project newProject = testController(expectedTitle);

    Assert.AreEqual(expectedTitle, newProject.Title);
}
</code>```

I'm still feeling good at this point. I don't have a concrete data store yet, but I created the interface how I anticipated it would look.

I'm going to skip a few steps here because this post is getting long enough, but I followed similar processes and eventually I get to this test for my data store:

```<code>[TestMethod]
public void SaveNewProject_BasicParameters_RequestsNewPage()
{
    /* snip init code */
    testDataStore.SaveNewProject(A.Dummy<IProject>());
    A.CallTo(() => oneNoteInterop.SavePage()).MustHaveHappened();
}
</code>```

This was good until I tried to implement it:

```<code>public String SaveNewProject(IProject project)
{
    Page projectPage = oneNoteInterop.CreatePage(...);
}
</code>```

And THERE is the problem right where the "..." is. I realize now at THIS point that CreatePage requires a section ID. I didn't realize this back when I was thinking at the controller level because I was only concerned with testing the bits relevant to the controller. However, all the way down here I now realize I have to ask the user for a location to store the project. Now I have to add a location ID to the datastore, then add one to the project, then add one to the controller, and add it to ALL of the tests that are already written for all of those things. It has become tedious very quickly and I can't help but feel like I would have caught this quicker if I sketched out the design ahead of time rather than letting it be designed during the TDD process.

Can someone please explain to me if I've done something wrong in this process? Is there anyway this kind of refactoring can be avoided? Or is this common? If it is common are there any ways of making it more painless?

Thanks all!

答:
While TDD is (rightly) touted as a way to design and grow your software, it's still a good idea to think about the design and architecture beforehand. IMO, "sketching out the design ahead of time" is fair game. Often this will be at a higher level than the design decisions you will be led to through TDD, however.

It's also true that when things change, you will usually have to update tests. There's no way to eliminate this completely, but there are some things you can do to make your tests less brittle and minimize the pain.

As much as possible, keep implementation details out of your tests. This means only test through public methods, and where possible favor state-based over interaction-based verification. In other words, if you test the result of something rather than the steps to get there, your tests should be less fragile.

Minimize duplication in your test code, just like you would in production code. This post is a good reference. In your example, it sounds like it was painful to add the ID property to your constructor because you invoked the constructor directly in several different tests. Instead, try extracting the creation of the object to a method or initializing it once for each test in a test initialize method.


答:
...I can't help but feel like I would have caught this quicker if I
sketched out the design ahead of time rather than letting it be
designed during the TDD proces...

Maybe, maybe not

On the one hand, TDD worked just fine, giving you automated tests as you built up functionality, and immediately breaking when you had to change the interface.

On the other hand, perhaps if you had started with the high-level feature (SaveProject) instead of a lower-level feature (CreateProject), you would have noticed missing parameters sooner.

Then again, maybe you wouldn't have. It's an unrepeatable experiment.

But if you're looking for a lesson for next time: start at the top. And think about the design as much as you want first.

Title: Difficulties With TDD & Refactoring (Or - Why Is This More Painful Than It Should Be?)

Body:
I wanted to teach myself to use the TDD approach and I had a project I had been wanting to work on for a while. It wasn't a large project so I thought it would be a good candidate for TDD. However, I feel like something has gone awry. Let me give an example:

At a high level my project is an add-in for Microsoft OneNote that will allow me to track and manage Projects more easily. Now, I also wanted to keep the business logic for this as decoupled from OneNote as possible in-case I decided to build my own custom storage and back end some day.

First I started with a basic plain words acceptance test to outline what I wanted my first feature to do. It looks something like this (dumbing it down for brevity):

User clicks create project

User types in title of project

Verify that the project is created correctly

Skipping over the UI stuff and some intermediary planning I come to my first unit test:

```<code>[TestMethod]
public void CreateProject_BasicParameters_ProjectIsValid()
{
    var testController = new Controller();
    Project newProject = testController(A.Dummy<String>());
    Assert.IsNotNull(newProject);
}
</code>```

So far so good. Red, green, refactor, etc. Alright now it needs actually save stuff. Cutting out some steps here I wind up with this.

```<code>[TestMethod]
public void CreateProject_BasicParameters_ProjectMatchesExpected()
{
    var fakeDataStore = A.Fake<IDataStore>();
    var testController = new Controller(fakeDataStore);
    String expectedTitle = fixture.Create<String>("Title");
    Project newProject = testController(expectedTitle);

    Assert.AreEqual(expectedTitle, newProject.Title);
}
</code>```

I'm still feeling good at this point. I don't have a concrete data store yet, but I created the interface how I anticipated it would look.

I'm going to skip a few steps here because this post is getting long enough, but I followed similar processes and eventually I get to this test for my data store:

```<code>[TestMethod]
public void SaveNewProject_BasicParameters_RequestsNewPage()
{
    /* snip init code */
    testDataStore.SaveNewProject(A.Dummy<IProject>());
    A.CallTo(() => oneNoteInterop.SavePage()).MustHaveHappened();
}
</code>```

This was good until I tried to implement it:

```<code>public String SaveNewProject(IProject project)
{
    Page projectPage = oneNoteInterop.CreatePage(...);
}
</code>```

And THERE is the problem right where the "..." is. I realize now at THIS point that CreatePage requires a section ID. I didn't realize this back when I was thinking at the controller level because I was only concerned with testing the bits relevant to the controller. However, all the way down here I now realize I have to ask the user for a location to store the project. Now I have to add a location ID to the datastore, then add one to the project, then add one to the controller, and add it to ALL of the tests that are already written for all of those things. It has become tedious very quickly and I can't help but feel like I would have caught this quicker if I sketched out the design ahead of time rather than letting it be designed during the TDD process.

Can someone please explain to me if I've done something wrong in this process? Is there anyway this kind of refactoring can be avoided? Or is this common? If it is common are there any ways of making it more painless?

Thanks all!


问:
Multiple arguments in function call vs single array
I have a function that takes in a set of parameters, then applies to them as conditions to an SQL query. However, while I favored a single argument array containing the conditions themselves:

```<code>function searchQuery($params = array()) {
    foreach($params as $param => $value) {
        switch ($param) {
            case 'name':
                $query->where('name', $value);
                break;
            case 'phone':
                $query->join('phone');
                $query->where('phone', $value);
                break;
        }
    }
}
</code>```

My colleague preferred listing all the arguments explicitly instead:

```<code>function searchQuery($name = '', $phone = '') {
    if ($name) {
        $query->where('name', $value);
    }

    if ($phone) {
        $query->join('phone');
        $query->where('phone', $value);
    }
}
</code>```

His argument was that by listing the arguments explicitly, the behavior of the function becomes more apparent - as opposed to having to delve into the code to find out what the mysterious argument $param was.

My problem was that this gets very verbose when dealing with a lot of arguments, like 10+. Is there any preferred practice? My worst-case scenario would be seeing something like the following:

searchQuery('', '', '', '', '', '', '', '', '', '', '', '', 'search_query')

答:
IMHO your colleague is correct for the above example. Your preference might be terse, but its also less readable and therefore less maintainable. Ask the question why bother writing the function in the first place, what does your function 'bring to the table'- I have to understand what it does and how it does it, in great detail, just to use it. With his example, even though I am not a PHP programmer, I can see enough detail in the function declaration that I do not have to concern myself with its implementation. </p>

<p>As far as a larger number of arguments, that is normally considered a code smell. Typically the function is trying to do too much? If you do find a real need for a large number of arguments, it is likely they are related in some way and belong together in one or a few structures or classes (maybe even array of related items such as lines in an address).  However, passing an unstructured array does nothing to address the code smells. </p>

Body:
IMHO your colleague is correct for the above example. Your preference might be terse, but its also less readable and therefore less maintainable. Ask the question why bother writing the function in the first place, what does your function 'bring to the table'- I have to understand what it does and how it does it, in great detail, just to use it. With his example, even though I am not a PHP programmer, I can see enough detail in the function declaration that I do not have to concern myself with its implementation.

As far as a larger number of arguments, that is normally considered a code smell. Typically the function is trying to do too much? If you do find a real need for a large number of arguments, it is likely they are related in some way and belong together in one or a few structures or classes (maybe even array of related items such as lines in an address).  However, passing an unstructured array does nothing to address the code smells.


答:
Why git commits don't contain the name of the branch they were created on?

Just a design decision. If you need that information, you may add a prepare-commit-msg or commit-msg hook to enforce that on a single repository.

After the BitKeeper disaster Linus Torvalds developed git to match the Linux kernel development process. There, until a patch is accepted, it is revised, edited, polished several times (all through Mail), signed-off (=editing a commit), cherry-picked, wandering to branches of lieutenant maybe often rebased, more edits, cherry-picks and so on until they a finally merged upstream by Linus.

In such a workflow there may be no specific origin of a commit, and often a commit is just created in some temporary debugging branch in some unimportant private random repository with funny branch names, as git is distributed.

Maybe that design decision just happened coincidentally, but it exactly matches the Linux kernel development process.


答:
In your case, I would prefer your colleague's method. If you were writing models and I was using your models to develop over them. I see the signature of your colleague's method and can use it immediately.

While, I would have to go through the implementation of your searchQuery function to see what parameters are expected by your function.

I would prefer your approach only in the case when the searchQuery is limited to searching only within a single table, so there will be no joins. In that case my function would look like this:

```<code>function searchQuery($params = array()) {
    foreach($params as $param => $value) {
        $query->where($param, $value);
    }
}
</code>```

So, I immediately know that the elements of array are actually the column names of a particular table which the class having this method represents in your code.

Title: Multiple arguments in function call vs single array

Body:
I have a function that takes in a set of parameters, then applies to them as conditions to an SQL query. However, while I favored a single argument array containing the conditions themselves:

```<code>function searchQuery($params = array()) {
    foreach($params as $param => $value) {
        switch ($param) {
            case 'name':
                $query->where('name', $value);
                break;
            case 'phone':
                $query->join('phone');
                $query->where('phone', $value);
                break;
        }
    }
}
</code>```

My colleague preferred listing all the arguments explicitly instead:

```<code>function searchQuery($name = '', $phone = '') {
    if ($name) {
        $query->where('name', $value);
    }

    if ($phone) {
        $query->join('phone');
        $query->where('phone', $value);
    }
}
</code>```

His argument was that by listing the arguments explicitly, the behavior of the function becomes more apparent - as opposed to having to delve into the code to find out what the mysterious argument $param was.

My problem was that this gets very verbose when dealing with a lot of arguments, like 10+. Is there any preferred practice? My worst-case scenario would be seeing something like the following:

searchQuery('', '', '', '', '', '', '', '', '', '', '', '', 'search_query')

Body:
In your case, I would prefer your colleague's method. If you were writing models and I was using your models to develop over them. I see the signature of your colleague's method and can use it immediately.

While, I would have to go through the implementation of your searchQuery function to see what parameters are expected by your function.

I would prefer your approach only in the case when the searchQuery is limited to searching only within a single table, so there will be no joins. In that case my function would look like this:

function searchQuery($params = array()) {
    foreach($params as $param => $value) {
        $query->where($param, $value);
    }
}

So, I immediately know that the elements of array are actually the column names of a particular table which the class having this method represents in your code.


答:
My answer is more or less language agnostic.

If the only purpose of grouping arguments in a complex data structure (table, record, dictionary, object...) is to pass them as a whole to a function, better avoid it. This adds a useless layer of complexity and makes your intention obscure.

If the grouped arguments have a meaning by themselves, then that layer of complexity helps understand the whole design: name it layer of abstraction instead.

You may find that instead of a dozen individual arguments or one big array, the best design is with two or three arguments each grouping correlated data.


问:
use areFoo or isFoo?
I have never seen the use of "are" for boolean methods, but the use of "is" is very common.

When I want to use "are" is usually because I am passing multiple variables, or a list of objects.

I suppose I could rationalize my list of objects or multiple variables as one thing, such as "isSetupParametersValid", but that would still be plural.

Is the lack of use of "are" in boolean methods, simply an arbitrary convention or a side-effect of using best practices. If it's a side-effect of best-practices, which ones?

Note: for non-native English speakers "is" refers to a singular object, "are" refers to plural/multiple objects

答:
You often find has as an alternative to to is. In your case you could opt for hasValidSetupParameters accordingly, which makes perfectly sense. It is not part of the JavaBeans specification mentioned earlier, though.

I would speak against using areSetupParametersValid, for the following reason: Our main goal with naming methods should be to make code readable. I.e., in an ideal world code would read like sentences. Coming back to your example this means that your options are

```<code>object are setup parameters valid
</code>```

vs.

```<code>object has valid setup parameters
</code>```

I think you see what I'm hinting at.

Title: use areFoo or isFoo?

Body:
You often find has as an alternative to to is. In your case you could opt for hasValidSetupParameters accordingly, which makes perfectly sense. It is not part of the JavaBeans specification mentioned earlier, though.

I would speak against using areSetupParametersValid, for the following reason: Our main goal with naming methods should be to make code readable. I.e., in an ideal world code would read like sentences. Coming back to your example this means that your options are

object are setup parameters valid

vs.

object has valid setup parameters

I think you see what I'm hinting at.


问:
Is using something other than XML advisable for my configuration file?
I have a small tool I'm designing which would require a configuration file of some sort. The configuration file in my case is really more of a database, but it needs to be lightweight, and if needed the end-user should find it easily editable. However, it also will contain a lot of things in it. (depending on certain factors, could be 1Mb or more)

I've decided I'd rather use plain ol' text, rather than trying to use SQLite or some such. However, with using text, I also have to deal with the variety of formats. So far, my options are

XML

JSON

Custom format

The data in my file is quite simple consisting for the most part of key-value type things. So, a custom format wouldn't be that difficult... but I'd rather not have to worry about writing the support for it. I've never seen JSON used for configuration files. And XML would bloat the file size substantially I think. (I also just has a dislike of XML in general).

What should I do in this case?

Factors to consider:

This configuration file can be uploaded to a web service(so size matters)

Users must be able to edit it by hand if necessary(ease of editing and reading matters)

Must be able to generate and process automatically (speed doesn't matter a lot, but not excessively slow)

The "keys" and "values" are plain strings, but must be escaped because they can contain anything. (unicode and escaping has to work easily)

Multiple configuration files. Basically, each config file is tied to one "project"

答:
If you use JSON, people won't be able to comment out bits of configuration to try different things. For me, that's a deal breaker.

It also means you can't provide a nicely commented sample configuration file for users to customize.

XML is standard and if you can provide a schema, your users will thank you.


答:
Your question makes a limiting assumption. Let's take a step back here. Why not just bool ParametersValid (or Boolean parametersValid)? It's perfectly sufficient in my opinion.

All those isThis, isThat remind me of that anecdotal secretary who files everything under "T" ("the rent", "the invoices" etc.) :)

If the need for such prefixes becomes acute (it's not immediately obvious what parametersValid stands for), it may indicate the object design is simply bad.

Using prefixes is Hungarian notation of sorts and in this context, it's poor man's substitute of proper refactoring and splitting the class.

Regarding Caleb's criticism:

OP's question is about the particular isFoo style of naming boolean
  methods which is conventional in a number of languages

Maybe, but the question is not tagged with the name of any particular programming language, so I treat it as language-agnostic.

suggesting a different convention is not useful.

I'm not really suggesting a different convention, I'm rather saying that one does not need to follow any strict convention in this aspect, other than common sense and clear naming in general.

The idea that some strict convention is required is what created the OP's problem in first place.

If he adopts my point of view, his problem goes away, hence my answer is (potentially, of course - like any other answer) useful.

I opt for simplicity. See BackgroundWorker class in .NET. It has a CancellationPending property - not IsCancellationPending, not WasCancelledor HasBeenCancelled etc. Just keep it simple!

Furthermore, the convention you suggest is ambiguous by your own admission ("...it's not immediately obvious...")

I wrote it conditionally, you took it out of context. If it's not immediately obvious ... implies the class is too big, which is a problem in its own right.

Finally, the is in isFoo should be read as a verb; this use of prefixes is distinct from any Hungarian notation and in any case it's not necessarily indicative of poor design.

Verb or not verb, it's only reflecting the fact that the return type is boolean, which is redundant.

That's why I said it's Hungarian notation of sorts.

Title: use areFoo or isFoo?

Body:
I have never seen the use of "are" for boolean methods, but the use of "is" is very common.

When I want to use "are" is usually because I am passing multiple variables, or a list of objects.

I suppose I could rationalize my list of objects or multiple variables as one thing, such as "isSetupParametersValid", but that would still be plural.

Is the lack of use of "are" in boolean methods, simply an arbitrary convention or a side-effect of using best practices. If it's a side-effect of best-practices, which ones?

Note: for non-native English speakers "is" refers to a singular object, "are" refers to plural/multiple objects


问:
What factors should be considered before deciding to build a message bus with SOAP services?
It would seem to me that the cost of having a team of developers build and maintain all the components necessary to provide routing, workflow orchestration, durability, security and the other features provided by a commercial ESB would be equivalent to, or even more than, licensing a commercial ESB.  Other than up front licensing costs and perhaps architectural preference, what are important factors to consider when designing an integration architecture around building a message bus using SOAP services over licensing message bus software from a commercial vendor and integrating your business components with it?</p>

答:
It becomes an issue of flexibility - an ESB is all well and good, but ties you to the infrastructure. A SOA based approach (with web services as an example) gives you more flexibility as the components are more independent and can be redeployed or reused.

One issue is with the time taken to develop the solution, but in my experience you end up writing roughly the same amount of code with both systems (after you've developed 1 service, the others tend to be easily repeatable).


问:
Which is better for small bug fixes and small features - naming branches by ticket number or naming them by feature description?
I am in the middle of a disagreement (cordial, of course) with my lead about proper branch naming.  This applies to bug-fix and small feature branches, not long-running feature branches.  For long-running feature branches, we agree that human-readable names are better.  Here are the two points of view:

Mine:

Naming branches according to their team and ticket number is better.  It makes it easier to find them in our ticketing system, and shorter to type.  It also makes it easier to look up relevant branches in GIT when looking for historical information about a ticket.

Example:

```<code>team-name/12345
team-name/53719
</code>```

His:

Naming branches according to their feature/functionality.  It makes it easier to autocomplete, and is easier to remember than individual numbers.

Example:

```<code>team-name/fix-that-sql-bug
team-name/expand-http-parser
</code>```

One compromise I offered is this:

```<code>team-name/12345-fix-that-sql-bug
</code>```

But he does not like this, as it messes with GIT autocomplete.

If this is primarily opinion-based, please feel free to give me guidance on how this can be a better fit for SO - but I think that the reasons I gave can be amended/added to to give an empirical answer.

答:
Naming something solely to take advantage of autocomplete is stupid.

I agree that a link to the bug tracker is important (more important than a good name as it defines exactly the problem being solved by the branch that a couple of words does not) but at the same time, its a usability failure to expect people to know the difference between bug #7312 and #7213. Also its a failure to expect people to get the numbers perfectly right every time - one day someone will commit to the wrong branch because they misread/mistyped 7312 for 7213. (someone on my team did that today!)

So do both - number the branch and add a very short text description just to act as a check. I would put the number first - autocomplete be damned - as you still have to know the text of the branch anyway (eg "bug-fix-for-server" or "fix-bug-for-server" - you still need to know if it starts with f or b!)


问:
In DOM, why is childNodes defined in the Node interface if only some node types can have childNodes?
In DOM, why is childNodes defined in the Node interface if only some node types such as Element, Document and DocumentFragement,  can have childNodes?

Is this considered a good design? In what cases this is admissible? I mean, isn't this like defining a radius on an interface Shape even though we know that not every Shape has a radius?

答: Who says only Elements can have child nodes?  There are a bunch of node types, and several of them can have children.  Obvious examples include Document and DocumentFragment, neither of which are Elements, but both of which have child nodes.


答:
The trouble with 'are' as a prefix is what does it apply to? 'is X in state Y' is perfectly clear to all, but 'are Xs in state Y' is not so clear - does it mean are all X objects in that state, or only some of them? What if only some of them are not in the correct state or all of them - do you need a response that says "yes/no/partially"?

In cases where you think the English grammar suggests using are as a prefix - eg "are setup parameters valid", you can easily rephrase the question to be 'is the setup configuration valid', making a query on several items into a yes/no response to a single collection.

Its pretty trivial though, and the considered standard is to use 'is', so I'd say just keep using is and not worry about it all.

Title: use areFoo or isFoo?


答:
Is the lack of use of "are" in boolean methods, simply an arbitrary
  convention or a side-effect of using best practices.

The answer depends in part on the language and framework that you're using.

For example, in Objective-C you should always use foo or isFoo and never areFoo because the first two are compatible with Key-Value Coding while the last is not.

In object oriented contexts, methods like isFoo are common while methods like areFoo are not because the thing to which the test applies is usually the object receiving the message. Since you can usually call a method on only one object at a time, the plural verb are doesn't make sense.

In your question, you seem to want to ask the object whether some set of values that you're passing in are valid instead of asking about the object itself. It might be more conventional, and therefore easier for others to understand, if you turn that question into a question about the receiver. Instead of myObject.areParemetersValid(...), consider myObject.isAbleToUseParameters(...) or more simply myObject.canUseParameters(...).

To summarize, the convention isn't arbitrary -- it results from the fact that most OO languages let you call a method on only one object at a time.

Title: use areFoo or isFoo?


问:
Design Issue: Service layer/ trying to maintain RESTful architecture
I'm trying to design a web-application - and after doing a lot of reading on REST + design patterns, I'm at a loss on how to handle my requirements. I think I may be getting caught-up in all the design-patterns, but at the same time want to produce a well-architect-ed design.

I have 2 major business-objects, Customer and Order, with a Has Many relationship. Currently, I have no service layer, and the REST API is in the BL:

```<code>GET Customers                         GET Orders
GET Customers/id                      GET Orders/id
POST Customers                        POST Orders
PUT Customers/id                      PUT Orders/id
DELETE Customers/id                   DELETE Orders/id
</code>```

But things become hard to design when I have to architect for legacy means of user-data input, and well as for the future:

Now: Users upload an Excel .xlsx file containing Customer, Order information, which I parse, extract, create Customer/Order business-objects for, and perform validations. In order to have a pleasant User-experience, I don't save these objects right away, I return them to the User (along with any errors from the verifications) so they may make any needed changes before finally submitting them. (this 2-step submission just adverts the requirement of correcting sources of any validation errors directly in the Excel file).

Future: Customer/Order data will be maintained, and uploaded, through a web service/platform.

I don't know how to handle these requirements gracefully, and intelligently. Is this a case where I need to expose a Service Layer that publishes an interface for the soon-to-be-legacy Excel-upload, as well as an interface for the web service?

Any design help would be appreciated, as I'm rather new to this type of development and rather not make a major architectural mistake that will come back to bite me later..

Thanks in advance.

edited as comments suggest

答:
I think the simplest path would be to create a RESTful interface around your business objects and then code a small service with the purpose of taking an spreadsheet, parsing it, and making the appropriate calls against your RESTful service.

No matter which route you take you will have to create the RESTful portion as well as the spreadsheet handling portion (or maybe that's already written). It only seems logical to code the spreadsheet portion against your final API. This will also give you an early peak into using your API and possibly point out some issues or shortcomings that were overlooked in the planning stages.


问:
How to gracefully handle unsupported browsers?
Recently I have started experimenting with some of the newer W3C specifications such as WebGL and the Web Audio API that are not yet widely supported in browsers. As I want my page to look professional, I need a way to treat the unsupported browsers gracefully.

Now I was wondering:

Is there a standard or a guideline that details what a person should see when their browser does not support a certain page?

Are there any pitfalls I should look out for when implementing a not-supported-message?

And considering the extremely fast pace browsers release new, updated versions, how can I ensure that my script still works in future browser versions that actually do have the previously unsupported feature without blocking them?

答:
1st Question: Is there a standard or a guideline that details what a person should see when their browser does not support a certain page?

I would advise giving a proper message to the user, and give him his options (Like downloading a supported browser)

2nd question: Are there any pitfalls I should look out for when implementing a not-supported-message?

3rd question: And considering the extremely fast pace browsers release new, updated versions, how can I ensure that my script still works in future browser versions that actually do have the previously unsupported feature without blocking them?

If anything, do not detect the browsers, detect the features. If you need WebGL, than create a script that will actively look for the WebGL APIs, and run if they are present, and will not if they are not present.

You cannot really protect yourself for the future browser, if they break the API, they break it, and there is nothing you can do about that. However, if a new browser version brings official W3C WebGL api support to it's users, you should be able to run on it provided that your detection method look for the feature, and not the browser's version.


问:
Is POST for an element generally not exposed or invalid in REST APIs?
I was browsing around wikipedia on REST, reading specifically the section on REST APIs

Reading the different ways to treat elements from collections I read that POST is not generally used.

How does that work in practice? When successful REST APIs are developed, when it comes to elements, does POST just not exist or return an error?

Is there a reasoning behind that I haven't grasped?

答:
Philosophically, it is a hard question... There are schools of thoughts about REST, and nobody is right or wrong.

The way I develop my rest APIs is simple:

GET - Read an element

PUT - Update an element

POST - create an element

DELETE - Delete an element

The Wikipedia entry say that PUT can be used for create or replace. Sure it can be done that way, but I find it clearer (and it is subjective) so separate the 2 actions.

It all comes down to a matter of taste.


问:
Can I create a desktop Python GUI application and run it as a web app?
I'm working on a project where multiple (several hundred perhaps) users will need to run an application remotely.  We thought that running a web app would be the best course of action to go.  (Note: when I say web app I mean a program where a user can type in a URL that will then allow the user to run the application we're working on remotely without any installations or limited installations to the browser they're using)

My problem is not knowing where to start in creating a web app. The way that I see it (and correct me if I'm wrong), there are two types of web apps out there.    A Rich Internet Application which:

has many of the characteristics of desktop application software, typically delivered either by way of a site-specific browser, via a browser plug-in, independent sandboxes, extensive use of Javascript, or virtual machines.

wiki

or a 'regular' web app similar to gmail.  I'm very familiar with Python and desktop GUI development using wxPython.  Is it possible to write a program in Python, and then run it as a webapp?

If so, How?

答:
If you are willing to develop web applications as if you were developing desktop applications, I would recommend:

for the Java world: Vaadin

for the Python world: muntjac (which is Vaadin actually, but converted to Python)

I have a shell script which installs muntjac and creates a skeleton for a simple web application in one go. Simply follow these steps:

create a separate folder

$ mkdir hello

dowload install_muntjac.sh and run it inside the folder you've just created

$ cd hello

$ /path/to/shell/script/install_muntjac.sh

note: when you run the shell script, it uncompresses two .zip files and some files will be overwritten. That's OK, no worries. Simply respond A, meaning (A)ll when it asks about overwritting files.

run the web application

$ python portal.py

Serving on 0.0.0.0:8080

open the web application in your browser

server: localhost, port: 8080, context: /portal


答:
Also you could pass a string resembling a query string, and use parse_str (because it seems you are using PHP, but other solutions are probably available in other languages) to process it into an array inside the method:

```<code>/**
 * Executes a search in the DB with the constraints specified in the $queryString
 * @var $queryString string The search parameters in a query string format (ie
 *      "foo=abc&bar=hello"
 * @return ResultSet the result set of performing the query
 */
function searchQuery($queryString) {
  $params = parse_str($queryString);
  if (isset($params['name'])) {
    $query->where('name', $params['name']);
  }
  if (isset($params['phone'])) {
    $query->join('phone');
    $query->where('phone', $params['phone']);
  }
  ...

  return ...;
}
</code>```

and call it like

```<code>$result = searchQuery('name=foo&phone=555-123-456');
</code>```

You can use http_build_query to convert from an associative array to a string (the reverse that parse_str does).

Body:
Also you could pass a string resembling a query string, and use parse_str (because it seems you are using PHP, but other solutions are probably available in other languages) to process it into an array inside the method:

/**
 * Executes a search in the DB with the constraints specified in the $queryString
 * @var $queryString string The search parameters in a query string format (ie
 *      "foo=abc&bar=hello"
 * @return ResultSet the result set of performing the query
 */
function searchQuery($queryString) {
  $params = parse_str($queryString);
  if (isset($params['name'])) {
    $query->where('name', $params['name']);
  }
  if (isset($params['phone'])) {
    $query->join('phone');
    $query->where('phone', $params['phone']);
  }
  ...

  return ...;
}

and call it like

$result = searchQuery('name=foo&phone=555-123-456');

You can use http_build_query to convert from an associative array to a string (the reverse that parse_str does).


答:
According to the RFC for HTTP, which most REST APIs build upon, the meaning of the methods is:

GET: Retrieve a resource

POST: Add a sub-entity to a resource

PUT: Create or replace a resource

DELETE: Remove a resource

In common usage, POST is also often used to modify a resource by indicating the changes that must be applied.

The main distinction between POST and PUT is that you should use PUT if you already know the exact URI of the resource you are creating, and POST if you only know the collection that will hold the resource.

As for the usage in REST APIs, I would recommend to use POST for adding resources to a collection and for modifying resources piecewise. If neither makes sense, then you should return a 405 (Method Not Allowed) error.

Title: Is POST for an element generally not exposed or invalid in REST APIs?

Body:
I was browsing around wikipedia on REST, reading specifically the section on REST APIs

Reading the different ways to treat elements from collections I read that POST is not generally used.

How does that work in practice? When successful REST APIs are developed, when it comes to elements, does POST just not exist or return an error?

Is there a reasoning behind that I haven't grasped?


问:
What imperative programming languages do not support recursion?
To my knowledge, all modern imperative programming languages support recursion in the sense that a procedure can call itself. This was not always the case, but I cannot find any hard facts with a quick Google search. So my question is:

Which languages did not support recursion right from the start and when was that support added?

答:
Wikipedia says:

Early languages like Fortran did not
  initially support recursion because
  variables were statically allocated,
  as well as the location for the return
  address.

http://en.wikipedia.org/wiki/Subroutine#Local_variables.2C_recursion_and_re-entrancy

FORTRAN 77 does not   allow recursion,
  Fortran 90 does, (recursive routines
  must be explicitly   declared so).

Most FORTRAN 77 compilers allow
  recursion, some (e.g. DEC) require
  using a compiler option (see compiler
  options chapter). The GNU g77,  which
  conforms strictly to the Fortran 77
  standard, doesn't allow   recursion at
  all.

http://www.ibiblio.org/pub/languages/fortran/ch1-12.html

ContentLicense: CC BY-SA 2.5


问:
Generics vs IoC
One of the "Service Locator" pattern drawbacks is that a caller can be misleaded about dependencies of a callee.

Ok, but what if I put dependencies as generic parameters at a class level:

```<code>class Node<T> where T : ISomeInterface, new()
{
  ISomeInterface obj
  public Node()
  {
     obj = new T();
  }
}
</code>```

I have found a couple of opinions here. But I want a discussion to be continued.

The most significant counterargument is that dependency injecting using generics makes late binding unavailable. But who cares in most cases? What if my app does not need this feature?

I want to find some solid counterarguments.

p.s. new() constraint is not necessary, as you understand.

答:
The linked article is a bit misleading, in my opinion. Yes, using Inversion of Control containers makes some errors appear at runtime rather than compile time. And in general, it makes the process of writing and maintaining your code more fragile. This applies to Service Locators or really any other IoC container in my experience. This does not make them anti-patterns.

The key thing is that if you don't need that sort of plugin behavior, then don't use it. All design decisions are a trade off, and in IoC's case, that late binding (and ease of testing) is what you get and runtime errors rather than compile time (and decreased readability/debug-ability) is what you pay.

Indeed, your default approach should just be making plain old objects that take parameters in their constructor. Once that's insufficient, then start worrying about fancy tricks.

Title: Generics vs IoC


答:
I would say that your solution is actually worse than the original.

You're limiting yourself to types that have default constructor. What if you want to use a type that takes some configuration in its constructor?

If you have a dependency that has a dependency that has a dependency, you end up with horrible types like Node<Foo<Bar<Baz>>>. This doesn't make much sense, especially since none of the members of the type actually depend on the type parameters.

You need to specify the concrete type of dependency at compile time. This makes your code much less flexible and you can't for example switch the dependency just by editing a configuration file (which can be useful).

How is new Node<Foo>() any better than new Node(new Foo())?

Title: Generics vs IoC

Body:
One of the "Service Locator" pattern drawbacks is that a caller can be misleaded about dependencies of a callee.

Ok, but what if I put dependencies as generic parameters at a class level:

```<code>class Node<T> where T : ISomeInterface, new()
{
  ISomeInterface obj
  public Node()
  {
     obj = new T();
  }
}
</code>```

I have found a couple of opinions here. But I want a discussion to be continued.

The most significant counterargument is that dependency injecting using generics makes late binding unavailable. But who cares in most cases? What if my app does not need this feature?

I want to find some solid counterarguments.

p.s. new() constraint is not necessary, as you understand.


答:
I've seen a lot of confusion from people over what POST actually means. It does not mean create, and it does not mean update. POST means “send a message to a resource without the expectation of idempotency”. The other basic HTTP methods are all idempotent: if you do the same thing twice, you get (morally) the same result.

Let's clarify. When you use POST twice in a row, sending the same message to the same resource, you are nevertheless anticipating different results from the two operations. This can map quite nicely to creation where the server is creating new resource URIs in response to the messages: different URIs, non-idempotent. On the other hand, if the client is making the URI (a common case where you're modelling a filesystem) then POST is the wrong thing for creation: PUT to the resource you want to create is more typically correct there (and PUTting the same content to the same URI twice results in the same thing: the content exists afterwards at that URI whether or not it existed beforehand).

It is important to realise that REST is not just about simply having collections and values in those collections. It can do much more than that (though in that case you have to do more work to make it all discoverable).


问:
Why is cleverness considered harmful in programming by some people?
I've noticed a lot of questions lately relating to different abstraction techniques, and answers saying basically that the techniques in question are "too clever." I would think that part of our jobs as programmers is to determine the best solutions to the problems we are given to solve, and cleverness is helpful in doing that.

So my question is: are the people who think certain abstraction techniques are too clever opposed to cleverness per se, or is there some other reason for the objection?

EDIT: This parser combinator is an example of what I would consider to be clever code. I downloaded this and looked it over for about half an hour. Then I stepped through the macro expansion on paper and saw the light. Now that I understand it, it seems much more elegant than the Haskell parser combinator.

答:
I couldn't find the word discipline mentioned anywhere around here, so I'll chip in. I do not want to post the answer, but to share a different insight on the matter, maybe one that the original question did not have in mind.

A clever developer is a good thing.

However, before cleverness come other traits. As you might have realized I will talk about discipline. A clever and undisciplined developer can be very bad for the long term maintainability of the system.

Suppose that a bug arises or a new requirement comes in. A clever developer might soon realize that a couple local fixes will get the job done in 2 minutes. If that developer is disciplined he will restrain from applying those fixes to the source code and will, instead, find a meaningful way to compose the desired behavior to the system. This way, the next time the need will arise to modify the particular pieces of code the maintainer will have an easy time to understand the code and implement the new changes without breaking anything. If not, well you get the picture.


答:
Do both, sort of.  array_merge allows for an explicit list at the top of the function, as your colleague likes, while keeping the parameters from getting unwieldy, as you prefer.

I also strongly suggest using @chiborg's suggestion from the question comments - it's a lot clearer what you intend.

```<code>function searchQuery($params = array()) {
    $defaults = array(
        'name' => '',
        'phone' => '',
        ....
    );
    $params = array_merge($defaults, $params);

    if(!empty($params['name'])) {
        $query->where('name', $params['name']);
    }
    if (!empty($params['phone'])) {
        $query->join('phone');
        $query->where('phone', $params['phone']);
    }
    ....
}
</code>```

Body:
Do both, sort of.  array_merge allows for an explicit list at the top of the function, as your colleague likes, while keeping the parameters from getting unwieldy, as you prefer.

I also strongly suggest using @chiborg's suggestion from the question comments - it's a lot clearer what you intend.

function searchQuery($params = array()) {
    $defaults = array(
        'name' => '',
        'phone' => '',
        ....
    );
    $params = array_merge($defaults, $params);

    if(!empty($params['name'])) {
        $query->where('name', $params['name']);
    }
    if (!empty($params['phone'])) {
        $query->join('phone');
        $query->where('phone', $params['phone']);
    }
    ....
}


问:
What is the best way to estimate when using Agile with Scrum? Hours or Story Points?
I was at a company that switched us over from Hours to Story Points for our estimations.  I remember it being difficult to understand it, and we all chaffed against the idea.  However, once we figured out how to do it and started doing it, I think our estimations became much more accurate.  We were much better able to complete our sprints on time and to better be able to estimate duration of remaining work.  Once a couple weeks had passed, we had a good idea of our individual teams’ velocities and could then translate the story points into days and weeks of work.  We then used that to know what we could complete within a given time-span.

I guess the same could work if estimating in hours, as long as it is understood that each team will have a different number of hours per week in their velocity.  One team may do 200 hours, while another may do 150 hours on average.  This doesn't mean one team is working any harder than the other, it just means that they estimate hours differently, or that some team members may not have as much time available to work on the project, for instance, they may always be pulled into bug fixes, or help on other projects, which reduces their available time for this project.

Anyway, what do you think?  And why?  Which is best?  Hours, or Story Points?

答:
Story points and hour estimates don't serve the same purpose. Story points apply to user stories, they are used for broad brush forecasts of what amount of business value a team is able to produce on the long run (via velocity). Hours are generally put on tasks, they are mostly useful inside iterations for day-to-day steering and to determine if the team is going to make it for the end of the sprint.

This is a traditional approach - some teams don't break down user stories into tasks, some use coarser grained units than story points and others don't even estimate in the usual sense of the word so YMMV.

I guess you should first ask yourself why you need estimates and then infer which type of measure you need. Might be points, might be hours, might be both. Or none.


问:
Reason for a reflection error
I’m working on an Eclipse plug-in project.

Using this plug-in, users can create Eclipse Java projects with some specificities. For example, they can add Java classes’ names which will be saved in a file. These Java classes can be created on the src of the project or used from a jar file which must be added to the project classpath. In this case, the plug-in will use reflection to get some data from each class.

There are two different test cases that give the same error because the plug-in can't find the class to instantiate:

A jar contain a class having a name saved in the file is not added to the project classpath. So in this case the classpath is incomplete.

The user of the plug-in updated a jar in which its old version of the jar contained the named class, but the new version of jar does not (which could happen if class was deleted from the new version of the jar). In this case, the plug-in will not find the class but the classpath is complete.

So The plug-in must differentiate between the two test cases when it fails finding the class name using reflection.

How that can be done?

答:
I see no practical difference between the two.  In both cases, the class you are looking for is not on the classpath.

Perhaps, the answer is to search every drive available on the machine for every .class or .jar file. Inspect every file found to see what classes are contained inside.  If the missing class is there, the classpath is incomplete.  Otherwise the class doesn't exist.

This doesn't sound very realistic, though.

Title: Reason for a reflection error


问:
Performance considerations when using Go for my project
I'm looking at using Go (aka golang) for a project (a SQL database, but that mostly doesn't matter here) where performance is critical, but under low load the primary bottleneck will be I/O to disk. In this case, I think Go would be great!

Under high load or while hitting cache a lot, CPU and memory utilization will increasingly become bottlenecks, and I'm worried that Go could make the high-end of the performance spectrum significantly lower than what C/C++/D might provide.

Can anyone with experience working in Go give some insight into how quickly that bottleneck is reached (networking applications are subject to the same bottleneck, typically) and what you can do to relax it in Go other than rewriting the bottleneck in a faster language?

Note my question was sufficiently different that I asked it anyway after reading related question:

https://softwareengineering.stackexchange.com/questions/160651/what-kind-of-software-is-done-best-with-the-go-programming-language

I have a specific application I'm asking about, and I've limited my concerns to performance (not usability, library support, development tools, etc).

答:
From the Go Nuts mailing list, https://groups.google.com/forum/#!forum/golang-nuts, and my own practice, I've picked up a few things:

There are ways to reduce the amount of garbage created, so less has
  to be collected, improving performance.

The code generator is still undergoing improvement and is nowhere as
   mature as gcc, for example.

The ease of parallel programming on multi-cpu servers should, in the
   large-enough case, make a golang implementation faster.
   Also, it can actually simplify program logic.  Few other
   concurrency systems can claim that.

Some of the Go standard libraries are better than others.  This implies
  that the others are worse.

The networking code is very good.  However, the netchan package
   was deprecated as too intricate.

You'll have a choice of representing character/string data as byte arrays
  or as strings.  Prefer byte arrays for performance and
  database storage.  Prefer strings for user displays and file names,
  and to leverage utf8.  All Go strings are utf8, byte arrays often
  are utf8, and arrays of ints are used for utf-32.  Converting from
  one to the other requires an allocation-and-copy, and generates
  garbage (for later collection).

Generally, pass strings and/or byte arrays as slices, which is like a
   reference, but has substring semantics.

Go strings are immutable but you can iterate through the characters,
   which means if it's utf8 data in the string, each iteration can consume
   more than one byte.  Usually that's a great  help.

The profiler is essential, I easily sped up a program that used 17 minutes
   of cpu time in 17 minutes, down to a few seconds.  The benchmarking facility
   provides finer grained information.

Compilation is fast and there is no VM to startup, so compile-and-test is
   fast.


问:
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.

答: Since it seems you are limited to MVC (re: comment from professor), you may want to look at this from a slightly different direction. Consider a chat received and chat to be sent as "events" that the controller must process and dispatch. The controller can have two queues. One for processing received chats and one for sending them. The network code feeds into and out of these queues. That's at least how I would look at it because it makes the threading a little simpler to handle. </p>


问:
Rethinking testing strategy
Working on Plone projects our team tries to achieve full test coverage at least for important products. The kind of tests we write are unit tests, functional tests and integration tests. (Also stress-tests, but those aren't in the scope of this question). The goal is two fold at least: to facilitate upgrades and to catch bugs (sometimes it even happens in the process of writing tests).

However, Plone/Zope is a complex system, and with years of experience I've noticed, that test strategy should be re-thought. First of all, unit tests, which often require  to use a lot of mocking, are not that (cost)efficient. They are mostly easy and beneficial when some core, logic-heavy functionality is being written, like pure Python modules, which have negligible couplings with Plone/Zope, databases, etc. I rarely seen unit-tests catching any bugs at all, except while writing them.

So, when doing the usual thing (writing views/portlets/viewlets), from my experience, it's much more efficient to write functional and integration tests. The rationale of it is that in case Plone/Zope changes (in an upgrade) we can catch the mishaps in our code. Views usually do not have a lot of "algorithmic" logic, they glue together several data sources (like catalog queries), maybe with some form handling and preprocessing for templates. It is quite often views call one or more tools to do some routine job (like getting navigation tree or looking up site root). Mocking it all seems unwise. For example, sometimes Plone/Zope changes some default to another type and all those mocked tests happily continue to work while code fails in the real instance.

Functional/Integration tests may be at times fragile (HTML can change), but they are cheaper to produce too. They provide basic coverage, and trigger alarms when underlying system changes. Spotting the source of mishap is usually not an issue. (update: Wrong: spotting where integration test fails can be a big issue, but our code's unit tests are usually of no help.)

The question is, am I overlooking something of importance confining unittesting to functions and classes, which do not require mocking the environment heavily and are instead "purely" logic-heavy? I can't find any justification for writing unit-test "first", or even at all, for every piece of code in Plone/Zope (I do not mean the core of the system, just our own additions for our clients).

To make the question less opinion based, are there other reasons, I have not mentioned or tackled above, which necessiate to consider writing more unit tests (and less integration tests) in a situation when code heavily depends on a complex (and somewhat hairy) framework, and code serves more as a glue for framework's subsystems?

答:
I rarely seen unit-tests catching any bugs at all, except while writing them.

Well that's one good reason to keep writing unit tests - unit tests are there not just for regression testing but to help guide the design of your system. If unit tests can help you notice bugs in the code under test which you can then fix on the fly, that's real value right there

It is quite often views call one or more tools to do some routine job (like getting navigation tree or looking up site root).

And there's two more reasons - behavioural verification and regression testing - knowing with 100% certainty that View X did make a call out to tool Y and did pass the result to the widget processor therefore  the reason why widget Z is not rendering, must be the widget processor (or whatever) and you didn't even have to use the debugger to fix it!

Spotting the source of mishap is usually not an issue.

A very debatable and admittedly subjective (with my tongue firmly in my cheek!) "benefit" or at least "Food for thought" I hope, starts with : can you define "usually"?

In the "unusual" cases where you don't instantly spot the source of the problem, because it's 2 a.m and your eyes are bleeding from the glare of the monitor...how long do you really spend chasing down problems? Have you measured how much time it might be taking you in these cases vs writing tests up front that will pinpoint the problem for you - if you analyse this and find a net gain in time by TDD up front, then I say that's your bottom line.

Of course if analysis shows that in your case it really does not save you time, then there's a proven, good justification for not doing it - you can't lose!

Title: Rethinking testing strategy


问:
Extracting lambda expressions from linq queries and readability
Every now and then when I have a complex lambda, I do something like this:

```<code>Func<SomeObject, bool> equals = o =>
    o.ID == someID && o.Name == someName && IsAdd || ...
var myList = MyThings.Where(equals).ToList();
</code>```

Let's assume that the logic in equals can not be simplified. Does extracting the lambda from the linq query improve, or reduce readability?

The alternative being:

```<code>var myList = MyThings.Where(o => o.ID == someID && o.Name == someName && IsAdd || ...).ToList();
</code>```

答:
When you format a complex Linq query well enough (don't let it run on too many lines) it shouldn't be more difficult to read than a complex condition in a while loop or if statement.

The follow reads just fine to me:

var myList = MyThings.Where(o => o.ID == someID
                              && o.Name == someName
                              && IsAdd
                              || /* other conditions */).ToList();
```

So does the version using an extracted equals Func<T, bool>.

However, usually when I see a Func object like that, I make the assumption that it may not always be the same logic. I use a Func when the action being performed needs to be passed in externally, or determined by some condition. In this case, your Func is right next to the Linq expression itself, so it's easy to see that it's not the case, but it may be confusing if they were separated further.

Let's pretend this logic was being used in an if condition. If the logic is complex enough that you would consider splitting it out into its own named Boolean variable, it's probably justifiable to do something similar and make a Func. If you would write the condition directly inside the body of your if, it's probably simple enough to understand inside the body of your Where function.

Body:
When you format a complex Linq query well enough (don't let it run on too many lines) it shouldn't be more difficult to read than a complex condition in a while loop or if statement.

The follow reads just fine to me:

var myList = MyThings.Where(o => o.ID == someID
                              && o.Name == someName
                              && IsAdd
                              || /* other conditions */).ToList();

So does the version using an extracted equals Func<T, bool>.

However, usually when I see a Func object like that, I make the assumption that it may not always be the same logic. I use a Func when the action being performed needs to be passed in externally, or determined by some condition. In this case, your Func is right next to the Linq expression itself, so it's easy to see that it's not the case, but it may be confusing if they were separated further.

Let's pretend this logic was being used in an if condition. If the logic is complex enough that you would consider splitting it out into its own named Boolean variable, it's probably justifiable to do something similar and make a Func. If you would write the condition directly inside the body of your if, it's probably simple enough to understand inside the body of your Where function.


问:
How to handle lookup data in a C# ASP.Net MVC4 application?
I am writing an MVC4 application to track documents we have on file for our clients. I'm using code first, and have created models for my objects (Company, Document, etc...). I am now faced with the topic of document expiration.

Business logic dictates certain documents will expire a set number of days past the document date. For example, Document A might expire in 180 days, Document 2 in 365 days, etc... I have a class for my documents as shown below (simplified for this example).

What is the best way for me to create a lookup for expiration values? I want to specify documents of type DocumentA expire in 30 days, type DocumentB expire in 75 days, etc... I can think of a few ways to do this:

Lookup table in the database I can query

New property in my class (DaysValidFor) which has a custom getter that returns different values based on the DocumentType

A method that takes in the document type and returns the number of days

and I'm sure there are other ways I'm not even thinking of. My main concern is a) not violating any best practices and b) maintainability. Are there any pros/cons I need to be aware of for the above options, or is this a case of "just pick one and run with it"?

One last thought, right now the number of days is a value that does not need to be stored anywhere on a per-document basis -- however, it is possible that business logic will change this (i.e., DocumentA's are 30 days expiration by default, but this DocumentA associated with Company XYZ will be 60 days because we like them). In that case, is a property in the Document class the best way to go, seeing as I need to add that field to the DB?

```<code>namespace Models
{
    // Types of documents to track
    public enum DocumentType
    {
        DocumentA,
        DocumentB,
        DocumentC // etc...
    }

    // Document model
    public class Document
    {
        public int DocumentID { get; set; }

        // Foreign key to companies
        public int CompanyID { get; set; }

        public DocumentType DocumentType { get; set; }

        // Helper to translate enum's value to an integer for DB storage
        [Column("DocumentType")]
        public int DocumentTypeInt
        {
            get { return (int)this.DocumentType; }
            set { this.DocumentType = (DocumentType)value; }
        }

        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]
        public DateTime DocumentDate { get; set; }

        // Navigation properties
        public virtual Company Company { get; set; }
    }
}
</code>```

答:
If DaysValidFor is a property of the document type, then put it in the DocumentType table, and look it up or join it with the Documents table.

If DaysValidFor can be customized, add a DaysValidFor field to the Documents table, and use the DaysValidFor in the DocumentType table as a default value when you are creating a new Document record.

Rationale

By having a DocumentType table from the start, you provide a container by which all sorts of other features become possible as a function of that document type.  You also avoid a redesign when you find out you need a DocumentType table, and you didn't provide one.  Not every domain object needs such a type table, but documents are naturally organized into categories, so it's a good fit here.

You can have a DaysValidFor method in your repository if you want one.  Pass it the DocumentID, and look the value up from the Documents table.

If you think in terms of classes instead of tables (i.e. "code first"), just substitute the word "class" for the word "table" in the two paragraphs above.


问:
Module system for OOP language
I'm designing a simple OO programming language.

It's statically typed, compiled, and executed by a VM - similar to Java.

The difference is that I don't want to have such a strong emphasis on OOP. The code itself will mostly resemble C++ (classes, functions, and variables allowed in the file scope).

One of the things that I need to have is a module system. I have the following figured out:

Every file is a module (once compiled) - like Python

Programmers must import a module with the import keyword, which causes the compiler to search for modules in standard directories and the file directory (the VM has to do this at runtime as well)

And now I have no idea how should I introduce the concept of submodules and module hierarchy.

One option, for example, is to depend on the directory hierarchy, so that import engine.graphics.renderer would expect to find a directory called "engine" in the working directory, and inside a directory called "graphics", with a module called "renderer".

What are the drawbacks of such a design? Am I missing anything?

答:
Take a look at Python's package/module hierarchy/organization, and especially in historical aspect, major additions over the course of years, most importantly the latest ones. Probably, there is no sense in inventing the wheel.

I do not know how far you want to go with your language, eg

Do you want modules bytecode to be read from zip?

How do you separate modules/libraries for different interpreter versions?

Do you plan to make it seemless with distros?

Do not forget easiness of language's own distribution (think distutils / pypi - each platform/language has its own, not always good)

I guess, Java may be another interesting example. Things can be learned from Erlang's way as well (eg https://stackoverflow.com/questions/2968914/code-hot-swapping-in-erlang).

There is a whole lot of design issues (some touched above) if you plan to see your programming language mainstream one day. Fortunately, there are great examples out there.

Some directions programming language module/package/library system design should address:

intuitive code for both writing and using the module

module/package objects in the code

module/package introspection capabilities

module/package encapsulation (how to hide unnecessary details?)

use of interfaces/header files?

fine-graned dispatching system, which both language own distribution utils as well as system level utils can use (avoid "DLL hell")

storage places for bytecompiled modules

setup system, which automates compiling both "pure" modules and modules/dependencies

canonical place of compiled code, tests, documentation, assets in your module

Title: Module system for OOP language


答:
I'm not sure COBOL does (it certainly didn't at one time), but I can't quite imagine anybody caring much either.

Fortran has since Fortran 90, but requires that you use the recursive keyword to tell it that a subroutine is recursive.

PL/I was pretty much the same -- recursion was supported, but you had to explicitly tell it what procedures were recursive.

I doubt there are many more than that though. When you get down to it, prohibiting recursion was mostly something IBM did in their language designs, for the simple reason that IBM (360/370/3090/...) mainframes don't support a stack in hardware. When most languages came from IBM, they mostly prohibited recursion. Now that they all come from other places, recursion is always allowed (though I should add that a few other machines, notably the original Cray 1, didn't have hardware support for a stack either).

Title: What imperative programming languages do not support recursion?

Body:
To my knowledge, all modern imperative programming languages support recursion in the sense that a procedure can call itself. This was not always the case, but I cannot find any hard facts with a quick Google search. So my question is:

Which languages did not support recursion right from the start and when was that support added?