问:
How to write "good" unit tests?
Triggered by this thread, I (again) am thinking about finally using unit tests in my projects. A few posters there say something like "Tests are cool, if they are good tests". My question now: What are "good" tests?

In my applications, the main part often is some kind of numerical analysis, depending on large amounts of observed data, and resulting in a fit function that can be used to model this data. I found it especially hard to construct tests for these methods, since the number of possible inputs and results are too large to just test every case, and the methods themselves are often quite longish and can not be easily be refactored without sacrificing performance. I am especially interested in "good" tests for this kind of method.

答:
for TDD, "good" tests test features that the customer wants; features do not necessarily correspond to functions, and test scenarios should not be created by the developer in a vacuum

in your case - i'm guessing - the 'feature' is that the fit function models the input data within a certain error tolerance. Since I have no idea what you're really doing, I'm making something up; hopefully it is analgous.

Example story:

As a [X-Wing Pilot] I want [no more than 0.0001% fit error] so that [the targeting computer can hit the Death Star's exhaust port when moving at full speed through a box canyon]

So you go talk to the pilots (and to the targeting computer, if sentient). First you talk about what is 'normal', then talk about the abnormal. You find out what really matters in this scenario, what is common, what is unlikely, and what is merely possible.

Let's say that normally you'll have a half-second window over seven channels of telemetry data: speed, pitch, roll, yaw, target vector, target size, and target velocity, and that these values will be constant or changing linearly. Abnormally you may have less channels and/or the values may be changing rapidly. So together you come up with some tests such as:

```<code>//Scenario 1 - can you hit the side of a barn?
Given:
    all 7 channels with no dropouts for the full half-second window,
When:
    speed is zero
    and target velocity is zero
    and all other values are constant,
Then:
    the error coefficient must be zero

//Scenario 2 - can you hit a turtle?
Given:
    all 7 channels with no dropouts for the full half-second window,
When:
    speed is zero
    and target velocity is less than c
    and all other values are constant,
Then:
    the error coefficient must be less than 0.0000000001/ns

...

//Scenario 42 - death blossom
Given:
    all 7 channels with 30% dropout and a 0.05 second sampling window
When:
    speed is zero
    and position is within enemy cluster
    and all targets are stationary
Then:
    the error coefficient must be less than 0.000001/ns for each target
</code>```

Now, you may have noticed that there's no scenario for the particular situation described in the story. It turns out, after after talking with the customer and other stakeholders, that goal in the original story was just a hypothetical example. The real tests came out of the ensuing discussion. This can happen. The story should be rewritten, but it doesn't have to be [since the story is just a placeholder for a conversation with the customer].

Title: How to write "good" unit tests?

Body:
for TDD, "good" tests test features that the customer wants; features do not necessarily correspond to functions, and test scenarios should not be created by the developer in a vacuum

in your case - i'm guessing - the 'feature' is that the fit function models the input data within a certain error tolerance. Since I have no idea what you're really doing, I'm making something up; hopefully it is analgous.

Example story:

As a [X-Wing Pilot] I want [no more than 0.0001% fit error] so that [the targeting computer can hit the Death Star's exhaust port when moving at full speed through a box canyon]

So you go talk to the pilots (and to the targeting computer, if sentient). First you talk about what is 'normal', then talk about the abnormal. You find out what really matters in this scenario, what is common, what is unlikely, and what is merely possible.

Let's say that normally you'll have a half-second window over seven channels of telemetry data: speed, pitch, roll, yaw, target vector, target size, and target velocity, and that these values will be constant or changing linearly. Abnormally you may have less channels and/or the values may be changing rapidly. So together you come up with some tests such as:

//Scenario 1 - can you hit the side of a barn?
Given:
    all 7 channels with no dropouts for the full half-second window,
When:
    speed is zero
    and target velocity is zero
    and all other values are constant,
Then:
    the error coefficient must be zero

//Scenario 2 - can you hit a turtle?
Given:
    all 7 channels with no dropouts for the full half-second window,
When:
    speed is zero
    and target velocity is less than c
    and all other values are constant,
Then:
    the error coefficient must be less than 0.0000000001/ns

...

//Scenario 42 - death blossom
Given:
    all 7 channels with 30% dropout and a 0.05 second sampling window
When:
    speed is zero
    and position is within enemy cluster
    and all targets are stationary
Then:
    the error coefficient must be less than 0.000001/ns for each target

Now, you may have noticed that there's no scenario for the particular situation described in the story. It turns out, after after talking with the customer and other stakeholders, that goal in the original story was just a hypothetical example. The real tests came out of the ensuing discussion. This can happen. The story should be rewritten, but it doesn't have to be [since the story is just a placeholder for a conversation with the customer].


问:
How to get Object Oriented Programming Concepts?
What is the best way or best resources or tutorials to learn Object Oriented Programming?

For instance, when I begin a program with Java and all my code goes into just one class and I can't estimate when I need to create new classes and operate on these classes together.

答:
The Sun/Oracle API, particularly the Javadoc but also the source code itself, provides lots of good examples.  You'll use this stuff anyway; when you do, just take a harder look at it than you need to do to get the job done.  In particular, JTable is very interesting.  It and its associated classes have way too many methods, which muddles it a bit as a learning tool.  (I'm becoming convinced that convenience methods are evil.)  But note particularly how it uses TableModel.  (And also rows, row selection, columns, printing a cell, editing a cell....)

It can take a while to grasp what Sun was doing.  OOP tends to be at right angles to everything else; you have to get your brain to think in different ways and then keep it thinking differently.

To try to put OO into two sentences:  An object acts as a server, returning information or taking an action upon request.  In doing this it can also act as a client and use other servers to do things or return information.  (And it can treat, upon request, a client as a server and feed back information on its own schedule and initiative.)

ContentLicense: CC BY-SA 3.0


问:
is there any elegant way to analyze an engineer's process?
Plenty of sentiment exists that measuring commits is inappropriate.

Has any study been done that tries to draw in more sources than commits - such as:

browsing patterns

IDE work (pre-commit)

idle time

multitasking

I can't think of an easy way to do these measures, but I wonder if any study has been done.

On a personal note, I do believe that reflection on one's own 'metrics' could be valuable regardless of (or in the absence of) using these for performance eval.  I.E. an un-biased way to reflect on your habits.  But this is a discussion matter beyond Q&A.

答:
I want to add an alternative answer that points away from standard software engineering practice toward another field with the aim of stealing from basic tools that we can adapt as needed.  Quality assurance people are concerned with production, yield, and defect detection and prevention, just like software developers.

http://en.wikipedia.org/wiki/Seven_Basic_Tools_of_Quality

I like the control chart.

http://en.wikipedia.org/wiki/Control_chart

Do an activity, plot a metric, do another, plot its metric, and so on.  For example, plot commits per day.  The chart will scatter data that ranges from some minimum to some maximum.  Perhaps later you can characterize the results to determine that when the value is low, something is impeding progress and when it is too high, work is begin done in a fast but sloppy way.  How you encourage workers to speed up or slow down is left to you.

Personal metrics might be something you can correlate for yourself starting with a question like, "I feel most productive when I..."

Write a complete use case before start to code.

Write my unit tests before my code.

Check with stakeholders frequently to insure requirements don't change and create massive rework on work done toward an obsolete plan.

Change as much code as possible.

Delegate well defined changes to team members who are most expert with the parts I asked them to change.

Give my team a complete overview, but with priorities we can finish in the current sprint.

Start my refactoring pass with a hierarchical list of directories, files, classes, methods, equations, variables, documentation, etc. that I will change.

Research a high level problem to find prior art solutions, estimating the scope and key improvements needed to make a better solution.

The old saw what we measure is what gets done might lead you to attack the problem based what you determine to be the limiting factor

or multiple factors in order of priority based on a Pareto diagram.

http://en.wikipedia.org/wiki/Pareto_chart


问:
Would copyrights drop if I re-write open source project into another language?
I have re-written an open source project from java to haxe, then from haxe compiled to javascript, with totally different UI

So, the question is, is the code considered to be mine after rewriting it to another language in a closed source project? can I use it freely with no worries about original copyrights?

答:
Despite the other answers, its not as clear cut as they make out.  It comes down to what you actually did when you 're-wrote' the application.

Consider these scenarios:

If you sat down with the original source code and applied an
automatic translator to the original source code and produced new
code in the new language, then you have added no new originality to
the work, and probably do not even own copyright on the new source code.

If you sat down with the original source code, and thought about how
you could solve the same problem, but in the new language, largely
copying the same approaches, but varying them where the new
language behaved differently, then you will have added some (small)
originality to the work. it will be a derived work, and you will
still be bound by the terms of the original programs license
agreement.

The only way to be certain that you have created original software
is to sit down, and think about the problem afresh. Think about how
you would solve it today, in this language. You must avoid the temptation of looking at the original code to see how they solved problems. In this scenario, you will own the copyright to your project, and it will not be a derived work, leaving you free to license it under any terms of your own choosing.


问:
Is it good practice to return an array of objects?
If I have an ItemContainer class that contains, for example, items in an order, where each item is an Item object; is it best to have a method like:

```<code>ItemContainer->getItems()
</code>```

that returns an array containing Item objects, or is it better practice to do something like:

```<code>ItemContainer->getItem($itemNo)
</code>```

which returns a single item object for that item number, and forgoes the array. I realise this may be a trivial question or simply one of preference, but I'd like my app to adopt best practices from the start and I'm unsure which way to proceed. I'm writing in PHP, but I figured this pretty much applies to any OOP language.

答:
it depends:

returning an array allows you to pass it directly into the idiomatic foreach of the language

but using index-based get means you don't need to allocate the array and push all items into it.


答:
Why not both? Generally, since before 5.4 PHP did not support dereferencing the return of a function, it was commonplace to return an array of objects, and then if the key to the returned array was passed into that function, the function would return only that value.

It's PHP, so you are working in a dynamically typed language. If you want more surety, you could always create a separate object for storing the items, like ItemCollection. This would be an approach you would see in languages like Java or C#.

Title: Is it good practice to return an array of objects?

Body:
If I have an ItemContainer class that contains, for example, items in an order, where each item is an Item object; is it best to have a method like:

```<code>ItemContainer->getItems()
</code>```

that returns an array containing Item objects, or is it better practice to do something like:

```<code>ItemContainer->getItem($itemNo)
</code>```

which returns a single item object for that item number, and forgoes the array. I realise this may be a trivial question or simply one of preference, but I'd like my app to adopt best practices from the start and I'm unsure which way to proceed. I'm writing in PHP, but I figured this pretty much applies to any OOP language.


答:
The principle reasons for not following the ItemContainer->getItems() approach and returning an array are:

The initial implementation is likely to just return a reference to the original array, which would then allow the caller to modify the underlying collection. This is considered bad practice.

The next work around is then to make a copy of the array and return that instead. This is bad because a caller may think they are still modifying the underlying collection, and it is also expensive for large collections.

If the caller really wants to have a copy of the array, then itemContainer->cloneItems() is much clearer, and less likely to be used inappropriately.

If the caller is just wanting to have a single item, then providing a

itemContainer->getItem(index && key)

is clear and efficient

If the caller is wanting to iterate over the items, then providing a

itemContainer->getItemIterator()

is clearer.  Depending on the language you may implement

itemContainer->VisitItems(visitor)

where visitor is a visitor class, delegate or function pointer.

Hopefully, I've given you some ideas on how this can be approached differently


答: If you just port the same code it will be considered a derivative thus the same license must be used (at least for GPL). If you want to use a different license you must reimplement the whole product without reusing any source code (even a coincidence might be a problem if the case goes in court so be careful). </p>

Title: Would copyrights drop if I re-write open source project into another language?

Body:
I have re-written an open source project from java to haxe, then from haxe compiled to javascript, with totally different UI

So, the question is, is the code considered to be mine after rewriting it to another language in a closed source project? can I use it freely with no worries about original copyrights?


问:
Clarification of Python Functional document
I'm rereading this http://docs.python.org/2/howto/functional.html document and hit this line,

'...Unfortunately, proving programs correct is largely impractical and not relevant to Python software. Even trivial programs require proofs that are several pages long; the proof of correctness for a moderately complicated program would be enormous, and few or none of the programs you use daily (the Python interpreter, your XML parser, your web browser) could be proven correct. Even if you wrote down or generated a proof, there would then be the question of verifying the proof; maybe there’s an error in it, and you wrongly believe you’ve proved the program correct.'

/Emphasis mine on the Python interpreter part/

What does that mean that the Python Interpreter cannot be proven correct? Is that because it would be a long proof or that it in principal can't be proven correct, ala Godel like theorem? Is using the Interpreter then a useful fiction that all the while we use it, it could be wrong all the while, and what would being wrong mean? I mean, the interpreter has given me correct answers on integral arithmetic, so far...

Clarification much appreciated.

答:
It can be done (theoretically) but you'd need a full formal specification of the Python language and the Python interpreter internals. After that you'd need to prove the implementation matches the specification and you'd need to prove the specification adheres to all desired properties (e.g., all possible executions behave in certain ways).

As you can see, that's a massive task and not practical. It also involves updating the specification with every commit, patch or configuration change related to the interpreter. So when you've finally proved a version of the Python interpreter correct it would already be out of date.


问:
What's the most important feature of quality software?
This question is along the same lines as this one, but instead of talking about quality of code, I'm talking about the final product from the users' perspective. If you had limited time / budget, and could only guarantee one attribute of the software (other than the basic requirements) that take it from decent software to good quality software, what would you consider most important?

Is it having as few bugs as possible? An intuitive interface? Helpful error messages? Good technical support and documentation? If we don't want our software looking like cheap crap to our users, what should we always remember to include?

答:
Predictability

Software should do the job that is asked of it, when the user asks it to, in the way that the user expects it to. It should not introduce any surprises along the way ( be they unpredictable or non-obvious behaviours, long delays with no clear feedback or simple crashes ) it should simply be effective and reliable at its job.

Software that does one thing well is far more useful than software which offers many interface options but behaves unpredictably or crashes. You can always build new features in as demand shows itself, but unless your software does the job that is expected of it in a way that falls within user expectations you don't have the foundation to bring in any further improvements.

ContentLicense: CC BY-SA 2.5


问:
How can I indicate if an object operates with another one in an UML class diagram?
Suppose I want to draw a class diagram of a DAO and an Entity. The DAO is used to load instances of the Entity from the database. How can I represent this relationship on my class diagram? Is this considered one? I think it should be displayed on the diagram somehow:

TL;DR: should I draw something between them or not?

答:
The closest I can think of is a usage relationship. Possible stereotypes: "use", "call", "create", "instantiate", "send".</p>

```<code>SomeDAO ---<<use>>---> SomeEntity
</code>```

Body:
The closest I can think of is a usage relationship. Possible stereotypes: "use", "call", "create", "instantiate", "send".

SomeDAO ---<<use>>---> SomeEntity


问:
Is it appropriate for interviewers to ask candidates for their Stack Exchange user name?
Would you consider it appropriate if you were asked for your Stack Exchange username in a software job interview (or as a pre-interview screening question)?

To me, it seems like a very reasonable request, and one that would be extremely informative -- I'm sure I could learn more about a candidate in five minutes by looking at the questions and answers they have posted on Stack Exchange than by a 30 minute interview. But would such a question be bad form? Is it "too personal"?

(Likewise for GitHub, or other public/online code sharing forums.)

答:
Short Answer:  Absolutely OK.

A little lengthier answer:

At my workplace, we routinely ask for a candidate's Stack Overflow / Stack Exchange username. Contribution to the Stack Exchange community leaves a much clearer trail of where someone is at with their skills.

I know others who ask for GitHub accounts and refuse to accept candidates without a GitHub account*.

In our case, we won't remove a candidate for consideration if they don't have an account.

Ultimately, it's just one piece of the interviewing puzzle as you're trying to identify a match between the company's needs and the candidate's skills.  It's not a make-or-break factor; it merely helps confirm impressions made during the interview.

* To be clear, I don't condone that approach, and I think it causes that team to miss out on otherwise well qualified candidates. I brought it up to point out having heard of more extreme stances and to show that just asking for a Stack Overflow account name is pretty mild in comparison.

Some additional qualifiers based upon comments:

We don't look at Meta Stack Overflow and meta type posts. Meta is different, and we understand that. It's also really easy to miss the context behind those types of posts. IMO, they are closer to noise than signal when it comes to evaluating a candidate.

Likewise, comments and review activity aren't considered. They lack context and they don't have a meaningful correlation to the candidate's ability to do the job.

We have found a solid correlation between a candidate's performance in an interview and the level of Q&A that they engage in. Their Stack Overflow / Stack Exchange account becomes a supporting factoid, equivalent to a submitted code sample during the interview process.

Obligatory xkcd strip on interviews. Elaboration.


问:
How much time should jquery wait?
I'm programming a jQuery functionality for doing a search on articles while the user is typing in the search field.

I implemented a bind in jQuery that at every keyup, it sets a clearTimeout and a setTimeout to the actual function doing the post to the server. This is because users can be writing something and I want to avoid multiple posts.

I got "stuck" with: from the user interface point of view, what time should I set for the setTimeout? I tried different times (1s, 1.5s, 0.5s) but I have to admit the choice seems kind of random to me.

This raised the broader question: Is there any reference or study that answers the question of what are the "optimal" times for dynamic web interfaces?

I only now noticed that I've used more timers before (e.g. slides), that were also chosen "randomly".

Putting in other terms, does anyone knows how to justify why a given event in web interface has (or should have) a specific delta-time or range of delta-times?

(I'm sorry if this question is not adequate to here, It seemed to me closer than SO.)

答:
There is no specific delay time.
But if you think about it, waiting 0.5s means that every 0.5s you'll request a post result from your server. Now multiply this post frequency for 10 simultaneous users, your server will receive around 20 requests per second.
If the server have to search into a big database you'll have a lot of lag time between the request and response for each request.
Your web-app will be very slow.

I think that you can take 1.5 second of timeout before sending the post request.
A lot of IDE and programs are set by default with an autocompletion delay around 2 sec (Ex: Visual Studio, Sublime Text, Coda, etc.)

Title: How much time should jquery wait?


问:
Explicitly defining variable data types vs. using the keyword 'var'?
In C#, am I encouraged to use the all-purpose var keyword for every variable declaration? If yes, do I have to mention those special characters for literal values within the variable declaration like the M for decimal in the following statement:

```<code>var myDecimal = 14.5M;
</code>```

If it makes a difference, I'm trying to do some web development with C#.

答:
The C# Reference shows the following to illustrate good vs bad use of this construct:

The following example shows two query expressions. In the first expression, the use of var is permitted but is not required, because the type of the query result can be stated explicitly as an IEnumerable. However, in the second expression, var must be used because the result is a collection of anonymous types, and the name of that type is not accessible except to the compiler itself. Note that in Example #2, the foreach iteration variable item must also be implicitly typed.

```<code> // Example #1: var is optional because
    // the select clause specifies a string
    string[] words = { "apple", "strawberry", "grape", "peach", "banana" };
    var wordQuery = from word in words
                    where word[0] == 'g'
                    select word;

    // Because each element in the sequence is a string,
    // not an anonymous type, var is optional here also.
    foreach (string s in wordQuery)
    {
        Console.WriteLine(s);
    }

    // Example #2: var is required because
    // the select clause specifies an anonymous type
    var custQuery = from cust in customers
                    where cust.City == "Phoenix"
                    select new { cust.Name, cust.Phone };

    // var must be used because each item
    // in the sequence is an anonymous type
    foreach (var item in custQuery)
    {
        Console.WriteLine("Name={0}, Phone={1}", item.Name, item.Phone);
    }
</code>```

Body:
The C# Reference shows the following to illustrate good vs bad use of this construct:

The following example shows two query expressions. In the first expression, the use of var is permitted but is not required, because the type of the query result can be stated explicitly as an IEnumerable. However, in the second expression, var must be used because the result is a collection of anonymous types, and the name of that type is not accessible except to the compiler itself. Note that in Example #2, the foreach iteration variable item must also be implicitly typed.

 // Example #1: var is optional because
    // the select clause specifies a string
    string[] words = { "apple", "strawberry", "grape", "peach", "banana" };
    var wordQuery = from word in words
                    where word[0] == 'g'
                    select word;

    // Because each element in the sequence is a string,
    // not an anonymous type, var is optional here also.
    foreach (string s in wordQuery)
    {
        Console.WriteLine(s);
    }

    // Example #2: var is required because
    // the select clause specifies an anonymous type
    var custQuery = from cust in customers
                    where cust.City == "Phoenix"
                    select new { cust.Name, cust.Phone };

    // var must be used because each item
    // in the sequence is an anonymous type
    foreach (var item in custQuery)
    {
        Console.WriteLine("Name={0}, Phone={1}", item.Name, item.Phone);
    }


答:
Yes, but I think it would be most worthwhile as a pre-screening question. Realistically, you aren't going to be able to act on the information during the interview in a meaningful way if that's the first time you're asking about it. It'd be like waiting until they were in the office to ask for code samples. The other benefit of being a pre-screening question is that if they do decide they don't want to share it for whatever reason, they can make that decision without being on the hotseat.

In general, I think its a great/acceptable resource. If they do have one, it would make for excellent talking points during the interview itself, especially if you can find an answer they gave with a code sample, or if they've answered a few questions related to what they would be working on. This has the added advantage of being a specific topic they've clearly put some time into before, and developed a written answer to. (If that answer isn't well formed or flat out wrong, that's likewise a very useful indicator).

Title: Is it appropriate for interviewers to ask candidates for their Stack Exchange user name?

Body:
Would you consider it appropriate if you were asked for your Stack Exchange username in a software job interview (or as a pre-interview screening question)?

To me, it seems like a very reasonable request, and one that would be extremely informative -- I'm sure I could learn more about a candidate in five minutes by looking at the questions and answers they have posted on Stack Exchange than by a 30 minute interview. But would such a question be bad form? Is it "too personal"?

(Likewise for GitHub, or other public/online code sharing forums.)


答:
Would you consider it appropriate if you were asked for your Stack Exchange username in a SW job interview (or as a pre-interview screening question)?

Some good candidates will not have a StackExchange account. So if you can only offer onsite interviews to 5 people and expect 100 applicants, this might be a good strategy to simply provide a better way to distinguish initial candidates.

But do keep in mind you cannot eliminate candidates who do not have a StackOverflow account unless you are willing to take the risk of people who otherwise would be excellent candidates not having accounts.

If you want to use this as part of the interview process, I would strongly recommend it as one option of many - github and StackExchange are both potential (not comprehensive).

Just make sure this isn't presented as mandatory.

I would volunteer MY profile it if possible in an interview as an interviewee. It can naturally come up in regards to questions about "do you code for fun?" or "what do you do to learn outside work?" or any question like that.

It does help to find these, though.

Also, keep in mind a StackExchange account can show two different stories*:

Ability to ask meaningful questions

Ability to provide meaningful answers

Both can be good or bad, depending on your profile and ratio of questions/answers.

*it also might show you spend way, way, WAY too much time on here...


问:
What is the benefit of 64 bit A7 in iPhone
I'm trying to figure out why going to 64 bit processors is such a big deal in an iPhone. I understand that there will be twice as many registers so the processor can work with twice as much data which should increase performance.

However I don't see many phones going to more than 4GB of memory any time soon. It seems like overkill and it would negatively impact battery life.

Another problem that I see is that most variables now need twice as much memory. This will create problems in a mobile environment with small amounts of memory.

I believe that the folks at Apple are intelligent and they probably have great reasons for doing this, I'm just trying to understand them.

EDIT

Don't know much about GPU's but I was told that with 64 bit registers 2 pixels can be loaded into each register and operations can be performed on them individually. Is there a graphical advantage regarding 64 bit?

答:
In the short run pretty much nothing. It's actually a step back in a few ways. There are three main advantages that I know of.

64bit is a lot better with larger numbers, which is a  boon to crypto. Which may be an interesting combine with the finger print scanner on the phone.

Again in the same vein, the improvements with 64bit and large numbers help with physics rendering. Which is handy considering the amount of physics used in the UI of iOS7. This also benefits game developers as well especially on something with larger screen real estate like the iPad.

It's also adds some degree of future proofing current phones using this.


答:
Asking point-blank what their SO user name is probably not appropriate. It would sound very direct, and I would find such a question a little invasive. Asking what online resources they use when they are problem-solving is much more appropriate. And if they answer that they are a StackOverflow user, then I think you could ask them how interactive they are. If they mention that they are an active ask-er/answer-er, then asking them what their username is would be appropriate.

I think it's acceptable for an interviewer to ask, but if a candidate refuses then it shouldn't be a deal-breaker.

Some people work with specialized, proprietary tools that don't have any questions on StackOverflow (I just checked). Some people don't have time to spend answering other people's general questions. I know some developers who don't ask or answer on SO mostly because of language barriers.

There are great developers out there who just don't participate much in the StackExchange ecosystem.


答:
I think it's reasonable for an employer to ask for it, but I don't think its reasonable for that to be a make-or-break qualifier.

Joel mentions that a high rep equates to getting high paying jobs but by his own logic, unless you're under employed you may not have time to flex your mental skills and get a large amount of rep. So the man who waxes poetic about Stack Exchange (and rightfully so) admits that it's really an indicator of both high employability and under employment.


问:
Naming a sending/receiving module. Does the pattern have a name?
I'm working on a simple piece of functionality (actually a ruby gem, but that is beside the point) which can be used to

receive and persist incoming messages

send and persist outgoing messages

supplies a hook to the implementing code for performing some action based on a received message. Could for example send a reply, but also perform other actions.

I'm struggling to find a short and concise name for this functionality. Does this bare resemblance to any named patterns, and if so which?

***** UPDATE *****

To be more specific, what I am actually doing here is receiving and sending SMS.

Starting to wonder if perhaps the most appropriate name for this functionality would be an SMS dispatcher. From the Dispatcher page on wikipedia (although it has nothing to do with computing):

Dispatchers are communications personnel responsible for receiving and transmitting pure and reliable messages

Or would using the dispatcher name for this concept cause confusion with other design patterns?

答:
There are many patterns associated with messaging, as there are lots of facets to this problem. There is an entire section in the book Enterprise Integration Patterns, which is summarized here: http://www.eaipatterns.com/toc.html

The pattern to use depends on some parameters, such as: is this a point-to-point message? is there one sender and many receivers? vice versa? many-to-many? how is the recipient determined?

Here's some general patterns:

Point-to-Point

A sender establishes a direct connection to one destination. i.e., a call to a web service, remote procedure call

Publish-Subscribe

A single source of messages are published to all subscribers. Think RSS or Twitter.

Dispatcher

A dispatcher is used when there is a single source of messages and multiple destinations. All destinations receive each message and decide if they want to process it or not.

Router

Uses context to determine the destination of a message. The decision can be based on content of the message or external state or rules. Typically uses many sources of messages and routes to one of many destinations.

Broker

A broker is similar to a router in that it consumes messages from multiple sources and determines the correct destination. It differs, however, in that it may have logic for translating a message and/or negotiating with the sender to send different content.


答:
It sounds like this opinion is not particularly popular, but I don't think it is okay to ask for this information.

Stack Exchange is a place of learning; you shouldn't have to worry about being judged for asking "dumb questions" later down the line.  I know I come to Stack Exchange to broaden my knowledge, not just of programming, but in all sorts of subjects.  As long as I've put in some effort to solve questions on my own, I shouldn't have to feel self-conscious for asking a question that most experts on the subject would be expected to know the answer to.

Moreover, this would exacerbate the issue of users keeping multiple accounts, one for asking questions, and one for providing answers. I've already seen this a number of times on SE. I think users do it because they appear more knowledgeable with less questions asked.


问:
What is your favorite whiteboard interview problem?
Just as the title says, what is your favorite whiteboard interview problem, and why has it proven effective for you?

Junior, senior, Java, C, Javascript, PHP, SQL, pseudo-code, etc.

答:
My favorite which encompasses a few disciplines is to count the number of nodes in a binary tree given the interface (in C#):

```<code>public interface IBinaryTree<T>
{
    IBinaryTree<T> Left
    {
        get;
    }

    IBinaryTree<T> Right
    {
        get;
    }

    T Data
    {
        get;
    }

    // Other properties and methods not germane to this problem.
}
</code>```

and just for fun, here's the implementation, though the interviewee need not see this.

```<code>public sealed class BinaryTree<T> : IBinaryTree<T>
{
    private readonly IBinaryTree<T> left;

    private readonly IBinaryTree<T> right;

    private readonly T data;

    public BinaryTree(
        IBinaryTree<T> left,
        IBinaryTree<T> right,
        T data)
    {
        this.left = left;
        this.right = right;
        this.data = data;
    }

    public IBinaryTree<T> Left
    {
        get
        {
            return this.left;
        }
    }

    public IBinaryTree<T> Right
    {
        get
        {
            return this.right;
        }
    }

    public T Data
    {
        get
        {
            return this.data;
        }
    }

    // Other properties and methods not germane to this problem.
}
</code>```

and the assistant class:

```<code>public static class BinaryTreeNodeCounter
{
    public static int CountNodes<T>(this IBinaryTree<T> tree)
    {
        // TODO: What goes here?
    }
}
</code>```

The solution I like to see is this:

```<code>public static class BinaryTreeNodeCounter
{
    public static int CountNodes<T>(this IBinaryTree<T> tree)
    {
        return tree == null
            ? 0
            : 1 + tree.Left.CountNodes() + tree.Right.CountNodes();
    }
}
</code>```

As it demonstrates knowledge of:

how a tree (binary tree in particular) works

the recursive definition of a binary tree

recursive methods and how base cases stop recursion

what counting a single node means

interfaces as a contract

(less important) knowledge of C# syntax:

generics

extension methods

ternary operator

Body:
My favorite which encompasses a few disciplines is to count the number of nodes in a binary tree given the interface (in C#):

public interface IBinaryTree<T>
{
    IBinaryTree<T> Left
    {
        get;
    }

    IBinaryTree<T> Right
    {
        get;
    }

    T Data
    {
        get;
    }

    // Other properties and methods not germane to this problem.
}

and just for fun, here's the implementation, though the interviewee need not see this.

public sealed class BinaryTree<T> : IBinaryTree<T>
{
    private readonly IBinaryTree<T> left;

    private readonly IBinaryTree<T> right;

    private readonly T data;

    public BinaryTree(
        IBinaryTree<T> left,
        IBinaryTree<T> right,
        T data)
    {
        this.left = left;
        this.right = right;
        this.data = data;
    }

    public IBinaryTree<T> Left
    {
        get
        {
            return this.left;
        }
    }

    public IBinaryTree<T> Right
    {
        get
        {
            return this.right;
        }
    }

    public T Data
    {
        get
        {
            return this.data;
        }
    }

    // Other properties and methods not germane to this problem.
}

and the assistant class:

public static class BinaryTreeNodeCounter
{
    public static int CountNodes<T>(this IBinaryTree<T> tree)
    {
        // TODO: What goes here?
    }
}

The solution I like to see is this:

public static class BinaryTreeNodeCounter
{
    public static int CountNodes<T>(this IBinaryTree<T> tree)
    {
        return tree == null
            ? 0
            : 1 + tree.Left.CountNodes() + tree.Right.CountNodes();
    }
}

As it demonstrates knowledge of:

how a tree (binary tree in particular) works

the recursive definition of a binary tree

recursive methods and how base cases stop recursion

what counting a single node means

interfaces as a contract

(less important) knowledge of C# syntax:

generics

extension methods

ternary operator


答:
I think it is mildly inappropriate to ask a candidate for information they did not volunteer (with a few obvious exceptions, like criminal background, etc.)  It is also at least potentially dangerous, since in many places there are laws forbidding employment discrimination that limit what questions you can ask.  If participation on a particular site turns out to correlate with race, age, gender or other category for which discrimination is forbidden then you are potentially opening yourself up to a lawsuit.  You may even actually be factually committing such discrimination (almost certainly unintentionally).

According to this quick Google search result social media searches run the risk of an employer discovering information it is otherwise illegal to ask about, potentially exposing itself to a discrimination suit.  In some places it is not legal to ask about disability or pregnancy.  Since SO and SE are professional sites, it is more reasonable to claim that discrimination was not the purpose of the question, but...

I personally would ask something like "do you participate in any professional websites that you would like us to know about, but didn't quite make it onto your resume?"  And I would not regard it as a negative for those who had no such participation, other than that other candidates they are competing with might help themselves with their answer.


问:
Writing my problem solving approach on paper?
I'm a freshman Computer Science student and we just started doing some actual projects in Python. I have found I'm very efficient when I use the pen and paper method that my professor suggested in class. But when I can't write my problem down and work my algorithms out on paper I am really slow. During labs, I always seem to have to take the assignment back to my dorm. When I get there and write it out I solve the problem that took me the whole class in like 5 minutes.

Maybe it's because I get stressed seeing people solving labs before me. Or maybe it's the pen and paper method.

I was browsing through forums and someone wrote that if you have to write your programs on paper then you shouldn't be a programmer. I'm really worried because I'm so much better when I can see what the program is doing and track my way through it before typing actual code. Am I doing something wrong?

Edit: Sorry for being unclear, but when I said writing on paper I meant my problem solving approach (e.g writing examples, making tables with values, etc.) not my actual code. I just use the paper to get my ideas out.

答:
I don't think there's anything inherently wrong with drafting code (pseudo or otherwise) on paper first - it's really no different than writing it out on a whiteboard, which plenty of people do when discussing how to tackle a problem.

Do you write first drafts of essays for non-CS classes on paper first before typing them out?  In fact, I used to do that years ago when I was still a college student, but after my freshman year, I forced myself to write all drafts on a screen, since it made writing subsequent drafts so much easier, and the same idea applies to writing code.

I would suggest you try typing out your algorithms, even if it's just in a text editor like Word.  The more you do it, the more comfortable you'll be at not relying on paper and pen.  And if your typing skills are somewhat lacking and that's in fact the source of your frustration, take a typing course!  It would be the best thing you could do for your future career.


答:
There's nothing wrong with working out your algorithms on paper first.  Not so much for everyday coding, but for more complex algorithms, professional programmers work them out on paper or a whiteboard all the time, especially if a graphical format makes it more clear.  For a student, every program is complex.

If you want to get better at designing algorithms at a computer, though, there are some techniques you can practice.  Don't just start by writing out the code, write the same things you would put on paper as comments, then expand it into real code or more detailed comments one by one.

For example, if I'm deleting an element from the middle of a linked list, I might start with something like:

```<code>// find the element
// point the previous element to the next element
//    How do I get a pointer to the previous element?
//        doubly-linked list?
//        another find?
//        keep track during the first find?
// delete the element
</code>```

Then I might replace // find the element with a function with more pseudocode, and keep going until I have a complete solution.  Don't think code has to be written in a linear manner.

Title: Writing my problem solving approach on paper?

Body:
I'm a freshman Computer Science student and we just started doing some actual projects in Python. I have found I'm very efficient when I use the pen and paper method that my professor suggested in class. But when I can't write my problem down and work my algorithms out on paper I am really slow. During labs, I always seem to have to take the assignment back to my dorm. When I get there and write it out I solve the problem that took me the whole class in like 5 minutes.

Maybe it's because I get stressed seeing people solving labs before me. Or maybe it's the pen and paper method.

I was browsing through forums and someone wrote that if you have to write your programs on paper then you shouldn't be a programmer. I'm really worried because I'm so much better when I can see what the program is doing and track my way through it before typing actual code. Am I doing something wrong?

Edit: Sorry for being unclear, but when I said writing on paper I meant my problem solving approach (e.g writing examples, making tables with values, etc.) not my actual code. I just use the paper to get my ideas out.

Body:
There's nothing wrong with working out your algorithms on paper first.  Not so much for everyday coding, but for more complex algorithms, professional programmers work them out on paper or a whiteboard all the time, especially if a graphical format makes it more clear.  For a student, every program is complex.

If you want to get better at designing algorithms at a computer, though, there are some techniques you can practice.  Don't just start by writing out the code, write the same things you would put on paper as comments, then expand it into real code or more detailed comments one by one.

For example, if I'm deleting an element from the middle of a linked list, I might start with something like:

// find the element
// point the previous element to the next element
//    How do I get a pointer to the previous element?
//        doubly-linked list?
//        another find?
//        keep track during the first find?
// delete the element

Then I might replace // find the element with a function with more pseudocode, and keep going until I have a complete solution.  Don't think code has to be written in a linear manner.


答:
Go for it! If we call what you are doing thinking and designing your solution, then it makes sense your process will be much faster than just blasting out code.

People like to think (and the noisy ones like to tell us) that their way of doings is better. But everyone's ability and skill mix is different. So do what works for you. As you gain practice, you will probably switch to doing more of the design work in your head, and use paper for bigger problems.

One thing to look out for is what form the exams will take. Will they be on paper, or will they be computer based? If they are paper based, then your way will give you an advantage. If they are computer based, then that's fine too: do any design on paper, then write the code. Whatever works best!


答:
Solving the problem and writing the code that implements your solution are two different activities.

If you're unfamiliar with a language, you're going to spend a lot of time on the code itself - and not enough on finding a good solution. If paper, whiteboard or starting at the ceiling help you in that regard, then by all mean do it.

(Personally, I find myself getting off the computer and walking around in circles trying to build a solution in my mind)


问:
Microsoft SDE Interview vs Microsoft SDET Interview and Resources to Study
I have always heard that SDE interviews are much harder to crack than SDET. Is it really true?  I have also heard that if candidate doesnt do well in SDE interview he is also sometimes offered SDET position. How much truth is there into these talks?
I would highly appreciate if someone would put good resources and guidelines for how to prepare for Microsoft interviews..which books to read, which notes, online programming questions websites, etc. Give as much info as possible.

Thanks in advance to everyone for your valuable help and contribution.

答:
Unfortunately, those are both myths. SDEs and SDETs get the same starting salary, so it would be silly to have a lower bar for one of the positions. You'll have to code at the whiteboard in both interviews and show that you can deconstruct complex problems.

Depending on the group, the SDE loop may have more emphasis on algorithms, and on the SDET side, you'll find more emphasis on systems thinking - but the emphasis can vary slightly from group to group.

To prepare, study algorithms and implementation examples, but more importantly practice solving random programming problems on paper (or on a whiteboard if you have one). Be able to think out loud while you code (the answer is often not as important as the thought process). Also have examples to share on how you learn, communication, and dealing with conflict.

For an SDET interview, you can read my book (more importantly, the book will help you evaluate if you want to be an SDET. On the dev side, you can goo...bing "Microsoft Interview Questions" and probably get some good practice material - but skip the "why are manhole covers round" type questions, as those are rarely used anymore.


问:
Why isn't SSL/TLS built into modern Operating Systems?
A lot of the basic network protocols that make up the infrastructure of the Internet are built in to most major Operating Systems.  For example, TCP, UDP, and DNS are all built into Linux, UNIX and Windows, and are made available to the programmer through low-level system APIs.

But when it comes to SSL or TLS, one has to turn to a third-party library such as OpenSSL or Mozilla NSS.

SSL is a relatively old protocol, and it's basically an industry standard as ubiquitous as TCP/IP, so why isn't it built into most Operating Systems?

答:
There is some Kernel support for Crypto and SSL. This makes sense because the Kernel can more efficiently interface with the hardware and it is also convinient to protect credentials from any application. Good examples are kssl, a Kernel-level reverse-SSL Proxy in Solaris or the various crypto libraries in kernel (used for example for VPNs). A typical hardware accelerated crypto engine also has a kernel module (and is accessible over PKCS#11 or OS specific crypto interfaces).

Some reasons why you dont see it more often is that some application protocols are not properly layered (think STARTLS) or require application decisions while handshake (think client certificate and CRL checking) or are simply in a regular evolution.


问:
What design pattern (in python) to use for properly separate runtime infos with core code?
I am not sure if this is a clear question.

I work on a python project that is based on terminal(console), for which I am planning to implement a GUI.

I am not major in CS so I really have no idea about how to effectively design a message system such that:

In console, it provide nice look info when runtime.

In GUI, it is directed to a certain widget, let's say, a text label, or a bottom bar, or a hide-able frame.

Do you have any suggestions?

Currently, I am using print function to provide essential information on stdout during runtime. So a lot of print ....
are distributed here and there among the code.

I am thinking to use macro-like variables such as 'FILE_NOT_EXTIS_MESSAGE' for printing, and define the variables in one file.
Is this a standard way that people always do?
How about I introduce a logging system?

In sum, I am ask for a pattern that people are commonly using for handling of screen output information with high effectiveness and adaptivity.

答:
The scope of this question is too wide to answer on this platform.

However, I can suggest some tips which may help,

Keep your core program module and the modules that display / log information as separate as you can.

Have an interface to your core program module that can be used by console output module and/or your GUI output module and / or your logging module.

The core module need not be aware which of the output modules are currently hooked in.

Check the Observer design pattern, if the core module is primarily only sending out information that needs to be displayed / logged.

The best way to learn is by trying out different ways of structuring your code, then read more about design and then go back and refactor your design. Iterate until you run out of time.

OwnerDisplayName: shr


答:
I've never been asked about Stack Overflow at a job interview. As I've used this handle for more than a decade, and some of the politically oriented posts with this handle can be seen as ranging from trotskyist to ayn randist. My politics are none of their business (other than running for elected office, and maybe not even then), and I would not tell them this handle. I'm also winding down use of this nickname and ramping up usage of a different one.

I'm sure I could learn more about a candidate in 5 minutes by looking at the questions and answers they have posted on SE than by a 30 minute interview.

Yes, you could. I've been in the workforce for a long time, and I've had some bad experiences. Someone interviewing me and checking my posting history might wonder if I'd be posting about them too.

and refuse to accept candidates without a GitHub account

My current employer prohibits contributing to open source projects as they are terrified of having GPL code infecting their codebase.


答:
I do this all the time.

IMHO asking for online reputation sources is like asking for your resume, with one important difference: faking a good online reputation is way harder than faking a good resume.

Stack Exchange is a good place to find out about the candidate's communication skills.

There’s nothing I respect more than a great programmer. But if you can manage to become a great programmer and a great communicator, there’s almost nothing you can’t accomplish. - Jeff Atwood

GitHub is where most high profile projects are hosted (at least for the technology stack we use), and if the candidate contributed to some of these projects it says a lot about the quality of his work (good projects will not accept pull requests lacking documentation and/or unit tests).


答:
What you're describing is indeed a logger. Python provides facilities for that: logging documentation (Py 3.3). The logger class basically collects all the messages you dump into it and can output them for use in whatever form you like.

I personally like to have a little extra status window with messages, but I write scientific software, so i'm always in debug-mode. For common endusers, I would stick with a logfile (if you use advanced text editors (notepad++, etc) you can tell them to reload continuously and scroll to the last line, which is pretty close to a console output)

Title: What design pattern (in python) to use for properly separate runtime infos with core code?

Body:
I am not sure if this is a clear question.

I work on a python project that is based on terminal(console), for which I am planning to implement a GUI.

I am not major in CS so I really have no idea about how to effectively design a message system such that:

In console, it provide nice look info when runtime.

In GUI, it is directed to a certain widget, let's say, a text label, or a bottom bar, or a hide-able frame.

Do you have any suggestions?

Currently, I am using print function to provide essential information on stdout during runtime. So a lot of print ....
are distributed here and there among the code.

I am thinking to use macro-like variables such as 'FILE_NOT_EXTIS_MESSAGE' for printing, and define the variables in one file.
Is this a standard way that people always do?
How about I introduce a logging system?

In sum, I am ask for a pattern that people are commonly using for handling of screen output information with high effectiveness and adaptivity.


答: My code is much better organized when I scribble notes and approaches on a notepad, check books, check the web and think about it.  I'm also much more of a visual person, so drawing pictures with data structures is very helpful.  I don't write down every line, but I do scribble what I consider "important" fragments or key functionality.  For bigger projects I fire up Visio.  I'm not sure why someone would advocate jumping right onto a keyboard unless they're much more efficient, or paid by the hour.</p>


问:
Writing a bootloader with no bootloader
I have a question that I really can't find a straight answer to.  Let me start by saying I'm not asking for a step by step tutorial, or even plan on doing anything.  I'm just curious.

I've been reading up all day on the development of operating systems, and how they're built from scratch.  I have a pretty firm grip on the theory of it.  However, there is one step I can't seem to find an answer for.

Before the existence of a full on, tool filled operating system, how would one even write a simple boot loader for a computer that doesn't any have a boot loader, or anything for that matter, in its boot sector?  What would the very first step be after acquiring a computer with the bare minimal? (I.e., screen, keyboard, processor, ram, hdd, floppy)

答:
You need some way to create a ROM or EEPROM chip that can be installed on the motherboard and contains the bootloader. There's really a series of boot steps, starting with internal checks by the various chips (CPU, video card etc) followed by bus activation and discovery (the PCI-e bus controller locates everything connected to it and assigns IDs etc). Then the motherboard looks for a boot ROM and runs that code, which in turn finds the BIOS boot order and looks through that for a matching device, then loads the booter from that. Which in turn loads an OS.

The original boot chain was flicking switches that formed the ROM, then later using switches to program RAM, and so on right up to the modern multi-stage bootloaders.

Title: Writing a bootloader with no bootloader


问:
What justifies the use of an IDE versus a standard editor?
I find myself using my text editor of choice (vim, nano, gedit, pick your poison) much more often than any IDE as of late.

After noticing my ide shortcuts getting dusty I started to think about this and wonder: what justifies use of an IDE for you opposed to a text editor?

For that matter what rationale would you have for not using an IDE and merely relying on an editor?

答:
If you code in Lisp, Emacs has Intellisense-like capabilities like looking up method parameters and autocompletion, so you could say it's the original IDE. It's also nice to be able to use one program for multiple tasks (editing in general, shell/command prompt, reading news).

In general, the editor vs. IDE question seems to depend on the programming language. From what I've seen, Ruby and Haskell coders, for example, seem to prefer their favorite text editor.


问:
How do you handle deployment configuration of your thick browser (html/javascript/css) clients?

Question

For those of you working with html/javascript/css "thick clients", specifically those that work against some client-independent server API, how do you manage your deployment environment configuration?

Do you manage the configuration at build time with per-environment release builds (e.g. QA, STAGE, etc) or do you build a general release and rely on some server-side configuration? What's worked best in your experience?

Background

My company has several different thick browser clients. All clients share some common attributes.

They operate against a common api server which is unaware of client-specific concerns

They are completely static at deployment and delivered via apache with no server-side processing. This means that each environment requires it's own release build (QA, STAGE, UAT, PROD).

We are looking at refactoring our clients to have general release builds and relying on server side processing to support the necessary client-specific configuration. This seems like the obvious choice, but I'd like to see how other people in same situation have handled it.

答:
There are any number of different options, and the best one would depend on your specific (much more specific than we have so far) circumstances:

Create separate per-environment configuration files as part of your build script. Then have your deployment script replace the default (usually empty) files with the correct environment.

Have only one configuration, but use replacement tokens, and use a configuration management tool like ESCAPE or a release automation tool like Nolio to substitute them during deployment.

Implement a Configuration API as part of the application server. The client could request the current settings during the initial load.

Don't have any configuration dependencies in the client at all. Let the server handle it within the behaviour of its APIs, and make the only "setting" for the client be the base URL for the various APIs.

There might be more options but those are the obvious ones. And, like I said, which one is most appropriate for you depends on your exact situation. You haven't yet told us enough to recommend a specific one.


问:
Why we use virtual and override keywords in c#
Can anyone explain me what's the point of overriding base class implementations (if its not abstract), because it's not ethical move to modify features of the parent class according to the wishes of derived classes. The best way is to make the base classes abstract and carry on the inheritance chain. Whereas when designing a class hierarchy initially we gather or elicit  all the essential requirements/features that should be belonged to a base class. Therefore, in a middle of a project we do not need to change base class implementations. According to my knowledge, base class implementation should be a constant. Thus, under this aspect, there's no real use of "override" keyword in c#. If it's not so please explain me with an example.</p>

答:
Many times you will have dependencies in sub-classes, or may have to implement things differently.

```<code>class BasicCarModel
{
    public virtual void Accelerate(double speed)
    {
         RotateFrontWheels(speed);
    }
}

class LuxuryCarModel : BasicCarModel
{
    public override void Accelerate(double speed)
    {
        RotateAllWheels(speed);
    }
}
</code>```

There is nothing at all wrong with creating virtual methods in concrete classes and in some cases they are very useful.  The difficulty is that many novice programmers violate the Liskov Substitution Principle when doing so.  Remember that an overridden method should appear to do the same thing if used as a base method.  It should not strengthen or weaken the preconditions of the base method.

In the example I gave, the difference between the base class and the derived class was in the mechanics of how the car accelerated, not in the values allowed for speed.  It did not throw any exceptions that were not expected by a calling class.

This is a contrived example, but the principle is the same.  Do use virtual and override when needed.  Don't violate the LSP.

Body:
Many times you will have dependencies in sub-classes, or may have to implement things differently.

class BasicCarModel
{
    public virtual void Accelerate(double speed)
    {
         RotateFrontWheels(speed);
    }
}

class LuxuryCarModel : BasicCarModel
{
    public override void Accelerate(double speed)
    {
        RotateAllWheels(speed);
    }
}

There is nothing at all wrong with creating virtual methods in concrete classes and in some cases they are very useful.  The difficulty is that many novice programmers violate the Liskov Substitution Principle when doing so.  Remember that an overridden method should appear to do the same thing if used as a base method.  It should not strengthen or weaken the preconditions of the base method.

In the example I gave, the difference between the base class and the derived class was in the mechanics of how the car accelerated, not in the values allowed for speed.  It did not throw any exceptions that were not expected by a calling class.

This is a contrived example, but the principle is the same.  Do use virtual and override when needed.  Don't violate the LSP.


问:
I have to use Visual Studio 2005. What are good alternatives to using LINQ?
I have recently started a new job and am being forced to use VS 2005 and .NET 2. This has been quite painful for a number of reasons, but the one big change from VS 2005 to its successors was the introduction of LINQ and extension methods.

A common pattern that I used to follow when using enumerations was the following:

```<code>foreach(var myObject in myObjects.Where(x => x.Property == someValue)
{
    //Do some stuff
}
</code>```

What I am having difficulty with is coming up with a succinct way of expressing the same statement in C# 2.  The best I have come up with is the following:

```<code>foreach(MyObject myObject in myObjects)
{
    if(myObject.Property == someValue)
    {
        //Do some stuff
    }
}
</code>```

Is there a more effective or efficient way of writing this code?

How would you write C# 2 code so that it can most easily be transformed into C# 5 code (we will be upgrading to VS2012/.NET 4.5 after the next release)?

答:
Well, you have a few interesting bits to overcome:

Lambda syntax wasn't introduced until VS 2008, so you'd have to implement using anonymous delegates.

You can't even simulate extension methods for .NET 2 with VS 2005. VS 2008 only.

Func<> and its relatives weren't introduced until .NET 3.5

The Func<> delegates are covariant on their input and contravariant on their output. Not going to have that until .NET 4, so your use may be limited.

That being said, if you grab LINQBridge, you should be able to remove the extension method syntax and use it.

EDIT

So, for grins and giggles, I just translated LINQBridge into .NET 2.0 / VS 2005. Was easy, but not terribly pleasant :) Your example foreach above would wind up looking like this after the re-do:

```<code>foreach(MyObject myObject in Enumerable.Where(myObjects, delegate(MyObject x) { return x.Property == someValue; }))
{
    //Do some stuff
}
</code>```

This makes me think that your non-LINQ foreach is much easier to read for the environment you're working in.

Body:
Well, you have a few interesting bits to overcome:

Lambda syntax wasn't introduced until VS 2008, so you'd have to implement using anonymous delegates.

You can't even simulate extension methods for .NET 2 with VS 2005. VS 2008 only.

Func<> and its relatives weren't introduced until .NET 3.5

The Func<> delegates are covariant on their input and contravariant on their output. Not going to have that until .NET 4, so your use may be limited.

That being said, if you grab LINQBridge, you should be able to remove the extension method syntax and use it.

EDIT

So, for grins and giggles, I just translated LINQBridge into .NET 2.0 / VS 2005. Was easy, but not terribly pleasant :) Your example foreach above would wind up looking like this after the re-do:

foreach(MyObject myObject in Enumerable.Where(myObjects, delegate(MyObject x) { return x.Property == someValue; }))
{
    //Do some stuff
}

This makes me think that your non-LINQ foreach is much easier to read for the environment you're working in.


答:
Historically there were various ways:-

No OS at all. Executable was loaded in from first card, tape file or whatever.

Os hard coded in magnetic core memory. Cores were permanent magnets instead of plain ferrite, depending on the N/S orientation of the magnet it was a one or zero. The computers in the Gemini and Apollo spacecraft had all their programs "knitted" in this way.

First sector from disk. This was pretty standard on "mini" computers such as the PDP-11, the computer was hardwired to read the first track from the first disk and execute the code when it hit an EOF marker.

Custom boot device. The second generation IBM mainframes had a dedicated 12 inch floppy disk to load in a "microcode" OS. Which then searched for the real OS on disk somewhere. I have also seen micros with dedicated cassette tape drives to load the OS. Operators were required to rewind or "turn over" the tape.

BIOS. A minimal OS is stored in ROM and the processor is hard wired to execute the ROM code on "power up". The ROM then gets the real OS from wherever. This is pretty much how all modern computers work. What the ROM actually does varies from processor to processor. Itel boxes generally have a very sophisticated BIOS program dedicated to each procesor "generation". Unix type boxes generally have a much simpler BIOS, Sun/Oracle boxes famously load a "FORTH" interpreter which then executes a simple script to load Solaris.

Title: Writing a bootloader with no bootloader

Body:
I have a question that I really can't find a straight answer to.  Let me start by saying I'm not asking for a step by step tutorial, or even plan on doing anything.  I'm just curious.

I've been reading up all day on the development of operating systems, and how they're built from scratch.  I have a pretty firm grip on the theory of it.  However, there is one step I can't seem to find an answer for.

Before the existence of a full on, tool filled operating system, how would one even write a simple boot loader for a computer that doesn't any have a boot loader, or anything for that matter, in its boot sector?  What would the very first step be after acquiring a computer with the bare minimal? (I.e., screen, keyboard, processor, ram, hdd, floppy)


答:
You will ace interviews! They make you write code on paper or the whiteboard. I'm the exact opposite. Trying to write braces or cut & paste with a pen is SO tedious!

My dad used a lot of paper when programming COBOL. I think it's just your style of thinking.


问:
What are the responsibilities of a Manager and of the Dao Layers
In several projects we have been using the following layers:

Action (has 1 or more managers)

Manager(has 1 or more Daos)

Dao

But most of the time the manager only calls the dao. We do use the manager class to prepare the date to be sent to the db or to prepare the data to be sent to the action(is this a good practice?).

What are the responsibilities of a Manager and of the Dao classes?

Do we have to have a manager for every dao or can we just use the dao directly?

How do I handle situations where I need to use the functionality implemented in several Managers?

PS: I know that there is no golden hammer so I'll narrow it to the types of apps we do, generally webapps for banks.

Thank you

答:
What are the responsibilities of a Manager and of the Dao classes?

The responsibility of the DAO is the abstraction over data access.  The responsiblity of the manager it to organize and execute the business logic of the application -- the manager uses the DAOs to accomplish this.

Do we have to have a manager for every dao or can we just use the dao
  directly?

I would think you should be using the DAOs directly. Again, for the manager to accomplish its tasks, it might need to make use of several DAOs to manipulate data -- I don't see a problem with this.

How do I handle situations where I need to use the functionality
  implemented in several Managers?

This could be a code-smell that you need to group together (refactor) certain logic or functionality into a new manager, or (although it might be extreme) another service layer on top of that to organize action among the managers.


答:
In the really ancient days (such as the IBM 650 or PDP1) it was necessary to enter values into memory using front panel switches.  Looking at pictures of really early computers, you saw two rows of lights - Address and Data.  On a 16-bit computer there were 16 of these running across, usually color coded in groups of three or four for octal or hex, respectively.

The 'Reset' button would set the 'Address' counter to zero.  One could then set the switches on the data bus to the desired value, and toggle the 'data write' button.  This would write the switch settings into the memory at address 0.  There were up-down toggle switches to allow you to move to the next or previous address.  You could also set the switches for the address, and click 'address write'.  Whatever was at that new address would be displayed on the 16 data lights.

Typically one would toggle in, using this technique, a read loop for reading values out of a card reader or paper tape.  This would be just enough to load a larger block of code to proceed with the OS or application load.  At the time, such computers had 4K to 16K words (or 8K to 32K bytes) so such loaders were tiny by modern standards.  A read loop might only be three or five 16-bit words.

Front panel illustration

Title: Writing a bootloader with no bootloader


问:
Encapsulate standard C functions?
While studying the C programming language and learning safe practices, I'm inclined to write a layer of functionality over several parts of the standard library.  This would serve two purposes: I could use standard parts of the language in ways that feel more familiar or rational to me, and I could easily replace that functionality with my own, if I needed to.

I could benefit from this, but should I do it?  As an example, we can consider memory management.  If I've written malloc() into the constructors of each of my objects, then decide that I need to handle memory allocation on my own, I have to edit the constructor associated with every object.  By referencing my own function, I can change the contents of that function without writing a new constructors.

It seems obvious that I should do this, but I'm used to Python.  I'm extremely comfortable in that environment and have no problem linking to any part of the standard library from any part of my program because I know I will almost certainly leave that relationship untouched for the life of the project.  The situation I'm running into with C feels like I'm trying to hide the language from myself.

Will writing a layer of functionality over the C standard library help me in learning the language and developing a codebase, or will it stifle my understanding going forward?

答:
The temptation of writing a layer above a standard API is common among beginners. I've been there too.

Although you may find short term benefits, I strongly advise not to do so. The standard API is, by definition, standard. It is known and used by all developers and sooner or later you'll have to know and use it. Don't delay that learning by encapsulating the standard API with something that only you will be familiar with.

Title: Encapsulate standard C functions?


答:
I am also facing same problem at my initial day' of learning technical skills.

But this type practice should not give the 100% success because if we are writing code on paper then there is no chance to bug fixing, there is chance to resolve the errors and exceptions during doing paper work.

So paper work doesn't  give the any navigation to resolve the issues.And we can get type speed as bonus due to system practice.

I am also doing paper work but when before implementing my functionality just do rough estimation after this I will start My implementation on system.

Please try to spend more time on system practice. This will give 100% confidence and result.


答:
I think there could be some use in writing your own layer, so long as you retain appropriate perspective.

When you interact with other people about your code, you'll still need to talk about it in terms of the standard functions.

But it could help you crank out similar applications if you wrap-up a nice set of routines that's useful. At the worst, the artifact you may end up with will be little more than a well-organized snippets file. And that's not such a bad thing. This is iff you keep perspective.

There is a danger of going waaaaay overboard. Basically implementing your own language within C. And, well, that's dangerous, crazy territory! You may seize upon something really cool and becomes the next big thing (it could happen!) or you may bounce around the endless circles of speculation: oh, and this could be expressed like this, and all of that would be simpler through this interface, and you convert it all to a new super-canonical representation, and ...

http://xkcd.com/927/

I believe the danger zone I'm talking about is approximately the same as the "Architecture Astronaut" paradigm. <yoda>Remember: don't build another game engine, build a game. Then a second game. Then a third game. Then you may build an engine. </yoda>

Writing a layer over the API is a possible method of building an application. It is the approach taken by one of the most-readable X11 book I've ever found: X Window Applications Programming (Johnson & Reichard) (the series kept using K&R function syntax until at least 1996!), but for pedagogical value, it's priceless. Like I alluded to above, a well-organized snippets file.

Title: Encapsulate standard C functions?

Body:
While studying the C programming language and learning safe practices, I'm inclined to write a layer of functionality over several parts of the standard library.  This would serve two purposes: I could use standard parts of the language in ways that feel more familiar or rational to me, and I could easily replace that functionality with my own, if I needed to.

I could benefit from this, but should I do it?  As an example, we can consider memory management.  If I've written malloc() into the constructors of each of my objects, then decide that I need to handle memory allocation on my own, I have to edit the constructor associated with every object.  By referencing my own function, I can change the contents of that function without writing a new constructors.

It seems obvious that I should do this, but I'm used to Python.  I'm extremely comfortable in that environment and have no problem linking to any part of the standard library from any part of my program because I know I will almost certainly leave that relationship untouched for the life of the project.  The situation I'm running into with C feels like I'm trying to hide the language from myself.

Will writing a layer of functionality over the C standard library help me in learning the language and developing a codebase, or will it stifle my understanding going forward?


问:
How do I unit test multi-threaded code?
Are there ways to unit test your multi-threaded code for race conditions and deadlocks?

To see if they are performing the way they should be...

答:
Tests with non-reproducible results are useless. That rules out completely random tests, but leaves in tests generated from pseudo-random sequences.

Every actor in a concurrent environment has algorithmic or otherwise non concurrency components that can be tested by conventional means. Having tested them, any remaining failures must be lie in the concurrency logic.

The events in a concurrent system are always in fact a linear sequence of events. If enough precision is used to measure time, then there are no events happening "at the same time". That means that the actors in a concurrent system can be tested by generating events sequentially. Capturing the sequence of events around the time of failure of a concurrent system provides the required test cases.

The code that provides actors with liveliness (threads) is more-often-than-not provided by the operating system or by system libraries. It is safe to assume that said code needs not be tested. The code in charge of communication and synchronization is normally written by the applications programmer. That code can be tested without invoking the system code, that is, without launching any threads.

Boundary conditions in the algorithmic code (queue empty) often require handling in the synchronization code, and that is a good target for testing.

Defining proxies around system code (t.wait()) allows for the use of stubs/mocks of the functionality during testing.

Title: How do I unit test multi-threaded code?


答:
Moving from Python to C/C++ is a substantial jump in complexity and is no surprise that you are wanting to find a way to manage that complexity in your code.

In reality, trying to write your own complexity management layer will fail. In part, because you probably don't know enough about the language and how to use it effectively to do a good job, and secondly there are already libraries out there that provide what you are after (albeit it a C/C++ way, not python)

Have a good read through the Standard Template Library code, particularly around the shared_ptr and auto_ptr classes as ways to manage the heap memory safely.  This will, over time give you a good understanding of the way to solve problems in C++, rather than trying to use C++ to write python code.

Title: Encapsulate standard C functions?


答:
+1 @mouviciel.

I came into C from the Pascal highway (Turbo Pascal and yea, it was a long time ago).  I decided that C needed "Begin" and "End" and struggled for months to no avail.  In the end I gave up because there were bigger fish to worry about.  Any interpretive changes you make will have to be logical to whoever has to update your code in a few months (or years).  Odds are that won't happen because they aren't you and don't have your POV.  Your code (and reputation) will get thrown under the proverbial bus.

I suggest just bite the bullet and dig in.  Embrace the preprocessor.  You will have to contend with the failure of the presentation layer to control the functional (the Pythonic White Space Rules paradigm).  I'd also recommend jumping to C++ since you've already gotten past the O-O hurdle.  You're gonna love multiple base classes and having to do your own GC.

My favorite reference was the Harbison-Steele but that (as noted) was many moons ago.

Title: Encapsulate standard C functions?


问:
Hyperlinked, externalized source code documentation
Why do we still embed natural language descriptions of source code (i.e., the reason why a line of code was written) within the source code, rather than as a separate document?

Given the expansive real-estate afforded to modern development environments (high-resolution monitors, dual-monitors, etc.), an IDE could provide semi-lock-step panels wherein source code is visually separated from -- but intrinsically linked to -- its corresponding comments. For example, developers could write source code comments in a hyper-linked markup language (linking to additional software requirements), which would simultaneously prevent documentation from cluttering the source code.

What shortcomings would inhibit such a software development mechanism?

A mock-up to help clarify the question:

When the cursor is at a particular line in the source code (shown with a blue background, above), the documentation that corresponds to the line at the cursor is highlighted (i.e., distinguished from the other details). As noted in the question, the documentation would stay in lock-step with the source code as the cursor jumps through the source code. A hot-key could switch between "documentation mode" and "development mode".

Potential advantages include:

More source code and more documentation on the screen(s) at once

Ability to edit documentation independently of source code (regardless of language?)

Write documentation and source code in parallel without merge conflicts

Real-time hyperlinked documentation with superior text formatting

Quasi-real-time machine translation into different natural languages

Every line of code can be clearly linked to a task, business requirement, etc.

Documentation could automatically timestamp when each line of code was written (metrics)

Dynamic inclusion of architecture diagrams, images to explain relations, etc.

Single-source documentation (e.g., tag code snippets for user manual inclusion).

Note:

The documentation window can be collapsed

Workflow for viewing or comparing source files would not be affected

How the implementation happens is a detail; the documentation could be:

kept at the end of the source file;

split into two files by convention (filename.c, filename.c.doc); or

fully database-driven

By hyperlinked documentation, I mean linking to external sources (such as StackOverflow or Wikipedia) and internal documents (i.e., a wiki on a subdomain that could cross-reference business requirements documentation) and other source files (similar to JavaDocs).

Related thread: What's with the aversion to documentation in the industry?

答:
Possible disadvantages that I see:

You need a special editor that implements this feature

The code is not just plain text anymore, easy to manipulate and commit to VCS-es

You need twice more screen width to work with the code

As for your arguments:

More source code and more documentation on the screen(s) at once

But can be inconvenient if you want to view two files side-by-side.

Ability to edit documentation independently of source code (regardless of language?)

I would argue that it is actually a disadvantage. I personally try to keep the documentation as close as possible to the code, so that it does not become outdated.

Write documentation and source code in parallel without merge conflicts

Again, possibly a disadvantage. If your docs are deeply interleaved with code, how can you edit them independently?

Real-time hyperlinked documentation with superior text formatting

If it is in the code, it is already real-time ;) As for the hyperlinks, jumping to definition is already implemented in most IDEs.

Quasi-real-time machine translation into different natural languages

I don't see why you can't do that with regular comments/docstrings.

Every line of code can be clearly linked to a task, business requirement, etc.

This I'm uncertain about... Can't it be achieved with regular comments?

Documentation could automatically timestamp when each line of code was written (metrics)

Don't VCS-es provide this kind of information already?

Having said this, I quite like the layout itself — but I do not see the need of changing the file format, it is not that difficult to generate it from regular comments. There's a bunch of documentation generators which do that, e.g. Docco and its successors, like Pycco or Marginalia.


答:
Firstly, the doc comments need to go with the code - moving them elsewhere only makes things incredibly difficult to handle for practically zero gain. So why bother!

What could be done though is to take those embedded comments and hide them in the editor, showing them in a bubble or tooltip or whatnot as needed. I would hope that such an approach might encourage people to write much more documentation to the code - eg, a description of a class could go with the class rather than in an external design document.

You can currently embed hyperlinks in code comments, and you can generate documents from the code using tools like Doxygen or Sphinx. I guess it just would take some fancy extension tot he code editor to better support these tools.

I wouldn't link any lines of code to a bug tracker or requirements tool, that's a better job for your SCM. Then you can see code edits per commit that are linked to a task. I wouldn't integrate the documentation stored in the code against the bug tracker either - you'd be screwed if you ever wanted to migrate to a new one (hmm, I can see this feature being added to TFS right now) or if you lost your commit history (which happens)

Title: Hyperlinked, externalized source code documentation

Body:
Why do we still embed natural language descriptions of source code (i.e., the reason why a line of code was written) within the source code, rather than as a separate document?

Given the expansive real-estate afforded to modern development environments (high-resolution monitors, dual-monitors, etc.), an IDE could provide semi-lock-step panels wherein source code is visually separated from -- but intrinsically linked to -- its corresponding comments. For example, developers could write source code comments in a hyper-linked markup language (linking to additional software requirements), which would simultaneously prevent documentation from cluttering the source code.

What shortcomings would inhibit such a software development mechanism?

A mock-up to help clarify the question:

When the cursor is at a particular line in the source code (shown with a blue background, above), the documentation that corresponds to the line at the cursor is highlighted (i.e., distinguished from the other details). As noted in the question, the documentation would stay in lock-step with the source code as the cursor jumps through the source code. A hot-key could switch between "documentation mode" and "development mode".

Potential advantages include:

More source code and more documentation on the screen(s) at once

Ability to edit documentation independently of source code (regardless of language?)

Write documentation and source code in parallel without merge conflicts

Real-time hyperlinked documentation with superior text formatting

Quasi-real-time machine translation into different natural languages

Every line of code can be clearly linked to a task, business requirement, etc.

Documentation could automatically timestamp when each line of code was written (metrics)

Dynamic inclusion of architecture diagrams, images to explain relations, etc.

Single-source documentation (e.g., tag code snippets for user manual inclusion).

Note:

The documentation window can be collapsed

Workflow for viewing or comparing source files would not be affected

How the implementation happens is a detail; the documentation could be:

kept at the end of the source file;

split into two files by convention (filename.c, filename.c.doc); or

fully database-driven

By hyperlinked documentation, I mean linking to external sources (such as StackOverflow or Wikipedia) and internal documents (i.e., a wiki on a subdomain that could cross-reference business requirements documentation) and other source files (similar to JavaDocs).

Related thread: What's with the aversion to documentation in the industry?


答:
Besides what @Bogdan already states, I would add a few:

I configured my IDE to always have 2 files at once. With the feature you are suggesting, I would basically need 2 monitors to see the same amount of information, and 3 to do what I'm doing now with 2.

While browsing through a file, you don't immediately see the comments, and if you don't know exactly what you are looking for, it's very difficult to find it.

While searching through a file, I can't search through comments directly (or as easily).

I sometimes need to do various tests / write short pieces of code on the live server, through ssh. Although the functionality you are saying could be integrated with VIM or other command line editors - most likely there would be pretty big problems

Most IDEs support collapsing code/comments, with the end results being the following:

Instead of the normal:

Make the code more readable, in case you don't need the comments.


答:
404 - Page Not Found

When working with code you don't want you comments to get lost and that's what will happen when you seperate code and comments into seperate documents.

Also, keeping up versioning between your comment document and code document will cause more pain then gain.

Some of the suggestions you make I really like but could easily be implemented while also having code and comments in 1 file.


答: We used to have a two semester class named The Basics of Programming. Both mid-semester tests and exams at the end were done on paper. If you made any compile errors you lost a serious amount of points. If you made huge compile errors, you failed. However I feel it developed the ability in us to take a look at any code and find buggy lines in a relatively shorter amount of time.</p>


问:
Open source project question in interview
I've recently applied for a position as C# developer, and during the interview, the interviewers asked me many times if I contribute to develop one or more open source project.

Since they let me write a lot of code (from basics to TDD,MVVM,MVP), I didn't get the meaning of such a question, especially cause they insisted a lot on the topic and the thing started to bother me.

I wish I could have time enough to develop open source software, but I don't get why a company that sells software pretend that their employees work for free in their spare time.

What's the real reason of this question (apart from checking your code)?

答: Writing for open source projects in your spare time can show a love for coding. I can only guess to their reasoning, but maybe they want a programmer who loves programming rather then someone who only considers it work.</p>


答:
There is only one way to be sure what was reason for the question, and that's for the interviewer to answer on here.

I can think of several reasons why it might be asked at interview:

They have had past problems with employees contributing to open
source projects which have affected the company.  e.g. doing it in
work time, or cross contamination of source code.

They thought that they recognised your name as a contributor on a project from your CV - and that's why they brought you in for interview.

They have a company ethos of encouraging developers to do open source in their spare time, and were looking for a culture match

Title: Open source project question in interview

Body:
I've recently applied for a position as C# developer, and during the interview, the interviewers asked me many times if I contribute to develop one or more open source project.

Since they let me write a lot of code (from basics to TDD,MVVM,MVP), I didn't get the meaning of such a question, especially cause they insisted a lot on the topic and the thing started to bother me.

I wish I could have time enough to develop open source software, but I don't get why a company that sells software pretend that their employees work for free in their spare time.

What's the real reason of this question (apart from checking your code)?


问:
Which ASP.Net programming model is closer to PHP?
I've been using ASP.Net WebForms for the last year or two at work for development, but I've used PHP for personal projects for 10 years. So, I'm far more adept at developing with PHP.

When it comes to ASP.Net MVC, I have no experience with it because I've avoided it because I assumed it would just be a more complicated form of WebForms. Recently, I've been doing more research and it's sounding like MVC might be closer to what what I want. But, something I'm still not clear on is which ASP.Net programming model is closer to developing with PHP.

My biggest complaint about ASP.Net WebForms is the "magic boxes." Namely the View State, and ScriptManager.

I don't like that WebForms messes with my client side HTML/JavaScript/CSS. WebForms does a lot of this including, but not limited to:

Inserting JavaScript that I can't modify and have to rely on Microsoft to ensure cross-browser compatibility.

Forcefully changing the name attributes of tags that make use of  runat="server".

Wrapping the contents of a <form> with a
 tag.

Forcing wrapping everything inside one big <form> tag.

Everything in WebForms feels like it's catered to in-experienced web-developers who only know how to write Windows applications with .Net.

Standard names for tags and attributes are changed when using <asp:xxx> tags. For example, instead of an anchor () tag, it's a "hyperlink" (i.e. <asp:HyperLink>). Instead of href= it's NavigationUrl=.

The event driven model.

I also don't like the complete separation of server side code from the client side code. I miss being able to do things like this...

```<code> <table>
     <tr>
         <td>Name</td>
         <td>Age</td>
     </tr>
     <? foreach( $people as $person ) { ?>
     <tr>
         <td><?= $person->name ?></td>
         <td><?= $person->age ?></td>
     </tr>
     <? } ?>
 </table>
</code>```

So, with these points in mind, which programming model is closer to development with PHP (i.e. do the annoyances of WebForms that I've listed here exist in MVC)?

Note: I have found ways around many, if not all of these annoyances, but did not feel the solutions I use are revelent to the question at hand.

答:
In ASP.NET MVC (3 and greater) using razor the example would be

```<code><table>
  <tr>
    <td>Name</td>
    <td>Age</td>
  </tr>
@foreach(var person in people)
{
  <tr>
    <td>@person.Name</td>
    <td>@person.Age</td>
  </tr>
}
</table>
</code>```

The same syntax can be used in ASP.NET Web Pages.
There are differences in there two technologies.

In MVC there are separate classes for controllers and models. The project has more specific structure. The project is built before deployment.

Web Pages project is compiled on the fly, so you can just change a file and changes appear. It doesn't have same kind of "pipeline" as MVC.

I would recommend MVC, but Web Pages is more like PHP.

Body:
In ASP.NET MVC (3 and greater) using razor the example would be

<table>
  <tr>
    <td>Name</td>
    <td>Age</td>
  </tr>
@foreach(var person in people)
{
  <tr>
    <td>@person.Name</td>
    <td>@person.Age</td>
  </tr>
}
</table>

The same syntax can be used in ASP.NET Web Pages.
There are differences in there two technologies.

In MVC there are separate classes for controllers and models. The project has more specific structure. The project is built before deployment.

Web Pages project is compiled on the fly, so you can just change a file and changes appear. It doesn't have same kind of "pipeline" as MVC.

I would recommend MVC, but Web Pages is more like PHP.