答:
The biggest point of interfaces in test code is the idea of "seams" used for "test isolation".

To unit test properly, you have to be able to isolate the code under test completely, so the only production code running is that under test. To do this you will have to replace other objects it depends on with fakes.

To do this quickly, mocking frameworks exist and they can quickly build fake objects that implement the interfaces you need, that way your code doesn't depend on the concrete type and a fake can be passed to the code as part of your test call.

Dependency Injection is to do with ensuring production code knows which concrete type to pass to your code.

Title: Steps towards TDD


问:
How to spend less time on debugging?
Following the Pareto rule, a programmer spends only 20% of his time for really useful things.

I spend 80% of my time debugging, fixing small things to get everything working.

Is there a way to spend less time debugging?

答:
I've been given a lot of thought to this problem recently- the simple answer is go read Don Norman's The Design of Everyday Things; Write code like you would design a product.

To paraphrase, good design minimizes error. That means, a few things, most of which you already do (although you may not know exactly why).

-Name functions intuitively. This is formally known as affordance. That is, a button affords to be pressed, a lever affords to be switched, a handle to be pulled, etc.

-Make it hard to write bad code. Check for bad input and throw errors sooner rather than later, use apps hungarian when appropriate, etc. These are called lockout functions.

-Use abstraction where appropriate. Short-term memory is weak.

-Documentation is obviously important, but it is the least effective of making sure code is used properly. In short, well-designed products don't need any documentation. (The most obvious way to see this is looking at bad examples: namely, doors with handles that you're supposed to push.)

-Unit tests. These don't really prevent errors, so much as make it obvious where the bugs are, and provide sanity.

I'm sure I'm missing many more principles, but point is, read up on designing for error.

ContentLicense: CC BY-SA 3.0

Title: How to spend less time on debugging?


问:
Steps towards TDD
I need some advice to take the steps for TDD. How do we think in terms of interfaces for everything when we are writing code? Most of the testing books tell you how to write tests. But I want a book which tells whats the good way to write code in terms of TDD</p>

答:
How do we think in terms of interfaces for everything when we are writing code?

YOU DON'T

Some of the other answers have touched on proper courses of design, but the unstated assumption in the question is subtle and flawed and deserves to be dragged kicking and screaming into the harsh light of day.

YOU WRITE THE TEST FIRST

It's common to read about TDD and think 'yeah that is a great idea' and then not do it. Instead, it's easy to fall back into code-first habits, and then wonder how you're supposed to think of all of the required and convenient interfaces as you're writing the code. Ya don't!

NO, SRSLY, WRITE THE TEST FIRST

Writing the test first forces you to invent the interface before you write the code. So you're not thinking about the code at all, you're thinking about the interface to test the code.

TDD IS NOT UNIT TESTING

TDD tests features, not units. Feel free to add unit testing and code coverage et al if you want, but all TDD requires is that every feature has automated tests. [But look into BDD for even easier test specification]

RED-GREEN-REFACTOR

This process will create the interfaces, get the code working, then refine the interfaces and the code, incrementally.

If you find during the refactoring step that, say, dependency injection (DI) would simplify the design, great, use it. But don't start with DI or any other tactic/technique as a preferential hammer. Let the code be your guide, and let the design evolve naturally, one test at a time.

Title: Steps towards TDD


问:
The most mind-bending programming language?
From a reasonably common programming language, which do you find to be the most mind-bending?

I have been listening to a lot of programming podcasts and taking some time to learn some new languages that are being considered upcoming, and important. I'm not necessarily talking about BrainFuck, but which language would you consider to be one that challenges the common programming paradigms?

For me, I did some functional and logic (for example, Prolog) programming in the 1990s, so I can't say that I find anything special there.

I am far from being an expert in it, but even today the most mind-bending programming language for me is Perl. Not because "Hello World" is hard to implement, but rather there is so much lexical flexibility that some of the hardest solutions can be decomposed so poetically that I have to walk outside away from my terminal to clear my head. I'm not saying I'd likely sell a commercial software implementation, just that there is a distinct reason Perl is so (in)famous. Just look at the basic list of books on it.

So, what is your mind-bending language that promotes your better programming and practices?

答:
CIL

CIL, the Common Intermediate Language that all .NET programs compile to, a kind of an object-oriented assembly. It's interesting for me to try write or read code in it and comparing its constructs to those of C# that I already know. It's a good way to learn more what .NET does behind the scenes. And it can be useful for things like dynamic code generation or rewriting existing compiled code using Mono Cecil.


问:
How many are too many interfaces on a class?
I would probably consider it a code smell or even an anti-pattern to have a class that implements 23 interfaces. If it is indeed an anti-pattern, what would you call it? Or is it simply just not following the Single responsibility principle?</p>

答:
Classes should have exactly the right number of interfaces; no more, no less.

Saying "too many" would be impossible without looking at whether or not all of those interfaces serve a useful purpose in that class.  Declaring that an object implements an interface means that you have to implement its methods if you expect the class to compile.  (I presume the class you're looking at does.)  If everything in the interface is implemented and those implementations do something relative to the innards of the class, it would be hard to say that implementation shouldn't be there.  The only case I can think of where an interface meeting those criteria wouldn't belong there is external:  when nobody uses it.

Some languages allow interfaces to be "subclassed" using a mechanism like Java's extends keyword, and whoever wrote it may not have known that.  It also might be that all 23 are sufficiently far-flung that aggregating them didn't make sense.


问:
Why are brackets required for try-catch?
In various languages (Java at least, think also C#?) you can do things like

```<code>if( condition )
    singleStatement;

while( condition )
    singleStatement;

for( var; condition; increment )
    singleStatement;
</code>```

So when I have just one statement, I don't need to add a new scope with { }. Why can't I do this with try-catch?

```<code>try
    singleStatement;
catch(Exception e)
    singleStatement;
</code>```

Is there something special about try-catch which requires always having a new scope or something? And if so, couldn't the compiler fix that?

答:
In an answer about why brackets are required for some single-statement constructs but not others, Eric Lippert wrote:

There are a number of places where C# requires a braced block of
  statements rather than allowing a "naked" statement. They are:

the body of a method, constructor, destructor, property accessor, event accessor or indexer accessor.

the block of a try, catch, finally, checked, unchecked or unsafe region.

the block of a statement lambda or anonymous method

the block of an if or loop statement if the block directly contains a local variable declaration. (That is, "while (x != 10) int y = 123;"
  is illegal; you've got to brace the declaration.)

In each of these cases it would be possible to come up with an
  unambiguous grammar (or heuristics to disambiguate an ambiguous
  grammar) for the feature where a single unbraced statement is legal.
  But what would the point be? In each of those situations you are
  expecting to see multiple statements; single statements are the rare,
  unlikely case. It seems like it is not realy worth it to make the
  grammar unambiguous for these very unlikely cases.

In other words, it was more expensive for the compiler team to implement it than was justified, for the marginal benefit it would provide.


问:
University teaches DOS-style C++, how to deal with it
I had been programming for many years but wanted a diploma to make myself more employable. Having already been through university once, I didn't choose a full 5 year computer science major but a shorter, more practically-oriented software engineering program.

I expected that it might focus more on concrete skills than on theory, but still had this idea that universities and professors like things to be correct, formal, academic. It's still science, right? Wrong - I was surprised by how sloppy many IT courses were.

In an introductory course on C++ we were tested on clichés like "why are globals bad" and "why are constants good", after just writing 1-2 programs. Random anecdotes without proper context. Handouts contained system(pause/cls), getch and headers like conio.h and iodos.h. One of the tasks was to print "ASCII characters" from 32 to 255, with a screenshot showing such a table printed using the Windows-1252 code page, but without mentioning encoding at all.

Question: when a university/professor seems to be using inferior and/or outdated tools and methods, and the content being taught is borderline incorrect, how do you deal with it constructively and respectfully, if at all?

Some answers point out that you should look beyond the programming since it is just a tool for learning about topics such as data structures and algorithms. I agree with this idea, but in this case there wasn't really any such plan behind the poor style. Most courses would simply teach another "tool" without much background theory or any "big picture". It often felt like they were quickly put together just for the sake of offering such a course.

I stuck with it and finally graduated. Quality remained pretty low throughout (with a few great exceptions), and several other students have been complaining about it. As expected I have learned much more from personal projects and part-time jobs than from school, however the process of finishing school and the label "software student" seem mysteriously useful in themselves!

答:
There's nothing wrong with learning 'DOS-style'.  I'm sure many of the old-timers here started out on DOS, or even with earlier operating sytems, writing line-based programs, and have adjusted just fine.  The computing world changes so quickly that I wouldnt get hung up on specifics such as which library was used for what.

Actually, I suspect the reason we have a world full of programmers who can tell you what dependency injection is, but struggle to answer FizzBuzz, is because a lot of programmers dont spend much time at that very basic level.

It sounds like this is an introduction to programming, so essentually, dont worry about it.  Learn the basics, and you'll do fine.  If you're interested in other platforms, explore them on your own.  Thats the great thing about programming.

OwnerDisplayName: gaidal


答: TeX counts as a language, since it is Turing complete, and I consider it quite mind-bending. A language for typesetting math, (and books on programming)...</p>

Title: The most mind-bending programming language?

Body:
From a reasonably common programming language, which do you find to be the most mind-bending?

I have been listening to a lot of programming podcasts and taking some time to learn some new languages that are being considered upcoming, and important. I'm not necessarily talking about BrainFuck, but which language would you consider to be one that challenges the common programming paradigms?

For me, I did some functional and logic (for example, Prolog) programming in the 1990s, so I can't say that I find anything special there.

I am far from being an expert in it, but even today the most mind-bending programming language for me is Perl. Not because "Hello World" is hard to implement, but rather there is so much lexical flexibility that some of the hardest solutions can be decomposed so poetically that I have to walk outside away from my terminal to clear my head. I'm not saying I'd likely sell a commercial software implementation, just that there is a distinct reason Perl is so (in)famous. Just look at the basic list of books on it.

So, what is your mind-bending language that promotes your better programming and practices?


问:
In .net, why can't values of intrinsic data types (such as DateTime) be null?
First the history:

I found out DateTime data types cannot be null (Yes they can be nullable using the ? nullable declaration).

I was told this is because they are value types and placed on the stack (not on the heap).

I can understand why the stack is quicker and why value types need to (mostly) be placed on the stack, what I do not know is.

Is it true the real limitation of why a value type cannot be null is because the stack cannot handle null values?

If yes - Why? If No what is the real limitation.

I understand in .net we often don't care about exact memory allocation, yet it is important in performance applications to take the stack and heap into consideration, so I'm trying to wrap my head around this.

Thanks in advance for your expertise on a difficult question.

EDIT: Another thing to add are nullable types hence placed on the heap or stack?

答:
The heap and stack are not relevant. It is about Binary representation of values.

In a reference type, a zero binary representation means null, and other binary representations point to memory that contains the binary representation of the value.

In a value type, all binary representations, including zero, directly represent a particular value of the type. Value types cannot be null because there is no reserved binary representation that means null.


问:
How should I handle the publishing of an iPhone app under someone else's name?
I've agreed to build an iPhone app for a client that was referred to me. I'm a full-time software engineer by day, but this is only my 2nd iPhone app and I agreed to do it without upfront funding as it would give me a project to further learn the API as well as increase my portfolio of iPhone apps.

The client suggested as payment, that we split the profits 50/50. Normally I would not think this was fair but in a situation like this, I was ok with it since my family's life does not depend on it.

As we are nearing the end of development on the app, I asked the client if they would prefer their personal name be put on the project, or if they minded that it was my name (since I have the developer license). Naturally, they requested their name. I've not told them all that that entails because I would relinquish management of the app and profit divisions to them.

My question to this community, and pardon if this is not the proper place, is am I going about this the right way?

Should I request a partnership be setup?

Should I insist my developer name goes on it? What would you do?

Additionally, I'm going off of his word that this is a niche product with high demand (its in the medical field) so we will be able to charge a bit more for it.

答:
I had exactly the same situation.

You are the developer and more important -  a 50% partner. there is no reason in the world to register the app on their name.

You can open a new user in iTunes connect with permissions to view financial reports on the app and a different bank account.

request a partnership be setup before you upload the app. Always trust people, and if your partnership is important to you, set up a contract that will prevent you from conflicts when the money will start, (and i wish for you it will), to fly in.

Good luck

OwnerDisplayName: Kyle Hayes

OwnerDisplayName: shani


问:
The dreaded C# programming interview test - any advice?
I have a possible C# dev job lined up but before I can interview, I need to pass a test with the employment agency.

Now even though I am a senior developer with over 10 years of programming experience and more than 3 of these years with c#, I am really not looking forward to this test and I think there is a good chance I will fail it.

In my experience these tests are unpredictable asking you stuff you seldom use in everyday work situations.

I need your best advice on what I should be revising on - a good book or website for example. I have less than 1 week to prepare and it is essential I pass this.

Thanks in advance.

EDIT: To further justify my concerns of writing such tests - Consider the following question:

12) An Event is :

```<code>   a) The result of a users action - correct answer
   b) The esult of a party
   c) code to force users action
</code>```

The correct answer according to the test is A, but since I've been doing SOA development (often when events can be based on system events (not user actions) I'm 100% sure an event doesn't have to be driven by a user action. This was also a C# question (not an ASP.net question). Based on my understanding, I couldn't really spot a correct answer but B seems the best of the lot (if the definition of party is : any entity that can trigger an event.
These kind of questions scare me.

答:
With interview tests, a lot depends on the corporate culture and test creator. If they are intent on asking obscure questions and trying to trip you up, I would move on to another firm or agency that is more interested in high quality individuals that are smart and can get the job done.

That said, as you use c# in your day job, I would concentrate you efforts of problem solving and logic and less on the book learning side of things.

Project Euler is a great place to practice and hone skills that most likely have become a bit rusty.


答:
Printouts full of system(""); is actually a pretty damn good thing! I'm shocked that people don't know anything about these functions nowadays.

system("pause"), and you get rid of all gotchas of getX functions.
system("cls"), and you just saved one page of code.
system("mkdir foo") and you just saved 2 pages of buffer allocations, path splits, _makepath_ss, 256 path limits, ton of error exits and so on.

Moreover the code is so simple a monkey will understand it.

```<code> if(!system("mkdir foo"))
     //booo and exit`
</code>```

The school of polymorphic perversions is what should be banned by law.

P.S.: Moreover, with all due respect, I'm having hard time accepting that people are taught C++ with exceptions and virtual everything as a GOOD THING, because it has more gotchas and landmines than you can imagine, and even Bjarne Stroustrup evangelizes exceptions as something super easy and safe, while in reality they are a nuclear landmine.

See analysis about Misra-C++ and JSF-C++. And Link. I'm too lazy to find all the remaining articles today.

With all that being said, I'm c++ developer and I do enjoy a lot of features and the language as a whole.

Title: University teaches DOS-style C++, how to deal with it

Body:
I had been programming for many years but wanted a diploma to make myself more employable. Having already been through university once, I didn't choose a full 5 year computer science major but a shorter, more practically-oriented software engineering program.

I expected that it might focus more on concrete skills than on theory, but still had this idea that universities and professors like things to be correct, formal, academic. It's still science, right? Wrong - I was surprised by how sloppy many IT courses were.

In an introductory course on C++ we were tested on clichés like "why are globals bad" and "why are constants good", after just writing 1-2 programs. Random anecdotes without proper context. Handouts contained system(pause/cls), getch and headers like conio.h and iodos.h. One of the tasks was to print "ASCII characters" from 32 to 255, with a screenshot showing such a table printed using the Windows-1252 code page, but without mentioning encoding at all.

Question: when a university/professor seems to be using inferior and/or outdated tools and methods, and the content being taught is borderline incorrect, how do you deal with it constructively and respectfully, if at all?

Some answers point out that you should look beyond the programming since it is just a tool for learning about topics such as data structures and algorithms. I agree with this idea, but in this case there wasn't really any such plan behind the poor style. Most courses would simply teach another "tool" without much background theory or any "big picture". It often felt like they were quickly put together just for the sake of offering such a course.

I stuck with it and finally graduated. Quality remained pretty low throughout (with a few great exceptions), and several other students have been complaining about it. As expected I have learned much more from personal projects and part-time jobs than from school, however the process of finishing school and the label "software student" seem mysteriously useful in themselves!

Body:
Printouts full of system(""); is actually a pretty damn good thing! I'm shocked that people don't know anything about these functions nowadays.

system("pause"), and you get rid of all gotchas of getX functions.
system("cls"), and you just saved one page of code.
system("mkdir foo") and you just saved 2 pages of buffer allocations, path splits, _makepath_ss, 256 path limits, ton of error exits and so on.

Moreover the code is so simple a monkey will understand it.

 if(!system("mkdir foo"))
     //booo and exit`

The school of polymorphic perversions is what should be banned by law.

P.S.: Moreover, with all due respect, I'm having hard time accepting that people are taught C++ with exceptions and virtual everything as a GOOD THING, because it has more gotchas and landmines than you can imagine, and even Bjarne Stroustrup evangelizes exceptions as something super easy and safe, while in reality they are a nuclear landmine.

See analysis about Misra-C++ and JSF-C++. And Link. I'm too lazy to find all the remaining articles today.

With all that being said, I'm c++ developer and I do enjoy a lot of features and the language as a whole.

ContentLicense: CC BY-SA 4.0


答:
Computer Science courses will not teach you programming. This is a walk in the park compared to some of the programming I've done on my CS course.

The fundamental problem with this, in my experience, is that there's pretty much nowhere that will teach you programming at an equivalent level, so you have no choice whatsoever.


问:
What are the recommended resources for learning about the Actor model of concurrent systems?
The Actor concurrency model is clearly gaining favor. Is there a good book that presents the patterns and pitfalls of the model? I am thinking about something that would discuss, for instance, the problems of consistency and correctness in the context of hundreds or thousands of independent Actors.

It would be okay if it were associated with a specific language (Erlang, I would imagine, since that seems universally regarded as the proven implementation of Actors), but I am hoping for something more than an introductory chapter or two. I'm actually most interested in Actors as they are implemented in Scala, if there are any such resources available.

答:
There is a good article here: Concurrency in Erlang and Scala.

There are several references at the end, including books, but there is a good example in Scala by Example.


答:
Actors in Scala is dedicated to Actors programming model. It discusses many subjects like Event-based programming, exceptions handling, remote actors and distributed and parallel programming.

You may want to have a look at it.

Title: What are the recommended resources for learning about the Actor model of concurrent systems?

Body:
The Actor concurrency model is clearly gaining favor. Is there a good book that presents the patterns and pitfalls of the model? I am thinking about something that would discuss, for instance, the problems of consistency and correctness in the context of hundreds or thousands of independent Actors.

It would be okay if it were associated with a specific language (Erlang, I would imagine, since that seems universally regarded as the proven implementation of Actors), but I am hoping for something more than an introductory chapter or two. I'm actually most interested in Actors as they are implemented in Scala, if there are any such resources available.


问:
How do I decide whether to take a job I can't add to my portfolio?
I am a programmer, but since I've barely been in the professional market my portfolio is rather bare right now. Still, I started to try and get my website up and running to help a little bit, but what I really need right now is to be able to expand my portfolio.

I have a guy who wants me to do a lot of work for him, and I'm willing to do it for a while at least until I can get better jobs. The real problem, though, is that he does not want me to tell anyone that I have been doing work for him. Naturally, since I'm both trying to earn money and expand my portfolio, this poses a problem.

Part of the reason for doing an app was to prove I can develop one, but if I can't tell anyone I wrote it, then developing the app seems pointless; I may be better off creating my own app and eating the loss in profit because I can get more work out of it, but of course, at the same time, I'm in desperate need of cash. I do have jobs lined up elsewhere, but I'll likely get paid faster through doing this specific job.

What factors should I be looking at when making a decision on whether or not I should take a job for money that I can't talk about?

答:
Have your cake and eat it too.

Build the application... He gets a "real", full functional, branded version... You put an anonymous, "MyCompany.com", version on your portfolio & website.

He gets no mention, no credit, no contact. You get your portfolio and example project to show.

I plan on re-building a website for my work... my demo and practice stuff is currently 100% "MyCompany.com" and 100% not any way linked to the actual work - other than my name on it. Once I get going with it a bit more, I will start moving actual content, company logo, etc over... but it's still my work. I'll remove all links if requested, but it's still MY portfolio.

Caveate:  this all depends on the contract between you two. But I would be very hard pressed to believe that the contract forbids you from listing work experience on your resume, even if it is anonymous.


问:
How can I learn to write idiomatic C++?
I am a computer science student, and as a result, I was taught C++ as a better version of C with classes. I end up trying to reinvent the wheel whenever a solution to a complex problem is needed, only to find sometime after that, some language feature or some standard library routine could potentially have done that for me.

I'm all comfortable with my char* and *(int*)(someVoidPointer) idioms, but recently, after making a (minor) contribution to an open-source project, I feel that is not how one's supposed to think when writing C++ code. It's much different than C is.

Considering that I know objected-oriented programming fairly well, and I am okay with a steep learning curve, what would you suggest for me to get my mind on the C++ track when I'm coding C++?

答:
The book Effective C++ teaches a number of interesting things and will bring you to appreciate the features of C++. There is also Effective STL - I have not read it but I'm sure it would be a great read if you are unfamiliar with the STD.

The important thing to learn is that you should make use of the language and don't reinvent the wheel constantly. You've already learned how to make them, so make it easy on yourself (and others!) and use tools to all their potential.

As a side note, you'll run into a lot of people who demand the STD be used. This is just as bad of mindset as only using char* - sometimes it's not the correct tool and there are many other out there. In the same sense, don't be discouraged from making your own container classes - if you're going to be using char* the best place to do it is safely wrapped inside a class.

Title: How can I learn to write idiomatic C++?


答:
Well, open source projects is a very good start. Don't expect to become a professional programmer based on your university classes, they are not intended for that (as I wrote in my answer here).

You seem to be aware of the syntax, that's good. Now go and read others' code, and contribute your own for peer reviews. You'll learn a lot from reading code and trying understanding it, debugging it and fixing it, and of course - adding to it adhering the coding conventions that are already there.

Professional books are also a very good idea, as mentioned, and browsing through the questions and answers on StackOverflow will teach you a lot (it surely teaches me a lot, and I consider myself a C++ professional).

Title: How can I learn to write idiomatic C++?

Body:
I am a computer science student, and as a result, I was taught C++ as a better version of C with classes. I end up trying to reinvent the wheel whenever a solution to a complex problem is needed, only to find sometime after that, some language feature or some standard library routine could potentially have done that for me.

I'm all comfortable with my char* and *(int*)(someVoidPointer) idioms, but recently, after making a (minor) contribution to an open-source project, I feel that is not how one's supposed to think when writing C++ code. It's much different than C is.

Considering that I know objected-oriented programming fairly well, and I am okay with a steep learning curve, what would you suggest for me to get my mind on the C++ track when I'm coding C++?


答: Reading a lot of good C++ code will probably help. You have to see the code to start getting a feel of it. Then again, most of the C++ code is wrong.</p>

Title: How can I learn to write idiomatic C++?


答:
Based on your comments you know the C++ syntax.

You are not coding in C++ but what is often refereed to as C with classes.

The C++ tag on stackoverflow is a good place to start, it includes a reading list and FAQ.

The only real way to learn is to write code and get experienced user to comment. You can put your code here for review. A good example

I'm all comfortable with my "char*" s

Stop using them, switch to std::string.

and (int)(someVoidPointer) idioms.

Stop using them (apart from to interface with C code). Using the functor concept provides several advantages (included the idea of encapsulating state).

But recently, after making a (minor) contribution to an OSS project, I feel that is not how you think in C++. It's much different, though C has its own place.

Yes. C and C++ have diverged as languages. Though you can use practically the same syntax what is considered good C code is generally not considered good C++ code (or vice verse).

Some friends have suggested Accelerated C++, but again I know what types are, and what classes are and what overloading is.

You have the very basics down.

How can a (mutilated) C++ programmer, who happens to be sound with the OO concepts write idiomatic programs in the language.

With a lot of work :-)

Title: How can I learn to write idiomatic C++?


问:
Tailoring your resume for a career switch within programming
I am currently interested in job prospects outside of my own area of programming. Specifically, I'm a web developer but want to make the transition to desktop application programming. How should I tailor my resume to show that I am capable of this type of software development when I have had no prior experience with it? This question can also be generalized for any other programmer making a leap to a different area (for example a programmer mostly experienced in finance software that wants to go into embedded systems programming).

In short, I've used HTML, CSS, PHP, MySQL and Javascript at work. For a short while I also used ColdFusion. I'm very familiar with OOP concepts and frameworks. In the meantime I've moonlighted for over 3 years on my personal hobby projects in C# and C++.

I know it's bad focusing too much on the tools than their application as a metric to measure your abilities, but for making a transition in my career, would emphasizing knowledge in these tools be good idea to put on your resume? Problem is that a lot of jobs put programming languages as strict job requirements (see here). My resume currently shows 5 years of web development experience. I know general programming concepts well enough, and at this point my experience counts much more than my degree.

I want to know how I can make a potential employer of a software company look at my resume with cautious optimism, and not instantly reject it when it shows I have 5 years web experience with PHP and zero desktop software experience.

答:
List your personal project done in C# and C++. If the code that you've written is something that you're proud of, then stick it up on github or bitbucket. If you're not overly proud of it, refactor it 'til you are and then put it up. The intent is to showcase the fact that you're "not just another PHP hack" ;)

If you have a CS degree, that can help you jump borders.

I'd also try to get involved with a larger OS project in a team-based environment. Fix some bugs.. Try to get onto the actual dev team (as an approved committer). That'll go leaps and bounds from separating you out from the rest of the pack.

Also make sure that you're at least familiar with current desktop technologies (WPF, etc) and design patterns and algos commonly employed by desktop applications.


问:
is there any relationship between a story point in two different projects?
Assume we have two projects and one or more teams (one team doing the projects in serial or two teams doing the projects in parallel). </p>

<p>If Team A decides that a task is 8 story points and Team B decides that a task on their project is also 8 story points, does that say anything about the relationship between the two tasks? Or is there no relationship between the complexity of the two tasks? </p>

答:
There certainly doesn't have to be any correlation unless one team is working both projects in parallel. Then there must be, or the business cannot choose the priority work.

If two teams are working on separate projects in parallel, I see very little benefit to trying to relate the points across them. In fact I work on one of several teams who work in parallel like that, our points systems aren't even close to being the same and we've never run into a problem.

However, if one team is working on two projects in serial, there is one. You can carry the velocity from one project to the next, having learned lessons, rather than starting afresh.


答:
There a couple of different scenarios to my mind here that really do affect my answer:

Team making the estimates share the same baseline - This could be the same team estimating both tasks or different teams that agree on the same baseline of the scale,i.e. how complex is 1 story point is the same in both Team A and Team B.  In this case, the tasks should be close in complexity.  They probably won't match as there could be some variability in how long it takes to get something done.

Teams that are making estimates from an unshared baseline - This would be the more general case where each team has its own idea of how complex is a point and so an 8 story point task may get estimated much higher or lower by another team.

Title: is there any relationship between a story point in two different projects?

Body:
Assume we have two projects and one or more teams (one team doing the projects in serial or two teams doing the projects in parallel). </p>

<p>If Team A decides that a task is 8 story points and Team B decides that a task on their project is also 8 story points, does that say anything about the relationship between the two tasks? Or is there no relationship between the complexity of the two tasks? </p>


问:
Devise and Warden
I've been using Devise for a little while, and I've realized it's built on something else called Warden that handles authentication. What does Devise offer me outside of Warden, because I was considering removing devise and just using Warden.</p>

答:
Warden is the kernel of rack-middleware authentication. Devise is a complete authentication system for rails applications.

Let's take an analogy: Warden is like the Linux kernel, while Devise is like a complete Linux-based operating system such as Debian or Fedora. Or another: Warden is like the engine, while Devise is like the rest of the car.

For more details, please read the respective manuals that you linked to in your question.

Title: Devise and Warden


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
It's OK to figure out murder
  mysteries, but you shouldn't need to
  figure out code. You should be able to read it.

-- Steve McConnell

LastEditorDisplayName: Roger Pate

ContentLicense: CC BY-SA 2.5


问:
high level design of a browser layout engine?
I'm interested in how browser layout engines like gecko, webkit and trident are architected from a high level. what are the key abstractions? how are they layered? what are the inputs/outputs for the different abstractions? Is there a diagram or article that explains this particularly well?

I am sure the implementations vary, but I'm generally curious about how all the pieces fit together. I realize webkit is open source and I can just look at the code, but I wouldn't know where to start.

答:
A few papers that will help you get a better understating of browser architecture:

A Reference Architecture for Web Browsers

Architecture and evolution of the modern web browser

Conceptual Architecture of Firefox

The Security Architecture of the Chromium Browser

Be warned, the links are to pdf files. The last one is not exactly what you are looking for, but it's a good read. As for specific layout engines:

Gecko

Mozilla's Layout Engine, presentation by David Baron

Gecko Overview, in the Mozilla Wiki

Webkit

You can find some basic architectural diagrams in this presentation on Developing hybrid Web GTK+ applications by Alp Toker.

Trident

Internet Explorer Architecture, on MSDN


答:
I think that University should teach abstract concepts of programming languages, algorithms, etc and should not be the place where you learn programming: programming is a very practical activity and you can only learn it by doing.

During my study I learnt the basics of programming in Pascal, then I had one project in C (we had to learn the language by ourselves) and then I had a course on programming language concepts (procedural, object-oriented, functional, logic). It was folklore that on MSDOS you have conio.h or far pointers, which you do not have on a UNIX system. This was the stuff that we students would discuss over a beer, it was not something you discuss during the classes because it was not so important. University teaching focuses on the abstract, general knowledge and avoids going into the details: examples and details are presented just to illustrate the general stuff.

The example you gave about ASCII versus Unicode and the MSDOS conio.h library means just that every programming environment has its particular way of doing and organizing stuff. If you program in C++ on Visual Studio you will have to use other libraries, some of which are not found, e.g., on Linux. So if the course were in Windows 7 / Visual Studio some people might complain that it would be better to do it on Linux / GCC. But, IMO, this is not the point.

So, I think you should try not to get distracted by the details and concentrate on the general concepts that are being covered by the course. For example, that in most programming languages you will need some library to implement console I/O and that, given a programming environment, you will have to solve your problem with the tools you have at hand. Maybe this sounds quite obvious to you and you have the impression you're not really learning something because you already have some previous knowledge (this can happen) but I did not get the impression that you are attending a bad course.


答:
Definitely focus on the technologies you want to be working with and make those the emphasis, rather than languages you have worked with in the past. The biggest mistake I see when I look at resumes is what I call "alphabet soup" - that is, the candidate lists all the languages he or she ever heard of regardless of skill, hoping to impress someone with a shotgun approach.

Instead, put the languages you are applying to work with front and centre, highlight the best parts of your hobby projects, and indicate that you have 5 years of additional web-centric experience. The nice part about programming is you can easily apply the skills you learn in one language to another, so the key thing to my mind would be showing you have interest in the job you are applying for and have been educating yourself outside of work.

Title: Tailoring your resume for a career switch within programming

Body:
I am currently interested in job prospects outside of my own area of programming. Specifically, I'm a web developer but want to make the transition to desktop application programming. How should I tailor my resume to show that I am capable of this type of software development when I have had no prior experience with it? This question can also be generalized for any other programmer making a leap to a different area (for example a programmer mostly experienced in finance software that wants to go into embedded systems programming).

In short, I've used HTML, CSS, PHP, MySQL and Javascript at work. For a short while I also used ColdFusion. I'm very familiar with OOP concepts and frameworks. In the meantime I've moonlighted for over 3 years on my personal hobby projects in C# and C++.

I know it's bad focusing too much on the tools than their application as a metric to measure your abilities, but for making a transition in my career, would emphasizing knowledge in these tools be good idea to put on your resume? Problem is that a lot of jobs put programming languages as strict job requirements (see here). My resume currently shows 5 years of web development experience. I know general programming concepts well enough, and at this point my experience counts much more than my degree.

I want to know how I can make a potential employer of a software company look at my resume with cautious optimism, and not instantly reject it when it shows I have 5 years web experience with PHP and zero desktop software experience.


问:
Most "native"/integrated functional language for Mac OS X development?
If one views the CLR/.NET runtime and associated libraries as the future of windows, then the F# programming language could be seen in that light as the most native functional language.  Meaning that it has support from the OS creator, presumably integrates best with their libraries, etc.

Is there a similar logical choice of language on the Mac OS X platform?  While the most-native language itself is obviously Objective-C, is there a first-among-equals or most obvious functional paradigm language that stands out?

答:
Mac/OS is based on "Objective C". This is basically C with added OO. It pre-dates C++ and is generally considered a cleaner and simpler OO version of C, but, without the backward compatibility. This is definiately the way to go if you want to access the Mac/OS specific features like the "Aqua" GUI.

As Mac/OS is based on BSD unix, the full catalog of Unix languages is available C,C++, perl,Python etc. etc. etc. These all work well but are not so well integrated with the Apple "eye candy".


问:
What did Linus Torvalds mean by his quotation about portability?
In a debate with Andrew Tanenbaum over microkernel vs. monolithic operating system architecture, Linus Torvalds said,

Portability is for people who cannot write new programs.

What did he mean by that?

答:
As someone who's done a lot of Java, and experienced the "write once, debug everywhere" phenomenon on a weekly basis for years, I can fully relate to this.

And Java is probably a mild example. I can't even begin to imagine what people go through who try to while a portable code base in a language/toolkit which wasn't even designed to be portable in and of itself.

Right now at work, we are investigating the idea of writing a lite version of one of our products for mobile devices. I've done some research on how to do a portable version of it for both J2ME and Android - that tries to share as much of the codebase as possible (obviously can't be fully "portable" per se, but it's a similar philosophy). It's a nightmare.

So yeah, sometimes it really is good to be able to think (and do) in terms of using the given tools for the given job. ie Freely developing against one, single, monolithic platform/enviroment. And just writing separate, clean versions for each.


答:
Objective-C, as has been said, is the lingua franca for Mac development, if you want to hook in with Cocoa easily. That said, the best alternative language for Cocoa development is probably MacRuby, which is a Ruby implemented in Obj-C and can directly interface with Cocoa. It's not a functional language, it has some functional constructs. It's sorta developed by Apple (open sourced from Apple).

If you want a functional language for Mac OSX development, I think the best choice is Nu, which is a sorta-Lisp dialect built in Obj-C and can hook directly into Cocoa. It's not like F# (supported by the OS creator), but it is actively developed.

Title: Most "native"/integrated functional language for Mac OS X development?

Body:
If one views the CLR/.NET runtime and associated libraries as the future of windows, then the F# programming language could be seen in that light as the most native functional language.  Meaning that it has support from the OS creator, presumably integrates best with their libraries, etc.

Is there a similar logical choice of language on the Mac OS X platform?  While the most-native language itself is obviously Objective-C, is there a first-among-equals or most obvious functional paradigm language that stands out?


问:
I keep failing hands on part of the interview, suggestions?
So I have a couple of software/site in my portfolio. They make money but not a whole lot.

So I decided to get some job experience, mainly applying to Java/PHP junior development positions.

The problem is that I answer all the technical questions correctly and we schedule to do a coding "test", the final phase of the interview. I can never relax and over think things and end up doing the test very slowly. OR sometimes I just hit a block and find it very difficult to think on my feet.

I don't understand this because other stuff I had written were solving far more complex problems while the "Test" is actually brutally simple such as writing and testing palindrome.

Other times, they will give me a logic test with flows to math operations and again I won't be able to do it in the time they assign.

I know I can write sellable software/websites that can generate small revenues and find ways to solve problems but I have great difficulty with simple coding tests in interviews.

Any suggestions?

答:
This is very common. Most programmers are able to program effectively when they are in their comfort zone.
For example I can only on work on Ubuntu, with vim, if I don't have that workspace I won't feel like programming. I also require, to some extent Google for research.

I am sure you have develop some comfort zone for programming. I would recommend, getting used to the environment where some one is behind you waiting for their code to be completed. Best way to get used to it is to continue going to interview.

You might think it does not have much impact, and it might not. But for some of us out there, programming with music or without, using an IDE or a simple text editor, using a wood chair or sitting on a sofa, a dark room or a bright room... make a huge difference in our development speed.

Note, once you get the job, you can usually create your own comfort zone in the office space they give you.

EDIT: This question reminds me to a sales person, asking how to get comfortable and better at cold calling. The best answer is to keep doing cold calling, and reflect on each call. After a while sales man improve their skills and their comfort. I think programmer are no different when attending interviews, after all the main point is to sell yourself to the interviewer


答: This is just my suggestion, why not try being an entrepreneur. There might be many people who face the similar problem. If you can write websites for small revenue then surely you can earn big from it. </p>

Title: I keep failing hands on part of the interview, suggestions?

Body:
So I have a couple of software/site in my portfolio. They make money but not a whole lot.

So I decided to get some job experience, mainly applying to Java/PHP junior development positions.

The problem is that I answer all the technical questions correctly and we schedule to do a coding "test", the final phase of the interview. I can never relax and over think things and end up doing the test very slowly. OR sometimes I just hit a block and find it very difficult to think on my feet.

I don't understand this because other stuff I had written were solving far more complex problems while the "Test" is actually brutally simple such as writing and testing palindrome.

Other times, they will give me a logic test with flows to math operations and again I won't be able to do it in the time they assign.

I know I can write sellable software/websites that can generate small revenues and find ways to solve problems but I have great difficulty with simple coding tests in interviews.

Any suggestions?


答: Keep attending interviews. You'll eventually find a place that will ask questions more amenable to your strengths. You'll also get better and more comfortable with interviewing, which can only help. Look at it as a game, because that's really what it is. Keep playing, and eventually you'll win.</p>


问:
Making big changes incrementally
Currently working on a complete front-end and back-end overhaul of our webapp. We did this because a lot of changes needed to be made to the database schema as well as the user experience.

Now we are almost done with the overhaul and I'm thinking if we could have taken a more incremental approach? We started a new codeline for this overhaul and now we have to figure out a good data migration plan to make sure the old data is transferred over to the new schema properly.

We made the decision to do a separate codeline because we thought that if we did incremental changes to the schema, there would be more downtime to the site. A separate development cycle for it would reduce that downtime to the final day when we do the data migration. And of course that carries more risk.

What are some good approaches to this problem for the future if we ever need to do another major overhaul? Incremental approach would be desirable.

答:
Small is always better than big!

An incremental approach, dividing the upgrade into several small releases is usually the best approach, though its a hard sell to management.

It sound like splitting your project up into:--

presentation code updates to enable the fancy stuff, plus an implementation of some of the simpler user experience enhancements (i.e those that don't depend on schema changes).

schema upgrade enabling release. i.e. upgrade the schem, plus the technical changes in the programs to handle the new schem, but only business logic changes absolutly required by the new schema.

changes to your business logic to take full advantage of the new schema.

finally, the full enhanced user experience.

I find separating releases into technical/enabling releases, followed by a separate release for business logic changes, keeps each release controlled, focused and as small as possible. Resulting in quicker development and fewer bugs.

Title: Making big changes incrementally


答:
You are right to fear the complete rewrite, nothing is ever scarier in the world of refactoring. There are many strategies for breaking down the rewrite into digestible chunks, and it depends on what's wrong with the code base to begin with. Was it spaghetti? Was it inherently unstable? Or, based on deprecated services?

Without understanding more about your code base, I can only offer something generic and hopefully it helps in some way. Some things to try, maybe, assuming the problem is poorly structured spaghetti.

Start decoupling everything. Try to eradicate state and dependencies, piece by piece. This can almost always be done incrementally. Also, break apart the monster functions and modules.

As things get decoupled, sic the unit tests on them. You need stability throughout the refactor, and that should be your baseline.

You now have lots of little, independent things. Look at the patterns and start to organize and recombine.

As you do this, it may help to adopt an agile dev approach.

At the end of all this, you may not have the Ivory Tower that proponents of the rewrite might hope for, but you'll have tangible improvements that will likely eliminate the need for a complete rewrite.

Title: Making big changes incrementally

Body:
Currently working on a complete front-end and back-end overhaul of our webapp. We did this because a lot of changes needed to be made to the database schema as well as the user experience.

Now we are almost done with the overhaul and I'm thinking if we could have taken a more incremental approach? We started a new codeline for this overhaul and now we have to figure out a good data migration plan to make sure the old data is transferred over to the new schema properly.

We made the decision to do a separate codeline because we thought that if we did incremental changes to the schema, there would be more downtime to the site. A separate development cycle for it would reduce that downtime to the final day when we do the data migration. And of course that carries more risk.

What are some good approaches to this problem for the future if we ever need to do another major overhaul? Incremental approach would be desirable.


问:
Is it ok to write a quick software programme and then refactor it?
In my team, people have tendency to develop a POC (which is very close to actual deliverable in terms of features) which takes good amount of time to be created. And then spend a significant time to refactor the POC so that it matches the design principles using all required design patterns, sometimes naming etc...

One advantage everyone in team says is you have the confidence to meet deadlines one so called POC is ready, then you can spend time on design.

Just curious about, is it really good to refactor code after developing it in quick mode or we should spend time initially to work on architecture and design of the code?

EDIT:
After reading the answers I realized that, as most of guys said, what I am talking of is more than POC and as rightly put by Carl is an "evolutionary prototype." This is definitely not a throwaway code. Intention of the output is always to go to production.

答:
If you're spending so much time refactoring your (nearly feature-complete) POC to meet coding standards, it's time to consider whether those coding standards are actually helping. Are those naming standards actually helping you write better-quality code faster, or are they just adding needless busywork?

Of course, you say "very close to actual deliverable in terms of features" - the next question is, of course, how much time you spend squashing bugs. If the POC is actually mostly bug-free and nearly feature-complete, and with just a bit more work (if you skipped all the coding standards crap) it would meet all the client's requirements, then it's not a POC so much as an alpha or beta build.

In any case, whether this approach will be successful can depend on your team. If it's working for you - great! But if you're spending a lot of time on "refactoring" that doesn't actually help, it may be worth reconsidering whether that refactoring is actually useful.

This isn't to say that refactoring is necessarily bad. It could be that your "quick mode" code is an unmaintainable mess and the refactoring really is needed, in which case perhaps this "quick mode" isn't such a good idea. This, again, depends on whether your team is good at making more-or-less maintainable code the first time around. But, from your description, it could just as easily be a big waste of time.

OwnerDisplayName: Maheep

OwnerDisplayName: bdonlan


问:
Can freelancers ask their client to sponsor an iPad for project needs?
I do freelance web projects for a client.  The client has been asking me to buy an iPad for testing purposes. Should I ask him to get me an iPad ?

I otherwise don't have any need for the iPad. Is it ethical to ask for sponsorship when you are getting paid for the projects ? Should I try it out ?

答:
NO. You do NOT ask the customer to give you a free iPad. You either buy one yourself or ask the customer (if they have a requirement for the product to run on an iPad) to supply one for the duration of the project (which remains their property, and you should treat it as such and hand it back when the project is done).

If in fact you bid on the contract knowing it should involve an iPad I'd expect you as the contractor to have one already. It's not as if we're talking some highly obscure piece of kit here that has no application outside the scope of the contract or is so expensive you can't expect a private person or small supplier to have one.


问:
Does anyone else have a refactoring problem?
It seems like after I've written a significant amount of code I get this anxious feeling like I haven't done it in the best possible way, and I end up continuously refactoring and spending way too much time on the project, or never getting it done sometimes. Does this ever happen to anyone else, and how do you deal with this?</p>

答: It does seem like you can always refactor, doesn't it? I try to limit refactoring only when trying to solve other issues. For example, refactor when you have a performance problem and refactoring with help you solve it - refactor when you need to add new functionality and refactoring will help you solve it</p>


答:
If I was allowed to I would personally prefer to work in the fashion you have descibed: Get something working first and then designe a nice class or whatever as per design prinicples. After all what good is a pretty design if you cant get it to work.

In fact Bruce Eckel also recommends "buid one  to throw" as an effective programming technique. This is very useful when you are doing something that is technically complicated or very unfammiliar( a new library perhaps). Doing a POc gives you a very good idea about how your design should be.

If you already have a good grasp on your project's requirements and your design works fine say 70-80% of the time without refactoring then I think you are better off without a PoC. But if you spend more than 40% of your time refactoring your design to get it to work you are better off doing a PoC first .

As you have mentioned unit tests let me add : if youa are required to do TDD you need to get as much of a "right design" before you begin coding. If you do a POC first you can save yourself the trouble by not doing TDD along with the POC. First do a POC , then design your classes, next write the test cases. This way you dont have to write two sets of test cases.

Title: Is it ok to write a quick software programme and then refactor it?

Body:
In my team, people have tendency to develop a POC (which is very close to actual deliverable in terms of features) which takes good amount of time to be created. And then spend a significant time to refactor the POC so that it matches the design principles using all required design patterns, sometimes naming etc...

One advantage everyone in team says is you have the confidence to meet deadlines one so called POC is ready, then you can spend time on design.

Just curious about, is it really good to refactor code after developing it in quick mode or we should spend time initially to work on architecture and design of the code?

EDIT:
After reading the answers I realized that, as most of guys said, what I am talking of is more than POC and as rightly put by Carl is an "evolutionary prototype." This is definitely not a throwaway code. Intention of the output is always to go to production.


问:
Best practice for populating a dynamic popup menu?
I'm creating a dynamic popup menu whose contents depends on the state of what the user clicked on. Is it considered a better practice to create a template menu in html and modify which options are displayed in javascript, or to create everything in javascript on the fly? I'm using jQuery.

code example:

HTML:

```<code><div id="menuTemplate" class="menu">
  <div class="opt1">Option 1</div>
  <div class="opt2">Option 2</div>
</div>
...
</code>```

Javascript:

```<code>showMenu = function (state) {
  var menu = $("#menuTemplate").clone(true).removeAttr("id");
  if (state) {
    menu.find(".opt1").show();
    menu.find(".opt2").hide();
  }
  // the rest of the function
}
</code>```

or

Javascript:

```<code>showMenu = function (state) {
  var menu = $("<div class='menu'></div>");
  if (state) {
    menu.append($("<div class='opt1'>Option 1</div>"));
  } else {
    menu.append($("<div class='opt2'>Option 2>/div>"));
  }
  // the rest of the function
}
</code>```

答:
It depends upon the requirement: if the options are going to be limited then I would suggest going with show/hide functionality, but if in the future these values require an asynchronous request then refactoring it will be painful.

Moreover, in the second code sample, please don't append entire html in menu: create a div element and add css class to it. This way it is more readable and maintainable. for eg

```<code>newdiv = document.createElement('div');
newdiv.className = 'cssClass';
menu.append(newdiv);
</code>```

Body:
It depends upon the requirement: if the options are going to be limited then I would suggest going with show/hide functionality, but if in the future these values require an asynchronous request then refactoring it will be painful.

Moreover, in the second code sample, please don't append entire html in menu: create a div element and add css class to it. This way it is more readable and maintainable. for eg

newdiv = document.createElement('div');
newdiv.className = 'cssClass';
menu.append(newdiv);


答:
I personally prefer getting the main deliverable right from scratch. I always have one or two throwaway projects alongside to quickly test or distillate some ideas, but even working in this way, refactoring is inevitable.

Usually I wait with writing unit tests until I'm perfectly satisfied with a class. I've tried writing the tests before the implementation but my development time quadrupled keeping all the mockups up to date due to my urge to have everything compilable at all times (maybe I should just learn to relax, but I'm kind of rusty this way).

On the other hand, probably I'm too much of a perfectionist. Commercially the quick POC and patch might be a more economical choice.


答:
My approach - either write it "almost right" the first time or rewrite from scratch using POC as a project/draft, not the final piece. Sometimes I extract large chunks of code from the POC porting them into the final product - the ones I deem them especially successful and well written. But bulk of the code is rewritten from scratch.

Of course the POC will sometimes work as a stub for the final thing for a few days (or months... depending how critical the piece is as the deadline on more important stuff is looming), before it is replaced by the real thing. But that's not a good practice.


问:
Organising MVC App with virtual model using external API
I am creating a rails app with following constraints

It has no database

It uses a web API to store and retrieve the data

The connection to the web API is via a custom gem.

The Gem has a basic functionality to make a web API call based on the parameters given.

I have 2-3 different kinds of object that I can think of  ( or may be more precisely virtual model )

How should the structure of my program be ?

Should I incorporate all the method calls within the gem ?

Should I create models and put the api related calls  in there (then through the gem's basic method)

Should I just ignore the model and put everything in the controller . ?

The second method seems most appropriate , but then all the methods from model would be static and I would be calling all methods in essence without any objects.

答:
I'm not familiar with Rails, but theoretically, in order to retain it strictly MVC, you should encapsulate the gem in your model (your second method).

If your Gem already defines all the data structures needed, you could decide to call the Gem your 'model' even though it might reside in an unconventional location (again, I'm not familiar with Rails so maybe you can put a gem wherever you want?). You'll surely need to pass data to the Gem's methods and get data back, which implicitly makes those parameters and return value's your model.

There's nothing wrong with having a static model. In fact functional enthusiasts would love it that way.


答:
It is nice to get time to refactor the POC.

In many environments, if the POC is good enough, it gets deployed anyway, you don't get time to clean it up, and the problems don't emerge until you end up having to do some maintenance, or add a few features, in a year or two's time.

If this approach works in your environment, then I wouldn't suggest you stop using it. But if you try to port it to a different environment, be careful.

To me, a "Proof Of Concept" would be just enough code to prove to myself that I could make something work. No bells, no whistles, no error handling, no features that I was comfortable with unless they were absolutely critical to proving whatever the core thing was. The worse it looked, the better, on the grounds that it would be least likely to get pushed into production.

Then I'd start from scratch with my normal development methodology, using the POC (or spike) as a template when the appropriate time came. Perhaps whatever concept I'd just proven would be the first feature I built in this second version, but more likely I'd need to do some other stuff first to prepare the ground.


答:
I think this is ok depending on your situation. Writing a POC to get from A to B as quickly as possible, and then fleshing it out, and ironing out the creases is certainly a strategy that can worked and has worked for me in the past. The refactoring is not an afterthought though, you must refactor aggressively, do lots of it, and allocate significant project time to it.

I think your decision depends on the quality of your POC. If it's high quality (it may be 'rustic', but that doesn't stop it being high quality) you shouldn't start again from scratch at all. It wastes time - I've seen this - and if you get the new design wrong it's frustrating and you'll be saying "if only we'd stuck with..." then people will have to work hard to refactor anyway.
If it's low quality, then you are more likely to have got the approach wrong in some way and you'll hit an show-stopper at some point in the future. I've discovered the opinion of the quality of your codebase may vary amongst your team members. You need to work out who is right. You're looking for good high-level design, that will accommodate future concerns, and you can ignore most of the smaller scale badly written/non-idiomatic/loose stuff to an extent.

Whatever design you have, try to look ahead with it, identify the biggest required changes and make them now. Once you're further down the development road it'll be harder to change the overall structure.


问:
Approach to a programming task
All,

Given a problem statement, when I start of with the analysis and design, I tend to think too much about the various functionalities associated with the task (sometimes not even mentioned in the task). My point is, I get diverted from the main task at hand thinking about various scenarios that I should consider while coding and this tends to demotivate me because I am often very confused in the end. What approach should I take in this case since thinking a lot on all possible scenarios comes naturally and I only try hard not to.

答:
What you appear to be describing is a problem in defining your scope. My advise is as follows:

By all means think about all the different possible tasks, you may well come up with some useful additional features. Write headings for all the different ideas you've had, but nothing more than headings.

Review and prioritise the headings. Some at the bottom can probably be lost, concentrate on the functionality requested.

Expand the top headings into their sub-tasks until you have tasks that are only a few hours or days long each.

Review these with the person requesting the change (possibly before expanding the detail if the person is non-technical).

Begin work on the top task and continue downwards, producing prototypes and demonstrations (if not releases) at regular intervals for review with the requester.

Add to and review your task list between task completions; more tasks will always result from user reviews, and some may become obsolete.

Title: Approach to a programming task


答:
you have the confidence to meet deadlines one so called POC is ready, then you can spend time on design.

The correct question to ask yourself as a company is not if you have the confidence to meet deadlines when the POC is ready, but if you have the discipline to refactor and write unit tests before going to production.

Especially in an environment that is heavily weighted towards sales concerns, the temptation is just too great for the company to hand off the prototype as the product with minor modifications, typically without regard to the maintainability and the technical debt that will accrue later.  Four months later when the customer comes back and says, "It turns out that we do need the program to track ad-hoc visits to facilities.  How long would that take?" then that situation could force the need for a rewrite of the prototype anyway.  A project that should have taken a few months is now almost an 8 month project and the customer is angry about time and cost over what seems to them is a fairly simple feature.

It sounds as if you work for a good company that understands the dangers of NOT refactoring your POC before using it as the product.


答:
I'm going to say no.  Speaking from experience, 9/10 times if you write a program quick and deploy it, you won't be able to make the time to refactor it as management/client sees they got results fast so you will be inundated with more work that is expected to be done just as quick.  You'll end up with an awful program that keeps getting larger and larger.

Best to take the extra time and do things right.  It's slower at the start but faster down the road.  Short-term vs. long-term thinking - long-term should always win unless you aren't serious about what it is you're doing.


问:
Is using xml + xsl to create a weekly html email a good or bad idea?
The guy who is in charge of our html emails is leaving and I have been asked to take over. We are an online retailer and send out an email once a week. An email will consist of a main image, a bit of an opening paragraph and then rows of product offers.

As everyone knows html emails are painful to work with due to the archaic html and css you need to deal with. When something needs changing last minute it's a real pain to wade through the spaghetti of td's to get to the link that needs it's url and tracking code changing and the opportunities to make a mistake are plentiful.

So I've decided to create an xml file consisting of all the data that needs to go in the email. For example, the products would be recorded like this:

```<code><products>
    <product id="1">
        <title>My Product</title>
        <image width="160px" height="160px">
            <alt>My Product</alt>
            <url>http://somedomain.com/emails/image1.jpg</url>
        </image>
        <link>
            <term>my_term_for_google_analytics</term>
            <url>http://somedomain.com/products/1</url>
        </link>
    </product>
    <product id="2">
        <title>My Second Product</title>
             ... etc ...
    </product>
</products>
</code>```

I could then use an xslt template  to create the email. The advantage of this is that when a product goes out of stock the morning the email is due to go out I can just change a bit of text in the xml file, generate the html and we're good to go again. I can also use the same xml to create a microsite for the email. The trouble is I've had a good ol' Google about this and I can't find anyone else who has really tried this. So I'm either a visionary genius or an idiot. It usually turns out I'm an idiot so has anyone else had any experience of creating html emails from xml using xslt or can anyone see any major pitfalls with this approach. Is it a good idea?

Disclaimer - I don't really think I'm a potential visionary genius.

答: Transforming XML into HTML is fairly standard practice. So yes it’s a good idea but no you’re not a genius. :) </p>


答:
Start small. I would suggest an incremental approach with the following approach:

Pick a part of the system, preferrably the one that is in most need of refactoring.

Get this part of the system under test if possible. If not, do it after depencies have been broken.

Start refactoring this part of the system by breaking dependencies.

Verify that your changes work as intended through the tests.

Repeat.

Michael Feathers has a great book about this called Working Effectively With Legacy Code. I recommend it. For further assistance when it comes to breaking dependencies in code, try looking into the Mikado Method.

Title: Making big changes incrementally


答:
You have already identified what is your problem - solving problems under pressure (e.i. when somebody is watching you). Is it because you lack confidence or you don't have enough experience or you crack under pressure?

Going to a lot of interviews to get some experience and practice can be a good idea but also can produce counter-effects. Constant failures in interviews can shake your confidence even more, so be careful.

I would suggest you to try peer programming so you can get comfortable to solve problems when somebody is watching you. Also, try to figure out what's stopping you from being effective under pressure (is it stress from the actual testing itself, stress from working under close supervision, stress from working under a specific time limit etc.).


问:
Creating an a project-site for an open source project
So I have an open source project that I would like to promote and I want to create a project-site for it where I will host the documentation, etc. (preferably something that integrates with github for handling downloads, issues, etc). The project-site should be just like a typical.

Is there anything out-of-the-box for this or do I have to code it from scratch?

Thank you.

答:
I don't know if you've already coded a solution for this, but you may want to look at fossil. It allows you to have an integrated project page, wiki, bug tracking, and repository all in one. It'll even do zip files of the project for you, so people don't need fossil to download the source.

It will require you to have somewhere to host it though.


问:
How does a movie theater seat booking system prevent multiple users from reserving the same seats?
In the movie theatre I go to they have ticket kiosks that allow you to select the seats you want; they also have a website that does the same (the website also has a countdown timer of like 30 secs in which you must choose a seat).

While I understand things such as database transactions and other techniques for handling multiple simultaneous users, I just can't get my head around how multiple people can be allowed to select a seat at the same time; is it as simple as the first one to press BUY gets the seats and the other person will get an error message, or am I missing something?

答:
You can avoid the race condition if you delay allocating specific seats.

Collect seating preferences from customer (number of seats, price, area of theatre, adjacent seats mandatory, etc...)

Save the requested seating preferences in a queue

One-by-one seating requests are pulled from queue, seats allocated according to preference and the booking completed if seats found.

If booking completed, notify customers and mail tickets; otherwise, notify customer that no tickets matched preferences.


答: I would just use one of the simple "out of the box" website solutions like Wordpress. They are trivial to set up, can look pretty sleek, and will allow you to spend as much time working on your actual project as possible. Combine that with something like Github or Sourceforge and you end up with a fairly robust solution.</p>

Title: Creating an a project-site for an open source project

Body:
So I have an open source project that I would like to promote and I want to create a project-site for it where I will host the documentation, etc. (preferably something that integrates with github for handling downloads, issues, etc). The project-site should be just like a typical.

Is there anything out-of-the-box for this or do I have to code it from scratch?

Thank you.


答: We use XSLT templates to transform XML into HTML for reports all the time.  It works well, but like anything else you can take it too far.  Keep it simple or you end up with some pretty out of hand XSLT that nobody can understand.</p>

Title: Is using xml + xsl to create a weekly html email a good or bad idea?

Body:
The guy who is in charge of our html emails is leaving and I have been asked to take over. We are an online retailer and send out an email once a week. An email will consist of a main image, a bit of an opening paragraph and then rows of product offers.

As everyone knows html emails are painful to work with due to the archaic html and css you need to deal with. When something needs changing last minute it's a real pain to wade through the spaghetti of td's to get to the link that needs it's url and tracking code changing and the opportunities to make a mistake are plentiful.

So I've decided to create an xml file consisting of all the data that needs to go in the email. For example, the products would be recorded like this:

```<code><products>
    <product id="1">
        <title>My Product</title>
        <image width="160px" height="160px">
            <alt>My Product</alt>
            <url>http://somedomain.com/emails/image1.jpg</url>
        </image>
        <link>
            <term>my_term_for_google_analytics</term>
            <url>http://somedomain.com/products/1</url>
        </link>
    </product>
    <product id="2">
        <title>My Second Product</title>
             ... etc ...
    </product>
</products>
</code>```

I could then use an xslt template  to create the email. The advantage of this is that when a product goes out of stock the morning the email is due to go out I can just change a bit of text in the xml file, generate the html and we're good to go again. I can also use the same xml to create a microsite for the email. The trouble is I've had a good ol' Google about this and I can't find anyone else who has really tried this. So I'm either a visionary genius or an idiot. It usually turns out I'm an idiot so has anyone else had any experience of creating html emails from xml using xslt or can anyone see any major pitfalls with this approach. Is it a good idea?

Disclaimer - I don't really think I'm a potential visionary genius.


答:
Having an intermediate XML format will serve you right. Firstly, because with XSLT you will be able to cleanly recreate an HTML email, and secondly, because you will have your clean XML content ready if any other application needs it. Also, XSLT is just great for that job.

Just one remark about your "microsite".

Remember that just about every email application now blocks JavaScript (and ActiveX for that matter) from working, as a security measure. So No Javascript. I've tried doing it until I finally googled it up and realized this would never work.

Use inline CSS, and by the way remember that some of your clients may have older versions of Internet Explorer (used by Outlook to render them), and as such, your email may not look like it should be with modern browsers. I do have Outlook 2003 for example.

There are other things to know of which you can see here, but the most important one to me is to make sure to propose a plain text alternative version. Since you will be using XSLT, you could make a good choice by writing another script for transforming into plain text.


问:
How can I learn to write idiomatic C++?
I am a computer science student, and as a result, I was taught C++ as a better version of C with classes. I end up trying to reinvent the wheel whenever a solution to a complex problem is needed, only to find sometime after that, some language feature or some standard library routine could potentially have done that for me.

I'm all comfortable with my char* and *(int*)(someVoidPointer) idioms, but recently, after making a (minor) contribution to an open-source project, I feel that is not how one's supposed to think when writing C++ code. It's much different than C is.

Considering that I know objected-oriented programming fairly well, and I am okay with a steep learning curve, what would you suggest for me to get my mind on the C++ track when I'm coding C++?

答:
I read Accelerated C++ by Andrew Koenig and Barbara Moo in order to help me teaching C++, after having worked with C++ for nearly a decade. (In fact, I was starting to tinker with template meta-programming at that time.) I still found it to be a revelation, even though I don't think it taught me any new fact about the language.1

What it taught me, though, was to look at, and use, C++ as a high-level language. To not to tinker with raw pointers and delete and to use the standard library wherever possible.

I have the feeling that this is exactly what you are after.

1 Not that there wasn't anything left to teach me back then (there is plenty even now, a decade later), but there's only so much knowledge you can squeeze into a 250 pages introductory book.

Title: How can I learn to write idiomatic C++?


答: It's a good idea to have an intermediate XML format, but using XSLT to generate HTML files is so 1999.. it might be a better option to use a templating engine such as Velocity, Spark View Engine, Razor, StringTemplate etc depending on what technology you're using. I'm sure you'll find them much easier to work with than the monstrous beast that is XSLT...</p>


问:
Using "catching exceptions" to improve readability, Good or Bad?
In the section When to Use Exception in The Pragmatic Programmer, the book writes that instead of:

```<code>retcode = OK;
     if (socket.read(name) != OK) {
      retcode = BAD_READ;
    }
     else {
      processName(name);
       if (socket.read(address) != OK) {
        retcode = BAD_READ;
      }
       else {
        processAddress(address);
         if (socket.read(telNo) != OK) {
          retcode = BAD_READ;
        }
         else {
          //  etc, etc...
        }
      }
    }
     return retcode;
</code>```

, they prefer:

```<code> retcode = OK;
     try {
      socket.read(name);
      process(name);
      socket.read(address);
      processAddress(address);
      socket.read(telNo);
      //  etc, etc...
    }
     catch (IOException e) {
      retcode = BAD_READ;
      Logger.log( "Error reading individual: " + e.getMessage());
    }
     return retcode;
</code>```

simply because it looks neater. I'm all for neater code, however isn't unnecessary catching of Exceptions a performance bottleneck?

I can understand that we should give up minuscule optimization for neater code (at least 99% of the times), however from what I know, catching exceptions belong to the class of code which have a noticeable delay in runtime. Hence I was wondering what's the justification that the second piece of code is preferred over the first code?

Or rather, which code would you prefer?

答:
Exceptions are typically only slower if they actually thrown. Usually, the exceptions in situations like this are rare so its not something you should worry about. You should only really worry about the performance of exceptions if they are happening all the time and thus are a significant factor.

The second code is better because its much easier to follow the logic. The error handling is nicely localised. The only objection is that if you are using exceptions, then use exceptions. Don't catch the exceptions and then return an error code.

OwnerDisplayName: Pacerier


答:
It sounds like you choke under pressure. Since you have to do the timed examples as part of the interview process, you'll have to learn how to get past this. This is all about managing fear, not about programming skill.

One option would be to practice writing sample problems and time your self. Once you know that you can do them in under ten minutes, you may fear being timed less.

Another option would be to come up with a technique to calm your fear, and use it to un-choke yourself. Learning a meditation technique might help you. Or memorize the litany against fear (from Dune.) Learn some kind of trick to take down your fear response.


答:
Well, as they also say, exceptions should handle the exceptional cases, and since this is an exceptional case (i.e. something that happens few and far in between) I'd say that this applies here as well.

Also, I'd advise against micro-optimizing things such as this. Focus more on the readability of the code, since you'll be spending far more time reading code than writing new code.

To really make sure that this is a performance bottleneck, do some profiling, and analyze and focus on the more critical tasks based on that analysis.

Title: Using "catching exceptions" to improve readability, Good or Bad?

Body:
In the section When to Use Exception in The Pragmatic Programmer, the book writes that instead of:

```<code>retcode = OK;
     if (socket.read(name) != OK) {
      retcode = BAD_READ;
    }
     else {
      processName(name);
       if (socket.read(address) != OK) {
        retcode = BAD_READ;
      }
       else {
        processAddress(address);
         if (socket.read(telNo) != OK) {
          retcode = BAD_READ;
        }
         else {
          //  etc, etc...
        }
      }
    }
     return retcode;
</code>```

, they prefer:

```<code> retcode = OK;
     try {
      socket.read(name);
      process(name);
      socket.read(address);
      processAddress(address);
      socket.read(telNo);
      //  etc, etc...
    }
     catch (IOException e) {
      retcode = BAD_READ;
      Logger.log( "Error reading individual: " + e.getMessage());
    }
     return retcode;
</code>```

simply because it looks neater. I'm all for neater code, however isn't unnecessary catching of Exceptions a performance bottleneck?

I can understand that we should give up minuscule optimization for neater code (at least 99% of the times), however from what I know, catching exceptions belong to the class of code which have a noticeable delay in runtime. Hence I was wondering what's the justification that the second piece of code is preferred over the first code?

Or rather, which code would you prefer?


问:
Language-agnostic libs every programmer should consider learning?
Assuming the language provides it, what are some things to do or libraries to use that every programmer should know?

My list would be

Regular Expressions

Named Pipes

standard IO (std in/out/error)

Executing outside executables (like imagemagik and your own scripts)

How to grab an HTTP page as a string (mostly for updates and grabbing configs from servers)

I have a similar questions about tools. Also I am looking for specific answers. I don't want answers that can be done in different ways (such as learn how to synchronize threads).

I know how to do the above in 3+ languages. There always seems to be things programmers don't know how to do which can make their lives easier. For a long time I didn't know what regular expression was (although I did hear of it) and I was surprised how many people who tried to make a toolchain or complex app and did not know how to (or that you could) get the stdout from an exe they launched (they checked for errors in a very weird way or just didn't and hope it produce the expected results).

What do you think is useful, not well known and should be something every senior (or starting out) programmer should know?

答: Handling date calculations, date formating and localization issues dealing with dates.</p>


答:
I'd agree with the answers you've already gotten saying that this is an exceptional case, so it's reasonably to use exception handling.

Addressing your performance concerns more directly, I think you need to keep a sense of scale about things. Throwing/catching an exception under these circumstances is likely to take one the order of a microsecond. As flow control goes, that's slow -- many times slower than normal if statements, no question about that.

At the same time, keep in mind that what you're doing here is reading data from a network. At 10 megabits per second (slow for a local network, but pretty fast as Internet connections go), that's on the same order as the time to read one byte of information.

Of course, that overhead is only incurred when you actually throw the exception as well -- when it's not thrown, there's usually little or no overhead at all (at least from what I've seen, the most significant overhead isn't from the exception handling itself, as from adding more potential flows of control, making the code harder for the compiler to optimize quite as well).

In this case, when an exception is thrown, your writing data to the log. Given the nature of logging, chances are pretty good that your flushing that output as soon as you write it (to ensure it isn't lost). Writing to disk is (again) quite a slow operation -- you need a fairly fast enterprise-class SSD to even get into the range of tens of thousands of IOPs/second. A disk used for logging might easily be limited to something like hundreds of IOPs/second.

Bottom line: there are cases where exception handling overhead can be significant, but this almost certainly is not one of them.


答:
I can understand that we should give up minuscule optimization for neater code (at least 99% of the times), however from what I know, catching exceptions belong to the class of code which have a noticeable delay in runtime.

Where do you know that from? How do you define "noticeable delay"?

This is exactly the kind of vague (and completely wrong) performance myth that leads to useless premature optimizations.

Throwing and catching an exception may be slow compared to adding two numbers, but it's completely insignificant compared to reading data from a socket. You could probably throw and catch a thousand exceptions in the same time you've read a single network packet. And we're not talking about thousands of exceptions here, only a single one.


问:
ORM Tools and advantages of circular references in entities
Let me demonstrate a simple example,

Class Organization

ID type Number,

Name type String,

HAS A -> Collection

Class Facility

ID type Number,

Name type String,

Location String ,

HAS A -> Organization

I am demonstrating a simple circular reference between two objects of an anemic data model.  Assuming they are mapped to an ORM tool, a collection of Facility can be fetched lazily from an Organization, and likewise an Organization can be fetched lazily from a Facility.

I understand the convenience of this, at least on the middle tier.  With a single Facility I can immediately obtain information about its Organization from code.  My question then is:

Are there ANY other advantages to circular references in ORM mapped entities?

Despite my intense emotions on this subject right now, I am trying my best to not load the question...

The prime infuriating disadvantage I am sufferring through at this moment is when I am trying to serialize these objects into XML and send them across a web service, far from the lofty comforts of its benevolent ORM session.  I can't serialize them as is because the ORM proxies cannot be sent, I must either eagerly fetch the child entities and send a MASSIVE object tree, or strip out the proxies from the graph.

Fair enough, so I wrote a utility to simply remove proxies, Great!  It serializes and performance is salivatingly good, however when I get this object back from an UpdateEntity web service, it is missing the rest of the object graph, and now if I were to update this entity through the ORM, it thinks I have deleted all of these objects missing from the tree.  No good.

I can't help but feel that circular references present a massive disadvantage in this scenario and I can't really seem to think of a good way to overcome this problem and the crippling performance problems I am tasked with solving without a data model redesign and massive refactoring.

What are your opinions on this?  Is this indeed a design-smell?

答:
When you serialize entities with circular references, you just ask the serializer to remove one of the dependencies. In your example, it would be Facility → Organization, unless you serialize only one Facility and don't need any other of the same organization.

It's technically possible and easy to do in C#. I expect the situation be quite similar in Java.

when I get this object back from an UpdateEntity web service, it is missing the rest of the object graph

It's not clear what are you trying to achieve here. Before accessing your data, you must first validate it, especially when it comes from user input, i.e. a source expected to be never trusted. You can't just flush all the data from your database to the user, then to receive the updated data and flush it back into the database.

Are there ANY other advantages to circular references in ORM mapped entities?

I don't think so. Maybe there are some advantages for the ORM, at validation level or to optimize performance, but I'm pretty unsure about this; in all cases, the primary goal of circular references in ORMs is to simplify the manipulation of data in business layer.


答:
In your case, XSLT is acting as just another template engine.

So, is it a good idea to use a template engine in your case?

Completely! You already highlighted several advantages in your question: being able to modify the content without having to deal with HTML and vice versa, or being able to use the same content both for e-mails and on the website (even if, performance wise, you may consider using a real database for the website, from which to produce XML through serialization).

Now, is it a good idea to use XSLT for your templates?

It depends. Some developers find it 1999y; others hate it so much that they would use no matter what as far as it is not XSLT; others know XSLT quite well, enjoy it and use it frequently.

It also depends on the other technologies used. If your website is in PHP, why not using Smarty or other template engines which would allow you to write a more lightweight code compared to XSLT? If you use .NET Framework, you may want to consider Razor, a template engine used in ASP.NET MVC websites.


问:
GPL and closed-source licensing for selling my script
I am working on a PHP script that I plan to sell without giving the user the ability to distribute it to anyone else.

I have heard about GPL being viral and I have quite a few libraries that are being used in my script that are under the GPL. (for example : jquery, phpthumb etc)

Does this mean that if a user who has bought my code can freely distribute it because a part of my code is under GPL so it becomes viral and my whole project becomes GPL ?

Can i not use any GPL code in my project ?

Thanks for any help.

答:
If you use GPL code in your project, you have to release it under the GPL license. For more informations, see http://www.gnu.org/copyleft/gpl.html.
However, JQuery is also licensed under the MIT license, which is more permissive, and you can purchase a commercial license for phpThumb.</p>

OwnerDisplayName: WarDoGG

OwnerDisplayName: WilQu


问:
is there any relationship between a story point in two different projects?
Assume we have two projects and one or more teams (one team doing the projects in serial or two teams doing the projects in parallel). </p>

<p>If Team A decides that a task is 8 story points and Team B decides that a task on their project is also 8 story points, does that say anything about the relationship between the two tasks? Or is there no relationship between the complexity of the two tasks? </p>

答:
No.  No relationship.  None.

People (PM's?) who ask this need to be walked through why teams estimate in story points rather than hours.  It isn't to be clever, but to build up a learning system within the team that the team can use/relate over the course of the project to help refine the team's ability to incorporate customer facing features into a product.  This forces Functional/Project/Program/Product Managers to think -very- differently about looking at a portfolio of projects.  The dev team is using a different process, and the key stakeholders will need to as well.

Caveat - Two teams made of corresponding identical twins working on the exact same product at the exact same time working across the hall from one another might come close.  Maybe.


问:
How to test software that burns CDs without wasting CDs?
I want to write an application that can be used to burn CDs (music). I know I should test it with real CDs anyway, but I don't want to do this every time I make a small change. But I do want to know and test if the right data will be burnt, so you don't get corrupted CDs.

I am using a library which only exposes APIs to directly burn to a physical drive; it doesn't allow you to write to a disk image (which would be much easier to test).

How could I test this without wasting CDs and time for every change/few changes I make?

答:
The simple answer is often the best: re-writable CD's?

Also for saving time, write relatively small files. Only do larger files every so often.