答:
Having "programmed" for nearly 35 years I would say that, with all I know now that I wish I had known then, go functional, at least part of the way to start with!

If I had to point you at some languages to get started with I would say:

LISP (or Scheme and there is Clojure which gets you into JVM arena)
(A sad day for LISP people today, its creator passed away today... http://www.guardian.co.uk/technology/2011/oct/25/john-mccarthy)

or

Smalltalk, specifically Squeak as it is very well supported and also has e-toys to play with which can help to give a grounding in programming basics.

Why those two? Simply because the syntax is so damned simple to pick up... LISP dialects have exactly ONE syntax rule to be learned and Smalltalk is a close second. IIRC, Smalltalk only has five reserved words: self super true false nil and the entire language is based around sending messages to objects.

In LISP the syntax rule is this: (function arg1 arg2 ...argN) and that's it!

So, when learning the "concepts" of programming for the first time  I would say that it frees your mind to not be fighting the compiler or interpreter for your chosen language by making sure they are very easy to work with. Java or PHP have a lot of reserved words.

Once you have picked a language, start hacking furiously until you understand the simple concepts such as variables and bindings, functions, I/O etc. My way of learning a new language used to be to write a version of "Pong" as you need to know how to read keyboard, save and load high scores, draw stuff etc.

Start small though, even printing 2+2 and getting the right answer feels good.
Then get the user to input numbers.
Read a list of numbers from a file, print the sum of those numbers.

Build on small successes all the time and if you make an error, enjoy figuring it out! I found that the more mistakes I made early on the faster I picked up the language I was learning.

Best of luck, it's a lifelong learning process!

:)

Title: What's the best way to learn code if you are just starting out?

Body:
I'm just starting out with some articles and tutorials.

I am looking for some guidance on which languages to start with and what is the best way to go about learning code, books, tutorials, classes.

Which tutorials or books are best?

Is it possible to learn this stuff online? If so how?

Thanks for any help!


问:
What's the best way to learn code if you are just starting out?
I'm just starting out with some articles and tutorials.

I am looking for some guidance on which languages to start with and what is the best way to go about learning code, books, tutorials, classes.

Which tutorials or books are best?

Is it possible to learn this stuff online? If so how?

Thanks for any help!

答:
I would start by learning CONCEPTS. For instance, what constitutes a file definition? What is a string? What is a loop?

Once you've mastered the underlying concepts (in any language), the code will come much easier. At least in my case, when I've had trouble understanding code, it's because I didn't fully understand the concept behind it.

ContentLicense: CC BY-SA 3.0


问:
Appropriate uses of fall-through switch statements
When is it appropriate to use a fall-through (classic) switch statement? Is such usage recommended and encouraged or should it be avoided at all costs?</p>

答:
If I feel a need to go from one case to another (rare, admittedly), I prefer to be very explicit and goto case, of course, that assumes your language supports it.

Because falling thru is so uncommon, and very easy to overlook while reading code, I feel it is appropriate to be explicit - and a goto, even if it's to a case, should stand out like a sore thumb.

It also helps avoid bugs that may occur when case statements are reordered.


问:
Newbie seeking advice on programming in general
need some of you to remember back to a time when you might have been bad at programming...

Been at my new job (as a software developer) for a couple of months now, passed probation period. Have very little programming experience (C++ only) and am currently working with asp.net MVC and silverlight. So there's a website the company has been working on and I am joining the effort to make it better, iron out bugs etc.

The problem is - learning about a system/website which has already been made, via visual studio. I ALWAYS feel HUGELY overwhelmed, never knowing which part of this line should I look up, and generally having lots of trouble getting the big picture. Visual studio itself is something I'm finding it difficult to get to grips with, let alone the asp.net framework.

I get the impression that because my coworkers have more experience than me, they are getting all the good jobs, and I am left with crap to do - stuff which is not even vaguely programming. Meaning they are learning/creating more, and I am learning/creating near nothing. I'm getting demoralised, and too scared to say anything.

I'm not stupid, I've read and practiced plenty of the fundamental programming concepts...I'm just bloody scared of this damn framework. I look at it and just feel paralyzed.

The result is that I keep asking the older veteran guy of questions, and he is getting irritated, and would rather give me easy/mindless/non programming jobs to avoid wasting time with helping me out. Then when I don't understand something, I'm hesitating about whether or not I should ask him yet, and trying to decide if it would be a waste of time.

I'm the kind of person who picks things up slowly, but with a lot of attention to detail. The former I think is making me look incompetent though.

Anyone get where I'm coming from please say something helpful....I'm scared of losing my job in a few months or something...

答:
Firstly, Accept the fact that you are no good at programming. If you don't want to accept it, then its gonna be a problem. You're a noob. Be practical. And be truthful to yourself. Period.
Accepted? Then read on.

Secondly, prove, to yourself (and nobody else. I repeat, Nobody else but you) that you aren't a noob anymore and that you can crack, make, debug the most filthiest and the most atrociously written code. You can top the charts, expect the higher pay scale from your good 'ol Boss all by proving to yourself that you Aren't a noob Anymore.

So now, coming to the actual answer:
How the heck are you supposed to do that in between your tight packed working hours, your family, your free time?
Yes. i know its not easy.
The way i do it. And by far, i think its the most effective one:

Get your Basics Right
Nutshell: the cocepts of OOP should be integrated inside your brain.

Design Codes (in the place of Castles) in the Air
I know it sounds crazy but viewing the wheels of the cars as functions helps the human brain get accustomed to the coding world!

Practice on Paper First!
My professor told me this trick. Practice on paper first. Dry Run your programs on the paper itself. It will help you get in the flow of a compiler + it will open up those logic gates in your brain.

Design your own project
yes. be it a CLI based calculator. design your own code. Make it unique. Why your own unique program? Because it will force you to think 'How am i supposed to do this?' and not force you to get frustrated. And when you have doubts, ask Herbert Schildt (forgive me if the spellings not correct) or Google or drop a question here. This is the best way to self study and improvise your skills.

When i was introduced to C, I too had a bad time. Especially with Structures n Pointers n Blahs n blahs. I learnt these things overtime.. the hard way if u may call it. And then, when I was broken, I didn't lose hope. I bought a Reference book and started to make a program that i always wanted to. After 3 months (yeah you can laugh!) i finally made A CLI version of a program that will take your Name as an input and will show your personality as the output. Acrophonology.

Yes. I am boasting because i feel proud about it! Because I saw the faces of my seniors who used to mock at me. Its all determination my friend! Programming is not rocket science! If it would have been then you would not have gone through probation! Its easy!

My personal belief: If you've got logic in your brain and you understand what is common sense, you can be a good coder.

And the good news is, you have both! Because if you wouldn't have been having it then you wouldn't have taken the right step by sharing your problem with us!

If you feel good now, I'm happy. And yes, you can now ignore the first line of this answer.. was necessary then.. Not necessary now!
Cheers!


问:
Where does form processing belong in an MVC application?
I found  this question on stack overflow and I have a question about one of the answers:

In Zend Framework, forms are typically objects with decorators, but usually (I thought) processing is done using a combination of controllers and models, with the main objective to keep the controller as lightweight as possible, and each object responsible for its own state.

One of the answers said to use the form object itself as the place to encapsulate the form processing members. Is that a good practice?

For some reason that seems awkward to me. But it also seems awkward to do most of the work in either the database abstraction layer (Zend_Db_Table/Row) or the controller. Where is the best place to encapsulate form processing? Should you create separate classes for the form itself and another class for processing the form (which then deals with the DBAL)?

Edit: here is another SO post that asks a similar question, but the OP doesn't get a complete answer.

We want to know: where does each part of the form processing logic belong?

答:
if you create an object that is mapped from your form and which maps to a database table, zend makes your life very easier at that point.

You should process your forms either at controllers or if it makes sense in a business delegate class. but be vary that you dont make too may layers. than you will have to pass around objects etc. it will be a mess and hard to maintain. i usually start at the controller, if there is not much business logic to perform.


问:
Is having your own website important?
How necessary or important is it? I try to keep a running list of blogs or sites to follow, but a lot of the time I pull up someone's profile and notice there isn't anything there. Is it really important?

I understand are different levels of programming (from C/C++ system programmers to Rails and even Haskell and J) and not everyone works in a language easily worked with for web based applications. Not everything is web-centric, however with the advent of many popular and sometimes free services I don't think it's unreasonable to expect a majority of programmers to have a personal site.

答:
How necessary or important is it?

Important for what? If creating a public persona is useful in the work that you do, then by all means build a web site and devote some time to making it useful and keeping it fresh. A web site could be particularly useful for independent software development contractors, promoting software for sale, and otherwise making yourself and your work as visible as possible.

On the other hand, plenty of smart developers have more work than they can currently manage as it is. Spending time promoting themselves on the Internet is not necessarily time well spent. In fact, the more your customers like your work, the more likely it is that they'll want you to do additional work for them, or to recommend you to others. For such a developer, a web site may not be important at all. It may be an unwelcome distraction, or it might lead to a lot of annoying e-mail from recruiters.

Also, it's important to point out that not having a public web site is not the same as not having a portfolio. Sure, a web site can be a handy way to display your portfolio, but it's not the only way. Here are some others:

hand someone an iPod touch with a dozen apps that you've written

send them a message with links to the web sites or mobile apps that you've created

forward a list of satisfied customers

In summary, having a web site may be an important means to tell the world about yourself. Maintaining a web site is not an important activity in itself, and it's not important to have one if it's not doing something useful for you.

ContentLicense: CC BY-SA 2.5

Title: Is having your own website important?


问:
How well will a C++ app communicating through Apache handle traffic?
I'm writing an online game that has to run in a web browser and I'm worried about whether my server-side architecture will be able to handle the load.

I'm designing for 1000-2000 simultaneous clients.  Each client will need to query the server once every 2 seconds - so 500-1000 transactions per second is my design goal.

My game server communicates with Apache via FastCGI.  I'm actually running Apache on Windows for the moment.  All this will run on a dedicated "dual-core" server. The game server application itself is written in C++ and the transactions are pretty simple and fairly low bandwidth (maybe 2k data per) so I'm not too worried about the game server piece.

My client is written in Javascript and uses XMLHTTP to communicate with the server.

So am I smoking something to think I can get 500 to 1000 transactions per second?  If so, what number might I expect?

答:
I've seen benchmarks using ab for PHP run at around 500 requests per second and upwards of 1200 per second for Python. Note, however, that these are basic requests that don't really do anything spectacular.

So really, your bottleneck will be your server code: It's definitely possible to reach 1k requests per second using Apache/FastCGI/C++, it all depends on your server hardware and complexity of your server code though (and server-side I/O, etc).

On a side note, is there a reason that you're using this particular tech stack? C++ usually isn't a very nice language to write server code in (as opposed to Java, etc). I might also look at a language like Erlang for server-side code to get around the FastCGI requirement to give your server even more of a boost.

In response to the OP's comments (a little too long winded for a comment):

@Joe Rice: TBH, I'd find it perfectly acceptable that gaming users would be forced to use the most up to date browsers - you can't use old PC-based gaming clients in most environments and you definitely can't in the console world, so why should browser-based gaming be any different? You might be signing yourself up for a world of hurt otherwise, especially given your budget constraints.

If your concerns are around budgeting, why not take a look at node.js as your server tech with socket.io libs both client and server side? There are a few bonuses here:

No context switching (well, limited). Same language used both client and server side, so you don't have to be continuously switching mindsets.

Graceful degredation handled for you: socket.io has a bunch of built-in fallback mechanisms to handle support on most browsers.

node.js supports TCP and (AFAIK) UDP, so you don't have to worry about the overhead of HTTP (although you'd obviously have to deal with UDP synchronizing issues yourself if you chose to go that route)

As you're familiar with C++, if you find a bottleneck server-side, you can dive into the library code and update as required.

Of course, there are potential downsides as well. I'm not familiar with any high-usage gaming servers being written entirely using node.js. You can also check out hacknews for node.js flame wars for further potential gotchas with using node as well.

OwnerDisplayName: Joe Rice


答:
I think I can speak for many of us by saying that for a moment I wondered if my past self had transported to the future to ask my present self this question on programmers.se.  This is pretty much what I would tell my past self if I were face-to-face with him when he was in your shoes:

Don't Get Discouraged - it's going to be hard and some days you'll hate what you're doing and wish you could go be a gardener or something else equally non-programming.  Pick yourself up off the ground, dust yourself off, and keep going, because you'll get better and the work you do will get better.

Use StackOverflow and Google - don't be a "Copy and Paste Programmer", but realize that there's TONS of smart people on SO and on the rest of the web who are willing, ready, and happy to offer help.  Besides, the SO answer or the blog post aren't going to grumble at you or give you dirty looks if you keep re-reading them to make sure you get it.

Keep Asking Questions - as long as you're doing your part to figure out what you can, there's nothing wrong with asking somebody with more knowledge and experience for help.  If your coworker wants to be a jerk about it, find another coworker who's more willing to help you out, or as others have said, bring it up with him or her and see what they say.  A little communication in situations like this can go a long way.

Keep Trying - don't give up on it.  Programming is hard, but that's part of the reward of it.  It takes a lot of time and effort to learn a new tool, framework, language, paradigm, etc... but it's worth it because every time you do you become better and the act of pushing through that learning experience will better prepare you for the next time you face it.  I'm working in a much larger codebase than I did in my first job, but I've been able to pick it up much more quickly because of the learning I've had along the way.

Give Yourself Some Credit - you've managed to turn C++ experience into a job working with ASP.NET MVC and Silverlight.  You're on programmers.stackexchange looking for help.  You're working and trying and doing what you can to get better.  You're doing the right things, and you're already a good portion of the way there by virtue of the fact that you were able to get a programming job.  Keep at it and it will get easier.

Find Something To Do On The Side - doing programming that's too hard or too mundane or whatever can quickly wear down your enjoyment of the craft.  Find a project you can work on for yourself apart from work, one that's not too challenging but that will keep your interest and keep you excited about programming.  Not only will it save you from hating coding, every piece of code you write helps you to hone your skills and personal projects look good on resumes should you decide that this job is not a fit for you.

Sorry if this sounds like too big of a pep talk.  I've just been in your shoes and I know how it feels.  Hopefully this and the other advice from people on here will be of help to you.  Oh, and one more thing - you started your question with this line:

```<code>need some of you to remember back to a time when you might have been bad at programming...
</code>```

I still am!  We all are!  We just keep working at it and trying to suck less every year.

Title: Newbie seeking advice on programming in general

Body:
need some of you to remember back to a time when you might have been bad at programming...

Been at my new job (as a software developer) for a couple of months now, passed probation period. Have very little programming experience (C++ only) and am currently working with asp.net MVC and silverlight. So there's a website the company has been working on and I am joining the effort to make it better, iron out bugs etc.

The problem is - learning about a system/website which has already been made, via visual studio. I ALWAYS feel HUGELY overwhelmed, never knowing which part of this line should I look up, and generally having lots of trouble getting the big picture. Visual studio itself is something I'm finding it difficult to get to grips with, let alone the asp.net framework.

I get the impression that because my coworkers have more experience than me, they are getting all the good jobs, and I am left with crap to do - stuff which is not even vaguely programming. Meaning they are learning/creating more, and I am learning/creating near nothing. I'm getting demoralised, and too scared to say anything.

I'm not stupid, I've read and practiced plenty of the fundamental programming concepts...I'm just bloody scared of this damn framework. I look at it and just feel paralyzed.

The result is that I keep asking the older veteran guy of questions, and he is getting irritated, and would rather give me easy/mindless/non programming jobs to avoid wasting time with helping me out. Then when I don't understand something, I'm hesitating about whether or not I should ask him yet, and trying to decide if it would be a waste of time.

I'm the kind of person who picks things up slowly, but with a lot of attention to detail. The former I think is making me look incompetent though.

Anyone get where I'm coming from please say something helpful....I'm scared of losing my job in a few months or something...

Body:
I think I can speak for many of us by saying that for a moment I wondered if my past self had transported to the future to ask my present self this question on programmers.se.  This is pretty much what I would tell my past self if I were face-to-face with him when he was in your shoes:

Don't Get Discouraged - it's going to be hard and some days you'll hate what you're doing and wish you could go be a gardener or something else equally non-programming.  Pick yourself up off the ground, dust yourself off, and keep going, because you'll get better and the work you do will get better.

Use StackOverflow and Google - don't be a "Copy and Paste Programmer", but realize that there's TONS of smart people on SO and on the rest of the web who are willing, ready, and happy to offer help.  Besides, the SO answer or the blog post aren't going to grumble at you or give you dirty looks if you keep re-reading them to make sure you get it.

Keep Asking Questions - as long as you're doing your part to figure out what you can, there's nothing wrong with asking somebody with more knowledge and experience for help.  If your coworker wants to be a jerk about it, find another coworker who's more willing to help you out, or as others have said, bring it up with him or her and see what they say.  A little communication in situations like this can go a long way.

Keep Trying - don't give up on it.  Programming is hard, but that's part of the reward of it.  It takes a lot of time and effort to learn a new tool, framework, language, paradigm, etc... but it's worth it because every time you do you become better and the act of pushing through that learning experience will better prepare you for the next time you face it.  I'm working in a much larger codebase than I did in my first job, but I've been able to pick it up much more quickly because of the learning I've had along the way.

Give Yourself Some Credit - you've managed to turn C++ experience into a job working with ASP.NET MVC and Silverlight.  You're on programmers.stackexchange looking for help.  You're working and trying and doing what you can to get better.  You're doing the right things, and you're already a good portion of the way there by virtue of the fact that you were able to get a programming job.  Keep at it and it will get easier.

Find Something To Do On The Side - doing programming that's too hard or too mundane or whatever can quickly wear down your enjoyment of the craft.  Find a project you can work on for yourself apart from work, one that's not too challenging but that will keep your interest and keep you excited about programming.  Not only will it save you from hating coding, every piece of code you write helps you to hone your skills and personal projects look good on resumes should you decide that this job is not a fit for you.

Sorry if this sounds like too big of a pep talk.  I've just been in your shoes and I know how it feels.  Hopefully this and the other advice from people on here will be of help to you.  Oh, and one more thing - you started your question with this line:

need some of you to remember back to a time when you might have been bad at programming...

I still am!  We all are!  We just keep working at it and trying to suck less every year.


问:
What language should be used to teach object-oriented design and development in university?
My understanding is that C++ is usually offered as the 1st OOP language, and as the 2nd programming language (after C) in my country (Bangladesh). I've taught it several times, and the problem I've run into is that students often tend to think C++ as an extension of C, i.e. C with cin and cout!
This has lead me to think about teaching Java as the first OOP language in the upcoming semester.

What is your opinion? I would like some suggestions from professional programmers as well as academics.

答:
If you're trying to teach (pure) OOP I would recommend against using C++ and use a pure OO language instead. One of the strengths and weaknesses of C++ is that it is a multi-paradigm language, with OOP only being a small part of it. Add its (mostly) backward compatibility with C and it's not a surprise that a lot of people familiar with C fall into the "C with cout" trap.

I would strongly recommend using a pure OO language like Smalltalk if you want to teach your students the concepts of OO. Yes, they're unlikely to get a job writing Smalltalk apps but that's not the point. If they're reasonably competent in picking up programming languages they'll learn another language easily. At this point you're not trying to make them "X programmers" but you want them to get the insights into a specific paradigm so picking a language that's a pure implementation of the paradigm and most likely unfamiliar to the students should help teaching because you'll avoid the "Oh, I know a shortcut here" moments.


问:
How to apply good Object Oriented Design principles in Embedded Systems
I am a firmware engineer moved from Electrical background to Embedded Systems. I was till now programming in C and never bothered to apply OO principles in my design. Recently I was forced to implement design in C++. I started liking the OO principles like SOLID, design patterns, etc. I wanted to know more about applying OO design in my firmware design. All the resources on OO, that I found were too much into application programming rather than firmware. I found this book relevant (ordered it). I was curious if there are any other resource that can help me learn OO principles with a focus on embedded systems.

I am still new to OO world, so please suggest me if I should learn OO principles first and then learn about applying them for embedded systems or start learning only stuff relevant to embedded system.

答:
In his course Effective C++ in an Embedded Environment, Scott Meyers states:

Good embedded software development is just good software development.

So if you get a good solid grounding in object oriented techniques in general, you can apply them in the embedded environment.

That being said, Meyers presents how

Software must respect the constraints of the problem and the platform.

C++ language features must be applied judiciously.

Meyers makes his course notes available in PDF format for a small fee at his course page.


问:
How can I sell a legacy program rewrite to the business?
We have a legacy classic ASP application that's been around since 2001.  It badly needs to be re-written, but it's working fine from an end user perspective.

The reason I feel like a rewrite is necessary is that when we need to update it (which is admittedly not that often) then it takes forever to go through all the spaghetti code and fix problems.  Also, adding new features is also a pain since it was architect-ed and coded badly.

I've run cost analysis for them on maintenance but they are willing to spend more for the small maintenance jobs than a rewrite.  Any suggestions on convincing them otherwise?

答:
Figure out a way to do it a bit at a time.

If you try to rewrite the whole thing from scratch, you'll probably never release it.

If your bite size chunks are small enough, you may not even need to sell this to the business at all: you may be able to simply go ahead as you implement new features.


问:
hiring a web designer: design task
I need to hire a web designer. How do I test his creativity and skills before I hire him. Ideally I'd like to give him a fairly open-ended task i.e. I give him a problem statement and ask him to design a PSD file.

Any suggestions on the problem statement I might give him? Also, is there a better way to hire /test a web designer?

答:
You can always ask for:

Previous work

Examples of design

Mockups / thoughts / ideas before you commit to a design

OwnerDisplayName: Gaurav Sharma

Title: hiring a web designer: design task


问:
Are there any good Java/JVM libraries for my Expression Tree architecture?
My team and I are developing an enterprise-level application and I have devised an architecture for it that's best described as an "Expression Tree". The basic idea is that the leaf nodes of the tree are very simple expressions (perhaps simple values or strings). Nodes closer to the trunk will get more and more complex, taking the simpler nodes as their inputs and returning more complex results for their parents.

Looking at it the other way, the application performs some task, and for this it creates a root expression. The root expression divides its input into smaller units and creates child expressions, which when evaluated it can use to build it's own result. The subdividing process continues until the simplest leaf nodes.

There are two very important aspects of this architecture:

It must be possible to manipulate nodes of the tree after it is built. The nodes may be given new input values to work with and any change in result for that node needs to be propagated back up the tree to the root node.

The application must make best use of available processors and ultimately be scalable to other computers in a grid or in the cloud. Nodes in the tree will often be updating concurrently and notifying other interested nodes in the tree when they get a new value.

Unfortunately, I'm not at liberty to discuss my actual application, but to aid understanding a little bit, you might imagine a kind of spreadsheet application being implemented with a similar architecture, where changes to cells in the table are propagated all over the place to other cells that need the result. The spreadsheet could get so massive that applying multi-core multi-computer distributed system to solve it would be of benefit.

I've got my prototype "Expression Engine" working nicely on a single multi-core PC but I've started to run into a few concurrency issues (as expected because I haven't been taking too much care so far) so it's now time to start thinking about migrating the Engine to a more robust library, and that leads to a number of related questions:

Is there any precedent for my "Expression Tree" architecture that I could research?

What programming concepts should I consider. I realise this approach has many similarities to a functional programming style, and I'm already aware of the concepts of using futures and actors. Are there any others?

Are there any languages or libraries that I should study? This question is inspired by my accidental discovery of Scala and the Akka library (which has good support for Actors, Futures, Distributed workloads etc.) and I'm wondering if there is anything else I should be looking at as well?

答: It sounds to me like you've reinvented Lisp. It has trees of operators and data that get combined into larger and larger expressions. I would suggest you take a look at Clojure. Clojure is a Lisp for the JVM purpose built to tackle functional programming with heavy concurrency from the start. </p>


答: I'd take the best of both worlds in a sense and teach them Objective-C. It's a strict superset of C so you can drop C code right in and not worry about it if it comes to that. It has a Smalltalk style object model which tends toward a slightly cleaner feel than C++ and Java. The Syntax is a bit weird and it would require Macs or the use of GNUstep but if you want a language that balances practice and purity a little better than C++ or Java, I'd pick it. It definitely helped me to learn it as far as learning Object Oriented Design.</p>

Title: What language should be used to teach object-oriented design and development in university?

Body:
My understanding is that C++ is usually offered as the 1st OOP language, and as the 2nd programming language (after C) in my country (Bangladesh). I've taught it several times, and the problem I've run into is that students often tend to think C++ as an extension of C, i.e. C with cin and cout!
This has lead me to think about teaching Java as the first OOP language in the upcoming semester.

What is your opinion? I would like some suggestions from professional programmers as well as academics.


问:
Deploying Web Applications
Background

So I have developed an order system and order tracking for a organisation. Currently it is web based with plans to develop a mobile application and a desktop application.

The business model is an exclusive membership where you sign up to be able to distribute their products at a cheaper price than other competitors.

EDIT: To clarify its currently being developed using Yii Framework for PHP, but I have a basic stripped down version in PHP using no framework. It's still in a development environment, no code is live yet.

Question

What (in your opinion or the industries opinion) the most effective way to distribute this application to the members?

Possibly in each of the stages of development (such as how to distribute a web app, desktop app or mobile app).

答: Package your application up to be distributed easily, either in a fancy installer, a WAR/JAR/ZIP file, or even on a CD. The key is to distribute documentation along with your packaged application that will include an installation guide and a user guide that instruct users on how to install and use your application. Make it as easy as possible to get up and running and be sure to include any troubleshooting scenarios and advice that might come in handy, unless you want to handle repeated support calls from your customers.</p>

Title: Deploying Web Applications


问:
Employer asking me to use API for entire website?
I'm working with an ASP.net developer, under a boss who doesn't have much technical knowledge. I'm doing the front-end work, and and a database expert doing the backend.

However, recently, he said that he would be working on the API for our site- I asked why, thinking we should do the web version first, assuming the API was for mobile apps. However, he said that he would just make a single API to work for all the web and mobile apps, and I would do the front-end for that.

Is it just me, or is this a little crazy? If I'm doing front-end, it means there's going to be two back-ends, because I'm going to have to use PHP or something to curl his API to the site, which is twice the loading time as normal.

Thank for any help in advance. Also, I happen to be "the intern", so I'll have some but not very much pull with this issue.

答:
Definitely represents the misunderstanding of the power of an API.   Many companies build multiple back-ends for each of their internal interfaces, partner interfaces.

Identify your data and resources and deploy them as separate APIs.

Then consume them across your internal, partner and public system.

I wrote an article about this that goes into more details.


答: Patience.  20 years ago when I was the new guy, they were sending me back to the server room to reboot the routers that were crashing all the time.  Quick tip: to learn a new framework when you have existing code, try adding another field to an existing form and then carry its affects all the way through to where it would go into a database.  By following the value of another field already on that form.  You will learn a ton.</p>


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答: A really good text editor and knowledge of its key bindings.


问:
What techniques should I keep in mind in order to design efficient algorithms in PHP?
I am trying to solve programming challenges on www.interviewstreet.com using PHP. Are there certain techniques I should keep in mind that will optimize the efficiency of the algorithm? For example, I read that using PHP's language constructs versus function calls are faster. Is this true? Any other tips?</p>

答:
Not using functions isn't the mark of algorithmic efficiency. Algorithms themselves are language-agnostic, they are well-defined ways to do something that can be implemented in most any language. Algorithmic efficiency is far more concerned with ideas like "given input of size n, how many steps does a algorithm need to compute answer y?" and "if I increase the input, how does that affect the algorithm?"

Imagine this - what if you were going to sort 100 million items in a list? If your function was something like bubble sort, not using a function call will save you some microsecond of processing, but the actual sorting will take significantly longer and dwarf any gains from not using function calls or any other number of things (plus, not breaking your code up is usually a bad design and bad for maintenance!).

Algorithmic efficiency is usually noted with Big-O Notation and is part of complexity theory. They also relate heavily to data structures, which are things like linked lists, arrays, trees, graphs, etc.

You probably want to read about basic foundational algorithms, data structures and ideas, like:

Trees

Graphs

Associative arrays

divide and conquer algorithms

dynamic programming

greedy algorithms

sorting algorithms, which will give you a really good idea about algorithmic efficiency, as there are many different sorts that have different levels of efficiency and real world speed.

For books, if you're interested, there are:

Algorithm Design Manual - Skiena's presentations here: http://www.cs.sunysb.edu/~algorith/video-lectures/

Introduction to Algorithms (CLRS) - this is a very math-y book. It's excellent, but very mathematical.

Algorithms by Robert Sedgewick

Algorithms by Dasgupta et al. - you can get a free copy of their near-final draft

PS - many times you'll see people who want to optimize the hell out of their code to squeeze as much performance out of it as possible. What should really be asked first is if they picked the right algorithm to do it and are using the correct data structures.


答:
"If I'm doing front-end, it means there's going to be two back-ends".

No, it does not.
Do you mean that because there is a separation between the front end and the back end this implies that there will be either multiple front or back ends ?

Separation of presentation code (front-end) and logic is a good thing in itself. You should not mix these two concerns together. Moreover if you allow the logic to be on the back-end, then several front-ends can use the same back-end.

Also it is more common to have several front-ends to a single back-end then the case you mention: a single front-end with several back-ends.

As for his approach of creating an API to service both the standard web and mobile versions, if it is done well I see this point as beneficial.

Title: Employer asking me to use API for entire website?

Body:
I'm working with an ASP.net developer, under a boss who doesn't have much technical knowledge. I'm doing the front-end work, and and a database expert doing the backend.

However, recently, he said that he would be working on the API for our site- I asked why, thinking we should do the web version first, assuming the API was for mobile apps. However, he said that he would just make a single API to work for all the web and mobile apps, and I would do the front-end for that.

Is it just me, or is this a little crazy? If I'm doing front-end, it means there's going to be two back-ends, because I'm going to have to use PHP or something to curl his API to the site, which is twice the loading time as normal.

Thank for any help in advance. Also, I happen to be "the intern", so I'll have some but not very much pull with this issue.


问:
How can I display a diff result in a single file or document?
I'm reviewing my peer's code. I use SourceGear DiffMerge as my diff program, on a Windows environment.

While I'm using the diff program, I can clearly see the code changes, etc.

Is it possible to save the diff display somehow, with all its colorful rendering and strike-throughs so that I can send my comments by mail?

In other words, is it possible to export the diff display to a single file (which includes all the relevant data) to be displayed without the actual need to save the two files separately? (Perhaps HTML is fit for this job).

Can you recommend on a diff program that can export the diff as a single file?

Thanks in advance!

答:
TortoiseMerge from TortoiseSVN can export result of files-compare to *.diff (if you don't want to use old good ported to Win diff -u)

TortoiseUDiff (from the same source) show this colored-diff (sorry for non-readable text - it's UTF8 without BOM, don't know how to visualize it in TortoiseUDiff correctly: never use this feature): red is deleted strings, green - added, white - context


答:
Fall-through cases are perfectly fine. I often find that an enumeration is used in lots of places, and that when you don't need to differentiate some cases it is easier to use fall-through logic.

For example (note the explanatory comments):

```<code>public boolean isAvailable(Server server, HealthStatus health) {
  switch(health) {
    // Equivalent positive cases
    case HEALTHY:
    case UNDER_LOAD:
      return true;

    // Equivalent negative cases
    case FAULT_REPORTED:
    case UNKNOWN:
    case CANNOT_COMMUNICATE:
      return false;

    // Unknown enumeration!
    default:
      LOG.warn("Unknown enumeration " + health);
      return false;
  }
}
</code>```

I find this kind of use perfectly acceptable.

Title: Appropriate uses of fall-through switch statements

Body: When is it appropriate to use a fall-through (classic) switch statement? Is such usage recommended and encouraged or should it be avoided at all costs?</p>

Body:
Fall-through cases are perfectly fine. I often find that an enumeration is used in lots of places, and that when you don't need to differentiate some cases it is easier to use fall-through logic.

For example (note the explanatory comments):

public boolean isAvailable(Server server, HealthStatus health) {
  switch(health) {
    // Equivalent positive cases
    case HEALTHY:
    case UNDER_LOAD:
      return true;

    // Equivalent negative cases
    case FAULT_REPORTED:
    case UNKNOWN:
    case CANNOT_COMMUNICATE:
      return false;

    // Unknown enumeration!
    default:
      LOG.warn("Unknown enumeration " + health);
      return false;
  }
}

I find this kind of use perfectly acceptable.


答:
The easiest way to learn is by doing.

The only way to motivate yourself to do something is to make something that interests you.

Think of something interesting that you WANT to make and COMPLETE within a given time frame. Remember that the words in uppercase are key.

It has to be something you really WANT to make so you will have the motivation to not give up once you meet the first hurdle (of which there will be many ).

It should also be something you want to COMPLETE for at least three reasons.

A desire to complete something makes you push harder. More motivation is a good thing.

People that can't consistently deliver projects aren't coders, more like random typists with too much time on their hands

You get to experience the complete cycle of development. From basic design/planning to coding to delivery to maintenance. Trust me, if you are going to develop software for a living down the road, these are the most important things to learn. Experience design/planning because that's what sets your imagination free. Experience coding to a target because that is how all coding should be done. Experience delivery because when you do it for a living, that's often the most important part of your job. Lastly, experience maintenance, cos that will teach you how to do the first three parts better.

Once you decide what you want to do, people here will be able to tell you if the time frame is feasible and they can also recommend the right language for you to use. If you get stuck, I'm pretty sure some of us will be more than willing to help as well.

Let your desire guide you. Don't worry too much about whether a language is too "strict", too "loose", OO, procedural, etc, etc. Some of the most complex concepts are often the easiest to pick up for a beginner because you haven't been "contaminated" too much, haha.

Also don't worry worry about learning the "best" language because there is no such thing.

Just pick a project and start learning.


问:
Why should one avoid cross-team (circular) merges in multiple-team version control?

Please excuse the artwork, I know it looks like an elongated imperial shuttle, but it's the way I visualise a multiple team (or multiple stream) version control strategy. The central core, is the trunk (or master) repository. If there were lots more streams you can imagine more planes projecting out from the trunk, in which various branching and merging is taking place within those streams (the thinner lines).

The red line shows Alice from accounting wanting to take a piece of code that Bob from the backups team has only just forged (she needs it urgently for some reason that I can't think of). Actually, it's not like a one line change that she can just do herself. Instead you can consider that accounting are heavily blocked and need a large change set from Backups to continue.

Now as I understand it, this is against best-practice, and the changes required should go through the trunk, and Alice should pick them up that way, rather than take the short cut illustrated (a version control wormhole). However, although I have seen this stated in various places, I have never seen some deep, lengthy and well-justified reasons why a cross-stream (or circular?) merge is something not to allow. The only thing I can think of is that I guess it can lead to greater manual conflict resolution.

So questions are:

Why is allowing a cross-stream merge bad? (I need some well-defined
reasons to convince my various-minded colleagues why it shouldn't be
done)

Are there any justifiable reasons to go against best-practice?

What if Alice's team is reaching a release deadline, can there be an
exception?

答:
Now as I understand it, this is against best-practice, and the changes required should go through the trunk, and Alice should pick them up that way, rather than take the short cut illustrated

Why so??? Final task is (after all) getting product, not blindly follow policy. Cross-team communication is nice, if it serves final task - "getting thing done"


问:
Do you prefer conciseness or readability in your code?
Language shortcuts can often be used to make code more concise.

For example, ternary and null coalescing operators can reduce the amount of code, but arguably to the detriment of readability:

In C#:

```<code>Person newGuy = new Person();
if (boss == null) {
    newGuy.Boss = GetDefaultBoss();
} else {
    newGuy.Boss = boss;
}
</code>```

is functionally equivalent to:

```<code>Person newGuy = new Person();
newGuy.Boss = boss ?? GetDefaultBoss();
</code>```

but obviously a lot more verbose.

Where do you draw the line when it comes to conciseness vs readability?

答:
One aspect that I don't think has been mentioned yet: what are your goals?

If all you care about is job security, go for conciseness & compactness over everything else. Skip commenting your code, too.

If you want to be able to easily hand your code off to someone else while you go work on a cool new project, go for readability, clarity, and lots of solid comments.

Note: the above isn't about you personally, @Damovisa; it's for anyone choosing between the two positions.


问:
When do you drop old technologies from your resume?
I have been reviewing several resumes we have for a new position.  I noticed that a few of them had many old programming language versions and old applications on their resume (e.g. SQL 4.2, VB5, Lotus 123, Novell).  This left their list of computer experience very long.  Do you keep it fresh?  Do you show your depth of experience even though you will never use that techology again?

When should you drop old technology on your resume?  By keeping old technology on your resume does that do any harm in getting hired?

答: I only list out what I've been using for last about two or three years in my resume. For example, I was a crazy C++/MFC programmer ten years ago but I almost don't use it since then so does it still make sense in my skill list? It definitely not. Of course, old technologies are still in the list of projects/applications you did in the past.</p>


问:
What do you do when you encounter an idiotic interview question?
I was interviewing with a "too proud of my java skills"-looking person.

He asked me "What is your knowledge on Java IO classes.. say.. hash maps?"

He asked me to write a piece of java code on paper - instantiate a class and call one of the instance's methods. When I was done, he said my program wouldn't run. After 5 minutes of serious thinking, I gave up and asked why. He said I didn't write a main function so it wouldn't run. ON PAPER.

[I am too furious to continue with the stupidity...]

Believe me it wasn't trick questions or a psychic or anger management evaluation thing.

I can tell from his face, he was proud of these questions.

That "developer" was supposed to "judge" the candidates.

I can think of several things:

Hit him with a chair (which I so desperately wanted to) and walk out.

Simply walk out.

Ridicule him saying he didn't make sense.

Politely let him know that he didn't make sense and go on to try and answer the questions.

Don't tell him anything, but simply go on to try and answer the questions.

So far, I have tried just 4 and 5. It hasn't helped. Unfortunately many candidates seem to do the same and remain polite but this lets these kind of "developers" just keep ascending up the corporate ladder, gradually getting the capacity to pi** off more and more people.

How do you handle these interviewers without bursting your veins? What is the proper way to handle this, yet maintain your reputation if other potential employers were to ever get to know what happened here? Is there anything you can do or should you even try to fix this?

P.S. Let me admit that my anger has been amplified many times by the facts:

He was smiling like you wouldn't believe.

I got so many (20 or so) calls from that company the day before, asking me to come to the interview, that I couldn't do any work that day.

I wasted a paid day
off.

答: I answer all questions during an interview, even idiot ones. For example, in a recent interview (I applied for a Software Architect position and the interviewer is a Technical Architect, according to his title) I got a question to list out all versions of the .NET framework has been released until .NET4. No problem, I even gave the interviewer more when telling him that I used .NET Framework from its early beta in 06/2000 :).</p>


问:
How to design a performance comparison between two data structures
I want to compare the performance of two search trees of integers (an AVL tree and a RedBlack tree). How should I design/engineer the tests to accomplish this? For example, let's consider the insert operation; what steps should I follow in order to state that on average this operation is faster in the RB case? What considerations should I take to correctly measure CPU time? Should both implementations be optimized, or may I compare an optimized implementation of AVL vs a straightforward implementation of RB?

Any links or papers would be very helpful.

答:
It highly depends on what you plan to do with the data structure. If you will end up filling it with a certain structured input, then you should also test it that way.

If you don't know anything about your future inputs and want to measure average performance, then remember that complexity theory calculates average performance based on randomized inputs (using a normal distribution). Hence, average-case performance test should include many runs with varying random inputs.

Depending on the data structures themselves, you may also be interested in comparing certain input structures that are known to be very good/bad for one of the data structures. Nevertheless, your future application of the data structure may almost never create such inputs, in which case you may well ignore the performance comparison of these cases. (Intuitive Example: comparing sort algorithms in a context, where you often try to sort an already sorted sequence could throw many quicksort implementations off.)

As for your optimization point, the answer again is: It depends. Are you aiming for using this data structure in exactly that one project right now? Then I'd go for optimized versions. Are you aiming at a comparison to get a general idea on which one might be more suitable for a planned project? Then try to compare reference implementations, but do not waste time on creating super-efficient implementations. Of course, the context in which you execute the tests has to be comparable, so don't try to f.ex. compare implementations in different programming languages to each other. Probably obvious, but I just thought I'd make sure to mention it.


问:
Why do people still say Java is slow?
For a long time in SO and in other places Java has the reputation of being slow. From jokes to many comments in questions and answers, people still believe Java is slow based solely on experience with it in the 90s.

This is my issue: we have disproved (most) of the reasons that people believe Java is slow. Outside of small things, Java is pretty fast.

So why is it that people still refuse to believe Java is fast now? Is it part of their mindset that anything thats not C/C++ is slow? Is it because people don't check over time? Is it because people are just biased?

答:
@bigown "Why do people still say Java is slow?"

Because they are dumb. Because they have no work experience, but think they are the living incarnation of Dikjstra or the second coming of Linus Torvald, oh I dunno. The reasons for saying such a retarded thing are so many, but usually stupidity, mindless subjective fanboyism, and emotional attention-whoring seem to be behind them.

Let's disect this so that you can see the truth of what I've just said above:

First, what is slow, in what context, for what, under what conditions, with what engineering/scientific/business purpose (for saying tehe it sucks is not one of them.) Any person who says "X is slow" for any technology X, or simply "X is Y" where Y is some type of negative statement, without answering any of the questions above should be dismissed as a fool. Statements like that don't have a place in engineering. In politics and juvenile chat rooms maybe, but not on engineering.

Second, most of these misguided fools cry about Java being slow because ZOMG, their eclipse takes forever to fire up (gee, load the thing with all the plug ins, and guess what happens.) Most of these fools don't even know how to tune the jvm for eclipse to operate fast (or for any Java application for that matter). That is, they have no clue about performance tuning, which is a reality not just for Java, but for any non-trivial system, be it hardware or software. So right there, they disarm themselves for any technical validity in making such mindless statements.

Third, let's consider what the bulk of Java development is for: back end OLTP first and foremost; monitoring systems coming second. Either type of system is intended to run in clusters, and to run uninterrupted for weeks if not months. Does it really matter then that your little eclipse or toy app takes a minute or two to load when the purpose of REAL Java apps is to run for extended periods of time? Context, people, context.

Lastly, the backbone of OLTP on Google and Ebay run on Java. I would take that as a proof by contradiction that Java is not slow (at least for conditions that matter, not for little toy experiments, benchmarks and unverifiable annecdotal evidence done specifically for the purpose of saying "tehe X is slow, it sucks."

There is engineering, and there is fanboyism. Guess which category statements like those belong to?

Title: Why do people still say Java is slow?


答:
This depends on your customers and the people who are going to install the application. If you can assume that mostly system administrators (or at least software engineers) are going to install the application, than a ZIP is probably enough. The ZIP should contain all necessary files to install and run the application (also documentation).

You can also distribute your application in form of an RPM or DEB file. This would even allow simpler installation and you get more control over what is done in the standard installation process.

You can take a look at the installers which are offered by Jenkins (see the right sidebar) to get an idea about good distribution and installation techniques.

Possibly in each of the stages of development (such as how to distribute a web app, desktop app or mobile app).

Automate the process of creating your distribution. This reduces risk of errors and saves you time in the end. You might want to read up on Continuous Delivery.

Title: Deploying Web Applications

Body:
Background

So I have developed an order system and order tracking for a organisation. Currently it is web based with plans to develop a mobile application and a desktop application.

The business model is an exclusive membership where you sign up to be able to distribute their products at a cheaper price than other competitors.

EDIT: To clarify its currently being developed using Yii Framework for PHP, but I have a basic stripped down version in PHP using no framework. It's still in a development environment, no code is live yet.

Question

What (in your opinion or the industries opinion) the most effective way to distribute this application to the members?

Possibly in each of the stages of development (such as how to distribute a web app, desktop app or mobile app).


答:
Be careful with terminology. Data structures don't have performance; algorithms do. It's true that some data structures are designed specifically to enable their corresponding algorithms, but it's still a good idea to keep the distinction in mind.

For example, you asked about comparing "optimized" AVL to "straightforward" RB. If you think in terms of algorithms, then you're just comparing one algorithm to another. You can compare all the different flavors of algorithms that do the same task: optimized AVL insertion, straightforward AVL insertion, optimized RB insertion, straightforward RB insertion, heap insertion, linked list insertion, etc. They all accomplish similar goals, so comparing them is useful.

A typical way to do this sort of thing is to build a test harness that will run each algorithm the same way using the same data the same number of times. For example, you might write a function that takes a function (the algorithm), a data set, and a number of repetitions as parameters. The function would then run the algorithm using the data for that number of reps, and return the elapsed time.

Title: How to design a performance comparison between two data structures

Body:
I want to compare the performance of two search trees of integers (an AVL tree and a RedBlack tree). How should I design/engineer the tests to accomplish this? For example, let's consider the insert operation; what steps should I follow in order to state that on average this operation is faster in the RB case? What considerations should I take to correctly measure CPU time? Should both implementations be optimized, or may I compare an optimized implementation of AVL vs a straightforward implementation of RB?

Any links or papers would be very helpful.


问:
Where does form processing belong in an MVC application?
I found  this question on stack overflow and I have a question about one of the answers:

In Zend Framework, forms are typically objects with decorators, but usually (I thought) processing is done using a combination of controllers and models, with the main objective to keep the controller as lightweight as possible, and each object responsible for its own state.

One of the answers said to use the form object itself as the place to encapsulate the form processing members. Is that a good practice?

For some reason that seems awkward to me. But it also seems awkward to do most of the work in either the database abstraction layer (Zend_Db_Table/Row) or the controller. Where is the best place to encapsulate form processing? Should you create separate classes for the form itself and another class for processing the form (which then deals with the DBAL)?

Edit: here is another SO post that asks a similar question, but the OP doesn't get a complete answer.

We want to know: where does each part of the form processing logic belong?

答:
Depends on the type of validation - when the validation logic is part of the business domain, e.g. format of a social security number, then the validation should be located in the model. If the validation logic only applies to a specific form, then put the validation into the form.

You do this because you want to be able to reuse the validation logic in possibly multiple forms.


问:
Is it an appropriate use of #define to make typing repeated code easier?
Is there any view on whether using the #define to define full lines of code for simplifying coding is good or bad programming practice? For example, if I needed to print a bunch of words together, I'd get annoyed typing

```<code><< " " <<
</code>```

To insert a space between words in a cout statement. I could just do

```<code>#define pSpace << " " <<
</code>```

and type

```<code>cout << word1 pSpace word2 << endl;
</code>```

To me this neither adds or subtracts from the clarity of the code and makes typing slightly easier. There are other cases that I can think of where typing will be much easier, usually for debugging.

Any thoughts on this?

EDIT: Thanks for all the great answers! This question just came to me after doing a lot of repetitive typing, but I never thought there would be other, less confusing macros to use. For those who don't want to read all the answers, the best alternative is to use the macros of your IDE to reduce repetitive typing.

答:
My main thought on this, is that I never use "make typing easier" as a rule when writing code.

My main rule when writing code is to make it easily readable. The rationale behind this is simply that code is read an order of magnitude more times that it is written. As such, the time you lose writing it carefully, orderly, correctly laid out is in fact invested in making further reading, and understanding much faster.

As such, the #define you use simply breaks the usual way of alternated << and other-stuff. It breaks the rule of least surprise, and is not IMHO a good thing.


答:
Personally, I loathe it. There's a number of reasons why I discourage people from this technique:

At compile-time your actual code changes may be significant. The next guy comes along and even includes a closing bracket in his #define or a function call. What's written at a certain point of code is far from what's going to be there after pre-processing.

It is unreadable. It may be clear to you.. for now.. if it's just this one definition. If it becomes a habit, you will soon end up with dozens of #defines and will start to lose track yourself. But worst of all, no one else will be able to understand what word1 pSpace word2 exactly means (without looking up the #define).

It may become a problem for external tools. Say you somehow end up with a #define that includes a closing bracket, but no opening bracket. Everything may work well, but editors and other tools may see something like function(withSomeCoolDefine; as rather peculiar (i.e., they will report errors and whatnot). (Similar example: a function call inside a define - will your analysis tools be able to find this call?)

Maintenance becomes much harder. You have all those define in addition to the usual problems maintenance brings with it. In addition with the above point, tool support for refactoring may be affected negatively as well.

Title: Is it an appropriate use of #define to make typing repeated code easier?

Body:
Is there any view on whether using the #define to define full lines of code for simplifying coding is good or bad programming practice? For example, if I needed to print a bunch of words together, I'd get annoyed typing

```<code><< " " <<
</code>```

To insert a space between words in a cout statement. I could just do

```<code>#define pSpace << " " <<
</code>```

and type

```<code>cout << word1 pSpace word2 << endl;
</code>```

To me this neither adds or subtracts from the clarity of the code and makes typing slightly easier. There are other cases that I can think of where typing will be much easier, usually for debugging.

Any thoughts on this?

EDIT: Thanks for all the great answers! This question just came to me after doing a lot of repetitive typing, but I never thought there would be other, less confusing macros to use. For those who don't want to read all the answers, the best alternative is to use the macros of your IDE to reduce repetitive typing.


答:
Writing code is easy. Reading code is hard.

You write code once. It lives for years, people read it a hundred times.

Optimize code for reading, not for writing.


答:
Its a reasonably valid thing to do in a pure "C" program.

It is unnecessary and confusing in a C++ program.

There are many ways to avoid repetitive typing of code in C++. From using the facilities provided by your IDE (even with vi  a simple "%s/ pspace /<< "  " <</g" would save as much typing and still produce standard readable code ). You could define a private methods to implement this or for more complex cases C++ template would be a cleaner and simpler.


问:
Pair Programming Using Different Editors
I really like pair programming for particular projects or features. It can act as an immediate sanity check and increase code coverage across your development team. That said I always seem to run into an issue regarding editors. I primarily code Ruby and I personally like to use VIM whereas other developers on my team use EMACS, TextMate or RubyMine. On top of that, even if two developers are using the same editor, it seems that everyone has a different macro for running tests or executing a certain file.

My question is this: how do you continue to pair program when everyone has a different editor preference? Is there some kind of software or development practice that would allow two developers to pair program from different editors? Do you just have to agree on a common editor that you can both use? How do you solve this problem in your company?

答:
Hour one: you program, the other person watches and helps thinking.

Hour two: the other person programs, you watch and help thinking.

You can switch editors when the other person starts programming.


答:
You should use the default way of deploying applications for each device.

If you have a web application, deploy it as a WAR.

If you have an iphone app, bring it to the AppStore.

If you have a desktop application, use MSI+download or DEB+apt-get or RPM+yast or...

And make sure that you create the most simple installation procedure you can think of.

I'd love to agree with the answer of @Bernard but I think documentation is a waste of time for end users. The default way is download+double click and then skip through the install wizard. I think the MSI should have proper default settings and let the user complete the install with 1 click, instead of going through pages and pages of settings which the end user will never change nor read.

Title: Deploying Web Applications


答:
I've started using the homesick gem to track my .vimrc, .vim, etc

Now I can checkout my dot files to any machine, no worries! hooray!

I do tend to keep my customized vim pretty light (CommandT, some whitespace stuff, matchit) that way I learn how to do stuff the standard way instead of the really cool way that only my computer uses.

I also try to learn the basics of the different editors. I can pair program in RubyMine, TextMate, VIM, and a smidge of emacs. I practice a little bit with each editor. Sure I won't type as fast as if I were using VIM, but typing isn't the bottleneck ;).

Title: Pair Programming Using Different Editors

Body:
I really like pair programming for particular projects or features. It can act as an immediate sanity check and increase code coverage across your development team. That said I always seem to run into an issue regarding editors. I primarily code Ruby and I personally like to use VIM whereas other developers on my team use EMACS, TextMate or RubyMine. On top of that, even if two developers are using the same editor, it seems that everyone has a different macro for running tests or executing a certain file.

My question is this: how do you continue to pair program when everyone has a different editor preference? Is there some kind of software or development practice that would allow two developers to pair program from different editors? Do you just have to agree on a common editor that you can both use? How do you solve this problem in your company?


答:
The ever pertinent 'where the heck does validation logic go?!' question ;).

The answer is: It depends.

I like to apply the following ruleset:

First: database level validations that prevent me from putting in bad data

Second: view level validations that are a bit shinier to provide specific responses to the specific form

Third: javascript level validations that do dynamic validation to save them the hassle of clicking

```<code>submit->ohfrickmissedthat->fix->submit->ohfrickmissedthattoo
</code>```

Obviously how far you follow this ruleset depends on how usable your application ought to be.

Title: Where does form processing belong in an MVC application?

Body:
I found  this question on stack overflow and I have a question about one of the answers:

In Zend Framework, forms are typically objects with decorators, but usually (I thought) processing is done using a combination of controllers and models, with the main objective to keep the controller as lightweight as possible, and each object responsible for its own state.

One of the answers said to use the form object itself as the place to encapsulate the form processing members. Is that a good practice?

For some reason that seems awkward to me. But it also seems awkward to do most of the work in either the database abstraction layer (Zend_Db_Table/Row) or the controller. Where is the best place to encapsulate form processing? Should you create separate classes for the form itself and another class for processing the form (which then deals with the DBAL)?

Edit: here is another SO post that asks a similar question, but the OP doesn't get a complete answer.

We want to know: where does each part of the form processing logic belong?

Body:
The ever pertinent 'where the heck does validation logic go?!' question ;).

The answer is: It depends.

I like to apply the following ruleset:

First: database level validations that prevent me from putting in bad data

Second: view level validations that are a bit shinier to provide specific responses to the specific form

Third: javascript level validations that do dynamic validation to save them the hassle of clicking

submit->ohfrickmissedthat->fix->submit->ohfrickmissedthattoo

Obviously how far you follow this ruleset depends on how usable your application ought to be.


问:
What's the best way to learn code if you are just starting out?
I'm just starting out with some articles and tutorials.

I am looking for some guidance on which languages to start with and what is the best way to go about learning code, books, tutorials, classes.

Which tutorials or books are best?

Is it possible to learn this stuff online? If so how?

Thanks for any help!

答:
I'd like to take a slightly different tact than the old  'learn a language and do stuff with it' approach. Over the past 2 years I've developed an apprenticeship program at a software consultancy, and we discovered that there are 2 main factors to how easily a non programmer/beginning programmer becomes competent:

The innate desire they have to learn to make magic with computers

The amount of time they spend working directly with other programmers

If these 2 criteria are not fulfilled, you wind up with programmers who never get past the advanced beginner stage. Hopefully this is not you :)

Now, some people will recommend python as a first language. Others will recommend ruby. Some horrible people will recommend you learn Assembler first, that way you decide not to become a programmer and they can reduce competition in the field.

Here is my rule of thumb for guiding someone to their first language:
  * Python is great if you are already mathy (statistical analysis, etc) or you come from a highly technical background (*nix server administration, powershell, etc). The language is absolutely beautiful if you already think in terms of formulas and algorithms (a word I still struggle to spell).
  * Ruby is fantastic for everyone else.

Assuming you're not already a math genius, I'd recommend the following:

Work through tryruby.org. This will get you started with writing code! Woohoo! CODE!

Work through rails for zombies, as this will get you started making a very basic web application

Do the ruby koans. These are great for teaching you all about how the ruby language works.

Grapple with Learn Ruby the Hard Way. This is the hard way ;). But it's not too terrible.

If you want to continue to play (something I'd highly recommend!) rubywarrior  is a very fun dungeon crawl game where you write an AI to crawl the dungeon! I am not sure I'd recommend starting here, but it's definitely a fun time! I have the first few levels up as videos on youtube.

Once you are familiar with how to make computers do math and play with variables, I recommend digging a bit into some books:

Growing Object Oriented Software Guided by Tests

Clean Code

The RSpec Book

The Rails Way

And Remember: PLAY! Code with people! Share your source code! Ask for review! github.com is a wonderful place!


问:
What algorithm browsers follow to remember values for form controls?
You can have different HTML input elements on a single HTML form and all of them, have their associated remembered values (values that you've entered in those fields); Is it related to the id or name attribute of the input element? No. Proof? Your email address appears on many input elements across different websites, and all those fields have different id and name attributes.

So, there is a mystery here I don't understand. How browsers remember values for HTML form controls? What is the algorithm? How they know that they should show your email on this control and not on that control, while controls are both HTML input type=text elements?

答: Browser are checking for similarity between input elements' name attributes. Also, there are standard names for input fields defined in RFC 3106. Also look here.</p>


答:
Different browsers use different algorithms. I know if I were building one I would wind up

checking if the fields name/id has 'email' in it

checking if the label text has 'email' in it

checking for common abbreviations

(if I were google) keeping track of all the forms everyone inputs and seeing which ones get email address looking strings put in them. Since I'm google I can totally do that ;).

Title: What algorithm browsers follow to remember values for form controls?

Body:
You can have different HTML input elements on a single HTML form and all of them, have their associated remembered values (values that you've entered in those fields); Is it related to the id or name attribute of the input element? No. Proof? Your email address appears on many input elements across different websites, and all those fields have different id and name attributes.

So, there is a mystery here I don't understand. How browsers remember values for HTML form controls? What is the algorithm? How they know that they should show your email on this control and not on that control, while controls are both HTML input type=text elements?


问:
Opera for web development
Many developers recommend Firefox for web development for a variety of reasons. But, after looking at Opera, it seems to me that Opera has all of the same web development functionality that Firefox has built into it. So what is wrong with Opera for web development?</p>

答:
I'm using constantly Opera, Safari, Firefox and Chrome for web development (switching each two-three days). It helps me to find early browser specific issues.

As of Opera, things are getting better. For example even a year ago I won't advice anybody use Opera ad main development browser. Nowadays now Dragonfly looks pretty mature.

But I still belive that firefox is most comfortable tool.

Title: Opera for web development


答:
It will be, by all means, better if you tune you favorite IDE/text editor for inserting snippets of code you find tiresome to retype again and again. And better is "polite" term for comparison. Actually, I can not think about any similar case when preprocessing beats editor's macros. Well, may be one - when by some mysterious and unhappy reasons you are constantly using different set of tools for coding. But it is not a justification :)

It also can be a better solution for more complex scenarios, when text preprocessing can do thing much more unreadable and complicated (think about parametrized input).


答:
The others have already explained why you should not do it. Your example obviously does not deserve being implemented with a macro. But, there is a wide range of cases where you have  to use macros for a sake of readability.

A notorious example of a wise application of such a technique is Clang project: see how .def files are used there. With macros and #include you can provide a single, sometimes entirely declarative definition for a collection of similar things which will be unrolled into types declarations, case statements wherever appropriate, default initialisers, etc. It increases maintainability significantly: you won't ever forget to add new case statements everywhere when you've added a new enum, for example.

So, as with any other powerful tool, you have to use C preprocessor carefully. There are no generic rules in the art of programming, like "you should never use this" or "you always have to use that". All the rules are nothing but guidelines.


问:
Why don't more languages support recursive/nested comments?

Possible Duplicate:

  Why do most programming languages not nest block comments?

Most languages I've worked with don't have support for recursive/nested comments.

Is there any reason why language designers would choose not to implement this?

Is it deceptively complex?

Would it have undesired results?

I know there could be issues such as:

```<code>/*
    string Str = "aslfkalfksnflkn/*aslkfasnflkn";

*/

Console.WriteLine("asdoadokn");
</code>```

However, we could still get the same issue with non-recursive ones (consider */ in a string in a comment) so i don't feel that's a good argument against.

答:
The problem is that recursive comments force you to actually parse the comments section, pushing it outside the scope of a normal lexer and possibly introducing more problems.

As a refresher: A compiler usually has a number of distinct stages with different jobs, and the first stages are the lexer, which gets the input program and separates it into a sequence of tokens (each of which contains a keyword, and identifier or an operator), and the parser, which structures this sequence of tokens into an abstract syntax tree (AST).

For the scope of a lexer, remember that lexing can normally be done by regular expressions. Bracket-like structures like recursive comments cannot be parsed by regular expressions (see context-free grammars), so the lexer would have to have much additional complexity, e.g. would need to be implemented via a recursive-descent parser.

Additionally, for C and similar languages (who most famously used the /**/ comment syntax) the need never arose to comment out large chunks of code, since they had the pre-processor and unused chunks of code were just wrapped by

```<code>#if 0
....
#endif
</code>```

which circumvented the parsing problem by delegating the problem to a second, much simpler compiler (the pre-processor).

Summarizing: Because recursive comments would make compiling more complicated, it's usually disallowed, and only languages with C-style comments, but without a preprocessor, really need it. That Java is amongst them is unfortunate, of course.

Edit: This doesn't mean recursive comments would be impossible or even very hard to do. You could use a recursive-descent lexer or could have a preprocessor before the lexer for filtering out comments. However, both approaches come with considerable cost compared to the standard model (use RE to auto-build the lexer and an EBNF to auto-build the parser), and the gain is pretty small.

Body:
The problem is that recursive comments force you to actually parse the comments section, pushing it outside the scope of a normal lexer and possibly introducing more problems.

As a refresher: A compiler usually has a number of distinct stages with different jobs, and the first stages are the lexer, which gets the input program and separates it into a sequence of tokens (each of which contains a keyword, and identifier or an operator), and the parser, which structures this sequence of tokens into an abstract syntax tree (AST).

For the scope of a lexer, remember that lexing can normally be done by regular expressions. Bracket-like structures like recursive comments cannot be parsed by regular expressions (see context-free grammars), so the lexer would have to have much additional complexity, e.g. would need to be implemented via a recursive-descent parser.

Additionally, for C and similar languages (who most famously used the /**/ comment syntax) the need never arose to comment out large chunks of code, since they had the pre-processor and unused chunks of code were just wrapped by

#if 0
....
#endif

which circumvented the parsing problem by delegating the problem to a second, much simpler compiler (the pre-processor).

Summarizing: Because recursive comments would make compiling more complicated, it's usually disallowed, and only languages with C-style comments, but without a preprocessor, really need it. That Java is amongst them is unfortunate, of course.

Edit: This doesn't mean recursive comments would be impossible or even very hard to do. You could use a recursive-descent lexer or could have a preprocessor before the lexer for filtering out comments. However, both approaches come with considerable cost compared to the standard model (use RE to auto-build the lexer and an EBNF to auto-build the parser), and the gain is pretty small.


答:
Comments that span over multiple lines should be the exception, not the rule.

Even in C, I use C++ style // instead of standard /* */.

If I absolutely need to comment out a large portion of code, I use #if 0 preprocessor directive, which supports nesting.

Title: Why don't more languages support recursive/nested comments?

Body:
Possible Duplicate:

  Why do most programming languages not nest block comments?

Most languages I've worked with don't have support for recursive/nested comments.

Is there any reason why language designers would choose not to implement this?

Is it deceptively complex?

Would it have undesired results?

I know there could be issues such as:

```<code>/*
    string Str = "aslfkalfksnflkn/*aslkfasnflkn";

*/

Console.WriteLine("asdoadokn");
</code>```

However, we could still get the same issue with non-recursive ones (consider */ in a string in a comment) so i don't feel that's a good argument against.


答:
I'm with you on this. When you work with large, old code bases, then those are littered with comments regarding hacks, commented out code, and other dirt and grit, let alone C interfaces documented in /*...*/ comments. If you need to comment out some of that, using /*...*/ comments is almost never an option, because they do not nest.

I don't believe "further complicating the compiler" is a reason either, because compared to the complexity of C++, parsing comments for /*, */ (and maybe //) should be laughably easy. In fact, I seem to remember Borland C++ (in the 90s) offering the option to parse nested comments - and that compiler used to be known for its lighting speed.

But the problem with non-standard solutions is that you cannot use them if you might have to port your code later. (And, in C++, who would ever rule out that?)

So I agree that it would be an improvement if this was standardized.

In the meantime, I use // comments to comment out chunks of code. Fortunately, most modern editors/IDEs have an option to apply this to several lines at once.


问:
Is JavaBeans a good example of encapsulation?
I'm trying to understand if JavaBeans is a good example of encapsulation. In my view, it's not as usually all the internal state is exposed through getters and setters.

A simple example is

```<code>public class Test {
    private List<String> names = new ArrayList<String>();

    public List<String> getNames() {
        return names;
    }

    public void setNames(List<String> names) {
        this.names = names;
    }
}
</code>```

This follows the JavaBeans standard but it leaks the implementation. For example a user could call test.getNames().clear().

Am I missing something?

答:
You're right. This is not a good example, and in fact code checkers like e.g. FindBugs will explicitly flag this ("Object exposes implementation by returning a reference to mutable field"). It's not quite as bad as public fields - a getter/setter implementation might one day be replaced by an implementation that does more logic than now, e.g. validation, logging etc., and then clients would receive the benefit of that without being recompiled, but even that won't stop people from relying on the semantics of getNames() being mutable.

A simple, good example of encapsulation is Collections.sort(). Decades of accumulated knowledge about performance and time/space trade-offs, sophisticated algorithms that the majority of programmers ould probably get subtly wrong if they had to write them themselves... and it's all yours for the price of one method call! Strive to emulate sort(), not getNames() in your code.


答:
This is recursion:

```<code>public void recursion()
{
    recursion();
}
</code>```

I have no idea what recursive comments would look like.

Nested comments on the other hand, would make sense, and actually already works to some extent. You can nest single line comments inside multiple line comments.

```<code>/* No longer use this!
// This is a method.
public void method()
{
}
*/
</code>```

Supporting what you are asking, from the point of perspective of the programmer, would make perfect sense.

```<code>/* No longer use this!
// This is a method.
public void method()
{
    /* Disabled!
       doInterestingStuff();
       ...
    */
}
*/
</code>```

Considering that programming languages are just tools in which programmers can express their intentions, supporting this intention would be an added value.

I can't comment on the technical aspects by heart, but it looks like some of the other answers already provided information on that.

Body:
This is recursion:

public void recursion()
{
    recursion();
}

I have no idea what recursive comments would look like.

Nested comments on the other hand, would make sense, and actually already works to some extent. You can nest single line comments inside multiple line comments.

/* No longer use this!
// This is a method.
public void method()
{
}
*/

Supporting what you are asking, from the point of perspective of the programmer, would make perfect sense.

/* No longer use this!
// This is a method.
public void method()
{
    /* Disabled!
       doInterestingStuff();
       ...
    */
}
*/

Considering that programming languages are just tools in which programmers can express their intentions, supporting this intention would be an added value.

I can't comment on the technical aspects by heart, but it looks like some of the other answers already provided information on that.


答:
Encapsulation is an overloaded expression, so let's define it first. According to Wikipedia encapsulation refers to two concepts:

In a programming language encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination thereof:

A language mechanism for restricting access to some of the object's components.

A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.

I would say that your typical JavaBeans class fulfills the second definition but almost never the first, so I guess the JavaBeans standard is not a good example of that particular notion of encapsulation.

Maybe slightly off topic, but explaining why something that starts with class in your code is not necessarily always a class in the more abstract sense.
I found a nice definition of class and data structure in Clean Code. Unfortunately I don't have the book here, so I need to recite from the top of my head:

A class encapsulates its state, only offering sensible methods and exposing state only where it is necessary.

A data structure fully exposes its state, not trying to hide anything from the outside world

A class implemented according to the JavaBeans standard would be a data structure according to the definition above. That maybe explains why it is a class in code but actually not a class that fulfills encapsulation.

Title: Is JavaBeans a good example of encapsulation?

Body:
I'm trying to understand if JavaBeans is a good example of encapsulation. In my view, it's not as usually all the internal state is exposed through getters and setters.

A simple example is

```<code>public class Test {
    private List<String> names = new ArrayList<String>();

    public List<String> getNames() {
        return names;
    }

    public void setNames(List<String> names) {
        this.names = names;
    }
}
</code>```

This follows the JavaBeans standard but it leaks the implementation. For example a user could call test.getNames().clear().

Am I missing something?


答: Newspeak has structured comments which can nest. And it has a very simple grammar, so it is obviously not "deceptively complex".


答:
usually all the internal state is exposed through getters and setters.

That may be the most common case, but usually the point of encapsulation is "provide a public interface behind which we can change things as needed" rather than "protect the implementation details like they were your firstborn sitting on a potty made of solid gold".

If it turns out the internal state has to be protected against manipulation, you can easily change the getter to return a defensive copy or a read-only wrapper.

And note that the real point of the JavaBeans standard is that the getter and setter don't necessarily access a private field - they can just as well convert to and from a field in a different format, you can have only a getter for a derived read-only property, or whatever you can imagine.

So I#d say that actually yes, the Java Beans standard is a good example for encapsulation, even though your typical JavaBean may not be.


问:
Get 100 highest numbers from an infinite list
One of my friend was asked this interview question -

"There is a constant flow of numbers coming in from some infinite list
  of numbers out of which you need to maintain a datastructure as to
  return the top 100 highest numbers at any given point of time. Assume all the numbers are whole numbers only."

This is simple, you need to keep a sorted list in descending order and keep a track on lowest number in that list. If new number obtained is greater than that lowest number then you have to remove that lowest number and insert the new number in sorted list as required.

Then question was extended -

"Can you make sure that the Order for insertion should be O(1)? Is it possible?"

As far as I knew, even if you add a new number to list and sort it again using any sort algorithm, it would by best be O(logn) for quicksort (I think). So my friend told it was not possible. But he was not convinced, he asked to maintain any other data structure rather than a list.

I thought of balanced Binary tree, but even there you will not get the insertion with order of 1. So the same question I have too now. Wanted to know if there is any such data structure which can do insertion in Order of 1 for above problem or it is not possible at all.

答:
Let's say k is the number of highest numbers you want to know (100 in your example).
Then, you can add a new number in O(k) which is also O(1). Because O(k*g) = O(g) if k is not zero and constant.

OwnerDisplayName: Sachin Shanbhag


答:
If by the question the interviewer really meant to ask “can we make sure each incoming number is processed in constant time”, then as many already pointed out (e.g. see @duedl0r's answer), your friend's solution is already O(1), and it would be so even if he had used unsorted list, or used bubble sort, or whatever else. In this case the question does not make much sense, unless it was tricky question or you remember it wrong.

I assume the interviewer's question was meaningful, that he was not asking how to make something to be O(1) which is very obviously already that.

Because questioning algorithm complexity only makes sense when size of input grows indefinitely, and the only input that can grow here is 100—the list size; I assume the real question was “can we make sure we get Top N spending O(1) time per number (not O(N) as in your friend's solution), is it possible?”.

The first thing that comes to mind is counting sort, which will buy complexity of O(1) time per number for Top-N-problem for the price of using O(m) space, where m is the length of range of incoming numbers. So yes, it is possible.

Title: Get 100 highest numbers from an infinite list

Body:
One of my friend was asked this interview question -

"There is a constant flow of numbers coming in from some infinite list
  of numbers out of which you need to maintain a datastructure as to
  return the top 100 highest numbers at any given point of time. Assume all the numbers are whole numbers only."

This is simple, you need to keep a sorted list in descending order and keep a track on lowest number in that list. If new number obtained is greater than that lowest number then you have to remove that lowest number and insert the new number in sorted list as required.

Then question was extended -

"Can you make sure that the Order for insertion should be O(1)? Is it possible?"

As far as I knew, even if you add a new number to list and sort it again using any sort algorithm, it would by best be O(logn) for quicksort (I think). So my friend told it was not possible. But he was not convinced, he asked to maintain any other data structure rather than a list.

I thought of balanced Binary tree, but even there you will not get the insertion with order of 1. So the same question I have too now. Wanted to know if there is any such data structure which can do insertion in Order of 1 for above problem or it is not possible at all.

OwnerDisplayName: hamstergene


答: this one is easy if you know Binary Heap Trees. Binary heaps support insertion in average constant time, O(1). And give you easy access to the first x elements.</p>

OwnerDisplayName: Chris