答:
ANY language you learn is going to change in the next 5 years. It isn't about learning a language that you think might be around a while, but rather, learning HOW to learn. The more exposure to learning the language and the process of learning that language will help you tremendously in the long run!

The last company I worked for used their own in-house language. It was similar to visual basic but not the same. Just for the fact that I knew other languages, I was able to pick their language up a lot quicker than the other employees.

I learned Japanese after I learned C++, BASIC, Pascal, and I can say that learning a computer language and a foreign language take the same skills. Those skills can be lost or sharpened. If you have the drive, keep it going and learn new languages!

(ps. as for learning FORTRAN or assembly, I think it is valuable to at least take one semester of the older languages. It makes you think about stuff you just take for granted in the newer languages, things like flags, memory allocation and such.)

Title: Is it worth to learn Experimental Languages?

Body:
I'm a young programmer who desires to work in the field someday as a programmer.  I know Java, VB.NET and C#.  I want to learn a new language (as I programmer, I know that it is valuable to extend what I know - to learn languages that make you think differently).  I took a look online to see what languages were common.  Everybody knows C and C++ (even those muggles who know so little about computers in general), so I thought, maybe I should push for C.

C and C++ are nice but they are old.  Things like Haskell and Forth (etc. etc. etc.) are old and have lost their popularity.  I'm scared of learning C (or even C++) for this same reason.  Java is pretty old as well and is slow because it's run by the JVM and not compiled to native code.

I've been a Windows developer for quite a while.  I recently started using Java - but only because it was more versatile and spreadable to other places.  The problem is that it doesn't look like a very usable language for these reasons:

It's most used purpose is for web application and cellphone apps (specifically Android)

As far as actual products made with it, the only things that come to mind are Netbeans, Eclipse (hurrah for making and IDE with the language the IDE is for - it's like making a webpage for writing HTML/CSS/Javascript), and Minecraft which happens to be fun but laggy and bipolar as far as computer spec. support.

Other than that it's used for servers but heck - I don't only want to make/configure servers.

The .NET languages are nice, however:

People laugh if I even mention VB.NET or C# in a serious conversation.

It isn't cross-platform unless you use MONO (which is still in development and has some improvements to be made).

Lacks low level stuff because, like Java with the JVM, it is run/managed by the CLR.

My first thought was learning something like C and then using it to springboard into C++ (just to make sure I would have a strong understanding/base), but like I said earlier, it's getting older and older by the minute.

What I've Looked Into

Fantom looks nice.  It's like a nice middleman between my two favorite languages and even lets me publish between the two interchangeably, but, unlike what I want, it compiles to the CLR or JVM (depending on what you publish it to) instead of it being a complete compile.

D also looks nice.  It seems like a very usable language and from multiple sources it appears to actually be better than C/C++.  I would jump right with it, but I'm still unsure of its success because it obviously isn't very mainstream at this point.

There are a couple others that looked pretty nice that focused on other things such as Opa with web development and Go by GOOGLE.

My Question

Is it worth learning these "experimental" languages?  I've read other questions that say that if you aren't constantly learning languages and open to all languages that you aren't in the right mindset for programming.  I understand this and I still might not quite be getting it, but in truth, if a language isn't going to become mainstream, should I spend my time learning something else?  I don't want to learn old (or any going to soon be old) programming languages.  I know that many people see this as something important, *but would any of you ever actually consider (assuming you didn't already know) FORTRAN?  My goal is to stay current to make sure I'm successful in the future.

Disclaimer

Yes, I am a young programmer, so I probably made a lot of naive statements in my question.  Feel free to correct me on ANYTHING!  I have to start learning somewhere so I'm sure a lot of my knowledge is sketchy enough to have caused to incorrect statements or flaws in my thinking.  Please leave any feelings you have in the comments.

The Results...

I'm truly amazed by the amazing responses, most of them so nicely pointing out my misunderstandings and misjudgments.  I've learned quite a lot from this and I'm excited to hopefully utilize everything I've learned!  I'll probably start learning Haskell next (the not so old language, albeit over 20 years old - hahaha) and then start looking at some other options around me.

Thanks


问:
Is it worth to learn Experimental Languages?
I'm a young programmer who desires to work in the field someday as a programmer.  I know Java, VB.NET and C#.  I want to learn a new language (as I programmer, I know that it is valuable to extend what I know - to learn languages that make you think differently).  I took a look online to see what languages were common.  Everybody knows C and C++ (even those muggles who know so little about computers in general), so I thought, maybe I should push for C.

C and C++ are nice but they are old.  Things like Haskell and Forth (etc. etc. etc.) are old and have lost their popularity.  I'm scared of learning C (or even C++) for this same reason.  Java is pretty old as well and is slow because it's run by the JVM and not compiled to native code.

I've been a Windows developer for quite a while.  I recently started using Java - but only because it was more versatile and spreadable to other places.  The problem is that it doesn't look like a very usable language for these reasons:

It's most used purpose is for web application and cellphone apps (specifically Android)

As far as actual products made with it, the only things that come to mind are Netbeans, Eclipse (hurrah for making and IDE with the language the IDE is for - it's like making a webpage for writing HTML/CSS/Javascript), and Minecraft which happens to be fun but laggy and bipolar as far as computer spec. support.

Other than that it's used for servers but heck - I don't only want to make/configure servers.

The .NET languages are nice, however:

People laugh if I even mention VB.NET or C# in a serious conversation.

It isn't cross-platform unless you use MONO (which is still in development and has some improvements to be made).

Lacks low level stuff because, like Java with the JVM, it is run/managed by the CLR.

My first thought was learning something like C and then using it to springboard into C++ (just to make sure I would have a strong understanding/base), but like I said earlier, it's getting older and older by the minute.

What I've Looked Into

Fantom looks nice.  It's like a nice middleman between my two favorite languages and even lets me publish between the two interchangeably, but, unlike what I want, it compiles to the CLR or JVM (depending on what you publish it to) instead of it being a complete compile.

D also looks nice.  It seems like a very usable language and from multiple sources it appears to actually be better than C/C++.  I would jump right with it, but I'm still unsure of its success because it obviously isn't very mainstream at this point.

There are a couple others that looked pretty nice that focused on other things such as Opa with web development and Go by GOOGLE.

My Question

Is it worth learning these "experimental" languages?  I've read other questions that say that if you aren't constantly learning languages and open to all languages that you aren't in the right mindset for programming.  I understand this and I still might not quite be getting it, but in truth, if a language isn't going to become mainstream, should I spend my time learning something else?  I don't want to learn old (or any going to soon be old) programming languages.  I know that many people see this as something important, *but would any of you ever actually consider (assuming you didn't already know) FORTRAN?  My goal is to stay current to make sure I'm successful in the future.

Disclaimer

Yes, I am a young programmer, so I probably made a lot of naive statements in my question.  Feel free to correct me on ANYTHING!  I have to start learning somewhere so I'm sure a lot of my knowledge is sketchy enough to have caused to incorrect statements or flaws in my thinking.  Please leave any feelings you have in the comments.

The Results...

I'm truly amazed by the amazing responses, most of them so nicely pointing out my misunderstandings and misjudgments.  I've learned quite a lot from this and I'm excited to hopefully utilize everything I've learned!  I'll probably start learning Haskell next (the not so old language, albeit over 20 years old - hahaha) and then start looking at some other options around me.

Thanks

答:
In order to extend Telastyn's answer, it's indeed about exposure to different programming paradigms. For example, it isn't really about learning logic programming, but for:

learning to learn (practice on learning new skills)

training your brain to think in novel ways

maybe getting some less popular (or even esoteric) knowledge that few people have and could come in handy

or at least impress them with your technical knowledge :)

and of course, it provides valuable technical insight. Why is C# more popular than D? Can C++ do everything that D can do? Can D do more, or is it more like syntactic sugar?

http://skilldrick.co.uk/2011/02/why-you-should-learn-brainfuck-or-learn-you-a-brainfuck-for-great-good/

Another good reason to learn brainf*ck is to understand how basic a Turing-complete programming language can be. A common argument when programmers compare languages is “well they’re all Turing-complete”, meaning that anything you can do in one language you can do in another. Once you’ve learnt brainf*ck, you’ll understand just how difficult it can be to use a Turing-complete language, and how that argument holds no water.

http://norvig.com/21-days.html (Peter Norvig)

Learn at least a half dozen programming languages. Include one language that supports class abstractions (like Java or C++), one that supports functional abstraction (like Lisp or ML), one that supports syntactic abstraction (like Lisp), one that supports declarative specifications (like Prolog or C++ templates), one that supports coroutines (like Icon or Scheme), and one that supports parallelism (like Sisal).

ContentLicense: CC BY-SA 3.0


问:
Research topics for starting and optimizing a high-traffic website
I bury a good deal of my ideas for fear that I don't know enough about scaling web applications and high-traffic websites. That said, I'd like to know of any general topics to research in order to ensure that your web app doesn't break / slow down when you start getting to Twitter-level traffic.

I'm looking for research topics with, preferably, additional resources.

For example: Make sure you optimize SQL queries (see High Performance MySQL Optimization)

答:
Likely Suspects

Most likely, the things you want to pay attention to are:

your caching tier,

your database tier,

your general architecture's design (if it's not designed to scale, it just won't).

Further Reading

Words of caution about the resources below:

Some are generic resources, others are specific to one stack or language but still provide insight on the types of issues to deal with and how to (try to) address or mitigate them.

Some provide general information of scalability.

Some give only hints on basic pipeline and programming optimizations.

Some are sponsored or hosted by industry-actors, in which case conclusions and comparisons may or may not be accurate and/or impartial.

Research papers

Some papers' links may be unaccessible for you if you don't have a subscription to some publication networks.

Dynamic Load-Balancing on Web-Server Systems [PDF]

Web-Search for a Planet: the Google Architecture [PDF]

High-Performance Site Design Techniques [PDF]

Scalability Issues for High-Performance Digital Libraries on the Web [PDF]

Improving Performance on the Internet [PDF]

Web Server Farm in the Cloud [PDF]

Observations on Tuning a Java Application for Performance and Scalability

The Akamai Network: A Platform for High-Performance Web-Applications [PDF]

Books

Building Scalable WebSites (Henderson, 2006)

Building Scalable and High-Performance Java Web-Applications (Barish, 2002)

Handbook of Cloud Computing (Furht, Escalante, 2010)

High-Performance WebSites: Essential Knowledge for Front-End Engineers (Souders, 2007)

Architecture of Reliable Web-Applications Software (Radaideh, Al-Ameed, 2007)

Articles, Blogs and Web Resources

Performance Tuning and Optimization of High-Traffic WebSites

The Ultimate Guide to Web Optimization (Tips and Best Practices)

A herd of resources on Google's Make The Web Faster effort

like these tutorials

Scaling Python for High-Load WebSites

Handling Web-Servers of High-Traffic WebSites

How to Scale PHP Applications

TYPO3 Scalability for High-Traffic WebSites

Scaling Twitter: Making Twitter 10,000 Percent Faster

Scaling a High-Traffic Application: Our Journey From Java to PHP

Notes on the Google Talk Architecture

Famous Last Words

While I can understand your original intuition that you should bury some projects out of fear that they won't adapt well and survive, I think that's the wrong approach. While the "build it and they will come" approach can be wrong, the "build it only once it's perfect" counter-part can be just as wrong.

You don't know if your projects will reach the critical mass where they actually need to care about these issues, so why not build them anyways?

Maybe you'll fail at first, but then you'll have learned and your next product will fare better. It's better to try it this way than to one day really have to dive in the deep end of the pool without a net, for a real product. So go ahead and give these ideas a chance.

While it's true that it's hard to make an application scalable when it hasn't been originalyl designed to be, at least you'll have an application that needs to be modified for scalability. In my book it's better than no application at all.

ContentLicense: CC BY-SA 4.0


问:
Are unit tests really used as documentation?
I cannot count the number of times I read statements in the vein of 'unit tests are a very important source of documentation of the code under test'. I do not deny they are true.

But personally I haven't found myself using them as documentation, ever. For the typical frameworks I use, the method declarations document their behaviour and that's all I need. And I assume the unit tests backup everything stated in that documentation, plus likely some more internal stuff, so on one side it duplicates the documentation while on the other it might add some more that is irrelevant.

So the question is: when are unit tests used as documentation? When the comments do not cover everything? By developers extending the source? And what do they expose that can be useful and relevant that the documentation itself cannot expose?

答:
I'm going to answer your question by asking you another.

How often when working with a new API/routine have you fired up help to look for a code example of the thing you're trying to use? Failing that you switch over to google for an online search of code samples?

That is exactly when you would use unit tests as documentation.

In fact the unit tests can be a little more rigorous than normal code examples, because you should have multiple tests (examples).

Hopefully your unit tests illustrate proper usage. E.g. They clearly show all essential dependencies either via normal objects or mock objects. (Otherwise they're not particularly good unit tests.)

NOTE: If your comments or "normal documentation" provides code examples, you're actually violating the DRY principles. And those code examples can easily become incorrect over time, whereas there's significantly less chance of that with regularly executed unit tests.

If the unit tests are thorough (usually a big if), then they should provide additional information:

All known edge cases clearly illustrated.

All expected exceptions that can be thrown.

All bugs previously found (this is probably more useful when extending the unit under test than when writing a new client for the unit).

All underlying business rules associated with the unit. (if any)

I suspect there are quite a few reasons unit test don't tend to get used as documentation even though they could be an excellent complement to more traditional documentation:

I would venture to suggest that often the tests themselves aren't well enough written for the purpose. Other answers have already alluded to tests that are:

Incomplete.

Confusing. (I've seen test cases that don't call the method under test directly - you go 3/4 levels deep into the call stack before it's called and the preconditions to calling the method are scattered in different places in a complex class hierarchy.)

Outdated. (usually tests should fail when they become outdated, but this is not always the case).

There are usually plenty examples of use already available in production code whenever the need for an example arises.

The unit under test is so well written (self documenting) that the methods don't need examples. I wish!

In my experience as a programmer, we tend to be quite keen to jump in at the deep end and RTFM next Tuesday...

Documentation and comments that violate the DRY principle.


答:
Languages are developed to solve problems in some sort of domain(at least at first). If you haven't faced problems that your tools can't solve in a way that you are comfortable with, you'll be hammering a wooden plank expecting to become a carpenter.
Try to understand the kind of problems the languages are trying to solve. The only difference between an "experimental" language and a new/hip cool guy language is the money supporing it, for example Go from google and Dart. If they were developed in my backyard, they will probably die in some forum and that's it. They only survive if they are good at explaining the problems they are trying to solve. Or the other way around, like Perl and C++, which are good at absorving ways of solving problems to keep being alive.
And i might suggest learning Lua, it's a language made for embedding inside programs, it's very fast and lightweight, which will give you tools to solve the big or small problems that some languages like Java can't solve in a straightforward way.
Taking the example of Japanese, if you just learn the syntax, grammar and alphabets, ignoring the culture, you will never understand why it's so complicated, and eventually forget all about it. It's not solving anything for you.</p>


答:
Stay Fit: Get Regular Practice

Practice makes perfect.

The more code you write AND read, the closer you get to enlightenment / mastery as a programmer / developer / software engineer / guru / ninja / craftsman / hacker / buzzword-of-choice. By not only coding and reading more, but also trying our new ways of writing code, the more open-minded you (hopefully) remain.

Recommended Reading:

Programming, Motherf*cker (Z. Shaw, 1984) (pardon his French... ;))

Learning About New Paradigms and Language Features

Maybe you won't be able to translate what you use in brand new Super-Language-X to your Enterprise-Language-Y, but maybe you'll be able to recognize when it could have been a good fit. Maybe you'll be able to know when to integrate a different technology or stack in your project to fit a particular purpose. Or maybe you'll know how to use the features of language Y to emulate the cool feature of language X, and refactor your code to benefit from it (and potentially enlighten other co-workers along the way).

For instance, you could have discovered interesting FP principles and want to adapt them to Java, which is arguably not FP by design.

Recommended Reading:

Why Functional Programming Matters [PDF] (J. Hughes, 1984)

Be a Jack of All Trades... Master of Some?

You don't know which language will become mainstrain when it's in that "experimental" stage, so you shouldn't worry too much about betting on one of them. Chances are, other people will make the same bet and will be intrigued when they see these showing up on your resume. Add one tool to your belt. In our case, there's not much problem with how much it weighs in the end.

Sure, you can't become a master of all trades. But you could be a master of one, and pretty good at the rest. You're learning a craft, and ours is multi-faceted. Doing regular exercises, attending workshops, grabbing a book, writing a new pet-project and other similar things are our way to keep up with the ever-increasing pace of change in our field.

Recommended Reading:

Teach Yourself Programming in 10 Years (P. Norvig)

Beating the Average (P. Graham)

Stay Adaptable

If you don't learn to adapt, it's hard to do it when you need it. By constantly learning new things, you get better and better each time at picking new stuff up (as long as you don't constrain yourself to very similar challenges).

It's like the "Stay Young" Oasis song goes: Stay young and invincible.

If you can adapt, you can survive.

Recommended Reading:

There's No Speed-Limit. (The Lessons That Changed My Life) (D. Sivers, 2009)

Stay Visible: Understand the Recruitment-Agency's Radar

They use keywords and technologies as check-boxes. We use them as honey-pots for mindless recruiters.

It works both ways. As long as you really know your stuff, then having lots of stuff on your resume is good. It shows your adaptability and breadth of knowledge. Plus, if you really master a few of these, and are decent in a few others, it allows you to modulate different versions of your resume for different positions and jobs.

Other Helpful SE Topics

If One is to Learn One Programming Language Per Year, What Should the List Be?

Jack of All Trades, Master of None

I'm Having Trouble Learning


问:
Can I provide a GPL app, with different licenced logo?
I want to provide my app under GNU GPL v3, but I would be glad if people couldn't change its name or its logo. Can I provide my app under the GNU GPL v3 licence, while the app's name and logo are under another type of licence like CC BY-NC-ND 3.0? (The logo and name is used in the app source and design.)</p>

答: You can put the logo (and other non-code content) under another license, but the name is considered indivisible from the code and falls under its license.</p>

OwnerDisplayName: totymedli

OwnerDisplayName: Ignacio Vazquez-Abrams


问:
When to use assertions and when to use exceptions?
Often when I write a functions I want to make sure the inputs to it are valid in order to detect such errors as early as possible (I believe these are called preconditions). When a precondition fails, I've always thrown an exception. But I'm beginning to doubt whether this is the best practice and if not assertions would be more appropriate.

So when should I do which: when is it appropriate to use an assertion and when is it appropriate to throw an exception?

答:
Assertions should only be used to verify conditions that should be logically impossible to be false (read: sanity checks). These conditions should only be based on inputs generated by your own code. Any checks based on external inputs should use exceptions.

A simple rule that I tend to follow is verifying private functions' arguments with asserts, and using exceptions for public/protected functions' arguments.

ContentLicense: CC BY-SA 2.5


问:
Single quotes vs double quotes
I just started a job where I'm writing Python after coming from a Java background, and I'm noticing that other developers tend to quote strings using single quotes ('') instead of double quotes (""). For example:

```<code>line1 = 'This is how strings typically look.'
line2 = "Not like this."
</code>```

Is there a particular reason for this other than personal preference? Is this the proper way to be quoting strings? Specifically, what I want to know is if there is some type of standard or accepted best practice that drives this style of coding.

答:
There is no difference between using single quotes and double quotes in Python. In practical terms, depending on the kind of data you are working with, you may find one or the other style more convenient.

The type of quotes used "by default" (where there is no compelling reason to use one or the other) is pretty much a matter of personal preference.

For more information, see the section on String Literals in the Python documentation.

Title: Single quotes vs double quotes


问:
DRY, string, and unit testing
I have a recurring question when writing unit tests for code that involves constant string values.

Let's take an example of a method/function that does some processing and returns a string containing a pre-defined constant. In python, that would be something like:

STRING_TEMPLATE = "/some/constant/string/with/%s/that/needs/interpolation/"

def process(some_param):
    # We do some meaningful work that gives us a value
    result = _some_meaningful_action()
    return STRING_TEMPLATE % result
```

<p>If I want to unit test <code>process</code>, one of my tests will check the return value. This is where I wonder what the best solution is.</p>

<p>In my unit test, I can:</p>

<ol>
<li>apply DRY and use the already defined constant</li>
<li>repeat myself and rewrite the entire string</li>
</ol>

<pre class="lang-py prettyprint-override"><code>def test_foo_should_return_correct_url():
    string_result = process()

    # Applying DRY and using the already defined constant
    assert STRING_TEMPLATE % "1234" == string_result

    # Repeating myself, repeating myself
    assert "/some/constant/string/with/1234/that/needs/interpolation/" == url
</code>```

The advantage I see in the former is that my test will break if I put the wrong string value in my constant. The inconvenient is that I may be rewriting the same string over and over again across different unit tests.

答:
There's a little warning about the DRY principle that many people aren't aware of: Don't get so obsessed about avoiding repetition that you remove 'duplicates' of things that appear to be the same but are actually conceptually very different.

As an extreme example you wouldn't try to remove the repetition of the duplicates of '/s', 'th', 'on', 'nt', etc within your original string.

In your particular example, you don't/shouldn't care about implementation details of your code under test. (I.e. that it uses the STRING_TEMPLATE const.)  Your test cares about the fact that when you:

```<code>void Test() {
  DoSetup(...);
  ActualResult = DoProcess(...);
  Check(ActualResult == "/some/constant/string/with/1234/that/needs/interpolation/");
}
</code>```

The fact that "/some/constant/string/with/1234/that/needs/interpolation/" is similar to STRING_TEMPLATE should be considered coincidental, not a violation of DRY.

NOTE: This of course doesn't apply if you're actually testing some localisation aspect of your system, or if your system is affected by localisation that you initially set up via STRING_TEMPLATE. Because then the duplication is explicit.

Title: DRY, string, and unit testing

Body:
There's a little warning about the DRY principle that many people aren't aware of: Don't get so obsessed about avoiding repetition that you remove 'duplicates' of things that appear to be the same but are actually conceptually very different.

As an extreme example you wouldn't try to remove the repetition of the duplicates of '/s', 'th', 'on', 'nt', etc within your original string.

In your particular example, you don't/shouldn't care about implementation details of your code under test. (I.e. that it uses the STRING_TEMPLATE const.)  Your test cares about the fact that when you:

void Test() {
  DoSetup(...);
  ActualResult = DoProcess(...);
  Check(ActualResult == "/some/constant/string/with/1234/that/needs/interpolation/");
}

The fact that "/some/constant/string/with/1234/that/needs/interpolation/" is similar to STRING_TEMPLATE should be considered coincidental, not a violation of DRY.

NOTE: This of course doesn't apply if you're actually testing some localisation aspect of your system, or if your system is affected by localisation that you initially set up via STRING_TEMPLATE. Because then the duplication is explicit.


答:
Is all the GPL code you use in that application yours? Then you can license it any way you want, you yourself aren't required to follow the terms of your own licenses, you always have all rights. (Given you don't sell your rights, like it is possible in the US, of course.)

If it is not then you can only dual license it because the GPL applies to the whole distribution, no matter what. Dual licensing is giving the choice between multiple different licenses, for example the picture could be licensed under the GPL and a custom license. This obviously doesn't work for taking rights away but only for giving additional ones.

I am not sure but the logo might be seen as trade mark, in that case additional laws might apply but I have absolutely no knowledge about that.

Title: Can I provide a GPL app, with different licenced logo?

Body: I want to provide my app under GNU GPL v3, but I would be glad if people couldn't change its name or its logo. Can I provide my app under the GNU GPL v3 licence, while the app's name and logo are under another type of licence like CC BY-NC-ND 3.0? (The logo and name is used in the app source and design.)</p>


问:
Tool to visualize values from variables during the execution of a program in C
I just need to see what is stored, in realtime, in some particular variables and struct used by an application written in C.

I need something like the stack tracer that comes with the ADT plugins for Eclipse as part of the Android sdk.

答: If I understand correctly you just need to use a debugger.  If you compiled with gcc then you can use gdb.  You will want to add the -g -O0 flags to include debugging symbols and turn off optimization.  If you need to you can even attach gdb to a running process.  I know microsoft has a similar debugger I'm just not familiar with it.</p>


答:
From a technical perspective it makes no difference, from a style perspective a few thoughts:

Most other programming languages use double quotes.

When writing in English usually double quotes are used.

Single quotes are useful when you have a lot non-technical/narrative text in your application because they allow you to use double quotes in a more natural way. bar = '"It\'s awesome" he said.'

On the other side the single quote character is also used in a few occasions in the english language. bar = "\"It's awesome\" he said."

Title: Single quotes vs double quotes

Body:
I just started a job where I'm writing Python after coming from a Java background, and I'm noticing that other developers tend to quote strings using single quotes ('') instead of double quotes (""). For example:

```<code>line1 = 'This is how strings typically look.'
line2 = "Not like this."
</code>```

Is there a particular reason for this other than personal preference? Is this the proper way to be quoting strings? Specifically, what I want to know is if there is some type of standard or accepted best practice that drives this style of coding.


答:
The other answers are correct in that it makes no technical difference, but I have seen one informal style rule on a couple of open-source projects: double quotes are used for strings that might eventually be visible to the user (whether or not they need translation), and single quotes are for strings that relate to the functionality of the code itself (eg. dict keys, regular expressions, SQL).

This is certainly not a universal rule (or even codified in a PEP), so like any other arbitrary aspect of coding it comes down to local rules.

Note that PEP 8 (which I hadn't noticed when I wrote this answer) says:

This PEP does not make a recommendation for this. Pick a rule and stick to it. When a string contains single or double quote characters, however, use the other one to avoid backslashes in the string. It improves readability.

As a commenter points out, this isn't necessarily contradictory, depending on how you interpret "rule". What I suggest doesn't really work with the second half of the quote though.

Title: Single quotes vs double quotes


答:
It is very simple:

Single quotes allow un-escaped embedding of double quotes.

Double quotes allow for embedding of un-escaped single quotes.

It is most Pythonic to use ' ( single quotes ) until you need double quotes.

The following quote is directly from the documentation on String literals.

In plain English: String literals can be enclosed in matching single
  quotes (') or double quotes ("). They can also be enclosed in matching
  groups of three single or double quotes (these are generally referred
  to as triple-quoted strings). The backslash () character is used to
  escape characters that otherwise have a special meaning, such as
  newline, backslash itself, or the quote character. String literals may
  optionally be prefixed with a letter 'r' or 'R'; such strings are
  called raw strings and use different rules for interpreting backslash
  escape sequences. A prefix of 'u' or 'U' makes the string a Unicode
  string. Unicode strings use the Unicode character set as defined by
  the Unicode Consortium and ISO 10646. Some additional escape
  sequences, described below, are available in Unicode strings. A prefix
  of 'b' or 'B' is ignored in Python 2; it indicates that the literal
  should become a bytes literal in Python 3 (e.g. when code is
  automatically converted with 2to3). A 'u' or 'b' prefix may be
  followed by an 'r' prefix.

In triple-quoted strings, unescaped newlines and quotes are allowed
  (and are retained), except that three unescaped quotes in a row
  terminate the string. (A “quote” is the character used to open the
  string, i.e. either ' or ".)

Title: Single quotes vs double quotes


答:
Some things to consider when developing your habit of whether to use single or double quotes regularly.

Double quotes requires two finger keying; and therefore more likely for typing errors as well as a speed decrease

Your editor may show one character better then another; for easier visual syntax debugging.

Docstrings use triple characters: Which looks better? """""" or ''''''

Although I have not seen this on Windows OS, some syntax or documentation tools may expect double verse single quotes.

For most of the Python tutorials I've seen I see the opposite of your experience. I usually see double quotes used.

Title: Single quotes vs double quotes


问:
Implementing `let` without using a macro
I'm learning Lisp, and I've just gotten to let, which I don't quite understand (the implementation of).

A common definition for it is given in terms of lambda as a macro.  However, nowhere have I seen that let must be implemented as a macro or in terms of lambda.

Is it possible to define let without using a macro or lambda?

I know it can be implemented as a primitive, but I want to know whether it can be implemented in Lisp without creating a macro -- by creating a special form or a function.

答:
For beginners nested function calls like the following might be very difficult to understand:

```<code> (+ (fibonacci (- N 1)) (fibonacci (- N 2)))))
</code>```

To make such expressions easier to write and comprehend, one could define local name bindings to represent intermediate results:
    (

```<code>let
    ((F1 (fibonacci (- N 1)))
     (F2 (fibonacci (- N 2))))
      (+ F1 F2))
</code>```

The let special form above defines two local variables, F1 and F2, which binds to Fib(N-1) and Fib(N-2) respectively. Under these local bindings, let evaluates (+ F1 F2). The fibonacci function can thus be rewritten as follows:

```<code>(defun fibonacci (N)
  "Compute the N'th Fibonacci number."
  (if (or (zerop N) (= N 1))
      1
    (let
    ((F1 (fibonacci (- N 1)))
     (F2 (fibonacci (- N 2))))
      (+ F1 F2))))
</code>```

Body:
For beginners nested function calls like the following might be very difficult to understand:

 (+ (fibonacci (- N 1)) (fibonacci (- N 2)))))

To make such expressions easier to write and comprehend, one could define local name bindings to represent intermediate results:
    (

let
    ((F1 (fibonacci (- N 1)))
     (F2 (fibonacci (- N 2))))
      (+ F1 F2))

The let special form above defines two local variables, F1 and F2, which binds to Fib(N-1) and Fib(N-2) respectively. Under these local bindings, let evaluates (+ F1 F2). The fibonacci function can thus be rewritten as follows:

(defun fibonacci (N)
  "Compute the N'th Fibonacci number."
  (if (or (zerop N) (= N 1))
      1
    (let
    ((F1 (fibonacci (- N 1)))
     (F2 (fibonacci (- N 2))))
      (+ F1 F2))))


答:
In my opinion I prefer to use the double quotes for a string.

Why?
For programmers of other languages can be adapted quickly and understand the code more easily.

If a C programmer see:

'Writing "It\'s big?" No.'
```

<p>Will be hesitant, instead of:</p>

<pre class="lang-py prettyprint-override"><code>"Writing \"It's big?\" No."
</code>```

Title: Single quotes vs double quotes

Body:
In my opinion I prefer to use the double quotes for a string.

Why?
For programmers of other languages can be adapted quickly and understand the code more easily.

If a C programmer see:

'Writing "It\'s big?" No.'

Will be hesitant, instead of:

"Writing \"It's big?\" No."


答:
A couple comments on what you have said...

1)  Every programmer should learn C, even if it's old.  It's a great language for getting close to the machine.  From Joel's advice to CS students....

Learn C before graduating

Part two: C. Notice I didn't say C++. Although C is becoming
  increasingly rare, it is still the lingua franca of working
  programmers. It is the language they use to communicate with one
  another, and, more importantly, it is much closer to the machine than
  "modern" languages that you'll be taught in college like ML, Java,
  Python, whatever trendy junk they teach these days. You need to spend
  at least a semester getting close to the machine or you'll never be
  able to create efficient code in higher level languages. You'll never
  be able to work on compilers and operating systems, which are some of
  the best programming jobs around. You'll never be trusted to create
  architectures for large scale projects. I don't care how much you know
  about continuations and closures and exception handling: if you can't
  explain why while (*s++ = *t++); copies a string, or if that isn't the
  most natural thing in the world to you, well, you're programming based
  on superstition, as far as I'm concerned: a medical doctor who doesn't
  know basic anatomy, passing out prescriptions based on what the pharma
  sales babe said would work.

2)  Languages can be good for learning mindsets, even if they aren't commonly used.  Learn Scheme (or LISP) to understand functional programming, even if it isn't trendy.  From another post on this board.

Congratulations, it sounds (to me) like you may be
  going to one of the few schools left that actually tries to teach
  computer science. Learning Scheme as a first language is (IMO) a very
  good thing. No, it's not as commercial as many others, but it's an
  excellent language for learning the real essence of computer science.
  – Jerry Coffin Oct 20 '11 at 3:32

C, C++ and Java are industry
  byproducts of computer science. Scheme's entire roots are in computer
  science. The languages in commercial use have as much to do with
  computer science as McDonalds has to do with cuisine.
  – JasonTrue Oct 20 '11 at 5:30

These guys are correct; you are confusing
  computer programming with computer science -- as Dijkstra said, that's
  like confusing telescope construction with astronomy. Scheme is about
  the best language there is for learning basic concepts in computer
  science. If you're expecting that taking a computer science degree is
  about learning how to write line-of-business apps in Java, you might
  be enrolled in the wrong program.
  – Eric Lippert Oct 20 '11 at 7:40

Almost all developers I know have learned C/C++ by themselves.
  You don't need university for that. – mouviciel Oct 20 '11 at 7:48

For the same reason that zoology courses teach evolutionary biology,
  anatomy and animal behaviour rather than how to muck out an elephant
  stall – jk. Oct 20 '11 at 7:58

Now despite attacking your original premise, I think you should be commended for your curiosity.  Too many people become obsolete due to a lack of curiosity.  Taking advantage of your personal development is a great sign that you will develop well.  The people who learn the most are the ones willing to keep asking how things work.


答:
Learning multiple different languages will give you a broader view of programming. Emphasis on "different" - e.g. learning C# and Java will not teach you that much more than learning just one of them. But learning C# or Java, and a functional language (for example) will.

Having said that, as a young programmer, I think you would get a lot more value out of getting to know one language really solidly, before bouncing around looking at different types of language. It's not entirely clear from your question how well you know Java, VB.NET and C#. Are you confident that if you attacked a project using one of the above languages, your bottleneck would be the project itself, not your knowledge of the language? If you would spend more time asking yourself "how do I do this in language?" than you would spend thinking about the actual problem, then your probably need more focus on one of your current languages.

And personally I think you should take a pragmatic approach to deciding which one that is. Java is used for Android apps? Great, if making Android apps is something you're interested in. Irrelevant if it isn't. C# is not a great fit for non-Windows development? Bad news if you're interested in developing for Linux. Irrelevant if you're not. And so on.

And the "experimental" languages you mentioned? Pragmatically, they're going to be a poor fit when it comes to working with other people - you'll probably find a thousand people who know C# or Java for every one who knows Fantom. For personal projects, this is not necessarily a problem. If your goal is to increase your employability, it is.


答:
You can certainly keep ownership of the logo and name yourself while releasing the code under the GPL. This is essentially what the Firefox/Mozzila logo licence did. Truecrypt also have a similar requirement, you can alter the code but not call the modified version Truecrypt.

However since you have released the code under the GPL there is nothing to stop the users  simply rebuilding their code under a new name and logo.


问:
Do companies care about university grades when hiring programmers?
Most of my fellow students that I've talked to claim that aiming for good grades is useless as the companies don't care about them when hiring programmers. To them, it's enough to have simply attended courses which may be important, and that's that.

Is this true? Are university grades useless when leaving campus, or do employers ask to see them for an interview?

答:
I can only tell about the local area - for me it's Latvia - the companies prefer peoples with working experience.

Based on my interview experience I was never asked about my university grades (my grades were just slight above average); the same situation for my friends and colleagues, who are working in the IT/software development area. Of course, that could be because of technical graduated student's shortage here - mostly students are going for a management and economic education...


答:
It is not strictly necessary that let must be implemented as a macro. It would be possible for let to be defined as a primitive form, where the expression evaluator understands directly what let is supposed to mean.

However, since Lispers are typically a minimalist bunch, let is usually defined in terms of existing facilities (a macro and lambda). This kind of definition saves having to do extra work. For example, in Scheme R5RS, the let construct is defined as "library syntax":

library syntax:  (let <bindings> )

where library syntax means:

To aid in understanding and implementing Scheme, some features are marked as library. These can be easily implemented in terms of the other, primitive, features.

Title: Implementing `let` without using a macro

Body:
I'm learning Lisp, and I've just gotten to let, which I don't quite understand (the implementation of).

A common definition for it is given in terms of lambda as a macro.  However, nowhere have I seen that let must be implemented as a macro or in terms of lambda.

Is it possible to define let without using a macro or lambda?

I know it can be implemented as a primitive, but I want to know whether it can be implemented in Lisp without creating a macro -- by creating a special form or a function.

Body:
It is not strictly necessary that let must be implemented as a macro. It would be possible for let to be defined as a primitive form, where the expression evaluator understands directly what let is supposed to mean.

However, since Lispers are typically a minimalist bunch, let is usually defined in terms of existing facilities (a macro and lambda). This kind of definition saves having to do extra work. For example, in Scheme R5RS, the let construct is defined as "library syntax":

library syntax:  (let <bindings> <body>)

where library syntax means:

To aid in understanding and implementing Scheme, some features are marked as library. These can be easily implemented in terms of the other, primitive, features.


答:
I agree with you on the exposure part of things. Though I know Java, C, C++, Javascript, Python, Ruby and a bit of .NET (primarily because I hate anything M$ <- personal opinion) I'll have to say that I really love programming in D.

D has a really nice feature set (most of them are implemented in C++/Java (languages which have class abstractions) etc) but the one thing I absolutely love the most is generics and delegates(makes it easy to implement callbacks). That apart you get a much simpler syntax to deal with in comparison to C++. D has a really efficient garbage collector, though you can choose to handle memory yourself (especially when interfacing with C/C++ modules). Though D does not have loads of user contributed modules that shouldn't be a barrier for entry. You can easily interface with existing C/C++ libraries (which are pleanty) thus making it redundant for need of modules.

D has its own standard library (Phobos) which serves the need for all common programming problems. There is also an alternative library (Tango-D2) which you can use either with Phobos or by itself. If you are a web developer and in the need for writing an event-based server, Tango has a nice Selector abstraction (tango.io.Selector for only select(), poll(), epoll()). I have found it to perform even better than libev.


问:
My boss decided to add a "person to blame" field to every bug report. How can I convince him that it's a bad idea?
In one of the latest "WTF" moves, my boss decided that adding a "Person To Blame" field to our bug tracking template will increase accountability (although we already have a way of tying bugs to features/stories). My arguments that this will decrease morale, increase finger-pointing and would not account for missing/misunderstood features reported as bug have gone unheard.

What are some other strong arguments against this practice that I can use? Is there any writing on this topic that I can share with the team and the boss?

答:
Point out that if a single person's mistake causes a bug to end up in production, then there's something wrong with your methodology, or your over-all way of developing software.  Point out that preventing bugs getting to production is the responsibility of the entire team.

Using either of these two arguments, see if you can persuade your boss that having the "whom to blame" field as a single-selection field would be misleading; and that therefore, it's necessary to make sure that the "whom to blame" field is a multiple-selection field.  Once you've achieved this, then ensure that for every bug, everybody's name is in the field.  Your boss will eventually see that any reporting on the field is futile.


问:
A deque based on binary trees
This is a simple immutable deque based on binary trees. What do you think about it? Does this kind of data structure, or possibly an improvement thereof, seem useful? How could I improve it, preferably without getting rid of its strengths? (Not in the sense of more operations, in the sense of different design) Does this sort of thing have a name?

Red nodes are newly instantiated; blue ones are reused. Nodes aren't actually red or anything, it's just for emphasis.

Note that right deques do not take O(n). Any access to an element in the deque depends on how long ago it was inserted. You can perform any enqueue or concat operation at O(1).

You can also use the 'weight' of each non-leaf node to change the orientation of the tree, such as to make all right access costly and left access cheap, or to provide O(logn) access to either end. This process takes O(n) worst case, depending on the initial orientation of the tree.

Alternatively, I could 'search' for the lightest node into which to insert a given node, turning all operations into O(logn) operations.

答: O(N) dequeue right? Thanks, but I'll find another implementation. The deque from the C++ Standard lib can do O(1) push and pop from both ends, and random access.

Title: A deque based on binary trees


答:
My first thought was learning something like C and then using it to
  springboard into C++ (just to make sure I would have a strong
  understanding/base), but like I said earlier, it's getting older and
  older by the minute.

Well, this is a giant pile of fallacy. People who know C have a harder time learning C++, because pretty much everything they think they knew about how to use the language is a giant pile of wrong. There is virtually no idiomatic C that is even remotely good C++. You are better off simply learning C++ from scratch. People like myself who volunteer their time to help other people learn C++ spend a massive proportion of it trying to teach people to drop their C habits.

As for popularity, well, C++ is experiencing a bit of a re-emergence recently. People noticed that actually, performance does matter, a lot, and you can't get away with running every component as a managed one, and Modern C++ (especially with C++11) is absolutely nothing like the C garbage they thought it was, and it's really not that bad at all. It's not really getting older. It's getting newer. The new Standard is a vast upgrade- and there are no suitable replacement languages, either current or in the pipeline, for many of the areas C++ is used in now. This is not least because there are no languages with decent C++ interoperability (even C++ itself), making it difficult to migrate away from existing C++ codebases.

People laugh if I even mention VB.NET or C# in a serious conversation.

Get new people. AFAIK, VB.NET doesn't really exist for any reason except to help migrate away from VB6 and isn't really a worthy goal in as of it's own right, but C# is a real language. It's kinda like Java, except they then added actual language features and some nice libraries. C# is a very popular, well-supported language with very good tools in VS, which doesn't suck that badly, and is a solid, if not exceptional, thing to learn.

It isn't cross-platform unless you use MONO (which is still in
  development and has some improvements to be made).

MONO is pretty stable. Plus, ultimately, 90% of desktop consumers (or was it 80%?) run Windows right now. If you're gonna develop a desktop application, it's an open question as to whether the non-Windows-users are worth the time to support, even if you use a cross-plat language.

Ultimately, you could get a lot from learning a language like C++ or Haskell, which focuses on strong compiler technology rather than a massive runtime.

Just don't pick PHP. The only thing you can learn from that is how not to build a language.


问:
What's the point of passing a parameter by reference in C#?

Possible Duplicate:

  Why are objects passed by reference?

Doesn't C# send the objects themselves? So unless it's some kind of swap function for primitive typed variables - why would I send an object by reference?

答:
Send objects by reference when you want to have the possibility of modifying the original object. Otherwise, send by value if you just need the value of the object.

Passing by reference happens all the time and isn't just for swap functions.


答:
It is necessary to use when you want a method to modify a value type or modify a reference to a reference type, The most commmon reason for doing either of these in code I've seen is interop with C || C++ libraries, e.g. ref int is marshalled to *int.

In pure managed code it tends to be rarer to need ref or out as you mainly use reference types which already give you references to objects rather than copies of objects like value types do. i.e. one level of indirection is all you need most of the time (indeed if you need ref a lot you may be a three star programmer ;)

Title: What's the point of passing a parameter by reference in C#?

Body:
Possible Duplicate:

  Why are objects passed by reference?

Doesn't C# send the objects themselves? So unless it's some kind of swap function for primitive typed variables - why would I send an object by reference?


答:
Making a deep copy of an object is a potentially very expensive operation in terms of both memory and CPU. In some cases (DataTable and friends come to mind), there is even code in place that prevents naive deep copying, although one could question here what is cause and what is effect. If the type of the instance has any sort of global state, making a naive deep copy could potentially be dangerous.

On the other hand, making a deep copy of the value of a primitively-typed variable is quite cheap, and in some cases (for example, immutability of strings) comes essentially for free.

Generally, I feel that functions should not touch their input parameters unless the caller actually wants it to. An easy way to ensure that the caller at least is aware that the callee might alter the input is to require passing by reference, either ref or out as appropriate.


答:
When you pass an object by reference, you can change the value of the reference.

Let's say you have a Person class:

```<code>public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public override string ToString()
    {
        return String.Format("Name: {0} - Age: {1}", Name, Age);
    }
}
</code>```

You also have these functions:

```<code>private static void NormalChangeProperties(Person person)
{
    person.Name = "Bob";
    person.Age = 17;
}

private static void NormalAssignNewPerson(Person person)
{
    person = new Person { Age = 55, Name = "John" };
}

private static void NormalSetNull(Person person)
{
    person = null;
}

private static void ByRefChangeProperties(ref Person person)
{
    person.Name = "Bob";
    person.Age = 17;
}

private static void ByRefAssignNewPerson(ref Person person)
{
    person = new Person { Age = 55, Name = "John" };
}

private static void ByRefSetNull(ref Person person)
{
    person = null;
}
</code>```

And then you have this console app:

```<code>static void Main(string[] args)
{
    Person p = new Person { Age = 29, Name = "Kristof" };
    Console.WriteLine("Initial: {0}", p);

    NormalChangeProperties(p);
    Console.WriteLine("After NormalChangeProperties: {0}", p);

    NormalAssignNewPerson(p);
    Console.WriteLine("After NormalAssignNewPerson: {0}", p);

    NormalSetNull(p);
    Console.WriteLine("After NormalSetNull: {0}", p);

    Console.WriteLine("");
    Console.WriteLine("");

    Person p2 = new Person { Age = 29, Name = "Kristof" };
    Console.WriteLine("Initial: {0}", p2);

    ByRefChangeProperties(ref p2);
    Console.WriteLine("After ByRefChangeProperties: {0}", p2);

    ByRefAssignNewPerson(ref p2);
    Console.WriteLine("After ByRefAssignNewPerson: {0}", p2);

    ByRefSetNull(ref p2);
    Console.WriteLine("After ByRefSetNull: {0}", p2 != null ? p2.ToString() : "null");

    Console.ReadLine();
}
</code>```

The output will be:

```<code>Initial: Name: Kristof - Age: 29
After NormalChangeProperties: Name: Bob - Age: 17
After NormalAssignNewPerson: Name: Bob - Age: 17
After NormallSetNull: Name: Bob - Age: 17

Initial: Name: Kristof - Age: 29
After ByRefChangeProperties: Name: Bob - Age: 17
After ByRefAssignNewPerson: Name: John - Age: 55
After ByRefSetNull: null
</code>```

As you can see, assigning a new value (as opposed to changing properties) or setting it to null (which is also changing the value) of the reference itself, requires you pass by reference.

For a better and more detailed explanation, you can have a look at this article by Jon Skeet.

Body:
When you pass an object by reference, you can change the value of the reference.

Let's say you have a Person class:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public override string ToString()
    {
        return String.Format("Name: {0} - Age: {1}", Name, Age);
    }
}

You also have these functions:

private static void NormalChangeProperties(Person person)
{
    person.Name = "Bob";
    person.Age = 17;
}

private static void NormalAssignNewPerson(Person person)
{
    person = new Person { Age = 55, Name = "John" };
}

private static void NormalSetNull(Person person)
{
    person = null;
}

private static void ByRefChangeProperties(ref Person person)
{
    person.Name = "Bob";
    person.Age = 17;
}

private static void ByRefAssignNewPerson(ref Person person)
{
    person = new Person { Age = 55, Name = "John" };
}

private static void ByRefSetNull(ref Person person)
{
    person = null;
}

And then you have this console app:

static void Main(string[] args)
{
    Person p = new Person { Age = 29, Name = "Kristof" };
    Console.WriteLine("Initial: {0}", p);

    NormalChangeProperties(p);
    Console.WriteLine("After NormalChangeProperties: {0}", p);

    NormalAssignNewPerson(p);
    Console.WriteLine("After NormalAssignNewPerson: {0}", p);

    NormalSetNull(p);
    Console.WriteLine("After NormalSetNull: {0}", p);

    Console.WriteLine("");
    Console.WriteLine("");

    Person p2 = new Person { Age = 29, Name = "Kristof" };
    Console.WriteLine("Initial: {0}", p2);

    ByRefChangeProperties(ref p2);
    Console.WriteLine("After ByRefChangeProperties: {0}", p2);

    ByRefAssignNewPerson(ref p2);
    Console.WriteLine("After ByRefAssignNewPerson: {0}", p2);

    ByRefSetNull(ref p2);
    Console.WriteLine("After ByRefSetNull: {0}", p2 != null ? p2.ToString() : "null");

    Console.ReadLine();
}

The output will be:

Initial: Name: Kristof - Age: 29
After NormalChangeProperties: Name: Bob - Age: 17
After NormalAssignNewPerson: Name: Bob - Age: 17
After NormallSetNull: Name: Bob - Age: 17

Initial: Name: Kristof - Age: 29
After ByRefChangeProperties: Name: Bob - Age: 17
After ByRefAssignNewPerson: Name: John - Age: 55
After ByRefSetNull: null

As you can see, assigning a new value (as opposed to changing properties) or setting it to null (which is also changing the value) of the reference itself, requires you pass by reference.

For a better and more detailed explanation, you can have a look at this article by Jon Skeet.


答:
One problem with asserts for me is that they are disabled by default in Java.

We use a fail-first strategy where the program - which may have been running unattended for years - needs to crash as early as possible to avoid data corruption in case of bad data (on an unexpected form).  This is what we use the checking for, and by using asserts we basically risk them not being active.

Title: When to use assertions and when to use exceptions?

Body:
Often when I write a functions I want to make sure the inputs to it are valid in order to detect such errors as early as possible (I believe these are called preconditions). When a precondition fails, I've always thrown an exception. But I'm beginning to doubt whether this is the best practice and if not assertions would be more appropriate.

So when should I do which: when is it appropriate to use an assertion and when is it appropriate to throw an exception?


答:
C may be old, but it still is very powerful and interesting, learning C will help you a lot in  your "programming" future.

Java is not slow, whoever told you that doesn't know what he's talking about, Java will learn you a ton about O.O.P.

Why don't you just start with Python and then go for C or something else,


答:
Typical programming practice is to compile out assertions from production/release builds. Assertions will help only during internal testing to catch failure of assumptions. You should not assume the behavior of external agencies, so you should not assert on events from the network or user. Also it is a good practice to write handling code for production builds in case an assertion fails.

For example in C,

```<code>int printf(const char *fmt, ...)
{
  assert(fmt);  // may fail in debug build but not in production build
  if (!fmt) return -1; // handle gracefully in production build
  ...
}
</code>```

Exceptions are meant to be built into production builds. The alternative for exception is returning error and not assertions.

Body:
Typical programming practice is to compile out assertions from production/release builds. Assertions will help only during internal testing to catch failure of assumptions. You should not assume the behavior of external agencies, so you should not assert on events from the network or user. Also it is a good practice to write handling code for production builds in case an assertion fails.

For example in C,

int printf(const char *fmt, ...)
{
  assert(fmt);  // may fail in debug build but not in production build
  if (!fmt) return -1; // handle gracefully in production build
  ...
}

Exceptions are meant to be built into production builds. The alternative for exception is returning error and not assertions.


答: You'd better learn as many "old" languages as you can, if you ever want to be a programmer. Start with Lisp, get a good grasp of Forth, pay a close attention to the evolution of all the Wirth languages, evolution of Fortran, rise and fall of Prolog, sneak into the secretive Ada ecosystem, get your secret weapon from learning Occam. Chasing the "mainstream" is the stupidest thing an aspiring programmer could ever do.</p>


答:
Congratulations you invented the immutable list. It appears in every functional language and is the bread and butter of functional programming. It's not often used as a dequeue though.

For that purpose there are better data-structures. I recommend reading "Purely Functional Data Structures" by Chris Okasaki if you'd like to gain some insight into the different data-structures that exist.

Title: A deque based on binary trees

Body:
This is a simple immutable deque based on binary trees. What do you think about it? Does this kind of data structure, or possibly an improvement thereof, seem useful? How could I improve it, preferably without getting rid of its strengths? (Not in the sense of more operations, in the sense of different design) Does this sort of thing have a name?

Red nodes are newly instantiated; blue ones are reused. Nodes aren't actually red or anything, it's just for emphasis.

Note that right deques do not take O(n). Any access to an element in the deque depends on how long ago it was inserted. You can perform any enqueue or concat operation at O(1).

You can also use the 'weight' of each non-leaf node to change the orientation of the tree, such as to make all right access costly and left access cheap, or to provide O(logn) access to either end. This process takes O(n) worst case, depending on the initial orientation of the tree.

Alternatively, I could 'search' for the lightest node into which to insert a given node, turning all operations into O(logn) operations.


问:
How to control messages to the same port from different emitters?
Scene: A company has many factories X, each emits a message to the same receive port in a Biztalk server Y; if all messages are processed without much delay, each will trigger an outgoing message to another system Z.

Problem: Sometimes a factory loses its connection for a half-day or more and, when the connection is reestablished, thousands of messages get emitted. Now, the messages still get processed well by Y (Biztalk can easily handle the load) but system Z can't handle the flood and may lock up and severely delay the processing of all other messages from the other X.

What is the solution? Creating multiple receive locations that permits us to pause one X or another would lose us information if the factory isn't smart enough to know whether the message was received or not.

What is the basic pattern to apply in Biztalk for this problem? Would some throttling parameters help to limit the flow from any one X? Or are their techniques on the end part of Y which I should use instead ? I would prefer this last one since I can be confident that the message box will remember any failures, which could then be resumed.

答: When a flood of messages is received from a particular X (say X1), Y should try and combine the messages (removed duplicates, etc.) without any loss of information and then send the messages at pace that Z would be able to handle. All this while messages from other Xs would be processed (by Y) and be sent to Z.</p>


问:
Make a big deal out of == true?
There is a colleague of mine who constantly writes:

```<code>if (someBool == true)
</code>```

It drives me up the wall!  Should I make a big deal of it or just drop it?

答:
Consider yourself lucky, my half-monkey colleague writes

```<code>if (true)
</code>```

I found it many times in his code. And that's not the worst thing I found. I found GOTOs. And we use C#. Now calm down and hold back your homicidal instincts.

Title: Make a big deal out of == true?

Body:
Consider yourself lucky, my half-monkey colleague writes

if (true)

I found it many times in his code. And that's not the worst thing I found. I found GOTOs. And we use C#. Now calm down and hold back your homicidal instincts.


问:
Are all languages basically the same?
Recently, i had to understand the design of a small program written in a language i had no idea about (ABAP, if you must know). I could figure it out without too much difficulty.

I realize that mastering a new language is a completely different ball game, but purely understanding the intent of code (specifically production standard code, which is not necessarily complex) in any language is straight forward, if you already know a couple of languages (preferably one procedural/OO and one functional).

Is this generally true? Are all programming languages made up of similar constructs like loops, conditional statements and message passing between functions? Are there non-esoteric languages that a typical Java/Ruby/Haskell programmer would not be able to make sense of? Do all languages have a common origin?

答:
I would say that a  language encodes meaning. If the meaning has any sense in some context then all languages that could express the meaning could be said to be equivalent limited by the meaning and the context.

If you limit that context to a standard Von Neumann machine then the computational meanings of changing memory and computing in a cpu could be said to be the origin - and possibly the only meaning that all the languages have in common. All other things are abstraction built on these.

OwnerDisplayName: Anirudh

Title: Are all languages basically the same?

OwnerDisplayName: Preet Sangha


答:
Hardware description languages are programming languages, but they are conceptually very different.
Try VHDL or Verilog on for size.  They are common for programming FPGAs.  (Ok, so they're not processors, but they are general purpose computing devices.  And such should be considered valid hardware for computer science topics.)  You have to explicitely make things occur serially.  It's a completely different model.  You have think of things occuring in parallel as the rule not the exception.  For loops in verilog expand into parallel hardware.  So the "expected" behavior might not be what you expect.</p>

Title: Are all languages basically the same?

Body:
Recently, i had to understand the design of a small program written in a language i had no idea about (ABAP, if you must know). I could figure it out without too much difficulty.

I realize that mastering a new language is a completely different ball game, but purely understanding the intent of code (specifically production standard code, which is not necessarily complex) in any language is straight forward, if you already know a couple of languages (preferably one procedural/OO and one functional).

Is this generally true? Are all programming languages made up of similar constructs like loops, conditional statements and message passing between functions? Are there non-esoteric languages that a typical Java/Ruby/Haskell programmer would not be able to make sense of? Do all languages have a common origin?

OwnerDisplayName: NoMoreZealots


答:
The basics of most procedural languages are pretty much the same.

They offer:

Scalar data types: usually boolean, integers, floats and characters

Compound data types: arrays (strings are special case) and structures

Basic code constructs:  arithmetic over scalars, array/structure access, assignments

Simple control structures: if-then, if-then-else, while, for loops

Packages of code blocks: functions, procedures with parameters

Scopes: areas in which identifiers have specific meanings

If you understand this, you have a good grasp of 90% of the languages on the planet.
What makes these languages slightly more difficult to understand is the incredible variety of odd syntax that people use to say the same basic things.  Some use terse notation involving odd punctuation (APL being an extreme).  Some use lots of keywords (COBOL being an excellent representative).  That doesn't matter much.  What does matter is if the language is complete enough by itself to do complex tasks without causing you tear your hair out.  (Try coding some serious string hacking in Window DOS shell script: it is Turing capable but really bad at everything).

More interesting procedural languages offer

Nested or lexical scopes, namespaces

Pointers allowing one entity to refer to another, with dynamic storage allocation

Packaging of related code: packages, objects with methods, traits

More sophisticated control: recursion, continuations, closures

Specialized operators: string and array operations, math functions

While not technically a property of the langauge, but a property of the ecosystem in which such languages live, are the libraries that are easily accessible or provided with the language as part of the development tool.  Having a wide range of library facilities simplifies/speeds writing applications simply because one doesn't have to reinvent what the libraries do.  While Java and C# are widely thought to be good languages in and of themselves, what makes them truly useful are the huge libraries that come with them, and easily obtainable extension libraries.

The languages which are harder to understand are the non-procedural ones:

Purely functional languages, with no assignments or side effects

Logic languages, such as Prolog, in which symbolic computation and unification occur

Pattern matching languages, in which you specify shapes that are matched to the problem, and often actions are triggered by a match

Constraint languages, which let you specify relations and automatically solve equations

Hardware description languages, in which everything executes in parallel

Domain-specific languages, such as SQL, Colored Petri Nets, etc.

There are two major representational styles for languages:

Text based, in which identifiers name entities and information flows are encoded implicitly in formulas that uses the identifiers to name the entities (Java, APL, ...)

Graphical, in which entities are drawn as nodes, and relations between entities are drawn as explicit arcs between those nodes (UML, Simulink, LabView)

The graphical languages often allow textual sublanguages as annotations in nodes and on arcs.  Odder graphical languages recursively allow graphs (with text :) in nodes and on arcs.  Really odd graphical languages allow annotation graphs to point to graphs being annotated.

Most of these languages are based on a very small number of models of computation:

The lambda calculus (basis for Lisp and all functional languages)

Post systems (or string/tree/graph rewriting techniques)

Turing machines (state modification and selection of new memory cells)

Given the focus by most of industry on procedural languages and complex control structures, you are well served if you learn one of the more interesting languages in this category well, especially if it includes some type of object-orientation.

I highly recommend learning Scheme, in particular from a really wonderful book:
Structure and Interpretation of Computer Programs.  This describes all these basic concepts.  If you know this stuff, other languages will seem pretty straightforward except for goofy syntax.

Title: Are all languages basically the same?

OwnerDisplayName: Ira Baxter


答:
Depends on what you mean by "basically." All languages of any flexibility are Turing-complete. In that sense: yes, they are all basically the same.

On a low level, they all perform similar sequences of operations and all Windows, Linux, and (recent) OS X stuff all runs on Intel-compatible processors using the same instruction sets. In that way they are also basically the same.

I realize that you sorta defined "basically" in your question, but to really answer it, that definition will have to be much more refined. In many ways they are all alike. In many ways they are distinct. It's all too easy to say "it depends." If you take either extreme, the question will likely not answer what you intend it to so where that line is drawn is crucial to answering your question as you intend it.

Title: Are all languages basically the same?

OwnerDisplayName: Dinah


答:
Mature languages generally have a few goals, and they make tradeoffs where they sacrifice one thing for another.  A general-purpose language can be used for anything, but no language can ever excel in every area.  A few examples:

C attempts to be an ideal systems programming language.  To this end it sacrifices readability and safety for low-level control and speed.

Python aims to be an ideal scripting language.  To this end it sacrifices speed and verifiability for productivity and portability.

Haskell attempts to be a safe, mathematically pure language.  To this end it sacrifices learnability and convention for verifiability and reliability.

These sacrifices and benefits make a huge difference in the language.  Yes, most programming languages can be used for anything that can be done by a computer, but none of those same languages should be used for everything.  All of the languages above are ones I would choose for certain tasks but not for others.  If I were programming an operating system I would choose C.  If I were writing a backend for a website, I would use Python.  And if I were writing a financial system I would use Haskell.

In the end, your choice as a programmer is what the right tool for the job is.

Title: Are all languages basically the same?

OwnerDisplayName: Imagist


答:
Programming languages are also tools for thinking. With another thinking perspective, some problems disappear or are transformed to different, more manageable kind (for example, many C++ style design patterns just disappear when you are thinking in Lisp (see for example this Peter Norvik's presentation), and Erlang frees you from thinking of some low level concurrency or distributed computing constructs and lets you just concentrate on the application logic).

Note, however, that sometimes the "new" paradigms can be partially be applied to "older" programming languages which explains why we for example have books teaching functional programming for Java programmers. But natively supporting and integrating a more powerful paradigm in the language level enables more natural application of the paradigm (and consequentially makes it impossible to understand programs in a language supporting unfamiliar paradigm, as hinted by other answers - @Ira Baxter listing non-procedural languages and @kwatford referring to Paul Graham).

Title: Are all languages basically the same?

OwnerDisplayName: FooF


答:
Typically, "no". LET mixes evaluated and unevaluated forms, in a way that's hard to deal with without some kind of rewriting. So, if it's not a special form (that is, a form that is treated in a uniqeu way by the evaluator), it probably needs to be a macro.

Saying that, the transformation is (relatively) easy.

```<code>(let ((var1 value1) (var2 value2) ...) body)
</code>```

is simply turned into:

```<code>((lambda (var1 var2 ...) body) value1 value2 ...)
</code>```

So even if you can't implement LET without macros, you can certainly implement the same functionality (local, lexical bindings) without anything special.

Body:
Typically, "no". LET mixes evaluated and unevaluated forms, in a way that's hard to deal with without some kind of rewriting. So, if it's not a special form (that is, a form that is treated in a uniqeu way by the evaluator), it probably needs to be a macro.

Saying that, the transformation is (relatively) easy.

(let ((var1 value1) (var2 value2) ...) body)

is simply turned into:

((lambda (var1 var2 ...) body) value1 value2 ...)

So even if you can't implement LET without macros, you can certainly implement the same functionality (local, lexical bindings) without anything special.


答:
Grades are not the only factor to consider when hiring someone, but obviously they are pretty important, especialy if you lack experience.

But, I am concerned that you might seriously consider not aiming for good grades because you think that some employers might not care. If there is a remote chance that an employer might care (and many will), then why not aim for the best grades you can? In fact, forget about employers, and forget about grades, why are you not simply aiming to do the best you can and get the most out of your education?

If you aim to get the most out of your time studying then good grades will follow anyway. Sure, there may be compromises e.g. you might take a harder module because you enjoy it more and maybe you may get a lower grade than if you took an easier option, but if you care about what you are doing and put the effort in you'll get good grades.

Put it this way, if you don't get good grades and feel you could have, you'll regret it sooner or later.

Title: Do companies care about university grades when hiring programmers?

Body:
Most of my fellow students that I've talked to claim that aiming for good grades is useless as the companies don't care about them when hiring programmers. To them, it's enough to have simply attended courses which may be important, and that's that.

Is this true? Are university grades useless when leaving campus, or do employers ask to see them for an interview?


问:
Who should get a developer certificate from Apple if client want their company name to show up in App Store
I am about start my first project with client, However I will work as a consultant. So do I need to get developer certificate and post my client's app in app store? Or I should ask my client to get the license and then I help them deploying the app on their name?

They don't want company name to be my organisation but they want their company name to show up in App Store.

However the developer of app is my organisation not them.

How to deal with this situation?

答:
You need to separate out the different parts of the process.

What hardware, software, licenses, registration do you need to develop and test the code? You have to decide if you are going to use resources they have that the client owns; or if they are going to purchase and keep these tools; Or if they expect you to provide them.

Once the software is ready to be released via the app store you have to look at the ultimate consumer of the software. Will they want to see that the software was made by doNotCheckMyBlog LLC, or by your client. Most of the time the client should be the one listed. They are marketing the app in support of the rest of their business. You may be the one submitting all the documentation and code to get accepted by the app store, but their name should be on the documents

Keep in mind that you have a contract. Once the software is released the responsibilities for bug fixes, upgrades, and new versions could be handled either in-house or by another development company.


答:
Apple has this scenario covered. Your client will need to join the iOS dev program so they can post things to the store. They can then add you to their program for development certificates and such if you don't have your own as well as provision an iTunes connect account for you to publish to the store on their behalf.

I would advise getting your own iOS dev program account if for no other reason than convenience.

Title: Who should get a developer certificate from Apple if client want their company name to show up in App Store

Body:
I am about start my first project with client, However I will work as a consultant. So do I need to get developer certificate and post my client's app in app store? Or I should ask my client to get the license and then I help them deploying the app on their name?

They don't want company name to be my organisation but they want their company name to show up in App Store.

However the developer of app is my organisation not them.

How to deal with this situation?


答:
```<code>+++++++[>+++++++++++<-]>+.<+++++++++++[>+++<-]>.>>+++++++[>++++++<-]>++++.
</code>```

At the lowest level, every programming language is the "same," but that doesn't meant that they're the same at the level where you actually interact.  They abstract problems for you; that doesn't mean that they abstract the same problems or that they abstract each problem the same way.

Title: Are all languages basically the same?

Body:
+++++++[>+++++++++++<-]>+.<+++++++++++[>+++<-]>.>>+++++++[>++++++<-]>++++.

At the lowest level, every programming language is the "same," but that doesn't meant that they're the same at the level where you actually interact.  They abstract problems for you; that doesn't mean that they abstract the same problems or that they abstract each problem the same way.


问:
Do your managers prefer to create proof of concept (POC) before working prototype?
At last team meeting I heard from managers that we need to create proof of concept (POC) before main prototype and integrate this concept with the main system for proving a new feature.

Could you explain me the main features or this method?

Do you use the POC in your projects before implementation?

What is the main advantages and disadvantages of this method?

答:
The terms "proof of concept" and "prototype" are so similar that you should probably ask your managers what each of them means in the context of your company.

I've worked in a few places where proofs-of-concept, prototypes or whatever you want to call them are used, for different reasons:

to understand a technical risk, such as the performance of a product or its ability to integrate with external systems.

to evaluate different technology options for later selection e.g. choice of web server or database

to demonstrate how the product might work with a view to informing UX, design and business decisions over its features.

Notice that in each case there's a clear done-ness to the work: you have useful performance numbers. You have a justified choice of database technology. You have a usable prototype. That means that work on the prototypes or proofs-of-concept is bounded. It's usually also time-boxed (matching with the concept of a research spike in iterative development) so you agree what the problem is you're trying to solve and how long you've got to explore the solution.

Typically the PoC is "one to throw away"; it's built such that you can get something working quickly on your box to show that it can be done but it's not actually going to be part of the finished product. You might use the code to guide your production implementation[*], or you might just take what you learned and build it again from scratch.

[*] Where I'm using the proof of concept to learn about an API, I sometimes take the things I learn from the PoC and write them as unit tests. Those tests can be part of the real product's test suite without copying PoC code into production.

Advantages:

you quickly learn whether what you want to do is achievable

you quickly learn whether what you want to do is desirable

Disadvantages:

it can be hard to argue that what you're doing adds value when it isn't going into production

seeing the PoC functioning, even if it's smoke and mirrors, can lead to a false illusion of progress when you demo it to other people.


答:
You've rediscovered a couple of things...

"Binary tree" does not automatically mean "binary search tree".

The text-book form of a data structure isn't the end of the story. Data structures can be adapted and "augmented". Some augmented data structures are text-book examples in their own right - e.g. interval trees.

Adding extra summary data to each node is a fairly common trick with tree data structures. A favorite of mine is including subtree size information alongside key summaries. In that way, I have containers that can easily support subscripted access as well as key-based search. In my case, these are multiway trees with all data items in the leaf nodes (basically B+ trees). So the keys in the branch nodes are really just another form of summary - the first (or last) key in the subtree. With both subtree-sizes and discrete-typed keys, another sometimes-useful trick is being able to search in O(log n) time for the lowest key >= some minimum that isn't already present in the tree.

And obviously, it's just as valid to not have keys at all if you don't need them. A container that supports subscripting but not key-based search is, of course, an array or vector. A multiway tree version might be appropriate if you need a huge vector with frequent insertions/deletions at arbitrary positions, though it's a niche thing at best. A binary tree based vector might have some niche application too.

One example I have using subtree size summaries isn't really a data structure as it relies on underlying containers. It's used where the information is logically structured as a tree. In a BST, the data is logically structured as a sorted sequence - the end-user doesn't know or care that that's implemented via tree structures. This class is used where parent/child relationships are relevant to the application.

The underlying data is normally held in a similar way to how you'd build tree structures within a relational database - items have parent fields etc - though the library is decoupled from that by being a C++ policy-driven template. It works through a set of simple calls such as Get_Parent, Get_Next_Child and so on, which are usually trivial to implement.

I call the library an "XML tool", basically because it supports a view of the underlying tree that is similar to XML elements. You can traverse the whole tree, for example, and you will see begin "tags" and end "tags" for each node in the order you'd expect to see the tags in an XML file representing that tree. There's other traversal orders, such as "treeview" (preorder), and there's support for subscripting as well as simple traversal.

And there's support for summaries where every item gets a size (which can be zero, but not negative) and a running total is kept. I've used this e.g. for a tree-table control that I admittedly never finished. When an item is collapsed, it's total size summary for its descendants is forced to zero (with changes propogated up the tree) so that searches based on position within this view of the tree don't see those descendants. That makes it easy to find and iterate the currently visible items.

BTW - the unfinished GUI tree table control was never the most important application - it's just an easy one to visualise.

Title: A deque based on binary trees


问:
How to calculate the checksum for Laboratory Information System (LIS) frames?
I am developing instrument driver and I want to know how to calculate checksum for a Laboratory Information System (LIS) frame.

Explanation:

Expressed by characters [0-9] and [A-F].

Characters beginning from the character after [STX] and until [ETB] or [ETX] (including  [ETB] or [ETX]) are added in binary.

The 2-digit numbers, which represent the least significant 8 bits in hexadecimal code,   are converted to ASCII characters [0-9] and [A-F].

The most significant digit is stored in CHK1 and the least significant digit in CHK2.

This is sample frame :

```<code><STX>2Q|1|2^1||||20011001153000<CR><ETX><CHK1><CHK2><CR><LF>
</code>```

and I want to know what is value of chk1 and chk2 and I am new in this so I am totally blank about how to calculate checksum

I am not getting above 3rd and 4th point.

Can anyone provide sample code for c#?

答:
Finally I got answer.

Here is c# code for calculate checksum.

```<code>private string CalculateChecksum(string dataToCalculate)
{
    byte[] byteToCalculate = Encoding.ASCII.GetBytes(dataToCalculate);

    int checksum = 0;

    foreach (byte chData in byteToCalculate)
    {
        checksum += chData;
    }

    checksum &= 0xff;

    return checksum.ToString("X2");
}
</code>```

Body:
Finally I got answer.

Here is c# code for calculate checksum.

private string CalculateChecksum(string dataToCalculate)
{
    byte[] byteToCalculate = Encoding.ASCII.GetBytes(dataToCalculate);

    int checksum = 0;

    foreach (byte chData in byteToCalculate)
    {
        checksum += chData;
    }

    checksum &= 0xff;

    return checksum.ToString("X2");
}


答:
Section 7 of GPLv3 states:

Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
  ...
  c. Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version

I've heard this means you can add restrictions requiring someone to change the name (and logo) of your software if they make it different enough from the original (the "requiring that modified versions of such material be marked ... as different from the original version" part), and it seems that you could also require someone to preseve the name or logo when they modify our software (the "Prohibiting misrepresentation of the origin of that material" part).

As an example of the former case, cdrecord had a license restriction that required you to change the name of the software if you changed the location of the configuration file because the author didn't want to support distributions of cdrecord that he considered broken. The author's attitudes and ideas about how the GPL copyright works caused friction between him and the rest of the free software community, so eventually the Debian project forked his software and renamed it to wodim. However, if Debian felt that the naming requirement made the software non-free, they would have had legal problems distributing wodim too.

If you're too inflexible about balancing these two goals, some copyright consumers  might steer clear of your software to avoid getting into legal limbo. Consider that Debian's "desert island test" would mean they'd consider your software non-free if you imposed a requirement that someone who modified the software always had to contact the original author to determine whether they were still allowed to use the original name and logo.

Additionally: The Debian project that feels there are problems with distributing non-free logos in their archives, and they will not accept the software if their users do not have a license to modify the logo as they see fit. You can write a restrictive trademark license on the unmodified logo, but you must grant the user the freedom to modify the bits so that when he modifies them to the point that they no longer infringe the trademark, his modified version of your logo (which is a derived work for copyright purposes) can be used freely. (This may be required by the GPL v3, or it may just be Debian's approach to free software, but Debian's views on copyright are definitely worth considering if you're licensing Linux software under the GPL and tackling the issues that you've asked about.)

Body: I want to provide my app under GNU GPL v3, but I would be glad if people couldn't change its name or its logo. Can I provide my app under the GNU GPL v3 licence, while the app's name and logo are under another type of licence like CC BY-NC-ND 3.0? (The logo and name is used in the app source and design.)</p>


问:
OAuth2 vs Public API
My understanding of OAuth (2.0) is that its a software stack and protocol to allow 2+ web apps to share information about a single end user. User A is a member of Site B and Site C; Site B wants to fetch some data from Site C about User A, and this is where OAuth steps in.

So first off, if this assessment is incorrect, please begin by clarifying this for me and correcting me!

Assuming I'm on the right track, then I guess I'm not seeing the need for OAuth to begin with (!). I'm sure I'm just not seeing the "forest through the trees" here, but the way I see it, couldn't Site C just expose a public API that Site B could use to fetch the same data (sans OAuth)? If Site C required user credentials to access the data, could this public API just use HTTPS for secure transport and require username/password as a part of each API call?

Again, I'm sure I'm missing something, but I'm just not understanding why I would need OAuth when a secure, public API written and exposed by Site C seems more than capable of delivering what Site B needs regarding User A.

In general, I'm looking for a set of guidelines to go by when deciding to choose between using OAuth for my web apps or just writing my own web service ( exposing public API).

Thanks in advance!

答:
OAuth is an open standard that does not require users to give their credentials away to several different sites. They only give their credentials to one site, then the other sites can authenticate their users with your site without asking for a username/password. You've already seen this benefit when logging into your account here.

You could implement your own custom solution, but that eliminates the benefits of using an open standard. Using an open standard allows two things:

You can use other open source libraries to implement your own OAuth service rather than reinventing the wheel.

You won't be forcing other people to write their own custom logic for authenticating with your site. It's better to allow people a familiar OAuth interface than to force them to learn another new API.

Title: OAuth2 vs Public API


答:
In layman terms, if you are exposing an API, you will be asking the other site to pass username/password to your API so that you will verify those credentials and the user can start using the other site.

However, with OAuth the user does not give username/password or login credentials to the other site but directly to your site.

This is because it is a security breach for the other site to ask for login credentials from the user which actually belong to your site.

Title: OAuth2 vs Public API

Body:
My understanding of OAuth (2.0) is that its a software stack and protocol to allow 2+ web apps to share information about a single end user. User A is a member of Site B and Site C; Site B wants to fetch some data from Site C about User A, and this is where OAuth steps in.

So first off, if this assessment is incorrect, please begin by clarifying this for me and correcting me!

Assuming I'm on the right track, then I guess I'm not seeing the need for OAuth to begin with (!). I'm sure I'm just not seeing the "forest through the trees" here, but the way I see it, couldn't Site C just expose a public API that Site B could use to fetch the same data (sans OAuth)? If Site C required user credentials to access the data, could this public API just use HTTPS for secure transport and require username/password as a part of each API call?

Again, I'm sure I'm missing something, but I'm just not understanding why I would need OAuth when a secure, public API written and exposed by Site C seems more than capable of delivering what Site B needs regarding User A.

In general, I'm looking for a set of guidelines to go by when deciding to choose between using OAuth for my web apps or just writing my own web service ( exposing public API).

Thanks in advance!


答:
OAuth is not about exposing an API. OAuth is about authorization: Is Site B allowed to access User A's resources.

Before twitter began implementing OAuth, it used HTTP Basic auth. That meant users had to give their credentials to third party websites / services to allow them to access their data. This means that the website now has unlimited access to the users data, and the only way to 'revoke' that access, is to change your password.

OAuth solves this problem by not giving the website the users credentials, but a token. That token gives them (possibly limited) access to a users resources, without having any password. If a user want's to block this website, it only has to revoke the token, and that website / service has no access anymore.

Title: OAuth2 vs Public API