答:
Taking your example (with a bit of refactoring),

```<code>assert(a + b, math.add(a, b));
</code>```

doesn't help to:

understand how math.add behaves internally,

know what will happen with edge cases.

It's pretty much as saying:

If you want to know what the method does, go and see the hundreds of lines of source code yourself (because, yes, math.add can contain hundreds of LOC; see below).

I don't bother to know if the method works correctly. It's ok if both expected and actual values are different from what I really expected.

This also means that you don't have to add tests like:

```<code>assert(3, math.add(1, 2));
assert(4, math.add(2, 2));
</code>```

They don't help neither, or at least, once you made the first assertion, the second one brings nothing useful.

Instead, what about:

```<code>const numeric Pi = 3.1415926535897932384626433832795;
const numeric Expected = 4.1415926535897932384626433832795;
assert(Expected, math.add(Pi, 1),
    "Adding an integer to a long numeric doesn't give a long numeric result.");
assert(Expected, math.add(1, Pi),
    "Adding a long numeric to an integer doesn't give a long numeric result.");
</code>```

This is self-explanatory and damn helpful both for you and for the person who will maintain the source code later. Imagine that this person does a slight modification to the math.add to simplify the code and optimize the performance, and sees the test result like:

```<code>Test TestNumeric() failed on assertion 2, line 5: Adding a long numeric to an
integer doesn't give a long numeric result.

Expected value: 4.1415926535897932384626433832795
Actual value: 4
</code>```

this person will understand immediately that the newly modified method depends on the order of the arguments: if the first argument is an integer and the second one is a long numeric, the result would be an integer, while a long numeric was expected.

In the same way, obtaining the actual value of 4.141592 at the first assertion is self-explanatory: you know that the method is expected to deal with a big precision, but actually, it fails.

For the very same reason, two following assertions can make sense in some languages:

```<code>// We don't expect a concatenation. `math` library is not intended for this.
assert(0, math.add("Hello", "World"));

// We expect the method to convert every string as if it was a decimal.
assert(5, math.add("0x2F", 5));
</code>```

Also, what about:

```<code>assert(numeric.Infinity, math.add(numeric.Infinity, 1));
</code>```

Self-explanatory too: you want your method to be able to deal correctly with the infinity. Going beyond infinity or throwing an exception is not an expected behavior.

Or maybe, depending on your language, this will make more sense?

```<code>/**
 * Ensures that when adding numbers which exceed the maximum value, the method
 * fails with OverflowException, instead of restarting at numeric.Minimum + 1.
 */
TestOverflow()
{
    UnitTest.ExpectException(ofType(OverflowException));

    numeric result = math.add(numeric.Maximum, 1));

    UnitTest.Fail("The tested code succeeded, while an OverflowException was
        expected.");
}
</code>```

Title: How does unit testing work?

Body:
Taking your example (with a bit of refactoring),

assert(a + b, math.add(a, b));

doesn't help to:

understand how math.add behaves internally,

know what will happen with edge cases.

It's pretty much as saying:

If you want to know what the method does, go and see the hundreds of lines of source code yourself (because, yes, math.add can contain hundreds of LOC; see below).

I don't bother to know if the method works correctly. It's ok if both expected and actual values are different from what I really expected.

This also means that you don't have to add tests like:

assert(3, math.add(1, 2));
assert(4, math.add(2, 2));

They don't help neither, or at least, once you made the first assertion, the second one brings nothing useful.

Instead, what about:

const numeric Pi = 3.1415926535897932384626433832795;
const numeric Expected = 4.1415926535897932384626433832795;
assert(Expected, math.add(Pi, 1),
    "Adding an integer to a long numeric doesn't give a long numeric result.");
assert(Expected, math.add(1, Pi),
    "Adding a long numeric to an integer doesn't give a long numeric result.");

This is self-explanatory and damn helpful both for you and for the person who will maintain the source code later. Imagine that this person does a slight modification to the math.add to simplify the code and optimize the performance, and sees the test result like:

Test TestNumeric() failed on assertion 2, line 5: Adding a long numeric to an
integer doesn't give a long numeric result.

Expected value: 4.1415926535897932384626433832795
Actual value: 4

this person will understand immediately that the newly modified method depends on the order of the arguments: if the first argument is an integer and the second one is a long numeric, the result would be an integer, while a long numeric was expected.

In the same way, obtaining the actual value of 4.141592 at the first assertion is self-explanatory: you know that the method is expected to deal with a big precision, but actually, it fails.

For the very same reason, two following assertions can make sense in some languages:

// We don't expect a concatenation. `math` library is not intended for this.
assert(0, math.add("Hello", "World"));

// We expect the method to convert every string as if it was a decimal.
assert(5, math.add("0x2F", 5));

Also, what about:

assert(numeric.Infinity, math.add(numeric.Infinity, 1));

Self-explanatory too: you want your method to be able to deal correctly with the infinity. Going beyond infinity or throwing an exception is not an expected behavior.

Or maybe, depending on your language, this will make more sense?

/**
 * Ensures that when adding numbers which exceed the maximum value, the method
 * fails with OverflowException, instead of restarting at numeric.Minimum + 1.
 */
TestOverflow()
{
    UnitTest.ExpectException(ofType(OverflowException));

    numeric result = math.add(numeric.Maximum, 1));

    UnitTest.Fail("The tested code succeeded, while an OverflowException was
        expected.");
}


问:
How to reply to incomplete requests from potential customers?
Working as a freelancer, I receive many weird, invalid or incomplete requests from the actual or potential customers. The most frequent case is this one:

Hi,

I need a website where people can register and there are also postings and ratings. How much will it cost to me?

Thank you.

The request sucks, but it doesn't mean that a customer like this is not worth it. This person doesn't know how to make a request correctly, but with a bit of effort and a bit of learning and advice, this person may become a valuable customer who will not waste my time.

For a while, I just replied by asking to provide details. They never do.

Recently, I decided to reply in a more detailed way, explaining why is it impossible to give a price (except telling that it would be somewhere between $500 and $50 000). First I just made a simple explanation, telling that their description of the project is too sparse. Then I added further info, metaphors, etc., or by making comparisons with other domains which are better known by people with no technical background. For example:

“Imagine you want to build a two-storey house. Do you believe it's possible to determine the cost of building a house just by knowing the number of storeys? You probably need to provide much more details: is it built with rock or wood? Are there solar panels on the roof? Is there a swimming pool in the backyard?

A large Victorian-style house using the newest technologies, with two garages, a large terrace, etc. will cost much more than an tiny modest two-storey house for a family who really don't have too much money to spend.”

It's still not working: those potential customers never respond.

I also tried the "let me gather the project requirements for you from scratch and do the specification and architecture, but don't forget to pay me for this" technique, but it looks like scam¹. In all cases, in my country (France), this never works with new customers for several reasons.

Some hints show me that some of those people actually succeed finding a developer and succeed with their project. It means that my approach with those potential customers fails, while there is one approach used by someone else which works well.

How to reply to such price requests, considering that those people don't know me, don't trust me yet, don't want to spend days writing a detailed document describing every functionality of the project, and sometimes don't even know precisely what they want, but are not ready to pay you thousands of dollars just for requirements, specification and architecture steps?

¹ Most projects are small enough and have tiny funding; most customers don't bother to know that the source code is clean and maintainable, that it was regularly refactored, and that you have unit and integration tests. They want to pay less, now, no matter how expensive it would be later to maintain the codebase. In this context, talking about functional and non functional requirements, architecture etc., is perceived like the attempt either to waste half of the customer's money doing marketing jibber-jabber instead of writing code, or to scam them by making them pay for something they don't need nor understand, and then disappearing with their money when it will come to actually writing source code. They don't know that you are a professional, and they even don't care.

答:
There are many ways to answer such queries -

Answer 1: It will cost you X Euros per hour to define the system, after which I can give you a fixed price for a set of agreed-upon features.

Answer 2: send them a video clip of sharks in a feeding frenzy, and ask them how long it will take them to count the fish (not just the sharks), given that they can't see the whole scene.

Answer 3: Politely and briefly explain that there are many factors involved in creating a good web site, and ask them what their budget is.

Answer 1 is logical...to developers. And sadly almost no one else. I recently had a conversation with a construction firm along the lines of "we flat-bid complex construction projects every day, why can't you put a price on a simple application?" To which I politely replied "the blueprints for your application are blank. Do you flat-bid undefined jobs?"

Answer 2 is illustrative, and satisfying, but probably won't get you clients. Though it may make a good blog post for me later...

Answer 3 is preferred, for two reasons:

it implies but does not state directly that you don't do analysis and design work for free

it establishes whether or not the potential client has a budget in mind or in hand yet

The latter is critical - no budget = no project.

If you've got time to kill, or some reason to believe that the "potential" client could eventually become and "actual" client with a little coaching, by all means offer to educate them. But don't be surprised if they don't appreciate it. The effort required to create quality custom software is not a widely understood phenomenon.

ContentLicense: CC BY-SA 3.0


问:
Python: What is the point of using "import"?
I am not very clear on this aspect. Let's say you have a bunch of .py files that are their own separate modules.

Why does each .py file need to import the others when they use that class? Or do they? Because I was pretty sure that other languages (Java, for instance), did not require import when referring to classes/files in the same directory. I might be wrong.

答:
Because python is interpreted everything you import is available at the prompt.
Java (and C++) have a compile and link step which can search out and include only functions that are used

If everything was automatically imported there would be 1000s of functions and variables and it would be impossible to type anything without colliding with one.

edit: Ok it's a little more than just compiled vs interpreted. Python is intended as a "batteries included" language - there are libraries available to do almost everything. Since you are only ever going to use a small fraction of those there needs to be a way of organising them so that you only include those you need.

The import from syntax is clever because you can either import the whole library and keep Java-like fully qualified names or you can import specific functions (or all functions) into the local namespace

```<code>>>>import math
>>> math.sin(0)  #no confusion with any other 'sin'

>>> from math import sin  # or import *
>>> sin(0) # makes equations with sin shorter and simpler
</code>```

The second reason is is especially important in a dynamic language like python. Since you don't have to define variables before you use them it would be difficult for the environment to work out if sin is the maths function or a variable of yours in an interpreter.

Body:
Because python is interpreted everything you import is available at the prompt.
Java (and C++) have a compile and link step which can search out and include only functions that are used

If everything was automatically imported there would be 1000s of functions and variables and it would be impossible to type anything without colliding with one.

edit: Ok it's a little more than just compiled vs interpreted. Python is intended as a "batteries included" language - there are libraries available to do almost everything. Since you are only ever going to use a small fraction of those there needs to be a way of organising them so that you only include those you need.

The import from syntax is clever because you can either import the whole library and keep Java-like fully qualified names or you can import specific functions (or all functions) into the local namespace

>>>import math
>>> math.sin(0)  #no confusion with any other 'sin'

>>> from math import sin  # or import *
>>> sin(0) # makes equations with sin shorter and simpler

The second reason is is especially important in a dynamic language like python. Since you don't have to define variables before you use them it would be difficult for the environment to work out if sin is the maths function or a variable of yours in an interpreter.


问:
What's a good notation for showing MVC interactions?
I'm developing various websites and functionality to cater to various different use-cases up in Django.

Is there a good notation for showing what behaviour is at each stage, e.g., swimlanes.

I use BPMN 2 notation for everything, but feel that I am overusing this, and probably abusing the notation :P

Example:

Please recommend a suitable notation for showing the interactions between model, view and controller, as well as some of the inner business-logic in each stage.

答:
Your diagrams look clean and accurate. A good diagram type for

for showing the interactions between model, view and controller

would be a uml sequence diagram. For your

inner business-logic in each stage

i recommend uml statechart diagrams.

Are you generating code from them or is it just a documentation? If you just document it feels like overuse, cause you have to update always the code and the diagrams. I would only use it where the code is to complex (if this isn't a smell and any better design exists).

But if you cultivate these diagrams for customers, then they are great (if your customers understand them ;) )!


答:
What I have never done, but I know others do, and it is awful, but apparently it works, is this:

Give them a quote (say, €500) for the simplest possible web site that covers their requirements. (The crummiest thinkable two-story house made of matchsticks.) They will like it, and they will stop talking to your competitors and start talking to you.

As they begin explaining to you what they want, tell them that it will cost extra. If they complain, show them the simple web site, and tell them that this is what they asked for, and this is what costs €500. Anything more, costs more.

Title: How to reply to incomplete requests from potential customers?

Body:
Working as a freelancer, I receive many weird, invalid or incomplete requests from the actual or potential customers. The most frequent case is this one:

Hi,

I need a website where people can register and there are also postings and ratings. How much will it cost to me?

Thank you.

The request sucks, but it doesn't mean that a customer like this is not worth it. This person doesn't know how to make a request correctly, but with a bit of effort and a bit of learning and advice, this person may become a valuable customer who will not waste my time.

For a while, I just replied by asking to provide details. They never do.

Recently, I decided to reply in a more detailed way, explaining why is it impossible to give a price (except telling that it would be somewhere between $500 and $50 000). First I just made a simple explanation, telling that their description of the project is too sparse. Then I added further info, metaphors, etc., or by making comparisons with other domains which are better known by people with no technical background. For example:

“Imagine you want to build a two-storey house. Do you believe it's possible to determine the cost of building a house just by knowing the number of storeys? You probably need to provide much more details: is it built with rock or wood? Are there solar panels on the roof? Is there a swimming pool in the backyard?

A large Victorian-style house using the newest technologies, with two garages, a large terrace, etc. will cost much more than an tiny modest two-storey house for a family who really don't have too much money to spend.”

It's still not working: those potential customers never respond.

I also tried the "let me gather the project requirements for you from scratch and do the specification and architecture, but don't forget to pay me for this" technique, but it looks like scam¹. In all cases, in my country (France), this never works with new customers for several reasons.

Some hints show me that some of those people actually succeed finding a developer and succeed with their project. It means that my approach with those potential customers fails, while there is one approach used by someone else which works well.

How to reply to such price requests, considering that those people don't know me, don't trust me yet, don't want to spend days writing a detailed document describing every functionality of the project, and sometimes don't even know precisely what they want, but are not ready to pay you thousands of dollars just for requirements, specification and architecture steps?

¹ Most projects are small enough and have tiny funding; most customers don't bother to know that the source code is clean and maintainable, that it was regularly refactored, and that you have unit and integration tests. They want to pay less, now, no matter how expensive it would be later to maintain the codebase. In this context, talking about functional and non functional requirements, architecture etc., is perceived like the attempt either to waste half of the customer's money doing marketing jibber-jabber instead of writing code, or to scam them by making them pay for something they don't need nor understand, and then disappearing with their money when it will come to actually writing source code. They don't know that you are a professional, and they even don't care.


问:
What was the first hierarchical file system?
"Directories containing directories and files" seems to have been around forever, but there must have been a first.</p>

答:
IBM developed IMS in 1966, but I think you're looking for something simpler than that

http://en.wikipedia.org/wiki/IBM_Information_Management_System

OwnerDisplayName: Kent Beck


问:
What does the 'R' in x64 register names stand for?
I know the 32 bit registers were named like the 16 bit registers with an 'E' prefix to mean extended. I've always assumed that meant extended from 16 to 32 bits although I've never seen that explicitly stated.

I was trying to find out what the 'R' stands for but my google skills have failed me. Anyone know?

答: It just means 'register'. For historical reasons.</p>


问:
How does unit testing work?
I am trying to make my code more robust and I have been reading about unit testing, but I find it very hard to find an actual useful use.
For instance, the Wikipedia example:

```<code>public class TestAdder {
    public void testSum() {
        Adder adder = new AdderImpl();
        assert(adder.add(1, 1) == 2);
        assert(adder.add(1, 2) == 3);
        assert(adder.add(2, 2) == 4);
        assert(adder.add(0, 0) == 0);
        assert(adder.add(-1, -2) == -3);
        assert(adder.add(-1, 1) == 0);
        assert(adder.add(1234, 988) == 2222);
    }
}
</code>```

I feel that this test is totally useless, because you are required to manually compute the wanted result and test it, I feel like a better unit test here would be

```<code>assert(adder.add(a, b) == (a+b));
</code>```

but then this is just coding the function itself in the test.
Can someone provide me with an example where unit testing is actually useful? FYI I am currently coding mostly "procedural" functions that take ~10 booleans and a few ints and give me an int result based on this, I feel like the only unit testing I could do would be to simply re-code the algorithm in the test. edit:
I should also have precised this is while porting (possibly badly designed) ruby code (that I didn't make)

答:
Maybe you assume add() was implemented with the ADD instruction.  If some junior programmer or hardware engineer reimplemented the add() function using ANDS/ORS/XORS, bit inverts and shifts, you might want to unit test it against the ADD instruction.

In general, if you replace the guts of add(), or the unit under test, with a random number or output generator, how would you know that something was broken?  Encode that knowledge in your unit tests.  If nobody can tell if it's broken, then just check in some code for rand() and go home, your job is done.

Title: How does unit testing work?


问:
100K curl requests
I am using curl_multi_exec to process over 100K requests. I do 100 requests at a time because curl_multi_exec can only handle 100 requests at a time to eventually get to 100K requests. We have added multiple servers to this system to spread the load [we are using load balancing]. What is the best way to have curl handle 100K requests and make use of these additional servers? What is the downside (other than time) of handling that many requests on one server? How can I use the additional servers to help handle those requests?

I was thinking about having each server handle a batch of requests (like one server handles 500 requests, another 500, another 500, etc..

To elaborate- basically, we are using curl to send out over 100K requests to third party servers. The problem with only using 1 server is that there is a memory limit in the number of requests 1 server can handle. So we decided to add additional servers, but we are not sure how to design this system to use curl to handle that many requests..

The third party server is an API like Facebook; they are aware that we will be making that many requests to their servers.

For load balancing, we use Rackspace cloud server, basically the load balancer directs incoming requests to separate servers.

答:
Given the background provided so far, it sounds like Gearman could be useful:
http://gearman.org/index.php

It's a great tool that is very easy to use within PHP, and it's built specifically to help

...farm out work to other machines or processes...

There are some great use cases that are documented within the site that can help you get started.

Title: 100K curl requests


问:
Is Javascript a Functional Programming Language

Is Javascript a functional language? I know it has objects & you can do OOP with it also, but is it also a functional language, can it be used in that way?

You know how OOP became/seems like the next evolution in programming, does that mean that 'Functional Programming' is the next evolution(Note: this is NOT a prompt for opinion BUT a prompt for a factual evidence based answer, & this note is more for the moderators than the contributors ;) ).

I learn best through examples, maybe someone could show performing the same task in a OOP way & then in a Functional Programming way for myself to understand & compare what functional programming does/is.

I don't really completely understand 'Functional Programming' to be honest :P So comparing Javascript to functional programming may be totally incorrect.

To put Functional programming in laymans terms: is it simply the benefit of abstration THROUGH using anonymous functions?

Or is that way too simple? In a simple way, OOP is the benefit of abstraction through objects, but I believe thats being a little too simplistic to describe OOP.

Is this a good example of functional programming?...

Javascript OOP Example:

```<code>// sum some numbers
function Number( v )
{
  this.val = v;
}

Number.prototype.add( /*Number*/ n2 )
{
    this.val += n2.val;
}
</code>```

Functional programming example:

```<code>function forEach(array, action)
{
   for (var i = 0; i < array.length; i++)
       action(array[i]);
}

function add(array)
{
    var i=0;
    forEach(array, function(n)
    {
        i += n;
    });
    return i;
}

var res = add([1,9]);
</code>```

答:
Is Javascript a functional language? I know it has objects & you can do OOP with it also, but is it also a functional language, can it be used in that way?

Sometimes, people will say functional programming, when what they mean is imperative programming or procedural programming. Strictly speaking, functional programming is:

In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state. Functional programming has its roots in lambda calculus, a formal system developed in the 1930s to investigate function definition, function application, and recursion. Many functional programming languages can be viewed as elaborations on the lambda calculus.

Although Javascript is not widely known or used as a functional language, it does have some functional elements:

JavaScript has much in common with Scheme. It is a dynamic language. It has a flexible datatype (arrays) that can easily simulate s-expressions. And most importantly, functions are lambdas.

Scheme is a dialect of Lisp, and probably one of the languages most programmers think of when they discuss functional programming. When it comes to object orientation, Javascript is an object oriented language. But its object orientation is prototype based:

Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is performed via a process of cloning existing objects that serve as prototypes. This model can also be known as classless, prototype-oriented or instance-based programming. Delegation is the language feature that supports prototype-based programming.

So although Javascript is object oriented, it doesn't follow the more common class based model, as do languages as C++, C#, Java and PHP (and quite a few others). And of course it's also an imperative language, which leads to the confusion with functional programming I described above.

You know how OOP became/seems like the next evolution in programming, does that mean that 'Functional Programming' is the next evolution

Object orientation and functional programming are just two of the many different programming paradigms, they are different styles of programming with different concepts and abstractions. The key word is "different". There isn't a single paradigm that's better than others or more evolved than others, each and every one fits some scenarios better than the others. Some may be quite older in origin than others, but in evolutionary terms that makes them better, as they have survided longer. But that's not a very smart way of looking at it.

Javascript, as I described above and as quite a few other languages, is multi-paradigm. It allows you to write code in imperative, prototype based object oriented and functional style. It's up to you to choose which one best fits whatever you are building. There are also several single paradigm languages, the canonical example being Java, which only allows for class based object oriented programming1.

You should really resist any urge to treat languages & paradigms as fashion statements. There's an abudance of crap out there, mostly written by fanboys / fangirls or marketing people, with little (if any) knowledge and understanding of programming. Terms like "better", "more evolved" etc, simply don't apply.

I learn best through examples, maybe someone could show performing the same task in a OOP way & then in a Functional Programming way for myself to understand & compare what functional programming does/is.

That would be a terrible way to learn. Functional and object orientation are quite different styles, and any example other than terribly simple ones would not fit one or the other style.

1 But lately tries to expand its scope to generic programming, let's see how that goes.

In conclusion:

Concentrate on learning Javascript, it's a beautiful and extremly useful language. Learn the language, not the hype.

Quite a few different paradigms, all equally useful. Up to you to choose which one you prefer and which one fits best whatever you're building.

If you want to learn functional programming, choose a more suited language, like Scheme or Clojure. But you'll first need to understand the mathematical concepts involved.

Do some research before you ask. Most of your questions are answered by the relevant Wikipedia articles. Knowing how to research and how to ask is an extremely important skill for any programmer.


答:
Evolution normally means an incremental change. OOP is not an incremental addition to the procedural programming - in fact, it is entirely orthogonal to an underlying programming model and can be combined with any of them. Functional programming is not an incremental addition to procedural, OOP or whatever - it is an alternative basis  for expressing fundamental computing principles, and it is actually the first  such basis ever formulated, long before the first computers appeared. It is important to understand that all such fundamental systems are equivalent (i.e., one can be expressed in terms of another).

In order to understand the functional approach, you'll need to get the basic math first. If you want to get a feeling of what does it mean to code in a functional style in Javascript, start using jQuery.

Title: Is Javascript a Functional Programming Language

Body:
Is Javascript a functional language? I know it has objects & you can do OOP with it also, but is it also a functional language, can it be used in that way?

You know how OOP became/seems like the next evolution in programming, does that mean that 'Functional Programming' is the next evolution(Note: this is NOT a prompt for opinion BUT a prompt for a factual evidence based answer, & this note is more for the moderators than the contributors ;) ).

I learn best through examples, maybe someone could show performing the same task in a OOP way & then in a Functional Programming way for myself to understand & compare what functional programming does/is.

I don't really completely understand 'Functional Programming' to be honest :P So comparing Javascript to functional programming may be totally incorrect.

To put Functional programming in laymans terms: is it simply the benefit of abstration THROUGH using anonymous functions?

Or is that way too simple? In a simple way, OOP is the benefit of abstraction through objects, but I believe thats being a little too simplistic to describe OOP.

Is this a good example of functional programming?...

Javascript OOP Example:

```<code>// sum some numbers
function Number( v )
{
  this.val = v;
}

Number.prototype.add( /*Number*/ n2 )
{
    this.val += n2.val;
}
</code>```

Functional programming example:

```<code>function forEach(array, action)
{
   for (var i = 0; i < array.length; i++)
       action(array[i]);
}

function add(array)
{
    var i=0;
    forEach(array, function(n)
    {
        i += n;
    });
    return i;
}

var res = add([1,9]);
</code>```


问:
What are some characteristics of Python that makes it unique as its own language?
What are some characteristics of Python that makes it unique as its own language? I'm looking for any sort of characteristics ranging from good to bad, useful to hindrance, syntax to real-world usage, but non-obscure observations would be the most useful for the average developer.

I'm a newb here, so intuitive things may need to be explained.....

答:
I guess the only thing that makes Python unique is the particular combination of features it exposes. This would be true for most programming languages.

Or there might be one small thing: I haven't seen the way Python explicitly passes self as a formal parameter to object member functions done in any other language. It's a small thing, and I don't see how this changes anything really.

But I'm not very fluent in Python, so there might be stuff I'm missing for sure!


答:
If you can afford to give up an hour or two of your time for nothing, then you could offer to set up a meeting, ostensibly to "discuss their requirements in more detail".  If you can get them to sit in a room with you for an hour, you can ask them what they expect, and toss some ideas their way.  Hopefully, this will allow you to build up a rapport, and convince them that they know what you're talking about.  It may be just the edge you need, to be preferred over your competitors.

But don't make assumptions about what it is they actually want, or make a quote based on what you think they need.  One customer of mine once told me "I need a web page that lets the users enter information and stores it in a database".  After I spent half an hour with him, he realised that all he actually wanted was some help putting together a two-page Microsoft Word template.


答:
I would say it's use of indentation to enclose if statements and loops. Have not seen that in any other language.

I think its very handy because it makes it significantly more difficult to obfuscate python code!

It also seems to execute in a neat line by line manner with the exception of functions, and it can be interpreted as such too which is nice.

Body:
What are some characteristics of Python that makes it unique as its own language? I'm looking for any sort of characteristics ranging from good to bad, useful to hindrance, syntax to real-world usage, but non-obscure observations would be the most useful for the average developer.

I'm a newb here, so intuitive things may need to be explained.....


答:
You'll have a hard time finding features which are absolutely unique. Most language features in existence have been adopted in more than one language since their inception. Some may be rarer, mostly because they're either new and still in obscurity, or died out for good reason. Nevertheless, even then you'd be better off looking at combinations of features.

That said, several features of Python should make for a relatively unique combination. At least I'm not aware of any languages remotely as popular (and practical) with a mostly overlapping feature set. As noted in comments, Ruby is pretty close, but there are nevertheless numerous differences.

Metaclass-based metaprogramming. Basically, running arbitary code on class creation. Makes for very nice class customization with very little work on the recieving end - e.g. for an Object-relational Mapping (ORM), client classes can be written as usual with a few extra lines like attr = SomeDataType() and a ton of code is generated automatically. An example of this are Django's "models".

You're encouraged to use iterators for everything. This is especially apparent in 3.x, where most list-based alternatives with an iterator-based equivalent have been abolished in favour of the latter. Iterators also serve as nigh-universal interface for collections (both those you actually have in memory and those you only need once and thus create with the features below). Collection-agnostic, space-efficent (O(1) space for intermediate results often follows naturally, very few tasks actually need all items in memory at once), composable data crunching has never been easier.

Generator expressions, related to the above. Many will have heard of list comprehensions (creating a list from another iterable, filtering and mapping in the process, with very convenient syntax). Forget about them, they're syntactic sugar, a special case. Generator expressions are very close in syntactically and ultimately result in the very same sequence of items, but they produce results lazily (and thus take O(1) space unless you explicitly keep the results around).

yield, which mainly make writing iterators (called generators here) far nicer. They're the big brother of the above, supporting all kinds of control flow. C# has something similar, with the same keyword. But yield is also overloaded to support a limited kind of coroutines (Lua for instance has more elaborate support) which has nevertheless been put to good use by clever people working on hard problems. Two examples off the top of my head: Recursive descent parsing with backtracing and no stack limit and asynchronous I/O (with convenient syntax).

Multi-target assignment and iterable unpacking. Assignment on steroids. Not only you can assign to multiple values at once (even for swapping values and when iterating - for key, value in mapping.items()), you can unpack any iterable of known length (honestly, mostly tuples) into multiple variables. Since 3.x it's even practical for collections of unknown length as you can specify a few variables taking single items and one taking whatever remains: first, *everything_in_between, last = values.

Descriptors, probably the most powerful among the various ways to customize attribute access. There are properties (as in C#, but without special language support), static methods, class methods, etc. all implemented as descriptors. They're first-class objects as well. Just a week ago, I've been faced with repetive and tricky code in properties - so I wrote a small function generating the repetive part and wrapping it up in a propery object.

Purely offside rule (indentaion for delimiting blocks). I put this last intentionally. While it does distinguish Python, it doesn't really stand out in everyday programming once you're used to it (or at least that's my experience).

Title: What are some characteristics of Python that makes it unique as its own language?


答: Javascript can be used as a functional language, in fact it does it quite well. It is possible to implement monads has support for a lambda construct etc. It is not exclusively a functional language in that it also has a lot of object oriented features but it can be used that way. Actually I find that using Javascript as a functional language is a great way to use it. (Example jQuery and underscore.js)</p>


答:
The best way to deal with vague customers is to give them something concrete to choose between. Here is what I would reply.

Hi Bob

Thanks for your interest. We are a bespoke design company. That means
  you get exactly what you want but it can be a little hard to give you
  a price without knowing all your requirements. You're probably looking
  in the region of x but it depends how complex you want the site. We
  recently did foo.com for x, bar.com for y and baz.com for z. Why don't you take a look
  at those sites and see which most looks like what you wanted?

Where y < x < z


答:
Your primary problem and the reason you aren't getting this less-than-educated (to be put lightly) client base is because they are not used to dealing with how freelance contractors work, how they determine prices and how they interact with their clients.  They really don't want all that because deep down inside nobody really wants to believe that what they are really getting is a custom solution.  Sure they have special requests but when you bill by hour or try to extract requirements out of them then they get the distinct impression that they are paying for your time when they would much rather be paying for software.

Everybody wants the cheapest price, but don't just assume that quality is not important to them because it is.  They expect a level of usable quality and return on investment for the smallest possible investment.  Keep in mind they are talking to a hundred contractors at the same time they are talking to you, and to invest time feeding you requirements before you give them a quote is too risky.  One quarter of all quotes are going to be outrageously priced, and they vast majority will be fair, but a few will be small provided by underdogs, disadvantaged and desperate, and people trying to build experience.  I would be furious too if I spent hours of personal time explaining my complex needs in detail to contractor, only to find that he is quoting me 8 months of labor @120€ per hour!

This is why it is so important for you to lead with an initial pending and negotiable estimate as soon as possible (pending acceptable risk of the unknown of course).  Further if possible try to show examples of similar work you have done for clients in your portfolio because this will get them thinking about what is possible.  They will more seriously consider what they want, and if your price is right they will more seriously consider you.

If your initial price is still not right then everybody walks away and not a tear is shed.  Further if they are being unreasonable and they can't find a sucker, they might just come crawling back to you once they realize how much these things truly cost.  I have had that happen to me before.


答:
You can probably take a guess at what they would want, most sites require a basic set of core functions. I would imagine you don't code up the same fundamentals each time but use a common set over and over.

So do a bit of preparatory work and create some form responses you can send out in these cases. Write once, send many if you'll excuse the pun.

Provide a set of prices, perhaps linked to example URL's showing what they will get. At the lowest level provide user registration that lets the user log into a site and that's it. The idea here is to show them what they might want. You have to do some of the thinking work here for them and instill a sense of desire.

As I said, bit of preparation and you could send out that response 30 times a day with zero effort, perhaps just a tweaking of names and costs.


答:
Simply put, that is the way it was designed. You mentioned Java as a counter example - the Java language designers wanted to make classloading somewhat implicit, so they check the same directory before throwing ClassNotFound. Outside of that you need to qualify, just like in Python.

As Tom Anderson said, C does the same thing as Python, and it's a compiled language. Perhaps the interpreted nature of the language had something to do with the final decision (for performance, explicitness, etc.), but in the end it's up to the developer.

Title: Python: What is the point of using "import"?

Body:
I am not very clear on this aspect. Let's say you have a bunch of .py files that are their own separate modules.

Why does each .py file need to import the others when they use that class? Or do they? Because I was pretty sure that other languages (Java, for instance), did not require import when referring to classes/files in the same directory. I might be wrong.


问:
Why is the Select before the From in an SQL query?
This is something that bothered me a lot at school.

Five years ago, when I learned SQL, I always wondered why we first specify the fields we want and then where we want them from.

According to my idea, we should write:

```<code>From Employee e
Select e.Name
</code>```

So why does the norm say the following?

```<code>Select e.Name -- Eeeeek, what does e mean?
From Employee e -- Ok, now I know what e is
</code>```

It took me weeks to understand SQL, and I know that a lot of that time was consumed by the wrong order of elements.

It is like writing in C#:

```<code>string name = employee.Name;
var employee = this.GetEmployee();
</code>```

So, I assume that it has a historical reason. Why?

答:
Originally SQL language was called SEQUEL standing for

Structured English Query Language

with the emphasize on English, assuming it to be close in spelling to natural language.

Now, spell these two statements as you'd spell English sentences:

"From Employee table e Select column e.Name"

"Select column e.Name From Employee table e"

Second sounds closer to natural English language that's why it is set as norm.

BTW same reasoning goes to Where etc - SQL statements were intentionally designed to sound close to natural language.


答:
Do not know an answer that I could back up by references, but if I had to speculate: SQL is a declarative language, a statement of such language describes what you would like to do as opposed to how you would like to do it.

As such, "SELECT X FROM Y" sounds as a more appropriate way of answering "What would I like to select from the database", as opposed to writing "FROM Y SELECT X".

In addition, in SQL, the SELECT/UPDATE/INSERT specifies the type of operation you are about to do and FROM is just a clause that helps you select from the right table in the database. Again, what are you doing with data takes precedence over how exactly you are going to achieve that.

Title: Why is the Select before the From in an SQL query?

Body:
This is something that bothered me a lot at school.

Five years ago, when I learned SQL, I always wondered why we first specify the fields we want and then where we want them from.

According to my idea, we should write:

```<code>From Employee e
Select e.Name
</code>```

So why does the norm say the following?

```<code>Select e.Name -- Eeeeek, what does e mean?
From Employee e -- Ok, now I know what e is
</code>```

It took me weeks to understand SQL, and I know that a lot of that time was consumed by the wrong order of elements.

It is like writing in C#:

```<code>string name = employee.Name;
var employee = this.GetEmployee();
</code>```

So, I assume that it has a historical reason. Why?


答:
The automatic processing of docstrings to become properties of their owner. In general all of Python's brilliant introspection features make it a very unique language, from the ability to use help() to the ability to use __doc__ as a first-class property of an object. For example:

```<code>>>> class DocStringException(Exception):
...     """Error message is the same as docstring"""
...     def __str__(self):
...         return repr(self.__doc__)
...
>>> class ExampleException(DocStringException):
...     """An example happened"""
...
>>> raise ExampleException
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.ExampleException: 'An example happened'
</code>```

Other useful introspection features:

help/help() - help with the interpreter / help with an object

keywords - python keywords

locals() - get the local names

globals() - get the global names

dir() - get an object's properties and methods

the .mro method., issubclass - understanding inheritance

id() - get the memory address of an object

Body:
The automatic processing of docstrings to become properties of their owner. In general all of Python's brilliant introspection features make it a very unique language, from the ability to use help() to the ability to use __doc__ as a first-class property of an object. For example:

>>> class DocStringException(Exception):
...     """Error message is the same as docstring"""
...     def __str__(self):
...         return repr(self.__doc__)
...
>>> class ExampleException(DocStringException):
...     """An example happened"""
...
>>> raise ExampleException
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.ExampleException: 'An example happened'

Other useful introspection features:

help/help() - help with the interpreter / help with an object

keywords - python keywords

locals() - get the local names

globals() - get the global names

dir() - get an object's properties and methods

the .mro method., issubclass - understanding inheritance

id() - get the memory address of an object


答:
Because SELECT is required in a select statement and FROM is not.

```<code>Select 'This String'
</code>```

Of course your sql statement can be parsed to look for the SELECT, DELETE, UPDATE after the FROM, but is is really that big of a deal?

Remember, this was all done before intellisense. It's not that complicated.

Edit: There's probably no reason sql interpreters couldn't be built to do both.

Body:
Because SELECT is required in a select statement and FROM is not.

Select 'This String'

Of course your sql statement can be parsed to look for the SELECT, DELETE, UPDATE after the FROM, but is is really that big of a deal?

Remember, this was all done before intellisense. It's not that complicated.

Edit: There's probably no reason sql interpreters couldn't be built to do both.


问:
Naming conventions for the only envisioned implementation of an interface
If you decide "Program to An Interface" trumps YAGNI and decide to create a supertype where you don't envision anything other than one obvious implementation - is there a convention for naming the obvious concrete type?  E.g. this morning I wrote a a class called PlainOldConversionReport and I wonder if that name betrays ignorance of convention.  Would there a more normal name, in Object Oriented development generally or .Net or C# specifically, to give to a non specialized subtype of IConversionReport?  </p>

答: If there is no obvious name for the specialization in the single implementation, my teams have always normally used Impl as a suffix. If there is an obvious name, I would stick with it even if it will be the only implementation.


答:
I use a prefix of Base, so BaseConversionReport.

I clearly misread the question.  My apologies.  If there is a simple, bog-standard implementation for the ConversionReport, I'd simply call it ConversionReport or StandardConversionReport and call the SuperType BaseConversionReport (or ConversionReportBase.)

Title: Naming conventions for the only envisioned implementation of an interface

Body: If you decide "Program to An Interface" trumps YAGNI and decide to create a supertype where you don't envision anything other than one obvious implementation - is there a convention for naming the obvious concrete type?  E.g. this morning I wrote a a class called PlainOldConversionReport and I wonder if that name betrays ignorance of convention.  Would there a more normal name, in Object Oriented development generally or .Net or C# specifically, to give to a non specialized subtype of IConversionReport?  </p>


问:
What is MVC, really?
As a serious programmer, how do you answer the question What is MVC?

In my mind, MVC is sort of a nebulous topic — and because of that, if your audience is a learner, then you're free to describe it in general terms that are unlikely to be controversial.

However, if you are speaking to a knowledgeable audience, especially an interviewer, I have a hard time thinking of a direction to take that doesn't risk a reaction of "well that's not right!...".  We all have different real-world experience, and I haven't truly met the same MVC implementation pattern twice.

Specifically, there seem to be disagreements regarding strictness, component definition, separation of parts (what piece fits where), etc.

So, how should I explain MVC in a way that is correct, concise, and uncontroversial?

答:
I always start off by telling them that the pattern is not anything new and has been around for many years... its at this point they give me an inquisitive look and BAM!, they are hooked:

And then I would pretty much talk about the various points like the previous answers, but I think its important to be contextual as well, as JB King said, ASP.NET MVC etc,

Title: What is MVC, really?


问:
How Find operation works in a Binary Tree?
I am having a confusion in this Binary Tree Coding. I know the concept of binary tree and I know how those work and all, but in this source code i am confused with "Find" operation. I cannot understand how it works and all. Please help me, I am so interested in this area.</p>

```<code>package binarytree_task4;

  class Node
    {

    private static class Equivalent {

        public Equivalent() {
        }
    }

        public Equivalent data;
        public Node right;
        public Node left;

        public Node(Equivalent data)
        {

            this(data, null, null);
        }

        public Node(Equivalent data, Node left, Node right)
        {

            this.data = data;
            this.left = left;
            this.right = right;
        }
    }

 class binarytree {

    public static void main(String[] args) {

    }

    private static class Equivalent {

        public Equivalent() {
        }
    }

    private static class present {

        public present() {
        }
    }
    private Node root;
    private int size;

    public binarytree()
    {
        size = 0;
        root = null;
    }

    public void printTree()
    {
        if(size == 0)
            System.out.println("Empty");
        else {
            System.out.println("Tree contents:");
            inorder(root);
        }
    }

    public void inorder(Node present)
    {
        if(present != null)
        {
            inorder(present.left);
            System.out.println(present.data);
            inorder(present.right);
        }
    }

    public void Insert(Equivalent data)
    {
        root = Insert(data, root);
    }

    private Node Insert(Equivalent data, Node present)
    {
        if( present == null)
        {
            size++;
            present = new Node(data, null, null);
        }

        else if(data.compareTo(present.data)<0)
        {
            present.left = Insert(data,present.left);
                }

        else if(data.compareTo(present.data)>0)
                {

            present.right = Insert(data, present.right);
        }

        return present;
    }

    public boolean Find(Equivalent data)
    {
        return Find(data, root);
    }

    private boolean Find(Equivalent data, Node present)
    {

        if(present == null )
        {
            return false;
        }
        else if(present.data == data)
        {
            return true;
        }
        else if(data.compareTo(present.data)<0)
        {
            return Find(data, present.left);
        }
        else
        {
            return Find(data, present.right);
        }
    }

    public boolean Delete(Equivalent key){

        if (Find(key)){
            Delete(key);
            return true;
        }
        else{
            return false;
        }
    }

    public void delete(Equivalent key)
    {
        Node present = root;
        Node parent = root;

        boolean isLeftChild = true;

        while(present.data.compareTo(key) != 0)
        {

            parent = present;
            if(present.data.compareTo(key) > 0)
            {
                isLeftChild = true;
                present = present.left;
            }
            else
            {
                isLeftChild = false;
                present = present.right;
            }
            if(present == null)
                return ;
        }

        if(present.left == null && present.right == null)
        {
            if(present == root)
                root = null;
            else if(isLeftChild)
                parent.left = null;
            else
                parent.right = null;
        }

        else if(present.right == null)
            if(present == root)
                root = present.left;
            else if(isLeftChild)
                parent.left = present.left;
            else
                parent.right = present.left;

        else if(present.left == null)
            if(present == root)
                root = present.right;
            else if(isLeftChild)
                parent.left = present.right;
            else
                parent.right = present.right;

        else
        {

            Node successor = getSuccessor(present);

            if(present == root)
                root = successor;
            else if(isLeftChild)
                parent.left= successor;
            else
                parent.right = successor;

            successor.left = present.left;
         }
    }

   private Node getSuccessor(Node delNode)
   {
        Node successorParent = delNode;
        Node successor = delNode;
        Node present = delNode.right;

        while(present != null)
        {

            successorParent = successor;
            successor = present;
            present = present.left;
        }
        if(successor != delNode.right)
        {

            successorParent.left = successor.right;
            successor.right = delNode.right;
        }
        return successor;
   }

}
</code>```

答:
Find works recursively, meaning it can call itself. However, it doesn't just call itself with the same arguments, each time it calls itself it is going deeper into the tree. If there were no checks, this could go on forever. However, this recursion has a couple of checks to terminate the search if it is given a null node (meaning, it didn't find what it was looking for), or the node it is given is the one being looked for (meaning it did find the one it was looking for). Eventually one of these conditions must be true.

It works like this:

First it looks at the node it was given. If the node is null, it didn't find what it was looking for and there are no children to search, so it returns false. This is the first termination check, and means "we didn't find it".

If the node is not null, then it checks to see if the node has the requested data. This is the second termination check. If it does, it returns true meaning "we found it".

If it doesn't find the requested data, then it must look either to the left or the right depending on whether the requested data is larger or smaller than the current data.

How does it do this last step? By taking either the left or right node, and starting the whole process over by calling itself with the left or right node of the current node and then returning the result. If the node it is currently on is a leaf node (ie: no left or right branches to follow), then a null node will be sent when it calls itself, and as you can see from earlier in the process, if Find is given a null node it will return false.

So, essentially Find says "am I the node we are looking for?" If the answer is no, it then asks itself "is my left node the one we are looking for?" or "is my right node the one I am looking for?" and it keeps asking itself that question as it goes deeper and deeper into the tree.

Notice that in all cases, Find either returns true, false, or the result of the next call to Find. This means that eventually, some version of Find will return true or false when it gets to the end of the tree, and that true or false will work its way back up the chain -- true (or false) will return to the caller, which returns that value to it's caller, which returns that value to it's caller, ... until you are back to where Find was first called.


答: For IConversionReport, I'd simply use ConversionReport. I guess you know this already, but IXXXX and XXXX is a bit of a code smell. I think you should probably think a bit harder to see if there's a better name that gives some hint of what the implementation is (or drop the interface if you're neither doing any composition nor swapping out different implementations).</p>


问:
Can you learn OO programming without procedural?
I've seen a number of question asking whether someone should learn procedural or OO first. But is this even possible? Can you learn OO programming without first having an understanding of procedural programming? Obviously, they can learn to program in an OO language like Java or Python first. But you can write Fortran in any language. My impression is that such beginning programmers write procedural code in an OO language at least at first.

But what do you think?

答:
Any program in the world is typically comprised of either or all of the following characteristics:

A Logical Sequence (a decent algorithm)

Selection Structures (if, switch)

Repetition (Iteration or loops)

Any  beginning programmer has to be good at the aforementioned aspects of programming before proceeding to more advanced stuff. It is always recommendable to write your own functions and procedures just in the beginning so that it speeds up logical approach towards solving problems. Once that is done, then you can study data structures! A class (which is the essential unit of OOP) itself is a data structure. Ever wondered why C is taught before C++? Reason is that if one knows the implementation and weakness/disadvantage of struct(record), it will be easier to comprehend and appreciate the importance of using classes.

Although it not a prerequisite to learn a procedural programming first before going into the aspects of OOP. But it is highly recommended to write your own procedures and functions, before one gets rather addicted to reuse pre-built libraries and methods of objects.

One important note here I would always advise for beginning programmers is to stay away from primitive procedural programming languages of the 50's and 60's like FORTRAN, Pascal, COBOL, BASIC, etc. The reason I said that because those languages are all application oriented.They were meant to be there to perform certain things in their respective areas. Secondly, their syntax is also very different from the modern powerful OOP languages of today.

It is always best to start from C or C++! Once you are comfortable in these languages, it won't take much time for you to learn languages like Java, C#, PHP, Drupal, Ruby, etc. These   are all object oriented languages.


问:
What implementation do you use when dealing with operators in .Net?
My question is in a sense a follow up of this post on Time Series in .Net.

Ideally, you would like to expand the basic TimeSeries<T> class by something like NumericTimeSeries<T>, where you would want to make sure that the type T implements the common numerical operators +, -, *, `/', ...

I am not sure what would be the most intelligent way to do this.

My first idea is to create an abstract class Number, with abstract methods Add(Number n1,Number n2), Multiply(Number n1,Number n2), Subtract(Number n1,Number n2), Divide(Number n1,Number n2) (and so on). I would then call these methods in the operator overloads.

I can then create concrete classes such as IntNumber, DoubleNumber, MatrixNumber, ComplexNumber (and so on).

The problem is that in the methods implementation, I would have to make an awful switch to determine what the class of each parameter is, and it's not very elegant.

Would you have done it the same way?

Has something already be done?

In F# I would use and inline functions, or pattern matching using discriminated unions. But what should I do in C#?

EDIT:

There was an awesome answer by Olivier Jacot-Descombes. However, I would like to specify a feature.

The numbers can apply the operator between them (you can multiply a matrix with a scalar for example). The problem with this is that you cannot know in advance the type of the result; multiplying a vector (transposed) and a vector returns a double...

答:
It is possible to do it with some tricks. First, we define an abstract Number class with a generic parameter T and the funny generic parameter constraint where T : Number<T>. This might look like an endless recursion, but does in fact just mean that T must derive from Number<T>. We need the generic parameter for the implicit conversion trick:

public abstract class Number<T>
    where T : Number<T>
{
    public static Number<T> operator +(Number<T> x, Number<T> y)
    {
        return x.Sum(y);
    }

    // Automatic conversion from Number<T> to T
    public static implicit operator T(Number<T> x)
    {
        return (T)x;
    }

    // Each derived type must supply its own implementation
    internal abstract Number<T> Sum(T x);
}
```

<p><code>Number</code> also defines an overload for the "+" operator. Since this operator is static, we cannot override it in deriving classes. Therefore we declare an abstract <code>Sum</code> method, that the "+" operator uses to calculate its sum. We also implement an implicit conversion from <code>Number<T></code> to <code>T</code>.</p>

<p>Now let us implement a class for integer numbers that derives from <code>Number<T></code>:</p>

<pre class="lang-cs prettyprint-override"><code>public class IntNumber : Number<IntNumber>
{
    private int _n;

    public IntNumber(int n)
    {
        _n = n;
    }

    public int Value { get { return _n; } }

    // Automatic conversion from int to IntNumber
    public static implicit operator IntNumber(int x)
    {
        return new IntNumber(x);
    }

    internal override Number<IntNumber> Sum(IntNumber x)
    {
        return new IntNumber(_n + x._n);
    }

    public override string ToString()
    {
        return _n.ToString();
    }
}
</code>```

The important part is the implementation of the Sum method. The implicit conversion from int to IntNumber is optional. Overriding the ToString method makes it easier to display IntNumber. We also declare a constructor and a Value property that returns the integer number.

We can do the same with complex numbers:

public class ComplexNumber : Number<ComplexNumber>
{
    private double _re, _im;

    public ComplexNumber(double re, double im)
    {
        _re = re;
        _im = im;
    }

    public double Re { get { return _re; } }
    public double Im { get { return _im; } }

    public static ComplexNumber operator +(ComplexNumber x, ComplexNumber y)
    {
        return x.Sum(y);
    }

    // Automatic conversion from double to ComplexNumber
    public static implicit operator ComplexNumber(double x)
    {
        return new ComplexNumber(x, 0);
    }

    // Automatic conversion from IntNumber to ComplexNumber
    public static implicit operator ComplexNumber(IntNumber x)
    {
        return new ComplexNumber(x.Value, 0);
    }

    internal override Number<ComplexNumber> Sum(ComplexNumber x)
    {
        return new ComplexNumber(_re + x._re, _im + x._im);
    }

    public override string ToString()
    {
        return "(" + _re + "+" + _im + "i)";
    }
}
```

<p>The operator overload in the base class is required in order to handle generic typed numbers (see Calculator), the one in the derived class is required, because the automatic conversion from <code>IntNumber</code> to <code>ComplexNumber</code> only works with this one.</p>

<p>Now let us declare a generic calculator that operates on any of our number types. (It is just a simple replacement for your NumericTimeSeries for test purposes).</p>

<pre class="lang-cs prettyprint-override"><code>public class Calculator<T>
    where T : Number<T>
{
    public T GetSum(T x, T y)
    {
        return x + y; // <== You can add any numbers with generic type T with "+"
    }
}
</code>```

Note that we can just add two numbers of a generic type with the "+" operator. Because of the implicit operator declared in Number<T> we do not need any castings!

Let us test the addition of generic number types with the generic calculator and the direct addition of different number types:

IntNumber i1 = new IntNumber(2);
IntNumber i2 = new IntNumber(3);
var intCalculator = new Calculator<IntNumber>();
Console.WriteLine(intCalculator.GetSum(i1, i2)); // ==> 5
Console.WriteLine(intCalculator.GetSum(4, 6)); // ==> 10

ComplexNumber c1 = new ComplexNumber(2, 7);
ComplexNumber c2 = new ComplexNumber(3, -1);
var complexCalculator = new Calculator<ComplexNumber>();
Console.WriteLine(complexCalculator.GetSum(c1, c2)); // ==> (5+6i)

Console.WriteLine(c1 + 100.5); // ==> (102.5+7i)
Console.WriteLine(c1 + i1); // ==> (4+7i)
Console.WriteLine(i1 + c1); // ==> (4+7i)
```

Body:
It is possible to do it with some tricks. First, we define an abstract Number class with a generic parameter T and the funny generic parameter constraint where T : Number<T>. This might look like an endless recursion, but does in fact just mean that T must derive from Number<T>. We need the generic parameter for the implicit conversion trick:

public abstract class Number<T>
    where T : Number<T>
{
    public static Number<T> operator +(Number<T> x, Number<T> y)
    {
        return x.Sum(y);
    }

    // Automatic conversion from Number<T> to T
    public static implicit operator T(Number<T> x)
    {
        return (T)x;
    }

    // Each derived type must supply its own implementation
    internal abstract Number<T> Sum(T x);
}

Number also defines an overload for the "+" operator. Since this operator is static, we cannot override it in deriving classes. Therefore we declare an abstract Sum method, that the "+" operator uses to calculate its sum. We also implement an implicit conversion from Number<T> to T.

Now let us implement a class for integer numbers that derives from Number<T>:

public class IntNumber : Number<IntNumber>
{
    private int _n;

    public IntNumber(int n)
    {
        _n = n;
    }

    public int Value { get { return _n; } }

    // Automatic conversion from int to IntNumber
    public static implicit operator IntNumber(int x)
    {
        return new IntNumber(x);
    }

    internal override Number<IntNumber> Sum(IntNumber x)
    {
        return new IntNumber(_n + x._n);
    }

    public override string ToString()
    {
        return _n.ToString();
    }
}

The important part is the implementation of the Sum method. The implicit conversion from int to IntNumber is optional. Overriding the ToString method makes it easier to display IntNumber. We also declare a constructor and a Value property that returns the integer number.

We can do the same with complex numbers:

public class ComplexNumber : Number<ComplexNumber>
{
    private double _re, _im;

    public ComplexNumber(double re, double im)
    {
        _re = re;
        _im = im;
    }

    public double Re { get { return _re; } }
    public double Im { get { return _im; } }

    public static ComplexNumber operator +(ComplexNumber x, ComplexNumber y)
    {
        return x.Sum(y);
    }

    // Automatic conversion from double to ComplexNumber
    public static implicit operator ComplexNumber(double x)
    {
        return new ComplexNumber(x, 0);
    }

    // Automatic conversion from IntNumber to ComplexNumber
    public static implicit operator ComplexNumber(IntNumber x)
    {
        return new ComplexNumber(x.Value, 0);
    }

    internal override Number<ComplexNumber> Sum(ComplexNumber x)
    {
        return new ComplexNumber(_re + x._re, _im + x._im);
    }

    public override string ToString()
    {
        return "(" + _re + "+" + _im + "i)";
    }
}

The operator overload in the base class is required in order to handle generic typed numbers (see Calculator), the one in the derived class is required, because the automatic conversion from IntNumber to ComplexNumber only works with this one.

Now let us declare a generic calculator that operates on any of our number types. (It is just a simple replacement for your NumericTimeSeries for test purposes).

public class Calculator<T>
    where T : Number<T>
{
    public T GetSum(T x, T y)
    {
        return x + y; // <== You can add any numbers with generic type T with "+"
    }
}

Note that we can just add two numbers of a generic type with the "+" operator. Because of the implicit operator declared in Number<T> we do not need any castings!

Let us test the addition of generic number types with the generic calculator and the direct addition of different number types:

IntNumber i1 = new IntNumber(2);
IntNumber i2 = new IntNumber(3);
var intCalculator = new Calculator<IntNumber>();
Console.WriteLine(intCalculator.GetSum(i1, i2)); // ==> 5
Console.WriteLine(intCalculator.GetSum(4, 6)); // ==> 10

ComplexNumber c1 = new ComplexNumber(2, 7);
ComplexNumber c2 = new ComplexNumber(3, -1);
var complexCalculator = new Calculator<ComplexNumber>();
Console.WriteLine(complexCalculator.GetSum(c1, c2)); // ==> (5+6i)

Console.WriteLine(c1 + 100.5); // ==> (102.5+7i)
Console.WriteLine(c1 + i1); // ==> (4+7i)
Console.WriteLine(i1 + c1); // ==> (4+7i)


问:
Android development using C and C++
I am a C, C++ developer. I am interested in mobile development. I want to know how can I develop Android apps using C and C++, I have read that they are providing a kit for C, C++ developers but it does not have all functions as of Java kit. Should I go for C/C++ development kit or it's better to learn java as they may not provide all the functionality in future?</p>

答:
I would advise you to go for C++ if you have a firm plan to go into Game Development. But if not, you better go for Java. Here is a good primer for you on the official android website:

Game Development for Android: A Quick Primer

NOTE: Please do read step 2 (Step Two: Pick a Language) of the tutorial.

If you do not know Java at all and like to develop apps on Android for the long term, it is essential to learn Java. There are great tutorials given on the official website. There is a nice book that you can grab for learning specifically for Android development:
Here it is: Learn Java for Android Development

Title: Android development using C and C++


答:
I would say MVC is a concept or a family of similar patterns.

I think this article is worth to read. GUI Architectures by Martin Fowler

Title: What is MVC, really?

Body:
As a serious programmer, how do you answer the question What is MVC?

In my mind, MVC is sort of a nebulous topic — and because of that, if your audience is a learner, then you're free to describe it in general terms that are unlikely to be controversial.

However, if you are speaking to a knowledgeable audience, especially an interviewer, I have a hard time thinking of a direction to take that doesn't risk a reaction of "well that's not right!...".  We all have different real-world experience, and I haven't truly met the same MVC implementation pattern twice.

Specifically, there seem to be disagreements regarding strictness, component definition, separation of parts (what piece fits where), etc.

So, how should I explain MVC in a way that is correct, concise, and uncontroversial?


问:
How much code should I be responsible for?
Through colleagues and exit interviews, I have heard that at my small company I am "responsible" for anywhere from 3-10 times more code than I would be at another job. I'm trying to look for some sort of fuzzy metric that I can use to compare my workload with others in my field.

By "code responsibility", I don't mean "I'm the only one who knows area X of the code base" (though sadly, it's often true in a startup environment), but rather am referring to a number like "code_base_size/number_of_developers".

Are there any resources I can use to help me more accurately measure my work load than just counting lines of code?

答:
The only concrete measure for an employed developer is the number of hours spend coding and fixing bugs, and the money you get paid for it. If you are staying late at night 6 days a week for 50K US$ a year, then you have a problem. No matter how many lines of code your boss want you to be responsible for, you won't handle more than you can do, taking account of a certain code quality of course. Developing poor quality code with no unit tests is a good way to handle much more code, but the company will have to pay the price of a large technical debt.

In small companies developers tend to be responsible for much more code than in large corp. The factor 3 to 10 you are referring to seems realistic to me.

OwnerDisplayName: Mick

OwnerDisplayName: Patrick Smacchia - NDepend dev


答:
Short version : working with C++ on Android is possible and easier with each Android SDK/NDK version, but it's harder than working with Java.

Long version :

For each version, Google adds more functionalities to Android Native Development Kit and makes it more and more independant on the Java code.

Read http://developer.android.com/sdk/ndk/overview.html for more details:

Write a native activity, which allows you to implement the lifecycle
  callbacks in native code. The Android SDK provides the NativeActivity
  class, which is a convenience class that notifies your native code of
  any activity lifecycle callbacks (onCreate(), onPause(), onResume(),
  etc). You can implement the callbacks in your native code to handle
  these events when they occur. Applications that use native activities
  must be run on Android 2.3 (API Level 9) or later. You cannot access
  features such as Services and Content Providers natively, so if you
  want to use them or any other framework API, you can still write JNI
  code to do so.

The problem is just that if you use the most recent NDK, you'll not be able to deploy and a lot of not-recent Android versions.

Anyway even with previous NDK versions, you can have minimal Java code (for interacting with the OS) and the full application code in C++ or anything native.

There are also efforts in helping native developers to work fully in C or C++ via IDE plugins like this Vs-Android that is a plugin for Visual Studio 201x hiding all the compilation and generation process from you : http://code.google.com/p/vs-android/

Also, if you plan do port your application to other OS, going with C++ for the core of your application (maybe with a scripting language on top) is a good idea. It's just more expensive on development time than other alternatives - for reasons specific to C++ and it's available dev tools implementations, for example too much compilation times can kill your effective productivity.

That being said, that is not the most easy way to work on mobile apps.

Title: Android development using C and C++

Body: I am a C, C++ developer. I am interested in mobile development. I want to know how can I develop Android apps using C and C++, I have read that they are providing a kit for C, C++ developers but it does not have all functions as of Java kit. Should I go for C/C++ development kit or it's better to learn java as they may not provide all the functionality in future?</p>


答: code base size/number of developpers isn't related to the workload.  If you have an huge stable code base that metric will be high.  If you have a small code base still in development, that metric will be low.  lines changes per unit of time per developper is more related to the workload.  But even then, I've spent days to track subtle bugs whose fix was one line...</p>

Title: How much code should I be responsible for?

Body:
Through colleagues and exit interviews, I have heard that at my small company I am "responsible" for anywhere from 3-10 times more code than I would be at another job. I'm trying to look for some sort of fuzzy metric that I can use to compare my workload with others in my field.

By "code responsibility", I don't mean "I'm the only one who knows area X of the code base" (though sadly, it's often true in a startup environment), but rather am referring to a number like "code_base_size/number_of_developers".

Are there any resources I can use to help me more accurately measure my work load than just counting lines of code?


答:
The code should be the responsibility of the group not of one developer. Support should be delegated fairly each week, it seems stupid to allocate it any other way. If that is not the case I suggest you speak to your management.

In the situation your describing one developer might be struggling to meet deadlines because of a huge amount of support from one area where other developers are under worked. Its a very inefficient management structure.

Also I suggest you move away from measuring workload in lines of code. Man hours is the only sensible metric I can think of

Measuring programming progress by lines of code is like measuring
  aircraft building progress by weight - Bill Gates

NB. I'm not saying equal I'm saying fairly. Its also worth noting that its fine to specialize in certain aspects of the code base, that happens naturally. Its only a problem if nobody else ever works on that code.


答:
Should I go for C/C++ development kit or it's better to learn java as they may not provide all the functionality in future?

The answer is both.

If you are writing any applications where performance is a main
concern, they almost have to be in something other than java. (C/C++
is most popular) Games is the big ticket item, but there are others.

If you are doing any android development, you should also take the time to learn java to a reasonable level.

Title: Android development using C and C++


问:
Does the MIT open source license require work derivatives to be made public (under MIT license)?
I am looking for an open source license for a library I want to publish. Ideally, one should be allowed to use this library in free or commercial applications without paying me a fee, but if any derivative work from the library is created (any improvement of the library for example), it should be made available to everyone under that same license.

In other words, I want to put the following ethics: "You benefit from this piece of work for free, and if you improve it, I can benefit from your improvement for free too". It's a type copyleft license I am looking for.

The MIT license looks like a possible solution, but it is unclear to me whether derivative works of the code covered by this license MUST be made available PUBLICLY to everyone. Can anyone clarify/confirm this? If there is another more appropriate open source license covering my needs, I am interested too. Thanks.

答:
The MIT licence doesn't require derivative works to be open sourced.  You are looking for the GPL.

The GPL grants the recipients of a computer program the rights of the Free Software Definition and uses copyleft to ensure the freedoms are preserved whenever the work is distributed, even when the work is changed or added to. The GPL is a copyleft license, which means that derived works can only be distributed under the same license terms...


答:
For example, if Facebook had 2 programmers, they would obviously be
  overworked - but HOW would you reach that conclusion? That's the type
  of the question I was going for.

This isn't a programming question, it's a management question.

There are a few easy questions to answer this and they have nothing to do with software.

How many hours are you working?

How many hours should you be working?

Are deadlines being met?

Then follow this logic:

If 1>2, you need more people or less aggressive deadlines.

If 1<2, you need less people or more initiatives.

If deadlines aren't being met and 1>=2, you need more people.

If deadlines aren't being met and 1<2, you should go fire someone.

This is an oversimplification that has two glaring flaws.

People are not created equal.

There are ways to make people more production (upgrade their computer or something).

But you get the idea.


答:
The way you are doing load balancing seems a bit off to me. Rackspace cloud load balancing sits in front of your servers and balances the incoming requests between them. This is great for balancing incoming requests.

However, you are doing outgoing requests. This should be a daemon running on your server(s). And if it is, then your frontend load balancing does not have any effect at all. What you need to do is split up the tasks you are doing and have workers process them in parallel.

The way you usually do this is by using some kind of message or job queue. Gearman is a possibility. You could also use a message queue like rabbitmq. I personally really like zeromq.

Unlike other queueing systems, zeromq is not a daemon. It's not a server that acts as a queue. It's a library that allows you to build queues and concurrency. I highly suggest you watch this presentation.

What this allows you to do is create any amount of workers that do work. In your case they will send API requests. And then you can create a sink that collects the results of those calls. So each worker has its own process and does curl multi on 100 requests. And if you spawn 100 or 1000 worker processes (can be distributed between machines, connected over TCP), they will be able to do do the work in parallel.

I think it fits your use case pretty well: ZeroMQ.

Title: 100K curl requests

Body:
I am using curl_multi_exec to process over 100K requests. I do 100 requests at a time because curl_multi_exec can only handle 100 requests at a time to eventually get to 100K requests. We have added multiple servers to this system to spread the load [we are using load balancing]. What is the best way to have curl handle 100K requests and make use of these additional servers? What is the downside (other than time) of handling that many requests on one server? How can I use the additional servers to help handle those requests?

I was thinking about having each server handle a batch of requests (like one server handles 500 requests, another 500, another 500, etc..

To elaborate- basically, we are using curl to send out over 100K requests to third party servers. The problem with only using 1 server is that there is a memory limit in the number of requests 1 server can handle. So we decided to add additional servers, but we are not sure how to design this system to use curl to handle that many requests..

The third party server is an API like Facebook; they are aware that we will be making that many requests to their servers.

For load balancing, we use Rackspace cloud server, basically the load balancer directs incoming requests to separate servers.


问:
Is this a good code documentation practice?
I'm working on 2 projects projA and projB, and both projects are maintenance projects.  For projA there are 3 programmers and for projB there are 2 programmers. In each case all are working on separate points.

As code documentation is very important, can you tell me which one is the better practice?

Examples:

```<code>  {Author : lee    -verion 1.7    -date 30 dec  -asked by someGuy  -decription: to antialiase a line}
  procedure antiAlias(thisline);
  begin
     //do the anti aliasing...
   end;
</code>```

or

```<code>   {*123}
  unit testone;
..
..
..

    procedure antiAlias(thisline);
  begin
     //do the anti aliasing...
   end;
..
..

 end. //end of the unit..

{*123}
  {Author : lee    -verion 1.7    -date 30 dec  -asked by someGuy  -decription: to antialiase a line}
</code>```

the {*123} represent the point I have done for the particular unit. So the next point {*124} will be at the end of the unit.

This is done (very rarely though) as the code looks clean without the commented part and lots of decription at the end.

答: I personally dislike both approaches. With the exception of the description (which ideally I'd have before the method i.e. the first example) the other details add unnecessary clutter to the code, this is what source control and commit logs are for.   </p>


问:
Is the GoF book still the one to read?

Possible Duplicate:

  Is there a canonical book on design patterns?

I'd like to read a design patterns book. GoF for sure is the one to read. But after 15 years is it still valid, I mean isn't there an updated one?

Something like "Charles Darwin On the origin of species" is a very important book, and some main concepts are still valid, anyway today (2010) one would read another book to study the subject.

In this question the main suggestions are the Head First and GoF books. But Head first is not a replacement for GoF.

So any suggestion or should I stick with GoF?

答: You will still need it. You will keep coming back to it for double checking and small revisons and good examples. Keep it on your shelf. If you are a starter pick up Head First. On the contrary I am very interested in  finding out a book which is rated higher than GOF :-)</p>

ContentLicense: CC BY-SA 2.5

Title: Is the GoF book still the one to read?


答:
Just comment what it does and why - things the programmer fixing the code needs to know and can't get from reading the code.

Who, where, when, etc they can get from the comments on the SVN/GIT/etc checkin

Title: Is this a good code documentation practice?

Body:
I'm working on 2 projects projA and projB, and both projects are maintenance projects.  For projA there are 3 programmers and for projB there are 2 programmers. In each case all are working on separate points.

As code documentation is very important, can you tell me which one is the better practice?

Examples:

```<code>  {Author : lee    -verion 1.7    -date 30 dec  -asked by someGuy  -decription: to antialiase a line}
  procedure antiAlias(thisline);
  begin
     //do the anti aliasing...
   end;
</code>```

or

```<code>   {*123}
  unit testone;
..
..
..

    procedure antiAlias(thisline);
  begin
     //do the anti aliasing...
   end;
..
..

 end. //end of the unit..

{*123}
  {Author : lee    -verion 1.7    -date 30 dec  -asked by someGuy  -decription: to antialiase a line}
</code>```

the {*123} represent the point I have done for the particular unit. So the next point {*124} will be at the end of the unit.

This is done (very rarely though) as the code looks clean without the commented part and lots of decription at the end.


答:
When I first started learning programming, I started with OOP. Procedural code was mentioned, and we all understood the concept, but we simply didn't care about exploring procedural further since we were using .Net and going to be learning OOP.

Personally, I think if I HAD learned Procedural first I would have had a hard time making the transition to OOP, but I find going from OOP to Procedural extremely easy.

Title: Can you learn OO programming without procedural?

Body:
I've seen a number of question asking whether someone should learn procedural or OO first. But is this even possible? Can you learn OO programming without first having an understanding of procedural programming? Obviously, they can learn to program in an OO language like Java or Python first. But you can write Fortran in any language. My impression is that such beginning programmers write procedural code in an OO language at least at first.

But what do you think?


答:
I think it would significantly complicate parsing, especially with subqueries, e.g.

```<code>  FROM Foo f
  JOIN (FROM Bar b
        WHERE b.ID = f.ID
        UPDATE b
           SET b.Wibble = 1) x
    ON x.ID = f.ID
SELECT f.XYZ
</code>```

Parsing this would be more complicated.  You could not tell that the UPDATE was a syntax error until you had parsed the FROM clause, and the parser would have to remember enough context to know that it was parsing a subquery.  I don't think updates are permissible in subqueries anyway, but if they were (maybe with a RETURNING clause) then you might not be able to tell this was invalid until you had parsed the SELECT statement.

This would at least increase k (lookahead) for the grammar and at worst make it context sensitive, although this is stretching the bounds of my rather dimly remembered compiler design papers from university.

Body:
I think it would significantly complicate parsing, especially with subqueries, e.g.

  FROM Foo f
  JOIN (FROM Bar b
        WHERE b.ID = f.ID
        UPDATE b
           SET b.Wibble = 1) x
    ON x.ID = f.ID
SELECT f.XYZ

Parsing this would be more complicated.  You could not tell that the UPDATE was a syntax error until you had parsed the FROM clause, and the parser would have to remember enough context to know that it was parsing a subquery.  I don't think updates are permissible in subqueries anyway, but if they were (maybe with a RETURNING clause) then you might not be able to tell this was invalid until you had parsed the SELECT statement.

This would at least increase k (lookahead) for the grammar and at worst make it context sensitive, although this is stretching the bounds of my rather dimly remembered compiler design papers from university.


答:
It means register, and it isn't all for historical reasons.

The historical part is that Intel got itself into the habit of enumerating registers with letters with the 8008 (A through E plus H and L).  That scheme was more than adequate at the time because microprocessors had very few registers and weren't likely to get more, and most designs did it.  The prevailing sentiment then was that software would be rewritten for new CPUs as they appeared, so changing the register naming scheme between models wouldn't have been a big deal.  Nobody foresaw the 8088 evolving into a "family" after being incorporated into the IBM PC, and the yoke of backward compatibility pretty much forced Intel into having to adopt schemes like the "E" on 32-bit registers to maintain it.

The non-historical part is all practical.  Using letters for general-purpose registers limits you to 26, fewer if you weed out those that might cause confusion with the names of special-purpose registers like the program counter, flags or the stack pointer.

I don't have a source to confirm it, but I suspect the choice of R as a prefix and the introduction of R8 through R15 on 64-bit CPUs signals a transition to numbered registers, which have been the norm among 32-bit-and-larger architectures not derived from the 8008 for almost half a century.  IBM did it in the 1960s with the 360 and has been followed by the PowerPC, DEC Alpha, MIPS, SPARC, ARM, Intel's i860 and i960 and a bunch of others that are long-forgotten.

You'll note that the existing registers would fit nicely into R0 through R7 if they existed, and it wouldn't surprise me a bit if they're treated that way internally.  The existing long registers (RAX/EAX/AX/AL, RBX/EBX/BX/BL, etc.) will probably stay around until the sun burns out.

Title: What does the 'R' in x64 register names stand for?

Body:
I know the 32 bit registers were named like the 16 bit registers with an 'E' prefix to mean extended. I've always assumed that meant extended from 16 to 32 bits although I've never seen that explicitly stated.

I was trying to find out what the 'R' stands for but my google skills have failed me. Anyone know?


问:
Why do some sorting methods sort by 1, 10, 2, 3...?
I've noticed than many numerical sorting methods seem to sort by 1, 10, 2, 3... rather than the expected 1, 2, 3, 10... I'm having trouble coming up with a scenario where I would need the first method and, as a user, I get frustrated whenever I see it in practice. Are there legitimate use cases for the first style over the second? If so, what are they? If not, how did the first sort style ever come into being? What are the official names for each sort method?</p>

答: Others have answers what this sort is, but no one every really answered your question about why you see it. The answer isn't really that exciting. It's usually a bug.  Most sorting methods will default to one or the other and the programming likely careless of changing the default when sorting numbers.</p>


问:
Does it hurt to learn bits of many programming languages?
I started my programming career with BASIC, during 9th grade. I learned a bit of BASIC by writing simple programs to add, subtract and to print. Then I went to the university and took Computer Information and Systems Engineering. In the first year I was taught C, and I have good command over it.

Next I learned C++ in the second year. It just taught me some knowledge of OOP. Now I am doing PHP (along with HTML). I have not mastered C++, BASIC or PHP. I am now planning to move to mobile development. But I feel that I have not covered everything in the languages I learned.

Does it really matter?

答: If you're still in university, it shouldn't matter yet that you don't feel you've covered everything in any of the languages you know. Understanding the common fundamental theories behind these languages is much more important. Once you understand the basics, you can learn the details of other languages when you need them.


答: I learn what I need to learn in a particular language when I need to learn something new. The "trigger" that tells me I need to delve deeper into a language is that a particular bit of code looks ugly or clumsy, appears unmaintainable or is difficult to test or comment. Often these triggers point to my lack of knowledge of a particular programming idiom, style, data structure and so on. </p>

Title: Does it hurt to learn bits of many programming languages?

Body:
I started my programming career with BASIC, during 9th grade. I learned a bit of BASIC by writing simple programs to add, subtract and to print. Then I went to the university and took Computer Information and Systems Engineering. In the first year I was taught C, and I have good command over it.

Next I learned C++ in the second year. It just taught me some knowledge of OOP. Now I am doing PHP (along with HTML). I have not mastered C++, BASIC or PHP. I am now planning to move to mobile development. But I feel that I have not covered everything in the languages I learned.

Does it really matter?


答:
We're all just learning bits of programming languages.  I would only consider the language implementers to be those who are a 10 out of 10 in the knowledge of a language.

Learning multiple languages, and paradigms, is the only way to develop a "taste" for what you like and don't like.  If you only learned one language, you wouldn't even be able to really decide whether you even like it or not.

You're actually doing it the correct way.  You will be able to reuse the most important fundamentals you learn in each while getting exposure to different syntax, libraries, and frameworks.


答:
In my opinion, there's little point in changing language very frequently. You'll never actually grasp any of them. Especially some like C++, where some people spend a decade writing the language and still have their code look like C.

If you can't write best practices in a language, then don't move on, IMO. That means that covering more than a couple will take many years, if not decades.


答:
It is not neccessary to track revision history in code comments.

Documentation should start with meaningful entity names. Comments should expand on what the name and signature tells you. A method named "antiAlias" which takes a parameter "thisLine" does not need a comment explaining that it is "to antialiase a line", that much is obvious. It could be useful to explain what you mean by "antialias". If your environment supports a style of comments that shows up in inline help for the entity, such a comment documenting what a method does should use that. Comments documenting how the code works should apppear just before the code described.