问:
How to handle encryption key conflicts when synchronizing data?
Assume that there is data that gets synchronized between several devices. The data is protected with a symmetric encryption algorithm and a key. The key is stored on each device and encrypted with a password. When a user changes the password only the key gets re-encrypted.

Under normal circumstances, when there is a good network connection to other peers, the current key gets synchronized and all data on the new device gets encrypted with the same key.

But how to handle situations where a new device doesn’t have a network connection and e.g. creates its own new, but incompatible key? How to keep the usability as high as possible under such circumstances?

The application could detect that there is no network and hence refuse to start. That’s very bad usability in my opinion, because the application isn’t functional at all in this case. I don’t consider this a solution.

The application could ignore the missing network connection and create a new key. But what to do when the application gains a network connection? There will be several incompatible keys and some parts of the underlying data could only be encrypted with one key and other parts with another key.

The situation would get worse if there would be more keys than just two and the application would’ve to ask every time for a password when another object that should get decrypted with another key would be needed.

It is very messy and time consuming to try to re-encrypt all data that is encrypted with another key with a main key. What should be the main key at all in this case? The oldest key? The key with the most encrypted objects? What if the key got synchronized but not all objects that got encrypted with this particular key? How should the user know for which particular password the application asks and why it takes probably very long to re-encrypt the data? It’s very hard to describe encryption “issues” to users.

So far I didn’t find an acceptable solution, nor some kind of generic strategy. Do you have some hints about a concrete strategy or some books / papers that describe synchronization of symmetrically encrypted data with keys that could cause conflicts?

答:
While I don't know of any books/papers that discuss this exact problem,
it seems to me that
any solution to "the synchronization problem",
paired with any solution to "the avoid-re-encrypting-file-with-new-key problem",
should solve your original problem.
Each of those sub-problems have several solutions.

The synchronization problem

You have one "common file" (in this case, a symmetric key)
that, ideally, you want to be the same across all devices.
However, for one reason or another,
the data is somehow different from one device to the next --
split-brain syndrome --
and you want all the devices connected to the network to
somehow reach a consensus as to whether to use version A from now on,
or use version B from now on, or perhaps some entirely new version C from now on.

There are three popular approaches:

Restructure the application to give people the functionality they want, without ever having such a "master key". In this case, the standard approach is to use public-key systems that let every device generate its own unique private key, then generate the public key from the private key, then (somehow) distribute the public keys.

Use some sort of quorum protocol to come to consensus.

Somehow time-tag each version, and when any node discovers that there are two versions, it picks the newest version. (I suppose it could pick the oldest version, but that makes it difficult to upgrade).

One of many possible solutions goes like this:

If the common file does not already exist locally, and I can't seem to connect to any other devices and download the one they are using, go ahead and create a new version of the common file.

Later, when connected to the network and we see other devices, somehow (?) download the version of the common file of each of those other connected devices. If there is at least a quorum of other devices (say, 2 other devices), then start using the version of the common file used by most connected devices (the plurality). If there is a tie among the top N versions of this file, then pick one of those top N versions at random and start using it.

In particular, if every device has a different version of this file,
then the "birthday problem" practically guarantees that, after enough iterations of this algorithm, eventually 2 devices will pick the same version of the file,
and eventually all the online devices will converge on the same version of the file.

The avoid-re-encrypting-file-with-new-key problem

All problems in computer science can be solved by another level of
indirection. But that usually will create another problem. --
attributed to David Wheeler in the book Beautiful Code (2007)

As I understand it,

You have (encrypted) data that is synchronized between multiple devices

You want to allow a person to change the passphrase on a device to some other passphrase of his own choosing, but you want this to be more-or-less "instant" rather than taking many minutes to decrypt and re-encrypt all the data.

Each device has its own passphrase that can be used to access the data on the device

You don't want unauthorized people to be able to decrypt the data (and "has the passphrase for this device" is an adequate proxy for "is authorized to decrypt the data on this device").

You want to allow a person to create new encrypted data files before the device is ever connected to a network -- and therefore before the devices knows any shared encryption keys -- and later when the device is connected to the network, those files are synchronized to other devices where other people can decrypt and read those files.

The standard way of doing that is to store the data in OpenPGP format (as standardized in RFC 4880).
a b c d e

You already have one layer of indirection -- a person types a passphrase, which is used to decrypt the device-specific password.

The OpenPGP process uses a second layer of indirection:
Every file is encrypted with its own unique symmetric key.

It works something like this:

Every time new data is created or edited, a completely new symmetric key is generated,
the new key itself is encrypted with the user's public key and that encrypted key is stored in the header of the encrypted file. The data is encrypted with that new symmetric key and stored afterward in that encrypted file.
(This can all be done before the device ever connects to the network).

Later that encrypted file is synchronized unmodified over the network.
(Except the sender somehow obtains the receiver's device-specific key,
encrypts the file-specific symmetric key with the receiver's key,
and then adds that encrypted key to the file header).

To decrypt that file and read the data,

A person types in the device-specific passphrase

The device uses that passphrase to decode a file containing the device-specific key. (This is exactly what you are doing already).

The device pulls the encrypted file-specific key out of the header of the file, and uses the device-specific key to decrypt the file-specific key. (This is a second layer of indirection).

Then the device uses the file-specific key to decrypt the data in the file.

To make the system easier to change/migrate,

Use an encrypted file format (such as OpenPGP) that specifies exactly which encryption algorithm was used for this particular file. That allows future software to detect which encryption algorithm was used to create a particular file. Then the device can decrypt today's shiny new files using today's shiny new preferred algorithm. The device can also decrypt dusty old files with yesterday's dusty old algorithms -- and optionally re-encrypt using today's shiny new preferred algorithm.

Use an encrypted file format (such as OpenPGP) that allows you to store the particular file-specific symmetric key in the header several times, each time encrypted with a different public key or device-specific key.

When a user changes the passphrase, only the device-specific key gets re-encrypted, just like what you are doing already.

If for any reason the device-specific key needs to change,
then the device must re-encrypt the file-specific key in the header of each and every encrypted file it holds. That's probably faster than decrypting and re-encrypting the entire file.

Have you considered using some off-the-shelf implementation of OpenPGP, such as "Pretty Good Privacy" or "GNU Privacy Guard"?

OwnerDisplayName: Rafael


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

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

答: Another probable result for such a policy is that people won't report bug if they think they may be the "person to blame", so it will actually reduce the number of bug reported by the team.</p>

ContentLicense: CC BY-SA 3.0


问:
How to show or direct a business analyst to do data modelling?
Our business analysts pushed hard to collect data through a spreadsheet.  I am the programmer responsible for importing that data.  Usually when they push hard for something like this, I never know how well it will work out until a few weeks later when I have time assigned to work on the task of programming the import of the data.  I have tried to do as much as possible along the way, named ranges, data validations, etc.  But I usually don't have time to take a detailed look at all the data and compare to the destination in the database to determine how well it matches up.

A lot of times there will be maybe a little table of items that somehow I have to relate to something else in the database, but there are not natural or business keys present that would allow me to do so.   Make the best of this, trying to write something that can compare strings and make a best guess at it and then go through the effort of creating interfaces for a user to match the imported data to the destination.

I feel like if the business analyst was actually creating a data model, they would be forced to think about these relationships, and have an appreciation for the need of natural or business keys to be part of the spreadsheet for the purposes of smoothly importing the data.  The closest they come to business analysis is a big flat list of fields, and that would be fine if it were like any other data dictionary and include data types+relationships, but it isn't.  They are just a bunch of names.  No indication of what type of data they might hold, and it is up to me to guess.  When I have pushed for more detail, they say that it is just busy work.

How can I explain the importance of data modelling?  How can I tell them what it is and how to do it?  It feels impossible, because they don't have an appreciation for its importance.  They do however, usually have an interest in helping out in whatever way they can, it's just this in particular has never gotten a motivated response.

答: Personally, I feel it is much better not to have such a "business analyst" in your team when that person does not have any programming or data modeling background. Ideally, let a programmer who is part of the development team doing the requirements analysis - that will prevent you from a hell lot of communication problems. However, if you can't change the situation, suggest the BA to take a few lessons in data modeling.</p>


问:
Why is it that MS Data Access story is so fractured ? Is it the nature of Data Access or is just MS?
This StackOverflow question asks "where can I get Microsoft.Data.Objects"

It turns out the answer was probably that its in the CTP4 (code first) release of Entity Framework 4
However there where a lot of guesses.  Including

System.Data

Entity Framework

Microsoft.ApplicationBlocks.Data

Microsoft.Practices.EnterpriseLibrary.Data

10 years ago if someone asked a similar question for they might have gotten DAO, RDO, ADO.

Is this just the nature of the beast or is it MS.

Does this pattern happen with other vendors? Where the base data access strategy is either wrapped or changed?

答:
To be fair all of the ones you mention are built on top of ADO.NET. Before that ADO was the favored route for a while but DAO just sort of hang around because it was native for Microsoft Access Databases. RDO was dead on arrival from what I can tell.

With all the different frameworks you mention I think the problem is that they are trying to give a solution for everybody and to compete with every other platform. If you want a simple way to just use SQL in your code then go for System.Data. If you want an ORM using Entity Framework. For something in between then use Enterprise Library Data. Everyone wants something different.

There is also the issue that MS is a very big company with different teams with different agendas. For example why do they also have 3 word processors (that I know of).

ContentLicense: CC BY-SA 2.5


问:
Reformatting and version control
Code formatting matters. Even indentation matters. And consistency is more important than minor improvements. But projects usually don't have a clear, complete, verifiable and enforced style guide from day 1, and major improvements may arrive any day. Maybe you find that

```<code>SELECT id, name, address
FROM persons JOIN addresses ON persons.id = addresses.person_id;
</code>```

could be better written as / is better written than

```<code>SELECT persons.id,
       persons.name,
       addresses.address
  FROM persons
  JOIN addresses ON persons.id = addresses.person_id;
</code>```

while working on adding more columns to the query. Maybe this is the most complex of all four queries in your code, or a trivial query among thousands. No matter how difficult the transition, you decide it's worth it. But how do you track code changes across major formatting changes? You could just give up and say "this is the point where we start again", or you could reformat all queries in the entire repository history.

If you're using a distributed version control system like Git you can revert to the first commit ever, and reformat your way from there to the current state. But it's a lot of work, and everyone else would have to pause work (or be prepared for the mother of all merges) while it's going on. Is there a better way to change history which gives the best of all results:

Same style in all commits

Minimal merge work

?

To clarify, this is not about best practices when starting the project, but rather what should be done when a large refactoring has been deemed a Good Thing™ but you still want a traceable history? Never rewriting history is great if it's the only way to ensure that your versions always work the same, but what about the developer benefits of a clean rewrite? Especially if you have ways (tests, syntax definitions or an identical binary after compilation) to ensure that the rewritten version works exactly the same way as the original?

答: Do the reformatting as separate commits. This will interfere minimally with the history, and you should be able to see at a glance which commits are just reformatting and which actually change code. It could skew git blame and similar, but if it points to a reformat-only commit, it's fairly straight forward to look for the previous change before that.

Title: Reformatting and version control


问:
When would I use pseudocode instead of flowchart?
I'm a student working with various techniques of programming, and I've come across pseudocode and flowchart. I know that these are both used in order to think through the problem before actually programming, but I have a few questions with this.

When would I use pseudocode to plan out and when would I use flowcharts? Or is it better to do both before actually programming. Particularly for a small arcade sort of game in JAVA since that is my next project.

I've noticed that pseudocode is very similar to the actual code rather than flowcharts. Would this make pseudocoding better because you essentially copy/paste the pseudocode into your program (of course, you have to change it to fit the language. I understand that part).

Is it practical to use both of these while programming? Particularly the same game mentioned earlier.
Thanks.

答: Why write pseudo code when you can write Java?  I've found Java, a good IDE, and Javadoc are the easiest way to grasp a programming problem--at least an Object Oriented one.  (And an arcade game ought to be OO.)  The language was designed from the ground up for this.  Its simple and straightforward.  (Too simple for many purposes, perhaps, but the best thing I've seen for this.)  The hypertext in the Javadoc and, via an IDE, in the code itself make for a more understandable "diagram" than you could draw on even a large sheet of paper.  Java code is as simple as any pseudo code and a good deal more rigorous.  And once you've got it "diagrammed" and "pseudo" coded, the program will actually run!


问:
How to determine if a class meets the single responsibility principle?
The Single Responsibility Principle is based on the high cohesion principle. The difference between the two is that a highly cohesive classes features a set of responsibilities that are strongly related, while classes adhering to SRP have just one responsibility. </p>

<p>But how do we determine whether a particular class features a set of responsibilities and is thus just highly cohesive, or whether it has only one responsibility and thus adheres to SRP? In other words, isn't it more or less subjective, since some may consider a class very granular (and as such will believe the class adheres to SRP), while others may consider it not granular enough? </p>

答:
I can give you several rules of thumb.

How easy is it to name the class?  If a class is difficult to name, it is probably doing too much.

How many public methods does the class have? 7+/-2 is a good rule of thumb. If the class has more than that, you should think about splitting it into several classes.

Are there cohesive groups of public methods used in separate contexts?

How many private methods or data members are there?  If the class has a complex internal structure, you probably should refactor it so that the internals are packaged into separate smaller classes.

And the easiest rule of thumb: how big is the class? If you have a C++ header file containing a single class that is more than a couple of hundred lines long, you should probably split it up.


答:
The answer to your actual question is, "You don't." I know of no current SCM tool that can trace changes in logic from code formatted in one way, through a major formatting change, and through further changes after the code is formatted in the new way. And, you know this, losing the history on a piece of code is Not Good.

Accordingly, I'm going to contradict your first sentence a bit. Code formatting doesn't matter that much. Pretty is nice, but it's not what we're here for. I understand as well as anybody that getting dumped into somebody's old hellish weird K&R variant code with the two-space indents sucks (1), but... the formatting isn't actually an obstacle to understanding what's going on, unless it's something exceptionally pathological. And in that case, you're going to have problems changing the code anyway, and shouldn't bother it.

Therefore, it's not worth it to make changes to established code STRICTLY to reformat it. Changing the variable names, breaking up long functions, all that good refactoring stuff that changes the content, yes, but not JUST reformatting.

1) - I once owned the Windows Clipboard Viewer for a while. The whole thing was one, 150k, C module. I found a spot where different people had used, I think, five different brace styles within thirty lines of each other. But that section of things WORKED. I carried around a printout of that chunk of code for ten years, but I didn't poke it because that history mattered, and that code was in at least three source trees (Windows 3.x, NT, future 95) which all lived in different buildings.

Title: Reformatting and version control

Body:
Code formatting matters. Even indentation matters. And consistency is more important than minor improvements. But projects usually don't have a clear, complete, verifiable and enforced style guide from day 1, and major improvements may arrive any day. Maybe you find that

```<code>SELECT id, name, address
FROM persons JOIN addresses ON persons.id = addresses.person_id;
</code>```

could be better written as / is better written than

```<code>SELECT persons.id,
       persons.name,
       addresses.address
  FROM persons
  JOIN addresses ON persons.id = addresses.person_id;
</code>```

while working on adding more columns to the query. Maybe this is the most complex of all four queries in your code, or a trivial query among thousands. No matter how difficult the transition, you decide it's worth it. But how do you track code changes across major formatting changes? You could just give up and say "this is the point where we start again", or you could reformat all queries in the entire repository history.

If you're using a distributed version control system like Git you can revert to the first commit ever, and reformat your way from there to the current state. But it's a lot of work, and everyone else would have to pause work (or be prepared for the mother of all merges) while it's going on. Is there a better way to change history which gives the best of all results:

Same style in all commits

Minimal merge work

?

To clarify, this is not about best practices when starting the project, but rather what should be done when a large refactoring has been deemed a Good Thing™ but you still want a traceable history? Never rewriting history is great if it's the only way to ensure that your versions always work the same, but what about the developer benefits of a clean rewrite? Especially if you have ways (tests, syntax definitions or an identical binary after compilation) to ensure that the rewritten version works exactly the same way as the original?


答:
The root cause for a fielded defect is never a single person.  Perfectly conscientious people will make errors, and a process that expects them to be infallible is unreasonable.  If you are not verifying changes to production systems before deployment, either manually or through automated testing, then bugs are inevitable.

Wrong:

Bob forget to check input and the program crashed dividing by zero.

Right:

Code vulnerable to a divide by zero error was not detected before deployment.
      New test cases have been added to verify proper handling of invalid input.  Code was corrected and all new test cases are passing.

Title: My boss decided to add a "person to blame" field to every bug report. How can I convince him that it's a bad idea?

Body:
In one of the latest "WTF" moves, my boss decided that adding a "Person To Blame" field to our bug tracking template will increase accountability (although we already have a way of tying bugs to features/stories). My arguments that this will decrease morale, increase finger-pointing and would not account for missing/misunderstood features reported as bug have gone unheard.

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


问:
Etiquette when asking questions in an IRC channel
Many larger OSS projects maintain IRC channels to discuss their usage or development. When I get stuck on using a project, having tried and failed to find information on the web, one of the ways I try to figure out what to do is to go into the IRC channel and ask.

But my questions are invariably completely ignored by the people in the channel. If there was silence when I entered, there will still be silence. If there is an ongoing conversation, it carries on unperturbed. I leave the channel open for a few hours, hoping that maybe someone will eventually engage me, but nothing happens.

So I worry that I'm being rude in some way I don't understand, or breaking some unspoken rule and being ignored for it. I try to make my questions polite, to the point, and grammatical, and try to indicate that I've tried the obvious solutions and why they didn't work. I understand that I'm obviously a complete stranger to the people on the channel, but I'm not sure how to fix this. Should I just lurk in the channel, saying nothing, for a week? That seems absurd too.

A typical message I send might be "Hello all - I've been trying to get Foo to work, but I keep on getting a BarException. I tried resetting the Quux, but this doesn't seem to do anything. Does anyone have a suggestion on what I could try?"

答:
Make sure you're in the right channel. If you're in a developers channel it's obviously not help-desk channel.

If I'm a developer I want to discuss development, not help randomuser #1040 who can't get really well documented feature x working.


答:
Your actual question was about how to change the culture before you leave the company, by convincing your boss that adding a person to blame field for bug reports is a bad idea.  But of course changing the culture requires him to really understand why this is a bad idea.

This is a tall order.  Besides the issue of saving face after changing his mind, there is the basic problem that people who think about solutions primarily in terms of individual blame are usually pretty set in that mindset.

You asked for writing on this topic, and Peopleware comes to mind.  It's highly regarded and talks in general terms about how to manage people doing creative work where the output is difficult to measure.  The problem is that you reading it won't help much, your boss would have to read it, and believe at least some of it.

Oddly, since the problem here is more about people than bug reports, it very possibly belongs more on Workplace than Programmers.  But the success of software projects is usually pretty heavily traceable to human social interaction, so the real answers are often mostly about things that transcend software.

My only other, half serious, suggestion is to say (or convince a co-worker to say, since you plan to leave) that you are willing to take on full responsibility for the project's success, and your name should always go in the field, since even if someone else made the mistake directly, you have assumed responsibility for making sure everyone on the team does quality work.

It's nonsense of course, how could you ever back that up, but some people (especially people who are big on blame) really eat that stuff up.  Ronald Reagan used to publicly accept personal responsibility every time any member of his administration was caught in a scandal (and there were quite a few) and it actually worked out pretty well politically every time.  The best part for you is that the responsibility generally comes with no actual consequences, they just think you are a stand up guy for taking the responsibility.

Or maybe that's not how it will go down.  It makes no sense at all to me so it's hard for me to predict when it will work, but I have witnessed it work when it seemed to have no business doing so (in the workplace, not just the Reagan example).


问:
Where should I insert data into the database?
I am making a pretty standard PHP sign up form that will validate the data the user entered and then redirect to a page with a success message. I would like to store this data in a database. Should I insert this information into the database before I redirect the page or after it is redirected? </p>

答:
You could avoid redirecting, You could have the form Action field submit to the current page and have a snippet of PHP higher up on the page to watch out for the form submission, save the data and show a Thank you message then.

For example:

```<code><?php
if($_POST['submit'] == 'Sign up')
{
// place some code here to save the details and thank the user
}
?>

<form action='sign_up.php' method='post'>
<form>
</code>```

Body:
You could avoid redirecting, You could have the form Action field submit to the current page and have a snippet of PHP higher up on the page to watch out for the form submission, save the data and show a Thank you message then.

For example:

<?php
if($_POST['submit'] == 'Sign up')
{
// place some code here to save the details and thank the user
}
?>

<form action='sign_up.php' method='post'>
<form>


答:
There are at least three problems with that field.

The first one is that blaming people isn't good for morale. Ok. But maybe he doesn't care about morale and wants to fire bad developers. Hard to argue against.

The second one is that getting that field right is going to be hard and a pretty big time sink. It's more complex than just finding out who wrote the bad code. And any potentially information that is hard to figure out can be sandbagged/cheated on. But maybe he's prepared to pay that cost and audit the information. Fine.

The more fundamental issue is that this field is not going to be a good metric to take action on. Sure, he'll have a nice ranking of whose code causes the most defects. But guess who'll be on top of that list? Probably the company founder, or maybe a top developer who has a very low defect rate but is so productive he writes a disproportionate portion of the code. So he'll either end up firing his best developer, or have him slow down so much he's not his best developer any more. And they guy who writes a line of code a month - preferably comments - will probably get rewarded for his low defect numbers.

Yet another software metric failure.


问:
Do higher resolution laptop displays matter for programmers?
I'm buying a new laptop that I'll be using mainly for programming.  A couple of options that really intrigue me are the Asus Zenbook UX31A and the new Retina Macbook Pro.  It's obvious that the high-resolution displays on these laptops is useful for entertainment, photo-editing, and other things.  My question is this:  Do these displays provide any benefit for programmers?  Do these displays make code any easier to read?  Are they any easier on the eyes after a whole day of staring at the screen?</p>

答:
Generally speaking, increased visual real-estate is a good thing with programming.  Most modern IDEs have a number of panels that you'd like to have open and it's nice to be able to see all of that information "at once."

There is a nefarious relationship between resolution and screen size.  The easy rule of thumb is "the higher the resolution, the better" along with "the bigger the screen, the better."  The problem is when one of those elements becomes fixed.  A super high resolution on an itty bitty display will simply be unreadable or will lead to eye strain.

Many developers work with multiple monitors for the above reasons.  It's a reasonable way to balance the relationship between resolution and screen size, but still keep adding to the overall real estate.

As others have pointed out, the two systems you mention have significant differences in the display resolution.  The Mac will have more effective real estate without venturing too far into too-small-to-read territory.

Your questions:

- Yes, there is distinct benefit for programmers with larger screens and higher resolution.

- It won't make the WTF code any easier to understand, but having larger blocks of code available makes it easier to understand overall program flow.

- I don't think you'll see a noticeable difference in eye strain with the two models you mentioned.  OTOH, this answer is pretty particular to your question and not very generalizable.

My ideal setup would be two or three 24" widescreen displays for coding against.  If a laptop was my primary system, I would be happy with one or two 24" widescreens to supplement the laptop display.


问:
How do we set a link to a Paid version of app if we don't have the app in App Store ?
If we don't have the free and the paid apps on the Apple app store yet, how would we program in the free version to link to the paid version because the link is not there yet?

Do we have to have a webpage as a placeholder to do the forward, for this first, initial case?   Is this the only solution and what if we don't have a website?

答:
If you go through the new app process in iTunes Connect, they'll give you the final App Store URL as soon as you've entered the basic metadata.

Therefore you can just create a placeholder app with a dummy name and screenshot, get the URL, and then sometime in the future when the app is ready you edit the details to the correct ones, upload the binary, and the URL will start working as soon as you publish the app.

However, I think you'd still be better off using a redirect URL anyway, so that it's under your control where the users interested in the paid version go. For example, you might want to send them to a webpage instead of straight to the App Store, especially before the paid app is published.


问:
Paranoid Encryption
Call me paranoid, but I really like to keep my stuff secret, but readily available on the cloud. So, asking this question.

How safe and reliable is encryption software (e.g., truecrypt)? The reason I ask is that, what is I encrypt my data today with this software and after a couple of years, the software is gone ! What happens to my encrypted data?

Is it equally safe to AES encrypt using 7-zip? Will it provide the same level or equivalent level of encryption as truecrypt or other encryption software? (I agree truecrypt will be better because of the container encryption it gives.) And what happens if 7-zip shuts down after 5 years?

I am sorry if I am sounding paranoid, but I am coming back to my original question... Is there any application/software independent encryption? Meaning, can I encrypt with one software and decrypt with another so that I will not be dependent on just one vendor? I want my encryption to depend ONLY on the password and NOT on the encryption program/software?

The next question, can I write my own program that does AES/stronger encryption when I give it a passphrase, so that I don't need to depend on third party software for encryption? If yes, which language supports the same?

Can someone give me a heads up as to where to look for in case of writing my own encryption program?

答:
application/software independent encryption ... where to look for in case of writing my own encryption program?

Yes, future proofing data is a good idea. By choosing a good file format -- preferably some "open" format that already has several applications that can read it -- it makes it more likely that at least one application will exist (or can be created) in the future, such that we can read that data in the future.

I agree with "insta" that there isn't anything significantly better than using AES encryption with any of the open archive formats such as 7z, and then store in multiple locations either: copies of that encrypted file -- or PAR2 recovery volumes generated from that encrypted archive file.
And also storing the encryption passphrase in a few places so we can find it again in the future.

Applications that already support decrypting data stored in that standard AES-encrypted 7z file format include
the 7-Zip archiver, sevenzsharp,
Ark, PeaZip, File Roller,
and a dozen other applications.

Writing your own encryption/decryption program entirely from scratch probably won't produce anything better -- and is highly likely to produce something much worse -- than using some pre-existing AES library or application.

However, the process of writing such a from-scratch program can be highly educational.

In principle, you could implement AES-256 "from scratch" directly from the AES: FIPS-197 standards document, in any programming language.
If you don't already have a favorite programming language
(or a language you've already selected as one you want more practice using),
I hear that Python is popular among people teaching a first programming course ( Criteria for selecting language for first programming course ).

However, FIPS standards are a bit difficult to read.
If you want to write yet another "from scratch" implementation of AES, I recommend (in no particular order):

implement a program to decode "Ciphersaber" format encrypted files.

implement a program to decrypt files encrypted with the "perfectly secure" one-time pad.

Carefully read through Wikipedia: Advanced Encryption Standard

skim through "Cryptographic Right Answers"

Each of those things helps you learn things that make the standards document easier to understand.

Title: Paranoid Encryption


答: I'm typing this on a Retina MacBook Pro. The biggest improvement of the high-res screen isn't the available real estate but the greatly improved sharpness and clarity of on-screen text. It looks like print. Programming is one of the activities that benefits most from better looking text.</p>

Title: Do higher resolution laptop displays matter for programmers?

Body: I'm buying a new laptop that I'll be using mainly for programming.  A couple of options that really intrigue me are the Asus Zenbook UX31A and the new Retina Macbook Pro.  It's obvious that the high-resolution displays on these laptops is useful for entertainment, photo-editing, and other things.  My question is this:  Do these displays provide any benefit for programmers?  Do these displays make code any easier to read?  Are they any easier on the eyes after a whole day of staring at the screen?</p>


答:
The short answer: Make the database update before the redirect.

You should always use the get-post-redirect pattern when the user submits a form that alters application data. (Props to @WyattBarnett and @PieterB for answering in comments.) In order to work well with browsers, only GET requests should display a page to the user, and GET requests should never have side-effects like database changes, email messages, etc.

So you POST** the form to a processing script, which handles validation, writes to the database, sends emails, whatever... and redirects to another page, which will be requested with GET and will not do any of those things. It just displays stuff.

** Read about REST for an approach to http methods that goes beyond GET and POST. It's most likely not necessary for this application, though.

Title: Where should I insert data into the database?

Body: I am making a pretty standard PHP sign up form that will validate the data the user entered and then redirect to a page with a success message. I would like to store this data in a database. Should I insert this information into the database before I redirect the page or after it is redirected? </p>


答:
This sounds a lot like when Scott Adams pointed out the failed wisdom of a Bug Bounty when the Pointy Haired Boss in Dilbert.  Wally announced he was going to go and 'write him a new Mini Van".

Dilbert comic strip for 11/13/1995 from the official Dilbert comic strips archive.

I recall once when Snow Skiing that someone pointed out that 'not falling" was not the sign of a good skiier; but often the sign of one that doesn't try anything (or doesn't really ski at all).

Bugs can be introduced in code by poor programming and poor design; but, they can also come as the consequence of writing lots of difficult code.  Dinging people who produce the most bugs is as likely to Ding poor developers as highly productive ones.

It sounds like your boss may be frustrated with the number of defects.  Are the people in your group passionate about quality?  Creating a 'what' field for the cause rather than a 'who' field could be more productive. Ex: Requirements Change, Design Flaw, Implementation Flaw, etc.  Even this will fail unless there is a group by-in to improving the quality of the product.


问:
Is it a good idea to write an OS in a scripting language?
Is it a good idea to create an OS that's written in a scripting language?

For example, how about creating an OS using Python?

答:
Before you decide on the how, you need to specify the what. What will this new OS do? Where will it run? Why would any one bother to use it? etc. The next thing is to determine the qualities of the OS. Speed, Security, Threading, Memory Management, Multi-Tasking, File Formats, Language support, supported processors, etc.

From answering the above questions and considering the many qualities of your OS you can determine what tool to use to achieve your goals.

Now, do you really want to do all that?

I assume that Python was used in part in writing parts of Linux - See: What Languages are Windows, Mac OS X and Linux written in?


问:
Fix bugs, or wait for the customer to find them?
Do other people fix bugs when they see them, or do they wait until there's crashes/data loss/people die before fixing it?

Example 1

```<code> Customer customer = null;
 ...
 customer.Save();
</code>```

The code is clearly wrong, and there's no way around it - it's calling a method on a null reference. It happens to not crash because Save happens to not access any instance data; so it's just like calling a static function. But any small change anywhere can suddenly cause broken code that doesn't crash: to start crashing.

But, it's also not inconceivable that correcting the code:

```<code>Customer customer = null;
...
customer = new Customer();
try
   ...
   customer.Save();
   ...
finally
   customer.Free();
end;
</code>```

might introduce a crash; one not discovered through unit tests with complete coverage, and manual user testing.

Example 2

```<code>float speed = 0.5 * ((G * mass1 * mass2) / R) * Pow(time, 2);
</code>```

People knowing physics will recognize that it's supposed to be R2 in the denominator.

The code is wrong, it's absolutely wrong. And overestimating the speed will cause the retro-rockets to fire too soon, killing all the occupants of the spacecraft.

But it's also possible perhaps having it over-estimate the speed is masking another issue: the air-bags can't deploy while the shuttle is moving too fast. If we suddenly fix the code:

```<code>float speed = 0.5 * ((G * mass1 * mass2) / Pow(R, 2)) * Pow(time, 2);
</code>```

Now the speed is accurate, and suddenly airbags are deploying when they shouldn't.

Example 3

Here's an example that i had recently, checking if a string contains invalid characters:

```<code>if (StrPos(Address, "PO BOX") >= 0)
{
   //Do something
}
</code>```

What if it turns out there's a bug in the Do something branch? Fixing the obviously incorrect code:

```<code>if (StrPos("PO BOX", Address) >= 0)
{
   //Do something
}
</code>```

Fixes the code, but introduces a bug.

The way I see it there are two possibilities:

fix the code, and get blamed for breaking it

wait for the code to crash, and get blamed for having a bug

What do you politically do?

Example 4 - Today's real world bug

I am constructing an object, but calling the wrong constructor:

```<code>Customer customer = new Customer();
</code>```

Turns out that the "parameterless" constructor is actually an parameterized constructor from  further back in the inheritance chain:

```<code>public Customer(SomeObjectThatNobodyShouldBeUsingDirectly thingy = null)
public Customer(InjectedDependancy depends)
</code>```

Calling it is a mistake, since it bypasses all the subsequent constructors.

I could change the object's lineage to not expose such a dangerous constructor, but now I have to change the code to:

```<code>Customer customer = new Customer(depends);
</code>```

But I can't guarantee that this change won't break anything. Like my Example 1 above, perhaps someone, somewhere, somehow, under some esoteric conditions, depends on the constructed Customer to be invalid and full of junk.

Perhaps the Customer object, now that it is properly constructed will allow some code to run that previously never did, and now I can get a crash.

I can't bet your wife's life on it.

And I can test it from here to Tuesday, I can't swear on your daughter's life that I didn't introduce a regression.

Do I:

Fix the code and get blamed for breaking it? or

Leave the bug, and get blamed when the customer finds it?

答:
You have good answers already. I will just add something about the issue of being afraid that something crashes.

First, in the ideal situation the software is modular, is architected correctly and there is good separation of concerns. In this case, the changes you make are highly unlikely to break anything as you will be in control of all the related code and there is no hidden surprises.

Unfortunately, the ideal situation is fictional. Regardless of the extent to which the coupling is loose, there will be coupling and hence the possibility of breaking something else.

The solution to this is two-fold:

Make the code as well structured as possible.

When the code is isolated enough that you know that nothing else will break, fix it.

Making the code well structured is not done by rewriting the whole code to a new architectural design. Rather, refactoring guided by tests is your friend here. In this step, you do not change the functionality.

The second step is that you fix the bug.

A few points are relevant:

Version Control is absolutely needed for this process.

The refactoring step and the bug fixing step are better committed to version control as separate commits, so each has a well defined historical functionality.

Don't fixate on the possibility of making another bug, you won't get anything done. Rather, think of making your code better. In other words, unless you know that you are increasing the bugs rather than decreasing them then you should do it.

Related to the last point: don't try to predict the future. Humans are biased to think that they are very good at prediction. In reality our prediction powers are short term. So don't worry about a vague undefined future bug. This is also the principle behind YAGNI.

The corresponding tool to version control in the bug world is the bug tracker. You will need that as well.

You need to fix bugs for two reasons: in order to satisfy the customer; and in order to be able to progress in your development. To use example 3 (the physics one): if the program satisfies the customer with such a broken equation, then there are many other parts of the software that are wrongly developed to mitigate this bug (for example the airbag deployment). If a version 2 (or 1.1) is required for this software, then you will find it more and more difficult to develop correct code based on this faulty one. You are then either heading for the big rewrite, or for the grand failure. Both of which you should avoid.

These are already more than a few points, so I guess I will stop here.


答:
If you are doing Agile, and it sounds like you are from the features/stories comment. The person to blame would be the QA person that let the bug slip through, or the Product Owner / Customer that accepted the feature/story as complete with the bug in it.

I did typesetting back in the day, here is my take on it.

This is like blaming a typesetter for misspellings and other things
  that a proofreader should have found but missed. The typesetter made
  the misspelling, but the proofreader missed it, so it is the
  proofreader to blame for the mistake making to print, not the
  person that made the error in the first place.

In an Agile environment it is the QA persons responsibility to catch errors ( bugs ) and it is the Product Owners responsibility to not accept things that aren't correct. This is two levels of proof readers that should insulate the developers from things that get released, which is the only way anything should be classified as a bug in an Agile environment.


答:
It looks like your boss has not a deep understanding of software and maybe he does not intend to, either. So he has a different language, a different culture.

Quitting a job for a problem like this, before even trying to step forward for a solution is just being a quitter. Quitting is quitting. Do not quit until he makes you sure that you can never understand each other. To be sure about that, you should first try.

Since he does not know our language, and he is the boss, the first step here would be trying to talk to him in his language. What do I mean with language? Let's think together:

We software people, most of us love the job we do, we have a deep connection with what we are doing. Otherwise it does not work and one cannot go on in this business for a long time without loving it or being a complete ...you fill the blanks...

He, however, sees things much differently. With every bug report, while most of us get excited to make the thing work better (no, even if it is sometimes really very stressful, we love problems, just admit it!), he sees it as a failure, a measure of being unsuccessful. First thing he should want to understand is that bugs are good. Bugs makes clients love the company. (Now this is his language) When a customer reports a bug, or when we find one ourselves, after it is solved, it is much better than the situation it never happened. Bugs create customer loyalty (I am serious!), bugs create a great excuse to communication between the consumer and the producer of the software.

To "increase the profit of bugs" you should offer making bug reports even more open. With every bug report and its quick, clean, good solution, customers feel and see that "wow, these guys are awesome! They work really hard. Look at these things they are solving. We were not even aware that software was such a complex thing!" blah blah and blah...

Make your move, talk in his language. Bugs are great for a software company, not a problem. They make us a living.

For team ethics, efficiency, or any kind of talk you would make might work the opposite way you intended. If you want to quit, he will think "aha, my solution started to work from the very first day! Bad links have already started to drop by themselves before they are exposed!" He believes in his idea of finding the bad boys in the company and it is very difficult to convince him otherwise. Especially when you might be one of those bad boys!

So, focus on his real problem: Bugs. Show him that bugs can be very useful. Without any problems, a relationship is boring. Everything that does not kill you makes you stronger. Every bug is a great opportunity that you can use to increase the customer happiness.

This is just one thing you can tell. Think about his concerns and you will find many other items to add to your list. The GOLDEN KEY is to offer an alternative thing instead of fighting with his idea!


答:
It's not just a bad idea. It's pretty much impossible.

How do you implement IO with a language whose IO facilities depend entirely on the host operating system?

How could you implement primitive scheduling without any useful interrupt primitives?

How could you write a device driver in a language which cannot address a particular byte?

Edit:--
Just to clarify a bit. You cannot write a "real" OS which interacts directly with the machine in a "scripting" language. You can however write a usable "virtual machine" if the scritping language is flexible enough. For instance implementations of Donald Knuths theoretical MIX (s) machine and a ZX80 emulator good enough to run pacman have been written in JavaScript.

Title: Is it a good idea to write an OS in a scripting language?

Body:
Is it a good idea to create an OS that's written in a scripting language?

For example, how about creating an OS using Python?


问:
Copyrighting software, templates, etc. under real name or screen name?
My question is hopefully simple - should I copyright my work (art, software, web design, etc.) under my real name or my screen name? My real name and screen name are also easily connected with a bit of searching, so does it really matter in the end?

I'm not a professional (at this point).

I read this question and they recommended releasing on the app market under a company name.

I also read this question, but that didn't answer my question.

I know it probably matters for big projects, but for little projects, does it matter?

答:
US Copyright office:

An author of a copyrighted work can use a pseudonym or pen name. A
work is pseudonymous if the author is identified on copies or
phonorecords of the work by a fictitious name. Nicknames and other
diminutive forms of legal names are not considered fictitious.
Copyright does not protect pseudonyms or other names.

Link

ContentLicense: CC BY-SA 4.0


问:
Computer Graphics: Principles and Practice in C ( in Python? )
I am attending a Computer graphics course after the summer. I have read lots of good things about the book "Computer Graphics: Principles and Practice in C" for people who are willing to put in some work. My school does not focus on C/C++ until next year, so I have decided to learn Python this summer and get good at Python this following year. </p>

<p>How language dependent is this book? Can I work through it in Python? </p>

答:
Python is fine for learning computer graphics, maths and matrix operations with numpy work internally in C and are just as fast as c. There are bindings to openGL and opencv

The book "Computer Graphics: Principles and Practice in C" is out of date when it comes to the actual code - although most of the basic principles are the same. If this is the set text for a course I would worry about how "in touch" the lecturer is


问:
How do I handle a user story that I complete, but with compromise and need to revisit?
I have just fulfilled (is that a good term?) two user stories out of a new project backlog I have just built. These are user registration and password reset, both requiring mail. I need to implement a substitute mail component because my initial choice, and a normally reliable one, wasn't working. Because I was focused on delivering the user stories, not debugging the mail component, I swapped it out to deliver working code at sprint end. Do I now log a new support issue for the mailer, or 're-insert' these stories into the backlog? If I do the latter, am I not introducing too much tech detail into user stories?</p>

答:
If the definition of done for the user story are fullfiled (fullfilled, what every you want to call done) then your user store is complete and you shouldn't be putting it back in the backlog.

However you've taken on technical debt to complete that and later you need to devote other time to fixing that.  So it sounds to me that you need a type of task for internal work such as refactors.

So add a new issue into the backlog.


答:
I know this is not a proper answer, but this project demonstrates a working operating system with a kernel written in JavaScript:

https://github.com/charliesome/jsos/

The drivers for VGA and the keyboard were also written in JavaScript using interrupts. I developed an implementation of OpenGL 1.1 for it myself a while ago and it works pretty nicely.


答:
No, it is not even possible (exclusively)

Why?  Consider the following:

What is a scripting language?

Lets make the following two assumptions about the definition of a "scripting language":

The language lives within a runtime environment.

The language does not have access to raw memory pointers.

What is an operating system?

Lets assume that an Operating System's primary goal can be simplified to the following:

to provide an abstraction between user programs and the hardware they run upon

By these very definitions, it is logically impossible for a scripting language to be an operating system.  Why?

An OS must have raw, untethered access to a computer's memory for communicating with hardware.  Since scripting languages do not have access to raw memory pointers, they cannot do this.

Since a scripting language requires a runtime environment, but they can't talk to directly to the hardware, the environment must be coded in another language that has this ability.  In this instance (as is with JSOS that was brought up in other posts), a lower level language must be used to interface with the machine.

It is possible to write a minimum amount of code in a "raw" language such as C, but a raw compiled language is always going to be needed by definition.  Once this is in place, other pieces of the OS can be implemented in a scripting language, but a scripting language could never be used alone.


答:
I must maintain that it is, in principle, possible to write an operating system in python. You would have to produce a Python-to-low level language compiler, as well as add modules to the standard library that provide access to the low level pieces of your computer. But if those two pieces were in place it would be possible.

However,

Its going to be really hard to write a compiler that produces efficient code

Python is going to be awkward for accessing low level details


答:
Insert the data into database after an individual signs up using a post method and then redirect using header('location:whateverpage.php?message=success') and on the other page use </p>

```<code>if(isset($_GET['message']) == 'success') {
//Show some message
}
</code>```

Body:
Insert the data into database after an individual signs up using a post method and then redirect using header('location:whateverpage.php?message=success') and on the other page use

if(isset($_GET['message']) == 'success') {
//Show some message
}


问:
Is a blob more efficient than a varchar for data that can be ANY size?
When setting up a database I want to use the most efficient data type for potentially fairly long data. Currently my project is to store song titles and thoughts pertaining to that song. Some titles might be 5 characters or longer than 100 characters and the thoughts could run pretty long.

Is it more efficient to use a varchar set to 8000 or to use a blob? Is using a blob the same as a varchar, in that there is a set size it is allocated regardless of what it holds? or is it just a pointer and it doesn't really use much space on the table? Is there a certain set size of a blob in KB or is it expandable?

答:
I would suggest using TEXT over BLOB.

Primary Difference

TEXT and BLOB is stored off the table with the table just having a pointer to the location of the actual storage.

VARCHAR is stored inline with the table.

Primary Guideline

Text format messages should almost always be stored as TEXT (they end up being arbitrarily long)

String attributes should be stored as VARCHAR (the destination user name, the subject, etc...).

To choose on when to use VARCHAR and when to use TEXT has been discussed extensively on Stack overflow in these threads:

MySQL: Large VARCHAR vs. TEXT?

MySQL varchar(2000) vs text?

There is also a performance comparison thread for this on MySQL forum.


问:
Should I provide fallbacks for HTML5/CSS3 elements in a web page at this point?
I'm wondering if I should bother providing a fallback for HTML5 tags and attributes and CSS3 styling at this point in time.

I know that there's probably still a lot of people out there who use older versions of browsers and HTML5/CSS3 are still fairly new.

I read this article: Should I use non-standard tags in a HTML page for highlighting words? and one answer mentioned that people kind of "cheat" with older browsers by using the new tags and attributes, but styling them in CSS to ensure they show up right. This question: Relevance of HTML5: Is now the time? was asked about two years ago and I don't know how relevant it is anymore.

For example, I want to use the placeholder and required attributes in a web form I'm building and it has no labels to show what each <input> is. How do I handle this, or do I bother?

答:
It really is up to who is your target audience? Is it fair to expect decent level of techiness (read: probably uses the latest browsers), so it would be a non-issue to use whatever technology the last couple versions of the major browsers support. If you can expect a sizable portion of the visitors using outdated browsers, you might want to consider using fallbacks.

In almost all cases, that means creating a separate CSS for mostly Internet Explorer, heh. For the issues not related to formatting, there's the possibility of using a separate container page for a HTML 4.01-based version. But of course keep the content separate, so you don't have to maintain two versions of the same data!

A simplified example, using PHP:

```<code><html>
...
<?php
    $browser = new SupportChecker();
    if($browser->supports('html5') == true) {
        echo '<section id="news">';
        include('content.txt');
        echo '</section>';
    } else {
        echo '<div class="news">'
        include('content.txt');
        echo '</div>'
    }
?>
...
</html>
</code>```

Of course for an actual page, a more sensible way to achieve that would be used. The above is just a description of the idea. The same will apply for the header of the page. You could start the page with the inclusion of a header based on the support:

```<code><?php
    $browser = new SupportChecker();
    if($browser->supports('html5') == true) {
        include('html5_header.txt');
        $_SESSION['support'] = 'html5';
    } else {
        include('regular_header.txt');
        $_SESSION['support'] = 'regular';
    }
?>
</code>```

That could be usable, I would presume. Then just compare to the session variable.

Body:
It really is up to who is your target audience? Is it fair to expect decent level of techiness (read: probably uses the latest browsers), so it would be a non-issue to use whatever technology the last couple versions of the major browsers support. If you can expect a sizable portion of the visitors using outdated browsers, you might want to consider using fallbacks.

In almost all cases, that means creating a separate CSS for mostly Internet Explorer, heh. For the issues not related to formatting, there's the possibility of using a separate container page for a HTML 4.01-based version. But of course keep the content separate, so you don't have to maintain two versions of the same data!

A simplified example, using PHP:

<html>
...
<?php
    $browser = new SupportChecker();
    if($browser->supports('html5') == true) {
        echo '<section id="news">';
        include('content.txt');
        echo '</section>';
    } else {
        echo '<div class="news">'
        include('content.txt');
        echo '</div>'
    }
?>
...
</html>

Of course for an actual page, a more sensible way to achieve that would be used. The above is just a description of the idea. The same will apply for the header of the page. You could start the page with the inclusion of a header based on the support:

<?php
    $browser = new SupportChecker();
    if($browser->supports('html5') == true) {
        include('html5_header.txt');
        $_SESSION['support'] = 'html5';
    } else {
        include('regular_header.txt');
        $_SESSION['support'] = 'regular';
    }
?>

That could be usable, I would presume. Then just compare to the session variable.


问:
Are programmers bad testers?
I know this sounds a lot like other questions which have already being asked, but it is actually slightly different. It seems to be generally considered that programmers are not good at performing the role of testing an application. For example:

Joel on Software - Top Five (Wrong) Reasons You Don't Have Testers (emphasis mine)

Don't even think of trying to tell college CS graduates that they can
  come work for you, but "everyone has to do a stint in QA for a while
  before moving on to code". I've seen a lot of this. Programmers do not
  make good testers, and you'll lose a good programmer, who is a lot
  harder to replace.

And in this question, one of the most popular answers says (again, my emphasis):

Developers can be testers, but they shouldn't be testers. Developers
  tend to unintentionally/unconciously avoid to use the application in a
  way that might break it. That's because they wrote it and mostly test
  it in the way it should be used.

So the question is are programmers bad at testing? What evidence or arguments are there to support this conclusion? Are programmers only bad at testing their own code? Is there any evidence to suggest that programmers are actually good at testing?

What do I mean by "testing?" I do not mean unit testing or anything that is considered part of the methodology used by the software team to write software. I mean some kind of quality assurance method that is used after the code has been built and deployed to whatever that software team would call the "test environment."

答:
What kind of testing do you mean?  If you mean comprehensive exhaustive testing then I could see some rationales for saying yes though I'd suspect most people would be poor in this category if one considers all possible combinations of inputs as a requirement for such testing.

I can acknowledge that the developer that designs the software may have tunnel vision when it comes to what the code is to handle and ignore some possible boundary cases that just may not have been considered.  For example, if I build a web form that takes a number, n, and then prints from 1 to n on the screen I may miss some special cases like if nothing is entered or something that isn't a natural number like e or pi.  What is the program supposed to do in these cases may be questionable.

Test Driven Development would be an example of a development methodology that puts testing into a different light that may give another view here.

Title: Are programmers bad testers?


问:
What are the drawbacks of Python?
Python seems all the rage these days, and not undeservingly - for it is truly a language with which one almost enjoys being given a new problem to solve. But, as a wise man once said (calling him a wise man only because I've no idea as to who actually said it; not sure whether he was that wise at all), to really know a language one does not only know its syntax, design, etc., advantages but also its drawbacks. No language is perfect, some are just better than others.

So, what would be in your opinion, objective drawbacks of Python.

Note: I'm not asking for a language comparison here (i.e. C# is better than Python because ... yadda yadda yadda) - more of an objective (to some level) opinion which language features are badly designed, whether, what are maybe some you're missing in it and so on. If must use another language as a comparison, but only to illustrate a point which would be hard to elaborate on otherwise (i.e. for ease of understanding)

答:
My main complaint is threading, which is not as performant in many circumstances (compared to Java, C and others) due to the global interpreter lock (see "Inside the Python GIL" (PDF link) talk)

However there is a multiprocess interface that is very easy to use, however it is going to be heavier on memory usage for the same number of processes vs. threads, or difficult if you have a lot of shared data. The benefit however, is that once you have a program working on with multiple processes, it can scale across multiple machines, something a threaded program can't do.

I really disagree on the critique of the documentation, I think it is excellent and better than most if not all major languages out there.

Also you can catch many of the runtime bugs running pylint.

Title: What are the drawbacks of Python?


问:
Use constructor or setter method?
I am working on a UI code where I have an Action class, something like this -

```<code>public class MyAction extends Action {
    public MyAction() {
        setText("My Action Text");
        setToolTip("My Action Tool tip");
        setImage("Some Image");
    }
}
</code>```

When this Action class was created, it was pretty much assumed that the Action class won't be customizable (in a sense - its text, tooltip or image will be not be changed anywhere in the code). Now, we are in need of changing the action text at some location in code. So, I suggested my co-worker to remove the hardcoded action text from the constructor and accept it as an argument, so that everybody is forced to pass the action text. Something like this code below -

```<code>public class MyAction extends Action {
    public MyAction(String actionText) {
        setText(actionText);
        setTooltip("My Action tool tip");
        setImage("My Image");
    }
}
</code>```

He, however, thinks that since setText() method belongs to base class it can be flexibly used to pass the action text wherever action instance is created. That way, there is no need to change the existing MyAction class. So his code would look something like this.

```<code>MyAction action = new MyAction(); //this creates action instance with the hardcoded text
action.setText("User required new action text"); //overwrite the existing text.
</code>```

I am not sure if that is a correct way to deal with problem. I think in above mentioned case user is anyway going to change the text, so why not force him while constructing the action? The only benefit I see with the original code is that user can create Action class without much thinking about setting text.

答:
It is useless to call setText(actionText) or setTooltip("My action tool tip") inside the constructor; it is easier (and you gain more performance) if you simply initialize the corresponding field directly:

```<code>    public MyAction(String actionText) {
        this.actionText = actionText;
    }
</code>```

If you change actionText during the life time of the MyAction corresponding object, you should place a setter method; if not initialize the field only in constructor without providing a setter method.

Since tooltip and image are constants, treat them as constants; have fields:

```<code>private (or even public) final static String TOOLTIP = "My Action Tooltip";
</code>```

Actually, when designing common objects (not beans or objects representing strictly data structures) it is a bad idea to provide setters and getters, since they kind of break encapsulation.

Title: Use constructor or setter method?

Body:
It is useless to call setText(actionText) or setTooltip("My action tool tip") inside the constructor; it is easier (and you gain more performance) if you simply initialize the corresponding field directly:

    public MyAction(String actionText) {
        this.actionText = actionText;
    }

If you change actionText during the life time of the MyAction corresponding object, you should place a setter method; if not initialize the field only in constructor without providing a setter method.

Since tooltip and image are constants, treat them as constants; have fields:

private (or even public) final static String TOOLTIP = "My Action Tooltip";

Actually, when designing common objects (not beans or objects representing strictly data structures) it is a bad idea to provide setters and getters, since they kind of break encapsulation.


答: I think you should use blob only if you have complex data type serialized, that is if you want to store in a single table a complex class. If you only want to store a String (or something equivalent) do not use blob.</p>

Title: Is a blob more efficient than a varchar for data that can be ANY size?

Body:
When setting up a database I want to use the most efficient data type for potentially fairly long data. Currently my project is to store song titles and thoughts pertaining to that song. Some titles might be 5 characters or longer than 100 characters and the thoughts could run pretty long.

Is it more efficient to use a varchar set to 8000 or to use a blob? Is using a blob the same as a varchar, in that there is a set size it is allocated regardless of what it holds? or is it just a pointer and it doesn't really use much space on the table? Is there a certain set size of a blob in KB or is it expandable?


答:
At the technical level (unit tests, integration tests, regression tests) programmers are probably the only qualified persons to be testers, because these kinds of tests are automatable and should thus be automated, which is something that requires programming.

But I don't think that's what you're talking about, and I'm pretty sure it's not what Joel Spolsky means either - it's the part that remains, the actual hands-on manual testing: turning a requirements document and functional spec into a test script and then meticulously executing this script against the finished product.

Being a good tester requires qualities that are mostly orthogonal to those that make a good programmer. There is a bit of overlap - you must be able to think analytically, you need a certain affinity with computers in general - but other than that, the skills of a tester are much different. That in itself doesn't mean you can have both skill sets, and in fact, quite some people probably do. However, to be a really good programmer requires a certain laziness (the desire to automate your chores away), while a really good tester needs persistence (check all of three thousand form fields for inconsistencies), and as a consequence, even those programmers who do have what it takes to be a tester typically abhor the idea.

And then there's the selective bias: A programmer who is already involved with a project, even if only marginally, already has some inside knowledge about the codebase, and will have a hard time approaching it with a blank mind, from an end-user's perspective. It doesn't even have to be explicit, as in "I know this button works, so I'll just note 'pass'"; it can be way more subtle, and those subtle effects can lead to critical edge cases being missed in testing.

Title: Are programmers bad testers?

Body:
I know this sounds a lot like other questions which have already being asked, but it is actually slightly different. It seems to be generally considered that programmers are not good at performing the role of testing an application. For example:

Joel on Software - Top Five (Wrong) Reasons You Don't Have Testers (emphasis mine)

Don't even think of trying to tell college CS graduates that they can
  come work for you, but "everyone has to do a stint in QA for a while
  before moving on to code". I've seen a lot of this. Programmers do not
  make good testers, and you'll lose a good programmer, who is a lot
  harder to replace.

And in this question, one of the most popular answers says (again, my emphasis):

Developers can be testers, but they shouldn't be testers. Developers
  tend to unintentionally/unconciously avoid to use the application in a
  way that might break it. That's because they wrote it and mostly test
  it in the way it should be used.

So the question is are programmers bad at testing? What evidence or arguments are there to support this conclusion? Are programmers only bad at testing their own code? Is there any evidence to suggest that programmers are actually good at testing?

What do I mean by "testing?" I do not mean unit testing or anything that is considered part of the methodology used by the software team to write software. I mean some kind of quality assurance method that is used after the code has been built and deployed to whatever that software team would call the "test environment."


答:
The question seems to be asking specifically about System Testing, so that's what I'm referring to throughout this answer.

I think there's an important distinction to be made between being a bad person to choose to perform testing, and actually being bad at testing.

Why programmers are bad at testing:

If you've written the code, you (should) have already thought of as many ways as possible that things could go wrong, and have dealt with them.

If finding a particularly niggly bug means that you have to then go and fix it, in a codebase you might be sick of, then that isn't going to help your motivation.

Why programmers are good at testing:

Programmers tend to be logical thinkers, and good at working in a systematic way.

Experienced programmers will be very good at quickly identifying edge cases and so coming up with useful tests. (If there's a formalised testing process, then most all of these cases should already have been identified and tested prior to systems testing.)

Programmers are pretty good at making sure that all the useful information goes into a bug report.

Why programmers are bad testers:

Programmers are more expensive than testers (in the vast majority of cases).

The mindset is fundamentally different: "Build a (working) product" vs "This thing isn't going out the door with any (unknown) bugs in it."

Testers will typically be more efficient - i.e. perform more tests in the same amount of time.

Programmers specialise in programming. QA professionals specialise in testing.

Title: Are programmers bad testers?


答:
Thanks for the inputs! Let us say for discussion that I know C++ fairly well.
Our school uses this book "Computer Graphics with OpenGL , but I afraid that the teachers are "dumbing" the subject down. Half of the class knows programming, calculus, linear algebra etc, but the other half is a "multimedia" class with no such experience and we shall use the same course material. </p>

<p>I guess I am after a solid book on Computer Graphics with the possibility to experiment and program the concepts at the same time. </p>

Title: Computer Graphics: Principles and Practice in C ( in Python? )

Body:
I am attending a Computer graphics course after the summer. I have read lots of good things about the book "Computer Graphics: Principles and Practice in C" for people who are willing to put in some work. My school does not focus on C/C++ until next year, so I have decided to learn Python this summer and get good at Python this following year. </p>

<p>How language dependent is this book? Can I work through it in Python? </p>

Body:
Thanks for the inputs! Let us say for discussion that I know C++ fairly well.
Our school uses this book "Computer Graphics with OpenGL , but I afraid that the teachers are "dumbing" the subject down. Half of the class knows programming, calculus, linear algebra etc, but the other half is a "multimedia" class with no such experience and we shall use the same course material.

I guess I am after a solid book on Computer Graphics with the possibility to experiment and program the concepts at the same time.


答:
From my experience, yes, programmers are bad testers. Too often have I seen others and myself go "Huh, but I tested that before I checked-in!" when confronted by a tester reproducing the bug in front of you.

Why? Well, I'm not sure why that is but maybe it's because we want to see the stuff working. Or we just want to get over with testing this or that feature already.

Anyway, testing isn't a skill we learned and we don't work as a programmer because we are good at breaking features. Also we might have no idea how to do proper test planning or all the other stuff that QA does. We aren't anymore qualified to do a tester's job than a tester is qualified to implement your new 3d rendering pipeline.

As in the question, testing doesn't mean anything automated but actually testing by using the program.

Title: Are programmers bad testers?


问:
Building a template engine - starting point
We're building a Django-based project with a template/generator component. This component will be separate from the project as such and can be Django/Python, Node, Java or whatever works. The idea is to generate questions based on a pattern. For eg., I would want to generate questions like "What is 2 + 3", "What is 5 + 8" based on the pattern "What is X + Y ; where X,Y < 10". In this sense, it's like a template engine.

The templates will contain references to objects with properties that are defined in the DB, say, a Bus. For eg, it could be something like

[object type="vehicle" weight="heavy"]

and it would have to pull a random object from the DB fulfilling the criteria : type="vehicle" weight="heavy" (bus/truck/jet) and then substitute that tag with an image, say, of a Bus.
Also it would have to be able to handle some processing. Eg:

What is [X type="integer" lte="10"] + [Y type="integer" lte="10"]

[option X+Y correct_ans="true"]

[option X-Y correct_ans="false"]

[option X+y+1 correct_ans="false"]

The engine would be expected to fill in a random integer value <= 10 for X and Y and show radioboxes for each of the options. Would also have to store the fact that the first option is the correct answer.

Does it to make sense to write something from the scratch? Or is it better to use an existing templating system (like Django's own templating system) as a starting point? Any suggestions on how I can approach this?

edit : Clarification of use case

答:
First of all, I think having the template system pull items from the database directly is a bad idea. It introduces a tight coupling between your templates (presentation) and database (data storage), with no way to add any logic between the two. This means that any change to your database schema has a potential impact on your templates, and vv.

Instead, the template engine should be able to consume arbitrary data structures, as long as they implement a dictionary-like interface. If you throw in the ability to call functions / methods, you can have the same functionality, only on top of objects rather than the naked database. If your objects have lazy-loading properties, then you can even trigger trips to the database from the template after all (by requesting such a property), only that the request still goes through your normal application logic before hitting the database. Not only does this mean you can change your database schema and catch the regression through the use of compatibility adapters, it also allows you to:

add authorization to your data access

pre-massage data before sending it to the template

display data from sources other than a database

implement all sorts of caching

do i18n by calling a special function (many template engines call it _()) on anything you want translated (and, obviously, implementing that special function to do your translating)

Typically, this is solved either by passing a data structure to the template engine when evaluating a template, or by making the templates so that whatever is currently in scope at the time the template is called, is accessible in the template.

As to whether you should invent your own template engine: Making template engines is great fun, especially if you love building parsers and lexers and tweaking AST's and optimizing rendering code, but I'd first hit the market and see what's already out there. This page (despite the source, not specific to CherryPy) gives a nice starting point. If you know for sure that no template engine exists to fill your needs, by all means make your own, but be advised that it's harder than it looks.


答:
The only benefit I see with the original code is that user can create Action class without much thinking about setting text.

That is actually not a benefit, for most purposes it's a drawback and in the remaining cases I'd call it a tie. What if someone forgets to call setText() after construction? What if that is the case in some unusual case, perhaps an error handler? If you want to really force the text to be set, you need to force it at compilation time, since only compile-time errors are actually fatal. Anything that happens at run-time depends on that particular code path being executed.

I see two clear paths forward:

Use a constructor parameter, as you suggest. If you really want to, you can pass null or an empty string, but then the fact that you are not assigning a text is explicit rather than implicit. It's easy to see the existence of a null parameter and see that there was probably some thought put into it, but not so easy to see the lack of a method call and determine if the lack of such was intentional or not. For a simple case like this, this is probably the approach I would take.

Use a factory/builder pattern. This may be overkill for such a simple scenario, but in a more general case it is highly flexible as it allows you to set any number of parameters, and check preconditions before or during object instantiation (if constructing the object is a large operation and/or the class can be used in more than one way, this can be a huge advantage). Particularly in Java it is also a common idiom, and following established patterns in the language and framework you are using is very rarely a bad thing.

Title: Use constructor or setter method?

Body:
I am working on a UI code where I have an Action class, something like this -

```<code>public class MyAction extends Action {
    public MyAction() {
        setText("My Action Text");
        setToolTip("My Action Tool tip");
        setImage("Some Image");
    }
}
</code>```

When this Action class was created, it was pretty much assumed that the Action class won't be customizable (in a sense - its text, tooltip or image will be not be changed anywhere in the code). Now, we are in need of changing the action text at some location in code. So, I suggested my co-worker to remove the hardcoded action text from the constructor and accept it as an argument, so that everybody is forced to pass the action text. Something like this code below -

```<code>public class MyAction extends Action {
    public MyAction(String actionText) {
        setText(actionText);
        setTooltip("My Action tool tip");
        setImage("My Image");
    }
}
</code>```

He, however, thinks that since setText() method belongs to base class it can be flexibly used to pass the action text wherever action instance is created. That way, there is no need to change the existing MyAction class. So his code would look something like this.

```<code>MyAction action = new MyAction(); //this creates action instance with the hardcoded text
action.setText("User required new action text"); //overwrite the existing text.
</code>```

I am not sure if that is a correct way to deal with problem. I think in above mentioned case user is anyway going to change the text, so why not force him while constructing the action? The only benefit I see with the original code is that user can create Action class without much thinking about setting text.


答:
The pattern for the success case:

Read POST request

Validate POST data

Pre-process POST data

Store

Redirect

Read GET request

Display success message

And in the failure case:

Read POST request

Validate POST data (if fail, go to 5.)

Pre-process POST data (if fail, go to 5.)

Store (fails)

Display error message

In your code, this structure looks somewhat like so (pseudocode, obviously):

```<code>if (is_post_request) {
    data = empty_data()
    try {
        data = read_post_data()
        validate(data)
        preprocess(data)
        store(data)
        redirect()
        exit
    }
    catch (ex) {
        display_form(data, error_message = ex)
    }
}
else {
    data = empty_data()
    display_form(data, error_message = NULL)
}
</code>```

The reason you're redirecting is that you want to avoid a second database update when the user reloads. Because of this, you need to first store and then redirect. In fact, I recommend you make a habit of calling exit immediately after each redirect. There is no point in doing anything whatsoever in the current request once you've redirected (except cleanup, such as closing open file handles).

The reason you don't redirect in the error case is because nothing has been stored yet - if the user reloads, they'll just run into the same error again. If you were to redirect in the error case, you'd have to carry the error messages over the redirect, which is possible but not really pretty, and you'd have an unnecessary round trip.

Body:
The pattern for the success case:

Read POST request

Validate POST data

Pre-process POST data

Store

Redirect

Read GET request

Display success message

And in the failure case:

Read POST request

Validate POST data (if fail, go to 5.)

Pre-process POST data (if fail, go to 5.)

Store (fails)

Display error message

In your code, this structure looks somewhat like so (pseudocode, obviously):

if (is_post_request) {
    data = empty_data()
    try {
        data = read_post_data()
        validate(data)
        preprocess(data)
        store(data)
        redirect()
        exit
    }
    catch (ex) {
        display_form(data, error_message = ex)
    }
}
else {
    data = empty_data()
    display_form(data, error_message = NULL)
}

The reason you're redirecting is that you want to avoid a second database update when the user reloads. Because of this, you need to first store and then redirect. In fact, I recommend you make a habit of calling exit immediately after each redirect. There is no point in doing anything whatsoever in the current request once you've redirected (except cleanup, such as closing open file handles).

The reason you don't redirect in the error case is because nothing has been stored yet - if the user reloads, they'll just run into the same error again. If you were to redirect in the error case, you'd have to carry the error messages over the redirect, which is possible but not really pretty, and you'd have an unnecessary round trip.


答:
I think programmers are bad at testing their own code.

We like to believe our code works perfectly according to the requirements and test it as such.  In my place we test our own code, then test each others code before releasing into the actual testing cycle and far more bugs were caught that way than just by testing our own code

Title: Are programmers bad testers?


答:
Constructor overloading would be a simple and straightforward solution here:

```<code>public class MyAction extends Action {
    public MyAction(String actionText) {
        setText(actionText);
        setTooltip("My Action tool tip");
        setImage("My Image");
    }
    public MyAction() {
        this("My Action Text");
    }
}
</code>```

It is better than calling .setText later, because this way nothing needs to be overwritten, actionText can be the intended thing right from the start.

As your code evolves and you will need even more flexibility (which will surely happen), you will benefit from the factory/builder pattern suggested by another answer.

Title: Use constructor or setter method?

Body:
Constructor overloading would be a simple and straightforward solution here:

public class MyAction extends Action {
    public MyAction(String actionText) {
        setText(actionText);
        setTooltip("My Action tool tip");
        setImage("My Image");
    }
    public MyAction() {
        this("My Action Text");
    }
}

It is better than calling .setText later, because this way nothing needs to be overwritten, actionText can be the intended thing right from the start.

As your code evolves and you will need even more flexibility (which will surely happen), you will benefit from the factory/builder pattern suggested by another answer.


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

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

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

答:
One issue in C is that there's a tradition of using values other than 0 and 1 for booleans.

```<code>typedef enum { WHATEVER = 1 << 4 } MyFlags;
if (flags & WHATEVER) {
}
</code>```

or even relying on -1 being true.

The problem is say you're writing an API:

```<code>struct foo {
  unsigned int bar : 1;
};

void myapi_foo_set_bar(struct foo *foo, int bar) {
   foo->bar = bar;
}
</code>```

Here if bar isn't canonicalized to 0 or 1 it won't fit in the bitfield and it breaks:

```<code>myapi_foo_set_bar(foo, flags & WHATEVER); /* broken */
</code>```

You can find other ways non-canonical bools break as well, such as comparing them to TRUE or FALSE as in the question!

Anyway what I'm coming around to is that it often makes sense to canonicalize a bool:

```<code>foo->bar = bar != FALSE;
</code>```

This is a C-specific weirdness, of course.

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

Body:
One issue in C is that there's a tradition of using values other than 0 and 1 for booleans.

typedef enum { WHATEVER = 1 << 4 } MyFlags;
if (flags & WHATEVER) {
}

or even relying on -1 being true.

The problem is say you're writing an API:

struct foo {
  unsigned int bar : 1;
};

void myapi_foo_set_bar(struct foo *foo, int bar) {
   foo->bar = bar;
}

Here if bar isn't canonicalized to 0 or 1 it won't fit in the bitfield and it breaks:

myapi_foo_set_bar(foo, flags & WHATEVER); /* broken */

You can find other ways non-canonical bools break as well, such as comparing them to TRUE or FALSE as in the question!

Anyway what I'm coming around to is that it often makes sense to canonicalize a bool:

foo->bar = bar != FALSE;

This is a C-specific weirdness, of course.


答:
The are several level of testing. The "low level" testing can and must be done by developers. I think at unit testig.

On the other hand, "high level" testing are totally another thing.
In general I think developers are bad tester not because they miss skills, but because is very hard change way to think and way to work in a few time.

I use to try test as mush as possible my codes, but after at least 10 mins made by a tester, something to consider a bug or enhancement arise. This means that test something you create, is an hard job. You know where to click, you know whene click, you know the business logic, you probably know how data are persisted. You are a god you'll never fall.

Title: Are programmers bad testers?


答:
I think this is true if we are going to make a generic action class (like update, which is used to update Employee, Department ...).
It’s all depends on scenario. If a specific action (like update employee) class (used many place in application - Update employee) is created with the intension to keep same text, tooltip and image at every place in the application (for consistency point of view). So hardcoding can be done for text, tooltip and image to provide the default text, tooltip and image. Still to give more flexibility, to customize these, it should have corresponding setter methods. Keeping in the mind only 10% places we have to change it.
Taking action text every time from user can cause Different text every time for same action. Like 'Update Emp', 'Update Employee', 'Change Employee' or 'Edit Employee'. I am not sure but I think this can create the confusion to the user that this is something different.</p>

Title: Use constructor or setter method?


问:
Does it work when a developer is the project manager's boss?
I am in the planning stage of a project and I am looking to hire a project manager. I would like to do some coding and keep eye on all parts of the project. However, i have a feeling that a project manager will get better results. I have the following options:
1) manage the project and not code
2) hire a project manager and code myself

I am worried that the project manager will feel impeded by having the project owner in the development team. If I run the project, the team might fall apart causing the project to fail. To stick within budget, I have to be involved in one capacity or another.

Does anyone have experience with this situation, any suggestions?

more info: 4 in-house developers each responsible for a specific area. The developers can also outsource work if agreed to by the project manager.

答:
Short answer: you need to hire professionals to grow business, and as a project owner you need to clarify the responsibilities and authority within the project/company.

Long answer:
My understanding of a project manager is planning and leading software project(s).

1) Manage the work, who does what ?

2) Plans the work load - timing on what we deliver when?

3) Makes decisions under given budget and resources (people/hardware/space/time)

(*) look at provided links below for a complete reference

Good start point Wikipedia - Software project management on what a PM in software development expected to do. In addition,  i would suggest to look at Q&A - How does Project Management Costs vary with the size of the whole software development project.