问:
What are the negatives of Development Managers as Scrum Masters?
It is commonly agreed that team managers should not be scrum masters, but I am struggling to see why.  For context, I am an Application Development Manager with 4 devs in a Scrum Team.  I come from a Scrum Master background, and have introduced scrum to the organisation.  I have built the team from scratch and made it clear that everything I do is to facilitate the team, and that they make the decisions.  As a team we are very open - they even silenced me at stand-ups for a while to eliminate the 'reporting' feel we were starting to get.  A lack of openness is generally the biggest argument against the manager as scrum master, but handled well, is easily overcome with the right culture.

I've been warned by experienced scrum coaches that this is a dangerous situation, and there are risks 'if things go badly'.  The way I see it the 2 positions do not conflict, in both roles I have the same aim for the team and individuals. Scrum resolves conflicts within the team, which could traditionally be a managers role. The self-managing nature of sprints takes away the allocation of work a manager would traditionally do.

All I really see left to pick up as a dev manager is making sure individuals needs are met, career objectives, workplace etc. I have a weekly catch up with each team member to raise any issues, and handle any admin tasks. A lot of this relates directly to the team, or my role as scrum master anyway.

I understand in large organisations how this could be unmanageable and a separate role but for a small organisation we could certainly not justify another Scrum Master or Development Manager.

Please enlighten me as to the pitfalls of Development Managers as Scrum Masters, excluding the points I raised above and have already overcome.

答:
I would listen to experienced scrum coaches. It is possible that you would work out just fine for 99% of the time. However when that dreaded 1% comes along and the roles conflict you have a chance to  screw up not only an individual's relationship with you but the entire team's well being. And after one screw-up your role as both scrum master and manager would be undermined. </p>

<p>If I were you I'd identify an individual on the team who has the potential to be the scrum-master and go with him/her. I always viewed a scrum master as someone who the team trusts and who understands the process, the business and the scary technical stuff as well. If you chose a capable person, a scrum master role is not (and not even close to being) a full-time job.  </p>

Body:
I would listen to experienced scrum coaches. It is possible that you would work out just fine for 99% of the time. However when that dreaded 1% comes along and the roles conflict you have a chance to  screw up not only an individual's relationship with you but the entire team's well being. And after one screw-up your role as both scrum master and manager would be undermined.

If I were you I'd identify an individual on the team who has the potential to be the scrum-master and go with him/her. I always viewed a scrum master as someone who the team trusts and who understands the process, the business and the scary technical stuff as well. If you chose a capable person, a scrum master role is not (and not even close to being) a full-time job.


答:
I believe the main problem is that as a manager, you have the authority to tell the team what to do.  A scrum master does not have this authority outside of enforcing the principles of Scrum.

What does this mean?  The manager's input will implicitly carry more weight.  You might not mean it to, or want it to, but at the end of the day your team members career and paycheck depend in some way on you.  And they know it.  And this taints the relationship.

Can you still do it?  Of course.  You just need to work very hard to reinforce that you are a servant-leader and top-down won't fly.

ContentLicense: CC BY-SA 3.0

Title: What are the negatives of Development Managers as Scrum Masters?

Body:
It is commonly agreed that team managers should not be scrum masters, but I am struggling to see why.  For context, I am an Application Development Manager with 4 devs in a Scrum Team.  I come from a Scrum Master background, and have introduced scrum to the organisation.  I have built the team from scratch and made it clear that everything I do is to facilitate the team, and that they make the decisions.  As a team we are very open - they even silenced me at stand-ups for a while to eliminate the 'reporting' feel we were starting to get.  A lack of openness is generally the biggest argument against the manager as scrum master, but handled well, is easily overcome with the right culture.

I've been warned by experienced scrum coaches that this is a dangerous situation, and there are risks 'if things go badly'.  The way I see it the 2 positions do not conflict, in both roles I have the same aim for the team and individuals. Scrum resolves conflicts within the team, which could traditionally be a managers role. The self-managing nature of sprints takes away the allocation of work a manager would traditionally do.

All I really see left to pick up as a dev manager is making sure individuals needs are met, career objectives, workplace etc. I have a weekly catch up with each team member to raise any issues, and handle any admin tasks. A lot of this relates directly to the team, or my role as scrum master anyway.

I understand in large organisations how this could be unmanageable and a separate role but for a small organisation we could certainly not justify another Scrum Master or Development Manager.

Please enlighten me as to the pitfalls of Development Managers as Scrum Masters, excluding the points I raised above and have already overcome.


答:
Essentially, you have a conflict of interest.  A manager's job is to meet deadlines.  A scrum master's job is to ensure estimates are as accurate as possible and to work at a sustainable pace.  A manager tends to want more work pulled into a sprint, and a scrum master tends to want an amount that can be realistically finished, regardless of external deadlines.  Although a good manager can balance that conflict, it's much easier when the job is split between two people.  Managers usually are much better suited for the product owner role.

There's nothing wrong with acting as scrum master if no one on your team is familiar with it, but your team will see benefits if you hand off that role after a few months.  It's important for that role to be seen as a peer.  Even non-management scrum masters often have to rotate out after a while because the team starts to treat them too much like a manager.


答:
The main problem I see is that you are sending conflicting messages to the team about the team's organization.

Below are two possible team organizations. Both can be successful. They are different. (They are not the only possible options.)

The team has an officially designated leader. The team leader is ultimately accountable for the teams' overall performance. The team leader may not make all decisions, but the team leader has the final say on all decisions.

The team is self-organized and does not have an officially designated leader. Everyone on the team is accountable for their own and the teams' overall performance. The Scrum Master facilitates the Scrum process, but is not empowered to make unilateral decisions for the team.

It sounds like your real team structure is #1, but by using the terminology and several processes from Scrum, you are implying that the structure is #2. My opinion is that #1 is not Scrum.

Below are a two suggestions for how to resolve the conflict.

Keep doing things as you are, but clarify that you are the team leader and you are not following Scrum 100%. It would probably help to explain that while you see the value in segregating the duties of a manager and scrum master, that is not feasible for the company.

Hand off the Scrum Master responsibilities, as much as you can, to someone else. Even if you still have to retain some responsibilities like clearing roadblocks and deflecting distractions from the rest of the organization, it will still help to have much of the Scrum Master work done by a peer.


问:
DDD Bounded Contexts & Domains?
I've been working in a relatively complex application with 10's of database tables (Aggregates, Entities/Value Objects) and applying DDD. At this point it appears to be basically DDD-Lite meaning that there are Application/Domain Services, the Domain Model (Entities, Value Objects), and Repositories.

I picked up a book Implementing DDD and the first thing he is mentioning is DDD-Lite and Bounded Contexts and Domain Events missing as first mistakes which are usual when beginning DDD.

Currently I've tried organizing the Domain Model by Aggregate relationships, and using namespaces to demonstrate it.

I'm failing to see the benefit/downfalls relating to separating the Domain Model project into separate Bounded contexts (yet). Perhaps it will become apparent later on but I'd like some real life feedback on Bounded Contexts (and possibly sub domains etc. if they tie into it).

答:
Consider a company that has a few different departments:

Software Development

HR

Accounting

Can you come up with a user model that can expressively represent all those areas of business? Think of what the User entity could look like in each one. Perhaps it's split into three different entities:

Developer

Employee

Payee

The effort to instantiate a user in each context is considerably different. Perhaps it's something like this:

new Employee(ssn, name, joindate, dateofbirth, gender)

new Developer(Employee, workstation, credentials)

new Payee(Employee, role)

excuse the example, it's hard to illustrate accurately without a proper domain model to reference

If you used a naive implementation and used a single user entity, it would end up being an anaemic data model full of getters and setters, because you couldn't fully represent the user all over the place.

There are clear boundaries in the business, so it's useful to model them that way. A user logging in versus a user in a payroll system versus a user playing a game are all very different, even if they are part of the same grand system.

Thinking in another way - you can now create your developer management code to be very lightweight and independent from the rest of your system. It can use more accurate types with less baggage to worry about. It's the step to building smaller subsystems that may eventually be extracted out into its own application.

Title: DDD Bounded Contexts & Domains?


答:
The biggest problem I see is the situation where the team has an issue related to you, the manager. If they are junior, or lack confidence, they may be afraid to speak up during retrospectives. This could limit the effectiveness of the retrospectives. Many people are afraid to say "I feel the manager is being unrealistic" when the manager is present.

So, maybe you excuse yourself from retrospectives to solve this problem. Now your team is doing retrospectives without a scrum master, also potentially limiting the effectiveness of the retrospective.

In either case, you're having a negative impact on the team.


问:
Is it possible to combine C/C++ with web languages?
I would like to create a web application (meaning that will run from browser). The point is that I want to write just the UI in HTML5 + CSS + JS (or maybe even some PHP). On the other hand, I want to write the functionality of the application in C or C++. Then, I want to combine the code about the UI and functionality. Therefore, I would like to ask, whether it is possible to combine C/C++ code with web markup/programming languages?</p>

答:
You can use tools like emscripten too, this converts LLVM bitcode into javascript. You can combine this with clang or clang++ to run your C or C++ in the browser. (Actually on the client side, unlike CGI)

(Unreal did their html5 port this way!)


问:
API design: concrete vs. abstract approach - best practices?
When discussing APIs between systems (on the business level) there are often two different point of views in our team: some people prefer a more - lets say - generic abstract approach, other a straight forward "concrete" approach.

Example: the design of a simple "person search" API. the concrete version would be

```<code> searchPerson(String name, boolean soundEx,
              String firstName, boolean soundEx,
              String dateOfBirth)
</code>```

People in favour of the concrete version say:

the API is self-documenting

it is easy to understand

it is easy to validate (compiler or as a webservice: schema validation)

KISS

The other group of people in our team would say "That is just a list of search criteria"

```<code>searchPerson(List<SearchCriteria> criteria)
</code>```

with

```<code>SearchCritera {
  String parameter,
  String value,
  Map<String, String> options
}
</code>```

with possibly making "parameter" of some enumeration type.

Proponents say:

without changing the (declaration of) the API the implementation can change, e.g. adding more criteria or more options. Even without synchronizing such a change at deployment time.

documentation is necessary even with the concrete variant

schema validation is overrated, often you have to validate further, schema cannot handle all cases

we already have a similiar API with another system - reuse

The counter-argument is

lots of documentation about valid parameters and valid parameter combinations

more communication effort because it's more difficult to understand for other teams

Are there any best practices? Literature?

答:
The best summary that I've ever seen is Rusty's scale, now called Rusty's API Design manifesto. I can only strongly recomment that one. For the sake of completeness, I cite the summary of the scale from the first link (the better on top, the worser below):

Good APIs

It's impossible to get wrong.

The compiler/linker won't let you get it wrong.

The compiler will warn if you get it wrong.

The obvious use is (probably) the correct one.

The name tells you how to use it.

Do it right or it will always break at runtime.

Follow common convention and you'll get it right.

Read the documentation and you'll get it right.

Read the implementation and you'll get it right.

Read the correct mailing list thread and you'll get it right.

Bad APIs

Read the mailing list thread and you'll get it wrong.

Read the implementation and you'll get it wrong.

Read the documentation and you'll get it wrong.

Follow common convention and you'll get it wrong.

Do it right and it will sometimes break at runtime.

The name tells you how not to use it.

The obvious use is wrong.

The compiler will warn if you get it right.

The compiler/linker won't let you get it right.

It's impossible to get right.

Both details pages here and here come with an in-depth discussion of each point. It is really a must-read for API designers. Thanks Rusty, if you ever read this.


问:
Checking a record is due based on the 'occuring' field
I have records that have dates against them and an occurring field that contains none,yearly and monthly

```<code>id    status    note   date        last_updated   occurring
1     open      ---    01/01/2011  01/02/2010     yearly
2     open      ---    05/05/2011  03/05/2011     monthly
3     open      ---    06/06/2011  05/06/2011     none
</code>```

Now I need to be able to check if a record is due (the date set has passed) which works perfect if occurring is set to none but I'm unsure of how to approach it when it's set to yearly or monthly (IE: This day in the year/month has passed)

So with the above records, if I had a method on the record called due? providing the status is 'open' it needs to return true every year when it's passed that date if it's not been updated within the year yet.

I apologise if this is confusing but it's melting my brain just trying to think of it, let alone put it into words.

答:
First you need to be able to do date arithmetic.  You've got to be able to turn a date into a number and back again.  Given a number, you've got to be able to find the start and end of the month and year it falls in.  You've got to be able to add 4 months to, say, October 22, 2012.  This isn't too hard to do on your own (I've done it) but nowadays there's bound to be a Date class or library that will do the work for you.

Then, for a monthly occurrence, generate a date using today's month and year plus the day-of-the-month the update's due.  If the resulting date is after today's date (using date arithmetic) subtract one month from it (using date arithmetic).  This us the latest due date.  If last_updated is before that, the next update is overdue.  You can do the same thing with years, but throw the month in as well as the day.

You may need arrays to check off updates.  Being early with an update might be a good thing, and you won't want to ignore one.  Arrays need to be indexed by month numbers or year numbers (minus an offset for the array start date), which you'll need to convert back to the basic date number.  Hopefully your Date library can handle this.  Take care to always use the library:  if you forget and add 3 days to a number date with a simple integer add, you could end up with a February 31st.

Hopefully this will get you started.


答:
First of all, try to find out if the platform you are using has date operations, built in or third party library.

For example, if you are using PostgreSQL, the appropriate information can be found on it's documentation page.

Hopefully, the library is good enough to provide functions like beginning of the month and end of the month, and doing time deltas. The very minimum is being able to break up the date into the parts and create new one from parts, and of course being able to compare dates. Good bonus is to be able to find previous month and next month, but these could be composed by getting beginning of the month and adding/substracting days: -1 for the previous month, +33 for the next month.

Beginning of the month can be easily constructed by setting day to 1. Beginning of the year - by setting both month and day to 1.

If I understood correctly, you need to find previous and next "due date" and then apply date comparing operations. First find due date in "this month", after that, in the previous month or next month (check the logic of the period to decide which one, or check both periods).

If your platform does not have good date library, find some open source library in the language you understand best, and try to port it to your platform.

Maybe, it will help you to understand the logic of due_date, if you can think of True condition meaning last_update belonging to one of the "due_date periods" (period has start and end dates). The trick then boils down to construct and check only nearby periods using functions/operations from your platform's datetime library.

Title: Checking a record is due based on the 'occuring' field

Body:
I have records that have dates against them and an occurring field that contains none,yearly and monthly

```<code>id    status    note   date        last_updated   occurring
1     open      ---    01/01/2011  01/02/2010     yearly
2     open      ---    05/05/2011  03/05/2011     monthly
3     open      ---    06/06/2011  05/06/2011     none
</code>```

Now I need to be able to check if a record is due (the date set has passed) which works perfect if occurring is set to none but I'm unsure of how to approach it when it's set to yearly or monthly (IE: This day in the year/month has passed)

So with the above records, if I had a method on the record called due? providing the status is 'open' it needs to return true every year when it's passed that date if it's not been updated within the year yet.

I apologise if this is confusing but it's melting my brain just trying to think of it, let alone put it into words.


答:
This isn't religion and the rules of Scrum are not dogmatic. If there's ever been a case for a combined HR Manager/ Srum Master role, you've made a good one. Be on the lookout for those pitfalls you mentioned, but there is never going to be a single set of rules that fit every situation perfectly.

If your team is comfortable with you performing both roles, then there's no reason to shake things up just to fit with the rules of a book.


问:
What 's the minimal requirement for a code be considered an AI implementation?
I'd like to know at what point can be considerated an AI implementation?

I means, what is the minimal requeriment for that?

Can you give a simple code example?

答:
I would consider any machine that is both useful and permanently beyond my understanding to be artificially intelligent (although I dare not suggest that such machine might exist outside of fiction lest my geekhood would be cast into doubt).

A less personal definition:

A machine can be considered artificially intelligent if it can solve classes of problem that were not envisaged by its designers.

Preumably, the architects of such a machine must endow their creation with the ability to lean, or else they must be possessors of extreem good fortune. By definition, trivial machine learning is precluded (so no, your tic-tac-toe solver dosn't count). Either way, happy + surprised should characterise the mood of that machine's engineers.

The closest I can get to a code sample? Is this:

http://www.google.com

This works quite well on my machine (indeed, this automiton sometimes appears prescentient) but YMMV.

ContentLicense: CC BY-SA 2.5


答:
What about developing your app functionality as a separate server and communicate with your UI using REST (or SOAP)? JS can process these messages and update UI. IMHO it is a better option.

Is this solution viable to you?

Title: Is it possible to combine C/C++ with web languages?

Body: I would like to create a web application (meaning that will run from browser). The point is that I want to write just the UI in HTML5 + CSS + JS (or maybe even some PHP). On the other hand, I want to write the functionality of the application in C or C++. Then, I want to combine the code about the UI and functionality. Therefore, I would like to ask, whether it is possible to combine C/C++ code with web markup/programming languages?</p>


问:
CSS File Editing for Teams? (how to avoid stepping on each others' feet?!)
I'm wondering if anyone has a good solution for when you're working as a team and there's a single file used throughout a project (like a styles.css file) and everyone needs to use it throughout the day - inevitably someone will make changes and save without grabbing the most recent version first. Is there some sort of group editing program for Windows/web? We currently just access the CSS files via FTP & edit in our usual editors. Probably an editor that can load & save changes on the fly?</p>

答:
Use Git.

Git is a version-control system that has features specifically for this purpose. You can make changes to a file concurrently, and then Git tries to merge the two together automatically. When it can't merge them reliably, it tells you there are conflicts and asks you to resolve them.

I say use Git over other version-control systems (SVN, CVS, etc..) because in my experience, Git's merging capabilities are better. It has always seemed to be able to automatically merge stuff better than SVN. That may have changed since I last used SVN, however.


问:
Why doesn't Python just establish a format for declaring tab widths?
I've read the flame wars over the use of spaces and tabs. When working with any markup language (when scope isn't very important and when pressing space 4 times is a PITA), I tend to minimize the tab width to just a space or two but I fluidly change to four full tabs for my other programming work.

It is a matter of convenience most of the time and it only translates into real errors when sharing or mixing code.  So why they don't just declare a format for optional overrides such as #tab = 2 at the beginning of a file?  There would be no scoping issues and it could be handled with 2 lines of code.

Update

Whoa, I didn't explain myself very clearly: I only use editors that handle the tab/space conversion automatically.  The only cogent point I can understand in the criticisms I have read regarding Pythons use of white space is how borked the space/tab convention becomes when sharing code.

Perhaps my confusion about using "4 spaces" is because of my prior life in the publishing industry and our use of tabs not as a unit of white space but an abstract element used to describe a document's structure, not the display. Substituting it with 4 spaces has more to do with Unix's shitty 8-space convention than it does with elegance.  If Python standardized on using tabs by default we would eliminate the layer of abstraction (literal visual spaces -> abstract tab) that is getting lost when we leave IDE land and go to Usenet/chat/email land.  I thought that #tab=2 would be a nice way to ensure that any differences originating due to convenience formatting wouldn't muck things up elsewhere.

答:
Most of the problems that you are describing deal with text editors, not the language itself.

To start with, who do you know that is hitting the space bar 4 times? Every editor I have is setup to insert 4 spaces when you hit the tab button. That is very standard procedure. Unless you are using Notepad, then the problem is that you need to reconfigure your dev environment.

Second, why are you "sharing and mixing code" in a way that implies that everything is happening within one file? And how would a macro at the beginning of the file change anything?

At the end of the day, standard practice is to use 4 spaces as a tab in Python. Use it, get used to it, and heavily chastise anyone who deviates from it.


答:
Python has established a format: Use spaces.

Quoting from the Python Styleguide (PEP 8):

Spaces are the preferred indentation method.

Tabs should be used solely to remain consistent with code that is already indented with tabs.

Python 3 disallows mixing the use of tabs and spaces for indentation.

Python 2 code indented with a mixture of tabs and spaces should be converted to using spaces exclusively.

Any decent text editor lets you configure how tabs should be handled, including converting all tabs to a fixed number of spaces. I have Sublime Text configured to 4 spaces, the recommended PEP 8 indentation size:

Use 4 spaces per indentation level.

Title: Why doesn't Python just establish a format for declaring tab widths?

Body:
I've read the flame wars over the use of spaces and tabs. When working with any markup language (when scope isn't very important and when pressing space 4 times is a PITA), I tend to minimize the tab width to just a space or two but I fluidly change to four full tabs for my other programming work.

It is a matter of convenience most of the time and it only translates into real errors when sharing or mixing code.  So why they don't just declare a format for optional overrides such as #tab = 2 at the beginning of a file?  There would be no scoping issues and it could be handled with 2 lines of code.

Update

Whoa, I didn't explain myself very clearly: I only use editors that handle the tab/space conversion automatically.  The only cogent point I can understand in the criticisms I have read regarding Pythons use of white space is how borked the space/tab convention becomes when sharing code.

Perhaps my confusion about using "4 spaces" is because of my prior life in the publishing industry and our use of tabs not as a unit of white space but an abstract element used to describe a document's structure, not the display. Substituting it with 4 spaces has more to do with Unix's shitty 8-space convention than it does with elegance.  If Python standardized on using tabs by default we would eliminate the layer of abstraction (literal visual spaces -> abstract tab) that is getting lost when we leave IDE land and go to Usenet/chat/email land.  I thought that #tab=2 would be a nice way to ensure that any differences originating due to convenience formatting wouldn't muck things up elsewhere.


答:
What is the code behind the API doing?  If it is something flexible then a flexible API is good.  If the code behind the API is very specific then putting a flexible face on it just means users of the API are going to be frustrated and annoyed at all the stuff the API pretends is possible but can't actually be accomplished.

For your person search example are all three fields required?  If so then the criteria list is bad because it allows for a multitude of uses that just plain do not work.  If not then requiring the user to specify non required inputs is bad.  How likely is search by address going to be added in V2?  The flexible interface makes that easier to add than the inflexible one.

Not every system needs to be an ultra flexible, trying to make everything so is Architecture Astronauting.  A flexible bow shoots arrows. A flexible sword is as useful as a rubber chicken.

Title: API design: concrete vs. abstract approach - best practices?

Body:
When discussing APIs between systems (on the business level) there are often two different point of views in our team: some people prefer a more - lets say - generic abstract approach, other a straight forward "concrete" approach.

Example: the design of a simple "person search" API. the concrete version would be

```<code> searchPerson(String name, boolean soundEx,
              String firstName, boolean soundEx,
              String dateOfBirth)
</code>```

People in favour of the concrete version say:

the API is self-documenting

it is easy to understand

it is easy to validate (compiler or as a webservice: schema validation)

KISS

The other group of people in our team would say "That is just a list of search criteria"

```<code>searchPerson(List<SearchCriteria> criteria)
</code>```

with

```<code>SearchCritera {
  String parameter,
  String value,
  Map<String, String> options
}
</code>```

with possibly making "parameter" of some enumeration type.

Proponents say:

without changing the (declaration of) the API the implementation can change, e.g. adding more criteria or more options. Even without synchronizing such a change at deployment time.

documentation is necessary even with the concrete variant

schema validation is overrated, often you have to validate further, schema cannot handle all cases

we already have a similiar API with another system - reuse

The counter-argument is

lots of documentation about valid parameters and valid parameter combinations

more communication effort because it's more difficult to understand for other teams

Are there any best practices? Literature?


问:
Method parameter takes object from it's own class?
I'm not absolutely sure if this is the right place for this question. But I guess StackOverflow won't be the right place.

Is it for any reason a bad way to pass an object to a method from the same class? For some reason I don't feel well with the first solution.

The method Start starts the game with the given player.

```<code>CurrentGame.Start(CurrentGame.CurrentPlayer);
</code>```

or

```<code>CurrentGame.StartWithCurrentPlayer();
</code>```

But the last method could require a second method like:

```<code>public void SetCurrentPlayer(Player player)
{
    CurrentPlayer = player;
}
</code>```

答: The first way seems best (CurrentGame.Start(CurrentGame.CurrentPlayer);). You can then feed it whatever player you want. it just happens by coincidence that your example uses an established player from your current scope.


问:
.NET MVC project architecture / layering
When planning the architecture for a mid-large scale MVC web application how do you implement the layers to be as decoupled as possible and easy to test? (basically follow best practices) Let's say I'm using code first as my data access.

I struggle with what to define "business logic" as, and how it is meant to interact with the data layer. Taking a vehicle sales application as an example, would business logic be classes that performed tasks such as calculating the tax band for given vehicles, comparing mile per gallon statistics etc? As for the business entities (e.g. Cars, Vans, Motorcycles) I would put these in the data layer along with my DataContext class.

Also what would constitute application logic as opposed to business - I'm guessing things like session / user input validations?

So for example, a car controller might return an action/view result that lists the top ten cars filtered by type and best mpg. So let's say I have an ICarRepository 'carRepo' injected into my controller(using the repository pattern / DI), I filter my cars from an action method parameter e.g. var cars = carRepo.getCarsByType("hatchback");

So I've kept the data access knowledge out of my controller using a repository, now to keep the business logic out of the controller using a domain model - var result = new MpgCalculator(cars); - Let's say I need the calculator class because it needs to perform additional logic to calculate the best fuel efficiency, more than just loading / filtering entities from the DB. So now I have a data set for my view to render that used a repository to retrieve from the data access layer, and domain specific object to process and perform business related tasks on that data.

Am I making mistakes here? do we still need to use the repository pattern or can I just code against an interface to decouple the ORM and test? On this topic, as my concrete data access classe(s) dbcontext are in the data layer, should the interface definitions go into the domain/business layer meaning that if the data access technology is ever changed, my other layers aren't effected?

From what I have studied thus far my structure looks like this:

MVC Internet Application -> The standard internet project - models in here are ViewModels

Domain/Business layer -> business specific classes/models that controllers can use to process domain entities from the data layer before passing on to the relevant views

Repository abstraction necessary? -> I hear lots of debate on this, especially when using an ORM

Data layer -> Entity classes (Car, Van, Motorcycle), DbContext - Concrete data access technology layer

答:
It looks like everything is correct for your structure.  The only thing that I am not sure about is that you mention that the models in MVC are "ViewModels" and that your controllers talk to the domain layer.  I think this makes sense if your default pattern is to use the controller to access the domain layer and then using your "ViewModels" as more view-specific compilations of information from multiple domain entities as makes sense for that particular view.  If that is what you are doing, then you are likely ok.

There is a school of thought that you should have a complete abstraction of your domain layer in your MVC application if you are going to have any.  Personally, the thought of doing that in an enterprise application causes me severe mental pains.

I prefer using the repository pattern to manage the access to the Data Layer as it enhances testability and flexibility.  The two things that tend to make the most drastic changes are the UI and the database.  Imagine if some of the information that you are pulling directly out of the database is changed so that it has to be retrieved from a service call rather than a database call, or some of the information is moved to a different database requiring a different .edmx file.  The repository pattern provides abstraction to support this.

ContentLicense: CC BY-SA 4.0


答:
Personally I'd go with the first option, because I find methods like the second option too specific. However if you had an array of players in your class, you could pass the array index instead.

Inside CurrentGame you would have something like the below for a four player game:

```<code>Player[] players = new Player[4];
</code>```

Then to start the players:

```<code>CurrentGame.Start(0);
CurrentGame.Start(1);
CurrentGame.Start(2);
CurrentGame.Start(3);
</code>```

Title: Method parameter takes object from it's own class?

Body:
I'm not absolutely sure if this is the right place for this question. But I guess StackOverflow won't be the right place.

Is it for any reason a bad way to pass an object to a method from the same class? For some reason I don't feel well with the first solution.

The method Start starts the game with the given player.

```<code>CurrentGame.Start(CurrentGame.CurrentPlayer);
</code>```

or

```<code>CurrentGame.StartWithCurrentPlayer();
</code>```

But the last method could require a second method like:

```<code>public void SetCurrentPlayer(Player player)
{
    CurrentPlayer = player;
}
</code>```

Body:
Personally I'd go with the first option, because I find methods like the second option too specific. However if you had an array of players in your class, you could pass the array index instead.

Inside CurrentGame you would have something like the below for a four player game:

Player[] players = new Player[4];

Then to start the players:

CurrentGame.Start(0);
CurrentGame.Start(1);
CurrentGame.Start(2);
CurrentGame.Start(3);


答:
This is a notably succinct, demonstrative, explanation of the problem, the potential solutions, and in my opinion; and contrary to Joel's exuberance about his new Mercurial tool;  a fatal blow to the entire idea of getting out of multi-user editing conflicts easily.

http://hginit.com/04.html

Note the 'graphical tool' that Joel uses when a merge conflict appears.  This is virtually no improvement on Visual SourceSafe, which has been maligned for decades, but still serves it's essential purpose.  But that purpose is not merging automatically.  Without proper architecture of your CSS classes / files, source control is hardly going to help you.

Title: CSS File Editing for Teams? (how to avoid stepping on each others' feet?!)

Body: I'm wondering if anyone has a good solution for when you're working as a team and there's a single file used throughout a project (like a styles.css file) and everyone needs to use it throughout the day - inevitably someone will make changes and save without grabbing the most recent version first. Is there some sort of group editing program for Windows/web? We currently just access the CSS files via FTP & edit in our usual editors. Probably an editor that can load & save changes on the fly?</p>


答:
Use version control.

If you find your team is uncomfortable with merges and it doesn't cause too much of a bottleneck, you could use a VCS that supports locking such as SVN or Veracity.

In Veracity, the workflow would be something like:

```<code>vv lock styles.css
# make changes to the file
vv commit
vv push
</code>```

Each team member must remember to lock the file before editing. If someone else has the file locked they will be told to wait their turn.

Body:
Use version control.

If you find your team is uncomfortable with merges and it doesn't cause too much of a bottleneck, you could use a VCS that supports locking such as SVN or Veracity.

In Veracity, the workflow would be something like:

vv lock styles.css
# make changes to the file
vv commit
vv push

Each team member must remember to lock the file before editing. If someone else has the file locked they will be told to wait their turn.


问:
Which http response do you return to a hit from a blacklisted ip?
I have been using the http:BL to block bad IP's from accessing my site.

If a malicious IP (comment spammer) trys to hit the site I just exit the web script which implicitly returns a 200 OK response.

Other responses I could return:

404 - Not found?

If I return a 404 maybe the robots will think "this is a waste of time, lets move on to attack another site" which would reduce the load on the site (I currently get about 2 spam-hits per second).

However

I'm reluctant to return 404's on urls that, under normal circumstances, can be found.

I'm not sure if spam robots can 'waste time'. i.e Why would a bot writer be bothered to code for 404's when they just blitz the web anyway?

401 Unauthorized?

Blocking a bad IP is not quite the same as "resource requires user authentication 1) which has not yet been provided or 2) which has been provided but failed authorization tests"

In general I feel that 'responding to the bad-bots according to proper http protocol' gives the bad guys the upper hand. In the sense that I play by the rules while they do not. On some days I feel like I should do something clever to divert these bot's away. On other days I just think that I should not take it personally and just ignore them. Accepting it as par for the course of running a web site.

I dunno - what are your thoughts? How do you respond when you know its a bad IP?

答:
If you want to play by the rules, 403 Forbidden, or 403.6 IP address rejected (IIS specific) would be the correct response.

Giving a 200 response (and ignoring the comment) may just increase the load on the server, as the spam bot will presumably continue submitting spam on future occasions, unaware that it is having no effect. A 4XX response at least says "go away you need to check your facts" and is likely to diminish future attempts.

In the unlikely event you have firewall access, then a block of blacklisted IP addresses at the firewall would minimize server load / make it appear that your server didn't exist to the spammer.

I was going to suggest using a 302 Temporary Redirect to the spammer's own IP address  - but this would probably have no effect as there would be no reason for the bot to follow the redirect.

If dealing with manually submitted spam, making the spam only visible by the IP address that submitted it is a good tactic. The spammer goes away happy and contented (and does not vary his approach to work around your defences), and the other users never see the spam.


答:
You've got a lot of moving parts in your question, touching on a lot of concepts, but here's my basic advice when it comes to how to think about a mid-to-large scale MVC application:

Presentation <---> Business Logic <---> Data Access

Firstly, it's best to not think of the the app as "an MVC application". It's an application that uses the MVC pattern as its presentation component. Thinking about it this way will help you separate out your business logic concerns from your presentation concerns. Perhaps it's ok for small applications to pile everything down to database access into the MVC structure, but it'll quickly become untenable for a mid-to-large application.

MVC (Presentation)

In your app, the ASP.NET MVC component should deal with transforming business data for display purposes (Models), displaying the user interface (Views), and communication issues such as routing, authentication, authorization, request validation, response handling, and the like (Controllers). If you have code that does something else, then it doesn't belong in the MVC component.

Repository/ORM (Data Access)

Also in your app, the data access layer should be concerned with retrieving and storing persistent data. Commonly that's in the form of a relational database, but there are many other ways data can be persisted. If you have code that isn't reading or storing persistent data, then it doesn't belong in the data layer. I shared my thoughts on the ORM/Repository discussion previously on SO, but to recap, I don't consider an ORM to be the same thing as a Repository, for several reasons.

Business Logic

So now you have your presentation layer (MVC), and your data layer (repository or ORM) ... Everything else is your business logic layer (BLL). All of your code that decides which data to retrieve, or performs complicated calculations, or makes business decisions, should be here. I usually organize my business logic in the form of 'services', which my presentation layer can call upon to do the work requested. All of my domain models exist here.

Your Approach

This is where your approach breaks down a little for me. You describe your MVC controller as the place you would get data from the repository, and call upon the MPGCalculator to do some work, etc. I would not have my controller do any of this, but instead would delegate all of this off to a service in the BLL.

In other words, I would not inject a repository and MPGCalculator into the controller, that's giving the controller too much responsibility (it's already handling all of the controller stuff I mentioned above). Instead, I would have a service in the BLL handle all of that, and pass the results back to the controller. The controller can then transform the results to the correct model, and pass that on to the correct view. The controller doesn't have any business logic in it, and the only things injected into the controller would be the appropriate BLL services.

Doing it this way means your business logic (for example, given a set of vehicles, calculate the MPG and sort best to worst) is independent from presentation and persistence concerns. It'll usually be in a library that doesn't know or care about the data persistence strategy nor the presentation strategy.

Title: .NET MVC project architecture / layering

Body:
When planning the architecture for a mid-large scale MVC web application how do you implement the layers to be as decoupled as possible and easy to test? (basically follow best practices) Let's say I'm using code first as my data access.

I struggle with what to define "business logic" as, and how it is meant to interact with the data layer. Taking a vehicle sales application as an example, would business logic be classes that performed tasks such as calculating the tax band for given vehicles, comparing mile per gallon statistics etc? As for the business entities (e.g. Cars, Vans, Motorcycles) I would put these in the data layer along with my DataContext class.

Also what would constitute application logic as opposed to business - I'm guessing things like session / user input validations?

So for example, a car controller might return an action/view result that lists the top ten cars filtered by type and best mpg. So let's say I have an ICarRepository 'carRepo' injected into my controller(using the repository pattern / DI), I filter my cars from an action method parameter e.g. var cars = carRepo.getCarsByType("hatchback");

So I've kept the data access knowledge out of my controller using a repository, now to keep the business logic out of the controller using a domain model - var result = new MpgCalculator(cars); - Let's say I need the calculator class because it needs to perform additional logic to calculate the best fuel efficiency, more than just loading / filtering entities from the DB. So now I have a data set for my view to render that used a repository to retrieve from the data access layer, and domain specific object to process and perform business related tasks on that data.

Am I making mistakes here? do we still need to use the repository pattern or can I just code against an interface to decouple the ORM and test? On this topic, as my concrete data access classe(s) dbcontext are in the data layer, should the interface definitions go into the domain/business layer meaning that if the data access technology is ever changed, my other layers aren't effected?

From what I have studied thus far my structure looks like this:

MVC Internet Application -> The standard internet project - models in here are ViewModels

Domain/Business layer -> business specific classes/models that controllers can use to process domain entities from the data layer before passing on to the relevant views

Repository abstraction necessary? -> I hear lots of debate on this, especially when using an ORM

Data layer -> Entity classes (Car, Van, Motorcycle), DbContext - Concrete data access technology layer


答:
First option is better as @brad already answered but i would like to suggest to not access CurrentPlayer explicitly but instead use a getter getCurrentPlayer(). IMHO you should have a setter too setCurrentPlayer. Maybe today you don´t have much computation to do and setCurrentPlayer is just an assignment as your example but if you already use setters / getters you have encapsulated all logic related to setCurrentPlayer inside a method.

Getters & Setters are a well known design pattern. You can find more about it here (http://en.wikipedia.org/wiki/Getter/setter) for example.


问:
How do I create every permutation
I have a list of letters, this is just an example list:

```<code>['a','b','c','d','e']
</code>```

How do I compute every combination of the list? The letters cannot repeat, for example.

```<code>a,b,c,d,e
a,c,b,d,e
a,c,d,b,e
a,c,d,e,b
a,e,d,c,b
...
</code>```

答:
The simple answer for Python is the itertools library.  That's it, you're done with it.

In Ruby, it's part of the Array class.

```<code>$ irb
>> a = [1, 2, 3]
=> [1, 2, 3]
>> a.permutation.to_a
=> [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
</code>```

However, this is a very boring answer and doesn't help anyone who (despite the tag and me pointing to other languages too) is trying to find out how to create every permutation of a set.

The basic approach to this you iterate over each item in the set, and generate the permutations of all of the remaining set.

The simple approach to this is a backtracking model.  The method do() does whatever one wants to do, be it print out or calculate with it further.

```<code>exchange (x, y) {
    return y, x;
}
generate (n) {
    int c;
    if(n = 1) do();
    for (c = 1; c < n; c++)
        {  exchange(c,n); generate(n-1); exchange(c,n); }
}
</code>```

This algorithm does 2n! exchanges.

Heap's method is a simple recursive approach.  Consider the following

```
-*-*-*-*-*-
 | | | | |
-*-|-*-|-*-
   |   |
---*---*---
a b c a b c
b a a c c b
c c b b a a
```

You start out with abc, and then swap 1 and 2, then 1, 3, then 1, 2, then 1, 3, then 1, 2.  If you have 4 elements, after this sequence of pattern is completed
you swap 1, 4 - then another sequence and 2, 4, and another sequence and 3, 4.

If it was 5, then you'd repeat the sequence of 4, and then do 1, 5, then 2, 5, then 3, 5.  You should get the idea.

Writing this recursively is rather straight forward.

```<code>generate(n) {
    int c;
    if (n == 1) { do(); return; }
    for (c = 1; c <= n; c++) {
        generate(n-1);
        exchange(n % 2 ? 1 : c, n)
    }
}
</code>```

If you really want to read more about this, The Art of Computer Programming
 Volume 4, Combinatorial Algorithms, section 7.2.1.2 is titled "Generating All Permutations" that goes deeply into the math.

Title: How do I create every permutation

Body:
The simple answer for Python is the itertools library.  That's it, you're done with it.

In Ruby, it's part of the Array class.

$ irb
>> a = [1, 2, 3]
=> [1, 2, 3]
>> a.permutation.to_a
=> [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

However, this is a very boring answer and doesn't help anyone who (despite the tag and me pointing to other languages too) is trying to find out how to create every permutation of a set.

The basic approach to this you iterate over each item in the set, and generate the permutations of all of the remaining set.

The simple approach to this is a backtracking model.  The method do() does whatever one wants to do, be it print out or calculate with it further.

exchange (x, y) {
    return y, x;
}
generate (n) {
    int c;
    if(n = 1) do();
    for (c = 1; c < n; c++)
        {  exchange(c,n); generate(n-1); exchange(c,n); }
}

This algorithm does 2n! exchanges.

Heap's method is a simple recursive approach.  Consider the following

-*-*-*-*-*-
 | | | | |
-*-|-*-|-*-
   |   |
---*---*---
a b c a b c
b a a c c b
c c b b a a

You start out with abc, and then swap 1 and 2, then 1, 3, then 1, 2, then 1, 3, then 1, 2.  If you have 4 elements, after this sequence of pattern is completed
you swap 1, 4 - then another sequence and 2, 4, and another sequence and 3, 4.

If it was 5, then you'd repeat the sequence of 4, and then do 1, 5, then 2, 5, then 3, 5.  You should get the idea.

Writing this recursively is rather straight forward.

generate(n) {
    int c;
    if (n == 1) { do(); return; }
    for (c = 1; c <= n; c++) {
        generate(n-1);
        exchange(n % 2 ? 1 : c, n)
    }
}

If you really want to read more about this, The Art of Computer Programming
 Volume 4, Combinatorial Algorithms, section 7.2.1.2 is titled "Generating All Permutations" that goes deeply into the math.


答:
This depends, in part, on which piece of code is responsible for controlling who the current player is. Is it CurrentGame or the code that uses CurrentGame ("the caller")?

If CurrentGame is responsible for setting the next player after CurrentPlayer's turn is over, then exposing SetCurrentPlayer would give the caller a way interfere with CurrentGame's state. For example, if player A finishes her turn, CurrentGame would set the CurrentPlayer to Player B; however, the caller could use this method to set CurrentPlayer back to Player A before Player B's turn is over.

If the caller is responsible:

Your first option would be workable, although the caller might be overly dependent on using a property of CurrentGame to remember who was playing the last game.

If CurrentGame is responsible:

Consider a different approach, such as:

```<code>CurrentGame.SetPlayers(OrderedList<Player>)
</code>```

The caller would pass in the list of players that is ordered according to the sequence of their turns. CurrentGame would just then set CurrentPlayer to the first player in the list when the game starts.

Body:
This depends, in part, on which piece of code is responsible for controlling who the current player is. Is it CurrentGame or the code that uses CurrentGame ("the caller")?

If CurrentGame is responsible for setting the next player after CurrentPlayer's turn is over, then exposing SetCurrentPlayer would give the caller a way interfere with CurrentGame's state. For example, if player A finishes her turn, CurrentGame would set the CurrentPlayer to Player B; however, the caller could use this method to set CurrentPlayer back to Player A before Player B's turn is over.

If the caller is responsible:

Your first option would be workable, although the caller might be overly dependent on using a property of CurrentGame to remember who was playing the last game.

If CurrentGame is responsible:

Consider a different approach, such as:

CurrentGame.SetPlayers(OrderedList<Player>)

The caller would pass in the list of players that is ordered according to the sequence of their turns. CurrentGame would just then set CurrentPlayer to the first player in the list when the game starts.


问:
Functional programming and stateful algorithms
I'm learning functional programming with Haskell. In the meantime I'm studying Automata theory and as the two seem to fit well together I'm writing a small library to play with automata.

Here's the problem that made me ask the question. While studying a way to evaluate a state's reachability I got the idea that a simple recursive algorithm would be quite inefficient, because some paths might share some states and I might end up evaluating them more than once.

For example, here, evaluating reachability of g from a, I'd have to exclude f both while checking the path through d and c:

So my idea is that an algorithm working in parallel on many paths and updating a shared record of excluded states might be great, but that's too much for me.

I've seen that in some simple recursion cases one can pass state as an argument, and that's what I have to do here, because I pass forward the list of states I've gone through to avoid loops. But is there a way to pass that list also backwards, like returning it in a tuple together with the boolean result of my canReach function? (although this feels a bit forced)

Besides the validity of my example case, what other techniques are available to solve this kind of problems? I feel like these must be common enough that there have to be solutions like what happens with fold* or map.

So far, reading learnyouahaskell.com I didn't find any, but consider I haven't touched monads yet.

(if interested, I posted my code on codereview)

答:
Here's a simple answer relying on mapConcat.

```<code> mapConcat :: (a -> [b]) -> [a] -> [b]
 -- mapConcat is in the std libs, mapConcat = concat . map
 type Path = []

 isReachable :: a -> Auto a -> a -> [Path a]
 isReachable to auto from | to == from = [[]]
 isReachable to auto from | otherwise =
    map (from:) . mapConcat (isReachable to auto) $ neighbors auto from
</code>```

Where neighbors returns the states immediately connected to a state. This returns a series of paths.

Body:
Here's a simple answer relying on mapConcat.

 mapConcat :: (a -> [b]) -> [a] -> [b]
 -- mapConcat is in the std libs, mapConcat = concat . map
 type Path = []

 isReachable :: a -> Auto a -> a -> [Path a]
 isReachable to auto from | to == from = [[]]
 isReachable to auto from | otherwise =
    map (from:) . mapConcat (isReachable to auto) $ neighbors auto from

Where neighbors returns the states immediately connected to a state. This returns a series of paths.


问:
Is there any reason zero should still equal false in a new programming language?
I understand that 0 is false because math established that a long time ago and C established it in the programming world, as talked about here.  However, other than following established conventions, is there any reason a new programming language shouldn't make 0 equal to true?  It seems like it would solve a lot of problems, such as in situations where 0 is a valid return value of a function (like when returning an index).

For example, assume I'm working with a grid where a user can select rows:

```<code>function getSelectedRowIndex()
{
    //return the index of the selected row - assume the first row is selected, returning 0
}

var selectedRowIndex = getSelectedRowIndex();  //returned 0

//the following will be evaluated as true, despite a valid row being selected
if (!selectedRowIndex)
{
    alert("Please select a row before continuing.");
}
</code>```

I see this bug over and over again in multiple people's code.  It's just much more convenient to evaluate a variable by itself.  Making 0 equal to true would eliminate this potential bug.  This is just one example, and I'm sure most people could think of others.

So we've established there is some value in making 0 equal to true, but what is the value in keeping it equal to false past sticking to what's always been done?

答:
My best answer, from the mass of others discussed.

This convention comes from Assembly.

When you do a comparison, e.g.    if a > b or  if a = b

what actually happens ( at least in motorola 6502 ) is the processor will SUBTRACT the two values! then then result is easily branchable, because it is either zero, or something other than zero.

the branch instruction is made to work with zero being an optimized value because typically you want to branch when an array index reaches zero.

thus, branchng is optimized for zeros, and thus branching based on comparison has evolved to use zero to indicate true of false of a boolean operation like = or >.

PS

Also because a bit by bit comparison of two numbers is basically the same thing as a bit by bit subtraction using the [Adder] http://en.wikipedia.org/wiki/Adder–subtractor in the ALU.  so this way, you don't have extra instructions laying around.  But if you use subtraction for boolean comparison you have to allow that the result of the integer subtraction being zero will mean that something is true or false. thus false is zero.

SOOOOOOOOOOO

i guess the reason for keeping it this way is that because originally, there were good reasons for doing this besides ' we felt like it'. those good reasons i suspect are highly irrelevant now, but, OTOH deep down, i also suspect the same optimizations occur with booleans in modern languages

Wikipedia notes that:

Zero Flag

Determining whether two values are equal requires the ALU to determine whether the result is zero. This can be accomplished by feeding each bit of the result into a NOR gate. The beauty of this is that a single multi-port NOR gate requires less hardware than an entire array of equivalent 2-port gates.

http://en.wikibooks.org/wiki/Microprocessor_Design/ALU_Flags

So, zero has a special meaning for CPUs and ALUs.  That is why zero is false.

i suspect that ALU design has not trancended this fundamental design optimization, even in the newest processsors, and as such, people writing compilers in assembly or close to assembly languages are probably still faced with the 'dirtiness' of equating zero with false.  And you should know about all this too.  just because.

http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html

"A lot of programmers that you might interview these days are apt to consider recursion, pointers, and even data structures to be a silly implementation detail which has been abstracted away by today’s many happy programming languages. “When was the last time you had to write a sorting algorithm?” they snicker.

Still, I don’t really care. I want my ER doctor to understand anatomy, even if all she has to do is put the computerized defibrillator nodes on my chest and push the big red button, and I want programmers to know programming down to the CPU level, even if Ruby on Rails does read your mind and build a complete Web 2.0 social collaborative networking site for you with three clicks of the mouse."

http://www.joelonsoftware.com/articles/GuerrillaInterviewing3.html


问:
How do you deal with the anxiety of not knowing enough?
I just finished college a couple of months ago and I'm taking time out to improve my knowledge. I love programming but I feel like I don't know enough to be confident if I went for an interview. Last night I was browsing through questions and came across a question that asks interviewees how to work out a linked list. I learned these at college but if I was asked on the spot how to do it I wouldn't know. So that's another thing added to the list of what to learn.

This is when the anxiety hit me because I have so much to learn in so little time (at least it feels that way). Upon introspection, I think this anxiety is related to my perfectionism even though being perfect isn't rational e.g. Shakespeare and Einstein failed 80% of the time.

So the questions are, have you felt this anxiety of not knowing enough? If so, how did you deal with it? I suppose there's a point in time when you begin to feel comfortable in your abilities?

答:
This sounds like a perfect example of the Dunning-Kreuger effect: http://en.wikipedia.org/wiki/Dunning%E2%80%93Kruger_effect

To very breifly summarize this:
People who are unskilled frequently overestimate their ability, they don't know how much they don't know and this leads to overconfidence.
People who are more skilled realize the flaws in their ability and (somewhat paradoxically) this actually leads to lower confidence.

Just remember that most people do not know how much they do not know. The fact that you are asking this question indicates a level of self awareness that many people simply don't have. There are many studies on this topic from many different authors.

Assuming that you need to know everything is a misunderstanding of the learning process because there will always be things that you don't know. Learning more will still not change the fact that there is more yet to learn, the main thing that changes is awareness of how much you know. Because of the staggering amount of information in the world of programming you can't know everything, so once you get beyond the fundamentals the really crucial skill is being able to find the information that you need when you need it.

As for the confidence in interviews part, just remember that your lack of confidence might actually be from having more, not less, skill/knowledge in the area that. Hopefully that helps!


问:
What does "because IL offers no instructions to manipulate registers, it is easy for people to create new languages" mean?
I am reading CLR via C# and came across this sentence in the first chapter and I did not understand what exactly it meant.

Full line here:

because IL offers no instructions to manipulate registers, it is easy for people to create new languages and compilers that produce code targeting the CLR.

What does it mean?

I ventured a guess that it means IL is a bit low level, but not too low so that it is easy to create languages on top of it.

答: They are saying that allowing a language to use registers ties it closer to a particular CPU architecture.  because the CLR and IL have abstracted this complication away for you, it is 'easier' to create more fully featured applications like compilers, faster and more error free.  because you are never worried about the details of whether your code will be portable beween CPUs, allowing you to focus on adding features to your programs.</p>


问:
What are the reasons for great performance differences running the same program?
I wrote a Python program that has to perform some expensive spatial searches while holding lots of data in memory. I tried to improve the performance, that is tried different approaches (see my question here for example).

First, and maybe not so surprisingly, I found great performance differences when running the same code on two different machines (up to 6 x faster on one machine).

Then however and very much to my own surprise, running the exactly same code on the same machine on two different days showed great performance differences.

To give you a rough idea what I mean by great.

Machine 1, day 1: 11 minutes

Machine 1, day 2: 2 minutes

There was no reboot in the meantime by the way.

What could be possible reasons for this difference? How can I can I make sure my system is ready for high performance when I start running my program?

答:
Radical, unexplained, apparently random changes in execution time are a consequence of the chaotic nature of such complex systems.  and by complex systems, i go so far as to include, BUGS, as part of the complexity.  You may be hitting a major bug somewhere in your programs, a bug that only manifests itself in certain situations and slows your program seemingly randomly ( until you figure it out )

see this bug in SQL server for an example of tracking this down.

http://support.microsoft.com/kb/2570501

so, the point is, you add more processors, your programs gets slower.  until you isolate and correct this bug, a bug in SQL server itself.


问:
Multithreading synchronization interview question: Find n words given m threads

Is there a way this problem could benefit from a solution with multiple threads, rather than a single thread?

In an interview, I was asked to solve a problem using multiple threads. It appears to me that the multiple threads lends no benefit.

Here's the problem:

You are given a paragraph , which contain n number of words, you are
  given m threads. What you need to do is , each thread should print one
  word and give the control to next thread, this way each thread will
  keep on printing one word , in case last thread come, it should invoke
  the first thread. Printing will repeat until all the words are printed
  in paragraph. Finally all threads should exit gracefully. What kind of
  synchronization will use?

I strongly feel we cannot take any advantage of threads here, but believe the interviewer is trying to measure my synchronization skills. Am I missing something in this problem that would make multiple threads have value?

No need of code, just put some thoughts. I will implement by myself.

答:
[Terms used here maybe specific to POSIX threads]

It should be possible to use a FIFO mutex as well to solve this problem.

Where to use :

Assume two threads T1 and T2 are trying to execute a critical section. Both don't have much to do outside this critical section and hold locks for a good amount of time. So, T1 may lock, execute and unlock and signal T2 for wakeup. But before T2 could wakeup and acquire lock, T1 reacquires lock and execute. In this way, T2 may have to wait a very long time before it actually gets the lock or may be not.

How it works / How to implement :

Have a mutex to lock on. Initialize Thread Specific Data (TSD) for each thread to a node containing thread id and semaphore. Also, have two variables - owned (TRUE or FALSE or -1), owner (owner thread id). In addition, keep a waiters queue and a pointer waiterLast pointing to last node in waiters queue.

lock operation :

```<code>node = get_thread_specific_data(node_key);
lock(mutex);
    if(!owned)
    {
        owned = true;
        owner = self;
        return success;
    }

    node->next = nullptr;
    if(waiters_queue == null) waiters_queue = node;
    else waiters_last->next = node;

    waiters_last = node;
unlock(mutex);
sem_wait(node->semaphore);

lock(mutex);
    if(owned != -1) abort();
    owned = true;
    owner = self;
    waiters_queue = waiters_queue->next;
 unlock(mutex);
</code>```

unlock operation :

```<code>lock(mutex);
    owner = null;
    if(waiters_queue == null)
    {
        owned = false;
        return success;
    }
    owned = -1;
    sem_post(waiters_queue->semaphore);
unlock(mutex);
</code>```

Body:
[Terms used here maybe specific to POSIX threads]

It should be possible to use a FIFO mutex as well to solve this problem.

Where to use :

Assume two threads T1 and T2 are trying to execute a critical section. Both don't have much to do outside this critical section and hold locks for a good amount of time. So, T1 may lock, execute and unlock and signal T2 for wakeup. But before T2 could wakeup and acquire lock, T1 reacquires lock and execute. In this way, T2 may have to wait a very long time before it actually gets the lock or may be not.

How it works / How to implement :

Have a mutex to lock on. Initialize Thread Specific Data (TSD) for each thread to a node containing thread id and semaphore. Also, have two variables - owned (TRUE or FALSE or -1), owner (owner thread id). In addition, keep a waiters queue and a pointer waiterLast pointing to last node in waiters queue.

lock operation :

node = get_thread_specific_data(node_key);
lock(mutex);
    if(!owned)
    {
        owned = true;
        owner = self;
        return success;
    }

    node->next = nullptr;
    if(waiters_queue == null) waiters_queue = node;
    else waiters_last->next = node;

    waiters_last = node;
unlock(mutex);
sem_wait(node->semaphore);

lock(mutex);
    if(owned != -1) abort();
    owned = true;
    owner = self;
    waiters_queue = waiters_queue->next;
 unlock(mutex);

unlock operation :

lock(mutex);
    owner = null;
    if(waiters_queue == null)
    {
        owned = false;
        return success;
    }
    owned = -1;
    sem_post(waiters_queue->semaphore);
unlock(mutex);


问:
Pure Java web browser, is it practical?
I know that a Java web browser is possible, but is it practical? I've seen the Lobo project and must admit I am impressed, but from what I've gathered it seems that development stopped in 2009. Would a browser coded in pure Java (no WebKit java bindings of any type) be able to compete with those among the ranks of Chrome or Firefox, or would it be inherently slower, hindering the user?</p>

答:
Sure it could be done.
And it would make sense too.
No browser supports the full w3c standards for unclear reasons.
On the part of css3 support the browser companies don't support standards either.
-moz-* and -webkit-* will never be part of the standard.
So a full standards compliant browser should ignore them.
One of the biggest mistakes from w3c is the total lack of rendering specifications.
So the same standards compliant web page would look different in every browser, a graphical design nightmare.
Another w3c fail is the lack of speed.
5 years discussion and still only a draft standard for html5?
Then your organization is blocking any serious innovation.

I think we should ignore w3c, ignore their specs and make a community standard within a half year for a web application markup language WITH rendering specs and security in mind.
Remember HTML was never designed for web applications, because there were no web applications at the time sgml was used as the basis for HTML.

Title: Pure Java web browser, is it practical?


问:
How do you organize your local development environment?

Possible Duplicate:

  How do you organize your projects folders?

I'm interested to learn how everyone keeps their local development projects organized in a logical manner. What do you do to keep your dev projects organized in a manner that allows you to easily find things?

答:
At any given time, I normally have several different clients, each of whom has one or more projects. I also use a mainline-with-branching development model, which works well with many version control systems like git and Perforce.

So on any one of my development machines, above the individual project level, things look like this:

```<code>Client 1 Directory
    Project Foo Directory
        Main Branch Directory
        All Branches In One Directory (useful for Perforce branching/merging)
        Simple Fixes Branch Directory
        Big Ongoing Feature 1 Directory
        Big Ongoing Feature 2 Directory
        (etc.)
    Project Bar Directory
        (similar branch directories)
Client 2 Directory
    Project Baz Directory
</code>```

and so on. I don't typically pull all branches onto any given machine, or pull Mac projects onto a Windows or Linux box.

Individual branches usually look something like this:

```<code>Build Instructions Document/Checklist
Top-Level Makefile/Project
Source (Directory)
   Main Source Files
   Component 1 Source Directory
   Component 2 Source Directory
   (etc.)
Include (Directory for headers exposed to the outside world, if suitable)
ThirdParty (Libraries, source code, etc. from elsewhere)
Unit Tests
</code>```

Of course, there's a lot of variation. And if I take over a project somebody else started, I usually retain their existing hierarchy.

I typically keep documentation and test files either attached to a wiki in my issue tracking system (Redmine), or if they're bigger than Redmine's default 5 MB limit, on an FTP server, so I don't have to keep local copies on all my development machines, but can retrieve them as I need them.

Body:
At any given time, I normally have several different clients, each of whom has one or more projects. I also use a mainline-with-branching development model, which works well with many version control systems like git and Perforce.

So on any one of my development machines, above the individual project level, things look like this:

Client 1 Directory
    Project Foo Directory
        Main Branch Directory
        All Branches In One Directory (useful for Perforce branching/merging)
        Simple Fixes Branch Directory
        Big Ongoing Feature 1 Directory
        Big Ongoing Feature 2 Directory
        (etc.)
    Project Bar Directory
        (similar branch directories)
Client 2 Directory
    Project Baz Directory

and so on. I don't typically pull all branches onto any given machine, or pull Mac projects onto a Windows or Linux box.

Individual branches usually look something like this:

Build Instructions Document/Checklist
Top-Level Makefile/Project
Source (Directory)
   Main Source Files
   Component 1 Source Directory
   Component 2 Source Directory
   (etc.)
Include (Directory for headers exposed to the outside world, if suitable)
ThirdParty (Libraries, source code, etc. from elsewhere)
Unit Tests

Of course, there's a lot of variation. And if I take over a project somebody else started, I usually retain their existing hierarchy.

I typically keep documentation and test files either attached to a wiki in my issue tracking system (Redmine), or if they're bigger than Redmine's default 5 MB limit, on an FTP server, so I don't have to keep local copies on all my development machines, but can retrieve them as I need them.


答:
I read this to refer to the choice of execution model, not to exposing lower-level details of the hardware architecture. The CLR is primarily a stack machine, meaning opcodes operate on a stack. The other common option in VM design space is the register machine, where a (usually unlimited) set of virtual registers is manipulated instead. These registers are an abstraction provided by the VM (much like the stack in the alternative), so it is hardware-independent and has to be mapped to hardware registers for faster execution. Examples are the Lua VMs (both the reference implementation and LuaJIT), Dalvik, and the experimental (for other reasons) Python VM Falcon.

If my reading is correct, the remarks simply refers to the fact that it's a bit easier to generate stack opcodes from an AST than it is to generate register opcodes. On a stack VM, each (or at least most) AST nodes can generate opcodes like this:

```<code>child1.codegen()
...
childN.codegen()
emit(OPCODES_FOR_THIS_OPERATION)
</code>```

for example, for addition:

```<code>lhs.codegen()
rhs.codegen()
emit(ADD)
</code>```

In contrast, a register-based VM needs to carry around at least some state to manage which register all the temporary values are put in. And if it wants to avoid using far too many registers, some slightly non-trivial optimizations are needed (to re-use registers, or more generally perform register allocation).

Title: What does "because IL offers no instructions to manipulate registers, it is easy for people to create new languages" mean?

Body:
I am reading CLR via C# and came across this sentence in the first chapter and I did not understand what exactly it meant.

Full line here:

because IL offers no instructions to manipulate registers, it is easy for people to create new languages and compilers that produce code targeting the CLR.

What does it mean?

I ventured a guess that it means IL is a bit low level, but not too low so that it is easy to create languages on top of it.

Body:
I read this to refer to the choice of execution model, not to exposing lower-level details of the hardware architecture. The CLR is primarily a stack machine, meaning opcodes operate on a stack. The other common option in VM design space is the register machine, where a (usually unlimited) set of virtual registers is manipulated instead. These registers are an abstraction provided by the VM (much like the stack in the alternative), so it is hardware-independent and has to be mapped to hardware registers for faster execution. Examples are the Lua VMs (both the reference implementation and LuaJIT), Dalvik, and the experimental (for other reasons) Python VM Falcon.

If my reading is correct, the remarks simply refers to the fact that it's a bit easier to generate stack opcodes from an AST than it is to generate register opcodes. On a stack VM, each (or at least most) AST nodes can generate opcodes like this:

child1.codegen()
...
childN.codegen()
emit(OPCODES_FOR_THIS_OPERATION)

for example, for addition:

lhs.codegen()
rhs.codegen()
emit(ADD)

In contrast, a register-based VM needs to carry around at least some state to manage which register all the temporary values are put in. And if it wants to avoid using far too many registers, some slightly non-trivial optimizations are needed (to re-use registers, or more generally perform register allocation).


答:
First, and maybe not so surprisingly, I found great performance differences when running the same code on two different machines (up to 6 x faster on one machine).

Then however and very much to my own surprise, running the exactly same code on the same machine on two different days showed great performance differences.

Performance measurement is a surprisingly hard topic and huge differences such as what you observed are very common. There is a lot of known measurement bias such as:

OS noise, as suggested by DFord's answer

OS policies (such as scheduler, memory mapper and IO-cache)

Environment variables, even unused ones

Memory alignment

Memory localisation

Each of these parameters may greatly influence the performance of your program.  If you want to prepare your program “for high performance” then:

Devise strategies to sanitize environment so that you gain some control over parameters 1-5 above.

Devise tests to determine which combination of parameters do well.

The key point here is that experiments need to be reproducible. If you are not able to reproduce an experiment, then it includes a source of randomness that you need to get a grasp on. And first of all, if you are not able to reproduce an experiment, then the results of the experiments are random and you probably do not want to take decisions based on random values, do you?

While this is not really the question you asked, I guess you are interested in performance measurement.  Here are a few references I suggest to you:

http://compilers.iecc.com/comparch/article/96-02-165

Boehm commenting about execution speed for the same binary
  varying by a factor of 2 depending on cache placement

http://www.inf.usi.ch/faculty/hauswirth/publications/asplos09.pdf

Producing Wrong Data Without Doing Anything Obviously Wrong!
  It is very easy to read, contains surprising results, and give a very
  good feeling of the difficulty of performance measurement and a few
  methods to produce (more) reliable results.

http://plasma.cs.umass.edu/emery/stabilizer

“Stabilizer is a compiler and runtime system that enables statistically
  rigorous performance evaluation.”  There is a scientific publication
  claiming to prove that -O3 and -O2 in gcc are not distinguishable,
  you will find plenty of interesting references in there.

As a final word, you just discovered with your measurements that wall clock does not provide a useful information when it comes to measure performance of programs, so that you will never get a useful answer to a question such as “how long runs my program?” and you have to consider more precise statements.

Title: What are the reasons for great performance differences running the same program?

Body:
I wrote a Python program that has to perform some expensive spatial searches while holding lots of data in memory. I tried to improve the performance, that is tried different approaches (see my question here for example).

First, and maybe not so surprisingly, I found great performance differences when running the same code on two different machines (up to 6 x faster on one machine).

Then however and very much to my own surprise, running the exactly same code on the same machine on two different days showed great performance differences.

To give you a rough idea what I mean by great.

Machine 1, day 1: 11 minutes

Machine 1, day 2: 2 minutes

There was no reboot in the meantime by the way.

What could be possible reasons for this difference? How can I can I make sure my system is ready for high performance when I start running my program?


问:
Does functional programming ignore the benefits gained from the "On the Criteria To Be Used in Decomposing Systems into Modules" (data hiding)?
There's a classic article named On the Criteria To Be Used in Decomposing Systems into Modules that I just read for the first time.  It makes perfect sense to me, and is probably one of those articles that OOP was based on.  Its conclusion:

We have tried to demonstrate by these examples that
  it is almost always incorrect to begin the decomposition
  of a system into modules on the basis of a flowchart.
  ... Each module is then designed to hide
  such a decision from the others

In my uneducated and inexperienced opinion, functional programming takes the exact opposite advice of this article.  My understanding is functional programming makes data flow idiomatic.  Data gets passed from function to function, each function being intimately aware of the data and "changing it" along the way.  And I think I've seen a Rich Hickey talk where he talks about how data hiding is overrated or unnecessary or something, but I can't remember for sure.

First I want to know if my assessment is correct.  Does the FP paradigm and this article philosophically disagree?

Assuming they disagree, how does FP "compensate" for its lack of data hiding?  Perhaps they sacrifice data hiding but gain X, Y and Z.  I'd like to know the reasoning for why X, Y and Z are considered more beneficial than data hiding.

Or, assuming they disagree, perhaps FP feels that data hiding is bad.  If so, why does it think data hiding is bad?

Assuming they agree, I'd like to know what FPs implementation of data hiding is.  It's obvious to see this in OOP.  You can have a private field that nobody outside the class can access.  There's no obvious analogy of this to me in FP.

I feel there are other questions I should be asking but I don't know I should be asking.  Feel free to answer those, too.

Update

I found this Neal Ford talk that has a very relevant slide in it.  I'll embed the screenshot here:

答:
First, thanks for the link to this great article, I did not know this so far, and it gave me some great input about some things which I was discussing with some other software designers from the community in the last years. Here is my opinion about it:

First I want to know if my assessment is correct. Does the FP paradigm and this article philosophically disagree?

FP design focuses very much on data-flow (which is IMHO not so bad as the article may imply). If this is a complete "disagreement" is argueable.

Assuming they disagree, how does FP "compensate" for its lack of data hiding? Perhaps they sacrifice data hiding but gain X, Y and Z. I'd like to know the reasoning for why X, Y and Z are considered more beneficial than data hiding.

IMHO it does not compensate. See below.

Or, assuming they disagree, perhaps FP feels that data hiding is bad. If so, why does it think data hiding is bad?

I don't think most of the FP users or designers do feel or think in this way, see below.

Assuming they agree, I'd like to know what FPs implementation of data hiding is. It's obvious to see this in OOP. You can have a private field that nobody outside the class can access. There's no obvious analogy of this to me in FP.

Here is the point - you have probably seen so many OOP systems implemented in a non-functional way that you believe OOP is non-functional. And that's a fallacy, IMHO OOP and FP are mostly orthogonal concepts, and you can perfectly build functional OO systems, which gives you an obvious answer to your question. The classic "object" implementation in FP is done by utilizing closures, and if you want objects to be used in a functional system, the key point is to design them immutable.

So for creating bigger systems, IMHO you can create modules, classes and objects using OO concepts, exactly the way described under "Modularization 2" in the article without leaving the "FP path". You will use the module concept of your favorite FP language, make just all your objects immutable and use the "best of both worlds".


答:
The article you mention is about modularity in general, and it would apply equally to structured, functional, and object-oriented programs.  I have heard of that article before from someone who was a big OOP guy, but I read it as an article about programming in general, not something OOP specific.  There is a famous article about functional programming, Why Functional Programming Matters, and the first sentence of the conclusion states "In this paper, we’ve argued that modularity is the key to successful programming."  So the answer to (1) is no.

Well designed functions don't assume more about their data than they need to, so the part about "intimately aware of the data" is wrong.  (Or at least as wrong as it would be of OOP.  You can't program strictly at a high level of abstraction and ignore all details forever in any paradigm.  In the end, some part of the program does actually need to know about the specific details of the data.)

Data hiding is an OOP specific term, and it isn't exactly the same as the information hiding discussed in the article.  Information hiding in the article is about design decisions that were hard to make or are likely to change.  Not every design decision about a data format is hard or likely to change, and not every decision that is hard or likely to change is about a data format.  Personally, I can't see why OO programmers want everything to be an object.  Sometimes, a simple data structure is all you need.

Edit:
I found a relevant quote from an interview with Rich Hickey.

Fogus: Following that idea—some people are surprised by the fact that Clojure does not engage in data-hiding encapsulation on its types. Why did you decide to forgo data-hiding?

Hickey: Let’s be clear that Clojure strongly emphasizes programming to abstractions. At some point though, someone is going to need to have access to the data. And if you have a notion of “private”, you need corresponding notions of privilege and trust. And that adds a whole ton of complexity and little value, creates rigidity in a system, and often forces things to live in places they shouldn’t. This is in addition to the other losing that occurs when simple information is put into classes. To the extent the data is immutable, there is little harm that can come of providing access, other than that someone could come to depend upon something that might change. Well, okay, people do that all the time in real life, and when things change, they adapt. And if they are rational, they know when they make a decision based upon something that can change that they might in the future need to adapt. So, it’s a risk management decision, one I think programmers should be free to make.
If people don’t have the sensibilities to desire to program to abstractions and to be wary of marrying implementation details, then they are never going to be good programmers.

Title: Does functional programming ignore the benefits gained from the "On the Criteria To Be Used in Decomposing Systems into Modules" (data hiding)?

Body:
There's a classic article named On the Criteria To Be Used in Decomposing Systems into Modules that I just read for the first time.  It makes perfect sense to me, and is probably one of those articles that OOP was based on.  Its conclusion:

We have tried to demonstrate by these examples that
  it is almost always incorrect to begin the decomposition
  of a system into modules on the basis of a flowchart.
  ... Each module is then designed to hide
  such a decision from the others

In my uneducated and inexperienced opinion, functional programming takes the exact opposite advice of this article.  My understanding is functional programming makes data flow idiomatic.  Data gets passed from function to function, each function being intimately aware of the data and "changing it" along the way.  And I think I've seen a Rich Hickey talk where he talks about how data hiding is overrated or unnecessary or something, but I can't remember for sure.

First I want to know if my assessment is correct.  Does the FP paradigm and this article philosophically disagree?

Assuming they disagree, how does FP "compensate" for its lack of data hiding?  Perhaps they sacrifice data hiding but gain X, Y and Z.  I'd like to know the reasoning for why X, Y and Z are considered more beneficial than data hiding.

Or, assuming they disagree, perhaps FP feels that data hiding is bad.  If so, why does it think data hiding is bad?

Assuming they agree, I'd like to know what FPs implementation of data hiding is.  It's obvious to see this in OOP.  You can have a private field that nobody outside the class can access.  There's no obvious analogy of this to me in FP.

I feel there are other questions I should be asking but I don't know I should be asking.  Feel free to answer those, too.

Update

I found this Neal Ford talk that has a very relevant slide in it.  I'll embed the screenshot here:


问:
What code lays behind C++ exception?
In C and C++ you can return a single variable inside a function. Now in the case that variable is returning data, and not an error code, you can use exceptions. But how is that possible? If you data being returned is the data you tell your function to return, then there is practically no way for the function calling it to know it's success (because the return is used for data, and not an error code). Also, the ability for a exception to literally stop the function in the middle of the code to return the error. How do C++ compilers achieve this?</p>

答:
When a function throws an exception it does not return a value of the type specified by the function specification, and it doesn't return to the point where the function was called. It instead "returns" an exception object, and it "returns" that object to whatever catch block that catches that particular kind of exception.

That I put "returns" in quotes is intentional. It's best not to think of throw as returning a value. It instead throws a value to the catch block that handles the exception. The mechanism for handling normal function call and return is almost always implemented in the form of a call stack.

Exception handling works by a different mechanism than the call stack, but that exception handling mechanism has to do so in a manner consistent with the call stack. The catch block that catches a thrown exception might be several calls above the function that called the function that threw the exception. All of the intervening stuff, the temporary variables passed as arguments to and the local variables declared in those intervening functions, has to be cleaned up along the way. This is called "unwinding the stack".

Title: What code lays behind C++ exception?


问:
What are the 'must know' Emacs commands?
I'm a fairly new convert to Emacs and I really love it as an editor, primarily because I keep finding new and super-useful commands. Are there any other programmer 'must known' commands missing from my list?</p>

```<code>M-x replace-string     - Find and replace a given string.
M-x goto-line          - Goto a specific line
M-x column-number-mode - Show the current column number in text bar
</code>```

答:
C-j  (M-x newline-and-indent)

C-M-\ (M-x indent-region)

M-.  (M-x find-tag)  requires running etags on your code

M-/  (M-x dabbrev-expand)

M-x compile

C-x v v  (M-x vc-next-action)

M-x font-lock-mode

and read the documentation for the language mode you use  (C-h m (M-x describe-mode))

I'm also a huge fan of (M-x shell), M-! (M-x shell-command) and M-| (M-x shell-command-on-region) becuase I find it very handy to be able to run command from inside emacs and
cut-and-paste the output.

Also, M-x sort-lines, M-x sort-fields and M-x sort-num-fields are useful for keeping long
lists of things (like variable names) in alphabetic or numeric order.