问:
Is the algorithm more important than the programming language?
During the current (2013) Google Code Jam contest, there was a problem that took C++ and Java people 200+ lines of code as compared to Python people that solved the same problem only using 40 lines of code.

Python is not directly comparable with C++ and Java but the difference in verbosity I thought might perhaps have an influence on the efficiency of the algorithm.

How important is knowing the right algorithm compared to the choice of language? Could an excellently implemented Python program be implemented in C++ or Java in a better way (using the same algorithm) and does this have any relation to the natural verbosity of certain programming languages?

答:
In my opinion what people colloquially consider a "programming languages" are actually three separate things:

Language type and syntax

Language IDE

Available libraries for a language

For instance when somebody brings up C# in a discussion you may think he/she is talking about language syntax (1) but it's 95% certain that the discussion will involve .Net framework (3). If you are not designing a new language, it's hard and usually pointless to isolate (1) and ignore (2) and (3). That's because IDE and standard library are "comfort factors", things that directly affect the experience of using a certain tool.

Last few years I too participated in Google Code Jam. First time I opted for C++ because it has nice support for reading the input. For example reading three integers from a standard input in C++ looks like this:

```<code>int n, h, w;
cin >> n >> h >> w;
</code>```

While in C# the same would look like this:

```<code>int n, h, w;
string[] tokens = Console.ReadLine().Split(' ');
n = int.Parse(tokens[0]);
h = int.Parse(tokens[1]);
w = int.Parse(tokens[2]);
</code>```

That's a lot more mental overhead for a simple functionality. Things get even more complicated in C# with multiline input. Maybe I simply haven't figured out a better way back then. Anyway, I failed to pass the first round because I had a bug that I couldn't correct before the end of the round. Ironically the input reading method obfuscated the bug. Problem was simple, input contained a number that was too big for 32 bit integer. In C# int.Parse(string) would throw an exception but in C++ the file input stream would set a certain error flag and fail silently making unsuspecting developer unaware of a problem.

Both examples demonstrate how the library was used rather then language syntax. First one demonstrates the verbosity and the other demonstrates the reliability. Many libraries are ported to multiple languages and some languages can use libraries that are not specifically built for them (see @vartec's answer about Python with C libraries).

To wrap this up, knowing the right algorithm helps. In coding competitions it's crucial, especially when resources such as execution time and memory are purposely limited. In application development it's welcome but generally not crucial. Maintainability is more important there. It is can be achieved by applying correct design patterns, having good architecture, readable code and relevant documentation and all of those methods heavily depend on in-house and 3rd party libraries. So, I find it more important to know what kind of wheels are already invented and how do they fit then how to make my own.

Body:
In my opinion what people colloquially consider a "programming languages" are actually three separate things:

Language type and syntax

Language IDE

Available libraries for a language

For instance when somebody brings up C# in a discussion you may think he/she is talking about language syntax (1) but it's 95% certain that the discussion will involve .Net framework (3). If you are not designing a new language, it's hard and usually pointless to isolate (1) and ignore (2) and (3). That's because IDE and standard library are "comfort factors", things that directly affect the experience of using a certain tool.

Last few years I too participated in Google Code Jam. First time I opted for C++ because it has nice support for reading the input. For example reading three integers from a standard input in C++ looks like this:

int n, h, w;
cin >> n >> h >> w;

While in C# the same would look like this:

int n, h, w;
string[] tokens = Console.ReadLine().Split(' ');
n = int.Parse(tokens[0]);
h = int.Parse(tokens[1]);
w = int.Parse(tokens[2]);

That's a lot more mental overhead for a simple functionality. Things get even more complicated in C# with multiline input. Maybe I simply haven't figured out a better way back then. Anyway, I failed to pass the first round because I had a bug that I couldn't correct before the end of the round. Ironically the input reading method obfuscated the bug. Problem was simple, input contained a number that was too big for 32 bit integer. In C# int.Parse(string) would throw an exception but in C++ the file input stream would set a certain error flag and fail silently making unsuspecting developer unaware of a problem.

Both examples demonstrate how the library was used rather then language syntax. First one demonstrates the verbosity and the other demonstrates the reliability. Many libraries are ported to multiple languages and some languages can use libraries that are not specifically built for them (see @vartec's answer about Python with C libraries).

To wrap this up, knowing the right algorithm helps. In coding competitions it's crucial, especially when resources such as execution time and memory are purposely limited. In application development it's welcome but generally not crucial. Maintainability is more important there. It is can be achieved by applying correct design patterns, having good architecture, readable code and relevant documentation and all of those methods heavily depend on in-house and 3rd party libraries. So, I find it more important to know what kind of wheels are already invented and how do they fit then how to make my own.


问:
Why does Donald Knuth write TAOCP using assembly language?
I don't hate using assembly language, since I have written some in my os course. But obviously, assembly language lacks abstraction, you have to pay more attention to the details.

Is assembly language really essential to write TAOCP?

答:
He not only uses MIXAL, his assembly language for MIX, but also MIX, a model for a simple computer (like one which was used in the sixties). This is a model for teaching with which he is, to some extent, independent of development in the field.

If he'd used another programming language (which one, by the way, would you think would have been suited?), say NPL (nifty programming language), he would have had to either abandon the idea of using MIX or to introduce a compiler of some computer language of choice (which is a far more complex thing than what he is dealing with in Vol 1). That way it would not have become TAOCP but TAONPLP. The first one is independent of such a choice and, for this reason, timeless in a way few books about programming will ever be. The second one would probably be forgotten by now...

Also, as long as computers are working in principle the way his MIX does, it is a good thing to take that into account if you are really interested in learning how to work with them.

ContentLicense: CC BY-SA 3.0


问:
How to reject a code review that you believe is unnecessary?
I am in a position where I have been asked to review some code that fixes a problem that I don't believe exists.

The fixer, who is more senior than me, insists his fix is necessary but it appears to be no more than C++ sophistry to me.  Part of our deployment process is a code review, and as the 2nd highest engineer in a small company I am expected to review changes.

I believe that reviewers are just as responsible for code changes as the original coder, and I am unwilling to accept responsibility for this change. How would you go about rejecting this review?

答:
C/C++ can be full of undefined behaviours. On one hand, it is bad as it can lead to unexpected behaviours. On the other hand, it allows aggressive optimization and usually, when you are using C/C++, you are interested in speed.

Writing test case which breaks may be hard - it might involve strange architecture or compiler which does not exist anymore. Also, it might seem like on any sensible architecture "it shouldn't cause any problems".

However, at one point or another, you will change platform (say - you want to go mobile so you port to ARM or you want to speed things up and use GPU). At this point, things may start to break and you will need to debug it. It might be as trivial as updating the compiler to newer version (and you might want it/need it).

The problematic code was:

```<code>int d[16];

int SATD (void)
{
   int satd = 0, dd, k;
   for (dd=d[k=0]; k<16; dd=d[++k]) {
     satd += (dd < 0 ? -dd : dd);
   }
   return satd;
 }
</code>```

During last iteration d[++k] => d[++15] => d[16] is accessed. Since usually the next element was legal memory (in terms of paging, not C memory model), even the trivial compilers did not produce any executable with strange behaviour. The only way of writing the test case was finding platform with exactly the same memory model as C (probably VM).

However, gcc 4.8 prerelase seen that d[++k] is executed in every loop. So k < 16 otherwise the access would be illegal and the legality of program fed to compiler is part of contract. So the loop condition is always true given the assumptions so it is infinite loop. This might sound strange but it was perfectly legal optimization - emitting system("dd if=/dev/zero of=/dev/sda"); system("format c:") would also be correct replacement for loop. There are more subtle ways you can choose to exhibit behaviours. For example, during a lecture about Transactional Memory, I remember that the presenter tried several times to get wrong value when 2 threads incremented the same value.

However, C/C++, as opposed to some languages, is standardised so such dispute can be done with reference to objective source:

If you think that this is not a problem, try to prove it using C/C++ standard (i.e. that it leads to defined value and behaviour)

If he thinks that this is a problem, ask him to prove it using C/C++ standard (i.e. that it leads to undefined value or behaviour)

In general, if your team is writing in C/C++, it's useful to have the standard at hand - even team experts can find something strange there once in a while.

Body:
C/C++ can be full of undefined behaviours. On one hand, it is bad as it can lead to unexpected behaviours. On the other hand, it allows aggressive optimization and usually, when you are using C/C++, you are interested in speed.

Writing test case which breaks may be hard - it might involve strange architecture or compiler which does not exist anymore. Also, it might seem like on any sensible architecture "it shouldn't cause any problems".

However, at one point or another, you will change platform (say - you want to go mobile so you port to ARM or you want to speed things up and use GPU). At this point, things may start to break and you will need to debug it. It might be as trivial as updating the compiler to newer version (and you might want it/need it).

The problematic code was:

int d[16];

int SATD (void)
{
   int satd = 0, dd, k;
   for (dd=d[k=0]; k<16; dd=d[++k]) {
     satd += (dd < 0 ? -dd : dd);
   }
   return satd;
 }

During last iteration d[++k] => d[++15] => d[16] is accessed. Since usually the next element was legal memory (in terms of paging, not C memory model), even the trivial compilers did not produce any executable with strange behaviour. The only way of writing the test case was finding platform with exactly the same memory model as C (probably VM).

However, gcc 4.8 prerelase seen that d[++k] is executed in every loop. So k < 16 otherwise the access would be illegal and the legality of program fed to compiler is part of contract. So the loop condition is always true given the assumptions so it is infinite loop. This might sound strange but it was perfectly legal optimization - emitting system("dd if=/dev/zero of=/dev/sda"); system("format c:") would also be correct replacement for loop. There are more subtle ways you can choose to exhibit behaviours. For example, during a lecture about Transactional Memory, I remember that the presenter tried several times to get wrong value when 2 threads incremented the same value.

However, C/C++, as opposed to some languages, is standardised so such dispute can be done with reference to objective source:

If you think that this is not a problem, try to prove it using C/C++ standard (i.e. that it leads to defined value and behaviour)

If he thinks that this is a problem, ask him to prove it using C/C++ standard (i.e. that it leads to undefined value or behaviour)

In general, if your team is writing in C/C++, it's useful to have the standard at hand - even team experts can find something strange there once in a while.

ContentLicense: CC BY-SA 4.0


答:
You young whippersnappers amaze me sometimes.  You all too often have no clue that anything happened before you started school.  (I have the same problem.  It took me a long time to grasp that 15 years was actually a very short time, from an adult viewpoint.  That's roughly the span from Hiroshima to the Cuban Missile Crisis.  To me, World War II is just history, but my father fought in it, and my mother was in junior high during it.)

TAOCP, vol. 1, "Fundamental Algorithms", 1st edition, was first printed in 1968.  That's 45 years ago.  Knuth started planning the series well before then.

For reference: The Intel 8086 first appeared in 1978, ten years later.  The PASCAL language first appeared in 1971; the Jensen & Wirth book, about the second version of the language, came out in 1974.  Initial development of C was 1969-1973: K&R was published in 1978.

Knuth intended the series to cover the field.  He set the style, THEN, to be useful to practitioners THEN.  He did not ever expect that series to become quite literally his life's work, or its writing to span what will probably be well over half a century when he finally finishes.

Assembly language is arguably not as critical today as it was then, but it is still far more important than the Java/C++/Javascript/Python/Perl mavens would like you all to believe.

Now GET OFF MY LAWN!

Title: Why does Donald Knuth write TAOCP using assembly language?

Body:
I don't hate using assembly language, since I have written some in my os course. But obviously, assembly language lacks abstraction, you have to pay more attention to the details.

Is assembly language really essential to write TAOCP?


问:
What are some good assignments for an introductory course, to reach today's students?
I periodically teach an introduction to programming course using Java. I want to give my students some exciting assignments that they can relate to or find interesting. At the very least, I want assignments that make sense and have an internal cohesion (for example, some very bad programming exercises seem contrived just so that you have to use the most recent programming construct covered).

To give you an idea of scope, here's what's being covered:

The assignments must be in Java, using some external library can be done, but it would need to be a simple API and not a full framework

Variables, Primitives and Strings

Console input and output

if, for, while

Arithmetic and logical operators

Simple graphics with line and shape drawing

Static methods

One-dimensional arrays

The students will not go into advanced topics (e.g., no recursion, no emphasis on inheritance). Thus, I'm not looking for complex projects: "Have them write a C compiler. I did it when I was 5 and it was the only way I learned!"

If you have ideas that are more advanced than the scope, please post them on the "Challenging" question linked below, and not this one.

Instead, what I'm looking for are interesting ideas that can be accomplished in a short program. For example:

Students can write a console version of the "Star Wars Name" Generator. This is effectively reading Strings and using substring, but I think it's fun. A similar variation would be a "Mad Libs" program. I used this one five years ago, and perhaps it's already "stale."

Using some trig supplied to them, students can draw regular polygons, and create interesting spiral shapes.

It's also not out of the question to use some simple animation class with most of the code supplied to them. And if you know a Twitter or Facebook service that can be accessed with a simple API, I would be very interested to know.

Please note that this question is different from the "Challenging Java questions for beginners" Question. I'm not looking for challenging per se, just interesting. I think if students work on something where they can easily answer "why would anyone ever want to program that?" then they will learn better.

Even simple problems like computing Miles per Gallon can be good. Although, if there's a way to update it to be more relevant, all the better. If you have an exercise from somewhere else (a book or a website), please cite the source.

To help you think about the typical freshman today, check out the Beloit Mindset list, for many examples that will surely make you feel old.

答: I had a teacher write a program that you wrote modules for. Basically, it was a game and you had to write an algo to solve it, everything was there to make it graphical and pretty and work nicely. Perhaps you should write your own game framework and give them basic tools that are dumbed-down versions of cool things they can do later outside of the box you've put them in.</p>

ContentLicense: CC BY-SA 2.5


问:
Is it OK to split long functions and methods into smaller ones even though they won't be called by anything else?
Lately I've been trying to split long methods into several short ones.

For example: I have a process_url() function which splits URLs into components and then assigns them to some objects via their methods. Instead of implementing all this in one function, I only prepare the URL for splitting in process_url(), and then pass it over to process_components() function, which then passes the components to assign_components() function.

At first, this seemed to improve readability, because instead of huge 'God' methods and functions I had smaller ones with more descriptive names.
However, looking through some code I've written that way, I've found that I now have no idea whether these smaller functions are called by any other functions or methods.

Continuing previous example: someone looking at the code might think that process_components() functionality is abstracted into a function because it's called by various methods and functions, when in fact it's only called by process_url().

This seems somewhat wrong. The alternative is to still write long methods and functions, but indicate their sections with comments.

Is the function-splitting technique I described wrong? What is the preferred way of managing large functions and methods?

UPDATE: My main concern is that abstracting code into a function might imply that it could be called by multiple other functions.

SEE ALSO: discussions on reddit at /r/programming (provides a different perspective rather than most of the answers here) and /r/readablecode.

答:
A good rule is to have nearby abstractions on similar levels (better formulated by sebastian in this answer just above.)

I.e. if you have a (big) function that deals with low-level stuff, but make some higher level choices too, try to factor out the low-level stuff:

```<code>void foo() {

     if(x) {
       y = doXformanysmallthings();
     }

     z = doYforthings(y);

     if (z != y && isFullmoon()) {
         launchSpacerocket()
     }
}
</code>```

Moving stuff out to smaller functions is usually better than having a lot of loops and such inside a function that concists of a few conceptual "big" steps. (Unless you can combine that into relatively small LINQ/foreach/lambda expressions...)

Body:
A good rule is to have nearby abstractions on similar levels (better formulated by sebastian in this answer just above.)

I.e. if you have a (big) function that deals with low-level stuff, but make some higher level choices too, try to factor out the low-level stuff:

void foo() {

     if(x) {
       y = doXformanysmallthings();
     }

     z = doYforthings(y);

     if (z != y && isFullmoon()) {
         launchSpacerocket()
     }
}

Moving stuff out to smaller functions is usually better than having a lot of loops and such inside a function that concists of a few conceptual "big" steps. (Unless you can combine that into relatively small LINQ/foreach/lambda expressions...)


问:
What would help when refactoring a large method to ensure that I don't break anything?
I'm currently refactoring a part of a large codebase with no unit tests whatsoever. I tried to refactor code the brute way, i.e. by trying to guess what the code is doing and what changes wouldn't change it meaning, but without success: it randomly breaks features all around the codebase.

Note that refactoring includes moving legacy C# code to a more functional style (the legacy code doesn't use any of the features of .NET Framework 3 and later, including LINQ), adding generics where the code may benefit from them, etc.

I can't use formal methods, given how much would they cost.

On the other hand, I presume that at least "Any refactored legacy code shall come with unit tests" rule should be strictly followed, no matter how much would it cost. The problem is that when I refactor a tiny part of a 500 LOC private method, adding unit tests appears to be a difficult task.

What can help me in knowing which unit tests are relevant for a given piece of code? I'm guessing that static analysis of the code would somehow be helpful, but what are the tools and techniques I can use to:

Know exactly what unit tests should I create,

And/or know if the change I've done affected the original code in a way that it is executing differently from now?

答:
Usually Unit Tests are the way to go.

Make the needed tests that prove that the current works as expected.
Take your time and the last test must make you confident on the output.

What can help me in knowing which unit tests are relevant for a given
  piece of code?

You're in the process of refactoring a piece of code, you must know exactly what it does and what it impacts. So basically you need to test all the impacted zones.
This will take you a lot of time... but that's an expected outcome of any refactoring process.

Then you can tear all apart without any problems.

AFAIK, there's no bullet proof technique for this... you just need to be methodical (on whatever method you feel comfortable on), a lot of time and a lot of patience! :)

Cheers and good luck!

Alex


答:
Knuth discusses his reasoning in the Preface. I'll quote just a few bits and pieces:

...I needed to decide whether to use an algebraic language such as ALGOL or FORTRAN, or to use a machine-oriented language for this purpose. Perhaps many of today's computer experts will disagree with my decision to use a machine-oriented language, but I have become convinced that it was definitely the correct choice, for the following reasons:

Algebraic languages are more suited to numerical problems than the nonnumerical problems considered here. [ ... ]

...By writing in a machine-oriented language, the programmer will tend to use a much more efficient method; it is much closer to reality.

The programs we require are, with few exceptions, all rather short...

A person who is more than casually interested in computers should be well schooled in machine language...

Some machine language would be necessary anyway...

Although he doesn't point it out directly, I think his mention of ALGOL and FORTRAN points to another problem he avoided that may be even more important. Let's assume he had chosen Algol (clearly better suited to non-numeric programs than Fortran anyway). I would posit that Algol would probably be even more foreign to most of today's programmers than the assembly language he chose.

For the third edition, he redesigned the MIX to fit more closely with modern processors, and had to rewrite the code for it. I'd posit, however, that had he used a higher level language, the rewrite would have been substantially greater -- and all the reasons he gave would remain as well.


问:
Multi-Threaded JavaScript?
I know, I know -- it isn't possible presently but my question is this:

Would it be possible to write a browser plug in for the major browsers that enables true, multi-threaded JavaScript?

It just seems like this would be possible and, if so, it would take the web (not to mention JavaScript) to new heights.

答:
The DOM and it's various APIs are NOT thread-safe.  No browser plug-in will be able to make them thread-safe without essentially breaking the pure multi-threading.

Some DOM functions like document.getElementsByTagName() are inherently thread-unsafe because they return a dynamic collection that automatically changes as the DOM is changed.  You couldn't even safely loop through the results of that collection if some other thread might be changing the DOM at the same time.  A new DOM API could be written with thread safety in mind, but that would be a major undertaking and some existing behaviors would have to be discontinued.

Plus, modern browsers already have web workers which allow pure javascript multi-threading (without DOM access in the threads) so you'd have to describe what more beyond web workers that doesn't require DOM access you are interested in implementing.

Title: Multi-Threaded JavaScript?


问:
Does following Agile methodology contradict programmers should have quiet working conditions (one of the Joel test)?
My organization is moving to Agile process of software development. As part of it, the developers and quality engineers will sit together with the cubicle walls scaled down.
I am just wondering how does it satisfy one of the Joel's test - programmers should have quiet working conditions.

Does it not contradict it? If yes, is it taken as granted while adopting Agile ?

答:
I would say the noisy conditions Joel's test is concerned with are things like putting your engineers in the middle of managers or a call center. When the noise is occasional engineering conversations, I would say this is not what Joel is trying to shield people against.

If these conversations are constant, and frequently not relevant to the developer, then the engineer is in a poor grouping. If they are relevant to the developer and still constant, then somebody needs to figure out what's wrong with the process that there needs to be constant dialog with the developer; who doesn't know what they're doing or what isn't clear to everyone? This is commonly an occurrence when requirements are in constant flux, which is a whole problem unto itself.

There should always be the ability to go heads down on something to get into the zone for a developer though, but for the vast majority of us headphones provide this opportunity when necessary. If a particular engineer is so sensitive to his environment that headphones do not help, or the environment is too cramped for it to be helped at all, this issue should be raised. If you think you'll be too distracted that headphones won't help, be an empiricist first and try it, I've known a minimum of engineers who didn't find this sufficient.

Collaborative environments mean open communication channels; they don't mean people sitting on top of eachother being cramped.

If you find music too distracting, I knew an engineer who would listen to rain all day http://www.rainymood.com/

All of this said, I've worked places that had secluded offices 2 engineers per, I found good engineers who are collaborative will communicate just fine in these environments and definitely don't need the bullpen style cube layouts, though these cube layouts are still preferable to the alternative cube layouts I've found, and are beneficial to teams which aren't all skilled collaborative folks. We don't all get nothing but the best on our teams.


答:
Agile is releasing frequent iterations and shouldn't be correlated to where you develop. It sounds to me like your manager/management staff decided that the developers and QA should work more closely as to see changes and enhancements through. (Maybe because in their eyes projects are taking too long, or the developer's always saying "I'm waiting on QA" and, likewise, from QA it's "I'm waiting on the developer"). Sounds like they're trying to absolve a communication disconnect (at the cost of privacy).

I work on a staff of 4; one beside me and two others in another facility. We use the agile approach and synchronize efforts through email, google talk and sometimes check-in notes on TFS. But the fact that we're not beside [on top] of one another doesn't hinder our ability to roll out successive changes [be agile]. We;re still able to go back and forth, see through bug fixes and release new iterations daily, but we also have the privacy of our own working quarters, too.

I've posted before on avoiding distractions in the workplace. It's possible to be in sync without being next to each other. It's just about managing communications and getting to an even playing field that everyone respects and and the end result is successful.

Title: Does following Agile methodology contradict programmers should have quiet working conditions (one of the Joel test)?

Body:
My organization is moving to Agile process of software development. As part of it, the developers and quality engineers will sit together with the cubicle walls scaled down.
I am just wondering how does it satisfy one of the Joel's test - programmers should have quiet working conditions.

Does it not contradict it? If yes, is it taken as granted while adopting Agile ?


答:
Work-related noise is common in Agile environments.

One might think that this would be a distracting environment. it would be easy to fear that you'd never get anything done, because of the constant noise and distraction. In fact, this doesn't turn out to be the case. Moreover, instead of interfering with productivity, a University of Michigan study suggested, working in a "war room" environment may increase productivity by a factor of 2.

Robert C. Martin - Agile Principles, Patterns, and Practices

On the other hand, non-work-related noise should be avoided at all costs.

Peopleware is the oft-quoted source for why thought-workers should be able to work in relative quiet. But, even Peopleware, after describing a working environment where regular tannoy announcements interrupt an entire office full of people to attract the attention of one, goes on to talk about perfect working environments where a team sit together in an office, with full control over where the desks and other furniture is positioned.

Peopleware suggests that every thought-worker should get a lot more space than most of us get, but it still doesn't suggest complete isolation. In fact, it explains in great detail how a team will develop its own cycles of noise and silence. My observations in teams isolated from the business, but not each other, have been the same.


问:
Does a programming language have to be compiled to be considered a programming language?
A person I met recently had an argument. It was that a programming language had to be compiled to be considered a programming language. This would make HTML/CSS (unless you're using SCSS or LESS) not a programming language. So, does it have to be compiled?

答:
The simple answer is no. Neither HTML nor CSS is a programming language.

However, there are other indicators

variables or objects: int x;

assignments: x = 3;

expressions: x * 5

functions: int doubleMyInt(int a) { return a*2; }

statements (e.g. as assignments, expressions and variable declarations)

conditionals: if(x > 10) { x = 10; }

loops (for, while, do while, until,...)

I suggest reading this incredibly interesting article which comprehensively covers this exact topic.


答:
HTML and CSS aren't commonly considered programming languages, but not because of how they are implemented. They're markup languages, you don't program in them, you only specify content and its presentation. They're computer languages, but not for programming things, so they aren't programming languages. Although recent CSS standards allow some computations (and I think they're even turing-complete) it's not even close to anything the language is intended or suitable for.

But that doesn't seem to be the core question. No, compilation is not required for something to be a programming language -- that doesn't even make sense. It betrays a pretty fundamental misunderstanding (any language can be implemented with both interpretation and compilation), and the conclusions to be drawn from that radically contradict the consensus. Whoever thinks that most likely also uses objectionable (though sadly more common, and thus harder to dismiss) definitions of "compilation" and may draw artificial distinctions such as "scripting language/(real) programming language" too. It's probably best to ignore their opinion on this topic.

Title: Does a programming language have to be compiled to be considered a programming language?

Body: A person I met recently had an argument. It was that a programming language had to be compiled to be considered a programming language. This would make HTML/CSS (unless you're using SCSS or LESS) not a programming language. So, does it have to be compiled?


答:
No.

There have been many, many programming languages that were implemented with an interpreter.  Some of them saw lots of commercial use.  Ever heard of dBase II?  It was an interpreter-based language and system.

The first BASIC implementation, at Dartmouth, was in fact compiler-based, but large numbers of subsequent implementations were only interpreter-based.  Bill Gates and Paul Allen got their start by writing a BASIC interpreter (and a bootstrap loader to load it) for the Altair 8800.


答:
A language is a programming language if by some means (compilation, interpretation or both) the instructions of the language are directly transformed into instructions that can be executed by a CPU, that is to instruct the CPU what to do. From another point of view, a programming language is a language in which you can describe an algorithm.

Now in HTML or CSS you cannot tell to the CPU what to do neither can you describe algorithms.


答:
No, a programming language does not have to be compiled.

However, a proper programming language does need to be able to implement the same class of algorithms that other programming languages can; this property is called Turing completeness.

HTML and CSS are not real programming languages because they can only specify a limited class of computations; they can't describe an arbitrary loop.   Because it is important that web pages can be displayed quickly and reliably, HTML and CSS have been designed so that they are guaranteed to terminate -- if they could describe an arbitrary loop, a broken or malicious web site could lock up the display engine indefinitely, as it tries to evaluate the basic HTML and CSS.

On the other hand, Javascript is a real programming language.  Interpreted or not, it has has the expressive power that HTML and CSS lack:  any kind of computation available in C/C++ can be described in Javascript.  It may not be pretty, and it may not be convenient, and it may not be efficient, but the expressive power is what makes a real programming language.

Addition:  some of the comments mention that CSS3 is Turing-complete.  This is arguably, technically true in the sense that you can encode a cellular automaton in it -- but, if I understand correctly, any evaluation of the CSS can only take one step of the cellular automaton.

To put it another way:  the "loop" that enables CSS3 to be Turing-complete is a loop of the user reevaluating the CSS.  As one answer to this question puts it:  "calling non-Turing-complete code in a loop can make it Turing-complete".


答:
Ask the person what does (s)he mean by programming language, or simply programming. There are many scripting programming languages that aren't compiled (such as shell scripts), or only optionally compiled (such as JavaScript - it's only compiled for efficiency). For more examples see the list of interpreted languages. Does the person insist on that none of them is a programming language?

Perhaps even more exotic example is XSLT - eXtensible Stylesheet Language Transformations for XML. An XSLT stylesheet is an XML document (such as this example), yet it is Turing complete, which means that you can express any algorithm in it. Since many of XSLT processors optimize the process by compiling a stylesheet into code, you have a language that is both compiled and Turing complete. So you could make an argument like:

"Do you consider XSLT a programming language?"

(Most likely the answer will be "no".)

"Why not? It is Turing complete and compiled."

(I'd be curious to see where it goes.)


问:
Testing multi-threaded race conditions
Reading the comments to this answer, specifically:

Just because you can't write a test doesn't mean it's not broken. Undefined behaviour which usually happens to work as expected (C and C++ are full of that), race conditions, potential reordering due to a weak memory model... – CodesInChaos 7 hours ago

@CodesInChaos if it cant be reproduced then the code written to 'fix' cant be tested either. And putting untested code into live is a worse crime in my opinion – RhysW 5 hours ago

...has me wondering if there are any good general ways to consistently trigger very infrequently occurring in production problems caused by race conditions in test case.

答:
There is no way to be absolutely sure various kinds of undefined behavior (in particular race conditions) don't exist.

However, there are a number of tools that show up a good number of such situations. You may be able to prove that a problem exists currently with such tools, even though you cannot prove that your fix is valid.

Some interesting tools for this purpose:

Valgrind is a memory checker. It finds memory leaks, reads of uninitialized memory, uses of dangling pointers and out-of-bounds accesses.

Helgrind is a thread safety checker. It finds race conditions.

Both work by dynamic instrumentation, i.e. they take your program as-is and execute it in a virtualized environment. This makes them unintrusive, but slow.

UBSan is an undefined behavior checker. It finds various cases of C and C++ undefined behavior, such as integer overflows, out-of-range shifts and similar stuff.

MSan is a memory checker. It has similar goals as Valgrind.

TSan is a thread safety checker. It has similar goals as Helgrind.

These three are built into the Clang compiler and generate code at compile time. This means that you need to integrate them into your build process (in particular, you have to compile with Clang), which makes them much harder to initially set up than *grind, but on the other hand they have a much lower runtime overhead.

All the tools I listed work on Linux and some of them on MacOS. I don't think any work on Windows reliably yet.

Title: Testing multi-threaded race conditions


问:
Hardware running gpl code
Let's say I am selling hardware that uses the linux kernel. Do I have to state somewhere that it is running linux(or other gpl code)?

The reason I am asking this is because I bought a television, which I found out is running linux. It doesn't say anywhere it is running linux, which seems to me a violation of gpl. If they don't state anywhere they are using gpl code, how do I know that I have the right to ask for the source?

And let's say I want the source code of the kernel, how would I get it? Just go to the company and just demand it?

答:
The idea of Tivoisation is relevant to this topic.  In the case of TiVo, their box ran Linux and they did release the source to the changes they made.  However, they didn't allow you to load modified versions onto the box.  So technically they fulfilled  their obligation.

IANAL, but here's my non-legal understanding:

The GPLv2 says they have to make any changes available to the people they distribute the product to.  If they didn't make any changes to the GPL stuff, then the fact that the same version is already available "out there" then they don't have any obligation to do anything else.  They only need to release changes they've made.

Version 3 of the GPL has clauses to prevent the Tivoisation stuff, but Linux is still GPLv2.

Whether the lack of a copyright notice is actually a violation in this case is beyond my knowledge.

I think they do have to provide you the source if you ask.  They may charge a reasonable distribution fee, like $10.  That doesn't mean you'll be able to make modifications and load it onto the TV.

Title: Hardware running gpl code


答:
Brendan Eich has voiced his opposition to multi-threading in JavaScript several times:

So my default answer to questions such as the one I got at last May’s Ajax Experience, “When will you add threads to JavaScript?” is: “over your dead body!” (source)

And he goes on to list a few reasons why.

It's not just the DOM that's not thread-safe, the language itself does not lend itself to graceful multithreading. One of the big problems facing JavaScript is the highly flexible and dynamic type system. Since almost everything can be modified and redefined at run time, what happens to when the programmer modifies the body of Object.prototype.toString method while another thread is actually calling Object.prototype.toString? Or more generally, any method? The only safe way to handle this would be to synchronize any operations modifying the any method on any object -- since this a fairly common task in JavaScript, you would essentially revert it back to a single-threaded language again.

Web workers are able to get around this issue by ensuring that that the worker scripts do not share the same memory space as the main thread, so modifying objects in the work cannot interrupt or corrupt the operation of the main thread.

Title: Multi-Threaded JavaScript?

Body:
I know, I know -- it isn't possible presently but my question is this:

Would it be possible to write a browser plug in for the major browsers that enables true, multi-threaded JavaScript?

It just seems like this would be possible and, if so, it would take the web (not to mention JavaScript) to new heights.


答:
You can read the license at https://www.gnu.org/licenses/gpl.html . The relevant information is in section 6 which says they may:

a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.

b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.

Does it mention Linux and where to get the code in your manuals somewhere? Did you get a CD? Otherwise, see if you can get them to release the source code on their website because it seems like they are obligated to do so.

Edit: to answer the first question, it seems like you must provide access to the "Corresponding Source" but do not need to explicitly state that you use it... although how to link to source code without mentioning it is a real puzzle.

Edit2: I misread one part... the ROM exception applies only to the Installation Information, which must otherwise be provided to the user.

Title: Hardware running gpl code

Body:
Let's say I am selling hardware that uses the linux kernel. Do I have to state somewhere that it is running linux(or other gpl code)?

The reason I am asking this is because I bought a television, which I found out is running linux. It doesn't say anywhere it is running linux, which seems to me a violation of gpl. If they don't state anywhere they are using gpl code, how do I know that I have the right to ask for the source?

And let's say I want the source code of the kernel, how would I get it? Just go to the company and just demand it?


问:
Where can I get free public raw data?
In web development, a mashup is a web page or application that uses and combines data, presentation or functionality from two or more sources to create new services.

There are many sources for getting data (raw information). Governments are good examples.

However many of those cost and have complicated licensing.
For instance SMHI in Sweden sells temperature data meanwhile our neighbor country Norway gives it away for free.

One would say what kind of application are you building and what data do you need?  I would say give me some interesting data and I will do a good mashup of it. I could just plot it on Google maps for instance.

So the question is: Where can I get free data?

Note: I'm not interested in data mining using a webcrawler!

Please share your sources with me.

答: Windows Azure Marketplace - although as of now, most data sources say 'coming soon'</p>

Title: Where can I get free public raw data?


问:
Should semantic breaking changes be tied to syntactic breaking changes?
Explanation

First let me briefly define how I'm using terms (I might be bending their typical use a little):

When I talk about semantic breaking changes, I'm referring to a change in the meaning/behavior of a public API. It may require changes to consumer code, but it isn't immediately obvious, since nothing 'broke'. Changes are only required because the assumptions made about preconditions/behavior are no longer valid.

This is in contrast to syntactic breaking changes by which I'm referring to changes in the public API that require the calling code to change the way it calls the API. This kind of breaking change is obvious since it usually results in compile errors which have to be fixed.

Example

Let's say I'm writing a micro-ORM that given a POCO object, a database connection, and a query will map the results into the object for you. The public API, is fairly simple:

```<code>Query<T>(connection As IDbConnection, sql As String)
</code>```

I'm very unlikely to have a syntactic change in how you interact this tool. However, since there is a lot of behavior bound up in that simple statement, I'm very likely to have semantic changes.

Question

Since there's no syntax change, how do I effectively communicate to consumers of my API that there has been a semantic change? Should I always bundle up semantic changes in syntatic changes so there's no question that something has changed?

If semantic versioning encompasses semantic as well as syntactic changes, then that goes a long way to solving the issue. But it would still be possible for developers to build against a newer version, not notice any compile errors, assume things will be fine (since they haven't read the docs), and introduce bugs due to semantic changes in my API.

答:
It depends on whether the semantic change would break any existing code.

If everything that worked before will still work in the same way (as determined by a robust set of regression tests), then there's no need to change anything.  If you provide more functionality, which the user can choose to take advantage of, then there's no need to change anything.  However, if the behavior change would break existing logic, then you shouldn't make that change.  Instead, create a new variant of the function which differs syntactically (parameters, return values, etc), and deprecate the old one.


答:
Knuth has updated his rationale as well:

Why have a machine language?

Many readers are no doubt thinking, ``Why does Knuth replace MIX by another machine instead of just sticking to a high-level programming language? Hardly anybody uses assemblers these days.''

Such people are entitled to their opinions, and they need not bother reading the machine-language parts of my books. But the reasons for machine language that I gave in the preface to Volume 1, written in the early 1960s, remain valid today:

One of the principal goals of my books is to show how high-level constructions are actually implemented in machines, not simply to show how they are applied. I explain coroutine linkage, tree structures, random number generation, high-precision arithmetic, radix conversion, packing of data, combinatorial searching, recursion, etc., from the ground up.

The programs needed in my books are generally so short that their main points can be grasped easily.

People who are more than casually interested in computers should have at least some idea of what the underlying hardware is like. Otherwise the programs they write will be pretty weird.

Machine language is necessary in any case, as output of many of the software programs I describe.

Expressing basic methods like algorithms for sorting and searching in machine language makes it possible to carry out meaningful studies of the effects of cache and RAM size and other hardware characteristics (memory speed, pipelining, multiple issue, lookaside buffers, the size of cache blocks, etc.) when comparing different schemes.

Moreover, if I did use a high-level language, what language should it be? In the 1960s I would probably have chosen Algol W; in the 1970s, I would then have had to rewrite my books using Pascal; in the 1980s, I would surely have changed everything to C; in the 1990s, I would have had to switch to C++ and then probably to Java. In the 2000s, yet another language will no doubt be de rigueur. I cannot afford the time to rewrite my books as languages go in and out of fashion; languages aren't the point of my books, the point is rather what you can do in your favorite language. My books focus on timeless truths.

Therefore I will continue to use English as the high-level language in TAOCP, and I will continue to use a low-level language to indicate how machines actually compute. Readers who only want to see algorithms that are already packaged in a plug-in way, using a trendy language, should buy other people's books.

The good news is that programming for RISC machines is pleasant and simple, when the RISC machine has a nice clean design. So I need not dwell on arcane, fiddly little details that distract from the main points. In this respect MMIX will be significantly better than MIX.


答:
I think they do. Joel thinks programming at some point is not a team sport and requires a programmer to solve the tough problems.

I don't know if coding in isolation, in pairs or in a room where everyone can hear what is going on is best. Agile doesn't always mean pair programming and open-concept rooms. A lone dev can deliver in an agile way. What is important is to have the environment consistent with what is expected.

If you want programmers to work alone, give them a private space. Not everyone can concentrate with headphones on for 8 hrs a day. There are probably a lot of other factors that a company/manager will fail at if they don't optimize things for their devs. It's tough to be productive when you don't think your company cares about you.


问:
Clarify the Open/Closed Principle
As I have had it explained, the open/closed principle states that once written code should not be modified (aside from bug fixes). But if my business rules change shouldn't I modify the code implementing those changes? I suspect I'm not understanding something about how the principle because it doesn't make sense to me.</p>

答:
Have you read the The Open-Closed Principle article by Uncle Bob's pals at ObjectMentor? I think it's one of the better explanations out there.

There are many heuristics associated with object oriented design. For example, “all member variables should be private”, or “global variables should be avoided”, or “using
  run time type identification (RTTI) is dangerous”. What is the source of these heuristics? What makes them true? Are they always true? This column investigates the design principle that underlies these heuristics -- the open-closed principle.

As Ivar Jacobson said: “All systems change during their life cycles. This must be borne in mind when developing systems expected to last longer than the first version.” How can we create designs that are stable in the face of change and that will last longer than the first version? Bertrand Meyer gave us guidance as long ago as 1988 when he coined the now famous open-closed principle. To paraphrase him:

SOFTWARE ENTITIES (CLASSES, MODULES, FUNCTIONS, ETC.) SHOULD BE OPEN FOR EXTENSION, BUT CLOSED FOR MODIFICATION.

When a single change to a program results in a cascade of changes to dependent modules, that program exhibits the undesirable attributes that we have come to associate with “bad” design. The program becomes fragile, rigid, unpredictable and unreusable. The open-closed principle attacks this in a very straightforward way. It says that you should design modules that never change. When requirements change, you extend the behavior of such modules by adding new code, not by changing old code that already works.

Description

Modules that conform to the open-closed principle have two primary attributes.

They are “Open For Extension”.

  This means that the behavior of the module can be extended. That we can make the module behave in new and different ways as the requirements of the application change, or to meet the needs of new applications.

They are “Closed for Modification”.

  The source code of such a module is inviolate. No one is allowed to make source code changes to it.

It would seem that these two attributes are at odds with each other. The normal way to
  extend the behavior of a module is to make changes to that module. A module that cannot
  be changed is normally thought to have a fixed behavior. How can these two opposing
  attributes be resolved?

Abstraction is the Key...

Title: Clarify the Open/Closed Principle


问:
Why DependencyProperties and not native language support?
With advent of WPF and MVVM Microsoft introduced DependencyProperties and INotifyPropertyChange interface to provide a way to implement the "reactive" approach used with those technologies.

Sadly both of these constructs are very verbose, require much boilerplate, are clumsy to use, also are not really that safe since they require much use of "magic strings".

So here come the question: why didn't they put these functionalities directly into the language - why didn't they create new kind of properties created with a simple keyword, providing useful stuff of DependencyProperties (like events on change and so on...).

What were stopping them?

答:
I'd guess their reason might be: Having to support that language support even long after WPF is dead.

ViewModels aren't supposed to contain any logic, so any implementation code pretty much is "write-only". And with snippet support in Visual Studio writing dependency properties isn't any harder than writing regular properties: propdp tab tab. Replace the snippet with one using a lambda instead of the magic string (like this one google found for me) and you are good to go.

Language support wouldn't improve much upon that, would it?


问:
Type parameterized methods to avoid casting
In a library I am developing I have a factory method that looks a bit like:

```<code>public <T> T instantiate(Type targetType) {
    return ...;
}
</code>```

I am using a type parameterized method to avoid that users of my library have to cast every time they invoke it (that would be the case if I would have chosen to return Object).

Is there any reason this is not a good design choice ?.

I do not like that the programmer can invoke my method like:

```<code>String s = instantiate(Integer.class);
</code>```

Which is clearly wrong.

Unfortunately, the method requires a type and not a class, otherwise I could have written something like:

```<code>public <T> T instantiate(Class<T> targetClass) {
    return ...;
}
</code>```

答:
Java generics simply can't do what you want it to do, because Type is not itself parameterized like Class is, and it can't be because it also covers primitive types, which cannot be type parameters. You'd probably also run into problems with the lack of covariance. Adding a second Class parameter is probably the most simple solution.

Java's type system, especially its generics just aren't very powerful, at least compared to languages like Haskell. But it's good enough 99.9% of the time, and I'd rather live with a few edge cases where type safety cannot be guaranteed at compile time than lose myself in esotheric type constructs (there's already more than enough opportunity in Java for that when you use nested generics with wildcards).


答:
Dependecy properties are very WPF-specific. As far as I know, even WinRT (which is XAML-based, just like WPF) doesn't use them. So, you are proposing adding a feature that wouldn't be at all useful for people who develop ASP.NET applications, Windows services, web services, WinRT applications, etc. That's points against this feature.

Also, it's not clear to me how exactly would this work. How would you set the default value of the property? Or PropertyChangedCallback? What about attached properties? If the feature you're proposing couldn't handle all this, it would make it much less useful. If it did, I have no idea how would the syntax look like, but I doubt it would fit well with the rest of C#.

And this feature doesn't actually add much, it just makes some code slightly more convenient.

This all says to me that such a feature wouldn't be worth it, considering that it would be relatively complicated change that would be useful only in a relatively small subset of programs and even in those wouldn't be actually useful that much.

Title: Why DependencyProperties and not native language support?

Body:
With advent of WPF and MVVM Microsoft introduced DependencyProperties and INotifyPropertyChange interface to provide a way to implement the "reactive" approach used with those technologies.

Sadly both of these constructs are very verbose, require much boilerplate, are clumsy to use, also are not really that safe since they require much use of "magic strings".

So here come the question: why didn't they put these functionalities directly into the language - why didn't they create new kind of properties created with a simple keyword, providing useful stuff of DependencyProperties (like events on change and so on...).

What were stopping them?


问:
Will an assembly language book for intel x86 processor be compatible with amd processors?
I'm wanting to get an assembly book to learn assembly, and was wandering if i get a book for intel x86 processor will there be any problems assembling the code on an amd processor?</p>

答:
I think it will be compatible(but still depends on what AMD you are using), as cited in Wiki:

x86 assembly language is a family of backward-compatible assembly
  languages, which provide some level of compatibility all the way back
  to the Intel 8008. x86 assembly languages are used to produce object
  code for the x86 class of processors, which includes Intel's Core
  series and AMD's Phenom and Phenom II series.


答:
For the most part you shouldn't notice any problems at all. Any introductory text will be using very common mnemonics (commands) and macros. Intel tried to introduce a 64-bit processor, IA-64 Itanium, that broke compatibility with the 8086 family of processors. AMD stepped up and designed a 64 bit processor that continued to work with older programming. Obvoiusly, this is what ended up being popular and Intel had to drop IA-64 and make something to work like AMD's.(Duntemann 106-107)

So now both AMD and Intel work from a set of instructions that work almost exactly the same. Little things here and there, but because the market demands it there are little differences to us the programmers. Anything you'll be learning will address when a particular mnemonic came along and which models it begins working on, for all but the latest and most obscure stuff you probably won't need for awhile anyway.

I would highly recommend Jeff Duntemann's Step by Step Assembly language. I learned from this originally 15 years ago. I was going to relearn it, and bought some other book... It just didn't work. So I found that Duntemann had released a new edition in 2009. It does a quick cover of the differences with some aspects of x86_64 but focuses on 32 bit. It really a back to front programming guide with more than just assembly. Editing, good commenting, linking, how the cpu moves data, base number counting, etc.

His website.
http://duntemann.com/assembly.html

Amazon link for the book:
http://www.amazon.com/Assembly-Language-Step---Step-Programming/dp/0470497025/ref=sr_1_1?ie=UTF8&qid=1367027229&sr=8-1&keywords=jeff+duntemann

Title: Will an assembly language book for intel x86 processor be compatible with amd processors?

Body: I'm wanting to get an assembly book to learn assembly, and was wandering if i get a book for intel x86 processor will there be any problems assembling the code on an amd processor?</p>


问:
MVC shared model different required fields on different type
I have a model called Car and depending on what type of Car the user select the view is presented differently. For example the user selects from a grid of different cars and depending if it is a Volvo or a Kia or a Ford the view must allow different fields to be editable. For example with a Volvo the color is editable and is mandatory but with a Kia it is not.

I would like to use the one Car class to bind the view but want the client side validation to pick up the required fields based on what type of car.

I want to go only to one Action method for the Update

what is a good way to approach this problem...? create a base class and inherit from it? will this give me binding problems..?

答:
To ensure the view provides the right capabilities, you should at the least extend the Car class with (a) method(s) that allow the view to get to know if a particular property is mandatory/editable/present.

Inside the model, this information can either be generated dynamically based on the values of various properties, or you can use subclasses of Car to encode the various possibilities. This choice should mostly be based on how fundamental the differences between a Ford and a Volvo are for your model. You should not create different classes just to differentiate in the editability of some properties.

Also, if you go for the subclass approach, each sub-class should be aware of all the properties that all the other subclasses support, at least in so far as to be able to gracefully handle attempts to access/modify non-existing or non-editable properties.


问:
Approach of delivering “Logging API”
I faced a question in a .NET interview.

As a client i need a LoggingAPI. How you go the approach of design and development and delivering Logging API to the client? I don't care about WPF or a language specific. I want a LoggingAPI which has to log some data? what is your approach in delivering the same.

I failed to answer for this question. Please guide how to proceed for answering this type of questions.

答:
How you go the approach of design and development and delivering Logging API to the client?

The first (and usually only) thought would be to use one of the many mature, tested and well-known existing logging libraries.. As for which one if the client doesn't care, use what you know best or what seems to be most popular.

This is if it's supposed to be a real world scenario, which it sounds like when talking about a client. It may be that the interviewers really wanted to test your understanding of how logging APIs are designed, so it might be best to first clarify that.

To gain the undestanding, it would be best to take a look at various logging libraries to see what they have in common. Typical elements are:

log levels that allow you to specify how important a log message is and allow the system to log only those above a certain level

a way to associate log messsages with modules (or classes, packages, namespaces...) so you can have per-module output and configuration

Various logging targets (log to a file, a DB, send emails, etc.)

a way to configure all of the above.

Title: Approach of delivering “Logging API”


答:
The interview question isn't clear enough. A client needs a logging API to do what? What's wrong with existent .NET Framework features?

Case 1: they were testing your analysis skills

Maybe they were expecting you to ask those precise questions, the intent being to make sure you have enough experience in elucidating the requirements and understanding the problem, instead of just starting to write code with no thought about the problem itself, like beginners usually do.

As a developer, you're expected to solve problems and the fastest, less expensive and most elegant way, not to simply type code. When you're asked to "create a blog engine which could be deployed in LAMP environment", if your first reflex is to create a new PHP file and to start typing, you're doing it wrong. Instead, you're expected to either know or go, search and find that there is already a product called WordPress that you can use, reducing the cost and delivery time, while increasing the final quality.

In real life, it happens like that:

— We need a logging API. What would be your approach of design, development and delivery?

  — Wait, why can't you use log4net?

  — Because we don't want additional libraries [one of the most stupid arguments, but sadly you rarely can reply this to the customer].

  — What about .NET Framework logging?

  — No. We need something powerful with lots of features.

  — Ok. What features do you need which are not already available in .NET Framework?

  — We need to be able to save some entries to the Windows Event Log, not simply to text files.

  — This is what EventLogTraceListener does.

  — Really? I didn't know that. Well, it's still not an option, because we need to include, with every trace event, the date and time of the event, as well as some debug values which are in a static class. Those values give us precious information about the state of the system.

  — The date and time are added with TraceListener.TraceOutputOptions. As for the additional variables, the most straightforward way would be to extend either the TraceSource or one of the TraceListeners to include the values of those variables.

Case 2: they were checking if you know how logging APIs are done

Maybe they were expecting you to describe the architecture of a logging library. In which case you were expected to tell that it should have:

Types (for example verbose, information, warning and error),

Listeners; this enables the user to attach one or more listeners like the one which logs the information to a file, or one which outputs it to the console, or one which saves the logs in the database or as Windows Events,

Filtering, i.e. each listener may want to listen to the logs from one component of an application, but not another, or a listener may be interested in only errors and warnings, while another one will record everything,

It should also be aware of concurrency issues. Writing logs to the same file from two threads would inevitably cause problems.

Being able to configure different options, especially the log level, at runtime (for example through App.config) is also nice to have.

Title: Approach of delivering “Logging API”

Body:
I faced a question in a .NET interview.

As a client i need a LoggingAPI. How you go the approach of design and development and delivering Logging API to the client? I don't care about WPF or a language specific. I want a LoggingAPI which has to log some data? what is your approach in delivering the same.

I failed to answer for this question. Please guide how to proceed for answering this type of questions.


问:
How can we track how well we're preventing and avoiding security vulnerabilities?
It's pretty easy to track when we fix security vulnerabilities in existing code.  But to make sure the whole team is staying on their toes about writing secure code, I'd like to also track how well we are preventing and avoiding writing new security vulnerabilities.  What is the right way to measure that?</p>

答:
You can never be 100% safe about security vulnerabilities, but a good approach is to check how much of your code got reviewed by a peer, because then both developers have to look over it and look for security problems. We're using Crucible (a tool by Atlassian) to accomplish that and every commit is reviewed.

Depending on your programming language there are also some tools which use algorithms to search for typical vulnerabilities in your code or even a crawler which checks your program or website in a blackbox approach.

Again, this is not to give 100% security, but it's one way to at least try to measure the improvements.


问:
Find how the data has been processed
Well this has been a question I have puzzled about for a long time:

Suppose I have a dictionary of input:output like:

This

```<code>{2: 6,
 5: 15,
 20: 60,
 26: 78,
 ...
 982: 2946,
 997: 2991}
</code>```

where output = input*3.

or This

```<code>{0: 5,
 3: 8,
 17: 22,
 19: 24,
 ...
 991: 996,
 996: 1001}
</code>```

where output = input+5

or something else.

In short where there is a definite relation between input and output.

How can a program find the relation between the input and output, such that, given another input, the output can be calculated??

Is it possible to do the same with more complex calculations like output = 5*((input*5)+3)

答:
I think the only way of doing this is taking 2 number pairs, and doing some basic mathematical operations on them and seeing if they give the same expected output.

Check for the difference between the two, divide the two, etc. Then do the same for the next pair and see if it's a match.

For example (3,8) and (10,15). Difference is 5, then add 5 to the 10 and see whether or not it's a match. If it's not, find another relation to check for.

Title: Find how the data has been processed


答:
Mathematically, the problem you describe is to find an unknown function f with

```<code>  y_i= f(x_i)   (i=1,...n)
</code>```

for a given set of input values x_1, x_2, ... and corresponding output values y_1, y_2, ...

To answer such questions, you will typically have to make some assumptions about your function f. For example, if you assume f is a linear function of the form

```<code>  f(x) =  a * x + b
</code>```

(which is true for all 3 examples you gave above), then you can find f by using two input values, solve the related linear equation system of degree 2 for a and b (and test if the other input values match the other output).

If you assume f is a polynomial of a certain degree, that means,

```<code>  f(x) =  a_n * x^n  + a_(n-1) * x^(n-1) + ... + a_1 * x + a_0
</code>```

you need to apply the the theory of polynomial interpolation. A polynomial is what you get when you allow arbitrary summation, subtraction, and multiplication, but no division. This problem is well known and if you choose a high-enough degree n, you can always construct a polynomial f matching all of your input and output values.

One can extend this problem to allow division, which leads to rational function modeling. If you want to know more about that, google for "rational interpolation".

Title: Find how the data has been processed

Body:
Well this has been a question I have puzzled about for a long time:

Suppose I have a dictionary of input:output like:

This

```<code>{2: 6,
 5: 15,
 20: 60,
 26: 78,
 ...
 982: 2946,
 997: 2991}
</code>```

where output = input*3.

or This

```<code>{0: 5,
 3: 8,
 17: 22,
 19: 24,
 ...
 991: 996,
 996: 1001}
</code>```

where output = input+5

or something else.

In short where there is a definite relation between input and output.

How can a program find the relation between the input and output, such that, given another input, the output can be calculated??

Is it possible to do the same with more complex calculations like output = 5*((input*5)+3)

Body:
Mathematically, the problem you describe is to find an unknown function f with

  y_i= f(x_i)   (i=1,...n)

for a given set of input values x_1, x_2, ... and corresponding output values y_1, y_2, ...

To answer such questions, you will typically have to make some assumptions about your function f. For example, if you assume f is a linear function of the form

  f(x) =  a * x + b

(which is true for all 3 examples you gave above), then you can find f by using two input values, solve the related linear equation system of degree 2 for a and b (and test if the other input values match the other output).

If you assume f is a polynomial of a certain degree, that means,

  f(x) =  a_n * x^n  + a_(n-1) * x^(n-1) + ... + a_1 * x + a_0

you need to apply the the theory of polynomial interpolation. A polynomial is what you get when you allow arbitrary summation, subtraction, and multiplication, but no division. This problem is well known and if you choose a high-enough degree n, you can always construct a polynomial f matching all of your input and output values.

One can extend this problem to allow division, which leads to rational function modeling. If you want to know more about that, google for "rational interpolation".


问:
What's the best documentation you produce and why?
I think it's safe to assume that for most programmers, producing documentation is not as fun as actually coding. I think it's also safe to assume that most good programmers recognize the need for useful documentation, and the code that they write is not an exception by any stretch of the imagination.

So, I'd like to know: what's the best documentation you produce (and source code doesn't count). Answer can be anything from comments to unit tests.

The bigger question is why is that the best documentation you produce?

答:
Our Wiki.

Because people actually use it and update it.

I think the nature of a Wiki lends itself to the way developers want to work which is just get the facts down and move on.

It's quick and easy, searching makes it simple to find what you're looking for which minimises the chance of duplication (and the subsequent "so which is right") and you need minimal technical skill to read or change stuff (as opposed to, say, tests).

Versioning is automatic, formatting is basic but effective which means the content tends to be prioritised over prettiness, and there's no pressure to have cover pages, change tables, summaries and so on all of which add work for little benefit.  Because it doesn't have a specific structure, people just worry about putting down what's important, not what fits.

That's all my guess as to why it gets used but as a development manager the main thing I like is that it does get used and remains broadly up to date.


问:
How do you test database abstraction in PHP?
I apologise in advance if this question is too subjective but I'm struggling to find a good answer, probably as there is not really a correct answer to give.

I'm currently writing a database abstraction layer to unify the use of a single API throughout my applications. Possibly re-inventing the wheel but I'm mainly doing it for my specific need of certain Oracle functionality that will eventually be migrated away from Oracle.

For the Oracle driver I'm finding it difficult to test the object due to the lack of an OO API in PHP, so to test I need to touch the database. There seems to be two schools of thought on testing database functionality.

Don't touch the database, mock it all away (obviously impossible without an OO API).

Allow the functionality to run and therefore feature test rather than unit test.

My question is two fold, has anyone done this before and how did you handle testing? If you haven't had cause to do this before, what are your thoughts on how you would handle it and why?

答:
I've seen someone doing an automatically replace of all functions in a similar case before running his unit tests.

So first he reads all the code who should be tested, in your case searches for oci_*() functions and replaces them by my_oci_*() functions . You can then mock these my_oci_*() functions.

Another option could be to install a php version without the oci-support on your test environment, so the functions are not defined and you can implement/mock them on your own.

OwnerDisplayName: happyaccidents


问:
What's the formal name of this diagram?

I'd also want to know how can I draw them.

答: That is a syntax diagram.  I think I first saw them in Grogono's "Programming in Pascal", from 1980, but they were used in Wirth's 1973 report on PASCAL.</p>

Title: What's the formal name of this diagram?


问:
To which extent can one take ideas from programs under GPL in developing a commercial app?
I am developing a commercial application. There are several programs under GPL which have some common features with my planned applications.

Can I take ideas from those applications under GPL and implement them myself without copying the code?

Would this violate the GPL?

答:
Short answer: Ideas, yes. Source code, no.

The source code is protected by copyright and the license only allows you to use the source code if you license the result as GPL. This doesn't block you from selling the result, but requires you to provide the source code to anyone you have sold the application to (and stops you from barring them passing the source or app on).

The ideas should be OK, as long as they're not otherwise protected (patents, essentially). There may be patents that allow an automatic license only for open source.

As always, please consult with a lawyer before taking legal advice from the internet. I am not one, so this is pure layman advice.


答:
Well written tests.  They describe what the code should do, and demonstrate that it works.

Since they are automatically run with every build, they are never out of date.

Title: What's the best documentation you produce and why?

Body:
I think it's safe to assume that for most programmers, producing documentation is not as fun as actually coding. I think it's also safe to assume that most good programmers recognize the need for useful documentation, and the code that they write is not an exception by any stretch of the imagination.

So, I'd like to know: what's the best documentation you produce (and source code doesn't count). Answer can be anything from comments to unit tests.

The bigger question is why is that the best documentation you produce?


问:
How should subsytem in different locations interact and communicate?
Apologies for the long post...

Where I work we have a system with many subsystems which are located in different locations. All the subsystems process some data and write the result on A database. In case any other subsystem needs the output f other subsystems it gets connected to the database and read from it. And that is how subsystems are communicating together. Also there is GUI which get connected to the DB and shows information to the end user. The interaction between database and subsystems are very high, and although I argued that this is not a very good choice of design, I have been told that due to lots of reasons (mainly "business-wise" and short deadlines) we cannot change anything in the system for now.

Now we want to add a new feature where user can add notification-alert system where in case something happened in any subsystem, it notifies the user via GUI. And of course depend on different subsystem there would be different items that should be considered. And based on these items user can specify a rule for the alert. For example, On different server we have software which get the server information like CPU and RAM usage and etc. SO these could be items for user to set a rule for a notification alert. Like if memory used space exceed X percent.

The only way I can think to solve this is, to create new tables in the database. When user add a new rule for a subsystem, insert the rule into the data base. And every subsystem reads the data base to see if any rule has been specified for it. But this means every subsystem should read from database every minute at the most, and I think this would break our system... And then subsystems write the result on the DB and GUI also reads the DB to see if any notification should be shown to user......

any thought on how to overcome this?

答:
Made it an answer as it fits and would have to make multi comments.

Nagi os can help with auto monitoring and notifying. its a full monitoring software with extns, UI, versions for windows and linux. we use it to monitor both linux/ unix and windows.

"there are other type of notification which can be set base on the behavior and output of other subsystems like their state "
You can do that with nagios too. We have some custom pages that output "okay" if everything okay and if there is some warning or error then output "Warning: ..." we configure nagios to look at these pages and can configure who to report to (contact group). we have email for warnings and SMS & email for other. the sms part is our own code (we use in other places too) that is called by NagiOS to send SMS (text on mobile) alert. (the custom pages have IP restrictions so they can be viewed in LAN only)

Have a look at nagios and see about the plugins, frontends, config tools ...

You should look in to security and having at least two roles in Nagi OS - admin and user.


问:
GPL/LGPL/MPL non-code content license
I want to use a dictionary (basically a text file, and no code) that is included with an open office spell checking plug-in. The plug-in is under the tri-license GPL/LGPL/MPL which I don't understand. is that legal?

If it is illegal, what if I wrote a script that uses the said open office plug-in to generate the dictionary (assuming it's technically possible, the script will generate all possible letter permutations, passes it to the plug-in and saves the correct ones) ?

I will be using the dictionary in a closed source commercial application.

The dictionary is in a language that has very little resources online, and short of making my own dictionary, there aren't any alternatives.

Clarification: The script idea I mentioned above, isn't a weird technique, I would generate a document with all possible words and use open office with the plug-in installed to show spelling mistakes and remove them, isn't this the intended use of the plug-in (spell checking)?

答:
Code can be released under multiple licenses.

If you don't have permission to use the original file and you "launder" it like you're suggesting, you aren't really changing anything.  Judges aren't dumb, so if you're essentially hoping that copying it in a weird way will make it legal when copying it directly would not, stop thinking that.

Also, don't think that "otherwise, I'd have to make my own" will fly.

It's possible that there is something available on the internet that is not specific to your language but that you could use.  It's also possible that the code and the data file for the plugin you're talking about are under different licenses.

Title: GPL/LGPL/MPL non-code content license


问:
What are the drawbacks of immutable types?
I see myself using more and more immutable types when the instances of the class are not expected to be changed. It requires more work (see example below), but makes it easier to use the types in a multithreaded environment.

At the same time, I rarely see immutable types in other applications, even when mutability wouldn't benefit anyone.

Question: Why immutable types are so rarely used in other applications?

Is this because it's longer to write code for an immutable type,

Or am I missing something and there are some important drawbacks when using immutable types?

Example from real life

Let's say you get Weather from a RESTful API like that:

public Weather FindWeather(string city)
{
    // TODO: Load the JSON response from the RESTful API and translate it into an instance
    // of the Weather class.
}
```

<p>What we would generally see is (new lines and comments removed to shorten the code):</p>

<pre class="lang-cs prettyprint-override"><code>public sealed class Weather
{
    public City CorrespondingCity { get; set; }
    public SkyState Sky { get; set; } // Example: SkyState.Clouds, SkyState.HeavySnow, etc.
    public int PrecipitationRisk { get; set; }
    public int Temperature { get; set; }
}
</code>```

On the other hand, I would write it this way, given that getting a Weather from the API, then modifying it would be weird: changing Temperature or Sky wouldn't change the weather in real world, and changing CorrespondingCity doesn't make sense neither.

public sealed class Weather
{
    private readonly City correspondingCity;
    private readonly SkyState sky;
    private readonly int precipitationRisk;
    private readonly int temperature;

    public Weather(City correspondingCity, SkyState sky, int precipitationRisk,
        int temperature)
    {
        this.correspondingCity = correspondingCity;
        this.sky = sky;
        this.precipitationRisk = precipitationRisk;
        this.temperature = temperature;
    }

    public City CorrespondingCity { get { return this.correspondingCity; } }
    public SkyState Sky { get { return this.sky; } }
    public int PrecipitationRisk { get { return this.precipitationRisk; } }
    public int Temperature { get { return this.temperature; } }
}
```

答:
The only drawback I can think of is that in theory use of immutable data may be slower than mutable ones - it is slower to create a new instance, and collect previous one than to modify existing one.

The other "problem" is that you can't only use immutable types. In the end you have to describe the state and you have to use mutable types to do so - without changing state you can't do any work.

But still general rule is to use immutable types wherever you can and make types mutable only when there really is a reason to do so...

And to answer the question "Why immutable types are so rarely used in other applications?" - I really don't think they are... wherever you look everyone recommends making your classes as immutable as they can be... for example: http://www.javapractices.com/topic/TopicAction.do?Id=29


问:
What are some good assignments for an introductory course, to reach today's students?
I periodically teach an introduction to programming course using Java. I want to give my students some exciting assignments that they can relate to or find interesting. At the very least, I want assignments that make sense and have an internal cohesion (for example, some very bad programming exercises seem contrived just so that you have to use the most recent programming construct covered).

To give you an idea of scope, here's what's being covered:

The assignments must be in Java, using some external library can be done, but it would need to be a simple API and not a full framework

Variables, Primitives and Strings

Console input and output

if, for, while

Arithmetic and logical operators

Simple graphics with line and shape drawing

Static methods

One-dimensional arrays

The students will not go into advanced topics (e.g., no recursion, no emphasis on inheritance). Thus, I'm not looking for complex projects: "Have them write a C compiler. I did it when I was 5 and it was the only way I learned!"

If you have ideas that are more advanced than the scope, please post them on the "Challenging" question linked below, and not this one.

Instead, what I'm looking for are interesting ideas that can be accomplished in a short program. For example:

Students can write a console version of the "Star Wars Name" Generator. This is effectively reading Strings and using substring, but I think it's fun. A similar variation would be a "Mad Libs" program. I used this one five years ago, and perhaps it's already "stale."

Using some trig supplied to them, students can draw regular polygons, and create interesting spiral shapes.

It's also not out of the question to use some simple animation class with most of the code supplied to them. And if you know a Twitter or Facebook service that can be accessed with a simple API, I would be very interested to know.

Please note that this question is different from the "Challenging Java questions for beginners" Question. I'm not looking for challenging per se, just interesting. I think if students work on something where they can easily answer "why would anyone ever want to program that?" then they will learn better.

Even simple problems like computing Miles per Gallon can be good. Although, if there's a way to update it to be more relevant, all the better. If you have an exercise from somewhere else (a book or a website), please cite the source.

To help you think about the typical freshman today, check out the Beloit Mindset list, for many examples that will surely make you feel old.

答:
In my intro course, three projects stuck out at me

Write a program to display a random Mondrian painting

Write the first part of a BrickBreaker game, get the ball bouncing around inside a set area

Write a text-based adventure game

From my algorithms class

Implement a Serpinski triangle

These four projects gave me a great understanding of string processing, randomization, graphics, recursion and animation.


答:
There are two possible scenarios, with different consequences for the licensing position.

Your application reads the dictionary as an input file. Your application does not care where the dictionary comes from as long as it is in the right format. Providing the dictionary along with your application is essentially a convenience for your users, if they want they can just replace it.

In this case, it does not really matter what license the dictionary has, as long as you are allowed to re-distribute (which all free licenses allow, that's an essential part of them being free), because the combination of your application and the dictionary will not be considered a derived/modified work, but rather an aggregation of independent works.

Your application links to the dictionary like using a software module.

If you link statically (the end-user can't replace the dictionary with a different version without recompiling), you are most likely out of luck and your closed-source application can't be distributed. It might be that the MPL allows it, but I am not familiar enough with it to tell.

If you link dynamically (the end-user can replace the dictionary with a different version without recompiling), then you can use the dictionary under the terms of the LGPL. Because the dictionary is multi-licensed, you get to choose which license terms you want to apply.

In all cases, it should be clear that the dictionary and your application are distributed under different licences and where the source for the dictionary can be obtained (unless the dictionary file itself is its source).

Title: GPL/LGPL/MPL non-code content license

Body:
I want to use a dictionary (basically a text file, and no code) that is included with an open office spell checking plug-in. The plug-in is under the tri-license GPL/LGPL/MPL which I don't understand. is that legal?

If it is illegal, what if I wrote a script that uses the said open office plug-in to generate the dictionary (assuming it's technically possible, the script will generate all possible letter permutations, passes it to the plug-in and saves the correct ones) ?

I will be using the dictionary in a closed source commercial application.

The dictionary is in a language that has very little resources online, and short of making my own dictionary, there aren't any alternatives.

Clarification: The script idea I mentioned above, isn't a weird technique, I would generate a document with all possible words and use open office with the plug-in installed to show spelling mistakes and remove them, isn't this the intended use of the plug-in (spell checking)?