答:
I've been developing with PHP for 8 years now - since I was 16.  I meet people of all ages, shapes and sizes and backgrounds.  I agree with most of MainMa's points, but let me add some emphasize and  a few points of my own.

Passion & Motivation

This is the most important thing by far.  Strive to be the best (you can be), and eventually you will.  It takes true passion for problem solving and honing your craft.  You can tell in 5 seconds if somebody is passionate.  When you ask them a question, do they instantly engage, or do they give a two-word response?  If you recommend something, do they come back and tell you about it after?

Dedication

Software development is a craft that can take decades to master. They say it takes 10,000 hours to master something, but I think when working with a moving target like software development, it's much more.  If you work full time, you will hit that mark every few years so you can constantly re-invent yourself.  Being able to stick with something this long requires an enormous amount patience & again, passion.  Be wary of the people with 10/15 years of experience who are not incredible.  They are not dedicated, and probably lost the passion a decade ago.  15 years of experience is not the same as 1 year of experience 15 times.

Hunger for Knowledge

It takes constant learning and defeat.  It should be downright embarassing/depressing looking at code from the previous year  If it's not, then you aren't learning enough. Find the people who are at the top and learn everything you can from them.  Typically that's key open source contributors (for PHP: Symfony, Zend, PHPUnit/Behat/etc. developers). They are the ones who train everyone else. When somebody tells you X is better than Y, do your own research.  They are usually sheep who were told that 5 years ago and still preach it.  I've actually this site to be an amazing resource.  I find a very wide range of content which usually leads back to the same key people or principals (Martin Fowler, Uncle Bob, etc., DDD, etc.)

PHP Sucks

Whatever.  If people want to rag on you/PHP, don't let it get you down.  If you follow the key development principles and actually build software, then keep on keeping on.  PHP has come a long way and it's not the ugly duckling it used to be. Learn from other languages, and mess around with others once and a while.  You may like them more, or you may not.  Either way, it'll widen your knowledge and introduce you to new patterns or practices that aren't popular or even possible in PHP.

Network

Start building a brand for yourself.  Blog.  Attend meetups/conferences. Reach out to others on Twitter.  Find a community/niche to engage with.  Contribute to open-source projects.  Programming is a very social job now.  Don't isolate yourself, and make your work known.  The sooner you do this, the sooner you'll build relationships with great developers who will take you under their wing, and the sooner you'll find decent clients/employers rather than the crappy ones that everyone else works for.

Title: Hallmarks of a Professional PHP Programmer

Body:
I'm a 19 year old student who really REALLY enjoys programming, and I'm hoping to glean from your years of experience here. At present, I'm studying PHP every chance I get, and have been for about 3 years, although I've never taken any formal classes. I'd love to some day be a programmer full time, and make a good career of it.

My question to you is this: What do you consider to be the hallmarks or traits of a professional programmer? Mainly in the field of PHP, but other, more generalized qualifications are also more than welcome, as I think PHP is more of  a hobbyist language and may not be the language of choice in the eyes of potential employers. Please correct me if I'm wrong. Above all, I don't want to waste time on something that isn't worth while.

I'm currently feeling pretty confident in my knowledge of PHP as a language, and I know that I could build just about anything I need and have it "work", but I feel sorely lacking in design concepts and code structure. I can even write object oriented code, but in my personal opinion, that isn't worth a hill of beans if it isn't organized well. For this reason, I bought Matt Zandstra's book "PHP Objects, Patterns, and Practice" and have been reading that a little every day.

Anyway, I'm starting to digress a little here, so back to the original question. What advice would you give to an aspiring programmer who wants to make an impact in this field?

Also, on a side note, I've been working on a project with a friend of mine that would give a fairly good idea of where I'm at coding wise. I'm gonna give a link, I don't want anyone to feel as though I'm pushing or spamming here, so don't click it if you don't want to. But if you are interested on giving some feedback there as well, you can see the code on github. I'm known as The Craw there.

https://github.com/PureChat/PureChat--Beta-/tree/


问:
Code maintenance: To add comments in code or to just leave it to the version control?
We have been asked to add comments with start tags, end tags, description, solution etc for each change that we make to the code as part of fixing a bug / implementing a CR.

My concern is, does this provide any added value? As it is, we have all the details in the Version control history, which will help us to track each and every change?

But my leads are insisting on having the comments as a "good" programming practice. One of their argument is when a CR has to be de-scoped/changed, it would be cumbersome if comments are not there.

Considering that the changes would be largely in between code, would it really help to add comments for each and every change we make? Shouldn't we leave it to the version control?

答:
I usually follow this rule: if the change is obvious and the resulting code does not raise questions, does not revert or substantially change any previous behavior in a substantial way - then leave it to the VCS to track bug numbers and other change information.

However, if there is the change that is not obvious, that changes the logic - especially substantially changes the logic done by somebody else in a non-obvious way - it may be very beneficial to add something like "this change is to do this and that because of bug #42742". This way when somebody looks at the code and wonders "why is this here? this looks weird" he has some guidance right in fron of him and does not have to do investigation via VCS. This also prevents situations where people break other's changes because they are familiar with old state of the code but do not notice it has been changed since.

ContentLicense: CC BY-SA 3.0


问:
What should I study to 'learn' Comp Sci?
[This question was originally asked on Stack Overflow, but recommended to move the question here.]

I can't find anything quite like the question I'm about to ask, so please forgive me if there's something just like it already, please feel free to point me in the right direction. It'll take a bit of background explaining too, please forgive me for that.

[backstory]

Basically, I graduated from University about 18 months ago with a degree in Business Information Systems and Japanese. The Japanese took up half of the degree so the BIS was only joint. I only learned PHP in terms of languages and basically no computing theory - everything was vocational (Networking, programming basics, CMS development, Office and VBA and then loads of Business theory courses).

Since this, I decided to teach myself C# and ASP.Net and try to get a position as a programmer. I created an online shop style website and a small CRM application in Windows Forms to both teach myself and build a portfolio, and luckily I managed to snag a developer position.

Bad side? I'm the only developer at my company. Now don't get me wrong, in the last year I've learned loads and loads, I did some devpt. before Uni so knew the basics anyway, but it was very much a "learning from books" job - every night.

Now then... I am now at a point where I'm building software on a regular basis, making good judgements for time scales, and have even been told my code and methodology are good by other professionals that have been in the game longer than me, and they have offered me jobs.

[/backstory]

What this whole thing boils down to, is that I now want to study up on the topics I'll have missed by not doing CS. More importantly, could you recommend books / free online courses? I want to learn about Computer Science theory, not just better coding.

Thank you!

答:
Math.

You need to be really good at math.  Not quite as much because you are likely to encounter the need to solve differential equations in order to write your code, but because you need the same skills it takes to solve math problems to be really good at software engineering.  I recommend taking a few upper lever math classes at your local community college.  Perhaps a numerical methods or discrete math class first.

I took a class in software engineering for my degree in computer science a few years ago that the professor used some of the material from MIT's open course-ware.  He used course 6.170.  I recommend going through that class and a good course on object oriented programming and especially design patterns.  If you still have time and want to learn more, move on to artificial intelligence and theory of computation studies.  If I had to to pick a single course that was most helpful in my career as a developer, it would be the studies on design patterns.

Because I have a low reputation, I can't post more links.  Do a Google search for "gang of four design patterns" for the book that is classically used to teach that subject.

Good luck!

ContentLicense: CC BY-SA 2.5


问:
see what ARC does?
If I understand correctly, all ARC does is automatically add memory-management statements such as retain and autorelease in the proper places in a program. Is there any way to see all the memory-management statements that ARC automatically adds to a program?

答: In Xcode's assistant editor, choose to view the Assembly for the file you're working on. You should see calls to functions like objc_retain and similar; these are the functions inserted by the compiler to support ARC.

Title: see what ARC does?


答:
Comments in the code should be minimal and accurate. Adding defect /change information not valuable. You should use version control for it.   Some time Version control provides a slightly better way of change- We use ClearCase UCM ; UCM  activities are created based on defect numbers, change area etc (  e.g. defect29844_change_sql_to_handle_null).

Detailed comments is preferred in check-in comments.

I prefer to include provide details about back ground information, details of solution NOT implemented due some side effects.

Pramagic Programmer and CleanCode leads to following guideline

Keep the low-level knowledge in the code, where it belongs, and reserve the comments for other, high-level explanations.

Title: Code maintenance: To add comments in code or to just leave it to the version control?

Body:
We have been asked to add comments with start tags, end tags, description, solution etc for each change that we make to the code as part of fixing a bug / implementing a CR.

My concern is, does this provide any added value? As it is, we have all the details in the Version control history, which will help us to track each and every change?

But my leads are insisting on having the comments as a "good" programming practice. One of their argument is when a CR has to be de-scoped/changed, it would be cumbersome if comments are not there.

Considering that the changes would be largely in between code, would it really help to add comments for each and every change we make? Shouldn't we leave it to the version control?


问:
Criteria for a programming language to be considered "mature"
I was recently reading an answer to this question, and I was struck by the statement "The language is mature".

So I was wondering what we actually mean when we say that "A programming language is mature"? Normally, a programming language is initially developed out of a need, e.g.

Try out / implement a new programming paradigm or a new combination of features  that cannot be found in existing languages.

Try to solve a problem or overcome a limitation of an existing language.

Create a language for teaching programming.

Create a language that solves a particular class of problems (e.g. concurrency).

Create a language and an API for a special application field, e.g. the web (in this case the language might reuse a well-known paradigm, but the whole API must be new).

Create a language to push your competitor out of the market (in this case the creator might want the new language to be very similar to an existing one, in order to attract developers to the new programming language and platform).

Regardless of what the original motivation and scenario in which a language has been created, eventually some languages are considered mature. In my intuition, this means that the language has achieved (at least one of) its goals, e.g. "We can now use language X as a reliable tool for writing web applications."

This is however a bit vague, so I wanted to ask what you consider the most important criteria (if any) that are applied when saying that a language is mature.

IMPORTANT NOTE

This question is (on purpose) language-agnostic because I am only interested in general criteria. Please write only language-agnostic answers and comments!
I am not asking whether any specific "language X is mature" or "which programming languages can be considered mature", or whether "language X is more mature than language Y": please avoid posting any opinions or reference about any specific languages because these are out of the scope of this question.

EDIT

To make the question more precise, by criteria I mean such things as "tool support", "adoption by the industry", "stability", "rich API", "large user community", "successful application record", "standardization", "clean and uniform semantics", and so on.

答:
I've actually had the same wondering a few years back. Back then, I decided that a language is mature (i.e. good for solving problems of type x) if it has most of the necessary features needed to solve that problem. In other words, how much of the specific problem solving tools I have to create myself vs. how many already come with the language. As per your comment I'm removing the language-speific example and replacing it with a language agnostic one:

I basically thought that a language having a lot of built in "helper" and "utility" libraries is more mature than one in which some of those didn't exist (and in which I'd have to write them - or something similar to them - myself)

I'm talking about all this in the past because these days I've pretty much ditched that way of thinking, and think of a language's maturity more like this:

how strong the community is for that language. How many docs, books, pertinent examples are there. This is important, because you can have languages which are very nice, and may be better suited for some specific task than others, but which are poorly documented, so that you never get to see their advantages.

performance. For a given task, and a given x implementation, the language in which that implementation will run faster is more mature. Yes, this is a very gray area, and for most languages and platforms it's hard to make the comparison. However for certain languages and platforms it's quite straight forward to see which one out-performs which. For certain kind of problems this is very important.

bugs. Oh yes. I never would have thought of this until I've seen it with my own eyes. I'm not gonna give any examples because I don't want to seem like I'm bashing one language or another, but there are languages out there (well, more precisely, compile and run-time environments for certain languages) which are very buggy, to the point where you can no longer trust and estimate how something will work. To me the maturity of a language falls heavily when this is the case.

The reasons why I switched the way I think of a language as more mature are :

first off, the fact that a language has a ton of helper libraries and utilities might not always mean that they're actually useful. Those libraries are still generic, and they may be a long way away from some specific need you have, such that in the end I tend to rewrite myself part of them to have a more efficient, problem-specific solution.

furthermore, things such as language & platform performance and documentation are things for which it's harder to compensate than it is with lack of libraries. If the code you wrote in language x and platform y is slow, optimizing it by yourself will never be as good as replacing it with language x2 and platform y2 for which a cohort of (probably smarter) people than myself have done optimizations. Same goes for documentation, the lack of it translates in more time spend on doing proof of concepts, trials and error, source and unit test code exploring in order to see how something must be done. And even if you go through all this, you still don't know if the solution you've chosen is the most suited, as the language creators intended for it to work.


问:
How do you learn a new programming language?
I am C++ developer with some good experience on it. When I try to learn a new language ( have tried Java, C#, python, perl till now) I usually pickup a book and try to read it. But the problem with this is that these books typically start with some very basic programming concepts such as loops, operators etc and it starts to get very boring soon. Also, I feel I would get only theoeritcal knowledge without any practical knowledge on writing the code. So my question is how do you tacke these situations? do you just skip the chapters if its explaining something basic? also, do you have some standard set of programs that you will try to write in every new programming language you try to learn?</p>

答:
You have many ways to learn a new programming language. I'd go with this method:

Choose the programming language you want to learn first

Read Books about it and watch good online tutorials

Connect to an online open source code repository and download some projects

Use the books and your brain to connect the dots with the "real life" code from the code repository

That way you'll learn the language itself and get to see how it is used in "real life".

Most important: Don't try to learn more than ONE language at the time. You'll screw it up.


问:
What is the best approach to solve a factory method problem which has to be an instance?
I have to add new funcionality in a web service legacy project and I'm thinking what is the best approach for a concrete situation.

The web service is simple: It receives a XML file, unmarshalling, generates response's objects, marshalling and finally it sends the response as a XML file. For every XML files received, the web service always responds with the same XML structure.

What I have to do is to generate a different XML file according to the XML received. So I have a controller class which has all marshalling/unmarshalling operations, but this controller class has to be an instance. Depending on XML received I need some marshalling methods or others.

Trying to make few changes on legacy source, what is the best approach? My first approach was to do a factory method pattern with the controller class, but this class has to be an instance.

I want to keep, as far as it goes, this structure:

```<code>classController.doMarshalling();
</code>```

I think this one is a bit smelly:

```<code>if(XMLReceived.isTypeOne())
    classController.doMarshallingOne();
else if(XMLReceived.isTypeTwo())
    classController.doMarshallingTwo();
else if(XMLReceived.isTypeThree())
    classController.doMarshallingThree();
else if ...
</code>```

I hope my question is well understood

答: You could use the Strategy pattern. It does exactly what you want, it executes different algorithms for different scenarios which are often related. The wikipedia article  gives an example implementation for java.</p>


问:
Clarification on the Strategy Pattern
I've just been reading through some basic design patterns,

Could someone tell me if the term "strategy pattern" only applies if your implementing a completely abstract interface?

What about when your children (concretes?) inherit from a parent class (the strategy?) with some implemented methods and some virtual and/or abstract functions? Otherwise the rest of the implementation, the idea that you can switch between different children at run time, is identical. This is something i'm quite familiar with, i was wondering if you would still call it the Strategy Pattern or if that term only applies to using an interface.

Apologies if this question is not appropriate! Or if this is just nitpicking :) I'm still learning and i'm not really sure if design patterns are quite heavily defined within the industry or just a concept to be implemented as you like.

答:
A strategy is simply where an object takes in something that defines how it should handle some behavior. It might be an implementation of an abstract base class, it might be a script, it might be a functor, it could be any number of things.

The pattern itself is a design that uses this concept.

Title: Clarification on the Strategy Pattern


问:
Which paradigm to use for writing chess engine?
If you were going to write a chess game engine, what programming paradigm would you use (OOP, procedural, etc) and why whould you choose it ? By chess engine, I mean the portion of a program that evaluates the current board and decides the computer's next move.

I'm asking because I thought it might be fun to write a chess engine. Then it occured to me that I could use it as a project for learning functional programming. Then it occured to me that some problems aren't well suited to the functional paradigm. Then it occured to me that this might be good discussion fodder.

答:
I ported a simple chess program as a means of learning the Forth language. It turned out to be a great fit to this very imperative problem, and I learned a lot. The open stack allowed me to implement alpha-beta search in a unique fashion which gave me greater insight into the algorithm.

One would think that functional programming would be great for chess programs, since the core algorithms (alpha-beta depth-first search, evaluation) are recursive and functionally strict.  However, a chess program lives and dies on efficiency and none of the current crop of functional languages have that aim. The top one hundred state-of-the-art engines all use imperative languages (mostly C/C++, then Delphi) in order to have maximum control over memory usage, multi-threading, global state, and code generation. All functional languages use dynamic memory allocation for core data structures, which is death for a chess program.

I'd still like to see someone make an attempt to break into the top 100 chess engines using a functional language.


答:
Acceptance Factors

I'd say a combination of various things, but I don't think they are all required. Some languages considered mature nowadays clearly do not satisfy some of these.

I'd say a combination of:

Tooling:

mainline: At least one stable "official" or widely-accepted (de-facto or vendor-recommended/supported) tool suite (compiler, interpreter, vm, editor).

alternative: Some stable and not-so-stable alternatives of the above tooling (closed or open source variants, free or commercial variants, extensions, etc...).

Community: An active , but not necessarily large group of followers and contributors.

Recognition:

Some degree of recognition and use by some industrial actors (even if in a niche).

Some degree of recognition in popular culture (even if in a niche).

On Fame, Recognition and Maturity

Note that the differentiator here is on having strong and active criteria validators, not large or numerous ones. To clarify, consider these vastly different examples:

Ruby was for a long-time a language with a large community-backing, an official reference implementation and so forth but could hardly be considered mature until it ironed out some of its rough edges. It was famous before being mature.

On the other hand of the spectrum, some once very-widely used languages (COBOL, FORTRAN...) are now less visible but are still mature in every possible sense. They were once famous and mature.

Also, some niche-languages are in my view definitely mature, inspite of their small (but established) market penetration. Consider Oberon or Limbo. They are mature but never got famous. Others, like R, are relatively famous in that their "niches" aren't really niches (bugs me when people call things like Scala or Clojure "niche languages", which they definitely aren't), though their field of applications are not exactly what you'd call mainstream.

On Stability

What's stable anyways? It's quite relative...

Compliance?

To the standard (if there's one)?

To a reference implementation (if there's one)?

Number of bugs? (hardly a good measure)

Use in critical environments?

In general, stability simply means I don't get surprised on a daily basis when going about my average job using the language's toolkit, and I can get definitive answers on what should or should not happen when I attempt to do something with the language and its toolkit, whether it's at the build-time or runtime of my programs.

But stability for someone writing smartphone apps and stability for someone writing medical or avionics systems is a different kind of bird.

Title: Criteria for a programming language to be considered "mature"

Body:
I was recently reading an answer to this question, and I was struck by the statement "The language is mature".

So I was wondering what we actually mean when we say that "A programming language is mature"? Normally, a programming language is initially developed out of a need, e.g.

Try out / implement a new programming paradigm or a new combination of features  that cannot be found in existing languages.

Try to solve a problem or overcome a limitation of an existing language.

Create a language for teaching programming.

Create a language that solves a particular class of problems (e.g. concurrency).

Create a language and an API for a special application field, e.g. the web (in this case the language might reuse a well-known paradigm, but the whole API must be new).

Create a language to push your competitor out of the market (in this case the creator might want the new language to be very similar to an existing one, in order to attract developers to the new programming language and platform).

Regardless of what the original motivation and scenario in which a language has been created, eventually some languages are considered mature. In my intuition, this means that the language has achieved (at least one of) its goals, e.g. "We can now use language X as a reliable tool for writing web applications."

This is however a bit vague, so I wanted to ask what you consider the most important criteria (if any) that are applied when saying that a language is mature.

IMPORTANT NOTE

This question is (on purpose) language-agnostic because I am only interested in general criteria. Please write only language-agnostic answers and comments!
I am not asking whether any specific "language X is mature" or "which programming languages can be considered mature", or whether "language X is more mature than language Y": please avoid posting any opinions or reference about any specific languages because these are out of the scope of this question.

EDIT

To make the question more precise, by criteria I mean such things as "tool support", "adoption by the industry", "stability", "rich API", "large user community", "successful application record", "standardization", "clean and uniform semantics", and so on.


问:
Scripting language for filling out web form
I have a job as an intern at a technology company, I was given the unfortunate job of performing some data entry into our web management system. The information entered into the web form is stored in a MySQL DB. Upon receiving the data I realized I would have to submit this online form about 1000 different times all consisting of about 10 different text fields / check boxes per form. (So in other words, would be completely mind numbing and be a ridiculous waste of time and resources, or so I thought...)

Having used databases a good bit prior to this, my immediate reaction was to just write a short MySQL script to bulk import all of the data, especially since it was already presented to me in an excel spreadsheet ready to go. Thought it may have been some sort of a test since it seemed too obvious. I wrote the script which consisted of about 10 lines of code but was then informed I couldn't be trusted with MySQL Admin privileges to run said script. So my next thought would be to write a script to just enter the information through the web form (Which will take ten times longer but it's what I have to)

Being unfamiliar with scripting of this nature (seems like I would need something similar to a bot, but the good kind) I was unsure of how to proceed to do this. Is there a preferred language to use to enter the data i have into the web form I do have access to? I'm not particularly looking for this to be done for me by any means just a nice point in the right direction as far as what scripting language to use and how to pair that with the data I have that needs to be entered.

Thanks for the help/ valuable input!

EDIT:

Is there a way to perform this using perl without having access to place any files on the server?

Would I be able to run some Javascript loops to pull the data out of .csv or just a .txt format with line delimiters and insert it into the web form?

答:
I think haylem's answer provides the best set of options. That said, I'd like to mention Autohotkey if you are on a Windows platform. It is a decent scripting language, but very strong for automating GUI tasks.

I agree that posting the data directly is the best way to go but there are situations when this doesn't work as easily. An example would be if your administration system requires a login and then tracks an authentication ticket of some sort using client-side state. You could certainly emulate this using headless HTTP, but it adds complexity to the problem. At some point it might become easier to manipulate the browser directly. Autohotkey is a good choice for this. It's just a scripting language so it's not as heavy as Selenium, and it can be useful for other unrelated tasks as well.


问:
Is COBOL still worth learning?
Does learning COBOL still make sense?</p>

答:
If you can see yourself as COBOL programmer, then go for it. There are still billions of lines written in COBOL that require maintenance.

Actually, there is no such thing as unnecessary knowledge, so broaden the knowledge and wider opportunities you (will) have.

Title: Is COBOL still worth learning?


问:
Design suggestions needed to create a MathBuilder framework
Let explain what I'm trying to create. I'm creating a framework, the idea is to provide base classes to generate a math problem.

Why do I need this framework? Because at first time, I realized when I create a new math problem I always do the same steps.

Configuration settings such range numbers. For example if I'm developing multiplications, in beginner level only generate the first number between 2-5 or in advanced level, the first number will be between 6- 9, for example.

Generate problem method. All the time I need to invoke a method like this to generate the problem. This one receives the configuration settings and generate the number according to them. And generate the object with the respective data.

Validate the problem. Sometimes the problem generated is not valid. For example, supposed I'm creating fractions in most simplified, if I receive 2/4, the program should detect that this is not valid and must generate another like this one, 1/4.

Load the view. All of them, have a custom view (please watch below the images).

All of the problems must know how to CHECK if the user result is correct.

All of this problems has answers. Some of them just require one answer, anothers may require more than one, so I guess a way to maintain flexibility to the developer has all the answers he wanna used.

At the beginning I started using PRISM. Generate modules for each math problem was the idea and load it in the main system.

I guess are the most important things of this idea.

Let me showing some problems which I create in a WPF standalone program. Here I have a math problem about areas. When I generate the problem a set to the view the object and it draw it.

In beginner level, I set in the configuration settings that just load square types. But in advance level, can load triangles and squares randomly.

In this another, generate a binary problem like addition, subtraction, multiplication or division.

Above just generate a single problem. The idea of this is to show a test o quiz, I mean get a worksheet (this I call as a collection of problems) where the user can answer it.

I hope gets the idea with my ugly drawing.

How to load this math problems? As I said above, I started using PRISM, and each module contains a math problem kind. This is a snapshot of my first demo.

Below show the modules loaded, and center the respective configurations or levels.

Until momment, I have no idea to start creating this software. I just know that I need a question | problem class, response class, user class.

But I get lost about what properties should have to contain in it.

Please give a little hand of this framework. I put much effort on this question, so if any isn't clear, let me know to clarify it.

答:
Turn the problem into a group of smaller problems (Modules if you like) that each have a single responsibility. For example "Generate problem method" is too high level to think about implementing. (considering all the different types of problems you have talked about generating: Worksheets, Diagrams etc.) If you split it into smaller parts you can then focus on solving each of these parts. You can then split these problems further if need be.

It seems to me like it is slightly too early for you to be thinking about classes. A helpful step can be thinking about these different modules of the program and how you will test them, if you cannot think of how you would go about testing them then you don't have a clear picture of their intended purpose.

Also, you will need a strong architecture to be able to build this efficiently, you have a lot of shared components such as validating the problems and the graphical interface but the problems themselves can be very different. I'm currently reading Design Patterns: Elements of Reusable Object-Oriented Software and would recommend it.


答:
Could someone tell me if the term "strategy pattern" only applies if
  your implementing a completely abstract interface?

Strategy pattern is about choosing the algorithm at runtime; technically the algorithm is ran by calling a function, so only that function needs to be abstract/left unimplemented. If all the similar algorithm call other function, independent of the algorithm, those functions can be pushed in the superclass.

For example you implement a strategy pattern for saving something in a file; depending on something else you could be saving it in XML or binary format. You can implement the logic of saving the data in a file in the superclass (since it's common to all implementation) and the logic of converting the data in XML in a subclass and in binary in a another subclass.

The idea behind patterns is not a rigorous implementation but an idea of design; you can implement it as you find it suitable for your particular problem.

Title: Clarification on the Strategy Pattern

Body:
I've just been reading through some basic design patterns,

Could someone tell me if the term "strategy pattern" only applies if your implementing a completely abstract interface?

What about when your children (concretes?) inherit from a parent class (the strategy?) with some implemented methods and some virtual and/or abstract functions? Otherwise the rest of the implementation, the idea that you can switch between different children at run time, is identical. This is something i'm quite familiar with, i was wondering if you would still call it the Strategy Pattern or if that term only applies to using an interface.

Apologies if this question is not appropriate! Or if this is just nitpicking :) I'm still learning and i'm not really sure if design patterns are quite heavily defined within the industry or just a concept to be implemented as you like.


问:
Naming methods that do the same thing but return different types
Let's assume that I'm extending a graphical file chooser class (JFileChooser).

This class has methods which display the file chooser dialog and return a status signature in the form of an int: APPROVE_OPTION if the user selects a file and hits Open /Save, CANCEL_OPTION if the user hits Cancel, and ERROR_OPTION if something goes wrong. These methods are called showDialog().

I find this cumbersome, so I decide to make another method that returns a File object: in the case of APPROVE_OPTION, it returns the file selected by the user; otherwise, it returns null. This is where I run into a problem: would it be okay for me to keep the showDialog() name, even though methods with that name — and a different return type — already exist? To top it off, my method takes an additional parameter: a File which denotes in which directory the file chooser should start.

My question to you: Is it okay to call a method the same name as a superclass method if they return different types? Or would that be confusing to API users? (If so, what other name could I use?)

Alternatively, should I keep the name and change the return type so it matches that of the other methods?

```<code>public int showDialog(Component parent, String approveButtonText) // Superclass method
public File showDialog(Component parent, File location) // My method
</code>```

答:
Why do you need to extend this class? And why do you need to name your own method the same as showDialog?

In reality your method does something entirely different than what showDialog does. A better name for your method would be showDialogAtLocationAndReturnSelectedFile as your method does more or less these things. Naming it showDialog will only confuse your code users.

Also, without knowing anything else, I'd say you're trying to shove too much in a single method. How do you react on a cancel press? How about an error? Do you return null? If so, you're forcing the user of the code to check the return value yet again. This has the potential of being just another "Leaky Abstraction", and Java APIs already have enough of these.

An important part of API design is making sure that the name of a function/class/method matches what it really does. And that is why in JFileChooser the method's name is showDialog. It just shows the dialog. It doesn't open the file for reading, it doesn't perform a check whether the filename is valid, and honestly, why would it? The user of the code just asked the class to show the dialog.

The creator of Ruby calls this the 'Principle of Least Surprise'*, and while I don't really know Ruby, this is a great line to learn from. Your code should be in the service of its user, and a part of this service is embedding the contract of the method/class in its name.

You might think you're not designing an API, but I doubt you work alone: there's probably someone else in the team, and they will appreciate this. Also, I heartily recommend this lecture on API Design: How To Design A Good API and Why it Matters. It was presented to Googlers by a Java designer, so it kinda matters.

Maybe this is more than you asked for, but I feel you seem to be somewhat missing the point of naming methods.

UPDATE: * I seem to be mistaken, the creator of Ruby has actually stated that he designed Ruby with the "Principle of Least Astonishment", not "Principle of Least Surprise". In any case, what I said still holds.


问:
reference datatype javascript
In javascript, what is the difference in applying a toString() method to the primitive datatype, number like this

```<code>var myString = myNumber.toString();
</code>```

and applying the same toString() method by creating a reference datatype equivalent, the Number class like this

```<code>var numberObject = new Number(myNumber);
var myString = numberObject.toString();
</code>```

答:
In a chrome console if you type:

```<code>new Number(10).toString === (10).toString
</code>```

It returns true, so I suppose there is no difference between the two since both functions refers to the same reference.

Title: reference datatype javascript

Body:
In a chrome console if you type:

new Number(10).toString === (10).toString

It returns true, so I suppose there is no difference between the two since both functions refers to the same reference.


答:
Both are equivalent and give the same result.

JavaScript allows to create objects without using new keyword.

For example, you may create an array using new Array(1, 2, 3), but you may also use the shorter syntax [1, 2, 3].

Use shorter notations ((123).toString(), "hello ".trim(), [1, 2, 3].reverse(), etc.) whenever possible. They are explicit enough, so there is no need to pass by a verbose new <Type>() notation.

Title: reference datatype javascript

Body:
In javascript, what is the difference in applying a toString() method to the primitive datatype, number like this

```<code>var myString = myNumber.toString();
</code>```

and applying the same toString() method by creating a reference datatype equivalent, the Number class like this

```<code>var numberObject = new Number(myNumber);
var myString = numberObject.toString();
</code>```


问:
Programming C++ using Qt4
Hey guys I am really new to the C++ programing I have a little knowledge in C and a bit more in C++, but I do not know them enough to call myself a programmer. I am working as a PHP Web Developer I like being a crafts man and creating things so that is the reason to combine the programming with web development. I think that I could really benefit from both of them and so... My question is:

Is it a good Idea to learn C++ with Qt or not?

Can you give me pros and cons of both?

Note: I do not want to become a programmer and give up the web development I want to combine them both.

答:
Make sure that you know the concepts of object oriented programming, and the specific way in which C++ implements it. Some examples could be operator overloading and multiple inheritance.

I would start by building simple console applications, because they are an easy way to have quick feedback about what you are doing.

When you will have already some knowledge of C++ programming, using any Qt will be fun, because you will be able to draw windows and UI controls etc.

Looking at a library is good because it gives you a good example about how you can structure your code.

Title: Programming C++ using Qt4


问:
REST API wrapper - class design for 'lite' object responses
I am writing a class library to serve as a managed .NET wrapper over a REST API. I'm very new to OOP, and this task is an ideal opportunity for me to learn some OOP concepts in a real-life situation that makes sense to me.

Some of the key resources/objects that the API returns are returned with different levels of detail depending on whether the request is for a single instance, a list, or part of a "search all resources" response. This is obviously a good design for the REST API itself, so that full objects aren't returned (thus increasing the size of the response and therefore the time taken to respond) unless they're needed.

So, to be clear:

.../car/1234.json returns the full Car object for 1234, all its properties like colour, make, model, year, engine_size, etc. Let's call this full.

.../cars.json returns a list of Car objects, but only with a subset of the properties returned by .../car/1234.json. Let's call this lite.

...search.json returns, among other things, a list of car objects, but with minimal properties (only ID, make and model). Let's call this lite-lite.

I want to know what the pros and cons of each of the following possible designs are, and whether there is a better design that I haven't covered:

Create a Car class that models the lite-lite properties, and then have each of the more detailed responses inherit and extend this class.

Create separate CarFull, CarLite and CarLiteLite classes corresponding to each of the responses.

Create a single Car class that contains (nullable?) properties for the full response, and create constructors for each of the responses which populate it to the extent possible (and maybe include a property that returns the response type from which the instance was created).

I expect among other things there will be use cases for consumers of the wrapper where they will want to iterate through lists of Cars, regardless of which response type they were created from, such that the three response types can contribute to the same list.

Happy to be pointed to good resources on this sort of thing, and/or even told the name of the concept I'm describing so I can better target my research.

答:
Based on your description, I would use option three. Option two is probably the worst of the bunch since you would be maximizing duplication and minimizing reuse.

Option one is the inheritance model. I don't feel like it's a good fit for the situation. The resulting class hierarchy will introduce complexity but you won't be gaining much in the trade-off. Inheritance can be very useful when you have a number of different objects which all share a common superclass. In this case you really only have one type of object (a car), you just have varying levels of completeness.

With your single car class from option three, there are some good tricks you can use like lazy loading of properties. Basically if your class has been filled with the least amount of data possible then in the getter of the other properties you can trigger a call out to the more detailed API and fill in the rest of the information. Be careful to model this type of behavior around actual usage patterns the object may see, but it can greatly help with ease of use for other programmers who consume your object.


答:
The major problem I can see with this is that if I use your method like this:

```<code>chooser.showDialog(parent,location).getPath()
</code>```

it will work perfectly most of the time, but if the user changes their mind about loading a file and hits cancel, the program will crash.  You could say that I shouldn't write code like that, and you'd be right, but people do write code like that sometimes.  The method as written isn't convenient, since you still have to check for null, and it's a bit of a trap for anyone not paying sufficient attention.

As far as I can tell, you're trying to abstract out 2 method calls into one, but it's quite possible that the new method would be just as cumbersome after factoring in the need for a null check.  It's possible that the whole workflow you're dealing with could be reasonably abstracted, in which case whatever you'd call the whole workflow would probably make a good name for a method.

To answer your actual question, I don't think that having methods of the same name that return different types is automatically bad, but names and return types should never be confusing.

Title: Naming methods that do the same thing but return different types

Body:
Let's assume that I'm extending a graphical file chooser class (JFileChooser).

This class has methods which display the file chooser dialog and return a status signature in the form of an int: APPROVE_OPTION if the user selects a file and hits Open /Save, CANCEL_OPTION if the user hits Cancel, and ERROR_OPTION if something goes wrong. These methods are called showDialog().

I find this cumbersome, so I decide to make another method that returns a File object: in the case of APPROVE_OPTION, it returns the file selected by the user; otherwise, it returns null. This is where I run into a problem: would it be okay for me to keep the showDialog() name, even though methods with that name — and a different return type — already exist? To top it off, my method takes an additional parameter: a File which denotes in which directory the file chooser should start.

My question to you: Is it okay to call a method the same name as a superclass method if they return different types? Or would that be confusing to API users? (If so, what other name could I use?)

Alternatively, should I keep the name and change the return type so it matches that of the other methods?

```<code>public int showDialog(Component parent, String approveButtonText) // Superclass method
public File showDialog(Component parent, File location) // My method
</code>```

Body:
The major problem I can see with this is that if I use your method like this:

chooser.showDialog(parent,location).getPath()

it will work perfectly most of the time, but if the user changes their mind about loading a file and hits cancel, the program will crash.  You could say that I shouldn't write code like that, and you'd be right, but people do write code like that sometimes.  The method as written isn't convenient, since you still have to check for null, and it's a bit of a trap for anyone not paying sufficient attention.

As far as I can tell, you're trying to abstract out 2 method calls into one, but it's quite possible that the new method would be just as cumbersome after factoring in the need for a null check.  It's possible that the whole workflow you're dealing with could be reasonably abstracted, in which case whatever you'd call the whole workflow would probably make a good name for a method.

To answer your actual question, I don't think that having methods of the same name that return different types is automatically bad, but names and return types should never be confusing.


问:
Design considerations on JSON schema for scalars with a consistent attachment property
I'm trying to create a JSON schema for the results of doing statistical analysis based on disparate pieces of data.

The current schema I have looks something like this:

```<code>{
    // Basic key information.
    video : "http://www.youtube.com/watch?v=7uwfjpfK0jo",
    start : "00:00:00",
    end : null,

    // For results of analysis, to be populated:
    // *** This is where it gets interesting ***
    analysis : {
        game : {
            value: "Super Street Fighter 4: Arcade Edition Ver. 2012",
            confidence: 0.9725
        }
        teams : [
            {
                player : {
                    value : "Desk",
                    confidence: 0.95,
                }
                characters : [
                    {
                        value : "Hakan",
                        confidence: 0.80
                    }
                ]
            }
        ]
    }
}
</code>```

The issue is the tuples that are used to store a value and the confidence related to that value (i.e. { value : "some value", confidence : 0.85 }), populated after the results of the analysis.

This leads to a creep of this tuple for every value.  Take a fully-fleshed out value from the characters array:

```<code>{
    name : {
        value : "Hakan",
        confidence: 0.80
    }
    ultra : {
        value: 1,
        confidence: 0.90
    }
}
</code>```

As the structures that represent the values become more and more detailed (and more analysis is done on them to try and determine the confidence behind that analysis), the nesting of the tuples adds great deal of noise to the overall structure, considering that the final result (when verified) will be:

```<code>{
    name : "Hakan",
    ultra : 1
}
</code>```

(And recall that this is just a nested value)

In .NET (in which I'll be using to work with this data), I'd have a little helper like this:

```<code>public class UnknownValue<T>
{
    T Value { get; set; }
    double? Confidence { get; set; }
}
</code>```

Which I'd then use like so:

```<code>public class Character
{
    public UnknownValue<Character> Name { get; set; }
}
</code>```

While the same as the JSON representation in code, it doesn't have the same creep because I don't have to redefine the tuple every time and property accessors hide the appearance of creep.  Of course, this is an apples-to-oranges comparison, the above is code while the JSON is data.

Is there a more formalized/cleaner/best practice way of containing the creep of these tuples in JSON, or is the approach above an accepted approach for the type of data I'm trying to store (and I'm just perceiving it the wrong way)?

Note, this is being represented in JSON because this will ultimately go in a document database (something like RavenDB or elasticsearch).  I'm not concerned about being able to serialize into the object above, because I can always use data transfer objects to facilitate getting data into/out of my underlying data store.

答:
This might be worse, or equal to your current situation: flatten the structure by splitting out confidence values into a second mirrored structure. It's flatter, but wider.

assessment->values->teams->second name = "Hakan"

assessment->confidence->teams->second name = 0.80

```<code>assessment:
  {
     values: {
         game : "Super Street Fighter 4: Arcade Edition Ver. 2012".
         teams : [{ name: "desk", ultra: 2}, { name : "Hakan",  ultra : 1 }]
      },
      confidence: {
         game:  0.9725
         teams : [{ name : 0.95, ultra : 0.90 }, {name : 0.80, ultra : 0.20 }]
      }
   }
</code>```

Body:
This might be worse, or equal to your current situation: flatten the structure by splitting out confidence values into a second mirrored structure. It's flatter, but wider.

assessment->values->teams->second name = "Hakan"

assessment->confidence->teams->second name = 0.80

assessment:
  {
     values: {
         game : "Super Street Fighter 4: Arcade Edition Ver. 2012".
         teams : [{ name: "desk", ultra: 2}, { name : "Hakan",  ultra : 1 }]
      },
      confidence: {
         game:  0.9725
         teams : [{ name : 0.95, ultra : 0.90 }, {name : 0.80, ultra : 0.20 }]
      }
   }


问:
Programming Interview : How to debug a program?
I was recently asked the following question in an interview :

How do you debug a C++ program ?

I started by explaining that programs may have syntax and semantic errors. Compiler reports the syntax errors which can be corrected. For semantic errors, various debuggers are available. I specifically talked about gdb, which is command line, and Visual Studio IDE's debugger, which has a GUI, and common commands. I also talked about debug and release version of code, how assertions should be used for debug build, how exceptions helps in automatic cleanup & putting the program in valid state, and how logging can be useful (e.g. using std::clog).

I want to know if this answer is complete or not. Also, I want to hear how other people will go about answering this question in a structured manner ?

Thanks.

答:
The answer to such a vague question can never be complete.

This sounds like one of those questions that was designed to be vague on purpose: I think you should have avoided excessive waffle and asked them to narrow the focus of the question. As you mentioned, you first classify errors into syntax and semantics, then you branch your answer from there - but since you already assumed they wanted you to discuss both in depth, you simply carried on talking.

Yes, what you have said is fine, but no-one here will be able to tell you if you answered the interview question.

Personally, I would approached by returning a question "why kind of C++ issue am I debugging?" (Segmentation Fault is very different to Unexpected ... as you know, but you should always make clear your assumptions in an interview) and taken it from there, once the question is narrowed enough that I would be able to answer it precisely and largely in entirety. Think of it like this: imagine they've just said to you "my car doesn't work, can you tell me why?". Would you really start trying to answer with so little information?


答: I'd say it's not complete, but certainly acceptable for a junior position. The most powerful debugging tool is to understand the code and to be able to reason correctly about what it is doing versus what it should be doing. This is aspirational though, and we all fall short. We always end up debugging code we've never seen before. A debugger is great for that. I'd also have talked about building a logging facility into your applications, and writing good documentation and clear code. It would also have been good to mention tools like Valgrind, systrace, and gprof or the Windows or Java equivalents. </p>

Title: Programming Interview : How to debug a program?

Body:
I was recently asked the following question in an interview :

How do you debug a C++ program ?

I started by explaining that programs may have syntax and semantic errors. Compiler reports the syntax errors which can be corrected. For semantic errors, various debuggers are available. I specifically talked about gdb, which is command line, and Visual Studio IDE's debugger, which has a GUI, and common commands. I also talked about debug and release version of code, how assertions should be used for debug build, how exceptions helps in automatic cleanup & putting the program in valid state, and how logging can be useful (e.g. using std::clog).

I want to know if this answer is complete or not. Also, I want to hear how other people will go about answering this question in a structured manner ?

Thanks.


问:
Why do node packages put a comma on a newline?
I'm learning node.js and am trying out Express.  My first app had this code:

```<code>var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');
</code>```

Reading through the mongoose tutorial gives me this:

```<code>var mongoose = require('mongoose')
  , db = mongoose.createConnection('localhost', 'test');
</code>```

On strict mode, JSHint gives me

app.js: line 6, col 32, Bad line breaking before ','.

Which shows that I'm not the only one out there who's bugged by this syntax.

Is there any reason to declare vars this way instead of adding the comma at the end of the line?

答:
For a human reader, the leading comma indicates that the line is a continuation of the one above - although personally I think the indentation by itself does that job just fine.

After checking the rules for automatic semicolon insertion it does seem surprising that this would cause an error in a static analyser. Maybe the authors just have a taste of their own.


答:
That sounds an awful lot like a semi-trick question to me - designed to catch you out and trap you into giving an overly complex answer when a simpler one would do.

You find out what the problem is, get a repro case, use a debugger, regression test when done; simple as that.

Your own answer touches on much of this so it may be acceptable.


答:
In C#, you can add attributes to the properties of an object:

http://msdn.microsoft.com/en-us/library/z0w1kczw(v=vs.80).aspx

http://msdn.microsoft.com/en-us/library/aa288454(v=vs.71).aspx

It would be easy enough to create an attribute that defines the level of detail a property represents - lite or full - and add the attribute to each of the properties of the car object.  Once you've decorated all of the properties with attributes, write a serialiser class that can be fed an object and a level of detail as its arguments.  It will:

Use reflection to find a list of all properties relevant to the current detail level;

Spit out a list of those properties and their current values.

This gives you:

A single class instead of multiple classes;

The ability to have a fully-populated object and produce a lite representation without having to create an intermediate abridged copy;

A class that can be extended with new properties and have them automatically be added to the REST API.

Title: REST API wrapper - class design for 'lite' object responses

Body:
I am writing a class library to serve as a managed .NET wrapper over a REST API. I'm very new to OOP, and this task is an ideal opportunity for me to learn some OOP concepts in a real-life situation that makes sense to me.

Some of the key resources/objects that the API returns are returned with different levels of detail depending on whether the request is for a single instance, a list, or part of a "search all resources" response. This is obviously a good design for the REST API itself, so that full objects aren't returned (thus increasing the size of the response and therefore the time taken to respond) unless they're needed.

So, to be clear:

.../car/1234.json returns the full Car object for 1234, all its properties like colour, make, model, year, engine_size, etc. Let's call this full.

.../cars.json returns a list of Car objects, but only with a subset of the properties returned by .../car/1234.json. Let's call this lite.

...search.json returns, among other things, a list of car objects, but with minimal properties (only ID, make and model). Let's call this lite-lite.

I want to know what the pros and cons of each of the following possible designs are, and whether there is a better design that I haven't covered:

Create a Car class that models the lite-lite properties, and then have each of the more detailed responses inherit and extend this class.

Create separate CarFull, CarLite and CarLiteLite classes corresponding to each of the responses.

Create a single Car class that contains (nullable?) properties for the full response, and create constructors for each of the responses which populate it to the extent possible (and maybe include a property that returns the response type from which the instance was created).

I expect among other things there will be use cases for consumers of the wrapper where they will want to iterate through lists of Cars, regardless of which response type they were created from, such that the three response types can contribute to the same list.

Happy to be pointed to good resources on this sort of thing, and/or even told the name of the concept I'm describing so I can better target my research.


答:
I've heard it's called NPM style "comma-first" rule. Example from the doc:

```<code>var magicWords = [ "abracadabra"
                 , "gesundheit"
                 , "ventrilo"
                 ]
  , spells = { "fireball" : function () { setOnFire() }
             , "water" : function () { putOut() }
             }
  , a = 1
  , b = "abc"
  , etc
  , somethingElse
</code>```

The doc doesn't state the motivation behind this coding style, but I guess it's to prevent dumb syntax errors from placing an excessive comma at the end of a comma-separated list, and to alleviate the mental tax it places on you from trying to get that part of the syntax right.

Also note that NPM style recommends "not to use semicolons". If you adopt this style, you're also doing away with the semicolon that fills the final position of a var statement, making it tempting to place a comma there instead.

As for the JSHint error, there's a switch to allow comma-first style line breaks.

Title: Why do node packages put a comma on a newline?

Body:
I'm learning node.js and am trying out Express.  My first app had this code:

```<code>var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');
</code>```

Reading through the mongoose tutorial gives me this:

```<code>var mongoose = require('mongoose')
  , db = mongoose.createConnection('localhost', 'test');
</code>```

On strict mode, JSHint gives me

app.js: line 6, col 32, Bad line breaking before ','.

Which shows that I'm not the only one out there who's bugged by this syntax.

Is there any reason to declare vars this way instead of adding the comma at the end of the line?

Body:
I've heard it's called NPM style "comma-first" rule. Example from the doc:

var magicWords = [ "abracadabra"
                 , "gesundheit"
                 , "ventrilo"
                 ]
  , spells = { "fireball" : function () { setOnFire() }
             , "water" : function () { putOut() }
             }
  , a = 1
  , b = "abc"
  , etc
  , somethingElse

The doc doesn't state the motivation behind this coding style, but I guess it's to prevent dumb syntax errors from placing an excessive comma at the end of a comma-separated list, and to alleviate the mental tax it places on you from trying to get that part of the syntax right.

Also note that NPM style recommends "not to use semicolons". If you adopt this style, you're also doing away with the semicolon that fills the final position of a var statement, making it tempting to place a comma there instead.

As for the JSHint error, there's a switch to allow comma-first style line breaks.


答:
At least there is no technical reason. From a technical point of view, it even seems a bad idea, considering the tendency of JS engines to add semicolons wherever they think they need one.

Aesthetically, it's just like the old OneTrueBraceStyle problem - ask 5 people, get (at least) 5 different answers.


答:
As an interviewer who asks very similar question frequently, maybe I can shed some light.

First of all, in interviews, there are often two types of questions: (1) prove that you know something (practically speaking, these have fairly clear "right" and "wrong" answers), and (2) pop open your skull and show me how your mind works (these have many more shades of gray, and many very different answers can all be good). I try to make sure interviewees know when I'm not looking for the "right" answer and just want to know how they think. For me, this question is in the second category.

Think back, was the question "How do you debug a C++ program?" or "How can a C++ program be debugged?", because the answer you provided was for the second question. In general, in interviews we want to hear the general (i.e., there are release and debug versions of the code) and then we want to hear about how you personally used that (i.e., "on project XYZ the Shroozlebob class wasn't initializing properly, so I loaded the debug version of the code into the debugger and..."). Of course, if I got an answer like yours, I would've started asking for examples. I don't expect interviewees to be knowledgeable at being interviewing; I expect them to be knowledgeable programmers.

For me, there is no one right answer to this question, although some answers are better than others. If you gave me your answer, and I asked for examples and you couldn't provide any, I would have to assume that you don't have very much real debugging experience. But if you gave me good examples of what you mentioned, then that would be a good answer.


答:
I respectfully disagree with @mh. This is not a trick question. I am guessing this was an attempt to start a discussion about debugging and the development process in general.

Your answer is a good starting point, especially the part about assertions and exceptions.  But you could have dug deeper. Do you write unit tests? If not, then you should.  Was the bug caught by a unit test? If not, then you need to add a new test for it.  Do you use a version control system? (Again, you should.) If so, then you should check the recent commit log to see which change could have caused the bug. You may want to try to reproduce the bug in previous versions to find the exact point in time when the bug was introduced.

Is your code clean? (See "Clean Code" by Robert C. Martin). If you have small classes and functions with descriptive names and obvious purpose, then you might be able to find the bug just by looking at the code. If not, then this might be a good time to refactor the part of the code in question to make it more clear and less error-prone.

By the way, you literally should ask the interviewer those questions about version control and unit tests.  The interview is as much about you evaluating them as them evaluating you.


答:
For learning C++, Qt has some good things and some bad things.

The good:

It provides the building blocks for everything you might want to do with C++, from network programming and threads to OpenGL and displaying web content.

It has a few tricks up it sleeves to make things a little easier. For example, it uses the parent hierarchy to handle object deletion makes memory leaks much less common. It also uses signals and slots to provide a somewhat sensible way to write event-driven programs.

The bad things are mostly corollaries of the good things:

Because it has everything wrapped up into a nice, cohesive whole, you are de facto encouraged to only use its things. For instance, you'll be using QString and QList instead of std::string and std::list, because that's what you'll get from Qt classes and that's what Qt classes expect you to provide.

When you eventually write non-Qt code with C++, you'll be missing some of the safety nets. You will really have to be responsible with your memory deallocation, and you'll have to learn the other patterns for doing event-driven code in C++.

Without Qt, you'll have to find some external or system library (e.g., outside the C++ standard) for: threads, network programming, GUI programming, graphics rendering (to the screen or to image files), XML parsing, rendering web content, etc. Qt includes classes for all of those things. But if you want to eventually become a generic C++ programmer, you'll need to learn how to program without it.

Title: Programming C++ using Qt4

Body:
Hey guys I am really new to the C++ programing I have a little knowledge in C and a bit more in C++, but I do not know them enough to call myself a programmer. I am working as a PHP Web Developer I like being a crafts man and creating things so that is the reason to combine the programming with web development. I think that I could really benefit from both of them and so... My question is:

Is it a good Idea to learn C++ with Qt or not?

Can you give me pros and cons of both?

Note: I do not want to become a programmer and give up the web development I want to combine them both.


答:
To expand a bit on ento's comment about syntax issue, JavaScript does not allow extra commas within object literals. For example, in PHP one might assign an array as follows:

```<code>$foo = array(
      "thing 1",
      "thing 2",
      "thing 3", // <-- extra comma
);
</code>```

The extra comma means that you do not have to give special treatment to the last item in a list. You don't have to remember to add the comma if later on you need to add something to the list, and version control only has to track one line changing.

In some versions of JavaScript (JScript), however, the trailing comma causes errors. So you need to leave it off. Later, when adding things you need to remember to add it, and version control has to track two changes.

Adding the comma at the start of every line instead of the end, means that you don't have to treat the last item specially. If you use the leading comma, and leave out semi-colons then items you never have to worry when adding or removing items from a list.

Body:
To expand a bit on ento's comment about syntax issue, JavaScript does not allow extra commas within object literals. For example, in PHP one might assign an array as follows:

$foo = array(
      "thing 1",
      "thing 2",
      "thing 3", // <-- extra comma
);

The extra comma means that you do not have to give special treatment to the last item in a list. You don't have to remember to add the comma if later on you need to add something to the list, and version control only has to track one line changing.

In some versions of JavaScript (JScript), however, the trailing comma causes errors. So you need to leave it off. Later, when adding things you need to remember to add it, and version control has to track two changes.

Adding the comma at the start of every line instead of the end, means that you don't have to treat the last item specially. If you use the leading comma, and leave out semi-colons then items you never have to worry when adding or removing items from a list.


答:
There is a case you missed.  While the program may not give an error, there can be cases where a requirement was misinterpreted and thus the software has to be changed to reflect this.  The compiler won't throw any exception because as far as the program is concerned, nothing wrong is happening.

While I'd also start with various kinds of bugs, compile-time, run-time, and changing requirements, I'd then drill into the question of what kind of bug am I facing?  Is this an issue in the code, data, or infrastructure?  There are more than a few places that could be the source.  I'd probably add that I'd look into the tests written for the program to see if this was covered somewhere or was missed.


问:
May I make an installer bundle GPL and payware together?
I have an affiliate marketing client who needs to know if I can program this. Can I do one or both of the following scenarios without violating the GPL license?

Scenario A:
Make a software installer for a GPL licensed product which includes source, binaries, and license info. The installer also has a checkbox for installing optional software that's payware. (In this case, the payware is free crippleware, but has a registration upsell to provide more features.) The two products will not share libraries or anything else.

Scenario B:
Same as A, but reversed. So, the installer installs the payware, but there's a checkbox to also install the GPL software. And, again, when you install the GPL software, it comes with binaries, source, and license info.

答:
You need to more accurately define what you mean by "payware" here; on the face of it it reads as though you're referring to commercial software, and the GPL itself is actually quite cool about commercial exploitation - there's nothing to stop your "payware" from also being licensed under the GPL for example, which would side-step the problem entirely.

That aside, I believe that your question is (at least partially) answered by the following GPL FAQ entry: http://www.gnu.org/licenses/gpl-faq.html#MereAggregation

An “aggregate” consists of a number of separate programs, distributed
  together on the same CD-ROM or other media. The GPL permits you to
  create and distribute an aggregate, even when the licenses of the
  other software are non-free or GPL-incompatible. The only condition is
  that you cannot release the aggregate under a license that prohibits
  users from exercising rights that each program's individual license
  would grant them.

Having the same installer used for both GPL and non-GPL software muddies things a little, but the easy solution seems to be to just use separate installers.

All of this comes with a standard "I am not a lawyer" disclaimer and advice that if you have a legal concern over this then you would be better served by consulting a qualified legal professional than by asking some random guy on the internet.


问:
Automatic static analysis vs White box testing
Many sources note that automatic static code analysis include data flow and control flow. But these two are included in white box testing as well. Is there a difference in the automation? That in automatic static analysis all is done by the tools while in white box testing, a person creates the data to exercise the possible paths?</p>

答:
Static analysis and testing are different things, and pick up different classes of problems.

With black or white box testing, you execute parts of the code with inputs, etc that the developer or tester thinks are important.  The only real quality control you have over the developer / tester's design of test cases is code coverage ... and that doesn't tell you anything about whether the logic has been properly tested.

By contrast, static analysis is looking for problems in a different way; i.e. by analysing what the code does independently of the test cases / data.  Typically they find different kinds of problem, and typically they find them with less effort on the part of the developer / tester.  For example, a static analyser might identify dead code, or a storage or resource leak that would be impossible to find by unit testing, or an unsafe practice like (in Java) using == to test strings.

In short the two approaches are complementary.


问:
Should I use an interface when methods are only similar?
I was posed with the idea of creating an object that checks if a point will collide with a line:

```<code>public class PointAndLineSegmentCollisionDetector {
    public void Collides(Point p, LineSegment s) {
        // ...
    }
}
</code>```

This made me think that if I decided to create a Box object, then I would need a PointAndBoxCollisionDetector and a LineSegmentAndBoxCollisionDetector.  I might even realize that I should have a BoxAndBoxCollisionDetector and a LineSegmentAndLineSegmentCollisionDetector.  And, when I add new objects that can collide I would need to add even more of these.

But, they all have a Collides method, so everything I learned about abstraction is telling me, "Make an interface."

```<code>public interface CollisionDetector {
    public void Collides(Spatial s1, Spatial s2);
}
</code>```

But now I have a function that only detects some abstract class or interface that is used by Point, LineSegment, Box, etc..  So if I did this then each implementation would have to to a type check to make sure that the types are the appropriate type because the collision algorithm is different for each different type match up.

Another solution could be this:

```<code>public class CollisionDetector {
    public void Collides(Point p, LineSegment s) { ... }
    public void Collides(LineSegment s, Box b) { ... }
    public void Collides(Point p, Box b) { ... }
    // ...
}
</code>```

But, this could end up being a huge class that seems unwieldy, although it would have simplicity in that it is only a bunch of Collide methods.

This is similar to C#'s Convert class.  Which is nice because it is large, but it is simple to understand how it works.  This seems to be the better solution, but I thought I should open it for discussion as a wiki to get other opinions.

答:
Theory

One should implement a common interface when:

Objects are similar and have a similar logic, and:

The shared logic is used in other places where the distinction between the types is not required.

For example, one shouldn't implement a common interface for both Dog: Animal and RSS, just because both have a common method Feed. Not only the logic behind those two methods is different (new Dog(...).Feed() would launch a robot which will give some food to a dog, while new RSS(...).Feed() will simply download the most recent RSS from the server), but you can hardly imagine a common Feeder which would be responsible of controlling dog food and downloading the last RSS feeds.

On the other hand, it would be convenient to have a common interface for both new Dog(...).Feed() and new Goldfish(...).Feed(), because while the implementation would be different, since the robot is expected to not putting a bowl of meat into an aquarium, the common interface still allows for the callers to not make any difference between the animals:

```<code>var myPets = new [] { (IAnimal)new Dog(...), new Goldfish(...) };
...
new FeedingEngine().FeedPets(myPets);

public class FeedingEngine
{
    public void FeedPets(IEnumerable<IAnimal> pets)
    {
        foreach (var pet in pets)
        {
            if (pet.Status == AnimalStatus.Alive && pet.IsPotentiallyHungry)
            {
                pet.Feed();
            }
        }
    }
}
</code>```

Your case

Both of your proposals are correct. From the point of view of the consumer of ICollisionDetector, all I need to know is that I can pass any pair of spacial objects and get the collision result, no matter how.

There is a slight difference between those approaches: it's the fact that the first proposal requires you to double-check if all objects inheriting ISpatial are handled correctly by the collision detector. It can be error prone later: if, working on your code later, another developer implements another spatial object, let's say Sphere: ISpatial, but forgets to implement the collision logic, Collides(sphere, box) will fail, and it would be difficult to understand why is it failing, especially if the collision detector is used indirectly, like through the game engine.

The second approach is an opt-in. If the collision detector doesn't have a Collides(Sphere s, Box b), nobody would be able to call such a conversion. This being said, this itself creates another problem: you will not be able to use generics or any high-level abstraction. For example:

```<code>var box = new Box(...);
var torus = new Torus(...);

var engine = new GameEngine();
engine.Show(new [] { box, torus });
engine.StartColliding(); // Moves objects to the center of the map and stops on collision.
</code>```

is easy to implement with your first proposal if both Box and Torus implement ISpatial, but would be extremely difficult to do with your second proposal.

In order to be able to use your first proposal while reducing the issue I noted above, here's a third proposal:

```<code>public interface ISpatial
{
    bool IsColliding(ISpatial obj);
}

public class CollisionDetector
{
    public bool IsColliding(ISpatial s1, ISpatial s2)
    {
        return s1.IsColliding(s2);
    }
}

public class Torus : ISpatial
{
    public bool IsColliding(ISpatial obj)
    {
        // Check that obj is not null.

        // Do the collision logic for known types.
        var box = obj as Box;
        if (box != null)
        {
            // Do the collision logic.
            return result;
        }

        return obj.IsColliding(this);
    }
}

public class Cube : ISpatial
{
    public bool IsColliding(ISpatial obj)
    {
        // Check that obj is not null.

        // Do the collision logic for known types.

        return obj.IsColliding(this);
    }
}
</code>```

Since the cube class is created first, it is unaware of torus; instead of throwing a NotImplementedException, it simply delegates the collision detection logic to the torus, which is well aware of the cube object, since the torus class was the second one to be created.

Note: of course, you still have to handle the situations where neither the first, nor the second object are aware of each other (for example if two objects were created by two different developers at the same moment of time). Actual code above will simply overflow and crash, but you can easily change it to throw NotImplementedException instead.

Body:
Theory

One should implement a common interface when:

Objects are similar and have a similar logic, and:

The shared logic is used in other places where the distinction between the types is not required.

For example, one shouldn't implement a common interface for both Dog: Animal and RSS, just because both have a common method Feed. Not only the logic behind those two methods is different (new Dog(...).Feed() would launch a robot which will give some food to a dog, while new RSS(...).Feed() will simply download the most recent RSS from the server), but you can hardly imagine a common Feeder which would be responsible of controlling dog food and downloading the last RSS feeds.

On the other hand, it would be convenient to have a common interface for both new Dog(...).Feed() and new Goldfish(...).Feed(), because while the implementation would be different, since the robot is expected to not putting a bowl of meat into an aquarium, the common interface still allows for the callers to not make any difference between the animals:

var myPets = new [] { (IAnimal)new Dog(...), new Goldfish(...) };
...
new FeedingEngine().FeedPets(myPets);

public class FeedingEngine
{
    public void FeedPets(IEnumerable<IAnimal> pets)
    {
        foreach (var pet in pets)
        {
            if (pet.Status == AnimalStatus.Alive && pet.IsPotentiallyHungry)
            {
                pet.Feed();
            }
        }
    }
}

Your case

Both of your proposals are correct. From the point of view of the consumer of ICollisionDetector, all I need to know is that I can pass any pair of spacial objects and get the collision result, no matter how.

There is a slight difference between those approaches: it's the fact that the first proposal requires you to double-check if all objects inheriting ISpatial are handled correctly by the collision detector. It can be error prone later: if, working on your code later, another developer implements another spatial object, let's say Sphere: ISpatial, but forgets to implement the collision logic, Collides(sphere, box) will fail, and it would be difficult to understand why is it failing, especially if the collision detector is used indirectly, like through the game engine.

The second approach is an opt-in. If the collision detector doesn't have a Collides(Sphere s, Box b), nobody would be able to call such a conversion. This being said, this itself creates another problem: you will not be able to use generics or any high-level abstraction. For example:

var box = new Box(...);
var torus = new Torus(...);

var engine = new GameEngine();
engine.Show(new [] { box, torus });
engine.StartColliding(); // Moves objects to the center of the map and stops on collision.

is easy to implement with your first proposal if both Box and Torus implement ISpatial, but would be extremely difficult to do with your second proposal.

In order to be able to use your first proposal while reducing the issue I noted above, here's a third proposal:

public interface ISpatial
{
    bool IsColliding(ISpatial obj);
}

public class CollisionDetector
{
    public bool IsColliding(ISpatial s1, ISpatial s2)
    {
        return s1.IsColliding(s2);
    }
}

public class Torus : ISpatial
{
    public bool IsColliding(ISpatial obj)
    {
        // Check that obj is not null.

        // Do the collision logic for known types.
        var box = obj as Box;
        if (box != null)
        {
            // Do the collision logic.
            return result;
        }

        return obj.IsColliding(this);
    }
}

public class Cube : ISpatial
{
    public bool IsColliding(ISpatial obj)
    {
        // Check that obj is not null.

        // Do the collision logic for known types.

        return obj.IsColliding(this);
    }
}

Since the cube class is created first, it is unaware of torus; instead of throwing a NotImplementedException, it simply delegates the collision detection logic to the torus, which is well aware of the cube object, since the torus class was the second one to be created.

Note: of course, you still have to handle the situations where neither the first, nor the second object are aware of each other (for example if two objects were created by two different developers at the same moment of time). Actual code above will simply overflow and crash, but you can easily change it to throw NotImplementedException instead.


答:
A generic interface would fit well here

```<code>public interface ICollisionDetector<TFirst, TSecond>
{
    bool Collides(TFirst first, TSecond second);
}

public class PointAndBoxCollisionDetector : ICollisionDetector<Point, Box>
{
    public bool Collides(Point first, Box second)
    {
        // Collision logic
    }
}
</code>```

You can use a FactoryMethod to generate your detector, based on the types of the two objects you have.

```<code>public class CollisionDetectorFactory
{
    public ICollisionDetector<TFirst, TSecond> Create<TFirst, TSecond>()
    {
         // Here you can have a giant switch/case, or
         // you can map using reflection, or you can get
         // from an IoC Container/Service Locator.
    }
}
</code>```

Title: Should I use an interface when methods are only similar?

Body:
I was posed with the idea of creating an object that checks if a point will collide with a line:

```<code>public class PointAndLineSegmentCollisionDetector {
    public void Collides(Point p, LineSegment s) {
        // ...
    }
}
</code>```

This made me think that if I decided to create a Box object, then I would need a PointAndBoxCollisionDetector and a LineSegmentAndBoxCollisionDetector.  I might even realize that I should have a BoxAndBoxCollisionDetector and a LineSegmentAndLineSegmentCollisionDetector.  And, when I add new objects that can collide I would need to add even more of these.

But, they all have a Collides method, so everything I learned about abstraction is telling me, "Make an interface."

```<code>public interface CollisionDetector {
    public void Collides(Spatial s1, Spatial s2);
}
</code>```

But now I have a function that only detects some abstract class or interface that is used by Point, LineSegment, Box, etc..  So if I did this then each implementation would have to to a type check to make sure that the types are the appropriate type because the collision algorithm is different for each different type match up.

Another solution could be this:

```<code>public class CollisionDetector {
    public void Collides(Point p, LineSegment s) { ... }
    public void Collides(LineSegment s, Box b) { ... }
    public void Collides(Point p, Box b) { ... }
    // ...
}
</code>```

But, this could end up being a huge class that seems unwieldy, although it would have simplicity in that it is only a bunch of Collide methods.

This is similar to C#'s Convert class.  Which is nice because it is large, but it is simple to understand how it works.  This seems to be the better solution, but I thought I should open it for discussion as a wiki to get other opinions.

Body:
A generic interface would fit well here

public interface ICollisionDetector<TFirst, TSecond>
{
    bool Collides(TFirst first, TSecond second);
}

public class PointAndBoxCollisionDetector : ICollisionDetector<Point, Box>
{
    public bool Collides(Point first, Box second)
    {
        // Collision logic
    }
}

You can use a FactoryMethod to generate your detector, based on the types of the two objects you have.

public class CollisionDetectorFactory
{
    public ICollisionDetector<TFirst, TSecond> Create<TFirst, TSecond>()
    {
         // Here you can have a giant switch/case, or
         // you can map using reflection, or you can get
         // from an IoC Container/Service Locator.
    }
}


问:
What if I can't make my unit test fail in "Red, Green, Refactor" of TDD?
So let's say that I have a test:

```<code>@Test
public void MoveY_MoveZero_DoesNotMove() {
    Point p = new Point(50.0, 50.0);
    p.MoveY(0.0);
    Assert.assertAreEqual(50.0, p.Y);
}
</code>```

This test then causes me to create the class Point:

```<code>public class Point {
    double X; double Y;
    public void MoveY(double yDisplace) {
        throw new NotYetImplementedException();
    }
}
</code>```

Ok.  It fails.  Good.  Then I remove the exception and I get green. Great, but of course I need to test if it changes value.  So I write a test that calls p.MoveY(10.0) and checks if p.Y is equal to 60.0.  It fails, so then I change the function to look like so:

```<code>public void MoveY(double yDisplace) {
    Y += yDisplace;
}
</code>```

Great, now I have green again and I can move on.  I've tested not moving and moving in the positive direction, so naturally I should test a negative value.  The only problem with this test is that if I wrote the test correctly, then it doesn't fail at first.  That means that I didn't fit the principle of "Red, Green, Refactor."

Of course, This is a first-world problem of TDD, but getting a fail at first is helpful in that it shows that your test can fail.  Otherwise this seemingly innocent test that is just passing for incorrect reasons could fail later because it was written wrong.  That might not be a problem if it happened 5 minutes later, but what if it happens to the poor-sap that inheirited your code two years later.  What he knows is that MoveY does not work with negative values because that is what the test is telling him.  But, it really could work and just be a bug in the test.

I don't think that would happen in this particular case because the code sample is so simple, but if it were a large complicated system that might not be the case.  It seems crazy to say that I want to fail my tests, but that is an important step in TDD, for good reasons.

答:
Then don't write it.

You have already come to a point where you

Have the simplest code which passes all tests.

Are unable to think of edge-cases that aren't covered by the code.

Time to stop worrying about that method.

If you're writing tests for edge-cases that you know are already covered then you're worrying more about the test part of TDD than the design part. Unfortunately, this is not a very productive thing to do.

Why do you need to know that your method works with negatives? How far do you take that? Do you then test fractions? Do you test odd and even numbers? Each factor of ten? Every possible value of double?

If not then why test negatives? They're not going to act any differently from positives.


问:
What should I study to 'learn' Comp Sci?
[This question was originally asked on Stack Overflow, but recommended to move the question here.]

I can't find anything quite like the question I'm about to ask, so please forgive me if there's something just like it already, please feel free to point me in the right direction. It'll take a bit of background explaining too, please forgive me for that.

[backstory]

Basically, I graduated from University about 18 months ago with a degree in Business Information Systems and Japanese. The Japanese took up half of the degree so the BIS was only joint. I only learned PHP in terms of languages and basically no computing theory - everything was vocational (Networking, programming basics, CMS development, Office and VBA and then loads of Business theory courses).

Since this, I decided to teach myself C# and ASP.Net and try to get a position as a programmer. I created an online shop style website and a small CRM application in Windows Forms to both teach myself and build a portfolio, and luckily I managed to snag a developer position.

Bad side? I'm the only developer at my company. Now don't get me wrong, in the last year I've learned loads and loads, I did some devpt. before Uni so knew the basics anyway, but it was very much a "learning from books" job - every night.

Now then... I am now at a point where I'm building software on a regular basis, making good judgements for time scales, and have even been told my code and methodology are good by other professionals that have been in the game longer than me, and they have offered me jobs.

[/backstory]

What this whole thing boils down to, is that I now want to study up on the topics I'll have missed by not doing CS. More importantly, could you recommend books / free online courses? I want to learn about Computer Science theory, not just better coding.

Thank you!

答:
If you can afford it, get an unlimited subscription to Safari Books Online.  You will have access to thousands of computer-related (and other technical) books.  Pick a topic: algorithms is a good place to start.  Then something on data structures and program design.  Object oriented programming.  Pick a new language, different from what you already know -- such as Ruby or Python.  Browse some books on each subject, and those you like, read in depth.

From there, pick some topics which interest you, such as operating systems, compilers, cryptography, image processing, etc.