答:
While the request itself is absurd, and you cannot have a reasonably-done legal proof that a person A checked the checkbox when filling a form, there is a question inside your question which can be actually answered:

[How to ensure that the data was not altered later, while] a DB could be changed after the users has sent the form?

This, actually, may be easier to do technically.

1. Keep a proof that the data was not altered

Sending an e-mail to yourself (to a dedicated mailbox) with the values actually sent by the user is easy (well, it may be, depending on the configuration of your server, the threshold, the chances to be filtered as spam, the number of e-mails sent per second, etc.), and is enough to show that the data was not altered after it was submitted. For example, unless I have an unrestricted access to Google servers, I'm pretty sure every one will be convinced that I am unable to alter the contents of the e-mails I sent to my own GMail address.

2. Keep a proof that the data is correct

Chances are, the customer will not be satisfied, because even if you have a proof that the data was not altered afterward, how can we be sure the data was not modified between the submission of the form and the sending of information by e-mail (and commit to the database)? In this case, the next step is to:

Remove the checkbox,

Mark anyone who filled the form as unwilling to receive <s>spam</s> promotional material from your customers company,

Indicate to the visitors that they have to send an e-mail (with a predefined title and an empty body) to the dedicated mailbox in order to receive the <s>spam</s> commercial offers.

Their e-mails can be then processed automatically, and kept as a proof.

3. Keep a proof that the data is authentic

Now that you have a proof that the person using the given e-mail address actually wants to receive the spam, the customer may still be unsatisfied (which usually happens with customers having such crazy requests). What if someone hacked someone else's mailbox just to register the hackee to receive your spam?

At this level of craziness, you can still respond technically to the requirements. Now, instead of sending a opt-in e-mail, the user of the website have to:

Send a mail with a copy of ID/passport, and a letter, with a signature, saying that this person really wants to receive the spam.

Validate the e-mail address through a secret code which will be sent back.

But before doing this, convince the customer to implement what I described in part 2 and test it. The customer will see that after a month or two, nobody never send any opt-in e-mail, and will happily forget about legal proofs and altered data in the database.


问:
Want to learn C++, and have prior web programming knowledge
I am actually considering learning C++. I want to become a quantitative financial analyst, and going to pursue my CFQ soon. Java is not heavily used in this field, but C++ is for its complexity. For someone who already has knowledge in HTML, CSS, JavaScript (intermediate), and PHP (intermediate), how hard would the switch be to pick up C++ over the course of a year? How long would it take to get certified in C++? And how hard is it to learn? I have built CMS websites, and some decent applications for the web.

I took a college course of beginning programming in Java as well.

Basically switching positions as a web designer to a C++ programmer and use Matlab.

I have heard the language is very complex, but easier to program than languages like Java.

答:
C++ has been around for a long time, which means there are lots of resources (many of them free) you could use to learn it. However, it has changed a great deal over the decades. You can see that in the answers here - people calling it insane and difficult are generally referring to features inherited from C or features that modern C++ developers rarely use, like manual memory management. You would probably find modern C++ quite easy to learn even with only PHP and CSS background. However, that won't help you if quants don't use modern C++.

I just published a course called C++ Fundamentals and since Pluralsight offers a free trial, you could watch the first few hours of it free to see whether learning C++ is something you can do or not. Then you could either go and buy a book or sign up for a paid course to carry yourself further down the path. Be very careful with the book though. If the first chapter is full of char*, int[], while loops that increment pointers, and functions whose names start str, don't buy that book. Look for the first chapter using cout, string, and vector. Look for coverage of lambdas and auto, and look for a tone of simplicity and control. You can find a TON of books, blogs, web pages, FAQs, courses, and so on that teach the hard insane C++ people love to tell stories about. I don't recommend you learn that language first.

If it turns out the quants don't use modern C++, I suppose you could learn the old stuff once you were comfortable with the new. It would be hard. You would also have to learn some specific libraries that do financial calculations, and probably something for multicore and manycore work. For example as a Visual C++ user I would learn PPL and C++ AMP. But start with a foundation of knowing the syntax of the language and the philosophy of those who use it.

ContentLicense: CC BY-SA 3.0


问:
What are the disadvantages of automated testing?
There are a number of questions on this site that give plenty of information about the benefits that can be gained from automated testing.  But I didn't see anything that represented the other side of the coin: what are the disadvantages?  Everything in life is a tradeoff and there are no silver bullets, so surely there must be some valid reasons not to do automated testing.  What are they?

Here's a few that I've come up with:

Requires more initial developer time for a given feature

Requires a higher skill level of team members

Increase tooling needs (test runners, frameworks, etc.)

Complex analysis required when a failed test in encountered - is this test obsolete due to my change or is it telling me I made a mistake?

Edit

I should say that I am a huge proponent of automated testing, and I'm not looking to be convinced to do it.  I'm looking to understand what the disadvantages are so when I go to my company to make a case for it I don't look like I'm throwing around the next imaginary silver bullet.

Also, I'm explicity not looking for someone to dispute my examples above.  I am taking as true that there must be some disadvantages (everything has trade-offs) and I want to understand what those are.

答:
I recently asked a question about tests in game development - this is BTW how I knew about this one. The answers there pointed some curious, specific disadvantages:

It is costly to do when your code should be highly coupled.

It is difficult to do when you have to be aware of the various hardware platforms, when you should analyze output to the user and the code result only makes sense in a broader context.

UI and UX testing is very hard.

And notably, automated tests can be more expensive and less effective than a bunch of very low-cost (or free) beta testers.

The 4th point makes me remember of some experience of mine. I worked on a very lean, XP-oriented, Scrum managed company where unit tests were highly recommended. However, in its path to a leaner, less bureaucratic style, the company just neglected the construction of a QA team - we had no testers. So frequently the customers found trivial bugs using some systems, even with test coverage of >95%.  So I would add another point:

Automated tests may make you feel that QA and testing are not important.

Also, I was thinking those days about documentation and cogitated a hypothesis that may be valid (to a lesser extend) to tests two. I just felt that code evolves so quickly that it is pretty hard to make documentation that follows such a velocity, so it is more valuable to spend time making code readable than writing heavy, easily outdated documentation. (Of course, this does not apply to APIs, but only to internal implementation.) The test suffers a bit from the same problem: it may be too slow to write when compared with the tested code. OTOH, it is a lesser problem because the tests warn they are outdated, while your documentation will stay silent as long as you do not reread it very, very carefully.

Finally, a problem I find sometimes: automated testing may depend upon tools, and those tools may be poorly written. I started a project using XUL some time ago and, man, this is just painful to write unit tests for such platform. I started another application using Objective-C, Cocoa and Xcode 3 and the testing model on it was basically a bunch of workarounds.

I have other experiences about disadvantages of automated testing, but most of them are listed in other answers. Nonetheless, I am a vehement advocate of automated testing. This saved an awful lot of work and headache and I always recommend it by default. I judge those disadvantages are just mere details when compared to the benefices of automated testing. (It is important to always proclaim your faith after you comment heresies to avoid the auto da fé.)


问:
Should you Create Class Diagrams before or after implementation?
The way I see it if you create one before you get the advantage of:

Planning ahead

Overview of the project

but you lose:

Time (doing work you'll probably end up repeating when writing code)

On the other hand, I could just create them all after writing my code just to keep it as a reference for future developers.

Which one serves the purpose of class diagrams and which is more advantageous?

答:
Class diagram creation should be done, during and after because the model should be interactive with the code and requirements modifications.
First you need to create a class diagram to start your project. It would help to visualize at a higher level of abstraction your objects. You will be able to create a stable and intelligent software architecture.
Then you need to code and sometimes you will notice that the architecture which seems to be well in UML is not really possible in the code. You then change you code and architecture.
Finally you update your model with code modification and generate documentation.

In my last project decision makers have changed my requirements over 50 times in the last year. It is really painful and UML help me to keep traceability of changes and why.
UML should allows model and code merge at any time in an iterative way (e.g. from code to model, from model to code, from both, from code after refactoring etc...)
I use Omondo EclipseUML for Helios and I am really happy with this tool. My favorite feature is the model merge which allows me to update my model at any time without loosing model information. I also like entities modeling directly in the class diagram and create the database using stereotype and hibernate. Really powerful and complete from object to database !!

ContentLicense: CC BY-SA 2.5


问:
Where should date formatting take place in an MVC pattern?
Suppose that you want to show a user list, on a web application having to handle custom date formats (depending on current selected interface language).

Several locations for applying the date format seem possible. Which one would you use, and why?

At model, for example doing a DATE_FORMAT(user.birthdate, '%d/%m/%Y') for date fields (supposing we have a MySQL DB).

At controller level, for example (supposing we use PHP):

```<code>$users = UserModel::getUsers();
// loops through results before display to format dates.
// in the $users structure, we have to know which fields are dates or not
$users = MagicFunctionFormattingDates($users);

$view = new View('someTemplate');
$view->assign('users', $users);
</code>```

At view level, for example (supposing we use a template language such as Smarty):

```<code>{foreach key=keyitem item=row from=$users}
  <tr>
  {foreach key=keyfield item=field from=$row.fields}
     {* Here $field should be an Object or associative array
        holding its 'type' (is it a date or something else) *}
     <td>{MagicFunctionForFormatting field=$field}</td>
  {/foreach}
  </tr>
{/endforeach}
</code>```

A similar and related question goes for sumbitting dates (e.g. on a user registration form). Where should the date conversion take place:

In the controller processing and validating the form, before calling the model?

In the model?

答:
The general rule you want to convert from/to date types as close to the user as possible - really this is true of all values but especially dates.

Dates that are stored as a proper date type are unambiguous (or as close as we're going to get) as soon as you go to a string you've got all kinds of opportunities for things to go wrong. So, unless you have good reason to do otherwise (which one does from time to time), you want to convert in both directions in the UX or as close to is as possible.

If these were numbers you probably wouldn't even be asking and yet its essentially the same thing.


问:
Is there a reason to prefer lambda syntax even if there is only one parameter?
```<code>List.ForEach(Console.WriteLine);

List.ForEach(s => Console.WriteLine(s));
</code>```

To me, the difference is purely cosmetic, but are there any subtle reasons why one might be preferred over the other?

答:
with the two examples you gave they differ in that when you say

```<code>List.ForEach(Console.WriteLine)
</code>```

you are actually telling the ForEach Loop to use the method WriteLine

```<code>List.ForEach(s => Console.WriteLine(s));
</code>```

is actually defining a method that the foreach will call and then you are
telling it what to handle there.

so for simple one liners if your method you are going to call carries the same signature as the method that gets called already I would prefer not to define the lambda, I think its a little more readable.

for methods with incompatible lambdas are definitely a good way to go, assuming they aren't to overly complicated.

Body:
with the two examples you gave they differ in that when you say

List.ForEach(Console.WriteLine)

you are actually telling the ForEach Loop to use the method WriteLine

List.ForEach(s => Console.WriteLine(s));

is actually defining a method that the foreach will call and then you are
telling it what to handle there.

so for simple one liners if your method you are going to call carries the same signature as the method that gets called already I would prefer not to define the lambda, I think its a little more readable.

for methods with incompatible lambdas are definitely a good way to go, assuming they aren't to overly complicated.


问:
Would you rather make private stuff internal/public for tests, or use some kind of hack like PrivateObject?
I am quite a beginner in code testing, and was an assert whore before. One thing worrying me in unit testing is that is often requires you to make public (or at least internal) fields that would have been private otherwise, to un-readonly them, make private methods protected virtual instead, etc...

I recently discovered that you can avoid this by using things like the PrivateObject class to acces anything in an object via reflection. But this makes your tests less maintainable (things will fail at execution rather than compile time, it'll be broken by a simple rename, it's harder to debug...). What is your opinion on this ? What are the best practices in unit testing concerning access restriction ?

edit : consider for instance that you have a class with a cache in a file on disk, and in your tests you want to write to memory instead.

答:
In C# you can use the InternalsVisibleToAttribute to allow your test assembly to see internal classes in the assembly you're testing.  It sounds like you already know this.

In most cases I'm only interested in testing the public API of my assembly.  In a case where I want to do white-box testing of some unit, I move the code to an internal class, and make it a public method of that class.  Then I can code a unit test for that class.

This lends itself well to dependency injection and the strategy pattern.  You can abstract the method into an interface, inject the interface into your parent object's constructor, and just test that the parent delegates appropriately.  Then you can test that the child object behaves appropriately.  This makes everything more modular.


答:
Looking at the compiled code through ILSpy, there actually is a difference in the two references.  For a simplistic program like this:

```<code>namespace ScratchLambda
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    internal class Program
    {
        private static void Main(string[] args)
        {
            var list = Enumerable.Range(1, 10).ToList();
            ExplicitLambda(list);
            ImplicitLambda(list);
        }

        private static void ImplicitLambda(List<int> list)
        {
            list.ForEach(Console.WriteLine);
        }

        private static void ExplicitLambda(List<int> list)
        {
            list.ForEach(s => Console.WriteLine(s));
        }
    }
}
</code>```

ILSpy decompiles it as:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
namespace ScratchLambda
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            List<int> list = Enumerable.Range(1, 10).ToList<int>();
            Program.ExplicitLambda(list);
            Program.ImplicitLambda(list);
        }
        private static void ImplicitLambda(List<int> list)
        {
            list.ForEach(new Action<int>(Console.WriteLine));
        }
        private static void ExplicitLambda(List<int> list)
        {
            list.ForEach(delegate(int s)
            {
                Console.WriteLine(s);
            }
            );
        }
    }
}
</code>```

If you look at the IL call stack for both, the Explicit implementation has a lot more calls (and creates a generated method):

```<code>.method private hidebysig static
    void ExplicitLambda (
        class [mscorlib]System.Collections.Generic.List`1<int32> list
    ) cil managed
{
    // Method begins at RVA 0x2093
    // Code size 36 (0x24)
    .maxstack 8

    IL_0000: ldarg.0
    IL_0001: ldsfld class [mscorlib]System.Action`1<int32> ScratchLambda.Program::'CS$<>9__CachedAnonymousMethodDelegate1'
    IL_0006: brtrue.s IL_0019

    IL_0008: ldnull
    IL_0009: ldftn void ScratchLambda.Program::'<ExplicitLambda>b__0'(int32)
    IL_000f: newobj instance void class [mscorlib]System.Action`1<int32>::.ctor(object, native int)
    IL_0014: stsfld class [mscorlib]System.Action`1<int32> ScratchLambda.Program::'CS$<>9__CachedAnonymousMethodDelegate1'

    IL_0019: ldsfld class [mscorlib]System.Action`1<int32> ScratchLambda.Program::'CS$<>9__CachedAnonymousMethodDelegate1'
    IL_001e: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<int32>::ForEach(class [mscorlib]System.Action`1<!0>)
    IL_0023: ret
} // end of method Program::ExplicitLambda

.method private hidebysig static
    void '<ExplicitLambda>b__0' (
        int32 s
    ) cil managed
{
    .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
        01 00 00 00
    )
    // Method begins at RVA 0x208b
    // Code size 7 (0x7)
    .maxstack 8

    IL_0000: ldarg.0
    IL_0001: call void [mscorlib]System.Console::WriteLine(int32)
    IL_0006: ret
} // end of method Program::'<ExplicitLambda>b__0'
</code>```

while the Implicit implementation is more concise:

```<code>.method private hidebysig static
    void ImplicitLambda (
        class [mscorlib]System.Collections.Generic.List`1<int32> list
    ) cil managed
{
    // Method begins at RVA 0x2077
    // Code size 19 (0x13)
    .maxstack 8

    IL_0000: ldarg.0
    IL_0001: ldnull
    IL_0002: ldftn void [mscorlib]System.Console::WriteLine(int32)
    IL_0008: newobj instance void class [mscorlib]System.Action`1<int32>::.ctor(object, native int)
    IL_000d: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<int32>::ForEach(class [mscorlib]System.Action`1<!0>)
    IL_0012: ret
} // end of method Program::ImplicitLambda
</code>```

Title: Is there a reason to prefer lambda syntax even if there is only one parameter?

Body:
```<code>List.ForEach(Console.WriteLine);

List.ForEach(s => Console.WriteLine(s));
</code>```

To me, the difference is purely cosmetic, but are there any subtle reasons why one might be preferred over the other?

Body:
Looking at the compiled code through ILSpy, there actually is a difference in the two references.  For a simplistic program like this:

namespace ScratchLambda
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    internal class Program
    {
        private static void Main(string[] args)
        {
            var list = Enumerable.Range(1, 10).ToList();
            ExplicitLambda(list);
            ImplicitLambda(list);
        }

        private static void ImplicitLambda(List<int> list)
        {
            list.ForEach(Console.WriteLine);
        }

        private static void ExplicitLambda(List<int> list)
        {
            list.ForEach(s => Console.WriteLine(s));
        }
    }
}

ILSpy decompiles it as:

using System;
using System.Collections.Generic;
using System.Linq;
namespace ScratchLambda
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            List<int> list = Enumerable.Range(1, 10).ToList<int>();
            Program.ExplicitLambda(list);
            Program.ImplicitLambda(list);
        }
        private static void ImplicitLambda(List<int> list)
        {
            list.ForEach(new Action<int>(Console.WriteLine));
        }
        private static void ExplicitLambda(List<int> list)
        {
            list.ForEach(delegate(int s)
            {
                Console.WriteLine(s);
            }
            );
        }
    }
}

If you look at the IL call stack for both, the Explicit implementation has a lot more calls (and creates a generated method):

.method private hidebysig static
    void ExplicitLambda (
        class [mscorlib]System.Collections.Generic.List`1<int32> list
    ) cil managed
{
    // Method begins at RVA 0x2093
    // Code size 36 (0x24)
    .maxstack 8

    IL_0000: ldarg.0
    IL_0001: ldsfld class [mscorlib]System.Action`1<int32> ScratchLambda.Program::'CS$<>9__CachedAnonymousMethodDelegate1'
    IL_0006: brtrue.s IL_0019

    IL_0008: ldnull
    IL_0009: ldftn void ScratchLambda.Program::'<ExplicitLambda>b__0'(int32)
    IL_000f: newobj instance void class [mscorlib]System.Action`1<int32>::.ctor(object, native int)
    IL_0014: stsfld class [mscorlib]System.Action`1<int32> ScratchLambda.Program::'CS$<>9__CachedAnonymousMethodDelegate1'

    IL_0019: ldsfld class [mscorlib]System.Action`1<int32> ScratchLambda.Program::'CS$<>9__CachedAnonymousMethodDelegate1'
    IL_001e: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<int32>::ForEach(class [mscorlib]System.Action`1<!0>)
    IL_0023: ret
} // end of method Program::ExplicitLambda

.method private hidebysig static
    void '<ExplicitLambda>b__0' (
        int32 s
    ) cil managed
{
    .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
        01 00 00 00
    )
    // Method begins at RVA 0x208b
    // Code size 7 (0x7)
    .maxstack 8

    IL_0000: ldarg.0
    IL_0001: call void [mscorlib]System.Console::WriteLine(int32)
    IL_0006: ret
} // end of method Program::'<ExplicitLambda>b__0'

while the Implicit implementation is more concise:

.method private hidebysig static
    void ImplicitLambda (
        class [mscorlib]System.Collections.Generic.List`1<int32> list
    ) cil managed
{
    // Method begins at RVA 0x2077
    // Code size 19 (0x13)
    .maxstack 8

    IL_0000: ldarg.0
    IL_0001: ldnull
    IL_0002: ldftn void [mscorlib]System.Console::WriteLine(int32)
    IL_0008: newobj instance void class [mscorlib]System.Action`1<int32>::.ctor(object, native int)
    IL_000d: callvirt instance void class [mscorlib]System.Collections.Generic.List`1<int32>::ForEach(class [mscorlib]System.Action`1<!0>)
    IL_0012: ret
} // end of method Program::ImplicitLambda


问:
How do you know when to stop adding features?
Some time ago I wrote a very small python script that periodically checked an xml feed for new entries, and alerted the user to new entries when present.
I wrote this for myself, so it was essentially a console based program that anyone comfortable with a console interface could have used.

After a while I decided it could be of more use to other people and began to tidy it up, sanitize inputs, remove bugs. It occurred to me that because I'd written the script I knew how to use it efficiently, accurately etc. Others might not, so I started adding a GUI. This started out as a simple menu, and then expanded to a more full GUI with both an interface and options menu. I then added stored user preferences and also storage for previously searched xml feeds to speed up repeat searches.

I added logging to help debug the application in case things go wrong, brought the application up to the latest available stable python codebase for my chosen platform and improved dialog features.

I've bugfixed and commented my code clearly, and yet I still have things I think can be done to improve the app before I make it available to alpha testers. It's a far far cry from my original 20-30 line script. What I anticipated would take me just an hour or two to go from proof of concept to an acceptable use program has taken 10-20 times that. (I'm still a noob, and stuff takes me a long time, but still....)

How do you know when to stop adding/tweaking/fixing stuff and let your baby crawl out in the open?

答:
I dont stop adding features anymore. I just try to get the app out there ASAP and write txt files if i need to. Then i can decide when to stop and when to work on something different

It also helps that i like doing the min possible to get something done (without resorting to hacking).


答:
I want to add one more, a false sense of security. </p>

<p>Beyond very small well defined problem sets, it is not possible to create comprehensive tests. There may and often will still be bugs in our software that the automated tests simply don't test for. When the automated tests pass we all too often assume there are no bugs in the code. </p>

Title: What are the disadvantages of automated testing?

Body:
There are a number of questions on this site that give plenty of information about the benefits that can be gained from automated testing.  But I didn't see anything that represented the other side of the coin: what are the disadvantages?  Everything in life is a tradeoff and there are no silver bullets, so surely there must be some valid reasons not to do automated testing.  What are they?

Here's a few that I've come up with:

Requires more initial developer time for a given feature

Requires a higher skill level of team members

Increase tooling needs (test runners, frameworks, etc.)

Complex analysis required when a failed test in encountered - is this test obsolete due to my change or is it telling me I made a mistake?

Edit

I should say that I am a huge proponent of automated testing, and I'm not looking to be convinced to do it.  I'm looking to understand what the disadvantages are so when I go to my company to make a case for it I don't look like I'm throwing around the next imaginary silver bullet.

Also, I'm explicity not looking for someone to dispute my examples above.  I am taking as true that there must be some disadvantages (everything has trade-offs) and I want to understand what those are.

Body:
I want to add one more, a false sense of security.

Beyond very small well defined problem sets, it is not possible to create comprehensive tests. There may and often will still be bugs in our software that the automated tests simply don't test for. When the automated tests pass we all too often assume there are no bugs in the code.


答: Personally I prefer to leave the code I am testing as pure as I can and if the test code needs hacks (and in C++ nasty pointers etc) I am happy to do that. </p>

Title: Would you rather make private stuff internal/public for tests, or use some kind of hack like PrivateObject?

Body:
I am quite a beginner in code testing, and was an assert whore before. One thing worrying me in unit testing is that is often requires you to make public (or at least internal) fields that would have been private otherwise, to un-readonly them, make private methods protected virtual instead, etc...

I recently discovered that you can avoid this by using things like the PrivateObject class to acces anything in an object via reflection. But this makes your tests less maintainable (things will fail at execution rather than compile time, it'll be broken by a simple rename, it's harder to debug...). What is your opinion on this ? What are the best practices in unit testing concerning access restriction ?

edit : consider for instance that you have a class with a cache in a file on disk, and in your tests you want to write to memory instead.


问:
Will correctness proofs of code ever go mainstream?
All but the most trivial programs are filled with bugs and so anything that promises to remove them is extremely alluring. At the moment, correctness proofs are code are extremely esoteric, mainly because of the difficultly of learning this and the extra effort it takes to prove a program correct. Do you think that code proving will ever take off?</p>

答:
Formal verification has come a long way, but usually industry/widely used tools lag behind the latest research. Here's some recent efforts in this direction:

Spec# http://research.microsoft.com/en-us/projects/specsharp/
This is an extension of C# which supports code contracts (pre/post conditions and invariants) and can use these contracts to do various types of static analysis.

Similar projects to this exist for other languages, such as JML for java, and Eiffel has this pretty much built-in.

Going even further, projects like slam and blast can be used to verify certain behavioral properties with minimal programmer annotation/intervention, but still cannot deal with the full generality of modern languages (things like integer overflow/pointer arithmetic are not modeled).

I believe that we'll see much more of these techniques used in practice in the future. The main barrier is that program invariants are difficult to infer without manual annotations, and programmers are usually unwilling to provide these annotations because doing so is too tedious/time consuming.


问:
Form screenshot for legal proof of clicking one of the checkboxes?
We got a request from one of our customers, and since I've never encountered such a request before, I don't even know where to start looking.

Our customer is a network of colleges, and we're building them a site. On that site, among other things, will be a form which potential applicants can fill out in order to get more info about the studies in one of the colleges. After a user fills out this form - including giving their email and/or phone number - the relevant college then contacts them with the relevant info.

Now, for legal reasons, the client is asking that this form also have a checkbox that the potential applicant checks to indicate that they agree to get promotional material from these colleges. That's of course no problem. But here comes the weird part of the request:

The details of each filled out form have to be be saved in a reliable method. Apparently, saving the form values in a database - a column indicating if the user agreed or didn't agree - isn't enough, because a DB could be changed after the users has sent the form. Our client claims that other college portals create a screenshot of the filled-out form, and save it somewhere in a dedicated folder, in a manner that is easily found, such as giving the file a name that includes the user's name, and the date and time.

My question is as follows: have you heard of using screenshots as a method of proving a user has actually filled out a form? Are there other methods that are are considered reliable?

答:
No such thing

This discussion needs to start with the understanding that there is no way to absolutely prove that the person agreed. This is true even in the physical world. Even if you video the person physically signing a form and putting a drop of their blood on the form, they can say that the video was faked, the blood was taken from them without their knowledge, and the signature was forged. But absolute proof isn't needed; just a reasonable amount of evidence.

In the digital world, any data - text, image, data in a database, or email - can be forged. The closest thing to proof we can have is for the user to encrypt something using a private key and show that their public key will decrypt it. However, this is currently beyond the ability of most users, and they could still say their private key was stolen.

The best we can do is:

Get something that would be difficult (though not impossible) to fake

Agree that, legally, that evidence is sufficient

Make it easy for the user to unsubscribe

Saving an image rather than text adds nothing in terms of proof; all it does is make the process slower and more expensive.

Electronic Signatures

In my job, we have an application where users sign a statement. Legally, the jurisdictions we operate in have passed laws saying that a user typing their email address into a form can count as an electronic signature. We have already verified that they have access to the address by sending a link they must click. That's not absolute proof, but it has been deemed good enough for our purposes.

Whatever information you capture, I'd suggest also capturing a timestamp, so you can say "you agreed at this exact date and time". I'm not sure if that has any legal relevance, but it seems more convincing to me, because it gives more opportunity for the user to prove otherwise ("I have proof that I was not at a computer at that time", for instance).

Going crazy with it

Some things you could do which might be considered evidence:

Capture timestamp, IP, browser, etc, so you can assert the circumstances of the signature

Require email address verification

Require the user to enter their password at the moment of signature

Arrange for there to be a write-only third-party web service running which will receive, at the moment the user signs, an HTTPS POST from  your app with the signature info. If the third party can testify that their service is write-only, that they received the record at that moment, and your copy is identical, you could argue that you haven't modified the data since then.

Send the user an email at that moment saying "thanks for signing up, here's how to unsubscribe." Their email provider or yours may be able to show that the email was sent just after the user signed.

IANAL

Please don't take any of this as legal advice.


问:
Do you find references invisible when you scan code, and are there any coding guidelines for their usage?
I have developed a habit of using safe C++ constructs where possible, but there is one place where I'm always not sure if it's better to use references or resort to good ol' pointers.

Example code:

```<code>int FillFancyPointer(char *&ptr)
{
    ptr = NULL;

    char *tmp_ptr = static_cast<char*>(calloc(...));
    if(!ptr)
        return -1;

   ptr = tmp_ptr;
   return 0;
}
</code>```

Later in code:

```<code>char *ptr = nullptr;
if(FillFancyPointer(ptr)>=0 && ptr)
   Nice();
</code>```

The problem with this, IMHO, is that the ptr appears to be read only variable when looking at the code, while in reality it is modified.

The COM approach ISmthn *ptr;, CoCreate(..., &ptr) seems more pronounced. But it's also more error prone, as there is this ** stuff everywhere.

Come to think of it, output variables like std::string will also be masked with such approach.

int Foo(const string &in, string &inout)

Do you find references confusing in such places?

答:
Everything about your code example is C and not C++. I think you have bigger issues than whether you are passing a pointer by reference or not.  For example, I would suggest using new and delete rather than malloc.

To answer you question directly, use references everywhere you can and pointers when you have to - ie when you need to reseat the reference. All of this is in the C++ FAQ which is a mine of brilliant information.


问:
Deprecation considered harmful?
I've just been compiling some of my own code with the -std=c++0x flag in GCC, as I want to vaguely keep up with what all the young folks are doing (provided they stay of my lawn), and I ended up with a load of warnings about auto_ptr being deprecated. Of course, I knew that auto_ptr was deprecated in C++0x, but...

Isn't deprecation a waste of time and effort? Reasons for not deprecating (with auto_ptr as an example):

there is an ocean of code out there that still needs to be supported, producing millions of warnings will only tempt people to turn warnings off.

auto_ptr is a bit naff, but it does actually do what it says on the tin.

if we really want to deprecate things, I nominate printf(). But just imagine the squeals that would ensue. auto_ptr doesn't have too many friends, but in at least my C++ code it is used more than printf, which isn't used at all.

the committee have a bad record of getting this right - they deprecated static at namespace scope, and now it seems to have been undeprecated  - I wouldn't be surprised if auto_ptr made a similar come-back

lastly, whatever the committee say, the compiler implementers ignore them - they simply can't risk breaking their customers code, all they can do is issue irritating warnings.

So my question - do you consider deprecation (of anything, not just auto_ptrs, and not just in C++) a good idea, and if so, why?

答:
As it stands, deprecation has at least two meanings.

It is going to be removed in a future version

We created better alternatives and now the feature is redundant (but not entirely useless). Newcomers would better skip this while learning the language; however, it is not going to be removed any time soon.

I think static falls into the latter category, but only time will tell if auto_ptr really deserves to be removed or if it's better to keep it in the language.

Title: Deprecation considered harmful?


问:
Platform to Learn/Experiment with Web Programming
I am looking to teach myself some web programming, but I am not sure how I can experiment with an actual website. Are there sites that host platforms for these purposes?</p>

答:
Just buy a domain to test with (as low as 99 cents for the first year if you buy a .info, otherwise about $8-12 a year) and get inexpensive shared hosting with the features you need (LAMP or Windows). This usually runs between $5-15 a month although if you need something like Sharepoint or cloud services it can cost more.

On shared hosting there are limits to what you can do and the amount of traffic you can process (even though they say "unlimited", this isn't exactly true). I've found them to work just fine though for my own ASP.NET and WordPress/PHP testing.


答:
Depending on what your goals are, you may not need to purchase a domain name and hosting.

If you have a Windows, Macintosh, or Linux computer in your possession with some spare disk space and CPU capacity, you can do it all on your own system. I've used Apache and Apache Tomcat on Windows and Mac systems, and if you have a new enough Windows system, you may be able to run IIS as well. This has the benefit of keeping your work private, which is always useful for works in progress.

Title: Platform to Learn/Experiment with Web Programming

Body: I am looking to teach myself some web programming, but I am not sure how I can experiment with an actual website. Are there sites that host platforms for these purposes?</p>


答:
All but the most trivial programs

cannot be fully proofed to be correct with reasonable effort. For any formal proof of correctness, you need at least a formal spec, and that spec has to be complete and correct. This is typically nothing you can easily create for most real-world programs. For example, try to write such a spec for something like the user interface of this discussion site, and you know what I mean.

Here I found a nice article on the topic:

http://www.encyclopedia.com/doc/1O11-programcorrectnessproof.html

Title: Will correctness proofs of code ever go mainstream?

Body: All but the most trivial programs are filled with bugs and so anything that promises to remove them is extremely alluring. At the moment, correctness proofs are code are extremely esoteric, mainly because of the difficultly of learning this and the extra effort it takes to prove a program correct. Do you think that code proving will ever take off?</p>


答:
The legal status of whatever you do is independent of the technical merit of the solution.

For example:

For years British members of parliament would ignore e-petitions because the law demanded that petitions carried a signature for each person. Then someone notice that a hash of an email address, date, time and comment -- even though it contained no secret key -- constituted a "digital signature" in the eyes of UK law.

Therefore, get a lawyer to tell you what to do, and do it. Don't worry whether it's sound.

Or, do what your client asks, trusting that they have checked with a lawyer. Make sure there's a record of the discussion.

Title: Form screenshot for legal proof of clicking one of the checkboxes?

Body:
We got a request from one of our customers, and since I've never encountered such a request before, I don't even know where to start looking.

Our customer is a network of colleges, and we're building them a site. On that site, among other things, will be a form which potential applicants can fill out in order to get more info about the studies in one of the colleges. After a user fills out this form - including giving their email and/or phone number - the relevant college then contacts them with the relevant info.

Now, for legal reasons, the client is asking that this form also have a checkbox that the potential applicant checks to indicate that they agree to get promotional material from these colleges. That's of course no problem. But here comes the weird part of the request:

The details of each filled out form have to be be saved in a reliable method. Apparently, saving the form values in a database - a column indicating if the user agreed or didn't agree - isn't enough, because a DB could be changed after the users has sent the form. Our client claims that other college portals create a screenshot of the filled-out form, and save it somewhere in a dedicated folder, in a manner that is easily found, such as giving the file a name that includes the user's name, and the date and time.

My question is as follows: have you heard of using screenshots as a method of proving a user has actually filled out a form? Are there other methods that are are considered reliable?


答:
The best host or plattform to experiment with is your own computer. Here you (potentially) have root rights for everything and you can learn how to configure your webserver, install all necessary libraries for languasge support etc.

I would recommend to use XAMPP bundle -- this is a bundle that already has a webserver (Apache), a database (MySQL), and two popular web languages PHP and Perl. XAMPP is the name of the original linux installation, but feel free to take WAMPP for Windows or MAMPP for Mac OS -- they all are most updated version of the same distribution.

But back to your question: as long as you have the bundle installed you can directly open your webpage by typing localhost or 127.0.0.1 in your address line -- these are the typical aliases of your own computer. You can immediately start with web development and the deployment of your project will be very easy, since it is on the same machine.

If you want that your webpage is available from outside then you can easily associate a certain DNS name (this is something like http://yousitename.host.com) with your home PC using Dynamic DNS service: this is mostly free (see here for detailed list of providers and prices) and you don't need to buy or rent any server somewhere.

Should you nonetheless wish to have an independent (from your home computer) webpage, I would suggest to look at the free webhosting offer fist. There are plenty of sites where you can host your page for free. Just google for "free web hosting". Be, however, prepared, that the free service has a very limited space, in most cases is linux-based (no licence costs) and often adds some ad to your webpage (either in form of a pop-up window or requires you to do it).


答:
A screenshot is easily fabricated, should you be so inclined. As is any kind of hashing, timestamping, etc, without a cryptographic basis. One presumes there is some stringent regulatory requirement for the college to be able to prove that they obtained positive consent before sending marketing material to people or trading their information to third parties.

The only reliable way to do this is by demanding a cryptographic signature from the user. For an example, see the way that the http://launchpad.net website asks you to cryptograpically sign the Ubuntu Code of Conduct.

This only has force of law in jurisdictions where a cryptographic signature may be used on a legal document, but by signing a specific piece of text, the user may provide proof of their assent that is later verifiable. It would be virtually impossible for the college to forge a correct signature from the same public key.

Note that it is still trivial for the college to update their database, and thus flip the consent field, and also to replace the public key with another for which they know the private key, and generate a valid signature for that key.

Therefore without a third party signing keys to attest that they belong to a particular individual, all this achieves is that the user can verify whether or not the college forged their privacy settings - without the third party signature, it's their word against the college.

If you further require that all key ownership is verified and the key signed by one or more trusted third parties, then the college will be unable to forge apparently valid signatures without a great deal more exposure (they would have to deceive or co-opt the trusted third party in order to get their bogus keys signed). The difficulty of this attack would increase with the number of required third party signatures, but as another poster notes, is not impossible.

So to summarize :

The user must own or generate a private / public key pair

The user must then obtain a signature for their public key from one or more trusted third parties

The user must upload their public key, at least to the college and preferably to a third party key repository

The user must sign a known plaintext and provide the signature as proof they they assented to sharing their private data

Practical problems :

Few people understand cryptographic signatures

The cost of third-party certification can be expensive

This seems like an awful lot of work to safeguard a junkmail checkbox in a college prospectus download page


答:
I'd start by reading up on Electronic Signatures for the client's country/state with the focus of finding out what methods and requirements are legally binding.  I'm positive that no country or state in their right mind would require a screenshot as the only method of proof for a binding electronic signature.

For example, in the U.S. 47 states have accepted the Uniform Electronic Transactions Act, which applies to "governmental matters" among other things and thus would likely apply to the college requirements.  It has the following parts that may help:

..

Electronic signature - means an electronic sound, symbol, or process attached to or logically associated with a record and executed or adopted by a person with the intent to sign the record.

..

Section 7 gives legal recognition to electronic signatures, records and contracts

(a) A record or signature may not be denied legal effect or enforceability solely because it is in electronic form.

(b) A contract may not be denied legal effect or enforceability solely because an electronic record was used in its formation.

(c) If a law requires a record to be in writing, an electronic record satisfies the law.

(d) If a law requires a signature, an electronic signature satisfies the law.

..

Once I knew the laws, I'd estimate the cost of the best electronic signature method vs. the cost of the screenshot method.

Last, I'd discuss with them my findings.  First, I'd explain to them the best option vs. the proposed option.  Next, I'd explain to them the amount of time this would add to the project.  Last, if I was in a place to do so, I'd tell them that this "feature" would add x dollars to the final bill.  I'd be very sure to use the additional cost to me as justification for the additional cost to them.

If they still wouldn't budge, I'd see if they have a supervisor with some sanity I could have the same meeting with.

*I am not a lawyer, so please seek legal advice if you are unsure about anything.


答:
Some formal methods tools (like e.g. Frama-C for critical embedded C software) can be viewed as (sort-of) providing, or at least checking, a (correctness) proof of a given software. (Frama-C check that a program obey to its formalized specification, in some sense, and respect explicitly annotated invariants in the program).

In some sectors, such formal methods are possible, e.g. as DO-178C for critical software in civilian aircraft. So in some cases, such approaches are possible and helpful.

Of course, developing less buggy software is very costly. But the formal method approach makes sense for some kind of software. If you are pessimistic, you might think that the bug are moved from the code to its formal specification (which may have some "bugs", because formalizing the intended behavior of a software is difficult and error prone).


问:
Who decided on the terminology downcasting and upcasting?
As far as I know, the terminology comes from how the inheritance hierarchy is traditionally displayed, with the extending types at the bottom, and the parent types at the top.

This is a bit pointless, unless you feel like calling the following leftcasting and rightcasting.

I am not looking for opinions why the terminology is as is, but they are more than welcome as comments. I am looking for references on who first introduced up and downcasting, and why they decided on that name.

答:
Basically the down- and up-cast is the logical continuation of the subtype (subclass in OOP) and supertype (superclass respectively), e.g. the classical representation of the derived type to be located below the original type -- subtype.

If we search for the term subtyping we find the following (Wikipedia):

The notion of subtyping in programming languages dates back to the
  1960s; it was introduced in Simula derivatives. The first formal
  treatments of subtyping were given by John C. Reynolds in 1980 who
  used category theory to formalize implicit conversions, and Luca
  Cardelli (1985).

So, as many other things, it originated in something vaguely called here as "Simula derivatives" (probably early OOP languages). Simula, however, already has the notion of subclass, but does not feature all the properties of OOP.


答:
The problem with your code sample isn't that you take a reference, it's that you use a return code. In C++, if the operation fails, throw an exception, or if that isn't unusual, then use boost::optional, or even boost::variant<T, ErrorCode>.

Your code is very C and not C++ at all.

Title: Do you find references invisible when you scan code, and are there any coding guidelines for their usage?

Body:
I have developed a habit of using safe C++ constructs where possible, but there is one place where I'm always not sure if it's better to use references or resort to good ol' pointers.

Example code:

```<code>int FillFancyPointer(char *&ptr)
{
    ptr = NULL;

    char *tmp_ptr = static_cast<char*>(calloc(...));
    if(!ptr)
        return -1;

   ptr = tmp_ptr;
   return 0;
}
</code>```

Later in code:

```<code>char *ptr = nullptr;
if(FillFancyPointer(ptr)>=0 && ptr)
   Nice();
</code>```

The problem with this, IMHO, is that the ptr appears to be read only variable when looking at the code, while in reality it is modified.

The COM approach ISmthn *ptr;, CoCreate(..., &ptr) seems more pronounced. But it's also more error prone, as there is this ** stuff everywhere.

Come to think of it, output variables like std::string will also be masked with such approach.

int Foo(const string &in, string &inout)

Do you find references confusing in such places?


答: A screenshot wouldn't be much proof, as there is no way of verifying that a screenshot is real.  That could so easily be faked.  As far as more technical solutions go, there is the archive storage engine for MySQL  that only supports insert and select.  You can't delete from the table at all.  Mind you, it might be possible to ALTER TABLE to a different storage engine, delete the record, and then ALTER TABLE to change the engine back without anyone noticing, but hopefully you could limit that to root, and only allow root to log in locally.  Then you could just track logins to the actual local database machine to figure out who possibly changed it. You could also analyze the binary logs, or enable the raw query log to see who could have issued queries which resulted in this kind of activity.  I'm not sure which database technology you are using, but most likely you should be able to come up with a solution which prevents the data from easily being changed.</p>


问:
How to manage your functional documentation?
Our functional / business documentation is spread across Word files on our corporate Intranet.  It's difficult to find and update information.  There has to be a better way.  Any ideas?

We had thought a Wiki would work great. Would seem to be an easy way to find information and easy for individual developers and analysts to add bits of documentation quickly and easily.  We'd be curious to know if other development (or business analysis) teams use Wiki's with success.

The target for this documentation is the internal development team: developers, qa, and to a lesser extent business analysts.

答:
We have been using Feature Driven Programming.  We upload all the features which come out of the Functional Design meeting as excel to Clear Quest and then can be further linked to Clear case code or any artifacts.

So far in last 15 years of my career, Function Design and traceablity were never this easy. This model takes out of so much of time wastage which I have seen in other companies.

Basically our features live in ClearQuest which is easy to maintain , easy to query, easy to run reports on efforts, backlogs , easy for managers.

Feature Driven Development


答:
How the bleep are you supposed to get a screenshot?  What you've got is the HTML and whatever you're sending to the client, and the electronic response from the client.  Neither involves a screenshot.

The screenshot is of what the browser renders, and will differ somewhat depending on browser in use and settings and equipment on the other end.  Personally, I browse using Firefox, Chrome, Opera, Mobile Safari, occasionally Lynx, and even a little IE sometimes.

You could render the page in a standard browser on your end, and screenshot that, but making your own document and recording it isn't going to impress a judge.  You could ask the user to send a screenshot, but good luck enforcing that.  Not all browsing devices have an obvious way to take and send a screenshot (how do you do it on an iPhone?).  If you're dealing with a vision-impaired customer using a screen reader, there may be no visual representation at all at the client end.  (I saw a couple of blind friends of mine use a portable computer, which had no display whatsoever.)

So explain to the customer that there is no way of getting a screenshot, and there may not even be a screen to take a picture of.


答:
The visibility of your code has nothing to do with your unit tests!

You make your methods private not with the purpose to hide them from testing and you don't make them public to expose for testing, right? This is your implemenation that is essential here, not the tests -- those server as proof of your code, but they are not your code.

There is a plenty of ways to enable access to hidden (private or internal) methods and properties. Many test frameworks and IDEs (for example, Visual Studio) support you here by generating everything needed for the access, you only have to author your test cases. So, why worry? Better keep your code clean and neat.


答:
No.  The common proverb for this is, "In theory, theory and practice are the same.  In practice, not."

One very simple example:  Typos.

Actually running the code through unit testing finds such things almost immediately, and a cohesive set of tests will negate the need for any formal proofs.  All the use cases - good, bad, error, and edge cases - should be enumerated in the unit tests, which end up as better proof the code is correct than any such proof that is separate from the code.

Especially if requirements change, or the algorithm is updated to fix a bug - the formal proof is more likely to end up out of date, same as code comments often get.


答:
You should never-ever have to

make public (or at least internal) fields that would have been private otherwise, to un-readonly them, make private methods protected virtual instead

Making a private member non-private turns the object into a Leaky Abstraction (wikipedia) which is the cause of much weeping and wailing and gnashing of teeth. (wiktionary)

Un-readonlying a field can make an immutable object mutable, which is nothing short of a disaster.

Your test should consider your object-under-test as a Black Box (Wikipedia), meaning that it should only be concerned with the public interface of the object-under-test, not with details of its implementation.

If an object cannot be sufficiently tested via its public interface, then you need to find ways to provide formal and useful extensions to its interface that would facilitate testing. For example, a registration system which only exposes a pair of Register()/Deregister() methods is what I call a Black-Hole Interface because information can only enter it but never leave. To fix this:

The solution is most definitely NOT to expose its internal collection of registrants, so that the test can go peeking into that collection.

The solution is to add an IsRegistered() method, even it will never be invoked by the application at hand; still, it is a formal and useful extension to the interface, it prevents the interface from being a black-hole interface, and incidentally, it accommodates Black-Box Testing.

The important thing is that changing the implementation of the object should not require you to change the unit test. In principle you should be able to completely rewrite the module under test, and reuse the existing test to make sure that the new version works exactly as the old version. This is only possible if the test is strictly a black-box test.

Amendment 2022-11-02 for further reading:

michael.gr - White-Box vs. Black-Box Testing

michael.gr - Incremental Integration Testing

ContentLicense: CC BY-SA 4.0


答:
Having gone through this exact learning experience myself I have two suggestions for you.

First, if you want to learn on the Linux side of things (PHP and MySQL) use easyPHP. I have worked with a good number of WAMP distributions (for running a simple test web server on your own computer) and easyPHP is by far the simplest setup. Also, download the Netbeans IDE for PHP. It is in my opinion, the best IDE for PHP development.

Now if you want to develop in ASP.NET this is all simplified because you can download Microsoft Visual Studio Web Developer Express which has it's own test server built in and is pretty simple to start learning with, seeing as how there are hundreds of tutorials out there for .NET development beginners.

Whatever you do though, don't waste your money on buying a domain and a hosting service unless you actually are planning on throwing up a live website in the immediate future. Save yourself the time and money.


答:
In my experience it is best not to expose the internals of your class specially for the test. Even though this may appear to make the test easier to write. The test is the first client of your class, so if it is hard to test your class through its public interface, it will probably be hard to use your class in other places too.

How easy the class is to test through its public API is feedback on how easy the class will be to use. Think of the tests partially as a way to prototype the usage of your class.

Try to consider why your test needs to sense something about the class that is not available through the public API. Perhaps your class is doing too much and needs to be decomposed into a group of co-operating classes instead? Then you can mock some of the collaborating classes to sense what the class under test is doing.

Try to apply the dependency inversion principal and introduce interfaces between your classes which you can mock in your tests. You can provide the collaborators to your test by using inversion of control.

Also consider applying the "tell don't ask" principal to help structure your class interface in a robust, loosely coupled, manner, where the right information is exposed and the rest is hidden.


答:
It depends on why you're adding features. Are project owners asking for it? users? QA?programmers?

Add the features you have to.

Sift through features that are important.

Ignore features that are nice to have.

Focus on the program's purpose, and make its purpose focused. Feature requests that extend its purpose should be questioned thoroughly before it becomes a swiss army knife.

Title: How do you know when to stop adding features?

Body:
Some time ago I wrote a very small python script that periodically checked an xml feed for new entries, and alerted the user to new entries when present.
I wrote this for myself, so it was essentially a console based program that anyone comfortable with a console interface could have used.

After a while I decided it could be of more use to other people and began to tidy it up, sanitize inputs, remove bugs. It occurred to me that because I'd written the script I knew how to use it efficiently, accurately etc. Others might not, so I started adding a GUI. This started out as a simple menu, and then expanded to a more full GUI with both an interface and options menu. I then added stored user preferences and also storage for previously searched xml feeds to speed up repeat searches.

I added logging to help debug the application in case things go wrong, brought the application up to the latest available stable python codebase for my chosen platform and improved dialog features.

I've bugfixed and commented my code clearly, and yet I still have things I think can be done to improve the app before I make it available to alpha testers. It's a far far cry from my original 20-30 line script. What I anticipated would take me just an hour or two to go from proof of concept to an acceptable use program has taken 10-20 times that. (I'm still a noob, and stuff takes me a long time, but still....)

How do you know when to stop adding/tweaking/fixing stuff and let your baby crawl out in the open?


答:
A schema that is closest to being tamper-proof would be to generate a public/private key pair when the user filled-in the form using (client-side) Javascript, then send the form content, the public key, and the signature to the server, and present the private key to the user and ask them to take note and store it somewhere safe.

With this schema, you would be able to prove that it is impossible to tamper the form data since you did not know the private key that are used to generate the signature. The weakness of this schema is that you have to be able to prove that you never touched the private key, and that the user must not lose their private key.

Since you must be able to prove that you never had access to the private key, it may be necessary include the HTML and all Javascript when generating the form signature; this proves the exact form that the user uses to submit the data (therefore proving that you had not modified the form/javascript since their submission, therefore proving that you did not use javascript to steal their private key).

This schema is complex, and as with any complex system, I cannot guarantee that there isn't a hole (actually, I'm fairly confident that there is, and someone would probably be able to point it out).


答:
If you want to validate that a document remains unaltered (database record, whatever), the "best practice" goes like this:

Serialize the data in a reproducible way, including any fields that might be contentious (e.g. eMail address, whether a box is checked.)

Take the hash of that record (e.g. sha1)

Use the public key for a trusted third party (i.e. a disinterested third party) to encrypt this hash

Post the data in a public way to establish the date at which it existed, e.g. a newsgroup.

To validate, the third party can decrypt the hash and compare it to the now-current hash value.

This has been used to guarantee that insurance records weren't tampered-with; however, the "trusted third party" we paid a certain amount of money to, promulgated the hashes as they were signed back to ourselves and several other clients, so there were several custodians of records who could potentially be subpoena:ed to obtain proof.

This is clearly a ridiculous burden for something like validating a boolean field. But, if you show the client the expense involved, they'll probably stop being dumb.


答:
As pointed out already you can't really prove that the person did agree or not so surely the best solution is:

a) Get the person to confirm their agreement via a link sent to their email address (this ensures they haven't just entered billgates@microsoft.com)

b) Give them the option to un-subscribe from marketing/promotion


问:
svn - when will I see conflicts?
I am just starting a new position and using svn rather than git (my favorite).

With svn if there are any conflicts will I see them after an svn update or after an (attempt) to svn commit?

In other words will an svn update merge remote changes into my current (uncommited) working copy?

I want to be sure not to mess up before my first svn commit if things are not good as I am new to this system! :)

Obviously I have also made a manual copy of my new code in case I run into any issues :)

fyi, I am on Ubuntu 11.10

答:
In other words will an svn update merge remote changes into my current (uncommited) working copy?

Yes.

svn will not let you commit if there are new changes in the repository; you will have to do an update first. This update will merge remote changes into your current working copy and alert you of any merge conflicts that occurred.

Title: svn - when will I see conflicts?


答: I've dealt with my share of crazy before. I can think of some technical solutions but why not go back to the client and suggest rewording the question to 'Do you not want to receive marketing emails?' (or similar wording) and allow the person to opt out?  Then you don't need a screen shot.</p>


问:
What are some examples of "wartiness" making a programming language more useful?
From the accepted answer to "Why is Lisp useful?":

 5. Wartiness. The real world is messy. Pragmatic coding winds up having to either use or invent messy constructs. Common Lisp has
  sufficient wartiness that it can get stuff done.

This thought has occurred to me, too.  I'm currently developing an application whose backend I chose to write in Haskell, and whose frontend is in PHP.  My experience has been that dealing with messy code in PHP is much easier than dealing with messy code in Haskell.  However, it's my own code, and my PHP code probably isn't all that bad.

A simple example of "wartiness" is PHP's == (equality) operator.  You know, the type of equality where '' == 0 is true.  Since I'm wary of ==, I often choose to use PHP's === (strict equality) operator instead:

```<code>$is_admin = ($gid === 24 || $gid === 25);
</code>```

However, the above usage turned out to be wrong.  The $gid value came from the database, and is still a string.  This time, the strict equality operator bit me, and I would have saved myself a few minutes by simply saying:

```<code>$is_admin = ($gid == 24 || $gid == 25);
</code>```

Consider another interesting identity:

```<code>php> var_dump('0012345' == '12345');
bool(true)
</code>```

What the heck?!  == on two strings isn't even string comparison!  However, consider if the user is given an ID card that says 0012345, but the database ID is simply 12345.  Users may have trouble logging in to your application if you chose to use ===.  Sure, you'll get a bug report, and you'll be able to make your application correct rather than relying on this obscure feature.  But it'll take more time.  I'd rather spend that time outside.  It's a really nice day.

By contrast, here's an example of wartiness that is not helpful in most cases:

```<code>js> parseInt(031);
25
</code>```

What are some more concrete examples where "wartiness" helps you Get Things Done?  Please explain why; don't just list features Haskell doesn't have.

Another way of putting it: what are some warty language features to be aware of, and how can we use them to save time?

答: An easy example is about half of C++. There are sections of C++ which frankly are just diseases that should be removed, and it's obvious- for example, array/pointer decay. But they're kept because it increases C compatibility- a useful thing.</p>


答:
I'm with those who recommend using your own computer.  I'd modify it a bit though.  I'd say use a spare computer.  Call it a scratch computer, or a crash-and-burn computer.

It is a great freedom to have a computer where you don't care if you erase the whole disk, where in fact you do that a few times as you "get your house in order."


答:
The back end technology for websites varies drastically among platform and language.  You can custom build your entire application in languages like PHP, use an MVC framework like Ruby on Rails, or use a development stack like ASP.NET or JSP.

Depending on your skill and comfort level (with SQL, HTML, CSS), doing things the (non framework) PHP way will arguably pay off the most, simply because of how much you have to build from the ground up.

If you want to become a professional independent web developer, learning something like Ruby on Rails will pay off more, because after you've learned the technology you can rapidly build websites.

On the flip side- If you want to play with .NET technology, Visual Studio will host ASP.NET webpages on your local machine for debugging purposes.  The ASP.NET way of building websites is also fairly different from the PHP or Ruby way.

Whatever you do, learn the basics of JavaScript and explore with jQuery- it'll apply to any website you build.


答: It's already used by everyone. Every time you use your programming language's type checking, you're basically doing a math proof of the correctness of your program. This works already very well - it just requires you choose correct types for every function and data structure you use. The more accurate the type, the better checking you're going to get. The existing types available in programming languages already have powerful enough tools to describe almost any possible behaviour. This works in every available language. C++ and the static languages are just doing the checks in compile-time, while more dynamic languages like python are doing it when the program is run. The check still exists in all these languages. (for example, c++ already supports checking of side effects the same way haskell does, but you just need to choose to use it.)</p>


问:
Hiring programmers for small companies?
I've been running a company for nearly 10 years, and all this time it's been just myself, another programmer (who's a great friend and cofounder), and a salesman (who's also a friend). Together, we've managed to do decent business and we've all managed to make a living, but we've been trying to expand for a long time now.

Unfortunately, there are a few problems:

The technology we use is not obsolete, but it's also not as popular
compared to other web development options like PHP

We work in a competitive market, competing against multi-million
dollar companies

We can't afford to pay new programmers or salesmen very well. We make
enough money for ourselves, but unless we got a significant number of
new customers we wouldn't be able to pay much.

Because of the fact we can't pay much, we use a slightly more rare
technology, and we compete against large companies, we find it
difficult to find new programmers or salesman.

We desperately need to expand, but when we try to get more customers, we can't support them with so few people (or their demands grow outside of our range of expertise) and when we try to hire new programmers and salesman, we usually don't get a high quality and they usually don't provide a major benefit for our company.

Does anyone have some suggestions or tips on how we could expand?

答:
We can't afford to pay new programmers or salesmen very well

Sorry to say, but I certainly wouldn't work for under market rates unless you can offset that with other options. Equity doesn't add in here very well - company value has a habit of fluctuating and the startup lotto win % doesn't work too well. :)

But you could simply ask people to work part-time. Say your market value for a programmer is 100K. But you can only pay 75% of that. Okay, I would work 3/4 time for 75K. That would actually work really well for me, since I like to work on my own stuff, and 75K would cover my bills well.

You could recruit graduate students for this sort of thing - they are usually badly paid and many are very capable. If you can hire them part time for relatively decent pay (sort of intern-ish), then both of you will be better off.

Fundamentally, you need to get your business more sustainable, of course. But that doesn't relate to hiring very much, and will take time.

Title: Hiring programmers for small companies?


问:
Beginners guide to developing optimization software
I am novice in "serious" programming i.e. applications that deal with real-life applications and software projects that go beyond school assignments.

My interests include optimization, operations research, algorithms and lately i discovered how much I do like software design/development/engineering.

I have already developed some simple desktop applications for some "famous" problems like TSP using heuristc approaches, a VRP solver (in progress) and so on.

While developing this kind of software I actually used basic concepts taught at school such as object-orientation analysis and design. But, I found these courses rather elementary and quite boring (for my expectations).

So I decided to go a little further and start developing "real" software (and this is where I realized how important and interesting software engineering/design is.)

Now, here's my issue: I can not find a "study guide" for developing software of this kind.

Currently, there are numerous resources out there (books, websites, tutorials) in designing and developing complex IS, web applications, smartphone apps but I can't find a book for example entitled "optimization software development". Definetly, someone could claim that "design patterns apply to software in general" but that's not my point.

My point is that I could simply use my imagination for "simple" implementations, but what happens, when my imagination can not go further?

In other words I'm looking for a guide/path to bridge the gap between:
Mathematics-Algorithm Design-Software Engineering-Optimization-Software development

答:
You seem to want to dive in to all aspects of software engineering, which is great, but the disadvantage is that there's no one place to get all these types of answers: ours is a young and rapidly evolving field. The correct answer for "how do I learn to design algorithms?" leads to one whole area of discussion, "how do I learn to write complex programs?" is another, "how do I learn to write fast programs?" a third, and "how do I find the best known ways to solve this type of problem?" is yet another.

What jumps out to me is that you have a passion for what are considered "hard" algorithmic problems. This is not a common career passion (for some reason) and you won't find as broad a range of resources as you will for more common focuses. On the other hand, for those with the combination of mathematical and practical interests and talents, it's a viable niche (although it's hard to break into -- you don't find jobs on Craigslist...). Most algorithmic resources in this area are going to be academic and technique-specific, while low-level performance programming is much more the world of obscure Internet fora and technical documents from the manufacturer.

On the specifics area of function optimization, it sounds like you have mostly worked with fully deterministic precise algorithms so far. These have all sorts of advantages, but are sometimes impractical in problems with very large solution spaces. You might enjoy exploring probabilistic approaches, such as Markov chains, simulated annealing, genetic algorithms and evolutionary programming, ant algorithms, etc.

Additionally, you should at least be aware of the field of approximation algorithms, which forego precision for higher performance (for instance, precise bin packing is NP, but can be solved in polynomial time with an arbitrarily low acceptable error).

I know I haven't given you any direct links, but hopefully I've thrown out enough subjects to fill some time with Google!


答:
The problem with formal proofs is that it only moves the problem back a step.

Saying that a program is correct is equivalent to saying that a program does what it should do.  How do you define what the program should do?  You specify it.  And how do you define what the program should do in edge cases that the spec doesn't cover?  Well, then you have to make the spec more detailed.

So let's say your spec finally becomes detailed enough to describe the correct behavior of every aspect of the entire program.  Now you need a way to make your proof tools understand it.  So you have to translate the spec into some sort of formal language that the proof tool can understand... hey, wait a minute!


答: It is actually possible to create a Mandatory Access Control in conjunction with a Trusted Timestamp Plus a Digital Signature for the database to ensure that the value of the column can be trusted. Screenshots are not the correct answer, there ARE however Trusted Computing solutions that achieve exactly what you wish to achieve. If you want more details you can start a chat with me.</p>


答:
In the short term, when you have something that works reliably and doesn't crash out. Even if it doesn't do everything it could do if you worked on it indefinitely. Shipping as the saying goes is a feature. Reliability and restricted feature set gives you an opportunity for the core functionality to be tested by real people in the real world, who will find things that you never thought of that break your code in ways that would never cross your mind. The less features you have, at this point, the easier it will be to fix those early problems. As the core functionality works more reliably you can start implementing the other "nice to have" stuff with the knowledge that your most important and central code still works well.

In the long term: When you have completed and documented the plug-in system that will allow your users ( and of course you ) to implement new features quickly and easily if you need them. That should be the last feature you need to add- after that it's all plug-ins.


答:
I think the general principle here is that when the shape of the warts in the language happen to match the shape of the warts on your requirements then they cancel out and you can program as if neither were warty.

You asked for an example, so I'll say that in java-script you can "parse" JSON by just using eval().

I picked that example because it shows the dangers of the "wart alignment" style of programming - doing an eval() on JSON strings is a huge security risk unless you control the string you're evaluating completely.  (Which is why I'm calling it warty - the definition is a little subjective).

In your examples, string to int conversions built into the language were great when that's how you wanted it to work, but when it worked differently (like parseInt(031) --> 25) it was not wartiness that helped, but actually wartiness you had to program around.

The problem with wartiness in a programming language is that you generally have limited control over it, so if your requirements drift a bit so that the warts no longer line up, all you're really left with is two sets of warts to program around, those of your requirements plus those of the language.

Title: What are some examples of "wartiness" making a programming language more useful?

Body:
From the accepted answer to "Why is Lisp useful?":

 5. Wartiness. The real world is messy. Pragmatic coding winds up having to either use or invent messy constructs. Common Lisp has
  sufficient wartiness that it can get stuff done.

This thought has occurred to me, too.  I'm currently developing an application whose backend I chose to write in Haskell, and whose frontend is in PHP.  My experience has been that dealing with messy code in PHP is much easier than dealing with messy code in Haskell.  However, it's my own code, and my PHP code probably isn't all that bad.

A simple example of "wartiness" is PHP's == (equality) operator.  You know, the type of equality where '' == 0 is true.  Since I'm wary of ==, I often choose to use PHP's === (strict equality) operator instead:

```<code>$is_admin = ($gid === 24 || $gid === 25);
</code>```

However, the above usage turned out to be wrong.  The $gid value came from the database, and is still a string.  This time, the strict equality operator bit me, and I would have saved myself a few minutes by simply saying:

```<code>$is_admin = ($gid == 24 || $gid == 25);
</code>```

Consider another interesting identity:

```<code>php> var_dump('0012345' == '12345');
bool(true)
</code>```

What the heck?!  == on two strings isn't even string comparison!  However, consider if the user is given an ID card that says 0012345, but the database ID is simply 12345.  Users may have trouble logging in to your application if you chose to use ===.  Sure, you'll get a bug report, and you'll be able to make your application correct rather than relying on this obscure feature.  But it'll take more time.  I'd rather spend that time outside.  It's a really nice day.

By contrast, here's an example of wartiness that is not helpful in most cases:

```<code>js> parseInt(031);
25
</code>```

What are some more concrete examples where "wartiness" helps you Get Things Done?  Please explain why; don't just list features Haskell doesn't have.

Another way of putting it: what are some warty language features to be aware of, and how can we use them to save time?


问:
Comment before or after the relevant code
Assuming a comment won't fit (or can't go) on the line it applies to, should one write the comment before the code or after?

Well, wherever future readers will best understand the comment's scope. In other words, wherever most programmers/scripters put such comments.

So where do most programmers/scripters put a comment: before or after its code?

If your answer applies only to specific languages, please indicate which.

And if you can cite an accepted spec or guide that supports your answer, so much the better.

答: I prefer comments to be above the code they refer to, it just makes more sense to tell a person reading code about what is coming up rather than trying to refer to previous code to explain that some messy lines of code fixed some bug that was tricky so don't touch it.</p>


问:
How do you determine velocity when the previous sprint was half User Stories and half Defects?
The following scenario often happens with my team at the office. Let's say we decided to plan our Sprint this way:

50% new features

50% bug fixing (they are high priority AND unestimated as the fixes are easy, the hard and time-consuming bit is the investigation)

The Sprint goes well and we finish all the features, say X story points, and quite a few unestimated bugs.

Two questions come to mind:

What is our Sprint velocity? Is it X?

Assuming it is X; how do we plan the next Sprint using "yesterday's weather" (X story points) if we now want to do an 100% new features Sprint?

答:
If the discovered defects are not related to a currently active story, the defect prioritization and estimation should be part of sprint planning.

Prior to planning, the team can assign points to defects in the same way they assign points to features, which will allow the product owner to prioritize defects in relation to features. The time required to investigate and resolve defects should be defined as tasks associated with the defect.

It's really crucial that the product owner be made aware of the level of effort required to resolve each defect so he/she has has a clear picture of what is going on.  I would hesitate to allow a philosophical debate on the definition of "velocity" get in the way of this.

However, if you're trying to show management that a high defect rate is impacting the rate at which you deliver features, you can always show this via defect counts or defect/feature ratios.

I think this would be better than showing declining velocity without explanation.


答: I think code is generally read top-to-bottom.  If nothing else, muscle memory would cause me to associate a comment with the next line of code beneath it.</p>

Title: Comment before or after the relevant code

Body:
Assuming a comment won't fit (or can't go) on the line it applies to, should one write the comment before the code or after?

Well, wherever future readers will best understand the comment's scope. In other words, wherever most programmers/scripters put such comments.

So where do most programmers/scripters put a comment: before or after its code?

If your answer applies only to specific languages, please indicate which.

And if you can cite an accepted spec or guide that supports your answer, so much the better.


答:
Typically the comment should be on the TOP of the row following the same indentation as the work. For example, comments above the body of the functions, and one liner comments just above the start of a critical algorithm.

The reason is, when someone starts reading it, it becomes obvious question that why something is done in such a way; where as the person doesn't know till what point one needs to scroll for the answer. If it is on top, it is right there to see.


问:
Pair Programming with Scrum
I'm on a team that is currently using Scrum, and we're considering adding pair programming to help improve the cross-functional skills of the team, as well as help reduce defects with a "two heads are better than one" philosophy.

On our team, each team member typically signs up for a full workload during sprint planning (with "full" being a number that is less than 40 hours a week, allowing for meetings, collaboration, etc.), with a single dedicated owner for each task.  I believe this is fairly common on Scrum teams but may not necessarily be by the book.

In particular, I'm looking to avoid a situation where team members are hesitant to pair because they have their own tasks to work on, which I'm afraid is likely to happen if the team simply self-organizes without time set aside for pairing.

Given this, what is the best way to account for effort/hours/story points in a pairing scenario, to make sure we have appropriately allotted time for pairing?

Some options considered are:

Allow two people to sign up for each task and (roughly) double the number of estimated hours

Only the "hands on keyboard" team member signs up for each task, which is estimated based on that person's estimated hours.  Anyone on the team who will be supporting pairing will sign up for fewer tasks in the sprint to allow time to support pairing.

答:
The most common option I have seen when pair programming is employed within scrum is to double up the development estimates.

That is, if the task is estimated to take 3 hours for one person, the time allocated would be 6 hours for the pair.

Substitute hours for points if that makes you feel more clean ;)

Title: Pair Programming with Scrum


答:
I would either comment inline or before the code the comment should apply to.
The sense of comments is to get some basic understanding what the code does, without the need to read the code itself. So it makes much more sense to place the comments before the code it describes.

Microsoft says it would be a good programming practice to begin procedures with a small comment. (They don't mention commenting after procedures) MSDN
The link is about VisualBasic but it applies to the most programming languages i think.


问:
What's the difference between the greedy and Hamiltonian methods?
Given T={CTAGC, GAGCG, AGCGG, CGGAG}, using a greedy algorithm, the superstring S will be CTAGCGGAGCG.

From S, the combination of triplets will be given as s = {CTA, TAG, AGC, GCG, CGG, GGA, GAG, AGC, GCG}.

Both GCG and AGC are repeated.

If using s to retrieve the superstring by using Hamiltonian method, would the repeated words will be used or omitted?

If the repeated word is omitted, then CTA, TAG, AGC, GCG, CGG, GGA, and GAG constructed back will become GTAGCGGAGC.

So, in the end, both the greedy method and Hamiltonian method will provide different results in the superstring.

Why are they different? In my research, all the examples I found showed that there are no repeated words in the combination, so if I reconstruct the superstring using the Hamiltonian method, the result of the greedy and Hamiltonian methods will be the same. But what about the repeated words?

答:
I didn't quite know the exact algorithm that expresses Super string S from the set T However here is a short answer to your question.

Basically, greedy optimization (or search) algorithm returns after they find first minimum. Thus, they are fairly dependent on the starting point and the nature of the function. On the other hand, Global optimization algorithms tend to search the entire possible space to find the minima across the space. When the search space is minimum, or convex by nature the result of both the type of algorithm is same because there is only 1 minimum. However, if there are many local minima then the global optimization algorithm will search the correct one, whereas the greedy algorithm may produce a sub-optimal result.


答:
To borrow some ideas from technical writing (at least in the English language), things such as notes and cautionary warnings are typically placed before the instruction or section that the note or cautionary warning applies to.

I don't see why code can not be considered a form of technical writing - each block is an instruction. Like the English language, most programming languages are read left to right, top to bottom. Comments are notes about the code - they might identify errors to fix, or things that a future developer might need to be aware of.

Following this relationship, it seems more appropriate to put the comment above the block of code that it refers to.


问:
What are the disadvantages of automated testing?
There are a number of questions on this site that give plenty of information about the benefits that can be gained from automated testing.  But I didn't see anything that represented the other side of the coin: what are the disadvantages?  Everything in life is a tradeoff and there are no silver bullets, so surely there must be some valid reasons not to do automated testing.  What are they?

Here's a few that I've come up with:

Requires more initial developer time for a given feature

Requires a higher skill level of team members

Increase tooling needs (test runners, frameworks, etc.)

Complex analysis required when a failed test in encountered - is this test obsolete due to my change or is it telling me I made a mistake?

Edit

I should say that I am a huge proponent of automated testing, and I'm not looking to be convinced to do it.  I'm looking to understand what the disadvantages are so when I go to my company to make a case for it I don't look like I'm throwing around the next imaginary silver bullet.

Also, I'm explicity not looking for someone to dispute my examples above.  I am taking as true that there must be some disadvantages (everything has trade-offs) and I want to understand what those are.

答:
Two that aren't mentioned are:

Length of clock time it may take to run a large test suite

I've been a part of automated QA efforts where it took half a day to run the tests, because the tests were slow. If you're not careful with writing your tests, your test suite could turn out this way too. This doesn't sound like a big deal until your now managing that time, "Oh, I just committed a fix, but it's going to take 4 hours to prove correctness".

Frailty of some test writing methods

Some testing methods (such as automating the UI) seem to break every time you turn around. Especially painful if your script, say, hangs the testing process because it's waiting for a button to appear - but the button has been renamed.

These are both things you can work around, with good testing practice: find ways to keep your test suite fast (even if you have to do tricks like distributing test runs across machines/CPUs). Likewise, some care can be taken to try to avoid frail methods of writing tests.


答:
I'm going to recommend you sit down and read the ESIGN Act. This statute covers what is and isn't necessary to record an electronic signature in order for it to be legally binding. At a previous employer, we found that the most difficult statutory hurdle was to be able to make the signatures and docments readable for 10-15 years into the future.

The details of each filled out form have to be be saved in a reliable method. Apparently, saving the form values in a database - a column indicating if the user agreed or didn't agree - isn't enough, because a DB could be changed after the users has sent the form. Our client claims that other college portals create a screenshot of the filled-out form, and save it somewhere in a dedicated folder, in a manner that is easily found, such as giving the file a name that includes the user's name, and the date and time.

As others have pointed out, the screenshot is something that cannot be done. It can be faked, as all "magic" shows are pure fakery: you see someone getting sawed in half, but they are not actually getting sawed in half.


答:
A comment may need to go either above or below a piece of code, depending on what kind of comment it is: if it gives an ultra-brief explanation of what the code does, then it needs to precede the code; if it elaborately clarifies a technical detail about how the code works, then it needs to follow the code.

Luckily, a comment can go either above or below a piece of code, and still leave no doubts about which piece of code it pertains to, by making proper use of blank lines. Of course, programmers who do not pay attention to the use of blank lines will not know what I am talking about; if you are one of those, please skip this answer and move on with your life. But programmers who pay attention to blank lines know very well that blank lines are used to divide code up into logical entities. So, if you see the following:

```<code>[blank line]
/* comment */
{ code }
[blank line]
</code>```

You know that the comment belongs to the code, and that it tells you what the code does. Whereas, if you see the following:

```<code>[blank line]
{ code }
/* comment */
[blank line]
</code>```

Again you know very well that the comment belongs to that code, and it is a clarification about how the code does what it does.

Body:
A comment may need to go either above or below a piece of code, depending on what kind of comment it is: if it gives an ultra-brief explanation of what the code does, then it needs to precede the code; if it elaborately clarifies a technical detail about how the code works, then it needs to follow the code.

Luckily, a comment can go either above or below a piece of code, and still leave no doubts about which piece of code it pertains to, by making proper use of blank lines. Of course, programmers who do not pay attention to the use of blank lines will not know what I am talking about; if you are one of those, please skip this answer and move on with your life. But programmers who pay attention to blank lines know very well that blank lines are used to divide code up into logical entities. So, if you see the following:

[blank line]
/* comment */
{ code }
[blank line]

You know that the comment belongs to the code, and that it tells you what the code does. Whereas, if you see the following:

[blank line]
{ code }
/* comment */
[blank line]

Again you know very well that the comment belongs to that code, and it is a clarification about how the code does what it does.