问:
How to split & manage projects
I started a project (a Windows based timetable program that helps you stay organised with your subjects and assignments).

The problem is that I'm not sure how I should manage this project and what order to build things. I.e. Should I build all the different interface elements then write the code or should I make an interface, code it, make another interface then code that? So my question is; how do I split up this longish project into small, ordered pieces to complete; and how should I order this?

答:
Obviously, there are multiple ways to split a project into more manageable parts, but the one way that I find both easy and useful is to structure your project around the features that you plan to implement.

First, define your use cases, and make a list of features that you plan to have in your product. Then prioritize the features that the product must have to be marginally usable. Once this set is in place, you could either refactor for things that you learned about the domain that you missed before you started, or prioritize the next set of features, and add them on.

The advantage of this approach is that you do not have to decide on the timeline upfront all at once. Developing new things is inherently unpredictable, so keeping your timeline as open as possible is a welcome thing.

Title: How to split & manage projects


答:
Everyone organizes a project slightly different, so it's up to you to figure out what works best for your needs. Here's what I do, and hopefully that'll help you out.

Write down EXACTLY what you want your project to accomplish. Think of it like a start-up pitch: clearly define the objectives of this project and how you're going to accomplish them.

Draw out a flow cart for the basic workflow associated with your project. How do you want the user to interact with it? How will things work on the back-end? What may be some common pitfalls that you'll need to look out for? All of these things should be clearly defined in a simple-to-digest way.

Start small and work your way up. This may seem a bit ambiguous, so let me explain: Obviously, a project goes through iterations and "grows" (both in maturity and complexity) over time. So, start with the bare minimum use case, and work your way up from there. For example, I'm developing a small messaging application. I'm not going to dive right into a client/server model where clients send messages to the server. Instead, I started off by writing simple plain-text messages to a file, and having the program parse that file and print out the correct output to STDOUT. When I get that part done, I'll refactor that code to work in a client/server model. Adapt that workflow for your needs, obviously.

Just a note to keep in the back of your head: until your project reaches "production readiness", treat every character of code as expendable. If you think of a "better" way of doing things, do it. Don't keep old code around just because. Even when your project reaches production, don't hesitate to throw out entire files as necessary. Your code can always be made better. Always.

Jokes aside, that's essentially how I organize my projects. I'll follow the basic work flow, writing code for a basic use case, and then work my way up from there, refactoring along the way. Hope that helps!

ContentLicense: CC BY-SA 3.0

Title: How to split & manage projects

Body:
I started a project (a Windows based timetable program that helps you stay organised with your subjects and assignments).

The problem is that I'm not sure how I should manage this project and what order to build things. I.e. Should I build all the different interface elements then write the code or should I make an interface, code it, make another interface then code that? So my question is; how do I split up this longish project into small, ordered pieces to complete; and how should I order this?


问:
When or why should one use getters/setters for class properties instead of simply making them public properties?
I program primarily in ColdFusion but this is a general OOP question.

Is there any benefit to using:

```<code>getProp() {
    return prop;
}

setProp(val) {
    prop = val;
}
</code>```

As opposed to simply

```<code>obj = new Obj();
obj.prop = "1";
</code>```

答:
I think you must try to use getters and setters always. In your case you have something like:

```<code>obj = new Obj();
obj.prop = "1";
</code>```

What if you have other 1000 references to obj.prop? And then, you decide that obj.prop cannot be a negative like "-4" (just an example). If that's the case, how would you control that nobody passes such values to the object? If you used a setProp method it will be easy:

```<code>setProp(val) {
    if(val < 0)
      // doSomething
    prop = val;
}
</code>```

In general, that's the kind of situations where using setter and getter would make your code easier to maintain. There are many other situations like that and most of them encourage you to use setter and getter.

However, I sometimes use classes with public fields. I do it when that class is an inner private class; which means that it is not used outside the parent class. In such cases the excuse is: "I always know what data to assign and that it is valid". Though, it is always a case of laziness.

Some guys say it is faster in runtime to assign the values directly, and that might be true but I think it is difficult to note a significant difference one way or the other.

Body:
I think you must try to use getters and setters always. In your case you have something like:

obj = new Obj();
obj.prop = "1";

What if you have other 1000 references to obj.prop? And then, you decide that obj.prop cannot be a negative like "-4" (just an example). If that's the case, how would you control that nobody passes such values to the object? If you used a setProp method it will be easy:

setProp(val) {
    if(val < 0)
      // doSomething
    prop = val;
}

In general, that's the kind of situations where using setter and getter would make your code easier to maintain. There are many other situations like that and most of them encourage you to use setter and getter.

However, I sometimes use classes with public fields. I do it when that class is an inner private class; which means that it is not used outside the parent class. In such cases the excuse is: "I always know what data to assign and that it is valid". Though, it is always a case of laziness.

Some guys say it is faster in runtime to assign the values directly, and that might be true but I think it is difficult to note a significant difference one way or the other.


问:
Designing an API on top with Java RMI and Rest APIs
I'm working on the backend of a java web application. We have a document repository (Fedora Commons specifically) where we house xml files. I want to abstract the API of the repository internally so that we aren't tightly coupled to one product. I'd also like to give the flexibility of connecting to to a repository via Java RMI or REST APIs. I was hoping to get advice or resources on how to implement something like this.

My thought it that I'd have some abstract repository class that had methods like getRecord, updateRecord, and deleteRecord. In the constructor I would pass the URI for the repository and the API method and port. This would allow some flexibility in the future so that if the REST api became more practical, but allow the flexibility or using RMI which could (should?) have better performance.

Am I over thinking this or am I on the right path?

答:
I think you are on the right path.

There is nothing wrong with putting an abstraction layer on top of a third party API.  Actually it is a very good idea.  At some point, you may want to replace that API with another third party API, and you would only have to change your abstraction layer, instead of your entire application.

Now admittedly this is an ideal scenario. The truth is that you'll probably end up locked into that vendor for other reasons.  But, you should still design this way anyway as it is good practice.


问:
Am I wrong to disagree with A Gentle Introduction to symfony's template best practices?
I am currently learning symfony and going through the book A Gentle Introduction to symfony and came across this section in "Chapter 4: The Basics of Page Creation" on creating templates (or views):

"If you need to execute some PHP code in the template, you should avoid using the usual PHP syntax, as shown in Listing 4-4. Instead, write your templates using the PHP alternative syntax, as shown in Listing 4-5, to keep the code understandable for non-PHP programmers."

Listing 4-4 - The Usual PHP Syntax, Good for Actions, But Bad for Templates

```<code><p>Hello, world!</p>
<?php
if ($test) {
   echo "<p>".time()."</p>";
}
?>
</code>```

(The ironic thing about this is that the echo statement would look even better if time was a variable declared in the controller because then you could just embed the variable in the string instead of concatenating)

Listing 4-5 - The Alternative PHP Syntax, Good for Templates

```<code><p>Hello, world!</p>
<?php if ($test): ?>
    <p><?php echo time(); ?>
</p><?php endif; ?>
</code>```

I fail to see how listing 4-5 makes the code "understandable for non-PHP programmers", and its readability is shaky at best. 4-4 looks much more readable to me. Are there any programmers who are using symfony that write their templates like those in 4-4 rather than 4-5? Are there reasons I should use one over the other? There is the very slim chance that somewhere down the road someone less technical could be editing it the template, but how does 4-5 actually make it more understandable to them?

答:
There is a third general syntax, which I have always found the most readable:

```<code><p>Hello, world!</p>
<?php if ($test) { ?>
    <p><?= time(); ?></p>
<?php } ?>
</code>```

Don't mix echo and printf with turning php on/off by way of ?>foo<?php - it's much harder to mentally separate output from code.

Contrary to popular advice, keep the { curly braces }.  I find them much easier to see when looking for the start and end of code blocks.

Use short tags if available:  <?= is identical to <?php echo.  It reduces the general amount of clutter, and starting in PHP 5.4, cannot be disabled.

Although echo isn't that difficult a concept, it also reduces the amount of PHP a template designer might have to know.

One issue I have with the HTML format:  I moved the closing
 to the line above it.  Now the end of the if statement has the same indentation as the beginning.

ContentLicense: CC BY-SA 2.5

Body:
There is a third general syntax, which I have always found the most readable:

<p>Hello, world!</p>
<?php if ($test) { ?>
    <p><?= time(); ?></p>
<?php } ?>

Don't mix echo and printf with turning php on/off by way of ?>foo<?php - it's much harder to mentally separate output from code.

Contrary to popular advice, keep the { curly braces }.  I find them much easier to see when looking for the start and end of code blocks.

Use short tags if available:  <?= is identical to <?php echo.  It reduces the general amount of clutter, and starting in PHP 5.4, cannot be disabled.

Although echo isn't that difficult a concept, it also reduces the amount of PHP a template designer might have to know.

One issue I have with the HTML format:  I moved the closing </p> to the line above it.  Now the end of the if statement has the same indentation as the beginning.


答:
There's no particular reason to use getters/setters if you dont need them.  Public properties are there, after all, for a reason.  Otherwise you're just cluttering the code with getter and setter functions that may never do anything more than assign a value.

Some of it is language dependent - some languages steer you more to them than others.  Delphi, for example, has properties, which can effectively act as either a wrapper around a private variable, or a getter/setter.  So there's no actual need to use a getter/setter method if you dont immediately need it, since a public variable can be recast as a property using getter/setters, keeping the interface to that class the same for the code that uses it (i.e., even though it may be a getter/setter under the hood, to code setting an object's property, it still does so as if it was a public variable).

Basically my advice is what it always is... worry less about how other people say you should be coding, and more about making sure your projects get done and are easily maintainable.  If that means getters/setters to you, then use 'em.  If it doesnt, thats good too.

Title: When or why should one use getters/setters for class properties instead of simply making them public properties?

Body:
I program primarily in ColdFusion but this is a general OOP question.

Is there any benefit to using:

```<code>getProp() {
    return prop;
}

setProp(val) {
    prop = val;
}
</code>```

As opposed to simply

```<code>obj = new Obj();
obj.prop = "1";
</code>```


答:
In languages without C-style structs, it's generally accepted, even encouraged, to use public fields for "Plain Old Data" classes, like complex numbers, points, etc.  Otherwise, getters and setters are recommended.

In addition to Cristian's excellent point about maintainability, it also makes debugging much easier to have only one place where a value can be changed.  For example, maybe a field is used to index an array and you get an out of bounds exception.  Without a setter, you're going to go through the entire code finding the one place that sets it to the wrong value.  With a setter, you just put a breakpoint in the setter and you know very quickly.  Setters also allow you to enforce data validation.

In other words, it's slightly more typing in the short run that maybe is not needed later on, but is extremely useful when it is.


问:
Biggest mistake you've ever made
Similar to the question I read on Server Fault, what is the biggest mistake you've ever made in an IT related position. Some examples from friends:

I needed to do some work on a production site so I decided to copy over the live database to the beta site. Pretty standard, but when I went to the beta site it was still pulling out-of-date info. OOPS! I had copied the beta database over to the live site! Thank god for backups.

And for me, I created a form for an event that was to be held during a specific time range. Participants would fill out the form for a chance to win, and we would send the event organizers a CSV from the database. I went into the database, and found ONLY 1 ENTRY, MINE. Upon investigating, it appears as though I forgot an auto increment key, and because of the server setup there was no way to recover the lost data.

I am aware this question is similar to ones on Stack Overflow but the ones I found seemed to receive generic answers instead of actual stories :)

What is the biggest coding error/mistake ever…

答:
The customer wants a mailout to their entire userbase that will basically send a personalised email about an event and when they click on a link in the email will automatically log them in to a form with half their data filled in.

I write the code, test the code, it works fine, the links work, it's pretty smooth. Having checked and double checked everything, I switch over to the live list and away we go.

The live list is significantly bigger than my sample data and the mail server falls over. I have to stop my console app, then realise I'll have to restart it from where it stopped. Fortunately this feature is not too hard to add and I have logged what users the mailout has already gone to, so having got the mailserver up and running again, and reconfigured the code to be able to restart from the point it failed previously and to pause to let the mailserver catch up, away we go.

Unfortunately I had somehow managed to not get all my code updating right. I don't remember the details of what I did, but the query to get the user data was getting one set of data, the query to generate the hash was getting another, so if a user clicked on the link they would get to a form that contained someone else's personal data from their account details. And this in a niche industry where there were lots of competetive small businesses on the list.

It didn't take long for the phone to start ringing at the customers' office...

That was the only mistake so far that has lead to me offering my resignation.

Title: Biggest mistake you've ever made


问:
How to convince teammates to use TDD
I am the only person on my team that use TDD. How do I make them to use it?

I am annoyed that when I pull, someone's code will break my tests and I am the one who has to fix them.

Will using github, fork and pull request solve this problem, so that they need to pass the test before the pull is accepted?

I am not the project manager and I can't seems to convince her to use it.

答:
The way I see it, the only way to convince for anything about tests is to demonstrate that they are useful - ie that test failures help to find and fix bugs.

The way you describe the problem though, looks like this is not the case here. Look...

...when I pull, someone's code will break my tests and I am the one who has to fix them.

If I understand correctly, you mean you have to modify tests. Well, that does not sound like test failures help to find and fix bugs does it? If tests don't help in finding bugs, it's pretty weak position to start convincing your colleagues - what could they expect to gain? tedious fixes in fragile test code?

This may sound like a dead end, but it really isn't. Your final goal (convince for TDD) still makes pretty good sense, don't drop it. Just re-focus your efforts on removing the obstacle you discovered.

Test failures that bother you now are essentially "false alerts" - meaning these are bugs in tests not in the code. Use these as an opportunity to improve tests, to learn how to make good reliable test design. Work on tests to make "false alerts" less frequent and to make it easier to discover real bugs in tested code.

As you discover real bugs, let your colleagues know and help them fix - and don't forget to point that these bugs are found by your tests. That will make a really solid ground to convince your colleagues.

It is worth mentioning that test design skills you develop at "preliminary" stage will most probably be needed again, if (when:) you finally convince your teammates to use TDD. Think of it...

...What would happen when test driven development is introduced to your inexperienced colleagues?

First thing to expect is that guys will start writing crappy tests and (horror!) even breaking good ones while learning. To help them find a way to do it right you'll need quite a solid understanding of good test design.

All the errors you find and fix in your tests now, will be repeated again and again by all your teammates when they begin learning. If (when!) that happens, you would better be prepared to quickly and clearly explain how to improve if you want them to remain positive about TDD.

Title: How to convince teammates to use TDD


答:
Take this advice for what it is worth, but I strongly urge you to reconsider the use of REST API instead of Java RMI.

Without having solid metrics to compare, I would highly suspect that performance between Java RMI and REST would be similar.

Java RMI is an older technology which is not as widely adopted.

More Java developers likely have experience with REST and web services versus RMI.

Clients of your server are tied to Java technology (think expansion to mobile clients for instance)

Security concerns

These are just a handful of the issues with it.  Beyond that, having to debug poorly written legacy RMI applications was a horrifying ordeal for me that has mentally and emotionally scarred me for life.  That may make me a little prejudiced.

Title: Designing an API on top with Java RMI and Rest APIs

Body:
I'm working on the backend of a java web application. We have a document repository (Fedora Commons specifically) where we house xml files. I want to abstract the API of the repository internally so that we aren't tightly coupled to one product. I'd also like to give the flexibility of connecting to to a repository via Java RMI or REST APIs. I was hoping to get advice or resources on how to implement something like this.

My thought it that I'd have some abstract repository class that had methods like getRecord, updateRecord, and deleteRecord. In the constructor I would pass the URI for the repository and the API method and port. This would allow some flexibility in the future so that if the REST api became more practical, but allow the flexibility or using RMI which could (should?) have better performance.

Am I over thinking this or am I on the right path?


问:
Application that provides unique keys to multiple processes
Any idea on how to build an application that provides unique keys each time it get called by another process.

Calling process isn't my problem here, my problem is how to sync between two(or more) processes and preventing it from providing the same key to both of them.

I'd really appreciate your help in this issue, please only outline the solution and I'll try to implement it.

答:
I haven't used C in ages, but there must be some way to synchronize your code so only one processes, or thread, can get into it at one time.  Something like:

```<code>int unique_index = 0;

synchronized int GetUnique()  {
    int i = unique_index++;
    return i;
}
</code>```

You'd want to make sure unique_index was accessed only from within GetUnique or other synchronized code.  If it gets called from 10,000 threads all at the same time, you might experience some delays and you'd need something more clever, but that should do for a start.

If this program is to start and stop and deliver unique numbers to other programs, you'd need to make sure GetUnique would not do anything until the program was up and had recovered its data (unique_index) from a file or where ever.  Likewise, GetUnique would have to stop responding before data was saved during shutdown.

Body:
I haven't used C in ages, but there must be some way to synchronize your code so only one processes, or thread, can get into it at one time.  Something like:

int unique_index = 0;

synchronized int GetUnique()  {
    int i = unique_index++;
    return i;
}

You'd want to make sure unique_index was accessed only from within GetUnique or other synchronized code.  If it gets called from 10,000 threads all at the same time, you might experience some delays and you'd need something more clever, but that should do for a start.

If this program is to start and stop and deliver unique numbers to other programs, you'd need to make sure GetUnique would not do anything until the program was up and had recovered its data (unique_index) from a file or where ever.  Likewise, GetUnique would have to stop responding before data was saved during shutdown.


问:
How would you explain that software engineering is more specialized than other engineering fields?
I work with someone who insists that any good software engineer can develop in any software technology, and experience in a particular technology doesn't matter to building good software. His analogy was that you don't have to have knowledge of the product being built to know how to build an assembly line that manufactures said product.

In a way it's a compliment to be viewed with an eye such that "if you're good, you're good at everything", but in a way it also trivializes the profession, as in "Codemonkey, go sling code". Without experience in certain software frameworks, you can get in trouble fast, and that's important.

I tried explaining this, but he didn't buy it. Any different views or thoughts on this to help explain that my experience in one thing, doesn't translate to all things?

答:
This sort of thing happens a lot where I work.

I like to compare to my wife's uncle's profession - a car mechanic.

He specializes in Mercedes, he can apply his knowledge to other makes of cars, and he does - some of them rather rare, but that doesn't mean that he can immediately repair make X because you say it's making a noise.

I program in a few languages, but that doesn't mean I know why Safari on your MacBook reloads pages every time you change tab (today's weird call). I'll try and figure out why but I'm not going to know off the top of my head because the computing field is HUGE.

In both cases after spending some time looking into our respective fields we could probably work out the answer but not in the ten seconds that people think because "but you work with cars" or "but you work with computers".

Do people say such things to their local doctor (such as "I have a headache what disease do I have?") - I bet they do because most people really don't understand that there is more to any one profession than their immediate expectations of said profession.


问:
I just started a job with Scrum and something seems to be missing. I am new to Scrum
The code is a complete mess of a combination of classic ASP/ASP.NET. The scrum consist of us patching up the big mess or making additions to it. We are all too busy doing that to start a rewrite so I am wondering..

Where is the part in Scrum where the developers can have the power to say that enough is enough and demand that they are given time to start the big rewrite? We seem in an endless loop of just patching old code with 'Stories'.

So things are being run by the non-technical people who seem to have no desire to push for a rewrite because they don't understand how bad the codebase has gotten..

So who is in charge of making this big rewrite change happen? The developers? The Scrum Master?

The current strategy is just to find time and do it ourselves without the higher-ups involved since they are mostly to blame for the current mess we are in.. <- insert rant about non-technical people telling technical people what to do here ->.

答:
Wait....what?

You're patching? You should be refactoring. Stick to agile values. Use TDD and appropriate practices and the situation will eventually become better.


问:
try-catch in javascript... isn't it a good practice?
There is a provision for try-catch block in javascript. While in java or any other language it is mandatory to have error handling, I don't see anybody using them in javascript for greater extent. Isn't it a good practice or just we don't need them in javascript?

答:
Try/catch in Javascript is not as bullet-proof as in other languages, due to Javascript's asynchronous nature. Consider this snippet:

```<code>try {
    setTimeout(function() {
        do_something_that_throws();
    }, 1000);
}
catch (e) {
    alert("You won't see this!");
}
</code>```

The problem is that the control flow leaves the try block before do_something_that_throws() gets executed, so the error thrown inside the callback never gets catched.

So try/catch is basically inappropriate in many cases, and it's not always obvious whether something executes code asynchronously or not. Fortunately, javascript with its peculiar single-threaded-asynchronous-callback idiom and its support for actual closures provides an elegant alternative: continuation-passing style error handling. Just pass the proper response to any error as a function, e.g.:

```<code>setTimeout(function () {
    do_something_that_calls_err(function(err) {
        alert("Something went wrong, namely this: " + err);
    }),
    1000);
</code>```

Body:
Try/catch in Javascript is not as bullet-proof as in other languages, due to Javascript's asynchronous nature. Consider this snippet:

try {
    setTimeout(function() {
        do_something_that_throws();
    }, 1000);
}
catch (e) {
    alert("You won't see this!");
}

The problem is that the control flow leaves the try block before do_something_that_throws() gets executed, so the error thrown inside the callback never gets catched.

So try/catch is basically inappropriate in many cases, and it's not always obvious whether something executes code asynchronously or not. Fortunately, javascript with its peculiar single-threaded-asynchronous-callback idiom and its support for actual closures provides an elegant alternative: continuation-passing style error handling. Just pass the proper response to any error as a function, e.g.:

setTimeout(function () {
    do_something_that_calls_err(function(err) {
        alert("Something went wrong, namely this: " + err);
    }),
    1000);


答:
Sometimes it helps me to just... start.  Wherever I can.

Not to say that you shouldn't design; obviously any project needs a design, and a big project probably needs a lot of design.  But I think it's easy to get paralyzed by the hugeness of the design; I find there is an awkward phase after figuring out what all the big chunks are but before it is clear to me what or how I should be coding.

At that point, I like to just start writing class declarations. Of course, everything I'm writing is likely to be discarded or dramatically changed, but I feel like I get a much better handle on the project once I start working on it.  So I'll spend a couple hours writing code, and then go back to my design and refine it - probably I've thought of another package I'll need, or changed my ideas about the hierarchy I'm building.  Then, when my design seems to make sense again and/or I get stuck, I go back to the code.  After a few iterations of this, my design is complete and I have a good handle on what needs to be done - and when I know exactly what needs to be done, it's often very clear what order it should be done in.

Title: How to split & manage projects


答:
In addition to the good points already mentioned, for C#.NET:

A - Unlike fields, a property does not have any associated storage space within the object.

B - The property value is set (or calculated) when accessed not when the object is instantiated.

Note:
A field value may be set only when used if you use the volatile keyword when defining the field.

C - A property could assign a calculated value based on specific instance data to the result (or input) whereas in the case of a field, you need to invoke a method to do that, this makes your code confusing because it would require both methods and properties to obtain the object state.

D - Fields can’t be writeonly but Properties can (writeonly is rarely used but is still part of the language).

Reference:
Source for A and B above is the book: Accelerated C# 2010. Information have been re-phrased based on my own understanding. For more information on volatile keyword, see Black-Wasp-Volatile Keyword.


问:
Are SQL Injection vulnerabilities in a PHP application acceptable if mod_security is enabled?
I've been asked to audit a PHP application. No framework, no router, no model. Pure PHP. Few shared functions. HTML, CSS, and JS all mixed together. I've discovered numerous places where SQL injection would be easily possible. There are other problems with the application (XSS vulnerabilities, rampant inline CSS, code copy-pasted everywhere) but this is the biggest. Sometimes they escape inputs, not using a prepared query or even mysql_real_escape_string(), mind you, but using addslashes(). Often, though, their queries look exactly like this (pasted from their code but with columns and variable names changed):

```<code>$user = mysql_query("select * from profile where profile_id='".$_REQUEST["profile_id"]."'");
</code>```

The developers in question claimed that they were unable to hack their application. I tried, and found mod_security to be enabled, resulting in HTTP 406 for some obvious SQL injection attacks. I believe there to be sophisticated workarounds for mod_security, but I don't have time to chase them down.

They claim that this is a "conceptual" matter and not a "practical" one since the application can't easily be hacked. Their internal auditor agreed that there were problems, but emphasized the conceptual nature of the issues.

They also use this conceptual/practical argument to defend against inline CSS and JS, absence of code organization, XSS vulnerabilities, and massive amounts of repetition.

My client (rightly so, perhaps) just wants this to go away so they can launch their product. The site works. You can log in, do what you need to do, and things are visibly functional, if slow. SQL Injection would indeed be hard to do, given mod_security. Further, their talk of "conceptual vs. practical" is rhetorically brilliant, considering that my client doesn't understand web application security. I worry that they've succeeded in making me sound like an angry puritan.

In many ways, this is a problem of politics, not technology, but I am at a loss. As a developer, I want to tell them to toss the whole project and start over with a new team, but I face a strong defense from the team that built it and a client who really needs to ship their product.

Is my position here too harsh? Even if they fix the SQL Injection and XSS problems can I ever endorse the release of an unmaintainable tangle of spaghetti code?

EDIT: As to my role on this project, I'm not a security expert, I'm a web developer generalist. the client initially asked me to load test the app and make recommendations for scalability. I haven't gotten that far yet, because when I first read the output of the home page, I saw inline CSS, table based layouts, and all sorts of crazy JS, so I requested a copy of the code, where I found the unholy mess described above. They don't even abstract the HTML header and footer. Every PHP file has a slightly different pasted version.

And as to the app itself, it does store personal information, and it processes (but does not store) credit card data.

答:
Well....it depends. If your client is a bank - no, they can't go live. They should fire the team, and start again. If your client is a site dedicated to showing funny pictures of kittens, doesn't deal with money or personally identifiable information - then sure, go live.

The fact they asked you to do an audit in the first place suggests there is at least some level of risk.

The "conceptual versus practical" argument is masterstroke, but you can counter with "Security is a process, not a product". If you don't have a process for managing security (and being ignorant of XSS and SQL injection suggests you don't), it's only a question of time before you become a victim. Sure, mod_security protects you against known vulnerabilities - but a poor codebase is far more vulnerable to new exploits. If your client's site is attractive to attackers, poorly constructed code is far more likely to offer some kind of way in - and it may not be SQL injection or XSS; it could be information leaking (what happens when you force an error? do you see information you shouldn't?), it might be poorly handling parameters (what happens if I manipulate HTTP requests to push invalid parameters into the app?).

My recommendation would be to ask the client to agree what their security process should be, what standards they think they should adhere to - you could do worse than using Drupal's, and how they will measure their targets. I'd suggest that getting a clean bill of health from a static analysis tool and being able to switch off mod_security would be a good starting point.

In my experience, a poor codebase tends to degrade very quickly; I've seen a startup literally having to throw away 90% of their code less than 18 months after it was written because the overall quality was so poor.

Once you know what the security process is, you can agree a plan for adhering to it. I think you can then take a business decision on whether to launch the current iteration of the site. I'd suggest this business decision needs to take into account protecting the investment in the current codebase, as well as the security concerns.

OwnerDisplayName: Austin Smith

OwnerDisplayName: Neville K


答:
Is my position here too harsh? Even if they fix the SQL Injection and XSS problems can I ever endorse the release of an unmaintainable tangle of spaghetti code?

No, your position is not too harsh. You need to adopt a very simple approach: Fix the vulnerabilities, organize the code, and then it will get endorsed.

Anything less than this will ensure that the client has even larger issues down the road...as I discovered when I took over development lead for an open source HRM project. I have spent a year re-writing 95% of the code from scratch, because the original developers wouldn't take the time to follow proper coding standards such as logical folder structure, using classes and functions for repetition, universal headers, normalized databases, etc.

The long and short is, if it's going to be served to anyone via the web, it is no longer a "conceptual" problem, it is very much practical.

Title: Are SQL Injection vulnerabilities in a PHP application acceptable if mod_security is enabled?

Body:
I've been asked to audit a PHP application. No framework, no router, no model. Pure PHP. Few shared functions. HTML, CSS, and JS all mixed together. I've discovered numerous places where SQL injection would be easily possible. There are other problems with the application (XSS vulnerabilities, rampant inline CSS, code copy-pasted everywhere) but this is the biggest. Sometimes they escape inputs, not using a prepared query or even mysql_real_escape_string(), mind you, but using addslashes(). Often, though, their queries look exactly like this (pasted from their code but with columns and variable names changed):

```<code>$user = mysql_query("select * from profile where profile_id='".$_REQUEST["profile_id"]."'");
</code>```

The developers in question claimed that they were unable to hack their application. I tried, and found mod_security to be enabled, resulting in HTTP 406 for some obvious SQL injection attacks. I believe there to be sophisticated workarounds for mod_security, but I don't have time to chase them down.

They claim that this is a "conceptual" matter and not a "practical" one since the application can't easily be hacked. Their internal auditor agreed that there were problems, but emphasized the conceptual nature of the issues.

They also use this conceptual/practical argument to defend against inline CSS and JS, absence of code organization, XSS vulnerabilities, and massive amounts of repetition.

My client (rightly so, perhaps) just wants this to go away so they can launch their product. The site works. You can log in, do what you need to do, and things are visibly functional, if slow. SQL Injection would indeed be hard to do, given mod_security. Further, their talk of "conceptual vs. practical" is rhetorically brilliant, considering that my client doesn't understand web application security. I worry that they've succeeded in making me sound like an angry puritan.

In many ways, this is a problem of politics, not technology, but I am at a loss. As a developer, I want to tell them to toss the whole project and start over with a new team, but I face a strong defense from the team that built it and a client who really needs to ship their product.

Is my position here too harsh? Even if they fix the SQL Injection and XSS problems can I ever endorse the release of an unmaintainable tangle of spaghetti code?

EDIT: As to my role on this project, I'm not a security expert, I'm a web developer generalist. the client initially asked me to load test the app and make recommendations for scalability. I haven't gotten that far yet, because when I first read the output of the home page, I saw inline CSS, table based layouts, and all sorts of crazy JS, so I requested a copy of the code, where I found the unholy mess described above. They don't even abstract the HTML header and footer. Every PHP file has a slightly different pasted version.

And as to the app itself, it does store personal information, and it processes (but does not store) credit card data.

OwnerDisplayName: jakimfett


答:
To look at it from a different angle, if the developers think that massive repetition is a "conceptual problem, not a practical one," then you have more serious concerns than security issues that--at this point at least--truly are theoretical.

A codebase that's full of needless repetition is going to be unmaintainable: when they try to change something, they'll have to change it in X different places.  They'll generally find X-1 of them (maybe less, depending on the complexity) and this will introduce subtle bugs in the codebase.  Fixing them will require more changes... and you can see where this is leading.  On any product that needs to evolve, (which is basically any product,) this can be the kiss of death.

And the fact that they dismiss it as a mere theoretical concern shows that they don't understand that it's a real problem, which means that they won't know how to fix it once it starts causing trouble for them, or even recognizing that this is at the root of their problems. If I was auditing this project, I'd fail them on that basis alone, even if the security was airtight.


问:
Programming Without A Computer

Possible Duplicate:

  Learning to program without a computer

I have a bit of experience programming (6 Months) and am soon to go on a 2 month trip where I will be without a computer, but with lots of spare time. Is there a way I can keep programming (or learning to program) even without a computer? Should I read language-agnostic books like Code Complete or PragProg?

答: Reading is helpful.  More helpful still would be writing.  If you can't bring along a laptop or even a smartphone, take a notebook and some pens or pencils.  Start working on some sort of personal project.  Write out your code in one section, and your ideas and thoughts in another.  Since you don't have a compiler, check your work in your head.  See how much you can learn from the process, and when you get home, enter your code into your computer and see how close it is to actually working.

Title: Programming Without A Computer


问:
Is javascript worth learning if you do not plan on being a web developer?
I heard Javascript is a full language just like c++. Is this true? What else is it good for programming besides web stuff?</p>

答:
Javascript is a great foundation language

It is :

powerful

easy to learn

supports both procedural and object-oriented paradigms

is quick to write and get running

popularised many modern language concepts - closures, anonymous functions, asynchronous/event-driven programming, dynamic types/inference

has great tools ( editors, runtimes, lint tools, browsers)

has amazing online support with lots of active communities

can do maths functions

has graphics abilities (via HTML/Canvas)

can use it to write Apps

I personally believe it is worth learning even if you won't use it daily. It will broaden your mind such that you consider different solutions when using other languages like C++ or C# - e.g. Iteration versus Algorithmic solution, dynamic typing and type inference.

I have seen people use it to crunch numbers/data dumps faster than professional tools, by pasting their data into an HTML text area of a page they'd constructed with some JS code behind to work through the data.

What else is it good for?

Embedding inside something else:

All of the companies I've worked for in the last 12 years have built both commercial products and internal development tools that used JavaScript (or close relative - ECMAScript, ActionScript, etc) as the foundation as it was easy to learn, had easily-integrated (free) implementations ready to go (SpiderMonkey and Microsoft Active Scripting SDK) and performance was 'good enough' to begin with and has just kept on getting better.

Before jQuery/Prototype and the whole AJAX movement came along, the choice of JS seemed non-obvious - why not use VBA (shudder), something lex+yacc-able or roll your own language? The power of JS as a language combined with rich widgets/frameworks meant not a whole lot of code needed to be written, so an off-the-shelf solution was attractive as more effort could be spent on the rest of the product.

As the language has increased in capability and speed, the bet on JS has paid off. With more developers able to grok JS, hiring is easier too.


答:
You can do what we used to do before IDEs - write your programs out by hand on paper.

Stop laughing.
I mean it.
Please?

There's a lot you can learn about programming without ever touching a computer.  Modern programs used to write programs (editors, IDEs, whatever) are a crutch, and they get in the way of your understanding.  Write a few programs where auto-complete didn't tell you which method to use or what argument comes next, and all the other little helpers.  You'll find  that, in actuality, programming is a purely mental exercise that we have ceded large parts of to machines, at great loss.

Go retro, and revel in the hipness :-)

Title: Programming Without A Computer

Body:
Possible Duplicate:

  Learning to program without a computer

I have a bit of experience programming (6 Months) and am soon to go on a 2 month trip where I will be without a computer, but with lots of spare time. Is there a way I can keep programming (or learning to program) even without a computer? Should I read language-agnostic books like Code Complete or PragProg?


问:
How to implement a no-login authentication system
I am looking to build a very loose authentication system that can track a user and link submitted data/comments to a specific user.  The submissions are essentially anonymous, but a user may want to edit his submission/comment at a later date.

I want the experience to be as smooth as possible so do not want to ask users to sign up for an account and then login each time.  There is no point as their submissions are not in their name and to another user browsing the site, there is no way of linking a submission to a specific user (think anonymous comments on a blog post or pastie).  However, the user should have the ability to edit (at least in the short term) the content they have posted.

The way I imagine doing this would be to place a unique identifier in a cookie on the users machine.  This would enable me to link a submission to a user, and while that cookie remained on the users machine, I would allow them to edit their content.  Of course, if the cookie is lost, or the user accesses the site from a different browser, then they would not be able to edit their content, but this is not really an issue, they can always resubmit a new piece of content.

Is there a better way of doing this?  How can I implement this so that the user can edit their data for the longest possible amount of time.

答:
Easy way? Grab their IP address. It's not perfect (what if several people are behind the same router, what if their IP address changes, what if they posted from work/starbucks/their phone, etc) but all you need to do is log the $_SERVER['REMOTE_ADDR'] of each user who posts...then only enable editing if they are from that IP address.

Example:

```<code>if($_SERVER['REMOTE_ADDR'] == $comment_author_ip_address_in_database){
    <stuff here for editing the comment/post>
}
</code>```

Body:
Easy way? Grab their IP address. It's not perfect (what if several people are behind the same router, what if their IP address changes, what if they posted from work/starbucks/their phone, etc) but all you need to do is log the $_SERVER['REMOTE_ADDR'] of each user who posts...then only enable editing if they are from that IP address.

Example:

if($_SERVER['REMOTE_ADDR'] == $comment_author_ip_address_in_database){
    <stuff here for editing the comment/post>
}


问:
Reinforcing Syntax Elements
I am currently learning Javascript, and there is one element of the syntax that I can just not seem to nail down. That element is adding semicolons at the end of each line. I have learned Python and Ruby, and written a ton of both, so the lack of semicolons is stuck in my mind! Is there a way to drill that (or even any syntax, to make this more useful to future readers) into my brain?</p>

答: In week #3 and language #3 of CS 103, Comparative Languages, our prof took questions about what problems we were having.  Someone said that they couldn't remember which languages had semicolons as separators, and which as terminators.  Prof said if you couldn't deal with that, you were gonna fail.</p>

Title: Reinforcing Syntax Elements


答:
Are SQL Injection vulnerabilities in a PHP application acceptable if mod_security is enabled?

No, at least not if you ask me.

If SQL injections are acceptable for the client, there is nothing you need to worry about. You could ask yourself why they did ask you to review the scripts anyway, but I won't bother, take the money and say goodbye. There is not much to argue, it's a pretty simple answer:

No.

If it's yes for them, they know what they do, not your business.


答: I did something like this a while ago when reading "The Little Schemer". The book is about scheme and uses a format where one side of the page asks a question with the other side having the answer. So it worked well writing out everything on a piece of paper, covering the answer side of the page, then checking if what I wrote was correct. I did not intend on actually using Scheme... just wanted to know what it was about. I thought I got a lot out of it despite not actually running anything on a computer. It's especially good if you want to get the hang of recursion... there is a ton of recursion in "The Little Schemer". </p>

Title: Programming Without A Computer


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答: "Test what you fly, fly what you test."</p>

LastEditorDisplayName: Roger Pate

Body: "Test what you fly, fly what you test."


问:
Subversion server hierarchy, need advice
I have a subversion server setup that I need to look after several projects, grouped by language, then client (company) and then by project

e.g.

```<code>repos/

flex3
     \com1
          \project1
          \project2
     \com2
          \project1
          \project2
          \project3

flex4
     \com1
         \projectx
     \com2
         \projecty

java
    \projectz
</code>```

repos is my repository root and then I have the 3 repositories inside (create with svnadmin create) flex3, flex4 and java, then flex3 should have two folders com1 and com2 for different clients, each will contain different "project" repos.

I have a feeling I have done this wrong, should I simply create the top level structure as normal folders and then make the com1 and com2 etc into repos with "svnadmin create" so that different projects can be added directly below them. Is this correct?

Thanks

答:
Why did you created three repositories and not just one?

```<code> root
  +--- flex3
         +----...
  +--- flex4
         +----...
  +--- java
         +----...
</code>```

may you should orgnaize the projects based on the projects not on the programming language which is used....and use a single svn repository instead of multiple....

Body:
Why did you created three repositories and not just one?

 root
  +--- flex3
         +----...
  +--- flex4
         +----...
  +--- java
         +----...

may you should orgnaize the projects based on the projects not on the programming language which is used....and use a single svn repository instead of multiple....


问:
Generalize, or Fix The Problem?
Which of these two programmers is "better", from a managerial standpoint?

The first programmer is Albert. You tell Al to make a system that will pass you the salt at the dinner table. He does it in less than a day. It works fine.

The second programmer is Ben. Ben is told to make a program to pass the salt, and after two days, he's still working on it.

It will save time in the long run...if you need pepper, ketchup, etc. There isn't any clear indication that there will be a need for this, but it's not improbable.

Who's the better programmer to have working under you, as a manager?

答:
The first programmer is better.

YAGNI is in play, and a program that passes arbitrary condiments isn't worth 200% more in the face of requirements that requested a program that passes salt.

Title: Generalize, or Fix The Problem?


答:
It depends.

Is the manager a control freak?

Is the manager also a programmer?

Programmers working under you, in general, shouldn't  take a stroll into uncharted zones without first discussing the matter with you.

Then, you, the manager, could be utterly incompetent and unable to discern the matter at hand, thus pushing your un-managed programmer to do his own core design decisions.

There, your managed programmer is now his own architect, and he's struggling with your made up deadlines, (ASAP isn't a reasonable deadline, you know) and has a lot of burden on him, more than he can probably handle, and this will probably backfire sooner or later.

So, it's never a good symptom. If it starts happening over and over:

your programmer could be incredibly naive and/or have very poor communication skills

then he should get proper training

your manager could be incredibly inept and should be removed from the project

the programmer then, could be managing material:

he runs late, but does he meets the deadlines?

does the codebase makes more sense since he put his paws on it?

Title: Generalize, or Fix The Problem?

Body:
Which of these two programmers is "better", from a managerial standpoint?

The first programmer is Albert. You tell Al to make a system that will pass you the salt at the dinner table. He does it in less than a day. It works fine.

The second programmer is Ben. Ben is told to make a program to pass the salt, and after two days, he's still working on it.

It will save time in the long run...if you need pepper, ketchup, etc. There isn't any clear indication that there will be a need for this, but it's not improbable.

Who's the better programmer to have working under you, as a manager?


问:
What's the difference between recursion and corecursion?
What's the difference between these?

Recursion

Corecursion

On Wikipedia, there is little information and no clear code explaining these terms.

What are some very simple examples explaining these terms?

How is corecursion the dual of recursion?

Are there any classic corecusive algorithms?

答:
There are a number of good ways of looking at this.  The easiest thing for me is to think about the relation between "Inductive" and "Coinductive definitions"

An inductive definition of a set goes like this.

The set "Nat" is defined as the smallest set such that "Zero" is in Nat, and if n is in Nat "Succ n" is in Nat.

Which corresponds to the following Ocaml

```<code>type nat = Zero | Succ of nat
</code>```

One thing to note about this definition is that a number

```<code>omega = Succ(omega)
</code>```

is NOT a member of this set.  Why?  Assume that it was, now consider the set N that has all the same elements as Nat except it does not have omega.  Clearly Zero is in N, and if y is in N, Succ(y) is in N, but N is smaller than Nat which is a contradiction.  So, omega is not in Nat.

Or, perhaps more useful for a computer scientist:

Given some set "a", the set "List of a" is defined as the smallest set such that "Nil" is in List of a, and that if xs is in List of a and x is in a "Cons x xs" is in List of a.

Which corresponds to something like

```<code>type 'a list = Nil | Cons of 'a * 'a list
</code>```

The operative word here is "smallest".  If we didn't say "smallest" we would not have any way of telling if the set Nat contained a banana!

Again,

```<code>zeros = Cons(Zero,zeros)
</code>```

is not a valid definition for a list of nats, just like omega was not a valid Nat.

Defining data inductively like this allows us to define functions that work on it using recursion

```<code>let rec plus a b = match a with
                   | Zero    -> b
                   | Succ(c) -> let r = plus c b in Succ(r)
</code>```

we can then prove facts about this, like "plus a Zero = a" using induction (specifically, structural induction)

Our proof proceeds by structural induction on a.

For the base case let a be Zero.  plus Zero Zero = match Zero with |Zero -> Zero | Succ(c) -> let r = plus c b in Succ(r) so we know plus Zero Zero = Zero.
Let a be a nat.  Assume the inductive hypothesis that plus a Zero = a.  We now show that plus (Succ(a)) Zero = Succ(a) this is obvious since plus (Succ(a)) Zero = match a with |Zero -> Zero | Succ(a) -> let r = plus a Zero in Succ(r) = let r = a in Succ(r) = Succ(a)
Thus, by induction plus a Zero = a for all a in nat

We can of-course prove more interesting things, but this is the general idea.

So far we have dealt with inductively defined data which we got by letting it be the "smallest" set.  So now we want to work with coinductivly defined codata which we get by letting it be the biggest set.

So

Let a be a set.  The set "Stream of a" is defined as the largest set such that for each x in the stream of a, x consists of the ordered pair (head,tail) such that head is in a and tail is in Stream of a

In Haskell we would express this as

```<code>data Stream a = Stream a (Stream a) --"data" not "newtype"
</code>```

Actually, in Haskell we use the built in lists normally, which can be an ordered pair or an empty list.

```<code>data [a] = [] | a:[a]
</code>```

Banana is not a member of this type either, since it is not an ordered pair or the empty list.  But, now we can say

```<code>ones = 1:ones
</code>```

and this is a perfectly valid definition.  Whats more, we can perform co-recursion on this co-data.  Actually, it is possible for a function to be both co-recursive and recursive.  While  recursion was defined by the function having a domain consisting of data, co-recursion just means it has a co-domain (also called the range) that is co-data.  Primitive recursion meant always "calling oneself" on smaller data until reaching some smallest data.  Primitive co-recursion always "calls itself" on data greater than or equal to what you had before.

```<code>ones = 1:ones
</code>```

is primitively co-recursive.  While the function map (kind of like "foreach" in imperative languages) is both primitively recursive (sort of) and primitively co-recursive.

```<code>map :: (a -> b) -> [a] -> [b]
map f []     = []
map f (x:xs) = (f x):map f xs
</code>```

same goes for the function zipWith which takes a function and a pair of lists and combines them together using that function.

```<code>zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith f (a:as) (b:bs) = (f a b):zipWith f as bs
zipWith _ _ _           = [] --base case
</code>```

the classic example of functional languages is the Fibonacci sequence

```<code>fib 0 = 0
fib 1 = 1
fib n = (fib (n-1)) + (fib (n-2))
</code>```

which is primitively recursive, but can be expressed more elegantly as an infinite list

```<code>fibs = 0:1:zipWith (+) fibs (tail fibs)
fib' n = fibs !! n --the !! is haskell syntax for index at
</code>```

an interesting example of induction/coinduction is proving that these two definitions compute the same thing.  This is left as an exercise for the reader.

Body:
There are a number of good ways of looking at this.  The easiest thing for me is to think about the relation between "Inductive" and "Coinductive definitions"

An inductive definition of a set goes like this.

The set "Nat" is defined as the smallest set such that "Zero" is in Nat, and if n is in Nat "Succ n" is in Nat.

Which corresponds to the following Ocaml

type nat = Zero | Succ of nat

One thing to note about this definition is that a number

omega = Succ(omega)

is NOT a member of this set.  Why?  Assume that it was, now consider the set N that has all the same elements as Nat except it does not have omega.  Clearly Zero is in N, and if y is in N, Succ(y) is in N, but N is smaller than Nat which is a contradiction.  So, omega is not in Nat.

Or, perhaps more useful for a computer scientist:

Given some set "a", the set "List of a" is defined as the smallest set such that "Nil" is in List of a, and that if xs is in List of a and x is in a "Cons x xs" is in List of a.

Which corresponds to something like

type 'a list = Nil | Cons of 'a * 'a list

The operative word here is "smallest".  If we didn't say "smallest" we would not have any way of telling if the set Nat contained a banana!

Again,

zeros = Cons(Zero,zeros)

is not a valid definition for a list of nats, just like omega was not a valid Nat.

Defining data inductively like this allows us to define functions that work on it using recursion

let rec plus a b = match a with
                   | Zero    -> b
                   | Succ(c) -> let r = plus c b in Succ(r)

we can then prove facts about this, like "plus a Zero = a" using induction (specifically, structural induction)

Our proof proceeds by structural induction on a.

For the base case let a be Zero.  plus Zero Zero = match Zero with |Zero -> Zero | Succ(c) -> let r = plus c b in Succ(r) so we know plus Zero Zero = Zero.
Let a be a nat.  Assume the inductive hypothesis that plus a Zero = a.  We now show that plus (Succ(a)) Zero = Succ(a) this is obvious since plus (Succ(a)) Zero = match a with |Zero -> Zero | Succ(a) -> let r = plus a Zero in Succ(r) = let r = a in Succ(r) = Succ(a)
Thus, by induction plus a Zero = a for all a in nat

We can of-course prove more interesting things, but this is the general idea.

So far we have dealt with inductively defined data which we got by letting it be the "smallest" set.  So now we want to work with coinductivly defined codata which we get by letting it be the biggest set.

So

Let a be a set.  The set "Stream of a" is defined as the largest set such that for each x in the stream of a, x consists of the ordered pair (head,tail) such that head is in a and tail is in Stream of a

In Haskell we would express this as

data Stream a = Stream a (Stream a) --"data" not "newtype"

Actually, in Haskell we use the built in lists normally, which can be an ordered pair or an empty list.

data [a] = [] | a:[a]

Banana is not a member of this type either, since it is not an ordered pair or the empty list.  But, now we can say

ones = 1:ones

and this is a perfectly valid definition.  Whats more, we can perform co-recursion on this co-data.  Actually, it is possible for a function to be both co-recursive and recursive.  While  recursion was defined by the function having a domain consisting of data, co-recursion just means it has a co-domain (also called the range) that is co-data.  Primitive recursion meant always "calling oneself" on smaller data until reaching some smallest data.  Primitive co-recursion always "calls itself" on data greater than or equal to what you had before.

ones = 1:ones

is primitively co-recursive.  While the function map (kind of like "foreach" in imperative languages) is both primitively recursive (sort of) and primitively co-recursive.

map :: (a -> b) -> [a] -> [b]
map f []     = []
map f (x:xs) = (f x):map f xs

same goes for the function zipWith which takes a function and a pair of lists and combines them together using that function.

zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith f (a:as) (b:bs) = (f a b):zipWith f as bs
zipWith _ _ _           = [] --base case

the classic example of functional languages is the Fibonacci sequence

fib 0 = 0
fib 1 = 1
fib n = (fib (n-1)) + (fib (n-2))

which is primitively recursive, but can be expressed more elegantly as an infinite list

fibs = 0:1:zipWith (+) fibs (tail fibs)
fib' n = fibs !! n --the !! is haskell syntax for index at

an interesting example of induction/coinduction is proving that these two definitions compute the same thing.  This is left as an exercise for the reader.


答:
I would say that it depends entirely on the nature of your business and the type of client relations you have.

Do you or your client have a pressing pressing "salt at the dinner table" need?
Do you or your client often need condiments of other sorts?
Do you or your client have a history of needing "just this one thing" and then needing that "just one thing" turned into "any of this set of things"?

I'm sure you can see what those questions are pointing to.  From a managerial standpoint, or more specifically from a business interest standpoint - the real answer is whichever developer is better for the long term profitability of your company.  And there isn't a hard and fast rule for that.

Considering the ambiguities in real-world scenarios like this, I would say the correct answer is "both" - you generally would want to make sure you have people on your team who can "get it done right now" for when "right now" is important.  AND you want people who can get it done "right" for when maintainability is important.  Rarely, you can find individuals who're capable of both - cherish them.

Developers who are in the extreme (either end of the "right"->"right now" gradient) and put into the opposite need situation generally do horribly.  Give a well experienced, abstract thinker a "get it done quick and dirty" job and they'll often flub it.  Give a "gets it done with baling wire and scotch tape" developer the role of planning and maintaining a complex product and you often end up with spaghetti tangles of doom.

Title: Generalize, or Fix The Problem?


答: An interesting approach might be to allow the users to create a password for each entry.  No username/profile/registration - just along with the post - a password.  The password should probably have some strict guidelines to keep your site from getting bruteforced into wall to wall spam.  I'd probably make it timeout after a reasonable amount of time too (only you can decide what "reasonable" is).  That would get you around the cookie expiration or not-on-same-computer issues.</p>

Title: How to implement a no-login authentication system

Body:
I am looking to build a very loose authentication system that can track a user and link submitted data/comments to a specific user.  The submissions are essentially anonymous, but a user may want to edit his submission/comment at a later date.

I want the experience to be as smooth as possible so do not want to ask users to sign up for an account and then login each time.  There is no point as their submissions are not in their name and to another user browsing the site, there is no way of linking a submission to a specific user (think anonymous comments on a blog post or pastie).  However, the user should have the ability to edit (at least in the short term) the content they have posted.

The way I imagine doing this would be to place a unique identifier in a cookie on the users machine.  This would enable me to link a submission to a user, and while that cookie remained on the users machine, I would allow them to edit their content.  Of course, if the cookie is lost, or the user accesses the site from a different browser, then they would not be able to edit their content, but this is not really an issue, they can always resubmit a new piece of content.

Is there a better way of doing this?  How can I implement this so that the user can edit their data for the longest possible amount of time.


答:
Get your users to enter a name and email address before creating the cookie. Associate their email address to that cookie's identifier in your database. Provide limited access to your website. </p>

<p>If the user decides to register, then have them fill out a form. If they use the same email address as the one in the cookie then associate all content associated with that cookie to their newly created account. So now they can always edit it. </p>

Body:
Get your users to enter a name and email address before creating the cookie. Associate their email address to that cookie's identifier in your database. Provide limited access to your website.

If the user decides to register, then have them fill out a form. If they use the same email address as the one in the cookie then associate all content associated with that cookie to their newly created account. So now they can always edit it.


问:
Incorporating libs into module pattern
I have recently started using require.js (along with Backbone.js, jQuery, and a handful of other JavaScript libs) and I love the module pattern (here's a nice synopsis if you're unfamiliar: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth).  Something I'm running up against is best practices on incorporating libs that don't (out of the box) support the module pattern.  For example, jQuery without modification is going to load into a global jQuery variable and that's that.  Require.js recognizes this and provides an example project for download with a (slightly) modified version of jQuery to incorporate with a require.js project.

This goes against everything I've ever learned about using external libs - never modify the source.  I can list a ton of reasons.  Regardless, this is not an approach I'm comfortable with.

I have been using a mixed approach - wherein I build/load the "traditional" JS libraries in a "traditional" way (available in the global namespace) and then using the module pattern for all of my application code.  This seems okay to me, but it bugs me because one of the real beauties of the module pattern (no globals) is getting perverted.

Anyone else got a better solution to this problem?

Title: Incorporating libs into module pattern

Body:
There is (nearly) nothing wrong in modifying the external libraries. jQuery is an open source project, so if you can adapt it to your particular needs, just do it.

There might be some issues with this approach:

When a new version of jQuery is released, what is easier to do? Update the <script> tag of a website to use the new version, or waste your time reapplying the changes you've already done to the older version?

When using an official version of jQuery, you can benefit of Google CDN. If you have your own, modified version, you have to host it yourself.

If you're working with other people, they may not be familiar with your changes, and assume that you are using the original jQuery library.

All those issues are still minor in most circumstances. For example, unless you have a large scale web application, I'm not sure that it's the fact that you don't use Google CDN which will be the bottleneck.

So if you have enough experience to do it, there is nothing wrong in modifying the existent libraries in order to better fit your requirements.


答:
If you want the longest and most flexible, implement OpenID and require them to register.  Done correctly, it's little more than a couple of mouse clicks.  Check out how easy it is to join one of the stack exchange sites.

If that's too much work for you/your users, then a cookie is really the only good choice -- you could generate a unique query string and have them bookmark it, but if they won't register with OpenId, they probably won't want to keep track of a URL.


答:
IMHO one of the most desirable features one could add to the html standard would be just that: loading a script without executing it right away*. I'd love to have all the code in a script wrapped in a closure, and call it like a function when and if I wanted (maybe even passing parameters to it, for instance using html attributes for that - but that is another story). That would solve many problems in programming for the browser today.

jQuery provides us with the noConflict utility, which is useful if you want to remove the global binding(s), but you have to call it "after the fact". I have no experience with require.js, so it's hard to say whether or not that would be a problem. But it's one of the best ways I know of keeping your programs global-free, and I tend to mimic in my own scripts.

Most jQuery plugins also abstain from creating globals, but they usually require that jQuery (and sometimes $, though it's a bad practice) exists as a global to work correctly - so it's better to use noConflict after all plugins are loaded (and some badly constructed ones might fail even then).

A "last resort" way I can think of accomplishing the same goal would be loading a script as text, using Ajax for instance, wrapping it into a closure before calling eval on it. Cumbersome, but not without its advantages (you could make checks/changes to the loaded script before actually running it - for instance if you load it from external sources). You'd lose some browser protections against XSS though...

About modifying the sources, I agree with MainMa, nothing wrong with that short of the specific pros/cons stated.

*Note: when I say "wrapping all code in a closure", I don't mean the way most scripts already do: create a function and then call it. I meant to create a function and allow another part of your program store it, executing it when convenient. AFAIK there's no "standards-compliant" way of doing that.

Title: Incorporating libs into module pattern

Body:
I have recently started using require.js (along with Backbone.js, jQuery, and a handful of other JavaScript libs) and I love the module pattern (here's a nice synopsis if you're unfamiliar: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth).  Something I'm running up against is best practices on incorporating libs that don't (out of the box) support the module pattern.  For example, jQuery without modification is going to load into a global jQuery variable and that's that.  Require.js recognizes this and provides an example project for download with a (slightly) modified version of jQuery to incorporate with a require.js project.

This goes against everything I've ever learned about using external libs - never modify the source.  I can list a ton of reasons.  Regardless, this is not an approach I'm comfortable with.

I have been using a mixed approach - wherein I build/load the "traditional" JS libraries in a "traditional" way (available in the global namespace) and then using the module pattern for all of my application code.  This seems okay to me, but it bugs me because one of the real beauties of the module pattern (no globals) is getting perverted.

Anyone else got a better solution to this problem?


问:
Are there advantages to using a DVCS for a solo developer?
Right now, I use visual svn on my server, and have ankhsvn/tortoise on my personal machine. It works fine enough, and I don't have to change, but if I can see some benefits of using a DVCS, then I might give it a go.

However, if there's no point or difference using it without other people, then I won't bother.

So again, I ask, are there any benefits to using a DVCS when you're the only developer?

答: My mother turns off the modem when it is too late to sleep. DVCS allows me to continue to work with VCS after modem is off.</p>


问:
The rule of 5 - to use it or not?
The rule of 3 (the rule of 5 in the new c++ standard) states :

If you need to explicitly declare either the destructor, copy constructor or copy assignment operator yourself, you probably need to explicitly declare all three of them.

But, on the other hand, the Martin's "Clean Code" advises to remove all empty constructors and destructors (page 293, G12:Clutter) :

Of what use is a default constructor with no implementation? All it serves to do is clutter up the code with meaningless artifacts.

So, how to handle these two opposite opinions? Should empty constructors/destructors really be implemented?

Next example demonstrates exactly what I mean :

```<code>#include <iostream>
#include <memory>

struct A
{
    A( const int value ) : v( new int( value ) ) {}
    ~A(){}
    A( const A & other ) : v( new int( *other.v ) ) {}
    A& operator=( const A & other )
    {
        v.reset( new int( *other.v ) );
        return *this;
    }

    std::auto_ptr< int > v;
};
int main()
{
    const A a( 55 );
    std::cout<< "a value = " << *a.v << std::endl;
    A b(a);
    std::cout<< "b value = " << *b.v << std::endl;
    const A c(11);
    std::cout<< "c value = " << *c.v << std::endl;
    b = c;
    std::cout<< "b new value = " << *b.v << std::endl;
}
</code>```

Compiles fine using g++ 4.6.1 with :

```<code>g++ -std=c++0x -Wall -Wextra -pedantic example.cpp
</code>```

The destructor for struct A is empty, and not really needed. So, should it be there, or should it be removed?

答:
There is another point not mentioned in the discussion yet: A destructor should always be virtual.

```<code>struct A
{
    A( const int value ) : v( new int( value ) ) {}
    virtual ~A(){}
    ...
}
</code>```

The constructor needs to be declared as virtual in the base class to make it virtual in all derived classes too. So, even if your base class does not need a destructor, you end up declaring and implementing an empty destructor.

If you put on all warnings on (-Wall -Wextra -Weffc++) g++ will warn you about this. I consider it good practice to always declare a virtual destructor in any class, because you never know, if your class will eventually become a base class. If the virtual destructor is not needed, it does no harm. If it is, you save time to find the error.

Title: The rule of 5 - to use it or not?

Body:
There is another point not mentioned in the discussion yet: A destructor should always be virtual.

struct A
{
    A( const int value ) : v( new int( value ) ) {}
    virtual ~A(){}
    ...
}

The constructor needs to be declared as virtual in the base class to make it virtual in all derived classes too. So, even if your base class does not need a destructor, you end up declaring and implementing an empty destructor.

If you put on all warnings on (-Wall -Wextra -Weffc++) g++ will warn you about this. I consider it good practice to always declare a virtual destructor in any class, because you never know, if your class will eventually become a base class. If the virtual destructor is not needed, it does no harm. If it is, you save time to find the error.


问:
Performance analysis of C++ programs
How can I measure the performance of my C++ programs using C++?

Specific metrics I want to measure are:

Memory used (space)

Duration taken (time)

答:
I agree with Pubby that profiling using external tools is better. Here are some pointers:

To get a rough estimate of the time an executable takes, I would use a linux tool like time. Running the executable spam like:

```<code>time spam
</code>```

Gives you feedback on how long it took. You could also write a small Python script which does this a few times and averages the results. See this SO thread for some hints how to measure the memory used by an application.

But this gives only a cumulative view of your program. Much more interesting is to break this analysis up for different parts of your code. You can do this by profiling your code, for example using the GNU profiler gprof. This will present you an overview of how much time is spent in which parts of the code. This can grant you insight where you could spend more time optimzing, and where the performance of the code is not really important.

Title: Performance analysis of C++ programs

Body:
I agree with Pubby that profiling using external tools is better. Here are some pointers:

To get a rough estimate of the time an executable takes, I would use a linux tool like time. Running the executable spam like:

time spam

Gives you feedback on how long it took. You could also write a small Python script which does this a few times and averages the results. See this SO thread for some hints how to measure the memory used by an application.

But this gives only a cumulative view of your program. Much more interesting is to break this analysis up for different parts of your code. You can do this by profiling your code, for example using the GNU profiler gprof. This will present you an overview of how much time is spent in which parts of the code. This can grant you insight where you could spend more time optimzing, and where the performance of the code is not really important.


答:
How can I measure the performance of my C++ programs using C++?

This is a very bad idea, because there are already tools to do that.

On linux, there is time to measure time used by application.

Also on linux, you can use massif, which is a heap profiler.

Title: Performance analysis of C++ programs

Body:
How can I measure the performance of my C++ programs using C++?

Specific metrics I want to measure are:

Memory used (space)

Duration taken (time)


答:
Space: Use specialized allocator(s). This way, you can record exact memory consumption and events -- local to the implementation you are interested in measuring. For example: std::vector<int,t_your_allocator>. Global new/delete (for testing only) and new placement are other approaches.

Time: Agner is a good reference. http://www.agner.org/optimize/ Agner Fog goes deep into costs and measurement in writing -- several books (or manuals) are available. The site also hosts implementations which measure execution times.

Title: Performance analysis of C++ programs


问:
How to properly structure a project in winform?
A while ago I started to create a winform application and at that time it was small and I did not give any thought of how to structure the project.

Since then I added additional features as I needed and the project folder is getting bigger and bigger and now I think it is time to structure the project in some way, but I am not sure what is the proper way, so I have few questions.

How to properly restructure the project folder?

At the moment I am thinking of something like this:

Create Folder for Forms

Create Folder for Utility classes

Create Folder for Classes that contain only data

What is the naming convention when adding classes?

Should I also rename classes so that their functionality can be identified by just looking at their name? For example renaming all forms classes, so that their name ends with Form.
Or is this not necessary if special folders for them are created?

What to do, so that not all the code for main form ends up in Form1.cs

Another problem I encountered is that as the main form is getting more massive with each feature I add, the code file (Form1.cs) is getting really big.
I have for example a TabControl and each tab has bunch of controls and all the code ended up in Form1.cs. How to avoid this?

Also, Do you know any articles or books that deal with these problems?

答:
The structure of a project totally depends on the Project and its size, however you can add few folders e.g.

Common (Containing classes e.g. Utilities)

DataAccess (classes related to access of data using sql or any other database server your   using)

Styles (If you got any CSS files in your project)

Resources (e.g. Images, resource files)

WorkFlow (Classes related to workflow if you have any)

You dont need to put Forms into any kind of folder, just rename your forms accordingly. I mean its common sense no one knows what name should be your forms better then yourself.

Naming convention is like if your class printing a "Hello World" message then class name should be something related to the task and class's appropriate name should HelloWorld.cs.

you can create regions as well e.g.

#region Hello   and then out  endregion at the end.

You can create classes for tabs, am pretty sure you can, and one last thing is reuse your code where possible, best practice is to make methods and use them again where needed.

Books ? erm.

There's no books tell you the structure of projects as each project is different, you learn these kind of things by experience.

Hope it helped!


答:
Your initial reaction is that of a developer purist. You see rubbish and you think it should be fixed.

Trouble with this approach is that commercially it is very unlikely to be acceptable to the client, and it is probably not commercially realistic.

You need to give the client an answer which addresses all the relevant points, as well as giving a plan for the future (give your client a solution, not a problem).

You might for example give a written report (and I strongly suggest you put this in writing - if you were engaged to do an evaluation, you should deliver something in writing).

The report might say something like (greatly expanded, of course):

the product is poorly written (cite examples you have already listed);

the product contains security vulnerabilities and even though you are not an expert in the field it is your view that these will be exploited at some time;

the product will not scale well (this was your original brief) because of poor code structure, lack of consistency, use of numerous instances of cut-and-paste code which detracts from maintainability.

You can then go on to say:

in a perfect world, unconstrained by commercial realities of release dates or budget, the product should be used as a prototype and development should be started again [Saying used as a prototype means you are not saying its garbage, you are saying it is a quickie that can be used to evaluate look / feel / style / workflow, etc... its politically softer.];

because the product must be released, a critical step is to do a security vulnerability analysis - this is an urgent task. Any patch up must be applied quickly, even if this makes the code-base more complex;

a secondary activity should begin to commence a replacement design that will scale and be more maintainable. This might use a framework, or it might take the existing code and improve it;

if the outcome of the secondary task is to embark on process of refactoring and improvement, this is acceptable... and you might suggest places to start (for example, common menu system, common HTML header / footer code, moving CSS out of code, etc etc). Each of these items could be listed, and these could be work items to be budgeted and worked on as small projects as part of the refactor.

So what I suggest you present is a staged solution rather than throwing your hands up and saying "its a mess start again" which is emotional and not very constructive.

Having submitted your report you may or may not become part of the solution. You probably won't be very popular with the developers - the fact that they have done what they have done probably also means they won't understand most of what you submit. The danger is that the client won't understand it either. So there is a high likelihood that having submitted your report you will get paid and never hear from them again. So be it. The written report covers your arse [ass for Americans].


问:
Which architecture should I choose for this project?
I have a project. The server which based on a phone PCI-board is responsible for received phone calls from the customer and then redirect the phone calls to the operators.

I have decided to code the server using c++ programming language and qt framework because the PCI-board SDK's interface is c/c++ originated and for the sake of portability.

The server need to send the information of the the customer to the operator while ringing the operator and the ui interface of the operator client should be browser-based.

Now the key problem is how could the server notify the operator that there is a phone call for he/she.

One architecture I have considered is like this,

The operator browser client use ajax pooling the web server to check whether there is call to the client; the web server pooling the database server to check whether there is call;
the desktop server(c++) wait for the phone calls and set the information in the database.

The other operations such as hang up the phone call from the client, retransfer the phone call to the other operator also use this architecture.

Then, is there any way other than pooling the server(js code setInterval('getDail', 1000)) to decide whether there is a call to the operator?

Is this architecture feasible or should I use some terrific techniques that I do know such as web services,xml-rpc, soap???

The Caller center is for 8~300 operators and the operators do not seperate geographically.
Moreover, I have figured out that we need provide interface for customer programmer, so this thing is so called middleware? Then some new questions, how could we expose interface to customer, COM?

Thanks in advance.

答:
Don't you think your trying to apply reverse engineering here? I mean like the architecture should be more like this:

When Server receives the call, it should look for a free operator and pass the database details of that customer (if known) to the operator, if not then play a video tape or something. In mean time it should have some kind of timer that checks for free operator or you can add some kind of event to the browser or operator's phone call task, as when the operator hangs up, event triggers and tell the server that he is free, on when it receives the call another event triggers and tells server that operator is busy.

I haven't worked on big projects of C++ but I did studied it in college and Uni for a year.

Hope it helped somehow!


答:
As per the folder structure, what you suggested is OK in general. You may need to add folders for resources (sometimes people create resources such that each set of resources are grouped under an ISO language code to support several-languages), images, database scripts, user preferences (if not dealt with as resources), fonts, external dlls, local dlls, etc.

What is the naming convention when adding classes?

Of course, you want to separate each class outside the form. I would recommend also, a file per class (although MS does not do that in code generated for EF for example).

Many people use meaningful short nouns in plural (e.g. Customers). Some ptrfer the name to be close to the singular name for the corresponding database table (if you use 1-1 mapping between objects and tables).

For naming classes there are many sources, for example take a look at:.net Naming Conventions and Programming Standards - Best Practices and/or STOVF-C# Coding Guidelines

What to do, so that not all the code for main form ends up in Form1.cs

Helper code should go to one or more helper classes. Other code that very common to GUI controls such as applying user preferences to a grid, could be removed from the form and either added to helper classes or by sub classing the control in question and creating the necessary methods there.

Due to the event-action nature of MS Windows Forms, there is nothing that I know of that could help you take away code from the main form without adding ambiguity and effort. However, MVVM may be a choice (in future projects), see for example: MVVM for Windows Forms.

Title: How to properly structure a project in winform?

Body:
A while ago I started to create a winform application and at that time it was small and I did not give any thought of how to structure the project.

Since then I added additional features as I needed and the project folder is getting bigger and bigger and now I think it is time to structure the project in some way, but I am not sure what is the proper way, so I have few questions.

How to properly restructure the project folder?

At the moment I am thinking of something like this:

Create Folder for Forms

Create Folder for Utility classes

Create Folder for Classes that contain only data

What is the naming convention when adding classes?

Should I also rename classes so that their functionality can be identified by just looking at their name? For example renaming all forms classes, so that their name ends with Form.
Or is this not necessary if special folders for them are created?

What to do, so that not all the code for main form ends up in Form1.cs

Another problem I encountered is that as the main form is getting more massive with each feature I add, the code file (Form1.cs) is getting really big.
I have for example a TabControl and each tab has bunch of controls and all the code ended up in Form1.cs. How to avoid this?

Also, Do you know any articles or books that deal with these problems?


答:
It looks like you've fallen into some of the common pitfalls, but don't worry, they can be fixed :)

First you need to look at your application a little differently and start breaking it down into chunks. We can split the chunks in two directions. First we can separate controlling logic (The business rules, data access code, user rights code,all that sort of stuff) from the UI code. Second we can break the UI code down into chunks.

So we'll do the latter part first, breaking the UI down into chunks. The easiest way to do this is to have a single host form on which you compose your UI with usercontrols. Each user control will be in charge of a region of the form. So imagine your application had a list of users, and when you click on a user a text box below it is filled with their details. You could have one user control managing the display of the user list and a second one managing the display of the user's details.

The real trick here is how you manage the communication between the controls. You don't want 30 user controls on the form all randomly holding references to each other and calling methods on them.

So you create an interface for each control. The interface contains the operations the control will accept and any events it raises. When you think about this app, you don't care if the list box list selection changes, you are interested in the fact a new user has changed.

So using our example app, the first interface for the control hosting the listbox of users would include an event called UserChanged which passes a user object out.

This is great because now if you get bored of the listbox and want a 3d zoomy magic eye control, you just code it to the same interface and plug it in :)

Ok, so part two, separating the UI logic from the domain logic. Well, this is a well worn path and I'd recommend you look at MVP pattern here. It's really simple.

Each control is now called a View (V in MVP) and we've already covered most of what is needed above. In this case, the control and an interface for it.

All we're adding is the model and the presenter.

The model contains the logic that manages your application state. You know the stuff, it would go to the database to get the users, write to the database when you add a user, and so on. The idea is you can test all of this in complete isolation from everything else.

The Presenter is a bit more tricky to explain. It is a class which sits between the model and the View. It is created by the view and the view passes itself into the presenter using the interface we discussed earlier.

The presenter doesn't have to have its own interface, but I like to create one anyway. Makes what you want the presenter to do explicit.

So the presenter would expose methods like ListOfAllUsers which the View would use to get its list of users, alternatively, you could put an AddUser method the View and call that from the presenter. I prefer the latter. That way the presenter can add a user to the listbox when ever it wants.

The Presenter would also have properties like CanEditUser, which will return true if the user selected can be edited. The View will then query that every time it needs to know. You might want editable ones in black and read only ones in Gray. Technically that's a decision for the View as it is UI focused, whether the user is editable in the first place is for the Presenter. The presenter knows because it talks to the Model.

So in summary, use MVP. Microsoft provide something called SCSF (Smart Client Software Factory) which uses MVP in the way I've described. It does a lot of other things too. It's quite complex and I don't like the way they do everything, but it may help.


问:
Was API hooking done as needed for Stuxnet to work? I don't think so
Caveat: I am a political science student and I have tried my level best to understand the technicalities; if I still sound naive please overlook that.

In the Symantec report on Stuxnet, the authors say that once the worm infects the 32-bit Windows computer which has a WINCC setup on it, Stuxnet does many things and that it specifically hooks the function CreateFileA(). This function is the route which the worm uses to actually infect the .s7p project files that are used to program the PLCs. ie when the PLC programmer opens a file with .s7p the control transfers to the hooked function CreateFileA_hook() instead of CreateFileA(). Once Stuxnet gains the control it covertly inserts code blocks into the PLC without the programmers knowledge and hides it from his view.

However, it should be noted that there is also one more function called CreateFileW() which does the same task as CreateFileA() but both work on different character sets. CreateFileA works with ASCII character set and CreateFileW works with wide characters or Unicode character set. Farsi (the language of the Iranians) is a language that needs unicode character set and not ASCII Characters. I'm assuming that the developers of any famous commercial software (for ex. WinCC) that will be sold in many countries will take 'Localization' and/or 'Internationalization' into consideration while it is being developed in order to make the product fail-safe ie. the software developers would use UNICODE while compiling their code and not just 'ASCII'. Thus, I think that CreateFileW() would have been invoked on a WINCC system in Iran instead of CreateFileA(). Do you agree?

My question is: If Stuxnet has hooked only the function CreateFileA() then based on the above assumption there is a significant chance that it did not work at all? I think my doubt will get clarified if: my assumption is proved wrong, or the Symantec report is proved incorrect. Please help me clarify this doubt.

Edit: For more clarity of my question and what I'm looking for.

Is it possible that the WinCC STL Editor be programmed in the following way?

```<code>//Pseudocode Begins
if (locale == ASCII Dependent) //like US, UK, Australia etc.
{
     CreateFileA(); //with appropriate parameters
}
else if (locale == UNICODE Dependent) //like Middle East, China, Japan etc
{
     CreateFileW(); //with appropriate parameters
} //Pseudocode ends
</code>```

If it is possible then does it follows that Stuxnet would work appropriately in the US but not in China or Japan or Iran?

答:
Many technical works are carried out all in English- it is the lingua franca of programming. It is not particularly uncommon at all for foreign teams to work, code, and document exclusively in English. For example, look at the Lua project, written by a bunch of Brazilians. Documentation? English only. Filenames? All English. And the PLC code would not support Unicode either, so it's not like the Iranians had the option to work all in Arabic.

It does surprise me that it didn't hook CreateFileW, but I suppose that it knew in advance that WinCC only uses CreateFileA.