答:
Firstly, you will want to ask the interviewer two questions.

Question 1.

whether the interviewer expects one or more "central machines" to be used to assign some unique numbers, or blocks of unique numbers.

Question 2.

Whether the interviewer expects a mechanism for collision detection, or instead  accept the calculated risk of a minuscule chance of collision without explicitly detecting them.

There is also the defense-in-depth approach, in which one incorporates some part of user-ID into the randomness (thus, not entirely random). The chance that the same user encounters a collision within the content created by that same user is therefore lowered.

There is an implicit question 3, ...

But it is one you'll have to gauge yourself without asking, because it is extremely impolite to ask your interviewer.

Whether the interviewer assumes the knowledge of probability, risk, and some simple techniques employed in cryptographic and information-security systems.

The first kind of knowledge ensures you're not trying to convince a non-scientific person into accepting a scientific concept they won't accept.

The second kind of knowledge ensures that you addresses concerns which are in addition to mere probability. In other words, how to defend against "assailants" who want to intentionally break your randomization scheme, by manipulating the machine(s) or their virtual hosts to force two machines to generate the same value.

Why ask.

The reason is that if the interviewer expects it one way or another, trying to answer with the opposite approach will never make the interviewer happy.

The deeper reason is that some people do not like the idea of say, a 1.0e-20 chance of failing. (I'll try not to stir up philosophical or religious arguments here.)

First of all the "namespace" of random numbers are made into a hierarchy, with certain number of bits allocated to one source of randomization, and the other number of bits allocated to some other ways, etc.

The centralized approach relies on some central authority to uniquely assign the first level of bits. Then, the other machines can fill the rest of the bits.

There are several decentralized approaches:

Just generate random numbers as good as one could, and accept the practically-zero chance of failing justified by calculations.

Use cryptographic means of generating random values from deterministic source, say, an incrementing values.


问:
Function guaranteed to never return the same value twice
This is a question I was asked at a job interview, and I can't figure out the answer they were looking for, so I'm hoping someone here might have some ideas. The goal is to write a function that is guaranteed to never return the same value twice. Assume that this function will be accessed by multiple machines concurrently.

My idea was to assign each machine a unique id and pass that value into the unique value generator function:

```<code>var i = 0;
function uniq(process_id, machine_id) {
   return (i += 1).toString() + machine_id + "-" + process_id;
}
</code>```

This would avoid the fallout from race conditions since even if two or more processes read the same value for i, each return value is tagged a unique combination of process id and machine id. However, my interviewer didn't like this answer because bringing another machine online involves assigning it an id.

So can anybody think of another way to solve this that doesn't involve configuring each machine to have a unique id? I'd like to have an answer in case this question comes up again. Thanks.

答:
Guaranteeing uniqueness is difficult because computers do not have infinitely-large variables. No real-world Turing machine can.

The way I see it there are two problems here, and both have well-established solutions.

Concurrency. Multiple machines may need a value at the same time. Thankfully, modern CPUs have concurrency built-in and some languages provide developer-friendly facilities to take advantage of this.

Uniqueness. While impossible to guarantee uniqueness, we can have arbitrarily-large variables which can hold values so large that a real-world system would have a very difficult time exhausting all of the unique values

Here is my solution in Java:

```<code>public class Foo {
  private static BigInteger value = BigInteger.ZERO;
  private static final Lock lock = new ReentrantLock();

  public static BigInteger nextValue() {
    try {
      lock.lock();
      value = value.add(BigInteger.ONE);
      return value;
    }
    finally {
      lock.unlock();
    }
  }
}
</code>```

BigInteger is an arbitrary-size integer type. It can grow to hold values that are quite large, even if not infinite. The lock ensures concurrency, so the same value cannot be returned twice by two simultaneous requests serviced by separate threads.

ContentLicense: CC BY-SA 3.0

Body:
Guaranteeing uniqueness is difficult because computers do not have infinitely-large variables. No real-world Turing machine can.

The way I see it there are two problems here, and both have well-established solutions.

Concurrency. Multiple machines may need a value at the same time. Thankfully, modern CPUs have concurrency built-in and some languages provide developer-friendly facilities to take advantage of this.

Uniqueness. While impossible to guarantee uniqueness, we can have arbitrarily-large variables which can hold values so large that a real-world system would have a very difficult time exhausting all of the unique values

Here is my solution in Java:

public class Foo {
  private static BigInteger value = BigInteger.ZERO;
  private static final Lock lock = new ReentrantLock();

  public static BigInteger nextValue() {
    try {
      lock.lock();
      value = value.add(BigInteger.ONE);
      return value;
    }
    finally {
      lock.unlock();
    }
  }
}

BigInteger is an arbitrary-size integer type. It can grow to hold values that are quite large, even if not infinite. The lock ensures concurrency, so the same value cannot be returned twice by two simultaneous requests serviced by separate threads.


问:
My class diagram needs to model a relationship with varying quantities
I am trying to design a restaurant ordering system in UML, which should also include the stock system.

One of the classes is a Dish (i.e. a dish on the menu), and another is an Ingredient.

My initial idea was to place an aggregation of Ingredients within Dish, but I've also read that a many to many relationship is more appropriate.

My problem is that in this case, simply having a relationship isn't enough. For instance a Dish could have 30g of Ingredient A, while another Dish could have 20g of Ingredient A.

How can I model this kind of dependency in UML?

答: An Ingredient is a Product in a Recipe (or Dish) with it's Quantity (quantity should include Unit of Measure and be translatable between units). A Recipe contains many Ingredients. A Product can be in many Ingredients. And can be in Stock with a Quantity as well.</p>


问:
Is there a technical reason why you can't develop iOS apps on a Linux computer?
I understand why you can't develop OS X apps on a Linux computer, but is there a good technical reason why you can't develop iPhone and iPad apps on Linux?  Why isn't it possible to compile iOS source code into an iOS executable and run it in an iOS simulator on Linux or install it on a development iOS device?

Is it just because the XCode IDE is a Cocoa application?

You can develop Android apps on any kind of platform, it seems. I don't see why the same can't be true of iOS.

答:
While you cannot sign applications for iOS on Linux, and thus distribute them through the accepted methods, you can develop (with the same APIs) on Linux using Theos. This is the toolchain used by the jailbreak community to develop apps for iOS, and it is cross-platform. If your iOS device is jailbroken, I believe you'll be able to push the compiled application to your device via libimobiledevice, but someone may correct me if I'm wrong.

Some more information: http://iphonedevwiki.net/index.php/Theos

I plan to give this a go in the next day or so, and I'll provide updates.


答:
The interviewer said the method will be called concurrently, not in parallel; just return the date/time down to as many decimal places as you can.

Why is everyone over-thinking this?  You'll be dead a long time before any finiteness is expended and you don't have a chance of a collision.

If you're worried about it returning the same time, add a delay for the smallest amount of measurable time.

If you're worried about setting a clock back for daylight savings time (experiencing 1 time twice), add a constant to the time the second time you experience it.

Title: Function guaranteed to never return the same value twice

Body:
This is a question I was asked at a job interview, and I can't figure out the answer they were looking for, so I'm hoping someone here might have some ideas. The goal is to write a function that is guaranteed to never return the same value twice. Assume that this function will be accessed by multiple machines concurrently.

My idea was to assign each machine a unique id and pass that value into the unique value generator function:

```<code>var i = 0;
function uniq(process_id, machine_id) {
   return (i += 1).toString() + machine_id + "-" + process_id;
}
</code>```

This would avoid the fallout from race conditions since even if two or more processes read the same value for i, each return value is tagged a unique combination of process id and machine id. However, my interviewer didn't like this answer because bringing another machine online involves assigning it an id.

So can anybody think of another way to solve this that doesn't involve configuring each machine to have a unique id? I'd like to have an answer in case this question comes up again. Thanks.


问:
How to check in website/url have been updated or not?
I am trying to make a Android application which will take your URL and if there is new update on that website then it will show the user that this link have been updated.

I am working on the project which will check for the website if they have been updated or not.
I know that there are RSS on most of websites, but I am talking about those websites which don't have but are important for us. Like the websites where result will be posted but for that I will have to check that website again and again.

How can I check that website is updated or not?

答:
Reinventing the wheel, huh?  I personally let https://www.changedetection.com/ send me an email & leave it to them to figure out if the page has changed. Perhaps your app could just scan your in-box for such emails? Or maybe a similar site has an API for developers?

There is some good info on WIkipedia. See also "5 Free Tools To Notify You of Website Content Changes".

If I had to code it from scratch, I would get the web page and generate an MD5 checksum. Fetch the page at regular intervals, regenerate the checksum and compare with the one stored in your database (of course,t eat will be triggered by a single character change, but you didn't specify what you consider to be a change - always nail down the requirements before getting into implementation).


问:
Is seeing loads of merge messages in a git branch standard, or are we working incorrectly?
We're in the process of switching from SVN to git, and I've noticed that we're seeing a lot of these commit messages in git:

Merge branch 'development' of [Url to Origin].

These are coming in where other developers are pulling down changes from remote, into their local repo, before they push their changes back into remote (I think, clarification would be great if not).

I just wanted to check that it's expected to see these messages in the remote, considering there's only 3 of us working on the project at the moment, but it seems like every other commit is one of these messages, making it a bit harder to gleam any useful information from the commit logs?

(Tagged as Visual Studio as I believe the message is auto-generated by VS when you use their IDE?)

答:
Since git is (in my opinion, and maybe everyone else's) more complicated than SVN, answering this single question will do you more harm than good. Sounds like you didn't spend time on learning the fundamentals.

I suggest you (and your entire team) read the great, well written tutorials by Atlassian (go to the 'getting started' section). I read them after some time of just winging it with git after migrating from svn, and I can't stress enough how important it is to actually sit down and read about how things work there:

https://www.atlassian.com/git/tutorials/


答:
These are coming in where other developers are pulling down changes from remote, into their local repo, before they push their changes back into remote (I think, clarification would be great if not).

That's absolutely correct.

I just wanted to check that it's expected to see these messages in the remote,

It's perfectly normal. If they're very noisy, alternatives are:

use git pull --rebase (you can configure this as the default behaviour) instead. This means everyone's local changes are always (re)based onto the remote branch HEAD, and pushes are always fast-forward.

You do have to be comfortable with fixing the rebase if it doesn't apply cleanly though, and with commits showing up out of time order

work on feature branches and merge less frequently

Title: Is seeing loads of merge messages in a git branch standard, or are we working incorrectly?

Body:
We're in the process of switching from SVN to git, and I've noticed that we're seeing a lot of these commit messages in git:

Merge branch 'development' of [Url to Origin].

These are coming in where other developers are pulling down changes from remote, into their local repo, before they push their changes back into remote (I think, clarification would be great if not).

I just wanted to check that it's expected to see these messages in the remote, considering there's only 3 of us working on the project at the moment, but it seems like every other commit is one of these messages, making it a bit harder to gleam any useful information from the commit logs?

(Tagged as Visual Studio as I believe the message is auto-generated by VS when you use their IDE?)


问:
Would you use C, today, for a software project?
If yes, where and why would you use it?

If no, please provide an explanation to why C is not acceptable to you.

答:
I use C professionally, nearly every day.  In fact, C is the highest level language in which I regularly program.

Where I use C: I write low-level library code that has a requirement to be as efficient as possible.  My glue code is written in C, inner computational loops are written in assembly.

Why I use C: It's much simpler to handle complex argument structures and error conditions than it is in assembly, and the performance overhead for that sort of condition checking before starting the real computation is often negligible.  Because C is a simple, well-specified language, I have an easy time working with the compiler team at work to improve the code generation whenever I see compiled code with unacceptable performance hazards.

Portability is another great virtue of C.  My glue code is shared across multiple hardware-specific implementations of the libraries I work on, which really simplifies bringing up support for new platforms.  Most platforms don't have a virtual machine or interpreter for the language flavor of the month.  Some platforms don't have a good C++ compiler.  There are very few platforms that lack a usable C compiler (and, since I have a good working relationship with our compiler team, I usually don't have a hard time getting the support I need).

ContentLicense: CC BY-SA 2.5


答:
So, keeping in mind that this is an interview question and not an actual real-life scenario, I believe the correct approach (and probably what the interviewer is looking for) is to ask a clarifying question, or to write "It can't be done" and move on. Here's why.

What the Interviewer Asks:

Write a function that is guaranteed to never return the same value twice. Assume that this function will be accessed by multiple machines concurrently.

What the Interviewer Needs:

Does this candidate effectively evaluate requirements and seek additional input when required?

Never Assume.

When an engineer is handed a requirement (via a SOW or Specification or some other requirements document), some are self-evident, and others are totally unclear. This is a perfect example of the latter. As the previous answers have shown, there is no way to respond to this requirement without making several major assumptions either (a) as to the nature of the question or (b) as to the nature of the system, because the requirement cannot be met as-written (it is impossible).

Most of the answers make one attempt or another at solving the problem via a series of assumptions.  One specifically recommends to just get it done quickly and let the customer worry about it if it's wrong.

This is really a bad approach.  As a customer, if I give an unclear requirement, and the engineer goes off and builds me a solution that doesn't work, I am going to be upset that they went to work and spent my money without bothering to ask me first. That sort of cavalier decision-making  demonstrates a lack of teamwork, inability to think critically, and poor judgement.  It can lead to any manner of negative consequences, including loss-of-life in a safety critical system.

Why Ask the Question?

The point if this exercise is that it is expensive and time-consuming to build to ambiguous requirements. In the OP's case, you have been given an impossible task. Your first action should be to ask for clarification - what is it that is required? What degree of uniqueness is needed? What happens if a value is non-unique? The answer to these questions could be the difference between several weeks of time and a few minutes.  In the real world, one of the biggest drivers of cost in complex systems (including many software systems) is unclear and poorly-understood requirements. This leads to expensive and time-consumig bugs, re-designs, customer and team frustration, and embarassing media coverage if the project is large enough.

What Happens When You Assume?

Given my background in the aerospace industry, and due to the highly visible nature of aerospace failures, I like to bring up examples from this domain to illustrate important points.  Let's examine a pair of failed Mars missions - the Mars Climate Orbiter and Mars Polar Lander.  Both missions failed due to software problems -- because engineers made invalid assumptions due, in part, to unclear and poorly-communicated requirements.

Mars Climate Orbiter - this case is typically cited as what happens when NASA tries to convert English to Metric units. However, that is an overly simplistic and poor representation of what really transpired. True, there was a conversion problem, but it was due to poorly-communicated requirements in the design phase and an improper verification/validation scheme. Furthermore, when two different engineers noticed the problem because it was obvious from flight trajectory data, they didn't raise the issue to the proper level because they assumed it was a transmission error. Would the mission ops team have been made aware of the issue, there was adequate time to correct it and save the mission. In this case, there was an impossible logical condition that was not recognized for what it was, leading to costly mission failure.

Mars Polar Lander - this case is a little less well-known, but possibly more embarassing due to its temporal proximity to the Mars Climate Orbiter failure. In this mission, the software controlled the thruster-assisted descent of the rocket into the Martian surface. At a point 40 meters above the surface, the legs of the lander deployed in preparation for landing. There was also a sensor on the legs that detected motion (to signal when they had impacted) to tell the software to shut off the engine. NASA's best guess as to what happened (because there are multiple possibile failures and incomplete data) is that random vibrations in the legs due to their deployment simultaneously and improperly triggered the shutdown mechanism 40m above the surface, resulting in the crash and destruction of the $110M spacecraft. This possibility was raised in development, but was never addressed.  Ultimately, the software team made invalid assumptions about how this code needed to run (one such assumption is that a spurious signal would be too short-lived to be picked up, despite tests showing the contrary), and those assumptions were never questioned until after the fact.

Additional Considerations

Interviewing and evaluating people is a tricky business. There are several dimensions of a candidate that an interviewer may wish to explore, but one of the most important is an idividual's ability to think critically. For a variety of reasons, not the least of which is that critical thinking is poorly-defined, we have a very difficult time evaluating critical thinking skills.

As an engineering instructor, one of my favorite ways to evaluate a student's ability to think critically was to ask a somewhat ambiguous question. The sharper students would pick up on the question's faulty premise, note it, and either answer given the premise or decline to answer altogether. Typically, I would ask a question similar to the following:

You pick up a drawing from your stack of work. The drawing contains a variety of different callouts, but the most important points to a horizontal surface and says "Perfectly flat". The surface is 5" wide by 16" long, and the part is made of aluminum. How will you machine the part to create this feature?

(By the way, you would be shocked at how often such a poor specification appears in the workplace.)

I expect that students will recognize that it is not possible to create a perfect feature, and that they will state this in their answer. I typically would award a bonus point if they say they will go back to the designer and ask for clarification before making the part. If a student proceeds to tell me how they are going to achieve .001 planarity or some other made up value, I award zero points.  This helps me make a point to my students that they need to be thinking of the bigger picture.

Bottom Line

If I am interviewing an engineer (or similar profession), I am looking for someone who can think critically and question what has been placed in front of him. I want someone who asks the question "Does this make sense?"  .

It does not make sense to ask for a perfectly flat part, because there is no such thing as perfect. It does not make sense to ask for a function that never returns a duplicate value, because it is impossible to make such a guarantee. In programming, we often hear the phrase "garbage in, garbage out." If you are handed garbage for requirements, it is your ethical responsibility to stop and ask whatever question helps you elicit the true intent. If I'm interviewing a candidate, and I give them an unclear requirement, I am going to expect clarification questions.


问:
calculating the average of a value over a month
I am working on a project right now that is having me calculate monthly interest on a bank account. The way the interest is supposed to be calculated is as follows:

Use the daily average to calculate interest. The daily average balance of an account is calculated by the taking the average of the end of the day balance for every day in the month. So, at the end of the every month, calculate the daily average balance for that month and use this to calculate interest.

The basic gist of my software is as follows: it's a Desktop Java Application with a Swing GUI and a serialized text file to store information about bank accounts when the software is not running.

What is a good way to go about calculating this daily average and applying interest at the correct time?

NOTE: If possible, I really really do not want to have to implement some sort of centralized data base with SQL or something similar. This would require me to rewrite a lot of code, and I don't know really anything about SQL as it is..

Additional Info

I will be using Joda-Time to keep track of the time/date.

I have contemplated just doing some sort of calculation on the time, date and balance every time I close/open the program. But what if the software is left running for, say 15 days straight?

Let's say I just wanted to implement some code to calculate the average balance for the month whenever the program is opened, and not worry about the program being run for days at a time. How could I go about doing this? I was thinking about having some sort of lastAccessed field that would store the date of the last time the program was opened. Then calculate the the average every time the software was opened using that last accessed field somehow.

答:
First I am going to put a disclaimer:

I really hope this is a school assignment project because storing account numbers and maintaining funds balance in a desktop application with a text file is unbelievably insecure and prone to error.  I vehemently recommend more of a client/server/database design with security built between all layers.

With that being said, I will give you some advice as to how many banking and accounting systems manage funds and account balances.

Maintain a master account record with a master balance.  Throughout the day when debits or credits are initiated in your application you will correspond these to a separate record that maintains Hold's against account numbers.

What is a hold?  It is a temporary hold of money on an account.  For an account that is being debited funds, you put a hold on that account for the amount to transfer.  The account receiving the credit will also have a Hold that signifies it will eventually be credited with the amount of the transfer.

Before initiating a transaction you have to do a balance check on the accounts to authorize the transaction.  Take into account the master account balance +/- all debit and credit holds on the account.

At the end of the day at a specified time, or after the application starts up you need to do what is called "Hard charging".  This is where you calculate the new master balance of the accounts in the ledger with all of the holds that have been previously placed.  This new balance will be your starting point now for the remainder of the day.

Why this complexity?  This allows for easier integration with accounting packages and software as well as with payments going out to a bank or other financial institution.


答:
I would expose the function via a port on the server; to call the function, the requesting machine requests a connection and is granted one, while at the same time being allocated an identifying code (sequential number for simplicity). Whenever a message is sent to the port requesting the unique value, the value is generated by concatenating the MD5 hash of the current date and time with the MD5 hash of the identifying code.

If they want a more bulletproof solution they would have to specify their actual requirements rather than being all vague about things.


问:
Method for all objects for checking conditions which also includes method chaining and avoiding variables
(I am currently using groovy but it should apply to most OO languages so I also put the langauge-agnostic tag)

I try to program in a function style which also includes method chaining and avoiding variables. Therefore I often find myself writing code with the with method in groovy that every object has. It works likes this:

```<code>someobject
.doSomething()
.doEvenMore() //this results in an object that I need check for some condition, e.g. a String
.with { String result ->
    if (result != "I AM A CORRECT RESULT")
        throw new Exception("assertion failed")
    else
        return result  //need to do this because else the closure will return null
}
.doAnotherThingOnTheResult()
//and so on
</code>```

(See also https://codereview.stackexchange.com/questions/57676/better-way-to-assert-correct-return-values-in-groovy for a real life example I asked some time ago)

This is rather unconcise so I was searching for a better way to check for conditions without using to have with. I came up with an idea I would like to hear your opinions to.
That is, an method that all objects have and that can be used like this:

```<code>someobject
.doSomething()
.doEvenMore() //this results in an object that I need check for some condition, e.g. a String
.assertTrue (new Exception("custom exception")) { it == "I AM A CORRECT RESULT" }
.doAnotherThingOnTheResult()
//and so on
</code>```

or for default behaviour with a default exception type

```<code>someobject
.doSomething()
.doEvenMore() //this results in an object that I need check for some condition, e.g. a String
.assertTrue { it == "I AM A CORRECT RESULT" } //results in AssertionException or sth similiar
.doAnotherThingOnTheResult()
//and so on
</code>```

In groovy I can make it that every (new) created object is decorated with such a method. What do you guys think about it? Are there better ways or should I stay with the with method?

答:
First, I think it is a good idea to refactor the with part into its own function. It makes IMHO the code easier to read, and it corresponds to the "Single Level of Abstraction" principle, which is one characteristic of clean code.

Second, if it is a good idea to decorate every class of your program with this additional method, depends. I would do this only if you need this function all over your whole program, in many classes. Otherwise, I would restrict it to the classes which really use the method. This helps to avoid unintentional naming collisions.


问:
Best way to handle delimited files
So typically a CSV file uses a comma and the return character as it's field and line delimiters.

This runs into obvious problems with text which can contain both these characters.

Obviously there are options there (escaping them) but how do people handle this?  Use different characters - pipes or tildas?  Escape them?  Not use delimited files, after all it's 2010 and we have XML now?

Looking at least effort for a decent chance of not seeing problems.

(Just to be clear, this is a question out of curiosity rather than something more solid - it's something I've come up against time and time again playing with data, always got round it but it normally feels a bit, well, dirty, and wondered what other people's experience was).

答:
Usually, what I find myself doing is getting a TSV (tab-separated values) rather than a CSV file, pull the file into Emacs and see which of a few uncommon characters it NEVER uses ($ is usually a good choice around here), and then I convert all the tabs to $.

From there, GNU AWK can be told to use $ as the field separator, and Bob's your uncle.

Title: Best way to handle delimited files


问:
Objects in smalltalk and c++
I have a question based on SmallTalk and C++. In one of the programming languages books, there is a question like:

"Does an object in Smalltalk require its own private stack? What about in C++?"

Could you please explain those questions above if you know the answers?

Thanks.

答:
I cannot speak for Smalltalk, but for C++, the stack is used by the entire program. Each object in the program shares the stack, based on when they are used. Objects in the stack are managed by the OS and are deleted when they fall "out of scope" in C++. For example, consider the following code:

```<code>// Global declarations and function prototypes
int x, y;
void someFunction();

int main()
{
    someFunction();
    // w and x are deleted here
}

void someFunction()
{
    int w, x;
}
</code>```

The variables x and y will remain on the stack until the program closes because they are global. The variables w and x will be declared and thus "grow" the stack when the program enters someFunction() so they can be used, and then will be deleted and thus "shrink" the stack when someFunction() exits.

Even objects such as classes do not have their own stack, because they are ultimately using the stack when they are instantiated, and are destroyed when they fall out of scope via the destructor.

A better way to say it is that each program gets its own stack, but the objects in it do not.

Title: Objects in smalltalk and c++

Body:
I cannot speak for Smalltalk, but for C++, the stack is used by the entire program. Each object in the program shares the stack, based on when they are used. Objects in the stack are managed by the OS and are deleted when they fall "out of scope" in C++. For example, consider the following code:

// Global declarations and function prototypes
int x, y;
void someFunction();

int main()
{
    someFunction();
    // w and x are deleted here
}

void someFunction()
{
    int w, x;
}

The variables x and y will remain on the stack until the program closes because they are global. The variables w and x will be declared and thus "grow" the stack when the program enters someFunction() so they can be used, and then will be deleted and thus "shrink" the stack when someFunction() exits.

Even objects such as classes do not have their own stack, because they are ultimately using the stack when they are instantiated, and are destroyed when they fall out of scope via the destructor.

A better way to say it is that each program gets its own stack, but the objects in it do not.


问:
Why are self-hosting compilers considered a rite of passage for new languages?
I've heard in a number of places now that people expect languages to use, or at least have, a self-hosting compiler in order to deserve respect.

I'm curious as to why this is. A compiler seems like a very significant piece of software to write, and I imagine not all languages are well-suited to creating them. Wouldn't it make more sense to spend the effort working in something that will give better results?

答:
Who says that? ...anyway, it's just an opinion. Some might agree, some may not, there is no right or wrong here. Some languages have compilers written in itself, others don't. Whatever.

Nevertheless, I think it's a nice exercice/proof-of-concept if a language is able to "self-compile" ...it's just ...nice ...and it prooves the language is suited to do some complex stuff.

I'd also like to mention that despite being nice, there are still a variety of reasons a compiler might be written in another language.
For instance, most javascript engines are not written in javascript. There are many reasons for this: integration with other software, linking to existing libraries/dependencies, superior tools, performance, legacy code... Sometimes, the language self-compiling is nice, but it still makes sense to maintain the core compiler in another. Yet, the language by itself makes sense. It's just you usually can't afford to redevelop an entire ecosystem.


答:
Wouldn't it make more sense to spend the effort working in something that will give better results?

Like what?

The nice thing about compilers is that they don't have many dependencies. This makes them good candidates for a new language that likely doesn't have a very large or diverse standard library yet.

Better yet, they require a variety of things, while also being well studied. The variety helps make sure that your example tests various parts of the language. Being well studied means that you have other compilers to compare against - as well as giving more credence to academic sorts that you know what you're doing.

And while compilers seem like a ton of work, they're pretty small in the grand scheme of things. If the language implementers can't even do something they've done before in the new language, how are they going to do novel things? How are they going to handle the really big stuff like standard libraries or an IDE?

Title: Why are self-hosting compilers considered a rite of passage for new languages?

Body:
I've heard in a number of places now that people expect languages to use, or at least have, a self-hosting compiler in order to deserve respect.

I'm curious as to why this is. A compiler seems like a very significant piece of software to write, and I imagine not all languages are well-suited to creating them. Wouldn't it make more sense to spend the effort working in something that will give better results?


答:
It shows that the language is capable of processing complex string processing and translating to another language/interpreting itself.

In the process of creating a compiler (the first big project) there will be issue that come to the fore.


答:
The goal of having a compiler in the language that is being compiled is often part of the practice of "eating your own dog food." It demonstrates to the world that you consider the language, compiler, and ecosystem of supporting modules and tools to be "good enough for serious work" or "production ready."

It also has the virtuous effect of forcing those closest to language, compiler, and runtime design to directly face the effects of all the decisions they have made, and development priorities they've chosen--warts and all. This often leads to a core group that not only understands the language environment in theory, but that have extensive practical experience using the language/tools in the crucible of hard, real-word conditions.


答:
People create new general purpose languages for one main reason:  they hate at least one thing about every other language out there.  This is why so many languages don't get off the ground.  You have a great idea for a language that would improve your programming life, but you have to make the first implementation in a language that annoys you in at least one way.  Self-hosting means you no longer have to work in that old annoying language.  That's why a language's creators work toward that step, and see it as a major milestone.

A lot of language features look good on paper, but when you get around to using them in a real project you start to see their limitations.  For one example, a lot of languages don't have decent unicode support at first.  Completing a large project helps ensure a lot of those sorts of situations have been encountered and dealt with, and a self-hosting compiler is as good a project as any.  That's why people other than the language's creators see it as a major milestone.

That doesn't mean it's the only milestone worth noting.  There is functionality that isn't exercised by a compiler, such as database integration, graphical interfaces, networking, etc.


答:
Every single language out there has a decent niche of use.  I frequently find myself implementing things in higher-level languages, and then gradually bringing them down to C-land if I need them to be higher-performance or even simply just more portable.  There are C compilers for nearly everything in existence, and if you write to an API that is universally available (such as POSIX), then it can be very useful.

What I often tell people who are interested in learning programming today is to make sure that at some point, they learn C and become comfortable with it.  You might find yourself in circumstances where you need it.  On more than one occasion, I've had to compile a tiny, statically-linked "fast reboot" program, and use scp to put it on a RAM disk on a server where the disk subsystem went away entirely.  (Cheap, cheap servers, no online redundancy, and only the ability to load a small program? C is the way to go.)

Also, learning how to work in C without shooting yourself in the foot can contribute significantly to one's ability to write efficiently in other languages and environment.  At least, that has been my experience.

While I certainly don't use it for everything, or even most things, it has its place and it's pretty much universal: so yes, I've used it in the past and will use it in the future (though I don't know when at the moment).

Title: Would you use C, today, for a software project?

Body:
If yes, where and why would you use it?

If no, please provide an explanation to why C is not acceptable to you.


问:
Should an object load itself?
although I'm programming in C++ for some time now, I'm always faced with design decisions (probably due to the language's flexibility). One such problem is deciding if a method should be part of the class or not.

As an example, oftentimes, I have a Simulation class similar to the following,

```
<code>
class Simulation{
public:
    Simulation(void);
    bool init(const char* init_file){
        //...
        particles_ = read_particles(init_file);
        //etc
    }
    //or even,
    bool init(int argc, char* argv[]);
    void run(void);
private:
    std::vector particles_;
    //Other private members
};
</code>
```

Here, I'm not sure if this init method, which parses a file and initializes the simulation should really be a class method. A different way to implement similar functionality, would be to have an external function or class which handles the parsing of either the command line arguments or the initialization file, and calls appropriate methods of the Simulation class.

```
<code>
bool init_simulation(Simulation& sim, const char* init_file){
    //...
    Particles particles = read_particles(init_file);
    sim.set_particles(particles);
    //etc
}
</code>
```

On the one hand it's easier to implement the functionality as a class method and it avoids having to introduce new classes/structs, specifically for passing parameters. On the other hand, externally handling the initialization, means that one can more easily extend it, although any changes on the Simulation class will propagate to the function.

What is the preferred design in situations similar to the one described above, and how should I approach similar design decisions?

答:
Your problem isn´t having a class with a constructor method, your problem is what you have put into it.  Parsing a text file should not be part of the object - its job is to create and manage Simulations.  The constructor/init method should take a simple list or map of particles as one of its parameters and use that data when initialising.  Reading data from a file and converting it into a simple list or map is the job of some other part of your code.

If you change the file format, or completely change how your data is stored (e.g. in a relational database), you should not have to rewrite the Simulation class.

You should not need an input file to write tests for this class.  Your tests should be able to create simple input data and pass that directly to the object.

Separation of concerns.  The file (its location, format etc.) is no concern of your Simulation object.

Title: Should an object load itself?


问:
How to break up a programming project into tasks for other developers?
I have recently joined a development project and was suddenly given the job of lead developer. My primary responsibility is to break up the programming part of the project into tasks, give these tasks to the other developers, and then make sure that the pieces work together.

The problem though is I haven't a clue how to do this. I've spent my weekend with a pencil and paper trying to figure it out but I keep coming up with a list of tasks to be worked on sequentially instead of in parallel. I've thought of maybe splitting it up into features but then you end up with tasks that require editing the same files, which could require an entire task to be completely rewritten because of how early in development we are. I could have some developers wait until the program is a bit more complete and easier to create tasks for, but then I would have people sitting on their hands for who knows how many weeks.

I had a conversation with my boss about my qualifications to do this and I wasn't given a choice in the matter.  I have no idea what I'm doing, so any tips and nudges in the right direction would be greatly appreciated.

答:
It looks like you've graduated from being a developer to being a software engineer.  Realize that managing work isn't a design exercise, but the two go hand in hand.  You need to manage work being done, and that depends on how your company does development.  If you have the time and resources, then look at adopting an agile methodology - there's mountains of written materials on the internet.  Find one that works for you, but be aware that, like everything else, it isn't free.  Adoption of any techniques involves training, learning, and failing before you succeed.  If you don't have the bandwidth to handle adopting a more comprehensive technique, then doing milestone planning may be the answer for you.  If you have a list of sequential tasks, it may be the case that you haven't found sequences that can be parallelized.  It may also be the case that you want to segment your development into more general tasks like testing, and implementation.  That, by itself doesn't solve the reporting problem, but you're managing quality.  Your progression may be a sequential list, but your roles are parallel.  Just a suggestion.  A design that maps into work done by people is called a work breakdown structure.

There are a lot of good suggestions that other people offered up, but remember you're managing work.  Sometimes you can map work concepts into the design/architecture, sometimes you can't do that so easily.  There's always a way to structure work so that it trackable.  I suggest going back to your manager and ask him what is important to him when it comes to communicating the state of the project.  That will begin to tell you how to approach what you're doing.  If it is schedule, then you want to focus on reporting progress.  If it is quality, then you want to report on a suite of metrics that you'll have to come up with.  If its costs, then you will probably want to look at effort.  All of those things also can map into or out of the tasks.


答:
Get Agile

I would suggest the following:

Editing the same files

First, use Git (or a similar concurrent versioning system). As long as you are editing different parts of the same files, you wont get conflicts. If you do get conflicts, they will be clearly marked as such.

Trying to manage a multi-developer project without Git is like trying to make a pudding without a pudding bowl. It is possible, but it's going to get pretty messy pretty fast.

As has been pointed out in the comments, Git is not a panacea, but combined with automated testing it certainly helps a great deal.

List all the features

Second, break the project up into user visible features. For example "when the user signs up, they should receive an email" or "The user can add an item". Involve all stakeholders here. Get everyone in a room, and have everyone shout out their features.

These should be user visible features, you can talk about implementation strategy later.

Write all the suggestions on index cards, even the dumb ones. Quickly rationalise the list to remove duplicates, and lay out all the cards on a big table, or even the floor.

Add in any additional cards that are needed. Say your application will send SMS text alerts. You might not know how to do that, so you have a question. Write "Investigate SMS portals" on a card. Likewise for any other big unknowns. You'll have to unpack these later. These features will probably not make it into your first sprint.

Now sort your cards into groups, shuffle them about, get a feel for them. This is your project scope.

Planning poker

Have a go at planning poker. Still with everyone together, give all the developers cards that say "1 point", "2 points", etc, up to "4 points". Also a "more" card. A point is roughly equivalent to an hour.

Go through the feature list one by one. As you read out a feature, everyone has to play a card. If one person plays 1, and another person plays 4 there's a communication problem there. One person understands the feature to mean something different from the other person. Have a discussion and work out what was actually meant and note it on the card.

If you agree that a feature is a "more", that feature is too large. You have to break that feature down. Do this in the same way as before.

As you have agreement, write the numbers on the cards in a different colour pen.

Points are better than hours

Using points instead of hours takes away the macho "look how fast I can code" thing that we developers often engage in. It's a subtle difference, but I have found it works rather well.

Now compose a sprint

A sprint is a quick burst towards a goal. Decide on the sprint length, perhaps 5 or 10 days. Multiply the number of days by the number of developers by the number of points per day.

Assume 6 points per day per developer initially. This is an achievable number. If you have 5 people, that's 5 * 5 * 6 = 150 points. In conjunction with all the developers and the management, pick features from the list, up to 150 points. That's your sprint.

Never be tempted to squeeze more in than will fit. Over-promising hurts everyone in the long run, including you.

You'll need to take account of dependencies here. For example, environment setup obviously has to be included in the first sprint. This is actually relatively easy to do when everyone is present. You have 6 brains in the room, all saying "this depends on this", etc. You can then shuffle the cards around to demonstrate dependencies.

Once you have your sprint, nothing can be added to it, it's locked for the 5 days. Feature creep will stress the team, damage morale and slow everyone down. Eventually, creep will stall a project. As team leader you have to protect your team from feature creep. If a new feature request comes in, it must be added to the next sprint. IF the next sprint is already full, something else must be taken out.

Never be tempted to squeeze in extras. Over-promising gives you around 1 day's worth of happy client, followed by 4 days of team stress, and eventually, most likely, several unhappy clients when the team can't deliver on time.

Now go to it.

Hand out cards, ask who wants to do what. You have full visibility on what is getting done, and you can count the points ticking down to zero. Have a standup at the start of each day so everyone knows who is working on what, and what has been done.

5 or 6 decent motivated developers working together as a unit on clearly defined manageable goals can achieve a pretty chunky amount of stuff in a 5 day sprint.

Maintain visibility

Make sure everyone can see what the status of the project is. Bluetack all the cards to the wall. On the left are cards that are not yet worked on. On the right are done cards.

When a developer is working on a card, they take it off the wall and put it on their desk. This maintains visibility, and keeps people from stepping on each others toes too much.

There are technological alternatives to index cards, but nothing beats having a massive paper display of the project status on the wall.

If possible, have everyone in the same room for the duration of the project. Have the stakeholders around as much as possible, ideally every day.

Burndown

You can graph your points progressing towards zero on a burndown chart. If your line of best fit crosses zero before you hit your time limit, you are likely on track. If not you may need to let your client know now, before you get too close to the deadline.

If you're going to fail, fail early.

You can make a burndown using software, but I prefer just a big piece of paper on the wall. Draw and write all over it.

Automated testing

When you have multiple developers working on the same stuff at the same time, they're probably going to break each other's code from time to time. Communication and visibility helps with this, but you're probably going to want to introduce some technology to help with finding issues.

Unit testing is the process of writing tests for each individual part of your codebase (ideally each method). Your unit tests should be run often, with every save if possible. There are many tools that can help with this, for example Karma or Rspec.

End to end testing involves testing your project as a whole, treating the internals as a black box. Base these tests on your high level business requirements, for example: "The user can sign up" or "The user can see a list of items". Protractor is a nice example of an end to end web based testing framework.

There are whole books written on testing, but having at least some acceptance tests in place can help to make sure nothing gets broken as you work on your project.

Avoiding technical debt and getting to done-done

Technical debt is a concept that describes things that will have to be cleaned up later. A common source of debt is features that were marked as done, but which were never "done-done". A done-done feature is checked in to Git, has been approved by the stakeholder, and has a test.

Don't check your features off until they are done-done. Never massage the graph. Again, this hurts everyone in the long run, including you.

This is one reason why we initially only quote 6 points per developer, per day. Done-done takes extra work, but feels great and gives the team a boost.

Title: How to break up a programming project into tasks for other developers?

Body:
I have recently joined a development project and was suddenly given the job of lead developer. My primary responsibility is to break up the programming part of the project into tasks, give these tasks to the other developers, and then make sure that the pieces work together.

The problem though is I haven't a clue how to do this. I've spent my weekend with a pencil and paper trying to figure it out but I keep coming up with a list of tasks to be worked on sequentially instead of in parallel. I've thought of maybe splitting it up into features but then you end up with tasks that require editing the same files, which could require an entire task to be completely rewritten because of how early in development we are. I could have some developers wait until the program is a bit more complete and easier to create tasks for, but then I would have people sitting on their hands for who knows how many weeks.

I had a conversation with my boss about my qualifications to do this and I wasn't given a choice in the matter.  I have no idea what I'm doing, so any tips and nudges in the right direction would be greatly appreciated.


答:
The other answers have talked about the programming aspects, but I just wanted to mention the program management aspect.  I'll start with a disclaimer: I am not a program manager.  I have taken one course at the graduate level for program management and my work experience involves bidding hours for small projects that are usually under 500 hours and never over 1000 hours.

But I have had to help define tasking for a lab where I had to keep 2-3 people busy for 2-4 months(part time and full time).  One thing that really helped me was using project management software like Microsoft Project(I'm not sure if there's a freeware version out there, but your employer probably has something like it...ask your supervisor what kind of program management software is used at your company).  In particular, I use the Gantt charts quite a bit, which is the default view in Microsoft Project.  By defining all the tasks and how long you think they will take, you can get a visualization to play with.

The Gantt chart helps me most because of its visualization.  Seeing tasks on paper doesn't help me a whole lot, but seeing pretty pictures and a chart certainly does.  Microsoft Project also allows you to set predecessors and start dates, with the main idea being "Find the minimal amount of tasks required to be completed for task X to start".  At least in my small projects, the amount of 'real' predecessors is quite small.  In fact, on one project I had the problem that almost everything could be done concurrently, and had to synthesize two concurrent paths that were somewhat cohesive.  E.g. I tried to make sure that if developer A ever touched the GUI, they worked on tasks that were close to the GUI as well.

It sounds like you were doing a lot of this already as far as pen and paper goes, but I always find it really helpful to actually see the Gantt charts.  Looking at the tasks lined up sequentially really gets me to think "Wait, does task X really have to be done before task Y?(in my experience so far, I've been surprised how often the answer is actually 'no')"


问:
I'm confused about which is the correct way to work with TDD
I'm trying to grasp what's the idea behind TDD and how a team is supposed to work with it. I have the following test case with NUnit + Moq (just writing by memory, it is not assured the example compiles but it should be explanatory):

```<code>[Test]
public void WhenUserLogsCorrectlyIsRedirectedToLoginCorrectView() {
    Mock<IUserDatabaseRepository> repoMock = new Mock<IUserDatabaseRepository>();
    repoMock.Setup(m => m.GetUser(It.IsAny())).Returns(new User { Name = "Peter" });

    Mock<ILoginHelper> loginHelperMock = new Mock<ILoginHelper>();
    loginHelperMock.Setup(m => m.Login(It.IsAny(), It.IsAny())).Returns(true);
    Mock<IViewModelFactory> factoryMock = new Mock<IViewModelFactory>();
    factoryMock.Setup(m => m.CreateViewModel()).Returns(new LoginViewModel());

    AccountController controller = new AccountController(repoMock.Object, loginHelperMock.Object, factoryMock.Object)

    var result = controller.Index(username : "Peter", password: "whatever");

    Assert.AreEqual(result.Model.Username, "Peter");
}
</code>```

AccountController has 3 dependencies which I mock that, when orchestrated inside the controller, allows me to verify if a login was correct or not.

What stumbles my mind is that... if in TDD in theory you have to write first your test suite and build your code up from it, how am I supposed to know beforehand that in order to perform my operation I'll need to use those three dependencies and that the operation will call certain operations? It's like I need to know the innards of the Subject Under Test before even implementing it in order to Mock the dependencies and isolate the class, creating some kind of write test - write code - modify test if necessary cycle.

Naturally, without any knowledge of the innards of my code and just expressing the test, I could express it like it could just need the ILoginHelper and "magically" suppose before writing the code that it will return the user on a successful login (and ultimately realize that the underlying framework doesn't work that way, for instance returning just an ID instead of the full object).

Am I understanding TDD in an incorrect way? Which is a typical TDD practice on a complex case?

Thank you

答:
You may eventually need all this complexity for a conceptually simple unit test, but you will almost certainly not write the test like this in the first place.

First of all, the complex set-up in your first six lines should be factored out into self-contained, reusable fixture code. The principles of maintainable programming apply to test code just like business code; if you use the same fixture for two or more tests, it should definitely be refactored into a separate method so that you have only one distracting line in your test, or into the class set-up code so that you have none.

But the more important thing: writing a tests first doesn't guarantee that it can stay unchanged forever. If you don't know the collaborators of a method call, you will almost certainly not be able to guess them correct on the first try. There is nothing wrong with refactoring your test code along with your business code if the public API changes. It's true that the aim of TDD is to write the correct, usable API in the first place, but this is hardly ever achieved to 100%. Requirements always change after the fact, and all too often this absolutely requires collaborators that didn't exist when you wrote the first iteration of a story. In that case there's nothing to be done but bite the bullet and change existing tests along with your application; and those are the occasions when the majority of the set-up code you quote would get into your test suite.


问:
What would you consider best practice workflow tools for web application (PHP) development?
I'm really hoping somebody with more experience can edit the question as per my examples of answers:

using version control

test driven development

debugging code (xdebug for php)

use of UML diagrams

use of OOP for maintainable, reusable code

use of frameworks (like Zend Framework for php) for rapid application development

Anything else or an elaboration of what I mentioned above?

Basically, I'm in the middle of forming a team of developers (I'm a developer myself) and I'd like some advice on how professional programmers/designers etc should work together and what standards/paradigms they should use.

Also, if anybody has any books or links on the subject I'd welcome that!

I did find this which I guess satisfies what I'm looking for, or at least part thereof:

http://www.ibm.com/developerworks/websphere/library/techarticles/0306_perks/perks2.html

答:
Use of UML diagram is nice but is entirely optional. Any diagrams would do as long as your team understand what they mean. Trying to use standard no-one really knows well may lead to issues and lost time.

I would recommend to start each page from a mockup (http://balsamiq.com) or have your designer to draw it for you. Don't expect developers to be good at visual aesthetics and create good pages out of nowhere.

Have someone assigned to code-review duty, if you have several seniour team members - make them do reviews in rotation (Review Board)


问:
Finding shortest path between nodes with a twist
Note: if you feel that I should include code, please tell me.

I am solving a problem of finding shortest path between nodes. I am given the vertices between nodes, however they are one sided (ie you can go from A to B, but not from B to A). The twist of the challenge, is that the paths (vertices) taken must be even number. I am able to find the path, however I am confused what to do when it is not even number. I assume next I should find some sort of loop to get the desired even amount of vertices covered (as you can go through same node more than once), however I don't know how to do it.

答:
(I assume you mixed up the term "vertices" with "edges", a graph typically consists of vertices = nodes, with edges between them).

I would try something along the lines of the following idea:

from your initial graph, construct a new one containing the same nodes, but different edges

you draw an edge in your new graph between two nodes A and B, when there is a two-step path from A to B in your original graph. This should be easy to construct by running a simple depth-first search on each node with a limited depth of 2. If your original graph had weighted edges, assign the new edges the sum of the weights of the two corresponding edges from the original graph

now you can apply a standard shortest-path algorithm to this new graph

from the solution found it should be trivial to construct the corresponding path im the original graph

This works because every path with an even number of edges in your original graph can be split up into sub-paths of length 2.


答:
Just transform your graph to something that can be searched easily!

How?

Given a a graph X {A, E} (A being the set of vertices, E being the set of (directed) edges), construct a graph X' {A, E*}, such that an edge is in E* (from point B to point D) iff there is a pair of edges in E such that the first is from B to C, and the second - from C to D.

You may also want to keep a reverse mapping for edges (I.e. how was the edge constructed?)

How difficult is this?

Potentially up to N^3 where N is the number of vertexes, depending on your graph structure. Given that path search algorithms are usually in the order of N^2 to N^3, that should be fine. Also N^3 is the naive way - you may be able to find a better way.

What do I do with it?

Given this new graph - Any even-length path in X is a path in X' if you throw out every odd vertex. Also - any path through X' is an even-length path through X if you fill in the gaps via the reverse mapping from the first section. I.E. You have a surjection from even-length paths in X to paths in X'.

This surjection also preserves path length comparison - a path K' is longer that a path L' in X' iff their corresponding paths in X - K and L - have the same relationship, i.e. K is longer than L.

Eh... OK, so what?

Well all this theory lets you claim one neat thing - the shortest path through X' is going to have a corresponding shortest even-length path through X. This graph is going to have the same number of vertexes, and maybe a larger or smaller number of edges. Hence any of the numerous path-finding algorithms will work - your question implies you can use those already.

Can I do all this without the extra graph?

Why yes! Of course you can! Just use your imagination! As in - don't explicitly construct the extra graph. Just imply it. This will require changes to the actual path searching algorithm - when asked about nodes adjacent to some given node, instead of listing everything connected directly - list everything connected through exactly 2 edges.

Depending on your situation this may or may not be a better solution. The "theoretical" one allows usage of search algorithms out-of-the-box, but suffers from a lot of setup. The second one mitigates setup at the cost of modifying the algorithms (and IMHO has more room for mistakes)

Title: Finding shortest path between nodes with a twist

Body:
Note: if you feel that I should include code, please tell me.

I am solving a problem of finding shortest path between nodes. I am given the vertices between nodes, however they are one sided (ie you can go from A to B, but not from B to A). The twist of the challenge, is that the paths (vertices) taken must be even number. I am able to find the path, however I am confused what to do when it is not even number. I assume next I should find some sort of loop to get the desired even amount of vertices covered (as you can go through same node more than once), however I don't know how to do it.


答:
I'm on the fence whether your code should be called a fluent interface or a train wreck. Either way, method chaining should not be overused because it decreases readability. I have first hand experience from a project where I found myself writing wrapper functions to shorter some chains. Furthermore, some folks such as Robert C. Martin in "Clean Code" Chapter 3 suggest that one should strive to separate commands from queries, which your code clearly does not do. I don't say this is an absolute truth, but you should be more careful with method chaining. After all, functional style does not say that one must chain everything but rather that one should strive to build code from functions that do not use implicit state. So, of course you should follow Doc Brown's suggestion and refactor with into a separate function, but you should also check if you're overusing method chaining.

For example, it may be better to assign the result of computation before invariant check to a variable, then verify the variable satisfies the check, and then continue with computation. You may even decide to wrap several commonly used sub-chains into separate functions with a descriptive name.

If it was Haskell, you could have returned Maybe.Some(yourobj) from each method and rely on compiler to halt computation as soon as Maybe.None is returned. This way, a verification method would return yourobj unchanged if it is OK, and return None otherwise. In Java there is a very similar thing called Optional, and this article explains how it can be used to solve your issue in a different way.

Title: Method for all objects for checking conditions which also includes method chaining and avoiding variables

Body:
(I am currently using groovy but it should apply to most OO languages so I also put the langauge-agnostic tag)

I try to program in a function style which also includes method chaining and avoiding variables. Therefore I often find myself writing code with the with method in groovy that every object has. It works likes this:

```<code>someobject
.doSomething()
.doEvenMore() //this results in an object that I need check for some condition, e.g. a String
.with { String result ->
    if (result != "I AM A CORRECT RESULT")
        throw new Exception("assertion failed")
    else
        return result  //need to do this because else the closure will return null
}
.doAnotherThingOnTheResult()
//and so on
</code>```

(See also https://codereview.stackexchange.com/questions/57676/better-way-to-assert-correct-return-values-in-groovy for a real life example I asked some time ago)

This is rather unconcise so I was searching for a better way to check for conditions without using to have with. I came up with an idea I would like to hear your opinions to.
That is, an method that all objects have and that can be used like this:

```<code>someobject
.doSomething()
.doEvenMore() //this results in an object that I need check for some condition, e.g. a String
.assertTrue (new Exception("custom exception")) { it == "I AM A CORRECT RESULT" }
.doAnotherThingOnTheResult()
//and so on
</code>```

or for default behaviour with a default exception type

```<code>someobject
.doSomething()
.doEvenMore() //this results in an object that I need check for some condition, e.g. a String
.assertTrue { it == "I AM A CORRECT RESULT" } //results in AssertionException or sth similiar
.doAnotherThingOnTheResult()
//and so on
</code>```

In groovy I can make it that every (new) created object is decorated with such a method. What do you guys think about it? Are there better ways or should I stay with the with method?


答:
While TDD is a test-first method, it does not require you to spend a lot of time writing test code before you write any production code.

For this example, the idea of TDD described in Kent Beck's seminal book on TDD (1) is to start with something really simple, like maybe

```<code>AccountController controller = new AccountController()

var result = controller.Index(username : "Peter", password: "whatever");

Assert.AreEqual(result.Model.Username, "Peter");
</code>```

At first, you don't know everything you're going to need you to do the job.  You just know you're going to need a controller with an Index method that gives you a model with a Username.  You don't know how it's going to do that yet.  You've just set a goal for yourself.

Then you get that to work using any means available, possibly just hardcoding the correct result at first.  Then in subsequent refactorings (and even adding additional tests) you add greater sophistication one step at a time.  TDD let's you to take as small of a step as you need to move forward but also leaves you free to take as large of a step as your skills and knowledge allow.  By taking a short cycle between test code and production code, you get feedback on every little step you take and know with near immediacy whether what you just did worked and whether it broke any else that was working before.

Robert Martin in (2) also advocates for a very short cycle time between writing test code and writing production code.

Title: I'm confused about which is the correct way to work with TDD

Body:
I'm trying to grasp what's the idea behind TDD and how a team is supposed to work with it. I have the following test case with NUnit + Moq (just writing by memory, it is not assured the example compiles but it should be explanatory):

```<code>[Test]
public void WhenUserLogsCorrectlyIsRedirectedToLoginCorrectView() {
    Mock<IUserDatabaseRepository> repoMock = new Mock<IUserDatabaseRepository>();
    repoMock.Setup(m => m.GetUser(It.IsAny())).Returns(new User { Name = "Peter" });

    Mock<ILoginHelper> loginHelperMock = new Mock<ILoginHelper>();
    loginHelperMock.Setup(m => m.Login(It.IsAny(), It.IsAny())).Returns(true);
    Mock<IViewModelFactory> factoryMock = new Mock<IViewModelFactory>();
    factoryMock.Setup(m => m.CreateViewModel()).Returns(new LoginViewModel());

    AccountController controller = new AccountController(repoMock.Object, loginHelperMock.Object, factoryMock.Object)

    var result = controller.Index(username : "Peter", password: "whatever");

    Assert.AreEqual(result.Model.Username, "Peter");
}
</code>```

AccountController has 3 dependencies which I mock that, when orchestrated inside the controller, allows me to verify if a login was correct or not.

What stumbles my mind is that... if in TDD in theory you have to write first your test suite and build your code up from it, how am I supposed to know beforehand that in order to perform my operation I'll need to use those three dependencies and that the operation will call certain operations? It's like I need to know the innards of the Subject Under Test before even implementing it in order to Mock the dependencies and isolate the class, creating some kind of write test - write code - modify test if necessary cycle.

Naturally, without any knowledge of the innards of my code and just expressing the test, I could express it like it could just need the ILoginHelper and "magically" suppose before writing the code that it will return the user on a successful login (and ultimately realize that the underlying framework doesn't work that way, for instance returning just an ID instead of the full object).

Am I understanding TDD in an incorrect way? Which is a typical TDD practice on a complex case?

Thank you

Body:
While TDD is a test-first method, it does not require you to spend a lot of time writing test code before you write any production code.

For this example, the idea of TDD described in Kent Beck's seminal book on TDD (1) is to start with something really simple, like maybe

AccountController controller = new AccountController()

var result = controller.Index(username : "Peter", password: "whatever");

Assert.AreEqual(result.Model.Username, "Peter");

At first, you don't know everything you're going to need you to do the job.  You just know you're going to need a controller with an Index method that gives you a model with a Username.  You don't know how it's going to do that yet.  You've just set a goal for yourself.

Then you get that to work using any means available, possibly just hardcoding the correct result at first.  Then in subsequent refactorings (and even adding additional tests) you add greater sophistication one step at a time.  TDD let's you to take as small of a step as you need to move forward but also leaves you free to take as large of a step as your skills and knowledge allow.  By taking a short cycle between test code and production code, you get feedback on every little step you take and know with near immediacy whether what you just did worked and whether it broke any else that was working before.

Robert Martin in (2) also advocates for a very short cycle time between writing test code and writing production code.


问:
What is this pattern called? Run finally?
Is there a name for this pattern? I've written this kind of thing a few times in JavaScript and recently found myself writing it in C#. Thing is, I expect this has already been implemented in a library somewhere I didn't know what to look for.

In pseudo code it's something like this:

```<code>if (null != referenceToPreviousRequest) {
    referenceToPreviousRequest.cancel();
}

referenceToPreviousRequest = setTimeout(function() {
    //The thing I ultimately want to do
}, 1000 /*The delay after the last request*/);
</code>```

Typically I use this kind of code in client side JavaScript, for delaying an AJAX request until a certain amount of time after the last user input, e.g. searching.

答:
What you describe are known as JavaScript Promises, in general programming parlance they are called Continuations. C# supports them through the Task Parallel Library and Async/Await keywords.

Here's how it works, I want to call an operation asynchronously. If the operation is already declared Async it's simple:

Add async to your function that is calling the existing async function

Change the return value to Task (for void) or Task (for any other type T)

Place the keyword await in front of the call to that async function. And follow that call with the rest of my function's logic.

Here's an example (taken from MSDN Docs on Async Await).

```<code>// Three things to note in the signature:
//  - The method has an async modifier.
//  - The return type is Task or Task<T>. (See "Return Types" section.)
//    Here, it is Task<int> because the return statement returns an integer.
//  - The method name ends in "Async."

async Task<int> AccessTheWebAsync()
{
    // You need to add a reference to System.Net.Http to declare client.
    HttpClient client = new HttpClient();

    // GetStringAsync returns a Task<string>. That means that when you await the
    // task you'll get a string (urlContents).
    // The await operator suspends AccessTheWebAsync.
    //  - AccessTheWebAsync can't continue until getStringTask is complete.
    //  - Meanwhile, control returns to the caller of AccessTheWebAsync.
    //  - Control resumes here when getStringTask is complete.
    //  - The await operator then retrieves the string result from getStringTask.

    string urlContents = await client.GetStringAsync("http://www.microsoft.com");

    // The return statement specifies an integer result.
    // Any methods that are awaiting AccessTheWebAsync retrieve the length value.
    return urlContents.Length;
}
</code>```

Reading the linked article will describe what's happening in the background.

You can also explicitly perform continuations in C# using the ContinueWith operation

Body:
What you describe are known as JavaScript Promises, in general programming parlance they are called Continuations. C# supports them through the Task Parallel Library and Async/Await keywords.

Here's how it works, I want to call an operation asynchronously. If the operation is already declared Async it's simple:

Add async to your function that is calling the existing async function

Change the return value to Task (for void) or Task (for any other type T)

Place the keyword await in front of the call to that async function. And follow that call with the rest of my function's logic.

Here's an example (taken from MSDN Docs on Async Await).

// Three things to note in the signature:
//  - The method has an async modifier.
//  - The return type is Task or Task<T>. (See "Return Types" section.)
//    Here, it is Task<int> because the return statement returns an integer.
//  - The method name ends in "Async."

async Task<int> AccessTheWebAsync()
{
    // You need to add a reference to System.Net.Http to declare client.
    HttpClient client = new HttpClient();

    // GetStringAsync returns a Task<string>. That means that when you await the
    // task you'll get a string (urlContents).
    // The await operator suspends AccessTheWebAsync.
    //  - AccessTheWebAsync can't continue until getStringTask is complete.
    //  - Meanwhile, control returns to the caller of AccessTheWebAsync.
    //  - Control resumes here when getStringTask is complete.
    //  - The await operator then retrieves the string result from getStringTask.

    string urlContents = await client.GetStringAsync("http://www.microsoft.com");

    // The return statement specifies an integer result.
    // Any methods that are awaiting AccessTheWebAsync retrieve the length value.
    return urlContents.Length;
}

Reading the linked article will describe what's happening in the background.

You can also explicitly perform continuations in C# using the ContinueWith operation


问:
Conveniently sorting and (binary?) searching an array of pairs of numbers?
So I have an array of distinct pairs of positive integers. That is, my array looks something like this (for instance):

{ (1,5) , (6,4), (5,3), (2,3), (2,4) }

And my task is, for a given pair (a,b) find (if it exists) the pair (c,d) which has c > a and d > b and, in addition, is the "minimal" such pair (that is, c is minimal and, if there are multiple pairs which satisfy this with the same c, then d is minimal).

So for instance, if I run the query for the above array for pair (1,1), it should return (2,3) and if I feed it (5,2) it should return (6,4).

Now the problem is that I have to run multiple queries so linear time is not good enough. And my question is: is there any way in / any law by which I can "sort" such an array so that I can later run binary searches on it to find my answer?

I was thinking I could simply go like this: let (x1,y1) and (x2,y2) be two pairs to compare. Then:

```<code>if(x1<x2)
    //pair 1 is smaller
else if(x1==x2 && y1<y2)
    //pair 1 is smaller
else
    //pair 2 is smaller
</code>```

This seemed to solve most cases, however.. if I have an array which looks like this:

{  ....   (50,60)  ..... }

where (50, 60) is at the middle of the array. And I run a query for (40,70) for instance. The problem is that the pair that I want to find could be either on the left or on the right of (50,60) (we could have something like (45,90) on the right of (50, 60), but then again we could only have (x,10) on the left of (50,60) where x<50 so no pair on the left would satisfy our condition and I'd have to look to the right).

So to sum it up, if I'm running a query for pair (x1,y1) and through my binary search I come across and element (x2,y2) which has x1<x2 and y1>=y2, then my algorithm cannot decide whether it should keep searching left or right. So I have to search both sides and in a worst case scenario this ends up being O(n).

So is there a more clever way in which you can do this? Any help would be appreciated. Thanks in advance :)

答:
Without using any extra storage, I think the best you can do is a binary search on the first element, then linear search forward from there to match the second element.  This has O(n) worst case performance, but should be close to O(log n) in the average case, especially since you only need to search this way after hitting an ambiguous direction.

If you have sufficient storage and the time to do the precalculation, you could make a two-dimensional pre-sorted data structure, like the following for your example { (1,5) , (6,4), (5,3), (2,3), (2,4) }:

```<code>[(1, [(2,3), (5,3), (2,4), (6,4), (1,5)]),
 (2, [(2,3), (5,3), (2,4), (6,4)]),
 (5, [(5,3), (6,4)]),
 (6, [(6,4)])]
</code>```

Then just do a binary search for the 1, 2, 5, or 6 as the first element, which gives you a list sorted by the second element, where you can do another binary search.  This is O(n2) for space, but gives you O(log n) in runtime.

Body:
Without using any extra storage, I think the best you can do is a binary search on the first element, then linear search forward from there to match the second element.  This has O(n) worst case performance, but should be close to O(log n) in the average case, especially since you only need to search this way after hitting an ambiguous direction.

If you have sufficient storage and the time to do the precalculation, you could make a two-dimensional pre-sorted data structure, like the following for your example { (1,5) , (6,4), (5,3), (2,3), (2,4) }:

[(1, [(2,3), (5,3), (2,4), (6,4), (1,5)]),
 (2, [(2,3), (5,3), (2,4), (6,4)]),
 (5, [(5,3), (6,4)]),
 (6, [(6,4)])]

Then just do a binary search for the 1, 2, 5, or 6 as the first element, which gives you a list sorted by the second element, where you can do another binary search.  This is O(n2) for space, but gives you O(log n) in runtime.


问:
Bad Practice using Auto Generated Classes for Data Access
I've seen this before but haven't found concrete reasons.

When you add Entities to your EF model, EF auto generates classes for these entities.

In terms of DataAccess, why is it preferred to not use these Auto Generated Classes, and instead use your own Data Models for Data Access.

Ex.

```<code> EFAutoGeneratedClass = //query = BAD

 SeparateModelClass = //query = Good
</code>```

答: If you database changes, your auto-generated entities will change upon a refresh of it's schema. You don't want these changes to break your code, but if you depend on them, it might break your code (in many places as oppose to one place if you transfer the entity content over to your own model) </p>


答:
I know nothing about smalltalk, so I'll only talk C++.
In C++ (and AFAIK in Java and C#), each thread has its own stack. If you don't know what a thread is, I suggest you read about it. I'll describe it here as the bus your code is taking a ride on. But I suggest you learn more than this horrible analogy (Also, not all C runtimes are multithreaded, so there may be only one thread. But you probably won't deal with those).

If you declare something inside a function like so:

```<code>void foo() {
  MyObject a;
}
</code>```

Then your new MyObject instance lives on the stack. If you have 2 objects:

```<code>void foo() {
  MyObject a;
  MyOtherObject b;
}
</code>```

Both of them live on the stack (the same stack). If you use new/malloc/HeapAlloc/whatever other heap allocation routine your platform has:

```<code>void foo() {
  MyObject* a = new MyObject();
}
</code>```

Then your new object instance is allocated in the heap, which is a different thing, which I won't describe since it's probably out of scope.

In short, the answer is no. Each object does not have its own stack.

Title: Objects in smalltalk and c++

Body:
I have a question based on SmallTalk and C++. In one of the programming languages books, there is a question like:

"Does an object in Smalltalk require its own private stack? What about in C++?"

Could you please explain those questions above if you know the answers?

Thanks.

Body:
I know nothing about smalltalk, so I'll only talk C++.
In C++ (and AFAIK in Java and C#), each thread has its own stack. If you don't know what a thread is, I suggest you read about it. I'll describe it here as the bus your code is taking a ride on. But I suggest you learn more than this horrible analogy (Also, not all C runtimes are multithreaded, so there may be only one thread. But you probably won't deal with those).

If you declare something inside a function like so:

void foo() {
  MyObject a;
}

Then your new MyObject instance lives on the stack. If you have 2 objects:

void foo() {
  MyObject a;
  MyOtherObject b;
}

Both of them live on the stack (the same stack). If you use new/malloc/HeapAlloc/whatever other heap allocation routine your platform has:

void foo() {
  MyObject* a = new MyObject();
}

Then your new object instance is allocated in the heap, which is a different thing, which I won't describe since it's probably out of scope.

In short, the answer is no. Each object does not have its own stack.


问:
How Best Can I Use Git When My Employer Uses VSS?
I am going to be working with VSS but I am much more productive and diligent with GIT.

I have to fit within the workflow of VSS and keep good history in VSS. The standard work flow here with VSS is

get working copy

do work

right click on folder -> show differences

in that view:

checkout (without overwriting local changes)

checkin (keeping write access)

Add comment with specific template

Personally I think this is already side-stepping the intended workflow of VSS and potentially overwrites any changes made by other people.

I think I can prevent the possible overwrite, but are there any other potential problems  that I should be aware of with this workflow?

--EDIT--

It's worth mentioning that in this case VSS is only used on legacy projects, and its largely treated with scorn by both the people that use it and the people that maintain it.

80% of the people that use it, use it alongside another version control system (some git, most mercurial)

When I asked the sys admin what my workflow should be, I was told "whatever your preference". I have kept them up to date with my thinking and they are interested in the results.

I would not recommend using any extreme methods (such as my script below) unless you have discussed it with whoever maintains VSS

答: I'm going to answer, "don't do this."  The workflows are quite different, and you'll not have considered one and end up causing yourself, or worse your team, a lot of grief.  Learn VSS, if nothing more than to make you appreciate other VCS more.</p>


问:
Advanced subversion techniques, what am I missing?
I started using SVN about 9 months ago and it's been a game changer to say the least.  Although, I feel I'm still a bit lost.  I feel like there is a lot more I need to take advantage of to really step up my application development.

For example

I would like to be able to quarantine any volatile/major changes into some kind of 'sub-repository' or something.  I'm finding that major changes are impeding minor bug fixes that are quite urgent.  How can I push one simple update without pushing incomplete or broken code?

答:
You can check out code into different sandboxes instead of just taking one copy and making all your changes there.

So you could have a folder structure that goes something like this:

```<code>D:\Dev\MajorFeature1
D:\Dev\Bug12345
D:\Dev\MajorFeature2
</code>```

etc.

All of those could be checked out from the same location in your SVN, e.g. http://mysvnrepo/trunk.

This way you can commit from your bug fix sandbox without affecting feature development ones, although you'll need to run svn update from other sandboxes to get the changes committed for the bug fix.

Body:
You can check out code into different sandboxes instead of just taking one copy and making all your changes there.

So you could have a folder structure that goes something like this:

D:\Dev\MajorFeature1
D:\Dev\Bug12345
D:\Dev\MajorFeature2

etc.

All of those could be checked out from the same location in your SVN, e.g. http://mysvnrepo/trunk.

This way you can commit from your bug fix sandbox without affecting feature development ones, although you'll need to run svn update from other sandboxes to get the changes committed for the bug fix.


问:
Why is the use of JavaScript in HREF attributes discouraged?
Disclaimer: I came to Programmers.SE to ask this question because I understand this is the place to ask this type of question, and not necessarily stackoverflow. If I am wrong, please close the question and direct me to a place where I may be able to discuss it.

I have noticed that people have been saying (in the year 2014) that we aren't supposed to use JavaScript in the href attribute of an HTML anchor tag. So then this function call:

```<code>Expand
</code>```

is discouraged, and over this it is preferred instead to attach an event handler to the onclick event of this anchor tag.

Why?

I'll take that this style of JavaScript function calls is very '90's, but what specific style guideline discusses this and weighs the pros and cons of doing it this was and recommends against it? I mean, there must be a pros and cons list, because I can think of some pros, like quick access to a function for a small HTML file, or easy readability on a small project. Yes, you have the cons, like not separating the view from the controller. I want to know who said this, why it is "generally understood", and where I can verify that.

Take something like this:

```<code><span>
    Please click here to refresh
</span>
</code>```

It is abundantly obvious what I am trying to do. Is it really necessary to separate the logic from the view in this case? If you agree with me that we can let this one slide, then where do we draw the line?

答:
It revolves around the principle of Unobtrusive JavaScript.  The modern approach dictates that there should be a separation of functionality from presentation.

I hate to cite Wikipedia, but give Wikipedia's article on Unobtrusive JavaScript a read.

On a personal note there are three things about Unobtrusive JavaScript I quite like:

Separation of concerns – My JavaScript is completely separate from my HTML code.  It's in separate files and it encourages me to write clean JavaScript code.  With inline tags I tend to dump piles of garbage into script tags.  Here I'm writing very tight, modular, reusable, and maintainable JavaScript.

Graceful degradation – When you use inline JavaScript like that, you're assuming that the client has JavaScript enabled.  What happens if the client doesn't have JavaScript enabled?  Does your site fail entirely? If you write unobtrusive JavaScript you're typically building a functional site with HTML then enhancing the experience with JavaScript.  Without JavaScript your site's user experience is degraded, but still functional.

Ask instead of assume – This ties in to what I was talking about with point number two.  What you're encouraged to do is build a core experience using HTML + CSS then enhance it with JavaScript.  In many of my sites (I'm a .NET MVC developer) I use jQuery UI to load partial pages for input forms.  With unobtrusive JavaScript my site works perfectly with full page loads, and then is enhanced with AJAX requests that allow me to create modal dialogs.  In my server code I actually dictate whether to return a View() (full layout) or PartialView() (plain HTML) based on whether or not the request is an AJAX request.

Let's look at your first example.  Based on context I can assume that you have a section of your page that is hidden, and the link calls a function to expand that section of the page.  You could be achieving that in one of two ways.  You could be hiding the section with the content and then displaying it when the link is clicked (toggling CSS) or you could be making a call to the server to load the data and display it on the page (AJAX request).  In its current form the content that the methods call displays is now inaccessible to your client.  You could refactor your page to display all content on the page at load time if JavaScript is unavailable and then hide it when the DOM is ready, or you could have the link direct to a full page with the content then change that behaviour to an AJAX request.

Body:
Disclaimer: I came to Programmers.SE to ask this question because I understand this is the place to ask this type of question, and not necessarily stackoverflow. If I am wrong, please close the question and direct me to a place where I may be able to discuss it.

I have noticed that people have been saying (in the year 2014) that we aren't supposed to use JavaScript in the href attribute of an HTML anchor tag. So then this function call:

```<code><a id="expand-rail" href="javascript:callMyFunc()">Expand</a>
</code>```

is discouraged, and over this it is preferred instead to attach an event handler to the onclick event of this anchor tag.

Why?

I'll take that this style of JavaScript function calls is very '90's, but what specific style guideline discusses this and weighs the pros and cons of doing it this was and recommends against it? I mean, there must be a pros and cons list, because I can think of some pros, like quick access to a function for a small HTML file, or easy readability on a small project. Yes, you have the cons, like not separating the view from the controller. I want to know who said this, why it is "generally understood", and where I can verify that.

Take something like this:

```<code><span>
    Please <a id="page-reload" href="javascript:window.location.reload()">click here</a> to refresh
</span>
</code>```

It is abundantly obvious what I am trying to do. Is it really necessary to separate the logic from the view in this case? If you agree with me that we can let this one slide, then where do we draw the line?