答:
You seem to be making a lot of assumptions, possibly based on your experience with SVN and CVS.

Git and Mercurial are basically like SVN and CVS

Comparing git and CVS is like comparing an iPad and an Atari. CVS was created back when dinoaurs roamed the Earth. Subversion is basically an improved version of CVS. Assuming that modern version control systems like git and Mercurial work like them makes very little sense.

A relational database is more efficient than a single-purpose database

Why? Relational databases are really complicated, and may not be as efficient as single-purpose databases. Some differences off the top of my head:

Version control systems don't need complicated locking, since you can't do multiple commits at the same time anyway.

Distributed version control systems need to be very extremely space efficient, since the local database is a full copy of the repo.

Version control systems only need to look up data in a couple specific ways (by author, by revision ID, sometimes full-text search). Making your own database that can handle author/revision ID searches is trivial and full-text searches aren't very fast in any relational database I've tried.

Version control systems need to work on multiple platforms. This makes it harder to use a database that needs to be installed and running as a service (like MySQL or PostgreSQL).

Version control systems on your local machine only need to be running when you're doing something (like a commit). Leaving a service like MySQL running all the time just in case you want to do a commit is wasteful.

For the most part, version control systems never want to delete history, just append to it. That may lead to different optimizations, and different methods of protecting integrity.

Relational databases are safer

Again, why? You seem to assuming that because data is stored in files, version control systems like git and Mercurial don't have atomic commits, but they do. Relational databases also store their databases as files. It's notable here that CVS doesn't do atomic commits, but that's likely because it's from the dark ages, not because they don't use relational databases.

There's also the issue of protecting the data from corruption once it's in the database, and again the answer is the same. If the filesystem is corrupted, then it doesn't matter which database you're using. If the filesystem isn't corrupted, then your database engine might be broken. I don't see why a version control database would be more prone to this than a relational database.

I would argue that distributed version control systems (like git and Mercurial) are better for protecting your database than centralized version control, since you can restore the entire repo from any clone. So, if your central server spontaneously combusts, along with all of your backups, you can restore it by running git init on the new server, then git push from any developer's machine.

Reinventing the wheel is bad

Just because you can use a relational database for any storage problem doesn't mean you should. Why do you use configuration files instead of a relational database? Why store images on the filesystem when you could store the data in a relational database? Why keep your code on the filesystem when you could store it all in a relational database?

"If all you have is a hammer, everything looks like a nail."

There's also the fact that open-source projects can afford to reinvent the wheel whenever it's convenient, since you don't have the same kinds of resource constraints that commercial projects do. If you have a volunteer who's an expert at writing databases, then why not use them?

As for why we would trust the writers of revision control systems to know what they're doing.. I can't speak for other VCS's, but I'm pretty confident that Linus Torvalds understands filesystems.

Why do some commercial version control systems use a relational database then?

Most likely some combination of the following:

Some developers don't want to write databases.

Developers of commercial version control systems have time and resource constraints, so they can't afford to write a database when they have something close to what they want already. Also, developers are expensive, and database developers (as in, people who write databases) are probably more expensive, since most people don't have that kind of experience.

Users of commercial version control systems are less likely to care about the overhead of setting up and running a relational database, since they already have one.

Users of commercial version control systems are more likely to want a relational database backing their revision data, since this may integrate with their processes better (like backups for example).


问:
Publish a software with copyright and license
I just read some artical about publishing software and I am personally developing some random metero application at the moment.

The artical were suggesting the software should have a publisher website.

But what I have to put down in the publisher website to keep my copyright?

Is it simply really just "Designed/Developed @ 2012 By King Chan" at the bottom of the site and software and is enough?

Or do I have to even write a long paragraph of license/agreement said the user who download/use the software cannot copy the icon/functionality etc?

(The Apple and Samsung things get me worry about CopyRight now....)

答:
You almost certainly own the copyright on your code (1)

You don't need to do anything to claim that - although putting an explicit claim in the code makes it clearer.

A license is there to control what other people can do with your code (MIT requires them to mention you, GPL requires that they also make their code GPL etc). If you don't want to put any extra restrictions on users of your code then you don't need to do anything.

1 - unless you are in some weird country that isn't in the Berne convention. Or if your employer claims copyright on anything you do and you live somewhere that would uphold this.

ContentLicense: CC BY-SA 3.0


问:
Compiler Warnings
Many compilers have warning messages to warn the programmers about potential runtime, logic and performance errors, most times, you quickly fix them, but what about unfixable warnings?

How do you deal with unfixable warnings? Do you re-write a portion of the code, or rewrite it in the "long, hackless way" or disable warnings all together? What should be the best practice?

What if you are editing someone else's code and his code has warnings?

Here is a good example:
jQuery has a lots of JavaScript warnings as a Mozilla-class browser detected, why the jQ developers don't fix them? If you contribute to jQuery, are you going to fix them?

答:
My opinion is that you should be strict with yourself. The compiler has been written by total experts in the language. If they are reporting that something is a bit wiffy (think code smell) then the code should be reviewed.

It is entirely possible to write code that compiles without errors and without warnings.

Title: Compiler Warnings

ContentLicense: CC BY-SA 2.5


问:
Releasing Mobile Application under multiple platforms, same time or?
I've always had this idea circling around until I am facing this issue.

We made an android app, it is ready, but we are planning to release the same app on iOS and possibly Windows Phone;

Now, should we just release the Android app and promise the clients that the iOS version is coming soon (create anticipation before release)

or delay the release until the iOS version is ready?

Same applies if we have a premium and free version, should we release the free version and promise that the better premium is coming soon, or release them both the same time?

EDIT: as requested, the APP is a social APP, it depends on people's activity to succeed, and the manpower is the same, we made the iOS version, but to compile it we are waiting for the company to get us better Mac Machines (will be in a  week for most)

答:
This is obviously a 'it depends' situation.  You havent provided much context about the app and/or the business plan.  For example, did you promise an iOS app along with the Android app? Do you multiple teams each which specializes in a particular os?

In general, if you release for one platform first, you can get some initial feedback from real users without being overwhelmed by having to make updates across multiple platforms.  Much the way retail outlets do 'soft openings' so that they can work the bugs in their process out, software companies can do 'soft releases' to trickle out the app at first to make sure there's no major, embarrassing problems.  Barring any specific business requirements that you have editions for multiple platforms available at the same time, thats how I'd do it.


问:
Which numeral systems are useful in computer science?
I am wondering which numeral system different programmers are using, or would use if their language has support for them. As an example, in C++ we can use:

Octal by prefixing with 0 (e.g. 0377)

Decimal by default (e.g. 255)

Hexadecimal by prefixing with 0x (e.g. 0xff)

When working with bitmask, I am using hexadecimal but would sometimes want to be able to express binary numbers directly. I know some programming language support it with 0b syntax (e.g. 0b11111111).

Is there any other numeric system useful in some computer science domain (e.g. cryptography, codecs, 3D graphics, etc)?

答:
For the sake of theoretical computer science, the branch of abstract mathematics, everything is either done conveniently in base10,  which we normally operate in, or base2, because it's the simplest to reason about.

In the more general sense of computer science, meaning the things you're likely to study for a CS degree, the situation is very similar.  Pretty much everything will simply be done in base10. The biggest reason you'll work with base2 is architecture classes when you're learning the internal representation of numbers in a CPU & how they're operated on.  Base8 and base16 might come up if you find yourself working in assembly or low-level OS operations.

If you get down to it, binary, octal and hex, all being powers of two, are essentially equivalent - they're convenient ways to represent a sequence of bits.  As time passes, there become fewer reasons to bother with them for general purpose computing.  Using bitmasks (or the equivalent hex codes) was an essential tool in saving memory when you're dealing with a system that only has a few KB of memory but in an era where desktop icons can be over a megabyte, it's seldom worth the hassle.  Obviously, there's still people writing low-level hardware interfaces, network services & doing embedded development but most programmers are increasingly isolated from that by layers of abstraction.

I'm not saying it's bad to learn them - it can be quite useful to be familiar with them (for example, Unix file permissions still use Octal) but don't expect to be using them every day.


答:
App purchases are often impulse buys.  If you're going to have a free and premium version, you'd want to release them together so users can quickly convert to paid users.

As for whether to release Android now or wait for the iOS version, there's multiple things to take into account.  Foremost, do you have the manpower to quickly respond to bugs on both platforms if they're released at the same time?  Does your app gain value to users by having more other users (e.g. a social game or group scheduling app)? Does your company need the income from the Android version right now to pay for development of the iPhone version? Have you budgeted each release separately for advertising or do you only want to have a single push?

For anyone else out there reading this, this is the sort of basic business planning you should do before you start writing code on a project.

Title: Releasing Mobile Application under multiple platforms, same time or?

Body:
I've always had this idea circling around until I am facing this issue.

We made an android app, it is ready, but we are planning to release the same app on iOS and possibly Windows Phone;

Now, should we just release the Android app and promise the clients that the iOS version is coming soon (create anticipation before release)

or delay the release until the iOS version is ready?

Same applies if we have a premium and free version, should we release the free version and promise that the better premium is coming soon, or release them both the same time?

EDIT: as requested, the APP is a social APP, it depends on people's activity to succeed, and the manpower is the same, we made the iOS version, but to compile it we are waiting for the company to get us better Mac Machines (will be in a  week for most)


答:
Copyright & licensing are separate issues.  Copyright prevents unauthorized duplication of your software/website.  By default, nobody can copy and use your software because of copyright.

A license defines the terms under which you allow people to use the software.  It also defines & limits what your obligations to the user are.  Generally there's language in there to stop them from suing you if the software breaks.

They're both important.  I suggest getting a lawyer if you're releasing it commercially - if you're releasing it for free, I strongly suggest going with a standard open source license.

Title: Publish a software with copyright and license

Body:
I just read some artical about publishing software and I am personally developing some random metero application at the moment.

The artical were suggesting the software should have a publisher website.

But what I have to put down in the publisher website to keep my copyright?

Is it simply really just "Designed/Developed @ 2012 By King Chan" at the bottom of the site and software and is enough?

Or do I have to even write a long paragraph of license/agreement said the user who download/use the software cannot copy the icon/functionality etc?

(The Apple and Samsung things get me worry about CopyRight now....)


问:
is Oracle ADF Mobile free? and what is it's usage scope?
I would like to know whether Oracle ADF Mobile is free to use for someone who doesn't  have the (expensive) ADF license, and what if I want to talk to a backend (web service), do I need Weblogic?

What about usage scope? Is ADF Mobile suitable for games?

答:
it turned out to be not free,
cost :
USD$ 120.00 per named user, or
USD$ 5800.00 per processor
and if you want to deploy your app say to app store you need processor license.

Oracle FAQ :
  A named user plus license of ADF will entitle customer a single
  named user license of the ADF Mobile.
  A processor license of ADF will allow customer to deploy ADF Mobile-based application to
  unlimited number of devices.

I'm still though unclear about whether it's suited for games but there is a hint :

Oracle FAQ: You may even add a feature based on
  device-native code. All of these can run within the same application,
  and all of these features can communicate with each other.

hope someone else shed more light more about making games with ADF mobile.


问:
How do I avoid GPL violations?
When I'm releasing a program, I like to license it under the GPL or LGPL. I also want to stay compliant with that license. I'm not good at reading legal documents, and the GPL3 is about 10 pages long. How do I avoid GPL violations in my code?</p>

答:
Did you write the code?

Then the GPL is working for you - you don't need to do anything to bide by it, the people you distribute the code to are bound by it. Remember the GPL doesn't apply to you for your own code - you are still free to do anything else you want with it. You can even sell it alongside the GPL version.

If you used other GPL code in your app then you just abide by the same license. You include the same gpl.txt file and make your source available (put it github etc)

edit: to add luis' point. If you accept contributions from anyone else then the GPL would apply to you - unless you had them give you extra permissions

Title: How do I avoid GPL violations?


答:
Does your code use any tools, APIs or other code that you didn't write?  What are the licenses of those bits of code?  Are they GPL compatible?  You understand, of course, that using the GPL means that no-one can distribute closed-source code with your code because doing so forces that code to become GPL.

Did anyone else contribute to your code?  Do you have contributors agreements with them?

Title: How do I avoid GPL violations?

Body: When I'm releasing a program, I like to license it under the GPL or LGPL. I also want to stay compliant with that license. I'm not good at reading legal documents, and the GPL3 is about 10 pages long. How do I avoid GPL violations in my code?</p>


问:
Why are source control systems still mostly backed with files?
It seems that more source control systems still use files as the means of storing the version data.  Vault and TFS use Sql Server as their data store, which I would think would be better for data consistency as well as speed.

So why is it that SVN, I believe GIT, CVS, etc still use the file system as essentially a database,  (I ask this question as we had our SVN server just corrupt itself during a normal commit) instead of using actual database software (MSSQL, Oracle, Postgre, etc)?

EDIT:  I think another way of asking my question is "why do VCS developers roll their own structured data storage system instead of using an exisiting one?"

答:
A filesystem is a database.  Not a relational database, of course, but most are very efficient key/value stores.  And if your access patterns are well-designed for a key-value store (eg, the git repository format), then using a database probably doesn't offer significant advantages over using the filesystem.  (In fact, it's just another layer of abstraction to get in the way.)

A lot of the database features are just extra baggage.  Full text search?  Does full text search make sense for source code?  Or do you need to tokenize it differently?  This also requires that you store full files at every revision, which is uncommon.  Many version control systems store deltas between revisions of the same file in order to save space, for example Subversion and Git (at least, when using pack files.)

The cross-platform requirements make using a database more challenging.

Most version control tools are built to run on multiple platforms.  For centralized version control tools, this only affects the server component, but it is still difficult to rely upon a single database server since Unix users cannot install Microsoft SQL Server and Windows users may be unwilling to install PostgreSQL or MySQL.  The filesystem is the least common denominator.  However, there are several tools where the server must be installed on a Windows machine, and thus require SQL Server, for example SourceGear Vault and Microsoft Team Foundation Server.

Distributed version control systems make this more challenging still, since every user gets a copy of the repository.  This means that every user needs a database to put the repository into.  This implies that the software:

Is limited to a subset of platforms where a particular database exists

Targets a single database backend that is cross-platform (eg, SQLite).

Targets a pluggable storage backend, so that one could use whatever database they wished (possibly including the filesystem).

Most distributed version control systems, therefore, just use the filesystem.  A notable exception is SourceGear's Veracity, which can store in a SQLite database (useful for local repositories) or a relational database like SQL Server (possibly useful for a server.)  Their cloud hosted offering may use a non-relational storage backend like Amazon SimpleDB, but I do not know this to be true.


问:
What are the differences between abstract classes, interfaces, and when to use them
Recently I have started to wrap my head around OOP, and I am now to the point where the more I read about the differences between abstract classes and interfaces the more confused I become. So far, neither can be instantiated.  Interfaces are more or less structural blueprints that determine the skeleton and abstracts are different by being able to partially implement code.

I would like to learn more about these through my specific situation. Here is a link to my first question if you would like a little more background information: What is a good design model for my new class?

Here are two classes I created:

```<code>class Ad {
    $title;
    $description
    $price;

    function get_data($website){  }

    function validate_price(){  }
 }

class calendar_event {
    $title;
    $description

    $start_date;

    function get_data($website){ //guts }

    function validate_dates(){ //guts }
 }
</code>```

So, as you can see these classes are almost identical. Not shown here, but there are other functions, like get_zip(), save_to_database() that are common across my classes. I have also added other classes Cars and Pets which have all the common methods and of course properties specific to those classes (mileage, weight, for example).

Now I have violated the DRY principle and I am managing and changing the same code across multiple files. I intend on having more classes like boats, horses, or whatever.

So is this where I would use an interface or an abstract class? From what I understand about abstract classes, I would use a super class as a template with all of the common elements built into the abstract class, and then add only the items specifically needed in future classes. For example:

```<code>abstract class content {
    $title;
    $description

    function get_data($website){  }

    function common_function2() { }
    function common_function3() { }
 }

class calendar_event extends content {

    $start_date;

    function validate_dates(){  }
 }
</code>```

Or would I use an interface and, because these are so similar, create a structure that each of the subclasses are forced to use for integrity reasons, and leave it up to the end developer who fleshes out that class to be responsible for each of the details of even the common functions. my thinking there is that some 'common' functions may need to be tweaked in the future for the needs of their specific class.

Despite all that above, if you believe I am misunderstanding the what and the why of abstract classes and interfaces altogether, by all means let a valid answer to be stop thinking in this direction and suggest the proper way to move forward!

Thanks!

答:
Long story short. Abstract classes are much like Interfaces in that they both provide a template of what methods should be within the inheriting class, but there are big differences:
- Interfaces only define names/types of methods that need to exist in an inheriting class, while abs-classes can have complete default code of method and just the details may need to be over-ridden.
- Interfaces cannot have access modifiers.
- Interfaces cannot have fields.
- Classes cannot have multiple inheritance of classes, while they can inherit multiple interfaces.
- Also, classes provide a hierarchy structure so that only classes derived from a specific class need to follow the guidelines of the abstract class: object->specific object-> very specific object. Interfaces on the other hand can be inherited by anybody anywhere.

In my opinion abstract classes are more common in that they can provide default implementation of code right away, but in large scale projects where you need to standardize certain classes, interfaces could come in handy.

Hope that helps,
but there is lots of info on this online,
Leo


问:
Help identify the pattern for reacting on updates
There's an entity that gets updated from external sources. Update events are at random intervals. And the entity has to be processed once updated. Multiple updates may be multiplexed. In other words there's a need for the most current state of entity to be processed.

There's a point of no-return during processing where the current state (and the state is consistent i.e. no partial update is made) of entity is saved somewhere else and processing goes on independently of any arriving updates.

Every consequent set of updates has to trigger processing i.e. system should not forget about updates. And for each entity there should be no more than one running processing (before the point of no-return) i.e. the entity state should not be processed more than once.

So what I'm looking for is a pattern to cancel current processing before the point of no return or abandon processing results if an update arrives. The main challenge is to minimize race conditions and maintain integrity.

The entity sits mainly in database with some files on disk. And the system is in .NET with web-services and message queues.

What comes to my mind is a database queue-like table. An arriving update inserts row in that table and the processing is launched. The processing gathers necessary data before the point of no-return and once it reaches this barrier it looks into the queue table and checks whether there're more recent updates for the entity. If there are new updates the processing simply shuts down and its data is discarded. Otherwise the processing data is persisted and it goes beyond the point of no-return.

Though it looks like a solution to me it is not quite elegant and I believe this scenario may be supported by some sort of middleware.

If I would use message queues for this then there's a need to access the queue API in the point of no-return to check for the existence of new messages. And this approach also lacks elegance.

Is there a name for this pattern and an existing solution?

答:
Assuming that you're okay with limiting your data repository options to Microsoft SQL Server, you could opt to go with using Service Broker to handle your messaging & queuing.

Since this would all be encapsulated within the database engine, there wouldn't need to be any sort of external API calls from the point of no-return check either. All of the logic could be written into stored procedures (either with T-SQL or as CLR procedures). Also, with Service Broker Activation, you can have other programs (e.g. your own executable) run on-demand, whenever there's work for it to do.

As an added bonus, Service Broker is easily scalable, so you can offload any data processing to another server(s) & keep your primary database server from being bogged down by any irregular data processing loads - just setup your multiple instances & point Service Broker to the appropriate endpoints.

However, some of the drawbacks of using Service Broker are:

Additional learning curve for developers (learning a new technology).

More complicated to troubleshoot for any non-DBA type tech support.

Requires Standard Edition or higher (with SQL Server 2012) - not available with the Express Edition (i.e. the free version).


问:
How to Deliberately Practice Software Engineering?
I just finished reading this recent article. It's a very interesting read, and it makes some great points. The point that specifically jumped out at me was this:

The difference was in how they spent this [equal] time. The elite players
  were spending almost three times more hours than the average players
  on deliberate practice — the uncomfortable, methodical work of
  stretching your ability.

This article (if you care not to read it) is discussing violin players. Of course, being a software engineer, my mind turned towards software ability. Granted, there are some very naturally talented individuals out there, but time and time again, it is those folks who stretch their abilities through deliberate practice that really become exceptional at their craft.

My question is - how would one go about practicing the "scales" of software engineering and computer science? When I practice the piano, I will spend more of my time on scales and less on a fun song. How can I do the same in developing software?

To head off early answers, I don't feel that "work on an open source project," and similar answers, is really right. Sure...that can improve your skills, but you could just as easily get stuck focusing on something that is unimportant to your craft as a whole. It can become the equivalent of learning "Twinkle Twinkle Little Star" and never being able to play Chopin.

So, again, I ask - how would you suggest that someone deliberately practice software engineering?

答:
None of the above is software engineering. It is all only programming in a haphazard manner.

Software Engineering (SE) is an engineering discipline concerned with a systematic, rigorous, disciplined approach to the design, development, operation, and maintenance of software, and the study of these approaches; that is, the application of engineering to software.

In particular, software can be engineered when you apply engineering techniques. To learn such techniques, the best is to study a relevant SE Master's Degree. When you teach yourself, you may learn about programming, but I cannot imagine you learning engineering on your own.

Example:
Programmer comes and starts writing code, optimizing code, etc. (everything that matters to a programmer is code and nothing but code). Complex projects are often late, the budget is exceeded up to a few orders of magnitude, and the software does not solve requirements well. This is known as software crisis. The answer to that is the SE discipline.

SE comes and wants to understand the problem domain as the first thing. An engineering approach is applied, in particular Requirements Engineering (RE) (requirements elicitation -> requirements analysis -> requirements specification -> requirements validation).

The result of RE is typically a set of models such as contextual model, behavioral model, and business process model. From these models, SE understands the business problem and designs a software solution.

The design typically means SE translates requirement models into component-based system architecture and then engineers component design for each component individually. This results in a certain specification of component boundaries, component interfaces, and classes to compose components from.

Next step is someone who comes to these (usually auto-generated) interfaces and creates their implementation. That person may be a programmer. Finally, SE follows with software validation where everything is tested against original design and requirements.

In SE, projects typically have a project plan which allows engineers to plan, control, and monitor projects. In particular, software is engineered on time, on budget, to specification.

During the implementation phase of software, documentation is produced for every artifact and many Configuration Items (CIs) are generated. These need to be managed somehow. Usually, in SE, there is a Software Configuration Management (SCM) repository and Change Management. Another part of SE is Software Process (SP), i.e. RUP, Scrum, DSDM, Crystal, Waterfall, ...

SP must be documented and rigorously followed as in the documentation, without any exception, so that results are always reproducible. (ISO 9000). This refers to Software Quality.

Another SE topic is Software Measurement and Estimation which allows you to measure the efficiency of your SP, team performance, estimated project size (LOC - Lines of Code) i.e. COCOMO, estimated project delivery (man days), and similar.

There is still much more to SE than this short answer describes. Applying SE approaches instead of only writing code is how you practice SE.

Because SE is still an emerging field, it happens that non-engineers call themselves engineers. Unless they are applying engineering approaches, they are merely programmers.

For further reading, see Software Engineering by Ian Sommerville and www.ieee.org / www.computer.org. In these resources, SE is the engineering discipline. On Stack Overflow and in many companies, unfortunately, they borrow the term SE and use it as another name for programming.


问:
What triggered the popularity of lambda functions in modern mainstream programming languages?
In the last few years anonymous functions (AKA lambda functions) have become a very popular language construct and almost every major / mainstream programming language has introduced them or is planned to introduce them in an upcoming revision of the standard.

Yet, anonymous functions are a very old and very well-known concept in Mathematics and Computer Science (invented by the mathematician Alonzo Church around 1936, and used by the Lisp programming language since 1958, see e.g. here).

So why didn't today's mainstream programming languages (many of which originated 15 to 20 years ago) support lambda functions from the very beginning and only introduced them later?

And what triggered the massive adoption of anonymous functions in the last few years? Is there some specific event, new requirement or programming technique that started this phenomenon?

IMPORTANT NOTE

The focus of this question is the introduction of anonymous functions in modern, main-stream (and therefore, maybe with a few exceptions, non functional) languages.
Also, note that anonymous functions (blocks) are present in Smalltalk, which is not a functional language, and that normal named functions have been present even in procedural languages like C and Pascal for a long time.

Please do not overgeneralize your answers by speaking about "the adoption of the functional paradigm and its benefits", because this is not the topic of the question.

答:
It certainly isn't the only factor, but I'll point out the popularity of Ruby. Not saying this is more important than any of the six answers already on the board, but I think that many things happened at once and that it's useful to enumerate them all.

Ruby is not a functional language and its lambdas, prods, and blocks seem clunky when you've used something like ML, but the fact is, it popularized the notion of mapping and reducing to a generation of young programmers fleeing Java and PHP for hipper pastures. Lambdas in several languages seem to be defensive moves more than anything else ("Stick around! We've got those too!!)

But the block syntax and the way it integrated with .each, .map, .reduce and so forth popluarized the idea of an anonymous function even if it's really a syntactic construct that behaves like a coroutine. And the easy conversion to a proc via & makes it a gateway drug for functional programming.

I argue that Ruby on Rails programmers writing JavaScript were already turned on to doing things in a lightweight functional style. Couple that with programmer blogging, the invention of Reddit, hacker News, and Stack Overflow around the same time, and the ideas spread faster over the Internet than they did in the days of Newsgroups.

TL;DR: Ruby, Rails, JavaScript, blogging, and Reddit/Hacker News/Stack Overflow pushed functional ideas to a mass market, so everyone wanted them in existing languages to prevent further defections.


答:
You could deduce the answer logically since you seem to be aware of the differences between the two.

Interfaces define a common contract. Such as an interface called IAnimal, where all animals share functions such as Eat(), Move(), Attack() etc. While all of them share the same functions, all or most of them have a different way (implementation) of achieving it.

Abstract classes define a common implementation and optionally common contracts. For example a simple Calculator could qualify as an abstract class which implements all the basic logical and bitwise operators and then gets extended by ScientificCalculator, GraphicalCalculator and so on.

If you have common implementation then by all means, encapsulate the functionality in an abstract class to extend from. I have near 0 PHP experience, but i don't think you can create interfaces with non constant fields. If the fields are common between your instance classes then you are forced to use an Abstract class, unless you define access to them via getters and setters.

Also, there seems to be no shortage of results in Google.

Title: What are the differences between abstract classes, interfaces, and when to use them

Body:
Recently I have started to wrap my head around OOP, and I am now to the point where the more I read about the differences between abstract classes and interfaces the more confused I become. So far, neither can be instantiated.  Interfaces are more or less structural blueprints that determine the skeleton and abstracts are different by being able to partially implement code.

I would like to learn more about these through my specific situation. Here is a link to my first question if you would like a little more background information: What is a good design model for my new class?

Here are two classes I created:

```<code>class Ad {
    $title;
    $description
    $price;

    function get_data($website){  }

    function validate_price(){  }
 }

class calendar_event {
    $title;
    $description

    $start_date;

    function get_data($website){ //guts }

    function validate_dates(){ //guts }
 }
</code>```

So, as you can see these classes are almost identical. Not shown here, but there are other functions, like get_zip(), save_to_database() that are common across my classes. I have also added other classes Cars and Pets which have all the common methods and of course properties specific to those classes (mileage, weight, for example).

Now I have violated the DRY principle and I am managing and changing the same code across multiple files. I intend on having more classes like boats, horses, or whatever.

So is this where I would use an interface or an abstract class? From what I understand about abstract classes, I would use a super class as a template with all of the common elements built into the abstract class, and then add only the items specifically needed in future classes. For example:

```<code>abstract class content {
    $title;
    $description

    function get_data($website){  }

    function common_function2() { }
    function common_function3() { }
 }

class calendar_event extends content {

    $start_date;

    function validate_dates(){  }
 }
</code>```

Or would I use an interface and, because these are so similar, create a structure that each of the subclasses are forced to use for integrity reasons, and leave it up to the end developer who fleshes out that class to be responsible for each of the details of even the common functions. my thinking there is that some 'common' functions may need to be tweaked in the future for the needs of their specific class.

Despite all that above, if you believe I am misunderstanding the what and the why of abstract classes and interfaces altogether, by all means let a valid answer to be stop thinking in this direction and suggest the proper way to move forward!

Thanks!


答:
First off, you should understand that you will often provide both an interface and an abstract class. The reason for this, and the core difference between the two, is that they allow you to re-use different code, and so solve different problems.

Interfaces allow you to re-use client code with different implementations. A client of you get_data($website) class doesn't care about the $title or $description items. It just wants to instruct your content to load the data. If you have different types of content, some of which need a $description, and some which do not, you could provide a ContentInterface class that only specifies the signature of your child classes. Now the client can have any number of different Contents without every knowing exactly how they work. The Liskov Substitution Principle is a good thing to read about to study this idea. I also like Uncle Bob's writing on the topic. Interfaces are very important to unit testing, and creating interfaces is a good habit to learn.

Abstract classes allow you to re-use common implementation details across a set of classes that share a common ancestor. In your question you seem to have a good handle on why you would inherit implementation from an abstract class. It is still dangerous to depend on the internals of a base class - it is very easy to violate encapsulation and create children who depend on specific implementation details of a base class. The Template Method Pattern provides a common and healthy example of how to use base classes without violating encapsulation.

So, as I hope I've shown, you will often provide interfaces for the clients of your class hierarchy, so you can safely change your implementation without impacting the client code. This allows the client to write unit tests using Mock Objects that inherit your interface. And you will also provide abstract classes that allow re-use of common logic or enforce semantics for the child classes.


问:
How do you use blank lines in your code?
There has been a few remarks about white space already in discussion about curly braces placements.

I myself tend to sprinkle my code with blank lines in an attempt to segregate things that go together in "logical" groups and hopefully make it easier for the next person to come by to read the code I just produced.

In fact, I would say I structure my code like I write: I make paragraphs, no longer than a few lines (definitely shorter than 10), and try to make each paragraph self-contained.

For example:

in a class, I will group methods that go together, while separating them by a blank line from the next group.

if I need to write a comment I'll usually put a blank line before the comment

in a method, I make one paragraph per step of the process

All in all, I rarely have more than 4/5 lines clustered together, meaning a very sparse code.

I don't consider all this white space a waste because I actually use it to structure the code (as I use the indentation in fact), and therefore I feel it worth the screen estate it takes.

For example:

```<code>for (int i = 0; i < 10; ++i)
{
    if (i % 3 == 0) continue;

    array[i] += 2;
}
</code>```

I consider than the two statements have clear distinct purposes and thus deserve to be separated to make it obvious.

So, how do you actually use (or not) blank lines in code ?

答:
My rules of thumb are these:

If I have trouble reading the code I wrote yesterday, I probably need to extract a method or three.

If my class definition is too long to read easily, I probably need to extract a module/interface/object.

Method definitions: add a line

Module/Class definitions: add two lines


答:
In layman's terms:

Interfaces are for "can do/can be treated as" type of relationships.

Abstract ( as well as concrete ) classes are for "is a" kind of relationship.

Look at these examples:

```<code>class Bird extends Animal implements Flight;
class Plane extends Vehicle implements Flight, AccountableAsset;
class Mosquito extends Animal implements Flight;
class Horse extends Animal;
class RaceHorse extends Horse implements AccountableAsset;
class Pegasus extends Horse implements Flight;
</code>```

Bird, Mosquito and Horse are Animals. They are related. They inherit common methods from Animal like eat(), metabolize() and reproduce(). Maybe they override these methods, adding a little extra to them, but they take advantage of the default behavior implemented in Animal like metabolizeGlucose().

Plane is not related to Bird, Mosquito or Horse.

Flight is implemented by dissimilar, unrelated classes, like Bird and Plane.

AccountableAsset is also implemented by dissimilar, unrelated classes, like Plane and RaceHorse.

Horse doesn't implement Flight.

As you can see classes (abstract or concrete) helps you build hierarchies, letting you inhering code from the upper levels to the lower levels of the hierarchy. In theory the lower you are in the hierarchy, the more specialized your behavior is, but you don't have to worry about a lot of things that are already taken care of.

Interfaces, in the other hand, create no hierarchy, but they can help homogenize certain behaviors across hierarchies so you can abstract them from the hierarchy in certain contexts.

For example you can have a program sum the value of a group of AccountableAssets regardless of their being RaceHorses or Planes.

Body:
In layman's terms:

Interfaces are for "can do/can be treated as" type of relationships.

Abstract ( as well as concrete ) classes are for "is a" kind of relationship.

Look at these examples:

class Bird extends Animal implements Flight;
class Plane extends Vehicle implements Flight, AccountableAsset;
class Mosquito extends Animal implements Flight;
class Horse extends Animal;
class RaceHorse extends Horse implements AccountableAsset;
class Pegasus extends Horse implements Flight;

Bird, Mosquito and Horse are Animals. They are related. They inherit common methods from Animal like eat(), metabolize() and reproduce(). Maybe they override these methods, adding a little extra to them, but they take advantage of the default behavior implemented in Animal like metabolizeGlucose().

Plane is not related to Bird, Mosquito or Horse.

Flight is implemented by dissimilar, unrelated classes, like Bird and Plane.

AccountableAsset is also implemented by dissimilar, unrelated classes, like Plane and RaceHorse.

Horse doesn't implement Flight.

As you can see classes (abstract or concrete) helps you build hierarchies, letting you inhering code from the upper levels to the lower levels of the hierarchy. In theory the lower you are in the hierarchy, the more specialized your behavior is, but you don't have to worry about a lot of things that are already taken care of.

Interfaces, in the other hand, create no hierarchy, but they can help homogenize certain behaviors across hierarchies so you can abstract them from the hierarchy in certain contexts.

For example you can have a program sum the value of a group of AccountableAssets regardless of their being RaceHorses or Planes.

ContentLicense: CC BY-SA 4.0


问:
Where should I put a method that returns a list of active entries of a table?
I have a class named GuestbookEntry that maps to the properties that are in the database table named "guestbook". Very simple!

Originally, I had a static method named getActiveEntries() that retrieved an array of all GuestbookEntry objects. Each row in the guestbook table was an object that was added to that array. Then while learning how to properly design PHP classes, I learned some things:

Static methods are not desirable.

Separation of Concerns

Single Responsibility Principle

If the GuestbookEntry class should only be responsible for managing single guestbook entries then where should this getActiveEntries() method most properly go?

Update:

I am looking for an answer that complies with the SOLID acronym principles and allows for test-ability. That's why I want to stay away from static calls/standard functions.

DAO, repository, ...? Please explain as though your explanation will be part of "Where to Locate FOR DUMMIES"... :-)

答:
Where did you learn that static methods are not desirable?  I have a question for you: how many guestbook tables do you have?  Obviously, you only have 1.

Sometimes it makes a lot of sense to use a plain old function or static method to perform meta-operations that are a "level above".

Some people would advocate a GuestbookEntryCollection class which manages a set of GuestBookEntry objects, but ...

... here is where purism vs. pragmatism come into play.

If all you need is a list of GuestBookEntry objects, then put that code in a callable (be it a function, or static method), and just call it.

Do you need advanced features, like building a custom query, sorting them, filtering them, etc...?  Maybe that warrants a separate class for managing it.

What's the difference between objects and functions?  Objects can maintain individual state, while functions are stateless.  If you are performing functional operations and do not have state to manage, then functions are great!

Here is another thing to consider... In PHP, functions need to be manually included before they can be used, but classes have the ability to autoload.

```<code>include('/path/to/function.php')
$x = GuestbookEntryList()
</code>```

vs.

```<code>$x = GuestbookEntry::GetList()
</code>```

vs.

```<code>$x = new GuestbookEntryCollection()
</code>```

Food for thought :)

Body:
Where did you learn that static methods are not desirable?  I have a question for you: how many guestbook tables do you have?  Obviously, you only have 1.

Sometimes it makes a lot of sense to use a plain old function or static method to perform meta-operations that are a "level above".

Some people would advocate a GuestbookEntryCollection class which manages a set of GuestBookEntry objects, but ...

... here is where purism vs. pragmatism come into play.

If all you need is a list of GuestBookEntry objects, then put that code in a callable (be it a function, or static method), and just call it.

Do you need advanced features, like building a custom query, sorting them, filtering them, etc...?  Maybe that warrants a separate class for managing it.

What's the difference between objects and functions?  Objects can maintain individual state, while functions are stateless.  If you are performing functional operations and do not have state to manage, then functions are great!

Here is another thing to consider... In PHP, functions need to be manually included before they can be used, but classes have the ability to autoload.

include('/path/to/function.php')
$x = GuestbookEntryList()

vs.

$x = GuestbookEntry::GetList()

vs.

$x = new GuestbookEntryCollection()

Food for thought :)


答:
Here's how I would do it. For row data just use arrays, so:

```$entry = array(
    'entry_id' => '23',
    'user_id' => '4',
    'creation_date' => '2012-11-03',
    'content' => 'blah blah.');```

Your database model calls will return row data in the above format - this is also how PHP database plugins return data so you don't really have to do anything. Then for getting the data just have a model object:

```class EntryModel {
    public function getEntries() {
        //
    }

    public function getEntry($entryID) {
        //
    }
}```

So as you can see it doesn't matter if you're getting a single entry or a bunch of entries - just have your method return the desired data set.

Title: Where should I put a method that returns a list of active entries of a table?

Body:
I have a class named GuestbookEntry that maps to the properties that are in the database table named "guestbook". Very simple!

Originally, I had a static method named getActiveEntries() that retrieved an array of all GuestbookEntry objects. Each row in the guestbook table was an object that was added to that array. Then while learning how to properly design PHP classes, I learned some things:

Static methods are not desirable.

Separation of Concerns

Single Responsibility Principle

If the GuestbookEntry class should only be responsible for managing single guestbook entries then where should this getActiveEntries() method most properly go?

Update:

I am looking for an answer that complies with the SOLID acronym principles and allows for test-ability. That's why I want to stay away from static calls/standard functions.

DAO, repository, ...? Please explain as though your explanation will be part of "Where to Locate FOR DUMMIES"... :-)

Body:
Here's how I would do it. For row data just use arrays, so:

$entry = array(
    'entry_id' => '23',
    'user_id' => '4',
    'creation_date' => '2012-11-03',
    'content' => 'blah blah.');

Your database model calls will return row data in the above format - this is also how PHP database plugins return data so you don't really have to do anything. Then for getting the data just have a model object:

class EntryModel {
    public function getEntries() {
        //
    }

    public function getEntry($entryID) {
        //
    }
}

So as you can see it doesn't matter if you're getting a single entry or a bunch of entries - just have your method return the desired data set.


答:
Difference is subtle but a clear one. Interface is about polymorphic behavior. Abstract class is about reuse and polymorphic behavior.

If you want to put emphasis on reuse and polymorphic behavior, choose abstract class. For example, different types employees have different provisions but all receive a few common. So, abstract class is suitable to represent it because commonalities can be expressed in a base abstract class Employee and the difference can be implemented in derived classes like Manager or Worker etc.

If you want to put emphasis on only polymorphic behavior, choose interface. Interface is more about contract, i.e., an object or hierarchy saying it conforms to certain behavior. For example, all employees have leave provision but different types of employees have  different types of provisionss. So, each different type of employee requires a different leave calculator. Here interface is a good choice because all types of employees can implement a LeaveCalculator interface with a Calculate() behavior differently.


答:
This use case calls for a data access object (DAO), which handles the responsibility of retrieving objects from the underlying data store.

For example, you could define a GuestbookEntryDao with methods such as getById(...), getActiveEntries(...sort options...), etc.

Edit: In response to your comment:

GuestbookEntryDao would be an interface, ultimately implemented by a MySqlGuestBookEntryDao class or so. The point is that you can later switch implementations (drop in a FlatXmlGuestBookEntryDao class) without affecting the rest of the app.

GuestbookEntry would not extend GuestbookEntryDao, and IMHO should not depend on it either (although some people disagree): They should be separate objects entirely, because there are 2 separate responsibilities in play (the model and data access responsibilities).

The result is that, somewhere in your app, you will have a high-level process representing a use case of your application which might looks something like (pseudo-code):

```<code>function browseGuestBook() {

    // ... determine which entries to retrieve ...

    // retrieve entries
    entries = guestBookEntryDao.getActiveEntries(...);

    // store entries in output model
    // (this part may vary wildly depending on your app)
    guestbookBrowserOutput.entries = entries;

    // ...

}
</code>```

The classes where such functions/processes reside are usually called services in domain-driven design (I'm referring to an application-level service in this case, not a domain service). This object will depend on GuestbookEntryDao to retrieve the needed entries; GuestbookEntry does not know GuestbookEntryDao exists.

This also relates to dependency injection and providing objects with the references they need to do their job - nothing more and nothing less - but that's a different topic...

Body:
This use case calls for a data access object (DAO), which handles the responsibility of retrieving objects from the underlying data store.

For example, you could define a GuestbookEntryDao with methods such as getById(...), getActiveEntries(...sort options...), etc.

Edit: In response to your comment:

GuestbookEntryDao would be an interface, ultimately implemented by a MySqlGuestBookEntryDao class or so. The point is that you can later switch implementations (drop in a FlatXmlGuestBookEntryDao class) without affecting the rest of the app.

GuestbookEntry would not extend GuestbookEntryDao, and IMHO should not depend on it either (although some people disagree): They should be separate objects entirely, because there are 2 separate responsibilities in play (the model and data access responsibilities).

The result is that, somewhere in your app, you will have a high-level process representing a use case of your application which might looks something like (pseudo-code):

function browseGuestBook() {

    // ... determine which entries to retrieve ...

    // retrieve entries
    entries = guestBookEntryDao.getActiveEntries(...);

    // store entries in output model
    // (this part may vary wildly depending on your app)
    guestbookBrowserOutput.entries = entries;

    // ...

}

The classes where such functions/processes reside are usually called services in domain-driven design (I'm referring to an application-level service in this case, not a domain service). This object will depend on GuestbookEntryDao to retrieve the needed entries; GuestbookEntry does not know GuestbookEntryDao exists.

This also relates to dependency injection and providing objects with the references they need to do their job - nothing more and nothing less - but that's a different topic...


问:
Maintainability of Boolean logic - Is nesting if statements needed?
Which of these is better for maintainability?

```<code>if (byteArrayVariable != null)
    if (byteArrayVariable .Length != 0)
         //Do something with byteArrayVariable
</code>```

OR

```<code>if ((byteArrayVariable != null) && (byteArrayVariable.Length != 0))
  //Do something with byteArrayVariable
</code>```

I prefer reading and writing the second, but I recall reading in code complete that doing things like that is bad for maintainability.

This is because you are relying on the language to not evaluate the second part of the if if the first part is false and not all languages do that.  (The second part will throw an exception if evaluated with a null byteArrayVariable.)

I don't know if that is really something to worry about or not, and I would like general feedback on the question.

Thanks.

答:
Don't waste time trying to trap for every non this condition. If you can disqualify the data or condition then do so as soon as possible.

```<code>if (byteArrayVariable == null) Exit;
if (byteArrayVariable.Length == 0) Exit;
// do something
</code>```

This lets you adapt your code much easier for new conditions

```<code>if (byteArrayVariable == null) Exit;
if (byteArrayVariable.Length == 0) Exit;
if (NewCondition == false) Exit;
if (NewerCondition == true) Exit;
// do something
</code>```

Body:
Don't waste time trying to trap for every non this condition. If you can disqualify the data or condition then do so as soon as possible.

if (byteArrayVariable == null) Exit;
if (byteArrayVariable.Length == 0) Exit;
// do something

This lets you adapt your code much easier for new conditions

if (byteArrayVariable == null) Exit;
if (byteArrayVariable.Length == 0) Exit;
if (NewCondition == false) Exit;
if (NewerCondition == true) Exit;
// do something


答:
Since you probably are looking for a purism kind of answer, and aren't just about what would work, then the Guestbook shouldn't even depend on a database.

Rather, you have a Guestbook, you have a Database and you have a GuestbookGateway. The gateway retrieves rows from the database in the form of PHP objects, and when something needs to change, the gateway has a save method that accepts a Guestbook. That's a proper separation of concerns.

ORM can lead to many issues from the tight coupling it's based on. I've had to deal with some of them in the past, and it wasn't pretty. However, it should be noted that for many applications (especially web applications that usually work the same way), ORM is good enough.


问:
Are there any drawbacks to the Major.Minor.YMDD.Build version strategy?
I'm trying to come up with a good version strategy to fit our specific needs. We've proposed settling on this and I wanted to ask the question to see if anyone's experience would suggest avoiding this or altering it in any way.

Here's our proposal:

Versions are released in this format: MAJOR.MINOR.YMDD.BN. Here it is broken out:

MAJOR & MINOR are typical; we'll increase MINOR when we feel code and new feature sets warrants it; once every few months most likely. MAJOR will increase ~yearly.

YMDD: Y will be the last digit of the current year, so "1" for 2011, "2" for 2012, etc. A non-padded month will be used to keep the number smaller (9 instead of 09 for example). DD of course is the day, padded with a zero for days under 10.

BN: BN is the build number and increases by one anytime we make a change to a branch of the code represented by the build, for example:

If were to make a build today, our release would be version 5.0.1707.1.  I release to QA today and 3 days from now QA finds that a change broke the save functionality on a page. Instead of me changing our current development code, I'd go back to the code that I used to create version 5.0.1707.1, make the fix there, then increase the BN portion of the version and would then re-release 5.0.1707.2 back to QA. In short, anytime a change is made to a branched version that isn't the active dev branch, we'd use the original version number and increase only the BN portion (even if the change happened 3 days, 3 weeks or 3 months from the initial release of that version).

Anytime we make a new release from our Active dev branch, we'd come up with a new version based on the M/D of the release using the outlined strategy. We do this once every 2-3 weeks.

Are there holes or pitfalls with this?  If so, what are they?

Thanks

EDIT

To clarify one point that I didn't get out very well - Oct/Nov/Dec will be two digits, it's only the year that won't be. So 9 for Sept, 10 for Oct, 11 for Nov, etc.

答:
PC time may not be synchronized to the same time server.
If more than one PCs build the program within a few minutes time, then the version number may not represent the order of build, which leads to confusion.</p>

OwnerDisplayName: Chu


问:
Why did object-oriented paradigms take so long to go mainstream?
I read this question and it got me thinking about another fairly recent thing. Object oriented languages. I'm not sure when the first one was created, but why did it take so long before they became mainstream?

C became vastly popular, but didn't become the object-oriented C++ for years(decades?) later

No mainstream language before the 90s was object oriented

Object oriented really seemed to take off with Java and C++ around the same time

Now, my question, why did this take so long? Why wasn't C originally conceived as an object-oriented language? Taking a very small subset of C++ wouldn't have affected the core language a whole lot, so why was this idea not popular until the 90s?

答:
First, let's try to establish a timeline:

1963 - Ivan Sutherland's Sketchpad is considered a pioneering work in both object orientation and GUIs.

1967 Simula appears, and whether it or Smalltak should be considered the first object oriented language is still a matter of debate.

1969 - Dennis Ritchie starts developing C.

1972 - Smalltalk, a language heavily influenced by Simula, appears. It's the brainchild of Alan Kay, who is generally considered the inventor of the term "object orientation" (Alan Kay also inspired the eponymous character in Tron ;).

1979 - Bjarne Stroustrup starts working on C with Classes, the precursor to C++.

1983 - Objective C appears, and essentially is an effort to add Smalltalk's flavour of object orientation to C.

1985 - Object Pascal appears, and is almost immediately popularized by Turbo Pascal 5.5.

1986 - Work begins on CLOS, an effort to bring object orientation to Common Lisp.

1991 - Visual Basic is released.

1995 - Java is released.

1995 - Delphi is released.

Ritchie's main influences were BCPL and ALGOL (both are imperative languages), and C was created at a time when Simula's and Smalltalk's approach to object orientation wasn't yet well known. It was completed around 1972 and C with Classes appeared only 7 years later, with both Dennis Ritchie and Brian Kernighan being involved in its inception:

At the time, I considered C the best systems programming language available. That was not as obvious then (1979) as it later became, but I had experts such as Dennis Ritchie, Steve Johnson, Sandy Fraser, Greg Chesson, Doug McIlroy, and Brian Kernighan down the corridor from whom I could learn and get feedback. Without their help and advice, and without C, C++ would have been stillborn.

Contrary to repeated rumors, I was never told that I had to use C; nor was I ever told not to use C. In fact, the first C++ manual grew from troff source of the C manual that Dennis gave me. Many new languages were designed at Bell labs; in "Research" at least, there were no rules enforcing language bigotry.

Objective C appeared 11 years later, and both it and C++ were major and successful efforts to bring object orientation to C. The gap might seem long now, but I don't think it was particularly long at the time, remember we're talking about an era before the World Wide Web. 1993, when Mosaic (the first browser) appeared was a turning point in the industry. Java and Delphi, released a couple of years later, had a huge advantage over their predecessors, at least in terms of popularity. The web was also one of the platforms Sun was targeting with their WORA promise, perhaps the more important one at the time, and Java was heavily marketed as the language for the then newly born platform.

Another key factor is that the late 1980's and early 1990's were a time when GUIs started becoming popular, especially in home computing, while at the same time hardware was getting cheaper and cheaper. Object orientation is an extremely convenient paradigm when developing GUIs and graphic oriented applications in general, and Turbo Pascal, Delphi, Visual Basic and (perhaps to a lesser extend) Java were lauded (at the time) for the simplicity they brought to GUI development.

Sun's aggressive marketing of Java obviously also played a role, however since I still vividly remember my first interaction with it, I was definitely not impressed. My first reaction to Java was "hm, nothing more than a resource hungry interpreted C++, I'll stick to Turbo Pascal, thank you very much" (hey, I was only 17 at the time ;). I don't know how anyone else reacted to Java at the time, but for me it was just a fad and I quickly moved on to Delphi (and Visual Basic, sigh), and only started using Java a few years later, in college, and only because it was a compulsory course.

While it's true that Java, and its flavour of object orientation, become popular extremely quickly, I really don't think the paradigm wasn't fairly popular before the mid 1990's, the introduction of the web changed our definition of popularity. In any case, the mid 1990's was a time when software development in general had a spurt of popularity, with the web, the proliferation of GUIs, and cheaper hardware being key factors. Java was simply at the right place at the right time.

Further reading:

Sketchpad: A man-machine graphical communication system (pdf)

A Brief History of the Object-Oriented Approach (pdf)

The Early History of Smalltalk

A Brief History of Object-Oriented Programming

Object-oriented programming article on Wikipedia

Related questions:

So what *did* Alan Kay really mean by the term "object-oriented"?

What did they call Object-Oriented Programming before Alan Kay invented the term?

Why is C not considered an 'object-oriented' language?

Is OOP hard because it is not natural?

What makes C so popular in the age of OOP?

Advantages of object-oriented programming

What's the benefit of object-oriented programming over procedural programming?

https://softwareengineering.stackexchange.com/questions/52608/what-is-object-oriented-programming-ill-suited-for

is OOP the dominant programming model in real world?


问:
Is it actually possible to have a 'useful' programming language that isn't Turing complete?
Where it is accepted that a language has to be Turing complete to be any good, is it actually possible to have a 'useful' programming language that isn't Turing complete?

I should clarify that this is quite specifically about 'programming' languages in the traditional sense, and not markup or query languages.

答: There actually do exist programming languages, where you can only write "efficient" programs. Efficient in this sense means that every program written in such a language represents a language in P. Bellantoni, Niggl and Schwichtenberg describe such a language here.


问:
What is the difference between "data hiding" and "encapsulation"?
I'm reading "Java concurrency in practice" and there is said: "Fortunately, the same object-oriented techniques that help you write well-organized, maintainable classes - such as encapsulation and data hiding -can also help you create thread-safe classes."

The problem #1 - I never heard about data hiding and don't know what it is.

The problem #2 - I always thought that encapsulation is using private vs public, and is actually the data hiding.

Can you please explain what data hiding is and how it differs from encapsulation?

答:
From Wikipedia:

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

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

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

Some programming language researchers and academics use the first
  meaning alone or in combination with the second as a distinguishing
  feature of object oriented programming, while other programming
  languages which provide lexical closures view encapsulation as a
  feature of the language orthogonal to object orientation.

The second definition is motivated by the fact that in many OOP
  languages hiding of components is not automatic or can be overridden;
  thus, information hiding is defined as a separate notion by those who
  prefer the second definition.


答:
Data and information hiding are a broader notions, found in computer science & software engineering. It refers to the fact that those part of a computer program that may change must not be accessible from other modules/from clients.

Encapsulation is a term that is found in Object-Oriented paradigm and refers to keeping the data in private fields and modify it only through methods.

Thus encapsulation may be seen as a way of achieving data hiding in object-oriented systems.

Title: What is the difference between "data hiding" and "encapsulation"?

Body:
I'm reading "Java concurrency in practice" and there is said: "Fortunately, the same object-oriented techniques that help you write well-organized, maintainable classes - such as encapsulation and data hiding -can also help you create thread-safe classes."

The problem #1 - I never heard about data hiding and don't know what it is.

The problem #2 - I always thought that encapsulation is using private vs public, and is actually the data hiding.

Can you please explain what data hiding is and how it differs from encapsulation?


问:
Is there an open source license with proprietairy-like terms?
Is there any license meeting the following criteria:

source code available (users allowed to browse the source)

users are allowed to modify the code with credits to the original author

not allowed to sell the software itself or any other program using code from it

can be sold by original author

答:
If you go by the definition of "open source" by The Open Source Initiative, then no you will not find a licence that fits your terms.

From the Open Source Definition:

3. Derived Works

The license must allow modifications and derived works, and must allow them to be distributed under the same terms as the license of the original software.

The second item in your original question is incompatible with that definition.

The "no commercial use" term you state is also incompatible with the OSD definition. Check for instance this FAQ item:

Can Open Source software be used for commercial purposes?

Absolutely. All Open Source software can be used for commercial purpose; the Open Source Definition guarantees this. You can even sell Open Source software.

However, note that commercial is not the same as proprietary. If you receive software under an Open Source license, you can always use that software for commercial purposes, but that doesn't always mean you can place further restrictions on people who receive the software from you. In particular, so-called copyleft-style Open Source licenses require that when you distribute the software, you do so under the same license you received it under.

Your last item isn't something that would be governed by the licence you choose to distribute your code. If you have the copyright to the code, you do whatever you want with it, including selling it and/or distributing it under a variety of licences.


问:
Compiler Warnings
Many compilers have warning messages to warn the programmers about potential runtime, logic and performance errors, most times, you quickly fix them, but what about unfixable warnings?

How do you deal with unfixable warnings? Do you re-write a portion of the code, or rewrite it in the "long, hackless way" or disable warnings all together? What should be the best practice?

What if you are editing someone else's code and his code has warnings?

Here is a good example:
jQuery has a lots of JavaScript warnings as a Mozilla-class browser detected, why the jQ developers don't fix them? If you contribute to jQuery, are you going to fix them?

答:
When I was writing in C and C++ I'd enable the strictest settings I could because I wanted to know when something wasn't making sense to the compiler. When I was done casting and checking return values I'd be happy because the code was as correct as I could make it.

I'd occasionally get code from someone else that would spew warnings. Checking the source showed they were ignoring things that were good programming practice in C, making their code fragile.

So, I think there are good reasons to enable strictness and take the time to fix things. Doing otherwise is sloppy. If I had a co-worker who turned off warnings I'd spend some time with them AND the manager explaining why that is a really bad thing.

Title: Compiler Warnings


问:
Using foldr to append two lists together (Haskell)
I have been given the following question as part of a college assignment. Due to the module being very short, we are using only a subset of Haskell, without any of the syntactic sugar or idiomatic shortcuts....I must write:

append xs ys : The list formed by joining the lists xs and ys, in that order

```<code>append (5:8:3:[]) (4:7:[]) => 5:8:3:4:7:[]
</code>```

I understand the concept of how foldr works, but I am only starting off in Functional programming. I managed to write the following working solution (hidden for the benefit of others in my class...) :

 append = \xs -> \ys -> foldr (\x -> \y -> x:y) ys xs

However, I just can't for the life of me, explain what the hell is going on!?
I wrote it by just fiddling around in the interpreter, for example, the following line :

```<code>foldr (\x -> \y -> x:y) [] (2:3:4:[])
</code>```

which returned [2:3:4] , which led me to try,

```<code>foldr (\x -> \y -> x:y) (2:3:4:[]) (5:6:7:[])
</code>```

which returned [5,6,7,2,3,4]

so I worked it out from there. I came to the correct solution through guess work and a bit of luck...

I am working from the following definition of foldr:

```<code>foldr = \f -> \s -> \xs -> if null xs then
                              s
                           else
                              f (head xs) (foldr f s (tail xs) )
</code>```

Can someone baby step me through my correct solution? I can't seem to get it....I already have scoured the web, and also read a bunch of SE threads, such as How foldr works

答:
Folds over lists consist of three elements - the list to fold over, some accumulator function f and an initial value.

They transform the list a:b:c:[] into (a f (b f (c f init))) where init is the initial element i.e. they replace the cons constructor : with your accumulator function and the empty list [] with your supplied initial value.

You can think of your append function as transforming the list x1:x2:..:xn into the list
x1:x2:..:xn:ys for some given list ys. This can be done by simply using ys as the replacement for the empty list [] which terminates your xs list.

Your code can be written as

```<code>append xs ys = foldr (\x y -> x:y) ys xs
</code>```

Your accumulator function f has the type a -> [a] -> [a] and is the same as the (:) function, so you could write it as

```<code>append xs ys = foldr (:) ys xs
</code>```

If the first argument xs is the list x1:x2:...:xn then the result of append is the list
x1:x2:...xn:ys as required.

Body:
Folds over lists consist of three elements - the list to fold over, some accumulator function f and an initial value.

They transform the list a:b:c:[] into (a f (b f (c f init))) where init is the initial element i.e. they replace the cons constructor : with your accumulator function and the empty list [] with your supplied initial value.

You can think of your append function as transforming the list x1:x2:..:xn into the list
x1:x2:..:xn:ys for some given list ys. This can be done by simply using ys as the replacement for the empty list [] which terminates your xs list.

Your code can be written as

append xs ys = foldr (\x y -> x:y) ys xs

Your accumulator function f has the type a -> [a] -> [a] and is the same as the (:) function, so you could write it as

append xs ys = foldr (:) ys xs

If the first argument xs is the list x1:x2:...:xn then the result of append is the list
x1:x2:...xn:ys as required.


答:
First let's simplify your solution a bit to standard Haskell to make it easier to comprehend:

```<code>append = \xs -> \ys -> foldr (\x -> \y -> x:y) ys xs
</code>```

can be written as

```<code>append xs ys = foldr (:) ys xs
</code>```

because \x -> \y -> x : y is equivalent to \x -> y -> (:) x y which is equivalent to (:) (this is called η-reduction, here we applied it twice).

I assume you know how foldr works so let's have a look at this special case:
Here foldr is specialized to type (a -> [a] -> [a]) -> [a] -> [a] -> [a].
The value that is accumulated during folding is of type [a], the same type as the list we're consuming. (This is probably what makes this a bit confusing.) We start with ys as the accumulated value. Then foldr processes elements of xs right-to-left, and at each step it prepends (using :) the currently inspected element to the currently accumulated value. So it starts by prepending the last element of xs in front of ys, then the second-to-last element of xs to that etc., finally building the whole xs prepended to ys.

(As another exercise for understanding folds, I suggest you to try to implement foldl just using foldr. Hover mouse over the following area for a hint.)

 The accumulated/returned value produced by foldr needs to be a function.

Title: Using foldr to append two lists together (Haskell)

Body:
I have been given the following question as part of a college assignment. Due to the module being very short, we are using only a subset of Haskell, without any of the syntactic sugar or idiomatic shortcuts....I must write:

append xs ys : The list formed by joining the lists xs and ys, in that order

```<code>append (5:8:3:[]) (4:7:[]) => 5:8:3:4:7:[]
</code>```

I understand the concept of how foldr works, but I am only starting off in Functional programming. I managed to write the following working solution (hidden for the benefit of others in my class...) :

 append = \xs -> \ys -> foldr (\x -> \y -> x:y) ys xs

However, I just can't for the life of me, explain what the hell is going on!?
I wrote it by just fiddling around in the interpreter, for example, the following line :

```<code>foldr (\x -> \y -> x:y) [] (2:3:4:[])
</code>```

which returned [2:3:4] , which led me to try,

```<code>foldr (\x -> \y -> x:y) (2:3:4:[]) (5:6:7:[])
</code>```

which returned [5,6,7,2,3,4]

so I worked it out from there. I came to the correct solution through guess work and a bit of luck...

I am working from the following definition of foldr:

```<code>foldr = \f -> \s -> \xs -> if null xs then
                              s
                           else
                              f (head xs) (foldr f s (tail xs) )
</code>```

Can someone baby step me through my correct solution? I can't seem to get it....I already have scoured the web, and also read a bunch of SE threads, such as How foldr works

Body:
First let's simplify your solution a bit to standard Haskell to make it easier to comprehend:

append = \xs -> \ys -> foldr (\x -> \y -> x:y) ys xs

can be written as

append xs ys = foldr (:) ys xs

because \x -> \y -> x : y is equivalent to \x -> y -> (:) x y which is equivalent to (:) (this is called η-reduction, here we applied it twice).

I assume you know how foldr works so let's have a look at this special case:
Here foldr is specialized to type (a -> [a] -> [a]) -> [a] -> [a] -> [a].
The value that is accumulated during folding is of type [a], the same type as the list we're consuming. (This is probably what makes this a bit confusing.) We start with ys as the accumulated value. Then foldr processes elements of xs right-to-left, and at each step it prepends (using :) the currently inspected element to the currently accumulated value. So it starts by prepending the last element of xs in front of ys, then the second-to-last element of xs to that etc., finally building the whole xs prepended to ys.

(As another exercise for understanding folds, I suggest you to try to implement foldl just using foldr. Hover mouse over the following area for a hint.)

 The accumulated/returned value produced by foldr needs to be a function.


问:
Is data integrity possible without normalization?
I am working on an application that requires the storage of location information such as city, state, zip code, latitude, and longitude. I would like to ensure:

Location data is accurate

Detroit, CA

Detroit IS NOT in California

Detroit, MI

Detroit IS in Michigan

Cities and states are spelled correctly

California not Calefornia

Detroit not Detriot

Cities and states are named consistently

Valid:

CA

Detroit

Invalid:

Cali

california

DET

d-town

The D

Also, since city/zip data is not guaranteed to be static, updating this data in a normalized fashion could be difficult, whereas it could be implemented as a de facto location if it is denormalized.

A couple thoughts that come to mind:

A collection of reference tables that store a list of all states and the most common cities and zip codes that can grow over time. It would search the database for an exact or similar match and recommend corrections.

Use some sort of service to validate the location data before it is stored in the database.

Is it possible to fulfill these requirements without normalization, and if so, should I denormalize this data?

答:
Yes.  You can always make sure the data conforms to the rules inside the application program(s) before adding the data to the database.  There are two things that make this hard to do.

The first is the imperative nature of almost all programming languages.  There is no simple way you can declare that a given field should never be left null or should always refer to an existing  referent or should always be in such and such a domain.  Such declarative rules would generally be counterproductive when dealing with program variables anyway.

So you have to check every execution path to make sure that it doesn't break the rules.  Encapsulation helps, but not enough.

The second is that multiple application programs can interact with the same database.  I've seen databases where dozens of programs, parts of several applications, share data by reading and writing to the same database.  Making sure none of those programs goes rogue is next to impossible.

By contrast, DBMS constraints are declarative, relatively simple, and get applied whenever necessary in the context of transactions that manipulate the data.   Triggers can make the enforcement more flexible, at the cost of going down the imperative route rather than the declarative one.

Normalizaton is only relevant to certain types of violation of data integrity.  The focus of normal forms 2NF through 5NF is to obviate the possibility of leaving the database in a self contradictory state.  The normal forms do this by ensuring that a single fact is only stored in one place.  It's either right or it's wrong, but it it isn't contradicted by another fact stored elsewhere in the database.

This can be enormously helpful in reducing the incidence of violations of integrity.  But there are plenty of cases of integrity that have nothing to do with normalization.  Referential integrity is one such case.

In nearly every case where a programmer opts out of DBMS enforced integrity because "my programs never have logic errors" or "the DBMS runs too slow", that programmer or his/her successor has lived to regret it.  Remember, the value of data often outlasts the system that captured it.

In the case that you gave us, where Detroit, CA is known to be wrong,  how can you be sure?  How do you know there isn't some tiny little suburb, somewhere in California, that has been given the name "Detroit"?  You can assume that, if it isn't in the database, then it can't be true.  But that assumption can easily come back to bite you.


答:
Anonymous functions are nice because naming things is hard, and if you only use a function in once place, it doesn't need a name.

Lambda functions have only recently become mainstream because until recently, most languages didn't support closures.

I would suggest that Javascript has pushed this mainstream. It's a universal language that has no way to express parallelism, and anonymous functions ease the use of callback models. Additionally popular languages like Ruby and Haskell have contributed.

Title: What triggered the popularity of lambda functions in modern mainstream programming languages?

Body:
In the last few years anonymous functions (AKA lambda functions) have become a very popular language construct and almost every major / mainstream programming language has introduced them or is planned to introduce them in an upcoming revision of the standard.

Yet, anonymous functions are a very old and very well-known concept in Mathematics and Computer Science (invented by the mathematician Alonzo Church around 1936, and used by the Lisp programming language since 1958, see e.g. here).

So why didn't today's mainstream programming languages (many of which originated 15 to 20 years ago) support lambda functions from the very beginning and only introduced them later?

And what triggered the massive adoption of anonymous functions in the last few years? Is there some specific event, new requirement or programming technique that started this phenomenon?

IMPORTANT NOTE

The focus of this question is the introduction of anonymous functions in modern, main-stream (and therefore, maybe with a few exceptions, non functional) languages.
Also, note that anonymous functions (blocks) are present in Smalltalk, which is not a functional language, and that normal named functions have been present even in procedural languages like C and Pascal for a long time.

Please do not overgeneralize your answers by speaking about "the adoption of the functional paradigm and its benefits", because this is not the topic of the question.


问:
What are some famous one-liner or two-liner programs and equations?
I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

```<code>#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}
</code>```

60 characters exactly!

Thanks so much for your wisdom!

答:
Not quite 2 lines but I would say this is quite famous:

```<code>void swap(float* x, float* y)
{
    float t;
    t = *x;
    *x = *y;
    *y = t;
}
</code>```

Actually some languages can describe it in one line. Lua comes to mind but there are more.

```<code>x, y = y, x
</code>```

Body:
Not quite 2 lines but I would say this is quite famous:

void swap(float* x, float* y)
{
    float t;
    t = *x;
    *x = *y;
    *y = t;
}

Actually some languages can describe it in one line. Lua comes to mind but there are more.

x, y = y, x


问:
History of Associative Array?
In quite a lot of modern scripting languages (e.g. Perl, Python, Ruby, PHP, Lua, JavaScript), associative arrays are supported as a primitive or first-class data type (with various names like map, dictionary, hash, etc.) in a very convenient syntax, making convenient data-driven paradigms possible.

Which language first adopted such a design? And how has this design evolved?

答:
Which language first adopted such a design? And how was this design evolved?

I don't know if it was first, but AWK had associative arrays long before Perl, Python, Ruby, PHP, etc. were ever conceived. Update: Yannis says SNOBOL4 had associative arrays before AWK, and it didn't take much googling to find a page that agrees. Here's an interesting piece about how associative arrays are implemented in SNOBOL4.

Although other early languages like Lisp may not have explicit support for associative arrays as a built-in type, you can easily implement them in other ways. In Lisp, for example, you could implement an associative array as a list of lists where each sub-list has two items: a key and a value.

Are you interested in the history of the associative array concept, in which values are accessed using a key rather than a numeric index, or are you interested in the history of the algorithm(s) used to implement associative arrays? Hash tables are commonly used to implement associative arrays, but as the SNOBOL4 link above shows, they're not the only possible implementation.

The idea of associating keys and values certainly predates computer languages and computers at all. Card catalogs and book indices are just two examples of real-world associative arrays.

Title: History of Associative Array?


答:
Having been involved in the recent history here a bit, I believe that one factor was the addition of generics to Java and .NET. That naturally leads to Func<,> and other strongly typed computational abstractions (Task<>, Async<> etc.)

In the .NET world we added these features precisely to support FP. That triggered a cascading set of language work related to functional programming, especially C# 3.0, LINQ, Rx and F#. That progression influenced other ecosystems too and still continues today in C#, F# and TypeScript.

It helps to have Haskell work at MSR too, of course :)

Of course there were many other influences too (JS certainly) and these steps were in turn influenced by many other things - but adding generics to these languages helped break the rigid OO orthodoxy of the late 90s in large parts of the software world and helped open the door for FP.

Don Syme

p.s. F# was 2003, not 2005 - though we would say it did not reach 1.0 until 2005. We also did a Haskell.NET prototype in 2001-02.


答:
I think the first language that included native support for associated arrays was SNOBOL4 (1967), calling them tables. From THE SNOBOL4 PROGRAMMING LANGUAGE (second edition):

Often it is desirable to associate a group of items with one variable name through numerical indexing or some other identifying property. The SNOBOL4 array and table provide these capabilities with more flexibility than most programming languages. An array is a data element consisting of a set of pointers to other data elements, so that each array element may be any data type, even an array. An element of an array is referenced by using an integer index. A table is similar to an array, except that the reference value need not be an integer, but can be any of several other types. Conversion can be made between tables and arrays.

...

1.13 Tables

Sets of pairs of associated data objects can be created by the use of tables. A table is similar to a one-dimensional array. However, instead of referencing an element with an integer, any data object can be used.

A table is created by the primitive function TABLE. For example

```<code>T TABLE ( )
</code>```

creates a table and assigns it as value of T.

Elements in the table can be assigned values In a manner similar to array elements.

Examples are

```<code>T<'A'> 5
</code>```

and

T T + 1

Tables have varying lengths and are dynamically extended if necessary. Some efficiency can be achieved by specifying an estimate of the size of a table at the time it is created.  TABLE (N) creates a table that initially has room for N entries.

MUMPS (1966) natively supports sparse multi-dimensional arrays, stored as b-trees, but I can't really find a solid reference that explains the original design.

AWK (1977) natively supports one-dimensional sparse arrays and directly influenced Perl. PHP in turn has borrowed a lot of concepts from Perl (including associative arrays), as the first version of PHP was simply a collection of Perl scripts.

In any case, associative arrays are a fundamental and trivial data type, although implementations have certainly evolved over time, I don't really think the design changed much.

Title: History of Associative Array?

Body:
In quite a lot of modern scripting languages (e.g. Perl, Python, Ruby, PHP, Lua, JavaScript), associative arrays are supported as a primitive or first-class data type (with various names like map, dictionary, hash, etc.) in a very convenient syntax, making convenient data-driven paradigms possible.

Which language first adopted such a design? And how has this design evolved?

Body:
I think the first language that included native support for associated arrays was SNOBOL4 (1967), calling them tables. From THE SNOBOL4 PROGRAMMING LANGUAGE (second edition):

Often it is desirable to associate a group of items with one variable name through numerical indexing or some other identifying property. The SNOBOL4 array and table provide these capabilities with more flexibility than most programming languages. An array is a data element consisting of a set of pointers to other data elements, so that each array element may be any data type, even an array. An element of an array is referenced by using an integer index. A table is similar to an array, except that the reference value need not be an integer, but can be any of several other types. Conversion can be made between tables and arrays.

...

1.13 Tables

Sets of pairs of associated data objects can be created by the use of tables. A table is similar to a one-dimensional array. However, instead of referencing an element with an integer, any data object can be used.

A table is created by the primitive function TABLE. For example

T TABLE ( )

creates a table and assigns it as value of T.

Elements in the table can be assigned values In a manner similar to array elements.

Examples are

T<'A'> 5

and

T T + 1

Tables have varying lengths and are dynamically extended if necessary. Some efficiency can be achieved by specifying an estimate of the size of a table at the time it is created.  TABLE (N) creates a table that initially has room for N entries.

MUMPS (1966) natively supports sparse multi-dimensional arrays, stored as b-trees, but I can't really find a solid reference that explains the original design.

AWK (1977) natively supports one-dimensional sparse arrays and directly influenced Perl. PHP in turn has borrowed a lot of concepts from Perl (including associative arrays), as the first version of PHP was simply a collection of Perl scripts.

In any case, associative arrays are a fundamental and trivial data type, although implementations have certainly evolved over time, I don't really think the design changed much.


问:
What is a thread pool?
How would one implement a threadpool? I've been reading on wikipedia for "threadpool" but I still can't figure out what one should do to solve this question (possibly because I didn't quite understand what a threadpool is in simple terms).

Can someone explain me in plain english what a threadpool is and how would one answer this question?

答:
In multithreaded application, thread pool is a "pool of available threads" that can be used by your application. Usually, e.g. .NET, it is all managed so you just assign tasks and once a thread is free, it is going to perform it.
So to implement a threadpool, I would expect to create a concept where tasks are automatically taken by free threads without explicit thread creation for each task.</p>

Title: What is a thread pool?


答:
Encapsulation and data hiding are related terms. It important to understand that they arise in relation to Abstraction. Booch et. al. in Object-Oriented Analysis and Design with Applications explains,

Abstraction and encapsulation are complementary concepts: Abstraction focuses on the observable behavior of an object, whereas encapsulation focuses on the implementation that gives rise to this behavior. Encapsulation is most often achieved through information hiding (not just data hiding), which is the process of hiding all the secrets of an object that do not contribute to its essential characteristics; typically, the structure of an object is hidden, as well as the implementation of its methods.


答:
Thread pool is a collection of managed threads usually organized in a queue, which execute the tasks in the task queue.

Creating a new thread object every time you need something to be executed asynchronously is expensive. In a thread pool you would just add the tasks you wish to be executed asynchronously to the task queue and the thread pool takes care of assigning an available thread, if any, for the corresponding task. As soon as the task is completed, the the now available thread requests another task (assuming there is any left).

Thread pool helps you avoid creating or destroying more threads, than would really be necessary.

I would start by creating a class with a queue of threads and a queue of tasks. Then implement a method which adds a task to the task queue and move on from there. Obviously, you should also make it possible to set the maximum allowed threads in a thread pool.

Title: What is a thread pool?

Body:
How would one implement a threadpool? I've been reading on wikipedia for "threadpool" but I still can't figure out what one should do to solve this question (possibly because I didn't quite understand what a threadpool is in simple terms).

Can someone explain me in plain english what a threadpool is and how would one answer this question?