问:
Third-party repositories in Subversion; local mods?
I'm building a small app as an interface to support functions, monitoring, web-based running of unit tests, etc. This will be checked into Subversion.

I want to include a third-party app which is also available via Subversion. Thus far I prefer to reference the remote repository to ease upgrades, particularly when I have made local modifications.

Now, I want the third-party app to be distributed alongside the parent app. Subversion externals are out, since I can't commit my local mods. git svn seems like it has potential, but I'm not sure on the details. (Seems dirty to have a .git directory with svn metadata stored in an svn repository.)

So how do you handle modifications to Subversion projects you can't commit to? I'm pretty open to any combination of git and svn, preferably allowing the code to live in our existing Subversion repository.

Update: I'm currently exploring vendor branches, which is more convention than feature. There is a tool called svn_load_dirs.pl to assist with the process.

答:
Piston is ideal for this -

http://piston.rubyforge.org/

It stores the external code in the SVN respository, can easily show differences between your code and the vendor branch, and handles updating as well.


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
Add Exceptions instead of producing E_WARNING... It's very annoying that I can't use something such as:

```<code>try{
   $f = fopen('asd', 'r');
   flock($f, LOCK_SH);

   while(!feof($f)){
       echo fread($f, 512);
   }

   fclose($f);

}catch(IOException $ex){
   echo 'Oops, something wrong: '.$ex->getCode();
}
</code>```

Of course, currently is not much practical but it's very annoying to receive:

WARNING

WARNING

WARNING

and I can't control the flow of code without writing my own error_handler and string sniffing which error has been produced (permission, incorrect filename or anything else; I don't mind about other sources of errors here) in order to throw correct exception.

I hope I haven't to explain why it's important.

PHP became Object-Oriented an amount time ago and we, programmers who use PHP, are looking forward for OO features, not introducing "goto"... When I found out it really happend, I thought it was an April Fool's day.

ContentLicense: CC BY-SA 2.5

Body:
Add Exceptions instead of producing E_WARNING... It's very annoying that I can't use something such as:

try{
   $f = fopen('asd', 'r');
   flock($f, LOCK_SH);

   while(!feof($f)){
       echo fread($f, 512);
   }

   fclose($f);

}catch(IOException $ex){
   echo 'Oops, something wrong: '.$ex->getCode();
}

Of course, currently is not much practical but it's very annoying to receive:

WARNING

WARNING

WARNING

and I can't control the flow of code without writing my own error_handler and string sniffing which error has been produced (permission, incorrect filename or anything else; I don't mind about other sources of errors here) in order to throw correct exception.

I hope I haven't to explain why it's important.

PHP became Object-Oriented an amount time ago and we, programmers who use PHP, are looking forward for OO features, not introducing "goto"... When I found out it really happend, I thought it was an April Fool's day.


问:
How to find a programming mentor?
I decided to learn programming. I've been reading SO for few days, and I think I will start with C++, as I read some articles. I am aware of loops, arrays, program logic and objects a little and I need someone to look me over and help me with small questions I get when doing my first projects.

So here is the question - where do I find such guy? I don't got any friends who program and all.

EDIT: 2 years later, I am still looking for mentor. I did not actively code just started 3 months again. I work on Objective-C and iOS programming and game programming with Cocos2d. If you want to become my mentor, drop me a or comment.

答:
The types of people who make really good mentors usually have a dozen or so juniors yapping for their time at any given moment.  So, "finding" the right mentor is just the beginning, you also have to make mentoring you more attractive/rewarding than mentoring somebody else.

So, step one is to join communities where you are likely to meet good mentors.

Step two is to become a worthwhile mentee.  Some things that I, personally, look for in a mentee are:

Intelligence near, equal to, or greater than my own.

Interest in the things I have to offer and enjoy teaching.

Compatibility of personality (i.e. we get along well, enjoy talking to one another).

Willingness to be valuable to the project/community I'm mentoring him/her in, by:

Writing Code

Writing Documentation

Doing scut work like issue queue triage, cleaning up comments, etc.

Helping out less experienced contributors

Compatibility with my usual workflow.

Ability to teach me things.  Being more experienced than someone doesn't preclude learning from them.  The best mentee has a knack for asking the right questions, or a fresh viewpoint, or some experience from outside my areas of knowledge from which I can learn.

ContentLicense: CC BY-SA 3.0

Title: How to find a programming mentor?


问:
The Programmers Bill of Responsibilities
So, we've all heard of The Programmers Bill of Rights and XP has a similar concept.

It's a common complaint these days that we hear a lot about people's rights but not so much about their responsibilities, so what should be on the programmers bill of responsibilities.  That is things that they should do, which they may find unpalatable, but that which separate programmers acting professionally and responsibly, from those who do not.

I'm primarily interested in the unpalatable ones and the ones which tend not to happen.  That is the ones that programmers tend to shirk and avoid, rather than the ones which 90% of programmers actually want to do (such as always refactor and use source control).

So, what should be on the Programmers Bill of Responsibilities?

答:
Don't make the user lose their work.

This is harder than it sounds... work is more than just "data in a file"... it's any time that the user has spent with your software.

For example, if the user filled out your 30-field form with 29 valid items and 1 invalid one, don't clear all his valid data to complain about the 1 invalid one (heck, don't even clear the invalid one... maybe it's long and just requires a minor correction, or the user won't remember what it was before if you clear it)

A non-obvious but important example is what Windows and practically every other "file manager" software gets wrong.... if I spent a half hour carefully Ctrl-Click'ing to select a set of files and I accidentally do Click instead of Ctrl-Click, it should not clear all my previously selected files, making me start over.

Another one that they got wrong... if I accidentally hit Ctrl-A (instead of Ctrl-S right next door), it should not lose my place in the file and put the cursor at the beginning.... I call finding the right place in the file "work" which the program has "lost".

Yet another: TortoiseSVN's "commit" dialog has a long list of files.  Before hitting "Commit", you can go down the list of files, double-clicking on each one to see its changes in a 2nd dialog.  To do this quickly I sometimes use the keyboard only, hitting <Esc> to close the 2nd dialog and go back to the 1st.  If I accidentally hit <Esc>
twice, it also closes the 1st dialog, which results in me forgetting which file I was up to.


问:
How often do you run & test your code while programming?
Especially when writing new code from scratch in C, I find myself writing code for hours, even days without running the compiler for anything but an occasional syntax check.

I tend to write bigger chunks of code carefully and test thoroughly only when I'm convinced that the code does what it's supposed to do by analysing the flow in my head. Don't get me wrong - I wouldn't write 1000 lines without testing at all (that would be gambling), but I would write a whole subroutine and test it (and fix it if necessary) after I think I'm finished.

On the other side, I've seen mostly newbies that run & test their code after every line they enter in the editor and think that debuggers can be a substitute for carefulness and sanity. I consider this to be a lot of distraction once you've learned the language syntax.

What do you think is the right balance between the two approaches? Of course the first one requires more experience, but does it affect productivity positively or negatively? Does the second one help you spot errors at a finer level?

答:
For me ;-

Short timeline (not much time to think)- write code, compile, test. debug

Sufficient time - while(done) {write small code, compile}, test, debug


问:
Is there any reason to use C++ instead of C, Perl, Python, etc.?
As a Linux (server side) developer, I don't know where and why should I use C++.

When I'm going for performance, the first and last choice is C.

When "performance" isn't the main issue, programming languages like Perl and Python would be good choices.

Almost all open source applications I know in this area have been written in C, Perl, Python, Bash script, AWK or even PHP, but no one uses C++.

I'm not discussing other areas like GUI or web applications, I'm just talking about Linux, CLI and daemons.

Is there any satisfactory reason to use C++?

答:
RAII for the win baby.

Seriously, deterministic destruction in C++ makes code much clearer and safer with no overhead whatsoever.

ContentLicense: CC BY-SA 4.0


答:
Programming is a profession, not a skill.  This means that a programmer has the responsibility to stay current in his field on the latest tools, techniques, and technology.

This may mean pushing back to managers to give time to allow for continuous learning and training, or doing it on your own time.

Title: The Programmers Bill of Responsibilities

Body:
So, we've all heard of The Programmers Bill of Rights and XP has a similar concept.

It's a common complaint these days that we hear a lot about people's rights but not so much about their responsibilities, so what should be on the programmers bill of responsibilities.  That is things that they should do, which they may find unpalatable, but that which separate programmers acting professionally and responsibly, from those who do not.

I'm primarily interested in the unpalatable ones and the ones which tend not to happen.  That is the ones that programmers tend to shirk and avoid, rather than the ones which 90% of programmers actually want to do (such as always refactor and use source control).

So, what should be on the Programmers Bill of Responsibilities?


答:
Here is my proposal.

A programmer should require the working conditions exposed in the Programmer's Bill of right, in order not to lower the standards for the position.

(For "programmer" I mean "programmer", not "weekend hacker", so all the standard thing a programmer should do are implied.)


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

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

答:
If I were to interview a software developer, I'd ask him to design a software and describe hardware requirements to remove duplicate entries from an arbitrarily large file containing a full name on each line. I leave some parts of the problem description ambigous purposefully. Then I challenge him to see if he understands analysing and clarifying requirements, different trade-offs, data structures and algorithms, I/O (secondary storage), software and hardware technologies, scalability, etc.

I think it is a small yet challenging problem, revealing applicant's knowledge and abilities in many computing areas.


问:
Does making source code available affect your ability to generate revenue?
We’re working on a .Net framework which ultimately amounts to a single DLL.  We intend to charge for commercial use of the framework, but make it free for open source/non-commercial use.  The rough plan at the moment is to administer this through some form of fairly simple licence which will be issued whether you’re using it for free or paying.

We’re debating whether to make the source code available.  It’s our perception (and our own preference) that it’s far more appealing to use something where you have access to the source code.

I’m interested in whether people think making the source code available will damage our ability to make money from the framework, or whether it will encourage more usage and enough “good” people will arrange to pay for the correct licence if using it commercially.

My feeling is that, generally, commercial operations don’t mess about on the licencing front and so making the source code available will only encourage usage and therefore ultimately generate more revenue, but I’d be interested in others views/experience.

答:
Personally I think that the best example of this is the way that companies such as Telerik and others do their licensing.

You pay for the license, you get the source code, and it is for your use.

If you make it under a method where it can be available for opensource/non-commercial use free, with source, I think it will be hard for you to get people to come forward and pay for it.


答:
From the Manifesto for Software Craftsman:

As aspiring Software Craftsmen we are raising the bar of professional software development by practicing it and helping others learn the craft. Through this work we have come to value:

Not only working software, but also well-crafted software

Not only responding to change, but also steadily adding value

Not only individuals and interactions, but also a community of professionals

Not only customer collaboration, but also productive partnerships

That is, in pursuit of the items on the left we have found the items on the right to be indispensable.


问:
How should calculations be handled in a document database
Ok, so I have a program that basically logs errors into a nosql database. Right now there is just a single model for an error and its stored as a document in the nosql database.

Basically I want to summarize across different errors and produce a summary of the "types" of errors that occured.

Traditionally in a SQL database the this normalization would work with groupings, sums and averages but in a NoSQL database I assume I need to use mapreduce.

My current model seems unfit for the task, how should I change the way I store "models" in order to make statistical analysis easy? Would a NoSQL database even be the right tool for this type of problem?

I'm storing things in Google AppEngine's BigTable, so there are some limitations to think of as well.

答:
Why not simply add a classification column to the table?  Something like "errorType:ReallyBadError".

Then you 'map' to the errorType, and 'reduce' with, for example, a 'Sum' function.


问:
Do you actually write 'clean code'?
I have seen some programmers tweaking their code over and over again not only to make it 'work good', but also to make it 'look good'.

IMO, 'clean code' is actually a compliment indicating your code is elegant, perfectly understandable and maintainable. And the difference comes out when you have to choose between an aesthetically appealing code vs. code that's stressful to look at.

So, how many of you actually write 'clean code'? Is it a good practice? What are the other benefits or drawbacks of this?

答: I think "clean code" should be as clean or cleaner than how you used to write on your physics/engineering/math exams. If it's too messy, the grader won't understand your work and will probably mark it wrong even if it's right. </p>

Title: Do you actually write 'clean code'?


答:
Have a look in the mirror and possibly recognize the worst qualities of a programmer in himself. Then work on eliminating them each day.

Not learning anything new

Not seeking to extend your skills

Not being open for new, sticking to old habits

Not caring about the quality of your work

Not seeking to improve the quality of your work

Being a 9-to-5 worker with no passion

Not having own opinion of the things

Accepting others' opinion without questioning

Believing you've learnt it all

Not tolerating any criticism

Not listening to external input

Being ego-centric, know-it-all individual

Having a negative personality and criticizing other people


答:
5 precepts of the programmer's guild

1.) check in his/her code weekly and on holidays.

2.) provide for the needs of the programming community.

3.) read at least one programming book per year.

4.) go to at least one programming conference per year.

5.) own up to your mistakes.


问:
White Boards -- Who Uses Them?
So as both a full-time programmer and hobbyist as well (developing my own things for personal use and maybe to sell one day), I feel that me purchasing a big white board to hang in my room at home or something would be very useful.

Does anyone here have one as well, to use for high level designs (UML, Architecture, etc.) and things like very early UI mockups, etc.?

If you guys do have them, which ones have you bought? I can't seem to pin one that would be good for home use and I'm not sure of the pricing/other things.

Thanks!

答:
I found a glass top from a coffee table at a garage sale.  I made a couple of brackets and screwed it to the wall in my office, and that's what I use.  My office walls are a light yellow, so most markers show up pretty well.

I considered building something with a piece of plywood and some white ceramic tile, but I found the piece of glass first.

Title: White Boards -- Who Uses Them?


问:
Do you check in bin or debug folders (and dlls) into your TFS?
Quick question about TFS -
Do you guys check-in bin/debug folders into TFS?
(if so, why?)
Since the content of those folders are dynamically generated is it better to leave them out so that the programmer will not run into read-only issues?</p>

答: I hesitate to check any non-text file into source control. Especially ones that should be generated by the developer. I also like to keep other binary files, such as images and PDFs, zipped up and stored elsewhere for each tag/release.</p>


答: We check-in the contents of the bin directories as part of our Change Request process.  To avoid the read-only issues, we copy the contents to a separate folder and check them in from there.  Our corporate policy requires that all binaries that go to production are checked-in separately from the source.  It's not the best solution but it works and it does give us the exact files that are in production.</p>

Title: Do you check in bin or debug folders (and dlls) into your TFS?

Body:
Quick question about TFS -
Do you guys check-in bin/debug folders into TFS?
(if so, why?)
Since the content of those folders are dynamically generated is it better to leave them out so that the programmer will not run into read-only issues?</p>


答:
As a general rule, source control is best used for source only, and generated files are not source.

There are exceptions.  Sometimes (using Visual Studio) you might want to keep the .pdb file for reading minidumps.  Sometimes you can't duplicate a toolchain, so that you can't necessarily recreate generated files accurately.  In these cases, you're primarily interested in doing this for released software, not for every VCS change, and in any case these can easily reside in versioned folders.  (These are typically binary files, anyway, and don't have comprehensible changes from one version to another, and don't benefit all that much from being in a VCS.)


答: I have a small paper sized white board that I use constantly.  I use it for high level designs, quick calculations, unit testing, etc.  It is very useful and more environmentally friendly because I was going through a lot of paper before I had my white board.  I find the smaller desk white board is more convenient because you can bring it with you if you need to show someone something.</p>

Title: White Boards -- Who Uses Them?

Body:
So as both a full-time programmer and hobbyist as well (developing my own things for personal use and maybe to sell one day), I feel that me purchasing a big white board to hang in my room at home or something would be very useful.

Does anyone here have one as well, to use for high level designs (UML, Architecture, etc.) and things like very early UI mockups, etc.?

If you guys do have them, which ones have you bought? I can't seem to pin one that would be good for home use and I'm not sure of the pricing/other things.

Thanks!


答:
No, but our in house project control tool does automatically, which annoys the heck out of me.

My solution is to mark all the files in release and debug as writable and when TFS complains I tell it to ignore the files, so I never have a problem with a build failing.


答:
Simple answer? No. Don't do it! I can't think of many reasons not to, but no reason why you would want to.

The only time I can think you would check in a dll is if it's from a third party library that you don't expect every developer to have installed to build. But even still, that's not located in the bin folder.

That being said I did work at one company that required that each deploy package be put into source control, but that was so that we could track the various builds we gave to our client and could easily roll back if we had to.


问:
Is anything in programming truly evil?
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...

答:
I agree with the c++ FAQ on this:

[6.16] Will I sometimes use any so-called "evil" constructs?

Of course you will!

One size does not fit all. Stop. Right now, take out a fine-point marker and write on the inside of your glasses: Software Development Is Decision Making. "Think" is not a four-letter word. There are very few "never..." and "always..." rules in software — rules that you can apply without thinking — rules that always work in all situations in all markets — one-size-fits-all rules.

In plain English, you will have to make decisions, and the quality of your decisions will affect the business value of your software. Software development is not mostly about slavishly following rules; it is a matter of thinking and making tradeoffs and choosing. And sometimes you will have to choose between a bunch of bad options. When that happens, the best you can hope for is to choose the least bad of the alternatives, the lesser of the "evils."

You will occasionally use approaches and techniques labeled as "evil." If that makes you uncomfortable, mentally change the word "evil" to "frequently undesirable" (but don't quit your day job to become an author: milquetoast terms like that put people to sleep :-)

Title: Is anything in programming truly evil?


答: I avoid entering them into source control. They're redundant information, the binaries can be built by the source code in that revision. Additionally, the source code is always up to date, the builds may not be on commit.</p>


问:
is coding important?
Is coding important to be good at computer science? Should one implement the algorithm to know it well ?

I remember one cs professor's idiom that "I never code"

答: Sounds like hes more of a discrete mathematics kind of guy... just into the math and theory behind computer science. Take what these types of professors have to say with a grain of salt.</p>

Title: is coding important?


答:
If you're talking about being a pure Computer Science academic specializing in abstract, foundational Computer Science concepts, then not necessarily.

To bend an analogy: this is a bit like asking if every rocket scientist at NASA should have to fly in space to be a "good rocket scientist". Of course not. Being an astronaut is part of the space flight industry, and a very hands-on part, but it doesn't mean that ground scientists aren't just as important in their own way.

That said, it's probably a good idea to APPLY the algorithm he created, if not actually write it in a real programming language. In this sense, you can think of algorithm design as a branch of mathematics.

Title: is coding important?

Body:
Is coding important to be good at computer science? Should one implement the algorithm to know it well ?

I remember one cs professor's idiom that "I never code"


答:
We do not check in the bin folder into TFS.  As you have probably noticed, if you do that, every time any developer builds the solution, they will be checking out the bin folder.  Not good.  However there are libraries that the project needs in order to compile and run, and our rule is that any project should be able to be opened from source control, and it should compile and run.  So what we do is create a "BinRef" folder for any DLLs that the project must have reference to, and create the Project References to the copy in the BinRef folder.  The BinRef folder is checked in to TFS.

The other advantage to this approach is that BinRef is always at the root level of the web project.  If my project lives in C:\Projects\Marcie\SomeProjectCategory\ProjectA and I create a reference to a DLL that sits in C:\DLLsThatILike, the reference will end up looking something like

\..\..\..\NiceThing.dll

.  You may keep your project files in C:\ProjectA which means that the project reference to NiceThing will blow up on your machine.  Hopefully people aren't doing references this way, but I've seen it happen.


答:
Linux? What about "object oriented Pascal" or "D"?

Suggestions:

Lazarus

Intro - D Programming Language 2.0 - Digital Mars

Title: Is there any reason to use C++ instead of C, Perl, Python, etc.?

Body:
As a Linux (server side) developer, I don't know where and why should I use C++.

When I'm going for performance, the first and last choice is C.

When "performance" isn't the main issue, programming languages like Perl and Python would be good choices.

Almost all open source applications I know in this area have been written in C, Perl, Python, Bash script, AWK or even PHP, but no one uses C++.

I'm not discussing other areas like GUI or web applications, I'm just talking about Linux, CLI and daemons.

Is there any satisfactory reason to use C++?

OwnerDisplayName: mramirez


答: You won't really know the algorithm well until you code it.

Title: is coding important?


答:
Coding is not important to your professor, but you need to keep in mind that he is not paid to DO things.  He is paid to SAY things (and WRITE things.)

I'm a former math professor, so I understand this dynamic well.

If you want to follow his path, and to be a theoretical computer scientist, then yes, coding is of lesser importance.  But if you do, remember to maintain humility, knowing that your salary is paid by resources earned by those that chose to DO things.

Title: is coding important?


答:
This is like asking if all English professors should be capable of writing movies, TV series, novels, plays and poems to my mind.  Similarly, imagine a Math professor that never uses numbers for an equally outlandish idea.  That is to say that there are some basic elements that do give coding some importance in being able to teach basic Computer Science.  Thus the professor should know basic language syntax and how to write programs as sophisticated as the courses that the professor is teaching.  If the professor is teaching about compiler design and never wrote a compiler before, this would be a major problem.  Imagine a chef cooking a cake that has never cooked or ate a cake previously.  Aye carumba.

While I can see some advantages to implementing an algorithm to know it, I doubt it is a requirement.  After all, one could wonder how far down the rabbit hole of implementation does one go in understanding how an algorithm is implemented?  For example does someone have to take any algorithm and implement it under various paradigms like procedural, Object-oriented, and functional programming to really know it?  Do they have to know how compilers translate all the code and move the bits around on an electron-by-electron level to be rather pedantic about it.

"I never code," does have an implication of containing the past as well as present tense in a way though.  There can also be an implicit assumption of "coding" as a lowly thing that is below the professor for another way to view the statement that can carry a rather negative tone to it that may not go over well in some circles.

Title: is coding important?


答:
Despite being a professional software developer, I got a degree in Mechanical Engineering.

You can be a good mechanical designer with very little experience building and machining parts, leaving that job to machinists. But knowing how to build and machine parts will make you a significantly better engineer, because you can predict difficulties involved with fabricating and assembling whatever you are designing.

The same goes for software. A "coder" is a machinist or technician, while a software engineer is, well, the engineer. For many places, one person does both jobs. It's not impossible, and for some very abstract issues, a "engineering only" position might work.

But for the vast majority, there is absolutely no benefit from refusing to code.

Title: is coding important?


问:
What techniques do you use when interviewing developers?
I realize there have been lots of discussions about this type of thing and they often devolve into dogma around whether you ask the "100 logical pirates" type of questions or whether you get them to write "fizz buzz".

I'm interested in what techniques and questions have been effective for you when interviewing potential developers for jobs.

One technique per answer so we can vote on them, please.

答:
Ask their take on an important architectural decision

For example. Here is program x that runs y number of subtasks concurrently. Which would you choose, a multi-process or threading structure.

What are the benefits/disadvantages of both. How well would they work and how could they be used to leverage a multi-core, multi-processor platform, what is your personal preference? Personal biases can aid in identifying whether they've ever had to actually apply the knowledge and give them a jump point to share their experiences?

There are tons of questions an interviewer could come up with like these:

TCP or UDP?

Dynamic or Statically typed language?

Monolithic application or multiple smaller applications?

What would you use for Interprocess Communication?

Stored Procedures or ORM?

Most of these topics are the types that involve an intimate knowledge of how/why a computer system works the way it does. They all are issues/solutions to problems that have no definite answer so they give a sense of how well that person is able to adapt or overcome the challenges at hand. Not the type of concepts that can be easily picked up without some actual hands on experience.

Note: Having the applicant write some pesudo code is a must too but that answer is already taken.


问:
Is there any evidence that one of the current alternate JVM languages might catch on?
There's been a lot of enthusiasm about JRuby, Jython, Groovy, and now Scala and Clojure as the language to be the successor to Java on the JVM.

But currently only Groovy and Scala are in the TIOBE top 100, and none are in the top 50.  Is there any reason to think that any of this bunch will ever gain significant adoption?

My question is not primarily about TIOBE, but about any evidence that you might see that could indicate that one of these languages could get significant backing that goes beyond the enthusiasts.

答: Alternate JVM Languages could get a significant boost on Android now that the Android Scripting Environment is available.</p>


答:
You can get away with understanding the theory only but I always found I understood algorithms and such 1000x better after having coded them (Bubble sort vs. Quicksort for example, it is great to know the Big-O but seeing it in practice with large data-sets gives you a certain real world appreciation for measuring computational complexity).

One interesting thing I have found is the more you study the theoretical aspets of computer science the easier coding becomes.  At some point you stop thinking of things in a particular language but rather see them just as the broader concepts of computer sience.

Title: is coding important?


答: I'll add "always document any assumptions made" to the list. :-)</p>


答:
Depends on the subfield the professor is in.

Anybody competent in numerical analysis is probably a Fortran whiz.  Any AI professor will code in Lisp or Prolog or something like that.

In some of the more mathematical areas, there really isn't a need to code.  I'd still be a touch suspicious, myself.

Title: is coding important?


答: I would have to say "Logic is important"

Title: is coding important?


答:
I write code that attempts to solve the given problem in the most efficient and theorertically 'elegant' way.  In that sense only it is clean.  If it happens to be 'pretty' when I am done, so be it.

What I have found in my limited experiences is that when people complain about 'clean-code', the ugliness is usually a result of a terrible solution rather than coding convention.

Title: Do you actually write 'clean code'?

Body:
I have seen some programmers tweaking their code over and over again not only to make it 'work good', but also to make it 'look good'.

IMO, 'clean code' is actually a compliment indicating your code is elegant, perfectly understandable and maintainable. And the difference comes out when you have to choose between an aesthetically appealing code vs. code that's stressful to look at.

So, how many of you actually write 'clean code'? Is it a good practice? What are the other benefits or drawbacks of this?


答:
I've got another idiom for your professor:

Those who can, do, those who can't, teach.

imo, talk is cheap.  Anyone can endlessly jabber on about 'theory' and call it 'computer science'.  But until its put into actual practice, theory isnt very useful because there's no way to validate it.  I'd take a prof's opinion about something much more seriously if I knew he's actually solved a particular problem in code than if he's just regurgitating 'theory' which may or may not have any supporting evidence to back up his point of view.

Title: is coding important?


答:
If by 'clean code' you mean do I go out of my way to make sure the code is as clear as possible?

Heck yes.

The cleaner, clearer the code, the easier it is to maintain, and thus saves you time in the long run. Don't look at clean code as vanity; look at it as an investment in saving future effort and time.

Title: Do you actually write 'clean code'?


答:
I write just enough code to get test to green.
That means I run test every few minutes. That's my C++ style. However in Ruby I use autotest, so every time I hit save I get tests feedback via nice popup. I don't even stop writing code, it just happens in background.</p>

Title: How often do you run & test your code while programming?

Body:
Especially when writing new code from scratch in C, I find myself writing code for hours, even days without running the compiler for anything but an occasional syntax check.

I tend to write bigger chunks of code carefully and test thoroughly only when I'm convinced that the code does what it's supposed to do by analysing the flow in my head. Don't get me wrong - I wouldn't write 1000 lines without testing at all (that would be gambling), but I would write a whole subroutine and test it (and fix it if necessary) after I think I'm finished.

On the other side, I've seen mostly newbies that run & test their code after every line they enter in the editor and think that debuggers can be a substitute for carefulness and sanity. I consider this to be a lot of distraction once you've learned the language syntax.

What do you think is the right balance between the two approaches? Of course the first one requires more experience, but does it affect productivity positively or negatively? Does the second one help you spot errors at a finer level?


问:
C++ : Lack of Standardization at the Binary Level
Why ISO/ANSI didn't standardize C++ at the binary level? There are many portability issues with C++, which is only because of lack of it's standardization at the binary level.

Don Box writes, (quoting from his book Essential COM, chapter COM As A Better C++)

C++ and Portability

  Once the decision is made to
  distribute a C++ class as a DLL, one
  is faced with one of the fundamental
  weaknesses of C++, that is, lack of
  standardization at the binary level.
  Although the ISO/ANSI C++ Draft
  Working Paper attempts to codify which
  programs will compile and what the
  semantic effects of running them will
  be, it makes no attempt to standardize
  the binary runtime model of C++. The
  first time this problem will become
  evident is when a client tries to link
  against the FastString DLL's import library from
  a C++ developement environment other
  than the one used to build the
  FastString DLL.

Are there more benefits Or loss of this lack of binary standardization?

答:
Cross-platform and cross-compiler compatibility were not the primary goals behind C and C++. They were born in an era, and intended for purposes for which platform-specific and compiler-specific minimizations of time and space were crucial.

From Stroustrup's "The Design and Evolution of C++":

"The explicit aim was to match C in
  terms of run-time, code compactness
  and data compactness. ... The ideal -
  which was achieved - was that C with
  Classes could be used for whatever C
  could be used for."

OwnerDisplayName: Nawaz

OwnerDisplayName: Andy Thomas-Cramer


答: I don't know why it doesn't standardize on a binary level.  But I know what I do about it.  On Windows I declare function extern "C" BOOL WINAPI.  (Of course replace BOOL with whatever type the function is.) And they are exported cleanly.</p>

Title: C++ : Lack of Standardization at the Binary Level

Body:
Why ISO/ANSI didn't standardize C++ at the binary level? There are many portability issues with C++, which is only because of lack of it's standardization at the binary level.

Don Box writes, (quoting from his book Essential COM, chapter COM As A Better C++)

C++ and Portability

  Once the decision is made to
  distribute a C++ class as a DLL, one
  is faced with one of the fundamental
  weaknesses of C++, that is, lack of
  standardization at the binary level.
  Although the ISO/ANSI C++ Draft
  Working Paper attempts to codify which
  programs will compile and what the
  semantic effects of running them will
  be, it makes no attempt to standardize
  the binary runtime model of C++. The
  first time this problem will become
  evident is when a client tries to link
  against the FastString DLL's import library from
  a C++ developement environment other
  than the one used to build the
  FastString DLL.

Are there more benefits Or loss of this lack of binary standardization?

OwnerDisplayName: mike jones


答:
As Andy said cross platform compatibility wasn't a big goal, whereas broad platform and hardware implementation was a goal, with the net result that you can write conforming implementations for a very wide selection of systems. Binary standardization would have made this practically unachievable.

C compatibility was also important and would have significantly complicated this.

There has subsequently been some efforts to standardise the ABI for a subset of implementations.

OwnerDisplayName: awoodland


答:
The aim of ISO/ANSI was to standardize the C++ language, issue that seems to be complex enough to require years to have an update of the language standards and compiler support.

The binary compatibility is much more complex, given that the binaries need to run on different CPUs' architectures and different OS environments.


答: It's not a bug, it's a feature! This gives implementors freedom to optimize their implementation at the binary level. The little-endian i386 and its offspring are not the only CPUs that have or do exist.</p>

OwnerDisplayName: Raedwald


答:
The problem described in the quotation is caused by the quite deliberate avoidance of standardisation of symbol-name mangling schemes (I think "standardisation at the binary level" is a misleading phrase in this respect although the issue is related to a compiler's Application Binary Interface (ABI).

C++ encodes a function or data object's signature and type information, and its class/namespace membership into the symbol-name, and different compilers are allowed to use different schemes.  Consequently a symbol in a static library, DLL, or object file will not link with code compiled using a different compiler (or possibly even a different version of the same compiler).

The issue is described and explained probably better than I can here, with examples of schemes used by different compilers.

The reasons for the deliberate lack of standardisation are also explained here.

OwnerDisplayName: Clifford


答:
Languages with binary-compatible compiled form are a relatively new phase[*], for example the JVM and .NET runtimes. C and C++ compilers usually emit native code.

The advantage is that there is no need for a JIT, or a bytecode interpreter, or a VM, or any other such thing. For example, you can't write the bootstrap code that runs at machine startup as nice, portable Java bytecode, unless perhaps the machine can natively execute Java bytecode, or you have some kind of converter from Java to a non-binary-compatible native executable code (in theory: not sure this can be recommended in practice for bootstrap code). You could write it in C++, more or less, albeit not portable C++ even at the source level, since it will do a lot of messing with magic hardware addresses.

The disadvantage is that of course native code only runs at all on the architecture it was compiled for, and the executables can only be loaded by a loader that understands their executable format, and only link with and call into other executables for the same architecture and ABI.

Even if you get that far, linking two executables together will only actually work correctly as long as: (a) you don't violate the One Definition Rule, which is easy to do if they were compiled with different compilers/options/whatever, such that they were using different definitions of the same class (either in a header, or because they each statically linked against different implementations); and (b) all relevant implementation details such as structure layout are identical according to the compiler options in force when each was compiled.

For the C++ standard to define all of this would remove a lot of the freedoms currently available to implementers. Implementers are using those freedoms, especially when writing very low-level code in C++ (and C, which has the same issue).

If you want to write something that looks a bit like C++, for a binary-portable target, there's C++/CLI, which targets .NET, and Mono so that you can (hopefully) run .NET elsewhere than Windows. I think it's possible to persuade MS's compiler to produce pure CIL assemblies that will run on Mono.

There are also potentially things that can be done with for example LLVM to create a binary-portable C or C++ environment. I don't know that any widespread example has emerged, though.

But these all rely on fixing a lot of things that the C++ makes implementation-dependent (such as the sizes of types). Then the environment that understands the portable binaries, must be available on the system where the code is to run. By allowing non-portable binaries, C and C++ can go places where portable binaries can't, and that's why the standard doesn't say anything at all about binaries.

Then on any given platform, implementations usually still don't provide binary compatibility between different sets of options, although the standard isn't stopping them. If Don Box doesn't like that Microsoft's compilers can produce incompatible binaries from the same source, according to compiler options, then it's the compiler team he needs to complain about. The C++ language does not forbid a compiler or an OS from pinning down all the necessary details, so once you limit yourself to Windows it's not a fundamental problem with C++. Microsoft has chosen not to do so.

The differences often manifest as one more thing that you can get wrong and crash your program, but there may be considerable gains to be made in efficiency between, for example, incompatible debug vs release versions of a dll.

[*] I'm not sure when the idea was first invented, probably 1642 or something, but their current popularity is relatively new, compared to the time when C++ committed to the design decisions which prevent it defining binary-portability.

OwnerDisplayName: Steve Jessop


问:
Intro to C for an experienced programmer
This reply to the question "I don't know C. And why should I learn it?" has me interested in learning C. What is a good self-instruction program (textbook/website/OpenCourseWare, etc.) for someone who already has lots of experience in high-level languages?</p>

答: This is a clichéd answer, but my intro to C programming was Kernighan and Richie's The C Programming Language.


答:
Computer Science is no more about computers than astronomy is about telescopes

— Edsger Dijkstra

I tend to agree.

Title: is coding important?


问:
What's the best way to run a technical book club?
At work, we've been doing lunchtime book clubs for a while. So far we've done:

Clean Code

Working Effectively with Legacy Code

The Pragmatic Programmer

We read a chapter per week, and one person is assigned to present over the content and help facilitate discussion.  Of the three, we've probably had the most success with The Pragmatic Programmer. It seems like the more technically complicated the content was, the more people tended to drop out as the book went along.

I'd like to do a technically-heavy book like SICP or Java Concurrency in Practice, but I don't know of good ways to make this work with the format we're currently doing. What advice do you have?

答: Maybe every once in a while change the meeting format, where someone takes on a technical topic to present to the group.</p>

OwnerDisplayName: JimmyJ


答:
What I like to do in a book club is find practical application - or examples of practical application of the concepts in the book. Instead of asking someone to present, ask multiple people (or anyone who wants to volunteer) to come up with relevant examples of the concepts in the book.

For example, when you read the chapter in the pragmatic programmer about broken windows (I know you read this one already, but since everyone has read this book, it's a good example), ask for examples of broken windows in your own source code - or examples of broken windows on code the team is familiar with. For me, the connection between ideas that look good on paper and real examples do a ton to drive the points home.

Title: What's the best way to run a technical book club?

Body:
At work, we've been doing lunchtime book clubs for a while. So far we've done:

Clean Code

Working Effectively with Legacy Code

The Pragmatic Programmer

We read a chapter per week, and one person is assigned to present over the content and help facilitate discussion.  Of the three, we've probably had the most success with The Pragmatic Programmer. It seems like the more technically complicated the content was, the more people tended to drop out as the book went along.

I'd like to do a technically-heavy book like SICP or Java Concurrency in Practice, but I don't know of good ways to make this work with the format we're currently doing. What advice do you have?


问:
Highly scalable and dynamic "rule-based" applications?
For a large enterprise app, everyone knows that being able to adjust to change is one of the most important aspects of design. I use a rule-based approach a lot of the time to deal with changing business logic, with each rule being stored in a DB. This allows for easy changes to be made without diving into nasty details. Now since C# cannot Eval("foo(bar);") this is accomplished by using formatted strings stored in rows that are then processed in JavaScript at runtime. This works fine, however, it is less than elegant, and would not be the most enjoyable for anyone else to pick up on once it becomes legacy.

Is there a more elegant solution to this? When you get into thousands of rules that change fairly frequently it becomes a real bear, but this cannot be that uncommon of a problem that someone has not thought of a better way to do this. Any suggestions? Is this current method defensible? What are the alternatives?

Edit: Just to clarify, this is a large enterprise app, so no matter which solution works, there will be plenty of people constantly maintaining its rules and data (around 10).  Also, The data changes frequently enough to say that some sort of centralized server system is basically a must.

答:
There are two cases of rules I have seen. In most cases the rule itself is not very volatile (almost fixed) but the data on which decision is taken can be changed by business users. In this case simple design patterns to encapsulate each rule with reading the reference data from DataBase is usually sufficient. Then provide a frontend to change the rules reference data.

The other cases where the rule logic itself can be changed dynamically. One approach would be to use IronPython or other dynamic languages (in .Net 4) to implement the rules and load them dynamically at execution time. This is a compromise as you will still require programmers to change the rules.

If you really want rules to be editable by business users then creating DSL for your business domain is an approach to be taken. This is a complex undertaking though.

Finally using Workflow or BizTalk can help if the rules fit into transformation/orchestration patterns.


问:
Is it necessary to discuss database changes
I am working on a project with a team of 4-5 people. Is it necessary to discuss the database changes with the team before implementing?  I am working on the database api's.

Is it better to discuss this or not? In my team are senior people. So can't I make changes myself and implement the change and explain the changes.

答:
iff you own the API and your changes dó not affect others, Then I would consider you to have free hands in doing what is neccesary to dó your job.

A's soon as your changes influence others it becomes a team issue.


问:
How do you define stateless methods while keeping them together in Objective-C?
I have a few methods which are stateless:

```<code>loginWithEmail: password: completion:
signUpWithEmail: password: completion:
resetPasswordForUsername: completion:
</code>```

Currently what I do is I create a class which holds these stateless methods:

```<code>@interface KGAccountService : NSObject

+ (void)//method1
+ (void)//method2
+ (void)//method3

@end
</code>```

I then would call the methods from some place like a view controller that a user is using to log in.

```<code>[KGAccountService loginWithEmail:@"email" password:@"password" completion:{
    // user logged in or error
}];
</code>```

A co-worker of mine is pretty adamant that even though the class only houses class methods and does not need any sort of state, it should be implemented using the singleton pattern and be called through that:

```<code>@interface KGAccountService : NSObject

+ (instanceType)sharedInstance;
- (void)//method1
- (void)//method2
- (void)//method3

@end
</code>```

Then:

```<code>[[KGAccountService sharedInstance] loginWithEmail:@"email" password:@"password" completion:{
// user logged in or error
}];
</code>```

I don't see the point in implementing the singleton pattern when it is not needed and my co-worker was not able to get his point of view through to me.  Is there a design pattern which I am missing and is my way of creating a class to house stateless class methods correct?

答:
First of all, have you tried to ask your co-worker what would be the benefits of his approach ? From my point of view, the only advantage of having a singleton (and basically object methods) is to ensure that later on, you will be able to extend those functions (or to mock them), and change the behavior of code that relies on it. This is especially useful if you need to make some unit-test.

```<code>@interface KGAccountService : NSObject

+ (instanceType)sharedInstance;
- (void)//method1
- (void)//method2
- (void)//method3

@end

@implementation KGMockedAccountService : KGAccountService

- (void)//overridden method1
- (void)//overridden method2
- (void)//overridden method3

@end

// The account service injected here could be any one implemented above
-(Data *) retrieveUserDataWithAccountService: credentials: completion:
</code>```

Is this answering your question ?

For more information, you could make some researches on the Open-Closed principle.

Body:
First of all, have you tried to ask your co-worker what would be the benefits of his approach ? From my point of view, the only advantage of having a singleton (and basically object methods) is to ensure that later on, you will be able to extend those functions (or to mock them), and change the behavior of code that relies on it. This is especially useful if you need to make some unit-test.

@interface KGAccountService : NSObject

+ (instanceType)sharedInstance;
- (void)//method1
- (void)//method2
- (void)//method3

@end

@implementation KGMockedAccountService : KGAccountService

- (void)//overridden method1
- (void)//overridden method2
- (void)//overridden method3

@end

// The account service injected here could be any one implemented above
-(Data *) retrieveUserDataWithAccountService: credentials: completion:

Is this answering your question ?

For more information, you could make some researches on the Open-Closed principle.


问:
What is an Activation object in JavaScript?

In a given execution context, the Variable object is the Activation object of that execution context.

From my research online, I am able to find the previous sentence rephrased in different ways but no one is able to tell what it is.

What is an Activation object?

答:
An Activation object is the object used to hold the properties that describe the environment and scope of an executing function. It is on this object that function arguments for example, are stored. By definition, to ACTIVATE something is to cause that thing to act or FUNCTION. So when you hear 'Activation object', think 'FUNCTION' object, or better yet, the root object that is LOCAL to a function (i.e., the FUNCTION LOCAL OBJECT).

With regards to the Variable object, an Activation object is more or less a concrete instance of a Variable object, which is itself (referring to the Variable object here) an ABSTRACT object type. As stated here...

The term ‘Variable object' is a general or abstract term used to refer to any object that holds the properties that describe the environment and scope of the currently executing context.

Hence, within the environment and scope of the global execution context (i.e., when outside of a function), the Global object is the Variable object. In the browser, because the global or outermost executing environment is the browser WINDOW, it is the window object that ends up being used as the Variable object. This is why variables declared with the var keyword outside of functions end up on the window object.

In the scope of a function, however, it is the Activation object (i.e., the function local object) that is the variable object because it is this object that is used to store the properties that describe the scope of an executing function.


答:
Unless you're contemplating and end to the halting problem, there's always a use for coding in every aspect of Computer Science. </p>

<p>The only CS class I took with absolutely no programming was theory. I'd imagine there are plenty of physicists out there who say, "I never experiment" but they're probably also the ones who say, "I never discover anything".  And I'd be surprised if they care. </p>

Title: is coding important?

Body:
Unless you're contemplating and end to the halting problem, there's always a use for coding in every aspect of Computer Science.

The only CS class I took with absolutely no programming was theory. I'd imagine there are plenty of physicists out there who say, "I never experiment" but they're probably also the ones who say, "I never discover anything".  And I'd be surprised if they care.


问:
What is a receiver in SWT (or GUI programming in general)?
I see this notation used throughout documentation and discussions on SWT, but I've yet to see it actually defined. The comment on Stack Overflow by MarsAtomic makes me think it is just the object that is associated with a method call, or is it more complex than this?

It seems to not be the case, but that is probably me not doing something right elsewhere in SWT ;).

Here is an example for a layout method of the Composite class:

```<code>public void layout (boolean changed) {
    checkWidget ();
    if (layout == null) return;
    layout (changed, false);
}

/**
 * If the receiver has a layout, asks the layout to <em>lay out</em>
 * (that is, set the size and location of) the receiver's children.
 * If the changed argument is <code>true</code> the layout must not rely
 * on any information it has cached about its children. If it
 * is <code>false</code> the layout may (potentially) optimize the
 * work it is doing by assuming that none of the receiver's
 * children has changed state since the last layout.
 ...
**/
</code>```

答:
Object-oriented programming can be interpreted as message passing: objects are independent actors to which we can send messages (that is, we can invoke methods on that object). E.g. here I send the panel object a layoutYourself message:

```<code>panel.layoutYourself();
</code>```

Some languages make this message sending more visible by using special message send operators. E.g.:

```<code>panel <- layoutYourself;
</code>```

The receiver of the message, well, is called the receiver.

In languages like C++ or Java, method calls are much more like function calls than like message sends. However, the terminology “receiver” is still fairly widespread. A more function-oriented synonym is invocant: the thing on which you invoke the method.

Body:
Object-oriented programming can be interpreted as message passing: objects are independent actors to which we can send messages (that is, we can invoke methods on that object). E.g. here I send the panel object a layoutYourself message:

panel.layoutYourself();

Some languages make this message sending more visible by using special message send operators. E.g.:

panel <- layoutYourself;

The receiver of the message, well, is called the receiver.

In languages like C++ or Java, method calls are much more like function calls than like message sends. However, the terminology “receiver” is still fairly widespread. A more function-oriented synonym is invocant: the thing on which you invoke the method.


问:
Factored out loop control in Python
I have a for loop in python like this:

```<code>for item in items:
    onwards = make_flow_decision(item)
    if onwards == 'break':
        break
    elif onwards == 'continue':
        continue
    elif onwards == 'carry_on':
        process_the_item(item)
</code>```

So idea is that flow control for the loop is factored out because it is really complex.

Is there a better way of doing this than passing strings around and checking for special strings like 'continue', 'break', and 'carry_on'?

Looking for ideas generally that make this a little more elegant.

答:
You can use enumerated types instead of strings, and keep your implementation.

Or, if you don't mind using exceptions you can write:

```<code>try:
    for item in items:
        if shall_process(item):
            process_the_item(item)
except StopIteration:
    pass
</code>```

Here, shall_process returns a boolean and can throw an exception to exit the iteration.

Title: Factored out loop control in Python

Body:
You can use enumerated types instead of strings, and keep your implementation.

Or, if you don't mind using exceptions you can write:

try:
    for item in items:
        if shall_process(item):
            process_the_item(item)
except StopIteration:
    pass

Here, shall_process returns a boolean and can throw an exception to exit the iteration.


问:
License Compatibility: CC-BY-NC 3.0 with GPL2 (for Wordpress)?
I'm trying to figure out if I can use code licensed under Creative Commons Attribution-NonCommercial 3.0 (CC-BY-NC 3.0) in a Wordpress plugin (which must be released under GPL).  I think the answer is "no," based on here (https://www.gnu.org/licenses/license-list.en.html#CC-BY-NC), but I find the whole licensing mess to be just incomprehensible.

Basically, I already have a plugin that uses Fancybox (http://fancybox.net/).  Prior to v2.0 this was licensed under GPL; unfortunately, the author decided to release v2.0+ under CC-BY-NC (http://fancyapps.com/fancybox/#license).  1.x is now extremely outdated and is having some problems with newer releases of WP.

So what I'm trying to figure out is, can I update the copy of Fancybox that I'm bundling with my plugin to 2.0?  I think the answer is "no," because the author changed its license to CC-BY-NC. But I just want to make sure, before I start spinning my wheels and looking for a totally new solution...

答:
CC-BY-NC is not a free or open source license, because it lacks one fundamental freedom: to use the work for any purpose (See the OSI Open Source Definition under “No Discrimination Against Fields of Endeavor” and the FSF Free Software Definition). The restriction to only use the work for non-commertial purposes is incompatible with free software. Also, the CC licenses aren't really suited for licensing source code, and even the non-NC variants (e.g. CC-BY-SA) might be incompatible with the GPL.

So, you're out of luck. Of course, the original Fancybox will still be GPL-licensed, as are any third-party modifications – only the original author can re-license their work. You could therefore try to fix the issues yourself, or look around for a fork someone else started.


问:
How often do you run & test your code while programming?
Especially when writing new code from scratch in C, I find myself writing code for hours, even days without running the compiler for anything but an occasional syntax check.

I tend to write bigger chunks of code carefully and test thoroughly only when I'm convinced that the code does what it's supposed to do by analysing the flow in my head. Don't get me wrong - I wouldn't write 1000 lines without testing at all (that would be gambling), but I would write a whole subroutine and test it (and fix it if necessary) after I think I'm finished.

On the other side, I've seen mostly newbies that run & test their code after every line they enter in the editor and think that debuggers can be a substitute for carefulness and sanity. I consider this to be a lot of distraction once you've learned the language syntax.

What do you think is the right balance between the two approaches? Of course the first one requires more experience, but does it affect productivity positively or negatively? Does the second one help you spot errors at a finer level?

答:
It REALLY depends on the aspect of the project you're working on.

When I do anything with OpenGL (which works like a state machine), I constantly compile and run to make sure that I didn't accidentally screw up anything. Setting one value without remembering to reset it at the end of a function can easily make the application render only a black screen.

For larger scale "under the hood" development, I try to get as many tests as possible beforehand. Since the tests can more easily tell me what broke, I can go a while without having to wait for the typically long compile.

For UX design, I use some sort of visual designer, which always looks the way it will run (or close to it). It is essentially always compiling the design code.


问:
Does declaring a field as final force redundancy in the constructors?
I have the following abbreviated class:

```<code>public class Player {
    final private DoubleDuple position;
    final private DoubleDuple momentum;

    public Player() {
        position = new DoubleDuple(0, 0);
        momentum = new DoubleDuple(0, 0);
    }

    public Player(double xPos, double yPos) {
        position = new DoubleDuple(xPos, yPos);
        momentum = new DoubleDuple(0, 0);
    }

    public Player(double xPos, double yPos, double xMom, double yMom) {
        position = new DoubleDuple(xPos, yPos);
        momentum = new DoubleDuple(xMom, yMom);
    }
}
</code>```

With the fields being listed as final, I can't just have each more complicated constructor call each simpler constructor, since the final field would then be assigned twice; which isn't allowed.

If though, I removed the final modifier from the fields, I could change the last constructor to:

```<code>public Player(double xPos, double yPos, double xMom, double yMom) {
        this(xPos, yPos);
        momentum = new DoubleDuple(xMom, yMom);
}
</code>```

Which I find neater. In this example, it's not much of a change, but in situations where there are more fields that have defaultable values, it would be nice to not have to repeat myself in each constructor (DRY).

Questions:

When dealing with final fields, is there any way to not repeat myself in each constructor?

I'm asking this to abide by the DRY (Don't repeat yourself) principal. Should I be thinking this way?

答:
The way I usually do it is to code only the last constructor, and then make the simpler constructors delegate to the most complete one, by providing default values.
So, taking your example, I'd so it like this:</p>

```<code>public class Player {
    final private DoubleDuple position;
    final private DoubleDuple momentum;

    public Player() {
        this(0, 0, 0, 0);
    }

    public Player(double xPos, double yPos) {
        this(xPos, yPos, 0, 0);
    }

    public Player(double xPos, double yPos, double xMom, double yMom) {
        position = new DoubleDuple(xPos, yPos);
        momentum = new DoubleDuple(xMom, yMom);
    }
}
</code>```

Body:
The way I usually do it is to code only the last constructor, and then make the simpler constructors delegate to the most complete one, by providing default values.
So, taking your example, I'd so it like this:

public class Player {
    final private DoubleDuple position;
    final private DoubleDuple momentum;

    public Player() {
        this(0, 0, 0, 0);
    }

    public Player(double xPos, double yPos) {
        this(xPos, yPos, 0, 0);
    }

    public Player(double xPos, double yPos, double xMom, double yMom) {
        position = new DoubleDuple(xPos, yPos);
        momentum = new DoubleDuple(xMom, yMom);
    }
}


问:
How are new[] and malloc implemented in Windows?
So when you call malloc or new [] from your C/C++ application, how does the CRT translate it into Windows API calls?</p>

答:
It depends if you are in debug or release mode. In release mode, as Pedro said there is HeapAlloc/HeapFree which are kernel functions,

while in debug mode (with visual studio) there is a hand written version of free and malloc (to which new/delete are re-directed) with thread locks and more exceptions detection, so that you can detect more easily when you did some mistakes with you heap pointers when running your code in debug mode. This is one more reason why a code compiled in debug mode is slower.

I think it is the only one API which is "simulated" like this in debug mode.

Just step it into the debugger to understand how it works, if I remember well this debug version uses somes trees of double linked lists.

And this is also with this kind of re-writing of malloc/free that memory consumption analysers work : there is tool for that in visual studio which just uses another .dll as the implementation of allocations functions which notice another data analyser program each time they are called.


答:
Thrice an hour, whether it needs it or not.

We do test-first programming and commit only working code to the VCS.  The smolderbot goes and checks out the repo every 20 minutes and runs the test suite.  Any failures are immediately mailed to the entire programming team for immediate fixing.


问:
Should I force the user to wrap the arguments, or allow them to pass in the data at the cost of having more arguments?
I have the constructor:

```<code>public class Player {
    final private DoubleDuple position;
    final private DoubleDuple momentum;

    public Player(double xPos, double yPos, double xMom, double yMom) {
        position = new DoubleDuple(xPos, yPos);
        momentum = new DoubleDuple(xMom, yMom);
    }
}
</code>```

I have to allow the momentum to be passed in since I'm making the class immutable, so I'll need the ability to construct a Player with a different position, but with the previous momentum.

The problem is, this constructor now has 4 fields, and could get larger if later there are more fields that I need to pass into a newly constructed object (health, for example).

I could combine arguments by forcing the user to wrap positional coordinates and momentum values in a DoubleDuple before passing them in to the constructor, which will cut down on the number of arguments. I think this will also make it clearer that the first 2 and second 2 arguments are associated with each other. Unfortunately, this also has the effect of making each object construction bulkier, since there will be a few extra new DoubleDuples mixed in.

Is it better practice to have similar arguments that are wrapped internally passed in wrapped to the constructor, or should they be passed in "loose"?

答:
You can consider allowing your callers to pass in DoubleDuple. (To save some typing, below I will use Vec2 in place of DoubleDuple.)

Example:

```<code>public class Vec2 {
    public final double x;
    public final double y;
    public Vec2(double x, double y) {
        this.x = x;
        this.y = y;
    }
    public Vec2 add(Vec2 other) {
        return new Vec2(this.x + other.x, this.y + other.y);
    }
    // ... there should be other methods applicable to 2D vectors.
}
</code>```

While it makes sense to make small objects immutable (to allow worry-free shared read-only access to getters without having to defensively clone it), I am not sure about making large objects immutable, because of the need to clone every one of its fields when a change needs to be made.

In other words, if the object is large (having many fields), and if its typical usage (semantically) often requires modification, and if there is no need to keep the old object state around (as in memento pattern), then I would think that modifying the object in-place would be a more natural way of programming in Java.

Note that this opinion isn't applicable to other languages, because languages that are designed for functional programming would have other mechanisms for resolving this issue.

Therefore, I would implement Player as follows:

```<code>public class Player
{
    // ... same fields and constructors as yours
    // ... but they will be mutable.

    public void setPosition(Vec2 newPos) {
        // Vec2 being immutable means you do not have to worry
        // about the caller mutating newPos after calling
        // Player.setPosition(Vec2)
        // Meanwhile, Player is mutable.
        this.pos = newPos;
    }
    public void addPosition(Vec2 deltaPos) {
        // The cost we pay for making Vec2 immutable
        // (in terms of lines of code) is minimal. However,
        // same cannot be said of the cost of making Player
        // immutable. My suspicion is that it could greatly
        // increase the lines of code for Player.
        this.pos = this.pos.add(deltaPos);
    }
    public Vec2 getPosition() {
        // Vec2 being immutable means you do not have to worry
        // about the caller mutating the returned Vec2, which
        // would have caused havoc on the Player.pos field
        // if Vec2 isn't immutable.
        return this.pos;
    }
    // ... and others
}
</code>```

Finally, you can consider putting pos and mom together, into a class Motion, and then add it as a field to the Player class.

```<code>// Motion can be mutable or immutable;
// shown below is the mutable implementation.
public class Motion
{
    private Vec2 pos;
    private Vec2 mom;
    public Motion(Vec2 pos, Vec2 mom) { ... }
    public void setPosition(Vec2 newPos) { ... }
    public void addPosition(Vec2 deltaPos) { ... }
    public Vec2 getPosition() { ... }
    public void setMomentum(Vec2 newMom) { ... }
    public void addMomentum(Vec2 deltaMom) { ... }
    public Vec2 getMomentum() { ... }
    // ... add other methods as needed.
}

public class Player {
    private Motion motion;
    // ... constructors and other fields

    // ... Now, we face a dilemma. Motion has a lot of methods,
    // ... but we don't want to copy all those methods here.

    // Option 1 - bite the bullet. Each method will delegate
    // to the method of same name on the Motion instance.

    public void setPosition(Vec2 newPos) { ... }
    public void addPosition(Vec2 deltaPos) { ... }
    public Vec2 getPosition() { ... }
    public void setMomentum(Vec2 newMom) { ... }
    public void addMomentum(Vec2 deltaMom) { ... }
    public Vec2 getMomentum() { ... }

    // Option 2 - getters and setters
    // As discussed above, getters and setters benefit from
    // immutable objects by not having to defensively clone them.
    public Motion getMotion() { return motion; }
    public void setMotion(Motion newMotion) { motion = newMotion; }

    // Option 3
    // Requires Java 8 Lambda.
    // Requires the MotionUpdater interface below.
    // Motion can be mutable or immutable; doesn't care.
    public void changeMotion(MotionUpdater motionUpdater) {
        this.motion = motionUpdater.update(this.motion);
    }
}

// Used by Option 3 above. It can be implemented by a class
// (class, inner class, inline class, etc.), or Java 8 Lambda.
public interface MotionUpdater
{
    Motion update(Motion oldMotion);
}
</code>```

By making this refactoring (extract class), now Motion class only has two fields, and therefore it qualifies for the immutability treatment, i.e. cloning a Motion to modify its values only involves copying two references to immutable Vec2.

To summarize, immutable objects are suitable when:

When it's needed by the application logic (need permanent records of objects; need frozen copies of objects shared by multiple threads, etc), or ...

When objects are very small (2-4 fields) and not part of any inheritance chain. Note that interface implementations is still allowed.

Body:
You can consider allowing your callers to pass in DoubleDuple. (To save some typing, below I will use Vec2 in place of DoubleDuple.)

Example:

public class Vec2 {
    public final double x;
    public final double y;
    public Vec2(double x, double y) {
        this.x = x;
        this.y = y;
    }
    public Vec2 add(Vec2 other) {
        return new Vec2(this.x + other.x, this.y + other.y);
    }
    // ... there should be other methods applicable to 2D vectors.
}

While it makes sense to make small objects immutable (to allow worry-free shared read-only access to getters without having to defensively clone it), I am not sure about making large objects immutable, because of the need to clone every one of its fields when a change needs to be made.

In other words, if the object is large (having many fields), and if its typical usage (semantically) often requires modification, and if there is no need to keep the old object state around (as in memento pattern), then I would think that modifying the object in-place would be a more natural way of programming in Java.

Note that this opinion isn't applicable to other languages, because languages that are designed for functional programming would have other mechanisms for resolving this issue.

Therefore, I would implement Player as follows:

public class Player
{
    // ... same fields and constructors as yours
    // ... but they will be mutable.

    public void setPosition(Vec2 newPos) {
        // Vec2 being immutable means you do not have to worry
        // about the caller mutating newPos after calling
        // Player.setPosition(Vec2)
        // Meanwhile, Player is mutable.
        this.pos = newPos;
    }
    public void addPosition(Vec2 deltaPos) {
        // The cost we pay for making Vec2 immutable
        // (in terms of lines of code) is minimal. However,
        // same cannot be said of the cost of making Player
        // immutable. My suspicion is that it could greatly
        // increase the lines of code for Player.
        this.pos = this.pos.add(deltaPos);
    }
    public Vec2 getPosition() {
        // Vec2 being immutable means you do not have to worry
        // about the caller mutating the returned Vec2, which
        // would have caused havoc on the Player.pos field
        // if Vec2 isn't immutable.
        return this.pos;
    }
    // ... and others
}

Finally, you can consider putting pos and mom together, into a class Motion, and then add it as a field to the Player class.

// Motion can be mutable or immutable;
// shown below is the mutable implementation.
public class Motion
{
    private Vec2 pos;
    private Vec2 mom;
    public Motion(Vec2 pos, Vec2 mom) { ... }
    public void setPosition(Vec2 newPos) { ... }
    public void addPosition(Vec2 deltaPos) { ... }
    public Vec2 getPosition() { ... }
    public void setMomentum(Vec2 newMom) { ... }
    public void addMomentum(Vec2 deltaMom) { ... }
    public Vec2 getMomentum() { ... }
    // ... add other methods as needed.
}

public class Player {
    private Motion motion;
    // ... constructors and other fields

    // ... Now, we face a dilemma. Motion has a lot of methods,
    // ... but we don't want to copy all those methods here.

    // Option 1 - bite the bullet. Each method will delegate
    // to the method of same name on the Motion instance.

    public void setPosition(Vec2 newPos) { ... }
    public void addPosition(Vec2 deltaPos) { ... }
    public Vec2 getPosition() { ... }
    public void setMomentum(Vec2 newMom) { ... }
    public void addMomentum(Vec2 deltaMom) { ... }
    public Vec2 getMomentum() { ... }

    // Option 2 - getters and setters
    // As discussed above, getters and setters benefit from
    // immutable objects by not having to defensively clone them.
    public Motion getMotion() { return motion; }
    public void setMotion(Motion newMotion) { motion = newMotion; }

    // Option 3
    // Requires Java 8 Lambda.
    // Requires the MotionUpdater interface below.
    // Motion can be mutable or immutable; doesn't care.
    public void changeMotion(MotionUpdater motionUpdater) {
        this.motion = motionUpdater.update(this.motion);
    }
}

// Used by Option 3 above. It can be implemented by a class
// (class, inner class, inline class, etc.), or Java 8 Lambda.
public interface MotionUpdater
{
    Motion update(Motion oldMotion);
}

By making this refactoring (extract class), now Motion class only has two fields, and therefore it qualifies for the immutability treatment, i.e. cloning a Motion to modify its values only involves copying two references to immutable Vec2.

To summarize, immutable objects are suitable when:

When it's needed by the application logic (need permanent records of objects; need frozen copies of objects shared by multiple threads, etc), or ...

When objects are very small (2-4 fields) and not part of any inheritance chain. Note that interface implementations is still allowed.


答:
What you could do, is factor out the filtering and breaking into a generator, which can be really handy if that logic is used multiple times, with different processing in the middle.

```<code>def relevant_items(items):
    for item in items:
        # logic to continue or break/return goes here
        yield item

def process_many_items(items):
    for item in relevant_items(items):
        process_item(item)
</code>```

This does however add an extra layer of indirection, which is probably only worth it if the relevant_items method would make sense outside process_many_items.

Title: Factored out loop control in Python

Body:
I have a for loop in python like this:

```<code>for item in items:
    onwards = make_flow_decision(item)
    if onwards == 'break':
        break
    elif onwards == 'continue':
        continue
    elif onwards == 'carry_on':
        process_the_item(item)
</code>```

So idea is that flow control for the loop is factored out because it is really complex.

Is there a better way of doing this than passing strings around and checking for special strings like 'continue', 'break', and 'carry_on'?

Looking for ideas generally that make this a little more elegant.

Body:
What you could do, is factor out the filtering and breaking into a generator, which can be really handy if that logic is used multiple times, with different processing in the middle.

def relevant_items(items):
    for item in items:
        # logic to continue or break/return goes here
        yield item

def process_many_items(items):
    for item in relevant_items(items):
        process_item(item)

This does however add an extra layer of indirection, which is probably only worth it if the relevant_items method would make sense outside process_many_items.


问:
How to design a class for a fixed-length id?
I'm building an app in C# that needs a fixed-length id, which is a string representation of a hex number. E.g. "0fa5" is an example of such an id of length 4. The length would not need to change within the program at runtime, but may be changed in the future or for example in tests.

My question is about how to approach designing such a class. I've come up with two methods so far:

The first would be making a single class, IdType that has a static method SetExpectedLength(int) that should only be called once, otherwise it gives an exception:

```<code>class IdType
{
    public static int ExpectedLength {get; private set;} = 0;
    public string Id {get; private set;} = "";

    public IdType(string id)
    {
        if (IdType.ExpectedLength== 0)
            throw new Exception("SetExpectedLength needs to be called first");

        if (id.Length != IdType.ExpectedLength)
            throw new Exception("Length constraints not satisfied!");

        this.Id = id;
    }

    public static void SetExpectedLength(int length)
    {
        if (IdType.Length == 0)
            IdType.ExpectedLength = length;
        else throw new Exception("SetExpectedLength can only be called once");
    }

    // other operations here...
}
</code>```

The other approach would be making a base abstract class and deriving IdTypes of different lengths from it:

```<code>abstract class IdType
{
    public string Id {get; protected set;}
}

// IdType of length 4
class IdType4 : IdType
{
    public readonly int Length = 4;

    public IdType4(string id)
    {
        if (id.Length != this.Length)
            throw new Exception("Length constraints not satisfied!");

        this.Id = id;
    }
}
</code>```

The second approach seems more clean, however if I need a new length for the ids I would have to make a new class AND replace the instance of the old class everywhere it is used.

What is the best practice in this case? Is there another design pattern that I can use?

答:
The second approach seems more clean, however if I need a new length for the ids I would have to make a new class AND replace the instance of the old class everywhere it is used

You already gave the two striking arguments why this is exact the opposite of beeing clean. So you should avoid specific derivations for specific lengths. However, you wrote

length would not need to change within the program at runtime

so why don't you just make the current length a constant and set it to 4 at one single place in your code? When you later need different lengths, that will be the only place you will have to change, and the need for a method like SetExpectedLength will be removed. If you need to change the expected length once at the program start, then your solution 1 is fine.

The question you have to answer for yourself is if you just expect a future scenario where you have to replace 4 by, for example 5, for all IDs in your program, or a scenario where you have both kind of IDs to deal with simultanously. If the latter is the case, you should rely on having the passed string the correct length 4 or 5


问:
"Do you have any questions for us?" In an interview
You know the prospective company fairly well but are asked "Do you have any questions for us?".  To show interest, what are some of your favorite questions to reply?</p>

答: If you don't have legitimate questions before you walk in, and I mean questions that you honestly came up with yourself, not asked for on the Internet because you don't want to look like a chump, then you haven't done a good enough job researching the company and positions.  </p>


问:
Is that good idea to add ViewModel exactly same as Model
I have following layers in my solution:

App.Domain

App.Service

App.Core (maybe you call this one App.DataLayer)

App.Web

Software design pattern is not my question, I have following Model in Domain

```<code>public class Foo {
    public int Id {get;set;}
    public int Name {get;set;}
    public int Value {get;set;}
}
</code>```

I want to use this model on the view (for example home page) AND I want to use Id, Name & Value, so if I want to create ViewModel, I'll add following:

```<code>public class FooViewModel {
    public int Id {get;set;}
    public int Name {get;set;}
    public int Value {get;set;}
}
</code>```

So, is that good idea? or just use Foo instead of FooViewModel?

答: I would say using FooViewModel in this way violates the DRY principal.  When you need to make a change to Foo you also have to make a change to FooViewModel.  I think you would be better served simply using Foo as the model for your view.  I would consider a view model if you need to display things from Foo and something other things.  For example, say you need to render some information from Foo and also from Bar.


答:
This may look like a violation of the DRY rule initially, but I'd argue that "similar, and even identical, code" isn't necessarily "repetition" if it does something different or is able to change independently. And in the case of view models, the code is defining what the "client" sees, not necessarily the entities and operations the business talks about. So, you're often revealing models to the client or interface that are sort of "incidentally identical." You may change either the business rules and terms or the end user terminology independently of each other.

So, I'd turn the question back on you. If the domain changes, is it acceptable for the "version 1" clients to continue using the old interfaces? Will you ever reveal terms or operations in the interface that aren't part of the "core business rules?" And vice versa?

Those sort of questions in mind, if your view's "function" is strictly to reveal the underlying domain model, yes, this seems like it violates the DRY rule.

Also bear in mind, exposing a view that changes more naturally with model changes can also be accomplished in some languages with member attributes and reflection. (Or with less repetition through other feats of cleverness... But, "cleverness" often fails to justify the repetition it spares you.)

Title: Is that good idea to add ViewModel exactly same as Model

Body:
I have following layers in my solution:

App.Domain

App.Service

App.Core (maybe you call this one App.DataLayer)

App.Web

Software design pattern is not my question, I have following Model in Domain

```<code>public class Foo {
    public int Id {get;set;}
    public int Name {get;set;}
    public int Value {get;set;}
}
</code>```

I want to use this model on the view (for example home page) AND I want to use Id, Name & Value, so if I want to create ViewModel, I'll add following:

```<code>public class FooViewModel {
    public int Id {get;set;}
    public int Name {get;set;}
    public int Value {get;set;}
}
</code>```

So, is that good idea? or just use Foo instead of FooViewModel?


问:
Do you actually write 'clean code'?
I have seen some programmers tweaking their code over and over again not only to make it 'work good', but also to make it 'look good'.

IMO, 'clean code' is actually a compliment indicating your code is elegant, perfectly understandable and maintainable. And the difference comes out when you have to choose between an aesthetically appealing code vs. code that's stressful to look at.

So, how many of you actually write 'clean code'? Is it a good practice? What are the other benefits or drawbacks of this?

答:
Would any of us buy a car if we know that under the hood it is all messy and hard to troubleshoot, maintain or fix and it takes more resources to run than it should?

Why should it be any different for a piece of software?

Just because the end users cannot look under the hood does not mean they will never know it. Sooner or latter it will show up.

Answering the question "Do you actually write 'clean code'?" -- Oh, Yeah.!

Title: Do you actually write 'clean code'?


问:
Design pattern for data structure that contains at most one item of each type
I have a superinterface that several different abstract classes implement: Coverage.

This is for insurance rating. There are several types of different coverage, and those coverages might vary by state. The "type" of coverage is an abstract class, and then the concrete implementations depend on the state where whoever buys it lives (several states generally share one of these concrete implementers).

Basically, we have

public interface Coverage {/*...*/}
public abstract class Pip implements Coverage {/*...*/}
public final class FLPip extends Pip {/*...*/}
```

<p>and then we have :</p>

<pre class="lang-java prettyprint-override"><code>public class quote {
    final List<Coverage> coverages;
    // ...
}
</code>```

I'm thinking it would be good to have it so that adding duplicates of any of the direct implementers of Coverage would throw an error.

I mean, I could do something like this:

abstract class Coverage {/*...*/}

abstract class Pip extends Coverage {/*...*/}

final class FLPip extends Pip {/*...*/}

class Quote {

    // ...

    private final PriorityQueue<Coverage> coverages;
    private final HashSet<Class> coverageTypes;

    // ...

    public void addCoverage(Coverage coverage) {
        Class c = coverage.getClass();
        while(c.getSuperclass() != Coverage.class)
            c = c.getSuperclass();
        if (coverageTypes.contains(c))
            throw new IllegalArgumentException();
        coverageTypes.add(c);
        coverages.add(coverage);
    }

    public void removeCoverage(Coverage coverage) {
        Class c = coverage.getClass();
        while(c.getSuperclass() != Coverage.class)
            c = c.getSuperclass();
        coverageTypes.remove(c);
        coverages.remove(coverage);
    }

    // ...

}
```

but this seems very "hacky" and prone to error / extensibility problems, and like I'm missing something here. Any ideas on a better pattern to use?

答: It sounds like you are looking for set behavior here, and indeed you are storing the "coverage types" in a HashSet. Could you use a Set to store the Coverage objects? If the Coverage implementations themselves implement equals() and hashCode(), then inserting a Coverage in a Set where it is already present would be a no-op.


问:
How do front-end developers test pages when the files they are handed are PHP views?
Someone who has a PHP project invited me to do the front-end work on his site.  I don't know PHP, I've only ever worked with HTML/CSS/JS files.  I cloned the project files from GitHub, and all of the html is generated using controllers and views in the Laravel framework.

So here's the question: as a front-end developer, am I expected to have a MAMP or some other kind of local development server to be able to test PHP files?  I want to be able merge my commits to the master branch of his project, but he understandably doesn't want me to do that without testing.  Or is normal to just send him the my branch commits and let him test and merge them into the master himself?

答:
I agree with Snowman, but as to not leave you empty handed, I will discuss a few possibilities.
If by 'doing the front-end work', you have primarily been tasked with designing the project, then you can design the site according to your normal workflow and simply pass it off to him to integrate it.
If you are responsible for everything client-side, then you will have establish a workflow with your partner, which could be as simple as maintaining a separate fork of the project that both of you have access to. He can then merge it in when he feels that it's ready.


答:
I would have a view model that contained just one property, a Foo instance. That way, you are not violating DRY according to any definition of it, if Foo changes, your view model automatically sees the change, and you leave yourself free of a direct tie of the view model to the model.

If tomorrow there is a need for the view to show something else as well as the Foo, you can just add a new property, and your view model's intent will still be clear, it contains a Foo and something else, you won't have a mixture of properties from Foo with unrelated other properties.

I wouldn't think of your view model as a FooViewModel, I would think of it in terms of what the view is supposed to display. If it just displays one Foo, then the view model contains one property, a Foo.

Not sure if I explained that clearly. If not, let me know and I'll try and reword it when I'm awake!