问:
Isn't GPL enough to make a software free as in free speech?

Background

I have read people rebutting the fact that a certain software is free as in free speech, even when it is licensed under GPL.

Some say Java isn't free because to obtain a professional certification you must get it from Oracle.

Some say Java JDK is not free to re-distribute.

Some people even say the openJDK is not free or open.

But Java is officially GPL.

Questions

Doesn't GPL explicitly mean you are free to re-distribute ?

Isn't GPL enough to make a software free as in free speech ?

How can Java be both GPL and not-free as in free speech ?

Is there is any license that trully makes a software free beyond any possible subjetive point of view?

EDIT: These question is not about names or trademarks, it's about the code.

答:
Free speech: I can write a book, and charge money for it. My speech is copyrighted. I have freedom to speak, but I also have the freedom to charge people to use my words. GPL takes away that second option (somewhat - the analogy isn't perfect).

The GPL makes selling software difficult. Any software you create using GPL'd libraries, you have to distribute as GPL. I am making a commercial game, trying to start an independent business. Games are sold. If I use a GPL library in my game (say, for a tiny piece of URL resolving, or PNG file loading), my entire project's source code must be distributed for free. I can still charge for my game... but anyone else could compile my game and sell it as well (if they replace the art and change the game's name). That's not good, and makes GPL'd software worthless to me.

I get that modifications to the GPL'd code itself should be released, but I heavily disagree that my entire game project should be forced to use the GPL because 0.01% of it relies on a library that's covered by the GPL.

LGPL resolves this problem (if you dynamically link), so I'm heavily in favor of LGPL code.

I think GPL is fine for entire projects, I don't mind using a GPL'd art program, for example. But imagine if using that art program forced the art you created to become Creative Commons license (thankfully, they don't). And imagine that you are trying to make a living selling your art. It'd make that art program unusable to you. That's what GPL libraries do to your code.

GPL = Fine for entire projects, utterly horrible for libraries (unless you don't want your libraries used for commercial projects).

LGPL = Perfect for libraries, not as great for entire projects (depending on the desires of the project).

GPL is designed to further the open source movement, by virally infecting anything that uses GPL to make the using code also become GPL. It's too demanding.
LGPL is designed to force you to share changes to something someone else made (good), but allowing you to use that something to create something new, and still lets you retain control of the new thing you created.


问:
Can I create and publish an iPhone app by building it in a second hand Mac?
I have never published an app to app store.
I have a chance to buy an apple mac from someone.

Is it possible to use that to publish to app store? What if the first owner was also a developer?

If I buy Mac with the only intention of publishing an app should I only go for a new one to get developer license or I can do it in a second hand Mac also?

答:
So long as the computer is an "Intel-based Mac running Mac OS X Snow Leopard or later", it doesn't matter.  In theory.

However, iOS 5.1 and up require a version of XCode which will only run on Lion.  So you need a computer that's capable of running Lion in order to do any serious development.

ContentLicense: CC BY-SA 3.0


问:
Is 25% to me as sole author a good deal?
This is my first contract negotiation.  So I've written a program which supports some hardware that the company makes.  (The support is important, and most customers will buy it, but the software product is ultimately optional.)  It will sell for about $2K/license and they sell 70-80 hardware systems/year.  The market here is biomedical research, i.e. the customers are individual research labs in universities and hospitals.  The company will be hosting the software (obviously) and it will be part of their marketing pitch.  They tell me that a 75-25% split is typical.  Really?  How does this smell to you guys?  What are numbers that you have worked with?

Edit: A little more info.  I have written an open-source version of this program that has been out about a year.  The contract is to write a commercialized version (basically, more features) which I would give to them.  They are going to pay me some money up front, then pay me 100% of gross up to a certain amount (low six figures) and after that, 75/25% them/me in perpetuity.  They will have all rights and I won't be able to build another product in that category as long as I have a relationship with them.

答:
Seems pretty fair to me actually.  Normal business (all business not this particular market) markup is 50% over cost, that is profit for the company etc.  The other 25% is the cost for them to market, sales commissioni etc. basically their costs, so a 25% cut to you is actually pretty decent IMO.

This is especially true, since they could have just paid you a flat rate.


答:
This is more of a business question then a programming question.

Frankly I'm jealous! You're in a great situation! Some thoughts:

If I understand the numbers in your post they're offering you an income of maybe $20,000 a year (once you reach the 25% level). Nice! But are you required to do anything for that income? For instance, is there a commitment to support the software?

In any negotiation, the first party to mention a figure (them) would usually expect the other side (you) to ask for more.

How long will it take to write the commercial version? Do you have enough money to live & work while that happens, bearing in mind savings and money up front?

Who will own the software? You or them? Either might be fine, but they should pay you more money if it's them.

These numbers are big enough that I would get a lawyer to look over any contract before you sign it.

Title: Is 25% to me as sole author a good deal?

Body:
This is my first contract negotiation.  So I've written a program which supports some hardware that the company makes.  (The support is important, and most customers will buy it, but the software product is ultimately optional.)  It will sell for about $2K/license and they sell 70-80 hardware systems/year.  The market here is biomedical research, i.e. the customers are individual research labs in universities and hospitals.  The company will be hosting the software (obviously) and it will be part of their marketing pitch.  They tell me that a 75-25% split is typical.  Really?  How does this smell to you guys?  What are numbers that you have worked with?

Edit: A little more info.  I have written an open-source version of this program that has been out about a year.  The contract is to write a commercialized version (basically, more features) which I would give to them.  They are going to pay me some money up front, then pay me 100% of gross up to a certain amount (low six figures) and after that, 75/25% them/me in perpetuity.  They will have all rights and I won't be able to build another product in that category as long as I have a relationship with them.


答:
Caveats: I am neither a lawyer nor a freelancer, so take this as simply my personal opinion rather than the voice of experience.

In general, this sounds like a really good deal to me.  However, there's some things you're going to want to make sure are explicit in the contract:

Are you responsible for on-going maintenance and improvements?  If so, will you be paid more for that, or is the 25% considered a retainer to cover any work you may need to do in the future?

Do they have any accountability to you?  Do you have the right to audit them to ensure that you're actually receiving the 25% you're owed, or do you simply have to take their word for it?

Are you allowed to sell these new features, or any similar ones to other companies, and/or add them to the open source version?  Or are you prohibited from adding anything resembling them?


问:
Can >8bit per channel colours be seen as intended in the browser?
For, say, a subtle background gradient to a web page, what are the advantages and disadvantages of saving it as a 16bit/channel png?

Are the colours represented by >8bits displayed in the intended detail in all browsers?

答:
The advantage of a 8 bits per channel indexed PNG is its size.

The disadvantage is that if the image contains more than 256 colors, the graphics editing program will try to adapt the palette, meaning that some colors will slightly vary. Some programs are smart to pick a well-adapted palette. Some are retarded. Don't use the last ones.

For a subtle gradient, this disadvantage doesn't exist, since subtle gradients would hardly use more than 256 colors. To reduce the size of the image even more, you can restrict PNG 8 to use less than 256 colors: for example only 16.

Note about gradients in general:

If this is an horizontal or a vertical gradient, ensure the image is one pixel large or one pixel high. This seems obvious, and still, I've seen a huge number of designers, programmers and persons specializing in HTML and CSS putting a 1000×150 pixels image in order to have a 150 pixels top-bottom gradient.

Unless you should support legacy browsers, consider CSS 3 gradients instead of images. For the browser, the best image in terms of size is no image at all.

When you should support legacy browsers, consider CSS 3 gradients anyway. People who are still using Internet Explorer 8 or earlier probably don't care too much about pretty gradients, shadows or rounded corners. For them, your website will be monotonous, flat and square, but still usable.

Note about graphics editing programs:

Using a professional graphics editing program helps. For example in Photoshop, you can instantly see how the image will be rendered with a set of settings, say Perceptual, Diffusion, Colors 16. This enables to quickly try different options and pick the one which is just above the level below which image quality visually decrease.

If you don't have one, you can still save multiple variants of the same image, and then compare it in a viewer side by side.

Note about size of images:

Most users won't be disgusted by minor JPEG artifacts or PNGs with sub-optimal palette, especially on mobile devices. Speed, on the other hand, matters, especially on mobile devices. If a website is nice but every image takes ages to load because of its size, nobody will use the website. Consider this bias when choosing the appropriate format and settings. In other words, look more at the size of the image and less at the visual quality.

Some other hints:

Playing around with the images and especially PNG 8, you may discover the following:

Sometimes, combining several images into one (i.e. create a CSS sprite) is beneficial in terms of performance: not only browsers are requesting one image instead of doing multiple requests, but also this one image is not much larger (and sometimes even smaller¹) than multiple original ones.

Also, splitting one image into multiple ones can reduce a lot the overall size when working with PNG 8. I remember going from 200 KB monolithic CSS sprite down to 40 KB by splitting it into ten images. According to the metrics, this effectively had a positive impact on the server, despite the fact that the browser was forced to do ten requests instead of one.

¹ I don't remember the case when I've seen it. If somebody knows such a case, feel free to edit the answer.


问:
Should all classes have a default constructor as part of good coding convention
From the texts I have read so far, the conventions talk about organizing constructors, starting with the default, if any. I am wondering, should all classes have a default constructor anyway. This will at least help to create a simple instance of the class on the fly, without having to use a parameterized constructor, which itself may require additional imports for specific parameter type.

答:
Generally speaking, you should have constructors for classes that take enough parameters to properly initialize the object being created into a valid state.  If your class is able to provide sane defaults for all fields that comprise a valid state for objects of that class, then a default constructor is most likely a good idea.

Also, some libraries require the existence of a default constructor for certain operations.  For instance, libraries in Java used for deserializing json/xml often require a default constructor to be invoked via reflection since those libraries will attempt to evaluate everything at runtime and can't know in advance what constructors are available to be used - so they expect a default constructor.  In instances like these if a default constructor is required by tooling, but should not be called by anything you control or any users of your API, it's best to use the the common idiom of your language to mark the constructor as private (e.g. private access in typical statically typed languages).


答:
The reason that some classes opt to have only a complex constructor is often that they cannot work usefully without knowing core information about an instance. Being able to create a trivial instance is not benefit in this case - in fact, it is probably a disadvantage, because then all methods must be able to deal with an object that is missing crucial data! By disallowing this, you can often establish invariants for a class that save a lot of coding time and run-time effort.

A general rule about what constructors you "should" or shouldn't have has little weight against such class-specific considerations. In practice, the only valid reason for enforcing a trivial constructor I have ever seen is if you hand your objects to a framework that itself requires one. Even then I'll probably make the constructor private if I can get away with it.

Title: Should all classes have a default constructor as part of good coding convention

Body: From the texts I have read so far, the conventions talk about organizing constructors, starting with the default, if any. I am wondering, should all classes have a default constructor anyway. This will at least help to create a simple instance of the class on the fly, without having to use a parameterized constructor, which itself may require additional imports for specific parameter type.


答: Depends on your coding style and the patterns you implement. With Dependency Injection (DI) you'll often find yourself only having a default constructor when you actually need one - be it for XML serialization or whatever. Being biased with DI, I would tend to say no, you don't need a default constructor, since the only work that gets done in a constructor, is the injection of the class' dependencies: constructors become a static documentation of a type's dependencies.</p>


问:
Which are the significant algorithms for humankind in past decades?
Which world most important algorithms have contributed most to humankind in past decades?

I thought this is a good general knowledge for a developer to know about.

Update:

If possible, please keep the answer to a specific programming algorithm.

I would like to get a list of the most important ones, only one algorithm per answer.

Please consider to state why the algorithm is significant and important...

答:
If I had to list the top 3 most important algorithms in use today in computers, I would say:

Binary Search

Quicksort

Dijkstra's algorithm

The Binary Search algorithm is used constantly to narrow down on an item within a sorted list, most index lookups will use something along these lines at some point.  This algorithm provides a search of an ordered list in o(log n) time.

The Quicksort algorithm finally managed to get sort down to O(n log n) average case and O(n^2) worse case.  Sorting is one of the most common data tasks in a computer and one of the most expensive, improving the average case sort was a huge step forward in efficiency.

Dijkstra's algorithm as has been said produces a shortest path between points within a graph.  This is used widely for all manner of routing applications, most extensively with regard to the internet itself ensuring that the quickest path through the tangled web of interconnected routers is used.

ContentLicense: CC BY-SA 2.5


答:
There are two cases where default constructor makes little sense:

Reliance of a class on its field or property.

Imagine a series of classes which load statistical data from the database and display it in a chart. One of the classes, DataTransform, normalizes the data from the database in order to be used in a chart. This class uses a IDataProvider which feeds DataTransform with raw data.

In order to be testable and interoperable, you have four classes implementing IDataProvider: the one for Oracle, the one for Microsoft SQL Server, the one which loads data directly from XML and finally the mock to use in unit tests.

Having a default constructor would force you to:

Check in nearly every method of DataTransform that IDataProvider dataProvider field was initialized,

Expect anyone using the class to either call the parametrized constructor, or call the default constructor and then set the data provider through an additional property or method.

This indicates a serious problem in the design. Throwing away the default constructor and having exclusively the constructor which takes the data provider as a parameter makes the class more intuitive to use, and its own code simpler.

Immutable objects for which defaults make no sense.

Imagine an immutable Person who has as properties FirstName, LastName and BirthDate. While first and last names can be defaulted to an empty string (or null, if the language authorizes null strings), what would be the birth date? The minimum authorized date? Why would you ever want an immutable person who has no name and was born in January 1st, year 1?

Note that immutability alone doesn't mean that there should be no default constructor. For example, it makes sense to have a default constructor for Point, resulting in Point(x = 0, y = 0); another way is to have a static constant Point.Zero. Another example: it makes perfect sense to have a default constructor for an immutable String (either a null or an empty string).


答:
Absolutely not. Default ctor is due if the class can be sensibly constructed without any info coming from outside.  (If you limit the question to that subset, the answer turns to yes.)

Otherwise having a default ctor forces two-stage initialization with all the drawbacks it draws in. We chose it only for extremely good reasons.


问:
Why doesn't Swing look native out of the box?
Java Swing GUI's don't look native by default (Except on Mac OS X for some reason). Swing uses it's own look and feel. You can get Swing to use the system look and feel by putting:

```<code>javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
</code>```

in the beginning of your main method, but: Why isn't this done by default?

答: I'm pretty sure that swing was designed to be lightweight with Java's (Sun's, now Oracle's) own widgets designed for cross platform usability. The graphics for the widgets look the same and are distributed along with the platform package. The native feels require interfacing with the OSes look and feel, which make it more heavyweight. Other GUI toolkits do this natively, like AWT.</p>


问:
How to protect my php code running on a client server?
I'd like to ask how to protect my code that is running on a client server from being altered and/or copied.

It's running on Ubuntu Server with the standard Apache Php Mysql stack.

Any software needed would preferably be open-source.

I'd also like to terminate the application when there is a license problem.

Doing this using my code is possible but since it's php the client could alter the code to prevent this from happening.

答:
Take a look at this new opensource project:

http://pecl.php.net/package/BLENC

BLENC is an extension that permit to protect PHP source scripts with Blowfish Encription.
BLENC hooks into the Zend Engine, allowing for transparent execution of PHP scripts previously encoded with BLENC.
It is not designed for complete security (it is still possible to disassemble the script into op codes using a package such as XDebug), however it does keep people out of your code and make reverse engineering difficult.


问:
Programming as fast as you can touch-type... How to get to that stage?
I took a test recently and found that I could touch type comfortably at around 100 wpm... and if given some sort of autocorrect/intellisense then that would be even faster (who knows maybe 150 wpm?)...

I definitely do not program anywhere near that speed... This led me to wonder how exactly does one become faster at programming? Once I look at a problem and design the algorithm to solve it (the problem is solved... I know what i'm going after give or take some debug runs) why does it take so much longer for me to actually type up the program? What I found was that in general when I'm coding, until I am done typing a word... even if it is just the letter a or number 1, I cannot simultaneously think and type. What that means is that I can come up with stuff as I'm typing but I don't have the ability to look ahead. Its either one or the other... For example in writing this, I might have a feel for where this goes, but until my fingers hit the keyboard, I don't really know what I'm going to say next.

How do I change this? How do I get the ability to think ahead while typing so that I can take advantage of my typing speed?

Also just in general how does one become a faster problem solver? I know the usual list of practice (which I have no problem with) but is there any particular excercise one should emphasize to train their mind? For example is playing various logic games (sudoku etc...) carry much help in improving your sense of logic in other areas of programming?

Sorry its a bunch of questions at once but they are all sort of related...

P.S. Is it possible to use a stenograph to program? I've heard that users of stenographs can achieve blistering speeds like 200 - 300 wpm. Assuming I can somehow think faster... that would be pretty cool.

Obviously fast programming != good programming. But if your always training to become a better programmer, it doesn't hurt to be able to do it fast.

答:
Some very pessimistic answers here. I can speak from personal experience that it is absolutely possible to touch-type programming. But that's not really the issue, right? I mean you're REALLY asking "how can I be a more productive programmer?" Let's take a look at some of the factors:

How verbose the language is. I'm a java programmer and I can easily type at maximum speed doing things like making getter and setter methods on a POJO. But some languages don't even require the creation of these boilerplate methods. And Eclipse has tools for autogenerating these. In Python you can accomplish in a single line which takes Java ten lines. So typing slowly in Python is just as efficient at typing quickly in Java?

How well you planned ahead. If you start working on something with vague intentions, you will be spending more time thinking instead of writing. If you have a good understanding of what code is already existing and you know exactly how to approach your solution, then you can expect to get things done more quickly. BUT you're still spending extra time planning ahead. So is the total amount of time spent equal? Different people work better with different styles. Some people prefer to jump straight into the fire and fight their way through.

How distracted or focused you are. Some people think it's a good idea to listen to music to tone out their environment. Some people like peace and quiet, and some people actually enjoy a noisy environment. I personally think that meditation is THE KEY to getting good focus. Most people don't realize how little control they have over their mind. Twenty minutes of meditation every day can make an incredible difference in your clarity of mind, translating to hightened productivity.

How healthy you are. The health of your brain is directly related to the health of your body. Avoid smoking, consuming alcohol or caffeine, eating heavy or unhealthy food, taking unnecessary medications, etc. Get the right amount of sleep each night, which is different for every person. You'll be amazed at the difference this makes.

How much stress you're under, how long you've been working, how many babies are crying in the background, etc, etc, etc... There are too many factors to list here. It's worth mentioning again that meditation can help with these things. Your mind is a beast and if you don't tame it then it controls you, instead of you controlling it.

Happy coding!


答:
I did a lot of Swing programming in the late 90's, but I don't do very much nowadays, so I don't know if it's still an issue or not.  It used to be the case that if you used a native look and feel, you'd occasionally run into layout issues when you ran it on another platform, due to slightly different control proportions and such.  Using the default metal look and feel avoided those kinds of issues.

Of course there's always the more puerile possibility that Java likes their look and feel better and it's their language, so there :P

Title: Why doesn't Swing look native out of the box?

Body:
Java Swing GUI's don't look native by default (Except on Mac OS X for some reason). Swing uses it's own look and feel. You can get Swing to use the system look and feel by putting:

```<code>javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
</code>```

in the beginning of your main method, but: Why isn't this done by default?


问:
Merge sign up with Twitter and Facebook
I want to have sign up/login functionality on my site with a "Login with Facebook" and "Login with Twitter" button.

Considering the following scenario:

User A logs in with Twitter.

Account gets created.

User A logs out.

User A comes back next week and can't remember what they signed up with (or just feels like) using Facebook login this time.

How can you combine these accounts?

So far there's 2 options I can think of:-

Cookie (Not reliable)

Have a 'login' and 'signup' action. So if they 'login' with Facebook it will say "You never signed up for this site with Facebook. Did you maybe use Twitter?" (But maybe they will 'signup' with Facebook then and then I still have no connection with the previous twitter account)

答:
There's no way to link the two accounts unless the user tells you they should be linked. You're entirely right that a cookie isn't reliable - someone else might be using that computer now.

What you need is a way for a user with an existing account to link their Twitter and/or Facebook account to the account they're currently logged into.  Then you detect that you already know about that Facebook login when they try to link it, and offer to merge their data.  It's really on the user to remember how they log in to your site, the same way it's on them to remember their passwords.

Scenario:

User A comes along and signs up with Facebook

Later, User B (who may or not be the same as A) comes along and signs up with Twitter

User B decides to link their Facebook account, which you recognize as being the same as User A.

You tell the user: "This Facebook account has already been linked to the the system.  Is this you?"  If so, you merge the accounts in your backend.

Title: Merge sign up with Twitter and Facebook


问:
UI (Specifically FLEX) automation testing
I was wondering whether the community utilizes automation tests to the extent of UI? Is there some common best practices for testing UI?
Also - the product I'm working on is flex-based. I would love to get ideas how to test it.
Mainly I want to test:

Data appears on the screen as expected

Field validations (for example: field is not a number) are working as expected

Alignment of fields

And so on

答:
I've seen a number of things tried for UI testing. Flex specifically has (had?) an automation framework which you can use. I believe that programs like FlexMonkey utilize this.

There's also the old stand-by of screen scraping. Tools like Skuli will let you do that.

But in general, the best practice that I've seen repeated over and over through the industry is this: GUI testing is hard, so don't focus on it. Create hooks (APIs, if you will) to get at the data underneath the GUI, and automate that testing. Then let the GUI be a very thin layer with minimal logic (view-logic only, if you must) which can be fairly easily tested manually.

In his book The Clean Coder, Bob Martin suggests that GUI testing should be manual and only account for ~10% of the system.

In my work experience, my department spent a long time trying to do automated GUI testing and never really got anywhere with it. It takes a ton of effort and seems to yield minimal results. Eventually we just gave up on it. Therefore, I cannot recommend it.

Most of the things you want to be able to test can be testable by exposing a good API.


答:
Java language "philosophy" is WORA:

Java is ...intended to let application developers "write once, run anywhere" (WORA), meaning that code that runs on one platform does not need to be recompiled to run on another.

Explanation for default given in Swing tutorial (Available Look and Feels) looks consistent with above:

CrossPlatformLookAndFeel — this is the "Java L&F" (also called "Metal") that looks the same on all platforms. It is part of the Java API (javax.swing.plaf.metal) and is the default...

Apparently, library designers decided that "CrossPlatform... looks the same on all platforms" deserves to be default for the library in the language primarily intended to be cross platform.

Marketing / designer dreams could play their role here, too. Every library designer hopes / expects it to be popular and widely used (otherwise, there's little sense to invest effort into it). If Swing designers expected it to be used very widely, consistent (not system dependent) L&F could be considered an advantage, so that users running the same (popular! how could it be different?) Swing application on different platforms would feel comfortable with familiar interface.


问:
Why do many PHP Devs hate using isset() and/or any of PHP's similarly defensive functions like empty()?
Over on stackoverflow, I see this issue crop up all the time:

E_NOTICE ?== E_DEBUG, avoiding isset() and @ with more sophisticated error_handler

How to set PHP not to check undefind index for $_GET when E_NOTICE is on?

How to stop PHP from logging PHP Notice errors

How do I turn off such PHP 5.3 Notices ?

Even Pekka (who offers a lot of solid PHP advice) has bumped against the dreaded E_NOTICE monster and hoped for a better solution than using isset(): isset() and empty() make code ugly

Personally, I use isset() and empty() in many places to manage the flow of my applications.  For example:

```<code>public function do_something($optional_parameter = NULL) {
    if (!empty($optional_parameter)) {
        // do optional stuff with the contents of $optional_parameter
    }
    // do mandatory stuff
}
</code>```

Even a simple snippet like this:

```<code>if (!isset($_REQUEST['form_var'])) {
    // something's missing, do something about it.
}
</code>```

seems very logical to me.  It doesn't look like bloat, it looks like stable code.  But a lot of developers fire up their applications with E_NOTICE's enabled, discover a lot of frustrating "uninitialized array index" notices, and then grimace at the prospect of checking for defined variables and "littering" their code with isset().

I assume other languages handle things differently.  Speaking from experience, JavaScript isn't as polite as PHP.  An undefined variable will typically halt the execution of the script.  Also, (speaking from inexperience) I'm sure languages like C/C++ would simply refuse to compile.

So, are PHP devs just lazy?  (not talking about you, Pekka, I know you were refactoring an old application.)  Or do other languages handle undefined variables more gracefully than requiring the programmer to first check if they are defined?

(I know there are other E_NOTICE messages besides undefined variables, but those seem to be the ones that cause the most chagrin)

Addendum

From the answers so far, I'm not the only one who thinks isset() is not code bloat.  So, I'm wondering now, are there issues with programmers in other languages that echo this one?  Or is this solely a PHP culture issue?

答:
I believe PHP, as a free language, that is interpreted and used on the web, has a very high proportion of non-professional, untrained coders who are not fully aware of why they should code defensively and just see the warnings as another unnecessary error.

I hear these points from junior developers and self-taught script-coders all the time:

Why initialise a variable if it will come in to existence anyway?

Why check if something exists before we use it, undefined equates to false anyway?

If I prefix with @ it fixes my code, why complicate things?

If they have never experienced a strongly-typed language, or experienced the pitfalls of undeclared/uninstantiated variables, then they take some convincing.  I find they usually give in once they have experienced the pleasure of debugging code for an hour or so to find it was a typo in a variable name causing the trouble.

The other strong factor is PHP's use in the web industry, which tends to be far more concerned with throughput than safety and code quality.


问:
When is it a good time to reason about performance in Haskell?
Simon Peyton Jones himself recognizes that reasoning about performance in Haskell is hard due to the non strict semantics.

I have yet to write a significant project in haskell so I wonder: can I reason about performance only at the beginning of a project (when choosing basic data structures & IO library) and whenever a problem arise, deal with it with the profiler?

To put it differently, is it possible (ie not too painful) to postpone dealing with performance when you have performance issues, or do you have to learn to predict how GHC will run your code (for exemple: infer what the strictness analyser will decide)?

答:
The other answers provide broad advice about performance reasoning.  This answer specifically addresses non-strict semantics.

While laziness does make it harder to reason about performance, it isn't as complicated as you might think.  Although laziness is quite useful in some situations, most of the time a lazy language gets used in the same way that a strict language would be used.  Consequently, performance reasoning for strict languages can be applied (with a few adjustments) to lazy languages.

In terms of time complexity, eager evaluation does strictly more work than lazy evaluation.  Both strategies produce the same result in most cases.  (More precisely, if eager evaluation doesn't run into any errors, it produces the same result as lazy evaluation.)  Therefore, to reason about the time complexity of a Haskell program, you can pretend that it evaluates eagerly.  In those infrequent situations where laziness matters, this estimate will be too high and should be revised downwards.

While lazy evaluation gives you lower time complexity than eager evaluation, it sometimes gives you higher space complexity, i.e. space leaks.  Higher space complexity can be fixed by adding strictness annotations to make a program execute more eagerly.  Profiling tools are pretty good at tracking down the cause of space leaks.  I'd categorize this as either correctness debugging or performance debugging, depending on the severity.


问:
Has whitespace in identifiers ever been idiomatic?
C# style suggests using CamelCase in identifiers to delimit words. Lisp tradition suggests using-dashes-instead.

Has there ever existed a programming language where using spaces in identifiers was not only allowed, but a commonly used idiom when employing multi-word identifiers?

It's possible to have identifiers with spaces in some Scheme implementations, but it's not a widely seen practice. Here's an example:

```<code>Petite Chez Scheme Version 8.4
Copyright (c) 1985-2011 Cadence Research Systems

> (define |hey there| 100)
> (define |x y z| 200)
> (list |hey there| |x y z|)
(100 200)
</code>```

答:
Powershell allows spaces in variable names:</p>

```<code>PS C:\> ${the var} = 100

PS C:\> ${the var}
100
</code>```

Body:
Powershell allows spaces in variable names:

PS C:\> ${the var} = 100

PS C:\> ${the var}
100


问:
Why was strict parsing not chosen for HTML?
I have often wondered why strict parsing was not chosen when creating HTML. For most of the Internet history, browsers have accepted any kind of markup and tried their best to parse it. The process degrades performance, permits people to write gibberish, and makes it difficult discontinue obsolete features.

Is there a specific reason why HTML is not strictly parsed?

答:
The short of it would be that HTML was based on another non-hyperlinked markup language called SGML often used for documentation and manuals and the like.

From an article about the history of HTML:

Tim had mentioned that some of the early HTML documents were based on an old SGML language that CERN was already using:- We have included in HTML some tags from the SGML tagset used at and once supported at CERN [...] The HTML parser will ignore tags which it does not understand, and will ignore attributes which it does not understand of CERN-SGML tags.

[...] most of the early HTML tags were actually taken from the CERN SGMLGuid language, which itself was a variant of AAP (an early SGML language). For example, title, hn, p, ol and so on are all apparently taken from this language. The only radical change was the addition of the all important anchor () link, without which the WWW wouldn't have taken off.

Taking note of the part I've bolded, basically, they implemented a subset of the tags available in the SGML system they were familiar with, adding the new anchor  tag, and choosing to ignore any of the many tags they didn't care about or wish to support for wahtever reason (such as tags for bibliography lists, xmp for "example", "box" tag to draw a box around a block of text, etc). So the simplest way to do that is to be forgiving of markup that is not known by the parser and ignore unknown markup as best as possible, regardless of whether the cause is user typed bad markup, or the quickest easiest way to convert existing documents to this new HTML format is to add some hyperlinks to existing SGML documents, and ignore whatever tags aren't supported or implemented.

Body:
The short of it would be that HTML was based on another non-hyperlinked markup language called SGML often used for documentation and manuals and the like.

From an article about the history of HTML:

Tim had mentioned that some of the early HTML documents were based on an old SGML language that CERN was already using:- We have included in HTML some tags from the SGML tagset used at and once supported at CERN [...] The HTML parser will ignore tags which it does not understand, and will ignore attributes which it does not understand of CERN-SGML tags.

[...] most of the early HTML tags were actually taken from the CERN SGMLGuid language, which itself was a variant of AAP (an early SGML language). For example, title, hn, p, ol and so on are all apparently taken from this language. The only radical change was the addition of the all important anchor () link, without which the WWW wouldn't have taken off.

Taking note of the part I've bolded, basically, they implemented a subset of the tags available in the SGML system they were familiar with, adding the new anchor <a> tag, and choosing to ignore any of the many tags they didn't care about or wish to support for wahtever reason (such as tags for bibliography lists, xmp for "example", "box" tag to draw a box around a block of text, etc). So the simplest way to do that is to be forgiving of markup that is not known by the parser and ignore unknown markup as best as possible, regardless of whether the cause is user typed bad markup, or the quickest easiest way to convert existing documents to this new HTML format is to add some hyperlinks to existing SGML documents, and ignore whatever tags aren't supported or implemented.


问:
Public-key cryptography security given NSA resources
I was wondering how secure public private key encryption methods are.

If two individuals were sending emails back and forth forever, where each person would encrypt the body of the email they were sending with the other person's public key, would anyone be able to decrypt the body of those emails after a while?

I'm assuming that each person creates their own private-public key pair and then if you wanted to send someone an email you would grab their public key and encrypt your message before sending it to them. They would then decrypt it with their own private key.

Wikipedia (http://en.wikipedia.org/wiki/Public-key_cryptography) claims that its effectively impossible to decrypt email if all you know is the public key. But is this really true? What if you had the resources of the NSA, are they not able to brute force the decryption?

答:
Modern public-key cryptography is impossible to brute-force.  And since that's a rather vague claim, let's be specific:  If you had a computer that was so advanced that it had hit the upper bounds of physical possibility and there was no room for improvement left in Moore's Law, you could give it the task of brute-force cracking a message encrypted with 256-bit encryption, and it wouldn't be anywhere even close to finishing before the sun burned out.  2^256 is a very, very large number.

This doesn't mean that it's impossible to read encrypted messages.  You just need to have a better way of doing it than that.  The two main possibilities are to attack it using a mathematical flaw in the cryptography, which would make the cryptanalysis process much faster than brute force, or to find some way (such as with a virus) to get ahold of the sender's private key.


问:
How do you name your private variables in C#?
What is the best practice, most commonly accepted naming conventions for private variables in C#?

private int myInteger;

private int MyInteger;

private int mMyInteger;

private int _myInteger;

private int _MyInteger;

Mysterious other option

Which do you use and why?  (My company is fairly new to C# and I would like to pick the most "industry accepted" method to try and get into our coding standard.)

答:
private int integer

If you get confused between member and local variables in a method scope then you probably need to refactor.


答:
Bayes' Theorem

It has probably contributed the most to keeping the amount of time-wasting spam in my inbox to a manageable level.

Of course, I'm it has been used in numerous other worthwhile applications, but SPAM-killing is my favorite.

Title: Which are the significant algorithms for humankind in past decades?

Body:
Which world most important algorithms have contributed most to humankind in past decades?

I thought this is a good general knowledge for a developer to know about.

Update:

If possible, please keep the answer to a specific programming algorithm.

I would like to get a list of the most important ones, only one algorithm per answer.

Please consider to state why the algorithm is significant and important...


答:
Everyone is able to brute force the decryption, it's just a matter of how long.

The question/concern you should have is if the NSA (or whomever) has done something to change the algorithmic complexity of the encryption itself (either by finding a mathematical shortcut or something like quantum computing that circumvents usual limitations or of course, attacking the security of your private key).

Title: Public-key cryptography security given NSA resources

Body:
I was wondering how secure public private key encryption methods are.

If two individuals were sending emails back and forth forever, where each person would encrypt the body of the email they were sending with the other person's public key, would anyone be able to decrypt the body of those emails after a while?

I'm assuming that each person creates their own private-public key pair and then if you wanted to send someone an email you would grab their public key and encrypt your message before sending it to them. They would then decrypt it with their own private key.

Wikipedia (http://en.wikipedia.org/wiki/Public-key_cryptography) claims that its effectively impossible to decrypt email if all you know is the public key. But is this really true? What if you had the resources of the NSA, are they not able to brute force the decryption?


问:
Helper Methods Placement
Here's a question that's always bugged me. I'm going to use java as an example because I've almost never run into a problem in java where I didn't need to use helper methods in its class structure.

Let's say I have a method that does a thing or two and then calls a helper method:

```<code>public void doStuff() {
    int x = 4;
    int y = 5;
    doStuffHelper(x, y);
}
</code>```

Now I need to create a private method, doStuffHelper, that doStuff calls with x and y. For readability I always put the helper directly above or below the function, but I can never quite decide which one is better. What are your thoughts/experiences with it?

I know the question seems trivial, but since I don't have any guiding principles on it, I find that it always kills coding time deciding what to do and re-organizing my code if it doesn't work out. If there is no consensus, I think it's time to finally commit to one over the other for me.

答:
Ordering functions is a valid and important concern, and some schemes work better than others.  Like comments and @Lachlan suggested, putting the fundamental aspects of the class earlier often makes the most sense.

I often prefer to see static things precede instance things, and public before private.  I prefer to see data and creational things before I see task things.  Specifically, I prefer to see constructors, initialization, getters and setters, and then task methods.  I try to often put helper functions immediately following the first function that uses it, instead of dropping them to the bottom.  Why this basic order?

Constructors:  before anything can be done with an object, it has to be created.  Like with getters and setters, I want to know right away if there is something different about how the object handles its construction, and what if any other side-effects might occur from the various methods of construction (do they all explicitly initialize, or only in certain cases?).

Initialization: what setup is done for me, and what do I likely need to provide to actually do something useful with this object

Getters and setters: I want to know early on if there is anything peculiar about how values are read or written.  Are they using any kind of multi-threading lock to restrict access that could skew how I would normally anticipate the getter or setter working?  Are they accessing the backing store in a non-standard way, like using an indexed array or collection of values instead of a discreet variable? Or are they writing changes to a database as the property is changed [, from within the property]?  And what other side-effects might occur from changing or accessing underlying state?

Task functions:  these are the functions that define the primary responsibility of the class or module.  As I mentioned, I like to put the helper methods that are explicitly part of the class, nearest to where they are first, or likely to first be used.

As you arrange those 'extra' functions with the primary task functions, you should always keep the following question in mind:  How does this helper function relate to the one responsibility and one reason to change for this class?

Extra [private] functions are inevitable in the course of refactoring functions down to their primary purpose, but beware that some of those extra functions may be violating the Single Responsibility Principle (SRP) and "one reason to change" for the class.

The case may be that helper functions deserve a class of their own, perhaps several.  One way to approach evaluating whether a function stays or moves on to its own home is by looking at cohesion.  Are the parameters the function accepts, and the internal values it manipulates, variables that are fundamental to the class?  Are they variables that are commonly used throughout the rest of the class, or are they mostly only used by a very small number of secondary functions?  If the function doesn't use, or only uses a few of those class variables or internal state, then it may indicate low cohesion and a strong candidacy for promotion to a separate class, and a slightly different method of invoking that helper method.

A fairly common example of where this occurs is with objects that have formatting helpers, or input and output helpers.  Helpers that do a conversion of the objects representation to or from the representation maintained by the model are usually good candidates for their own formatting class.  Normally, an object shouldn't have the responsibility of loading or saving it's own state, as they bleeds the implementation details into the model.  Such activity often is indicated by words or pairings such as:

from or to

convert or configure or transform

read or write

load or save

play or record

launch or suspend (and possibly reset depending on the class/context)

Many languages and frameworks often have some built in methods for converting the internal representation of an object's state to another base form.  Often it takes the form of 'to string' or some slight variation of this.  Usually this is provided for two reasons: to simplify certain aspects and expectations of the platform and for convenience.  It is a license to moderately over-ride and extend the method so that a base representation of a complex object can be communicated to the rest of the framework, but it shouldn't be treated as a license to give a class more responsibility than it needs.

Title: Helper Methods Placement


答:
Well we tried to establish a nice strict option in the 000s but it didn't pan out because people following "best practices" blindly, blamed the browsers when their incorrect markup went to pieces in strict mode. And the browser vendors didn't like being blamed.

They claimed it was because they wanted the web more accessible to non-professionals but nobody was being stopped from using HTML 4 in its most lenient form.

That said, you can still serve HTML5 as XML if you desire strict-style layout. IMO it can be a good way to reap the benefits of doing layout or UI work in a stricter mode before you pass it on to other people who may or may not want it as strict without any real risks (barring them ripping the doctype out because they actually favor quirks mode - in 2017 (the time of this edit) they should be shot. So it's still there basically but do some research. I seem to recall there being some caveats that we didn't have with XHTML that didn't really impact layout work. Just don't spread the word that it's "the only way to do it right" or the twits who buy into that kind of talk will dogpile the idea, blame the browsers again, and they'll take the teeth out of the only strict alternative we have left. (2017 edit: I have no idea whether this still works - gave up)

http://mathiasbynens.be/notes/xhtml5

Title: Why was strict parsing not chosen for HTML?

Body:
I have often wondered why strict parsing was not chosen when creating HTML. For most of the Internet history, browsers have accepted any kind of markup and tried their best to parse it. The process degrades performance, permits people to write gibberish, and makes it difficult discontinue obsolete features.

Is there a specific reason why HTML is not strictly parsed?


问:
Recompiling a java project while it is running
I have a Java program that takes about an hour to run. While it is running, if I change the source code and recompile it, will this affect the above run?</p>

答:
If the "while it is running" is a requirement, you need to be looking at dynamic loading of class files.  Application servers support this type of structure - after all, it is how you do a redeployment of an application without stopping and starting the server.

You start getting things like How to dynamically reload classes when class files are changed in WebSphere Portlet Factory and designing the application correctly (see Dynamic Class Loading and Reloading in Java).

Dynamic loading of classes isn't the best idea - especially if done frequently.  The reason is that the class itself is loaded into permgen in the vm (this depends on the jvm (see when do classes in jars enter the PermGen) - repeatedly reloading a class means you will be leaking the memory of the unused classes.  (See Classloader leaks: the dreaded "java.lang.OutOfMemoryError: PermGen space" exception - a bit dated, but still useful).

This assumes you want to load it on the fly.  If it is "I don't want to stop for an hour while I recompile" there are other solutions.

A build shouldn't take an hour to build if you change one class file.

In days of old, one used make to do partial compliation.  Consider the

```<code>$ ls
Makefile    bar.c       foo.c
$ make all
cc -c bar.c
cc -c foo.c
$ make all
make: Nothing to be done for `all'.
$ touch bar.c
$ make all
cc -c bar.c
$ cat Makefile
all: bar.o foo.o

bar.o: bar.c
    cc -c bar.c

foo.o: foo.c
    cc -c foo.c
$
</code>```

It will only compile things that have changed.  If you change one file, it only compiles one file.

So, only build the .class you need, or the .jar you need rather than the entire project.  If it isn't organized that way, organize it so that you can just compile the parts you need.

This way, you won't need an hour to recompile everything - just a minute to recompile what you need.

Body:
If the "while it is running" is a requirement, you need to be looking at dynamic loading of class files.  Application servers support this type of structure - after all, it is how you do a redeployment of an application without stopping and starting the server.

You start getting things like How to dynamically reload classes when class files are changed in WebSphere Portlet Factory and designing the application correctly (see Dynamic Class Loading and Reloading in Java).

Dynamic loading of classes isn't the best idea - especially if done frequently.  The reason is that the class itself is loaded into permgen in the vm (this depends on the jvm (see when do classes in jars enter the PermGen) - repeatedly reloading a class means you will be leaking the memory of the unused classes.  (See Classloader leaks: the dreaded "java.lang.OutOfMemoryError: PermGen space" exception - a bit dated, but still useful).

This assumes you want to load it on the fly.  If it is "I don't want to stop for an hour while I recompile" there are other solutions.

A build shouldn't take an hour to build if you change one class file.

In days of old, one used make to do partial compliation.  Consider the

$ ls
Makefile    bar.c       foo.c
$ make all
cc -c bar.c
cc -c foo.c
$ make all
make: Nothing to be done for `all'.
$ touch bar.c
$ make all
cc -c bar.c
$ cat Makefile
all: bar.o foo.o

bar.o: bar.c
    cc -c bar.c

foo.o: foo.c
    cc -c foo.c
$

It will only compile things that have changed.  If you change one file, it only compiles one file.

So, only build the .class you need, or the .jar you need rather than the entire project.  If it isn't organized that way, organize it so that you can just compile the parts you need.

This way, you won't need an hour to recompile everything - just a minute to recompile what you need.


答: Authorware, whose scripting language was based on non-object-oriented Pascal, allowed spaces in variable names, though over time people discovered the problems with using them and moved away from it http://books.google.com/books?id=bHC88YignAkC&pg=PA428&lpg=PA428 .</p>

Title: Has whitespace in identifiers ever been idiomatic?

Body:
C# style suggests using CamelCase in identifiers to delimit words. Lisp tradition suggests using-dashes-instead.

Has there ever existed a programming language where using spaces in identifiers was not only allowed, but a commonly used idiom when employing multi-word identifiers?

It's possible to have identifiers with spaces in some Scheme implementations, but it's not a widely seen practice. Here's an example:

```<code>Petite Chez Scheme Version 8.4
Copyright (c) 1985-2011 Cadence Research Systems

> (define |hey there| 100)
> (define |x y z| 200)
> (list |hey there| |x y z|)
(100 200)
</code>```


答:
I saw mention of similar for VB but in JS this is used a lot actually. Any property of an object in JavaScript can be accessed and set in string form with square brackets or simply as strings in object literals. Property names that don't follow JS's variable naming rules are inaccessible via . notation but they are handy. For instance, you might want to map URLs to behavior or reference a group of people by name when you're certain they're all unique. It's often very convenient and easy to read:

```<code>var peoplesFavoriteThings = {
    "Bob Jones":"kittens",
    "Jane Doe":"chainsaws"
}

for(var name in peoplesFavoriteThings){
    console.log(name + ' likes ' + peoplesFavoriteThings[name] + '.\n');
}
</code>```

This also makes it easy to restructure JSON for ease of use without losing the instant-object factor when dropped into JS.

Body:
I saw mention of similar for VB but in JS this is used a lot actually. Any property of an object in JavaScript can be accessed and set in string form with square brackets or simply as strings in object literals. Property names that don't follow JS's variable naming rules are inaccessible via . notation but they are handy. For instance, you might want to map URLs to behavior or reference a group of people by name when you're certain they're all unique. It's often very convenient and easy to read:

var peoplesFavoriteThings = {
    "Bob Jones":"kittens",
    "Jane Doe":"chainsaws"
}

for(var name in peoplesFavoriteThings){
    console.log(name + ' likes ' + peoplesFavoriteThings[name] + '.\n');
}

This also makes it easy to restructure JSON for ease of use without losing the instant-object factor when dropped into JS.


答:
I don't like blanket all or nothing recommendations. On those terms alone I'd say no.

Do consider any practice case by case. No silver bullets.

Only create a default constructor if you have a need for it. YAGNI is a better coding convention.


问:
Should a software company have a dedicated team for research and/or utility libraries?
I work in a company that does web applications for various banks and some smaller e-shops
We employ about 20 developers and have 4-5 projects in development at any one time.
Our development teams don't interact much and a lot of the same problems are done in varied ways(good to bad).

I was wondering if it would be a good idea for a company to have a team of programmers that do research on current frameworks and continually improve a common library of functions and a common framework to build current and future projects much faster and more efficiently.

How large should a team like this be?

Also should it have permanent members that train others or should it rotate people?

Update: I was thinking about a common project that people can work on for fun that might spark some interest. It seems that when people have job pressures the solutions they come up with are not the best.

答:
The saying "Eating your own dog food" address this issue. If your top-cool-rockstar-coder gives birth to a library he never used in practice, how can he say that it is a good one?

The main reasons to develop functionalities into framework are

1.It is useful to the developper

2.There are a few cases where it has been useful

3.It might be useful to others

When you've hit 2, the functionality is already there, how can you pass it to someone else?


问:
Why would a developer create a public class that has all static properties?
A previous developer has a couple public classes that do not inherit from any other classes but are filled with static properties. Is this another way of creating a struct or enum? Is this an older or newer technique of housing static data to be referenced? I find it odd/different to see a class built in this way but am wondering what other fellow programmers thoughts or feelings are about what this coder was trying to accomplish.

This is a made up example of what I am seeing...

```<code>    public class CashRegister
    {
        public static decimal OneDollarBill
        {
            get { return (decimal)1; }
        }

        public static decimal TenDollarBill
        {
            get { return (decimal)10; }
        }
    }
</code>```

答:
I think the main reason in this case is to add semantics to the code. It's about code readability.

Instead of code looking like:

```<code>CashRegister.Add(1 + 10)
</code>```

It now looks like:

```<code>CashRegister.Add(OneDollarBill + TenDollarBill)
</code>```

(not saying this has high value, just thinking this might have been the reasoning).

Body:
I think the main reason in this case is to add semantics to the code. It's about code readability.

Instead of code looking like:

CashRegister.Add(1 + 10)

It now looks like:

CashRegister.Add(OneDollarBill + TenDollarBill)

(not saying this has high value, just thinking this might have been the reasoning).


问:
Representational Equality versus Value Equality
I am coding a system where I have objects which represent a set of resources. These resources are identifiable (they have an ID). There can only be one resource with the same ID, and so multiple objects with the same ID really should have the same values.

My problem is with the equality concept in this case. Should it be based on the ID or on the values alone? Is object A = object B because they have the same ID OR should object A == object B because their fields are the same.

One possibility I was thinking of was to have the ID-based comparison be "equals" and the field-based comparison be "equivalent". Alternatively I could have it so the field-based comparison was "equals" and the ID based comparison was "representSameObject" (or something). Just a pseudo-code example:

```<code>class A {
   String uuid;
   int field1;
   double field2;
   List<String> listField;

   @Override
   public boolean equals(Object other) {
       return uuid.equals(other.uuid);
   }

   public boolean equivalent( other ) {
       if (this == other) {
           return true;
       }
       if (null == other) {
           return false;
       }
       if (other.getClass() != this.getClass()) {
           return false;
       }

       A rhs = (A) other;
       return new EqualsBuilder().append(field1, rhs.field1).append(field2, rhs.field2).append(listField, other.listField).isEquals();
   }
}
</code>```

In the end this may come down to a personal preference coupled with system requirements, but I am very interested to learn how others have approached this concept. It has been annoying the heck our of me since I started on this project!

If it makes a difference I am programming at the minute in Java. I don't mind where the answer comes from though as this is obviously a conceptual issue.

答:
If Bob is now wearing a blue hat instead of red hat (the one he was wearing yesterday) he is still Bob. So blue hat Bob equals red hat Bob.

I stick to keeping my equals to being identity based. Wether Bob has changed I keep in a different method or interface.


问:
Is there a setting to enable anti forgery globally in ASP.NET MVC, and if not, why?
The tutorials I've read tell you to use [ValidateAntiForgeryToken] attributes and <%= Html.AntiForgeryToken() %> in your code.

I was wondering why this isn't a built-in automatic setting or at least a global toggle in the web.config. Perhaps it is, and I haven't realised, but I am doing it by hand and I can't help but wonder if there is a good reason for not handling it automatically behind the scenes. Any ideas?

答:
I think in most cases it doesn't really matter if a form was issued by your server or not.

Anti-forgery tokens require session state on the server. When a user session expires so will the forms they have open, they become unpostable. Can be pretty annoying.


问:
Are there languages that expand on the STL's iterator types?
Many languages use the concept of an iterator. The c++ STL expands on this with input iterators, output iterators, forward, bidirectional, random access and others. As far as I know, these distinctions don't exist in other languages. In this talk the author of the STL, Alexander Stepanov, talks about iterators (among other things), and mentions the idea and of 2-dimensional iterators. I haven't seen these anywhere.

Question 1: Are there other languages/ libraries that expand on iterators and/or use 2-dimensional iterators?

Question 2: Could anyone point me to some good resources on iterator theory (if that is what it's called)?

答: Re question 2: see chapter 6 (Iterators) of Elements of Programming by Alexander Stepanov (the author of STL) and Paul McJones (me) for the theory of iterators. Re question 1: see chapters 7 (Coordinate Structures) and 8 (Coordinates with Mutable Successors) of the same book for some generalizations of iterators to data structures with more complex shapes than immutable linear shapes.


问:
Declare variable as interface
When should or shouldn't a variable be declared as a custom Interface type?

When walking through some code, I required to know what was happening here:

```<code>Public Class MyMainProject
    ....
    Public Sub DoMyWork()
        Dim objIMyInterface As IMyInterface
        ....
        objIMyInterface = GetReturnObject()
    End Sub
    ....
End Class
</code>```

According to what I saw, objIMyInterface is only being used for one thing.  I didn't know how many classes implement it, but there's no casting of similar types in this code. objIMyInterface is used just like a regular type, not anonymous in the least.  Second of all, my research helped a little...

GetReturnObject happens to return an instance of IMyInterface.  The return object of GetReturnObject, of course, has a call to another method.

```<code>Public Function GetReturnObject() As IMyInterface
    Dim retObject As IMyInterface
    ...
            retObject = AnotherMethod()
    ...
    Return retObject
End Function
</code>```

So I try to step into AnotherMethod, but it's in a project with no symbols.  So after some research, I find the source and go through it.  After repeating this process a few times, I eventually get to something like this:

```<code>Public Function FinalMethod() As IMyInterface
    Dim FinalObject As MyClassType
    ...
            FinalObject = GetMyClassType()
    ...
    Return FinalObject
End Function
</code>```

Yay!  GetMyClassType returns MyClassType!  I go to that Class and of course:

```<code>Public Class MyClassType
    Implements IMyInterface
    ...
End Class
</code>```

What I end up finding out is that IMyInterface is used by nothing else but this class.  No biggie, it's all good code by the looks of it.  But then I go back to my original project I notice this:

```<code>Public Class MyMainProject
    ....
    Public Sub DoMyWork()
        Dim objIMyInterface As IMyInterface
        ....
        objIMyInterface = GetReturnObject()
    End Sub
    ....
    Public Sub OtherWork()
        Dim objMyType As MyClassType
        ....
    End Sub
    ....
End Class
</code>```

The guy who created this is long gone, but I'd like to know what your thoughts are on which method should be used.  Should I declare both as IMyInterface?  Or both as MyClassType?  The code works fine either way.

答:
Perhaps the programmer creating the interface thought it would be an abstraction that would get some reuse (multiple implementations) somewhere in the future (YAGNI though, it's better to wait for reuse and then refactor to abstractions).

He might have created the interface so he could create mock objects around it to use in unit tests. Creating interfaces purely for testing purposes is controversial to some (it initially was for me).

Interfaces are sometimes useful to formulate calls and requests from caller's perspective. Even if there is only one implementation that can respond it may still be useful semantically or conceptually. It may also shield the implementing class' public interface, perhaps used from other perspectives.

Title: Declare variable as interface


答:
For an interface with a single implementing class, using both the interface and the concrete class in a consuming class is wrong UNLESS the interface does not include all of the properties/methods of the concrete class.

Choose one or the other, and unless it's needed/helpful for testing or only exposes a subset of the functionality of the class, drop the interface.

And not just in this class, everywhere.  An interface is used to abstract properties/methods from a concrete class, allowing several classes to be used interchangeably.  If there are no other classes, and there is no likely hood of other classes, then an interface is an unnecessary abstraction.  Unnecessary abstractions should be avoided.

Title: Declare variable as interface

Body:
When should or shouldn't a variable be declared as a custom Interface type?

When walking through some code, I required to know what was happening here:

```<code>Public Class MyMainProject
    ....
    Public Sub DoMyWork()
        Dim objIMyInterface As IMyInterface
        ....
        objIMyInterface = GetReturnObject()
    End Sub
    ....
End Class
</code>```

According to what I saw, objIMyInterface is only being used for one thing.  I didn't know how many classes implement it, but there's no casting of similar types in this code. objIMyInterface is used just like a regular type, not anonymous in the least.  Second of all, my research helped a little...

GetReturnObject happens to return an instance of IMyInterface.  The return object of GetReturnObject, of course, has a call to another method.

```<code>Public Function GetReturnObject() As IMyInterface
    Dim retObject As IMyInterface
    ...
            retObject = AnotherMethod()
    ...
    Return retObject
End Function
</code>```

So I try to step into AnotherMethod, but it's in a project with no symbols.  So after some research, I find the source and go through it.  After repeating this process a few times, I eventually get to something like this:

```<code>Public Function FinalMethod() As IMyInterface
    Dim FinalObject As MyClassType
    ...
            FinalObject = GetMyClassType()
    ...
    Return FinalObject
End Function
</code>```

Yay!  GetMyClassType returns MyClassType!  I go to that Class and of course:

```<code>Public Class MyClassType
    Implements IMyInterface
    ...
End Class
</code>```

What I end up finding out is that IMyInterface is used by nothing else but this class.  No biggie, it's all good code by the looks of it.  But then I go back to my original project I notice this:

```<code>Public Class MyMainProject
    ....
    Public Sub DoMyWork()
        Dim objIMyInterface As IMyInterface
        ....
        objIMyInterface = GetReturnObject()
    End Sub
    ....
    Public Sub OtherWork()
        Dim objMyType As MyClassType
        ....
    End Sub
    ....
End Class
</code>```

The guy who created this is long gone, but I'd like to know what your thoughts are on which method should be used.  Should I declare both as IMyInterface?  Or both as MyClassType?  The code works fine either way.


答: The class you posted could indeed be replaced by an enum. However, there are some situations a developer might want to use a class of static properties, for example if they needed to execute code in get{} (do some calculations based on other variables, etc.) and/or they wanted the value to be changeable via set{}.</p>

Title: Why would a developer create a public class that has all static properties?

Body:
A previous developer has a couple public classes that do not inherit from any other classes but are filled with static properties. Is this another way of creating a struct or enum? Is this an older or newer technique of housing static data to be referenced? I find it odd/different to see a class built in this way but am wondering what other fellow programmers thoughts or feelings are about what this coder was trying to accomplish.

This is a made up example of what I am seeing...

```<code>    public class CashRegister
    {
        public static decimal OneDollarBill
        {
            get { return (decimal)1; }
        }

        public static decimal TenDollarBill
        {
            get { return (decimal)10; }
        }
    }
</code>```


答: Even for the NSA, brute forcing an algorithm like RSA isn't feasible. There's always the very, very remote possibility the NSA/CIA/etc has discovered an exploit in RSA and managed to keep it a secret (See relevant xkcd comic) but it's much more likely that if the RSA needed to obtain a private key they would try to get it through a man-in-the-middle attack, social engineering, or infecting a computer where the private key is stored (Microsoft and others give the NSA information on unpatched exploits) rather than trying to break the encryption itself.</p>


问:
Tests for emptiness vs tests for nothingness
Is there any consensus between languages how tests for emptiness are distinct from tests for noneness? In python the following expression is false:

{} is {}

However this expression evaluates to True

False is False

Why is the first expression not evaluated to True?

答:
I think the part you missed is what "is" keyword actually does.

"is" tests references, or "identity" of an object.  {} is an empty dictionary, expression "{} is {}" creates two empty dictionary.  Their values are "equal" but their identities are not because those two dictionaries reside in different locations in memory as dictionary is an object which is created dynamically.

"False is False" works because it is a constant, so both of those values refer to the same block of memory. Since it makes no sense for Python to allocate different memory blocks every time it sees "False" in the code.


问:
Javascript modularity, server based MVC & business reality
I understand this is a very broad question, but I have worked with various aspects of this problem individually and am struggling to bring all the concepts and technologies together.

I'd like to specify that answers should include these technologies:

C#

MVC 3 w/ Razor

Javascript w/jQuery

Anything above and beyond those (such as Backbone.js, Entity Framework, etc) are welcome as suggestions if they help answer the question which is:

Using the above listed technologies, what is an optimal strategy for organizing code and logic while maintaining scalability and the ability to create a rich, fast, clean UI?

Ideally the focus should be put on a solution being deployed in a business/corporate environment.  On that note, the technologies list above will not be changed so please don't offer solutions with "you should be using xxx instead of yyy that you are using now".

Background

I work with jQuery everyday, have adopted ASP.NET's MVC and have been working with C# for a long time.  So you can present solutions assuming intermediate-to-advanced knowledge of those technologies.

I'll organize the question into smaller parts to make it simpler to respond to:

1. Project structure

Given I am working with ASP.NET MVC (in Visual Studio 2010) I would like a directory structure solution that offers some acceptance of the main layout this type of application.  Something like Brunch I suppose, but with a little more detail of what each folder would contain and how it works with other areas of the app.

2. Data access

I'd like to modularize my data access as much as I can, with an API-type structure.  You can assume lots of POCO objects (User, UserGroup, Customer, OrderHeader, OrderDetails, etc), but there will also be some complex reports that require data intensive SQL and careful UI rendering.  EF + LINQ are fantastic for the former but not so much for the latter.  I can't find something that seems to fit both scenarios without being overly complicated or overly simple.

3. Client-Side Code Organization and UI Rendering

Like most developers first picking up jQuery, I fell into the trap of mashing together code wherever it needed to go but quickly found it piling up and turning ugly.  Although I've come leaps and bounds since then, I still struggle with modularizing my code and working with various parts of the UI without repeating code.

As an example, a typical piece of code I might write would look like this, I have commented the stuff that bothers me (note that I've since changed to using deferred AJAX calls and separated the actual data requests from the DOM manipulation):

```<code>$('#doSomethingDangerous').click(function () {
    // maybe confirm something first
    if (confirm('Are you sure you want to do this?')) {

        // show a spinner?  something global would be preferred so I don't have to repeat this on every page
        $('#loading').show();

        // maybe the page should notify the user of what's going on in addition to the dialog?
        $('#results').show().html('<h2>Please wait, this may take a while...</h2>');

        $.ajax({
            url: 'blah/DoDangerousThing',
            success: function (data) {
                // The results will be loaded to the DOM obviously, is there a better way to pull this type of specific code out of the data access calls?
                $('#results').empty();
                $('#results').append('<b>' + data.length + '</b> users were affected by this dangerous activity');
                $('#results').append('<ul>');

                // I've recently started to use jQuery templates for this sort of logic, is that the way to go?
                $(data).each(function (i, user) {
                    $('#results').append('<li>' + user.Username + '</li>');
                });
                $('#results').append('</ul>');

                // Need to hide the spinner, again would prefer to have this done elsewhere
                $('#loading').hide();
            }
        });
    }
});
</code>```

General Questions

Client MVC vs. server MVC?  My project is already a server-side MVC structure, so is there still a need for client MVC like Backbone.js provides?

Should Javascript files get created for each object (like an OrderHeader.js) and then minified/merged during the build?  Or should there just be an Order.js which has logic for OrderHeader, OrderDetails, Reports etc?

How should complex queries be handled?  Right now my leading theory is /Reports/Orders-By-Date/ or something along those lines and I use a custom SQL query that renders a custom dataset (or ViewModel) to the Razor View.  But what about paging, sorting, etc?  Is this better to be done client or server side?  (assume larger dataset - 2 to 3 second SQL query)

I've read through Microsoft's Project Silk.  Is this a good way to go?  How does it compare to Backbone.js or others?

I'm very accustomed to an N-tiered architecture, do these concepts somewhat throw that out the window?  It seems MVC is like a bunch of mini N-tiered sections within what would have been the front-end or top tier in the past.

Again the more specific your answers are the better they will be.  I've read a lot of high level documentation and examples, I'm trying to better understand translating it into real world examples.

答:
Not sure how I missed this question but I'll add my two cents two years later.

Client MVC vs. server MVC? My project is already a server-side MVC
  structure, so is there still a need for client MVC like Backbone.js
  provides?

MVC and MV? even before it got pushed to the client-side has basically de-evolved into a marketing term that really only promises that somehow data will be separated from other stuff which is by and large a great idea but not really that hard to DIY. No matter what approach you're taking, just before or right in the middle of making changes to HTML that affects presentation or interaction possibilities is the absolute most awful place to be sorting out what the business wants you to do with the data.

There is nothing special about "view logic." The same principle should apply to all logic. And that is, don't do anything now that would have made a lot more sense to do before now. When all your ducks are in a row before you pass some data or initiate a new process, that previous phase is likely to be much more re-usable to anything else in the system doing something similar.

Should Javascript files get created for each object (like an
  OrderHeader.js) and then minified/merged during the build? Or should
  there just be an Order.js which has logic for OrderHeader,
  OrderDetails, Reports etc?

It's really up to you but I would try to get away from the one-file, one-class thing. I've never understood why it was helpful for instance have to find the abstract file and the interface, and the files implementing, etc... Categorize on broader concerns. ctrl+f ain't that hard to use if it goes a little long.

That said, you should never recombine JS to make files smaller on the web. Browsers cache JS so you're just forcing reloads of the same JavaScript by sticking old JS in new files. Barring staggering amounts of JavaScript, the only time you shouldn't have all the JS on the page is when a very large quantity of it that's highly specific to one section of the site with no overlap/gray areas will never be needed on a given page.

And FFS do not fuss with dependency management with JavaScript on the web. Require.js on medium to low complexity websites makes me want to club baby seals. Stick your third party libraries in a top block. Your in-house libraries in the second block. And then your implementation code (which should never be a tenth as long as your in-house library code - i.e. very succinct and clear and easy to understand ) in that third bock.

How should complex queries be handled? Right now my leading theory is
  /Reports/Orders-By-Date/ or something along those lines and I use a
  custom SQL query that renders a custom dataset (or ViewModel) to the
  Razor View. But what about paging, sorting, etc? Is this better to be
  done client or server side? (assume larger dataset - 2 to 3 second SQL
  query) I've read through Microsoft's Project Silk. Is this a good way
  to go? How does it compare to Backbone.js or others?

Honestly, I'd say whatever is easier for you that doesn't stink for the customer. Web pages load pretty damn fast on modern technology. If implementing in Ajax is a lot of pain for you, don't. Just go with what you know best and then you can get fancy later and see how you like it for paging. If you're building a new complex app from scratch, start with essential and hit neat-o later.

I'm very accustomed to an N-tiered architecture, do these concepts
  somewhat throw that out the window? It seems MVC is like a bunch of
  mini N-tiered sections within what would have been the front-end or
  top tier in the past.

It really depends on whoever's fantasy idea of what MV? is. IMO, the microcosm thing tends to work very well. A class of widget that separates data, communication, and view-related stuff internally works great. On the client-side web, the critical thing, IMO, is to maintain a balance of keeping concerns separated without needlessly fragmenting into tiny little concerns whose reassembly makes it difficult to understand and re-use and modify things. Basic "duh" OOP works great here. You don't want complex processes. You want obviously named things that can be moved around and told to do stuff. Here's a few tips on that front:

KISS that (OOP) interface I don't want to see DOM or jQuery or anything else a pinch-hitting server-side dev couldn't figure out fairly quickly in my implementation code. All that person should have to know is what class to slap on a div container and what switch to flip to make a fairly generic set of UI active on a given page. Variations on a theme should still be accomplished by passing in well-documented/commented options objects before they have to start looking at document.get<anything> or understand anything beyond the barest basics of CSS.

Okay so how do you do that? Well, we have already have a model. It's called the DOM. And we have event delegation. If you're not indiscriminately shutting down event bubbling (don't do that - it's there because it's useful) you can pick up every single even from the body if you want. Then examine the passed event object's target property and determine who just 'whatevered.' If you are structuring an HTML document sensibly there is no reason to not to use it as a delegating model. Behavior and content structure are naturally linked. It's okay for the two to have overlapping identifiers.

Don't Pay For Data-Binding And by "pay" I of course mean "slap a library onto your codebase that insists you do things just-so all the time in order to get some miracle benefit that's actually not hard to DIY." JQ's event system makes it pretty easy.

Example Time:

```<code>function PoliticianData(){ //a constructor

    var
        that = this, //I hate 'that' but example so convention

        flavorsOfLie = {

            lies: "Oh Prism? Psh... no we're all good. There's a guy keeping an eye on that.",

            damnedLies: "50% of the people chose to not give a damn when asked whether it was better to let the terrorists win or not give a damn."

        }
    ;//end instance vars

    this.updateLies = function( lieType, newData ){
        flavorsOfLie[lieType] = newData;
        $(that).trigger({type:'update', lieType:lieType, newData: newData });
    }

    //so everytime you use the updateLies method, we can have a listener respond
    //and pass the data
}

var filthyLies = new PoliticianData();

$(filthyLies).on('update', function(e){
    stickNewDataInHTMLWithSomeFuncDefinedElsewhere(e.lieType, e.newData);
} );

filthyLies.update('damnedLies','50% of the people said they didn\'t give a damn');
//oh look, WaPo's front page just changed!
</code>```

Don't Hide the Web The chief source of suckery in all early attempts at making the client-side easy for server-side and app devs hinged on this critical point. HTTP Requests are not and never were complicated. They didn't require an 18 !@#$ing layer confusing-event-name-at-each-stage monstrosity in order to make it easier to understand. Likewise, there's a lot to know about the client-side but there's no reason to hide from the HTML and the DOM that interacts with it by slapping a big giant model on top of it. It already is a big giant model and it works very well. All we need to make it a bit more manageable is some sensible OOP practices and some JS and DOM knowledge.

Favor Flexibility

EXTjs <====flexibility scale====> jQuery (not necessarily any of its plug-ins)

IMO, tools that let you DIY rapidly are always the better choice. Tools that did it all for you are only the right choice when nobody over your head is being particularly picky about the details and you don't mind ceding control to the very thing that's supposed to be helping you. I've actually seen plug-ins that validate the HTML to make sure you don't sneak a different kind of element with all the same exact display traits in there. Why? I only have theories. I think it boils down to completists really hating the idea of somebody using their stuff in a way that wasn't intended and that's always inevitably what somebody wants you to do in UI.

OwnerDisplayName: TerryR

Body:
Not sure how I missed this question but I'll add my two cents two years later.

Client MVC vs. server MVC? My project is already a server-side MVC
  structure, so is there still a need for client MVC like Backbone.js
  provides?

MVC and MV? even before it got pushed to the client-side has basically de-evolved into a marketing term that really only promises that somehow data will be separated from other stuff which is by and large a great idea but not really that hard to DIY. No matter what approach you're taking, just before or right in the middle of making changes to HTML that affects presentation or interaction possibilities is the absolute most awful place to be sorting out what the business wants you to do with the data.

There is nothing special about "view logic." The same principle should apply to all logic. And that is, don't do anything now that would have made a lot more sense to do before now. When all your ducks are in a row before you pass some data or initiate a new process, that previous phase is likely to be much more re-usable to anything else in the system doing something similar.

Should Javascript files get created for each object (like an
  OrderHeader.js) and then minified/merged during the build? Or should
  there just be an Order.js which has logic for OrderHeader,
  OrderDetails, Reports etc?

It's really up to you but I would try to get away from the one-file, one-class thing. I've never understood why it was helpful for instance have to find the abstract file and the interface, and the files implementing, etc... Categorize on broader concerns. ctrl+f ain't that hard to use if it goes a little long.

That said, you should never recombine JS to make files smaller on the web. Browsers cache JS so you're just forcing reloads of the same JavaScript by sticking old JS in new files. Barring staggering amounts of JavaScript, the only time you shouldn't have all the JS on the page is when a very large quantity of it that's highly specific to one section of the site with no overlap/gray areas will never be needed on a given page.

And FFS do not fuss with dependency management with JavaScript on the web. Require.js on medium to low complexity websites makes me want to club baby seals. Stick your third party libraries in a top block. Your in-house libraries in the second block. And then your implementation code (which should never be a tenth as long as your in-house library code - i.e. very succinct and clear and easy to understand ) in that third bock.

How should complex queries be handled? Right now my leading theory is
  /Reports/Orders-By-Date/ or something along those lines and I use a
  custom SQL query that renders a custom dataset (or ViewModel) to the
  Razor View. But what about paging, sorting, etc? Is this better to be
  done client or server side? (assume larger dataset - 2 to 3 second SQL
  query) I've read through Microsoft's Project Silk. Is this a good way
  to go? How does it compare to Backbone.js or others?

Honestly, I'd say whatever is easier for you that doesn't stink for the customer. Web pages load pretty damn fast on modern technology. If implementing in Ajax is a lot of pain for you, don't. Just go with what you know best and then you can get fancy later and see how you like it for paging. If you're building a new complex app from scratch, start with essential and hit neat-o later.

I'm very accustomed to an N-tiered architecture, do these concepts
  somewhat throw that out the window? It seems MVC is like a bunch of
  mini N-tiered sections within what would have been the front-end or
  top tier in the past.

It really depends on whoever's fantasy idea of what MV? is. IMO, the microcosm thing tends to work very well. A class of widget that separates data, communication, and view-related stuff internally works great. On the client-side web, the critical thing, IMO, is to maintain a balance of keeping concerns separated without needlessly fragmenting into tiny little concerns whose reassembly makes it difficult to understand and re-use and modify things. Basic "duh" OOP works great here. You don't want complex processes. You want obviously named things that can be moved around and told to do stuff. Here's a few tips on that front:

KISS that (OOP) interface I don't want to see DOM or jQuery or anything else a pinch-hitting server-side dev couldn't figure out fairly quickly in my implementation code. All that person should have to know is what class to slap on a div container and what switch to flip to make a fairly generic set of UI active on a given page. Variations on a theme should still be accomplished by passing in well-documented/commented options objects before they have to start looking at document.get<anything> or understand anything beyond the barest basics of CSS.

Okay so how do you do that? Well, we have already have a model. It's called the DOM. And we have event delegation. If you're not indiscriminately shutting down event bubbling (don't do that - it's there because it's useful) you can pick up every single even from the body if you want. Then examine the passed event object's target property and determine who just 'whatevered.' If you are structuring an HTML document sensibly there is no reason to not to use it as a delegating model. Behavior and content structure are naturally linked. It's okay for the two to have overlapping identifiers.

Don't Pay For Data-Binding And by "pay" I of course mean "slap a library onto your codebase that insists you do things just-so all the time in order to get some miracle benefit that's actually not hard to DIY." JQ's event system makes it pretty easy.

Example Time:

function PoliticianData(){ //a constructor

    var
        that = this, //I hate 'that' but example so convention

        flavorsOfLie = {

            lies: "Oh Prism? Psh... no we're all good. There's a guy keeping an eye on that.",

            damnedLies: "50% of the people chose to not give a damn when asked whether it was better to let the terrorists win or not give a damn."

        }
    ;//end instance vars

    this.updateLies = function( lieType, newData ){
        flavorsOfLie[lieType] = newData;
        $(that).trigger({type:'update', lieType:lieType, newData: newData });
    }

    //so everytime you use the updateLies method, we can have a listener respond
    //and pass the data
}

var filthyLies = new PoliticianData();

$(filthyLies).on('update', function(e){
    stickNewDataInHTMLWithSomeFuncDefinedElsewhere(e.lieType, e.newData);
} );

filthyLies.update('damnedLies','50% of the people said they didn\'t give a damn');
//oh look, WaPo's front page just changed!

Don't Hide the Web The chief source of suckery in all early attempts at making the client-side easy for server-side and app devs hinged on this critical point. HTTP Requests are not and never were complicated. They didn't require an 18 !@#$ing layer confusing-event-name-at-each-stage monstrosity in order to make it easier to understand. Likewise, there's a lot to know about the client-side but there's no reason to hide from the HTML and the DOM that interacts with it by slapping a big giant model on top of it. It already is a big giant model and it works very well. All we need to make it a bit more manageable is some sensible OOP practices and some JS and DOM knowledge.

Favor Flexibility

EXTjs <====flexibility scale====> jQuery (not necessarily any of its plug-ins)

IMO, tools that let you DIY rapidly are always the better choice. Tools that did it all for you are only the right choice when nobody over your head is being particularly picky about the details and you don't mind ceding control to the very thing that's supposed to be helping you. I've actually seen plug-ins that validate the HTML to make sure you don't sneak a different kind of element with all the same exact display traits in there. Why? I only have theories. I think it boils down to completists really hating the idea of somebody using their stuff in a way that wasn't intended and that's always inevitably what somebody wants you to do in UI.


答:
The entire internet security is based on the presumption that factoring prime numbers is NP-hard, as it has yet to be proven mathematically that it is (But centuries of looking indicate its not trivial).  If the NSA has figured out a way to do it more efficiently, then RSA is broken.

If the NSA  (or anyone else) have broken RSA - they unlikely to use the exploit on you, as the value of people not knowing they have the ability far exceeds any value you as an individual hold (Read the stories of the allies in WWII letting the Germans 'win some' - at the cost of lives, so as not to tip them off that Enigma was cracked). If they do use the exploit, they will manufacture a plausible story as to how the information was "cracked" by something like guessing the key, exploiting a flaw in the implementation etc This is where the statistics come into play - if the NSA gets lucky a "statistically significant" number of times, it will be noticed, so they need to get lucky just enough not to get noticed.

Other exploits (a gun to your head, a big bag of cash etc) are cheaper and as effective. The NSA is more likely to "persuade" your co conspirator to just give them any info they want....

In summary - If the NSA is interested, you can't be certain you can stop them, and can not be certain that you have succeeded. If you have an unlucky streak, maybe it was the NSA.... Best and only practical bet is not to upset the NSA and end up on their radar....