问:
Does this justify goto statements?
I came across this question a second ago, and I'm pulling some of the material off of there: Is there a name for the 'break n' construct?

This appears to be a needlessly complex way for people to have to instruct the program to break out of a double-nested for loop:

```<code>for (i = 0; i < 10; i++) {
    bool broken = false;
    for (j = 10; j > 0; j--) {
        if (j == i) {
            broken = true;
            break;
        }
    }
    if (broken)
        break;
}
</code>```

I know textbooks like to say goto statements are the devil, and I'm not fond of them at all myself, but does this justify an exception to the rule?

I'm looking for answers that deal with n-nested for loops.

NOTE: Whether you answer yes, no, or somewhere in between, completely close-minded answers are not welcome.  Especially if the answer is no, then provide a good, legitimate reason why (which is not too far from Stack Exchange regulations anyway).

答:
I don't think this case justifies an exception, as this can be written as:</p>

```<code>def outerLoop(){
    for (i = 0; i < 10; i++) {
        if( broken?(i) )
          return; // broken
    }
}

def broken?(i){
   for (j = 10; j > 0; j--) {
        if (j == i) {
            return true; // broken
        }
   }
   return false; // not broken
}
</code>```

Title: Does this justify goto statements?

Body:
I don't think this case justifies an exception, as this can be written as:

def outerLoop(){
    for (i = 0; i < 10; i++) {
        if( broken?(i) )
          return; // broken
    }
}

def broken?(i){
   for (j = 10; j > 0; j--) {
        if (j == i) {
            return true; // broken
        }
   }
   return false; // not broken
}


答:
In this instance, you could refactor the code into a separate routine, and then just return from the inner loop. That would negate the need to break out of the outer loop:

```<code>bool isBroken() {
    for (i = 0; i < 10; i++)
        for (j = 10; j > 0; j--)
            if (j == i) return true;

    return false;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Does this justify goto statements?

Body:
I came across this question a second ago, and I'm pulling some of the material off of there: Is there a name for the 'break n' construct?

This appears to be a needlessly complex way for people to have to instruct the program to break out of a double-nested for loop:

```<code>for (i = 0; i < 10; i++) {
    bool broken = false;
    for (j = 10; j > 0; j--) {
        if (j == i) {
            broken = true;
            break;
        }
    }
    if (broken)
        break;
}
</code>```

I know textbooks like to say goto statements are the devil, and I'm not fond of them at all myself, but does this justify an exception to the rule?

I'm looking for answers that deal with n-nested for loops.

NOTE: Whether you answer yes, no, or somewhere in between, completely close-minded answers are not welcome.  Especially if the answer is no, then provide a good, legitimate reason why (which is not too far from Stack Exchange regulations anyway).

Body:
In this instance, you could refactor the code into a separate routine, and then just return from the inner loop. That would negate the need to break out of the outer loop:

bool isBroken() {
    for (i = 0; i < 10; i++)
        for (j = 10; j > 0; j--)
            if (j == i) return true;

    return false;
}


答:
No, I don't think a goto is necessary. If you write it like this:

```<code>bool broken = false;
saved_i = 0;
for (i = 0; i < 10 && !broken; i++)
{
    broken = false;
    for (j = 10; j > 0 && !broken; j--)
    {
        if (j == i)
        {
            broken = true;
            saved_i = i;
        }
    }
}
</code>```

Having &&!broken on both loops lets you break out of both loops when i==j.

To me, this approach is preferable. The loop conditions are extremely clear: i<10 && !broken.

A working version can be seen here: http://rextester.com/KFMH48414

Code:

```<code>public static void main(String args[])
{
    int i=0;
    int j=0;
    boolean broken = false;
    for (i = 0; i < 10 && !broken; i++)
    {
        broken = false;
        for (j = 10; j > 0 && !broken; j--)
        {
            if (j == i)
            {
                broken = true;
                System.out.println("loop breaks when i==j=="+i);
            }
        }
    }
    System.out.println(i);
    System.out.println(j);
}
</code>```

Output:

```
loop breaks when i==j==1
2
0
```

Title: Does this justify goto statements?

Body:
No, I don't think a goto is necessary. If you write it like this:

bool broken = false;
saved_i = 0;
for (i = 0; i < 10 && !broken; i++)
{
    broken = false;
    for (j = 10; j > 0 && !broken; j--)
    {
        if (j == i)
        {
            broken = true;
            saved_i = i;
        }
    }
}

Having &&!broken on both loops lets you break out of both loops when i==j.

To me, this approach is preferable. The loop conditions are extremely clear: i<10 && !broken.

A working version can be seen here: http://rextester.com/KFMH48414

Code:

public static void main(String args[])
{
    int i=0;
    int j=0;
    boolean broken = false;
    for (i = 0; i < 10 && !broken; i++)
    {
        broken = false;
        for (j = 10; j > 0 && !broken; j--)
        {
            if (j == i)
            {
                broken = true;
                System.out.println("loop breaks when i==j=="+i);
            }
        }
    }
    System.out.println(i);
    System.out.println(j);
}

Output:

loop breaks when i==j==1
2
0


问:
Agile for the Solo Developer
How would someone implement Agile process concepts as a solo developer?  Agile seems useful for getting applications developed at a faster pace, but it also seems very team oriented...</p>

答:
By doing test-driven development

By developing in small sprints

By having a lot of contact with the customer

I remember reading a thesis about Cowboy Development, that is essentially Agile for solo developers. The thesis can be read here: Cowboy: An Agile Programming Methodology For a Solo Programmer (PDF)

ContentLicense: CC BY-SA 2.5

Title: Agile for the Solo Developer

ContentLicense: CC BY-SA 4.0


问:
Sharing programming fees with a fellow software developer
My question relates to how I should share the fees paid by clients to me and a fellow programmer, both of whom are freelancers.

I've thought of a few options, but I'm in a dilemma as to which one would be the most motivating for both of us.

1) The first option I've thought is a fifty-fifty share. However, more brainwork is going to be done by my colleague, while initially at least, I will be handling the communication with customers.

2) The second option is a 60-40 share, where the colleague exerting more efforts gets a bigger share. This is the option I feel most inclined to adopt, but I'm not sure how it's going to feel in the long run.

3) The third option is calculating each one's contribution in terms of the number of hours spent, and sharing the revenue accordingly.

It will be wonderful to hear everybody's thoughts on this!

答: Assuming neither of you have another source of income and both of you have similar financial responsibilities (family, mortgage etc.), 50-50 is IMO the best option. Otherwise, in a few years, one will have significantely more of everything (car, house, toys etc.), which will most likely cause envy and distrust.</p>


问:
Transparently adding a database interface layer
I am currently looking for ways to optimize an application that is consuming unacceptable amounts of memory.

The process basically takes input and parses it into a tree. The tree is currently stored in memory. For an average input, it may consume 100 MB to 2 GB of memory. For larger inputs, it may consume up to 6 GB, which is more than what most of our machines can handle if we wanted to test it locally. We are afraid there will be even larger inputs in the future, and so it's time to find a more scalable solution.

Rather than storing everything in memory, I would like to move the tree, or parts of the tree, into external storage. Benchmarking the effects of not storing certain parts of the tree in memory has resulted in a 90% reduction in memory consumption.

We have a framework (well, just our own library) that allows us to work with the tree using a set of standard getter and accessor methods. We use standardized methods for creating, reading, updating, and deleting nodes.

Our parsers typically interact directly with nodes. For example, a sample method might say

```<code>// Takes some data and updates the tree with new data
private void managePerson(String id) {

  // this returns a node with the given ID, or creates one if it doesn't exist yet
  // and returns a reference to it
  NodePerson node = getPerson(id)

  // add or update some attributes
  node.age.set(25)
  node.name.set("John")

  // add some points to the existing value
  int points = node.points.get()
  node.points.set(points + 5)
}
</code>```

Given this information, I am thinking of using a database. However, I would also like to be able to implement the changes transparently so as not to affect a decade's worth of code that relies on the tree.

What can I use that will allow me to get data out into a database while allowing developers to get a reference to an object (eg: a person node) and treat it like any other object without any knowledge of where and how the tree is stored internally?

It would also be nice if the solution tried to optimize the amount of queries that are made. For example, instead of inserting 10000 person nodes one at a time, it would somehow figure out a way to batch insert it.

This is meant to be temporary storage: once the parsing is complete, all of the data can be discarded as we are serializing the data in a file (again, based on practices that have been implemented years ago. This can be changed, but we don't have plans for that yet)

答:
You are basically having a problem most ORMs try to solve. You have an object model defined and you want to persist it in non-object way. I know NHibernate solves it by subclassing each class in the model and adding a specific functionality that allows it to track changes to this class. Then, when the session closes, those classes are queried for changes made and those changes are converted into SQL updates. This is called Unit Of Work pattern.

You could do the same. Define the model in a form of classes and then subclass those in the "persistence" module and add the persistence logic. But this kind of logic is usually extremely hard and tedious to program. And it requires changing the persistence model every time the model itself changes.

Like I said in my comment, It would be best if you somehow managed to parse the whole thing into a database and work with it directly there. It doesn't even have to be a relational, it could be a NoSQL solution too. And many of those allow in-memory embedded access, so there is no need to worry about running a separate application or performance issues. To me, this would be most reasonable solution.


问:
Coding standards for c#
I wanted to know if there are some default standards for writing c# code. By default I mean may be something officially from Microsoft, or any other organization.

I am looking for something where I can find answers to questions like following:

should I do this:

```<code>public void DoSomeThing(int id)
{
    //method body
}
</code>```

or:

```<code>public void DoSomeThing(int id) {
    //method body
}
</code>```

should I do this:

```<code>Car car = new Car();
</code>```

or:

```<code>Car car =
    new Car();
</code>```

should I declare my variable in camel or pascal case, should I declare input parameters in method signature camel or pascal, should the global variable be prefixed with underscore or internal variable be prefixed with underscore ...

all these kind of questions ... any suggestions?

The actual issue is, I work on two projects for two different companies. and both have exactly opposite standards. I want to convince either of those and my self that such and such is the right way, because of such and such reason.

I know there is no one right way, but still any defaults documented from any leader organization would help. Thanks.

答:
I would say StyleCop is the authoritative way of enforcing C# code style since it originally came from Microsoft. For any C# developer I can't recommend the combination of ReSharper and StyleCop enough -- it really makes a difference.

Code style can be something that starts all kinds of holy wars among programmers, and when I first started using StyleCop I ended up suppressing most of its suggestions (don't intermingle static and instance methods, pah!).

After a few years of using it and trying to abide by its standards I can say it really pains me to read code that's not StyleCop compliant.

Title: Coding standards for c#


答:
The apparent need for a go-to statement arises from you choosing poor conditional expressions for the loops.

You state that you wanted the outer loop to continue as long i < 10 and the innermost one to continue as long as j > 0.

But in reality that's not what you wanted, you simply didn't tell the loops the real condition you wanted them to evaluate, then you want to solve it by using break or goto.

If you tell the loops your true intentions to begin with, then no need for breaks or goto.

```<code>bool alsoThis = true;
for (i = 0; i < 10 && alsoThis; i++)
{
    for (j = 10; j > 0 && alsoThis; j--)
    {
        if (j == i)
        {
            alsoThis = false;
        }
    }
}
</code>```

Title: Does this justify goto statements?

Body:
The apparent need for a go-to statement arises from you choosing poor conditional expressions for the loops.

You state that you wanted the outer loop to continue as long i < 10 and the innermost one to continue as long as j > 0.

But in reality that's not what you wanted, you simply didn't tell the loops the real condition you wanted them to evaluate, then you want to solve it by using break or goto.

If you tell the loops your true intentions to begin with, then no need for breaks or goto.

bool alsoThis = true;
for (i = 0; i < 10 && alsoThis; i++)
{
    for (j = 10; j > 0 && alsoThis; j--)
    {
        if (j == i)
        {
            alsoThis = false;
        }
    }
}


问:
How to ensure method finishes running before being run again
I'm new and I am trying to figure something out. I have a simple program which executes a method either when an event happens or when my timer ticks. Lets just say the method takes 5 seconds to complete. During that 5 seconds an event could happen. What would I use/do to make sure my method isn't called while its already running.

Or is this something I would not have to worry about in a simple program, as it wouldn't run until the method is done anyway ?

A little background and example.
I am using System.Windows.Forms.Timer, I am not using any threads or anything, and I just have a simple windows form application with a timer, a method to do stuff, and two event handlers.

```<code>Program{
  public Program(){
    DoSomething();
    Event.EventHappened += HandleEvent;
  }
  void DoSomething(){
    MyTimerVariable.Stop();
    InitMyTimer();
    //Just do something check network, access db write line, something
    //that in this example takes 5 secs for example purposes
    MyTimerVariable.Start();
  }
  void HandleEvent(){
    DoSomething();
  }
  void InitMyTimer(){
    // Create Timer, and add Timer tick event
  }
  void TimerTickedEvent(){
    DoSomething();
  }
}
</code>```

I left a few things out of that program, but just was trying to show how simple it is. I was just thinking about making it more efficient so that say in the middle of doing "DoSomething()" an event is triggered, I wouldn't want two "DoSomething()"s method running.

答:
If the real intent is to make sure that you won't have multiple worker methods working at the same time the simplest way would be something like this:

```<code>bool isBusy = false;
void MyWorkerMethod()
{
  if(isBusy == true)
  {
    return;
  }

  try
  {
    isBusy = true;
    // do stuff
  }
  finally
  {
    isBusy = false;
  }
}
</code>```

This way every time the timer ticks, it still executes your method but your method will immediately exit if it's in the middle of working with a minimum of fuss. If you use locking you'll get thread contention as things stack up waiting for the lock to free which I'm assuming is not what you want.

If you're super paranoid you could also look into the Interlocked.* APIs to make sure beyond a shadow of a doubt that you never have your worker running more than once but that may be overkill here.

Body:
If the real intent is to make sure that you won't have multiple worker methods working at the same time the simplest way would be something like this:

bool isBusy = false;
void MyWorkerMethod()
{
  if(isBusy == true)
  {
    return;
  }

  try
  {
    isBusy = true;
    // do stuff
  }
  finally
  {
    isBusy = false;
  }
}

This way every time the timer ticks, it still executes your method but your method will immediately exit if it's in the middle of working with a minimum of fuss. If you use locking you'll get thread contention as things stack up waiting for the lock to free which I'm assuming is not what you want.

If you're super paranoid you could also look into the Interlocked.* APIs to make sure beyond a shadow of a doubt that you never have your worker running more than once but that may be overkill here.


答:
In your case, goto is enough of an improvement that it looks tempting, but it's not so much of  an improvement that it's worth breaking the rule against using them in your code base.

Think of your future reviewer:  s/he will have to think, "Is this person a bad coder or is this in fact a case where the goto was worth it? Let me take 5 minutes to decide this for myself or research it on the internet." Why on earth would you do that to your future coder when you can not use goto entirely?

In general this mentality applies to all "bad" code and even defines it:  if it works now, and is good in this case, but creates effort to verify it's correct, which in this era a goto will always do, then don't do it.

That being said, yes, you produced one of the slightly thornier cases. You may:

use more complex control structures, like a boolean flag, to break out of both loops

put your inside loop inside its own routine (likely ideal)

put both loops in a routine and return instead of breaking

It's very hard for me to create a case where a double-loop isn't so cohesive that it shouldn't be its own routine anyway.

By the way, the best discussion of this I've seen is Steve McConnell's Code Complete. If you enjoy thinking of these problems critically I strongly recommend reading, even cover-to-cover despite its immensity.

Title: Does this justify goto statements?


问:
Using Hibernate Criteria framework for complex queries vs. just making views in DB
I like using Hibernate for regular simple CRUD operations.

However, I am trying to understand why anyone would resort to its Criteria framework to assemble complex recordset criteria as opposed to simply creating a view at the database level.

E.g. here is a paraphrased snippet I am working with:

```<code>Criteria tableCriteria = session
    .createCriteria(SomeEntity.class)
    .add(Restrictions.eq("someID", someID))
    .add(Restrictions.gtProperty("scoreOne", "scoreTwo"))
    .add(Restrictions.gt("scoreThree", scoreThreeMin))
    .add(Restrictions.or(Restrictions.eq("inactive", Boolean.FALSE), Restrictions.isNull("inactive"))).addOrder(Order.asc("ordCol"))
</code>```

From the naked eye perspective, it is possible but let legible to discern what this filter definition is stipulating than to simply make a DB view where these restrictions could be expressed in the form of simpler WHERE clauses.

Am I missing something? Is there an advantage to using Criteria vs. DB views that I am not aware of?  Using views seems much cleaner.  Is there a performance upside to Criteria?

答:
From the database perspective, you are more likely to be able to write a better performing view.  You may be able to layer views together, where some of the views contain distinct, reusable chunks of business logic.  When approached this modular way you greatly reduce the probability of having outrageous numbers of views.  And this should simplify things in the "thousands" of Java applications using them, reducing development, maintenance, and performance costs on the Java side.

This may work well in some environments where you are dealing with a single DBMS. This also lays the groundwork for use outside you java development group. There might be applications wanting to use other access methods, now or in the future.

Of course some DBMS's may not optimize the layered views approach as well as mine.  YMMV.


问:
Is there a better way of writing unit tests than a series of 'AssertEquals'?
Here's a basic example of what my unit test needs to be, using qunit:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

<link rel="stylesheet" href="qunit/qunit-1.13.0.css">
<script src = "qunit/qunit-1.13.0.js"></script>
<script src = "../js/fuzzQuery.js"></script>

<script>

test("Fuzz Query Basics", function()
        {
            equal(fuzzQuery("name:(John Smith)"), "name:(John~ Smith~)");
            equal(fuzzQuery("name:Jon~0.1"), "name:Jon~0.1");
            equal(fuzzQuery("Jon"), "Jon~");
            //etc

        }
    );

</script>
</head>
<body>
    <div id="qunit"></div>
</body>
</html>
</code>```

Now I was thinking this is a bit repetitive.

Could put all the inputs/outputs into an array, and loop through it.

```<code>test("Fuzz Query Basics", function()
        {
            var equals = [
                           ["name:(John Smith)", "name:(John~ Smith~)"],
                           ["name:Jon~0.1", "name:Jon~0.1"],
                           ["Jon", "Jon~"]
                           ];

            for (var i = 0; i<equals.length; i++)
                {
                    equal(fuzzQuery(equals[i][0]), equals[i][1]);
                }

        }
    );
</code>```

And this works fine.

The single advantage I can think of for this second method, is that if it turns out that you don't actually want to use equal it's easier to make that change in one spot.

In terms of readability, I don't think it's conclusive either way, though I probably prefer the second.

Abstracting it further, you could put the input/output cases into a separate CSV file, which might make it easier to modify.

Question is - what are the general conventions around writing these kinds of unit tests?

Is there a reason you shouldn't put them into arrays?

答:
I like your second approach, but I would add 2 Points

do not use arrays to store tested data, as working with indexes is a not clean way

do not use for loops

`

```<code>[
    {
        process: "name:(John Smith)",
        result: "name:(John~ Smith~)"
    },
    {
        process: "name:Jon~0.1",
        result: "name:Jon~0.1"
    },
    {
        process: "Jon",
        result: "Jon~"
    }
]
.forEach(function(data){

    var result = fuzzQuery(data.process);
    equal(result, data.result);
});
</code>```

I'm not sure about qunit, but a good test runner will show you what input string failed, and what the expected result was

Body:
I like your second approach, but I would add 2 Points

do not use arrays to store tested data, as working with indexes is a not clean way

do not use for loops

`

[
    {
        process: "name:(John Smith)",
        result: "name:(John~ Smith~)"
    },
    {
        process: "name:Jon~0.1",
        result: "name:Jon~0.1"
    },
    {
        process: "Jon",
        result: "Jon~"
    }
]
.forEach(function(data){

    var result = fuzzQuery(data.process);
    equal(result, data.result);
});

I'm not sure about qunit, but a good test runner will show you what input string failed, and what the expected result was


问:
What's the point of Continuous Integration services like Travis CI?
As far as I can tell, services like Travis CI and CircleCI take your project and run its test suite whenever you push a new change to your repository.

Assuming that it's also possible to either manually or automatically run such test suite locally before you commit or push your change, what's the point in using a service like this?

答:
I'm not familar with those services but CI in general is good for

It gets rid of the "Builds on my machine" excuse for comitting bad work.

If it doesn't work in CI it doesn't work.

You can then take the known working code from there and use it for things like Continuous deployment.

Some provide a history so you can tag Version 1.0, 1.1 etc so its easy to go back to them if there is some unforseen problem in the new version or you just need to release the old version.


问:
How to store currency ranges in a Postgres table?
I am using Postgres 9.3.

I have to store range data like <$250K, $250K-$4M, etc which we will display in a dropdown.

now I am making a table for all possible options that can be configured from an admin interface.

Should I take separate column for min,max,currency_type(dollar,euro) and a column to store K,M etc or there is a better way to do that ?

答: Guessing you will be needing ranges for different kinds of dropdowns;


答:
Are you sure everyone will run the tests? E.g. those commits when you're late for the plane - and that change is tiny and really-really can't break anything.

Are you sure you want to run the whole testsuite on your system before every push? Some testsuites run for hours (UI automation) or execute slow tools like valgrind.

Are you sure you will run the testsuite on all supported platforms? E.g. if you do a C++ application on Linux/Mac OS X/Windows it is trivial to break compilation on other platforms if you don't test there. Imagine that sometimes you may even need to test Windows7 and Windows8 separately.

Build/package the whole application may take awhile by itself. CI lets you simply download the package built on the server.

Title: What's the point of Continuous Integration services like Travis CI?

Body:
As far as I can tell, services like Travis CI and CircleCI take your project and run its test suite whenever you push a new change to your repository.

Assuming that it's also possible to either manually or automatically run such test suite locally before you commit or push your change, what's the point in using a service like this?


问:
Data Model for selling groups of products as one product
Say I have an e-commerce with a data model like the following, which allows a Sale to describe how a single Product is sold. This division allows a product to be sold multiple times in different ways (different pricing, or offered at a different point in time). This works great when a sale is selling a single product.

Sale

product_id (sale belongs to product)

other offer details like price, sale expiry date, marketing content, etc

Product

product has many sales

factual product details like name, photo, manufacturers description, etc

The problem: How can this data model be improved to allow a sale to have many products?

For example, to create a bundle of 1 of product A, and 1 of product B. So if a customer wants quantity=3 of those bundles, they would receive a total of 3 A's and 3 B's.

Or a sale could be for multiples of a single product. In this case the sale would be for 5 of product C. So if a customer wants quantity=3 of those bundles, they would receive 15 product C's.

The best idea I have so far is add a new table. This would allow a sale to reference many orderables, which describe what's in the bundle.

Orderables

belongs to product

belongs to sale

qty in the bundle

But a refactoring of this magnitude is a monumental task.  The number times sale.product appears in the codebase for a variety of reasons is enormous.  And every single case need to be fixed in code, and probably presentation as well.

So before we commit too heavily to this approach, I'm wondering if there is a glimmer of hope I've not yet seen, or if my future is fraught with the pain and peril of this epic refactoring.

答:
In the past, what I've seen at companies that do this is one of two approaches:

A "bundle" is a separate product. It's put into the database as its own product, stored in inventory as its own product, and gets removed from inventory and shipped as its own product.  No refactoring required, but ties up product in inventory that could be sold individually, if it was broken out.  It has the virtue of being customizable as a bundle; i.e. the cost can be different than the individual products.

A "bundle" is a "Bill of Materials," culminating in a finished product.  Requires a completely different approach, and much refactoring, but preserves the integrity of individual products on shelves.  There would be lots of duplication, since each individual product still needs its own bill of materials containing one item (itself).

If I were doing it, I would find a way to sell the idea of bundles as "quick-entries."  It works sort of like a GUI macro; you select a bundle from the list of products, and it automatically adds the necessary individual line items (and quantities) to the invoice.  You still need a "bill of materials" to implement it but you don't have to refactor the entire system.


问:
How to line-break an email address?
After some discussion, I have come across a rather complicated situation. Say I intend to display an email address. I have, obviously, limited space available on the screen - be that browser or application UI. Email addresses are, however, limited to 64 + 1 + 255 = 320 characters by RFC5321, while the same RFC also caps the path at 256 (which leads to an actual 254) characters. That's quite a lot for most screens - the lines I'm writing right now contain less than a hundred characters each.

So, that poses a bit of a problem when trying to display email addresses. At this character count, sufficiently large containers would seem huge for a "default-sized" email address (my average is a bit below 30 characters right now), while a smaller container would lead to overflow.

At first the option to use a smaller container but introduce line-breaks on longer addresses seems like a good idea.

Which brings me to the first important question to this: Where do I break? After a set/relative amount of characters?  Before or after the @?

And the second question follows right after: How do I break? Zero-width space? <wbr> in HTML? Insert a dash or not?

There seem to be reasons for and against any of these, but I can't for the life of me find any sources to go off in my decision. It seems as though nobody ever actually dealt with this situation (that is, the physical cap on estate is never exhausted). The best I can find are some online publishing styleguides preferring an email address in one line and adjusting surrounding elements to make that work. Well, we might just not have that option under some circumstances.

答:
How about don't line break at all?

some.really.long.addres@my...

You can use text-overflow:ellipsis; and then something like HTML - how can I show tooltip ONLY when ellipsis is activated?:

```<code>$('.mightOverflow')
    .bind('mouseenter', function () {
    var $this = $(this);

    if (this.offsetWidth < this.scrollWidth && !$this.attr('title'))
        $this.attr('title', $this.text()); });
</code>```

If you're doing a touch/mobile-enabled app, you can also add a handler so when someone clicks it shows the full address in another box (also allowing copy/paste, which is probably a main reason someone would want to get the whole address), and in that, just do a hard wrap  (eg, with word-wrap:break-word;). Since it's just the address being displayed in some kind of overlay container, it would be completely natural to wrap inside that way.

If you think it would beneficial to always see domains, you could always shorten both the address and domain sections independently:

really.lon...@domain.com

another.reall...@long.domai....

You'd have to experiment with the exact code, but having s around both parts, with max-width:50%; text-overflow:ellipsis; is along the lines of what I'm thinking. It would probably require some smarter code to make the best of use of space to display "really.long.address.blah.blah.blah.blah@a.com" (or a short address and long domain) but it could be done.

Title: How to line-break an email address?

Body:
How about don't line break at all?

some.really.long.addres@my...

You can use text-overflow:ellipsis; and then something like HTML - how can I show tooltip ONLY when ellipsis is activated?:

$('.mightOverflow')
    .bind('mouseenter', function () {
    var $this = $(this);

    if (this.offsetWidth < this.scrollWidth && !$this.attr('title'))
        $this.attr('title', $this.text()); });

If you're doing a touch/mobile-enabled app, you can also add a handler so when someone clicks it shows the full address in another box (also allowing copy/paste, which is probably a main reason someone would want to get the whole address), and in that, just do a hard wrap  (eg, with word-wrap:break-word;). Since it's just the address being displayed in some kind of overlay container, it would be completely natural to wrap inside that way.

If you think it would beneficial to always see domains, you could always shorten both the address and domain sections independently:

really.lon...@domain.com

another.reall...@long.domai....

You'd have to experiment with the exact code, but having <span>s around both parts, with max-width:50%; text-overflow:ellipsis; is along the lines of what I'm thinking. It would probably require some smarter code to make the best of use of space to display "really.long.address.blah.blah.blah.blah@a.com" (or a short address and long domain) but it could be done.


问:
What is the aim of software testing?
Having read many books, there is a basic contradiction:

Some say, "the goal of testing is to find bugs" while other say "the goal of the testing is to equalize the quality of the product", meaning that bugs are its by-products.

I would also agree that if testing would be aimed primarily on a bug hunt, who would do the actual verification and actually provide the information that the software is ready?

Even e.g. Kaner changed his original definition of testing goal from bug hunting to quality assessment provision but I still cannot see the clear difference. I perceive both as equally important.

I can verify software by its specification to make sure it works and in that case, bugs found are just by products. But also I perform tests just to break things.

Also what definition is more accurate?

Note above I am primarily referring to software testing as a process.

答:
@David Hammen's answer is very well put, though not exactly what I'd have said. I agree that Verification answers "Did we built this one correctly?". Anything produced by a process can be Verified. Manufacturing involves constant verification that the thing being produced has been produced correctly.

He then defines Validation, which we agree is different, as "Did we build the right thing?" I would say that Validation moves in the opposite direction, to exhaustively confirming precisely correct functioning of a design. More like "Objectively demonstrate that the solution is correctly designed". The right grades of bolts, the right sizes of internal variables. The pieces are up to the job.

David's Validate, "Did we build the right thing?" is a high-level question that isn't something you can run against the daily build, thumbs up or thumbs down. Its a judgement of the requirements and to a lesser extent, the design. Its not a sensible question addressed to a text box on a screen or a parameter in an API. Not sure what the one-word name is for requirement correctness, maybe Requirement Validation. Exhaustively proving that the requirements correspond to the needs of the end user.

By contrast, my definition for Validate is proof of correctness of a design, objective tests that show the pieces selected will do the job. The Ariane IV software that was unsuitable for Ariane V would fail here, because Ariane IV had a limited range of angle-rate changes. The code was optimized for this limited range, and Ariane V was capable of a larger range of angle rates, which caused the overflow. When both onboard computers crashed on overflow, and did it again after auto-reboot, the destruct system was triggered.

As Dykstra said, "Premature optimization is the root of all evil."

In my definitions, the requirements are presumed to be correct and accepted, validated by Requirement testing. Design or Code Validation proves that the design, perhaps a bit of the implementation, is correct. It still has to be executed correctly, but confirming that is Verification, testing based on accepted Requirements and an accepted Design.

You'll note that this hews painfully close to the Waterfall model of development, which seems harmful if believed to describe complex systems. None the less, Requirements are different than Design and Code is a third thing entirely. I guess my plea is that the elements in the Waterfall are useful descriptions, but that 'complete' is misleading, so I've changed it to 'accepted' which suggests contingency and mutability.

Title: What is the aim of software testing?


问:
What is stopping people from copy-pasting open-sourced codes into their own projects and releasing only the compiled binaries?
Hi I'm new to programming, and I've always wondered what would be the point of contributing open-sourced codes if there is no way to ensure everybody who uses the code will adhere to the licenses (or is there?).</p>

答:
For some licenses you are permitted to release closed source binaries. These licenses are known as "permissive". Proponents of these licenses believe that downstream users will contribute back appropriate bug fixes or features because it is a more efficient way of maintaining the code. That is the incentive to share is economic and process driven.

Another category of license (weak copyleft) allows binary distribution as ling as there are no modifications in that code. This is most commonly used for libraries. In this case there is the same economic and process driver but it is backed by a legal requirement to release the source code of modifications.

The final category is copyleft which uses the law to require all source to be released if it includes any copyleft code. The economic and process drivers still exist here but proponents of copyleft (and weak copyleft) tend to believe this is not enough without the law to add teeth to the argument.


答:
One of the most common ways I've seen people break the build is when they're working on several different things at once, and they check in what they think is all the changes needed for one particular task that they have just finished.

Turns out they missed a file, or they checked in a change that was part of a separate task that isn't finished yet.

In cases like this, the tests probably do all run correctly on their machine. But the committed code no longer builds, runs, and passes all tests.

Basically, if the CI tool can get latest from source control, build it, and run the tests, you can be confident that anyone can get latest and get a working codebase.


问:
We use subversion - Should we place comments in my code anyways?
I brought up in a meeting an annoyance that code changes were not commented within the code itself. We use SVN (Subversion) for source control, and it was relayed to me that you can just go into SVN and check the history and see the changes.

My question is is this a best practices? It seems easier to me to place the comment in the code itself with the defect/user story reference (we use Rally/Agile) AND in the svn header when you check in the changes. My bosses seem to think putting it the code is unecessary, and I told them I completely disagreed with that practice. I've always been taught that comments in the code are never bad. This is not my first gig.

I was even more floored when he told me his boss has been known to rip out comments in some code. After I stopped having the shakes, I wanted to... vomit.

What do you think about comments in code vs/with comments in source control and what do you do as a best practice?

答:
I think there is not a general answer. It depends. Extra-commenting the code may bring noise and make it less readable.

Comments in the code like these:

```<code>// 2014/01/17 bob@mymail.com changed this path:
$path="/...";
</code>```

Shouldn't be there. They should be in the version control comment, along with other changes. Also, you should have a ticketing system in which this change is reported. Say you have an issue in your ticketing system numbered 12345. Then, whenever you want to see what was done and why, and who asked for changing this url, etc. you would go to your ticketing system and look for it. Then you would find related issue numbered 12345. Then you should grep subversion history for issue 12345 (good practice to add related issue number in your commit comment), etc.

But, comments like these:

```<code>// path must be retrieved from file_helper broker, as it crashes otherwise because...
$path=file_helper::get_path(...)
</code>```

Are very useful and they are worth to be there forever.

OwnerDisplayName: Mark Goodwin

Body:
I think there is not a general answer. It depends. Extra-commenting the code may bring noise and make it less readable.

Comments in the code like these:

// 2014/01/17 bob@mymail.com changed this path:
$path="/...";

Shouldn't be there. They should be in the version control comment, along with other changes. Also, you should have a ticketing system in which this change is reported. Say you have an issue in your ticketing system numbered 12345. Then, whenever you want to see what was done and why, and who asked for changing this url, etc. you would go to your ticketing system and look for it. Then you would find related issue numbered 12345. Then you should grep subversion history for issue 12345 (good practice to add related issue number in your commit comment), etc.

But, comments like these:

// path must be retrieved from file_helper broker, as it crashes otherwise because...
$path=file_helper::get_path(...)

Are very useful and they are worth to be there forever.

OwnerDisplayName: Alex Jurado - Bitendian


答:
Absolutely! They serve two completely different purposes.

Your commit messages are only describing why you're committing that particular changeset - customer request, fixing a particular bugs, etc. These would be where you log your user story references or bug references:

Revised method XYZ to cover additional use case highlighted by user story ABC.

Fixing bug 1234 which was caused by an off-by-one error in main loop

Comments in your code should describe why your code is written the way it is, or descriptive comments about the methods & variables (like headers to be processed by JavaDoc). See the example given at the end of the earlier answer.

The two concepts are independent. If you lose your source control, or migrate the code to a new VCS without retaining history, you've now lost all your documentation if you follow what your bosses suggest. And if you're trying to debug a system in production with no comments in the code, you're constantly flipping between reading hundreds of commits worth of SVN logs while trying to interpret the code & figure out what goes where.

The prospect of cramming the comments of hundreds of lines of code (which should be inlined with the code) into a single commit message is frightening.

Title: We use subversion - Should we place comments in my code anyways?

Body:
I brought up in a meeting an annoyance that code changes were not commented within the code itself. We use SVN (Subversion) for source control, and it was relayed to me that you can just go into SVN and check the history and see the changes.

My question is is this a best practices? It seems easier to me to place the comment in the code itself with the defect/user story reference (we use Rally/Agile) AND in the svn header when you check in the changes. My bosses seem to think putting it the code is unecessary, and I told them I completely disagreed with that practice. I've always been taught that comments in the code are never bad. This is not my first gig.

I was even more floored when he told me his boss has been known to rip out comments in some code. After I stopped having the shakes, I wanted to... vomit.

What do you think about comments in code vs/with comments in source control and what do you do as a best practice?

OwnerDisplayName: alroc


问:
Does it make sense to write tests for legacy code when there is no time for a complete refactoring?
I usually try to follow the advice of the book Working Effectively with Legacy Code. I break dependencies, move parts of the code to @VisibleForTesting public static methods and to new classes to make the code (or at least some part of it) testable. And I write tests to make sure that I don't break anything when I'm modifying or adding new functions.

A colleague says that I shouldn't do this. His reasoning:

The original code might not work properly in the first place. And writing tests for it makes future fixes and modifications harder since devs have to understand and modify the tests too.

If it's GUI code with some logic (~12 lines, 2-3 if/else block, for example), a test isn't worth the trouble since the code is too trivial to begin with.

Similar bad patterns could exist in other parts of the codebase, too (which I haven't seen yet, I'm rather new); it will be easier to clean them all up in one big refactoring. Extracting out logic could undermine this future possibility.

Should I avoid extracting out testable parts and writing tests if we don't have time for complete refactoring? Is there any disadvantage to this that I should consider?

答:
Do the automated test coverage.

Beware wishful thinking, both your own and by your customers and bosses.  Much as I would love to believe that my changes will be correct the first time and I'll only have to test once, I've learned to treat that kind of thinking the same way I treat Nigerian scam emails.  Well, mostly; I've never gone for a scam email but recently (when yelled at) I gave in on not using best practices.  It was a painful experience that dragged (expensively) on and on.  Never again!

I have a favorite quote from the Freefall web comic:  "Have you ever worked in a complex field where the supervisor has only a rough idea of the technical details? ...  Then you know the surest way to cause your supervisor to fail is to follow his every order without question."

It's probably appropriate to limit the amount of time you invest.


问:
Model and ViewModel for View
I am new to the MVVM pattern. I have a window which has 3 text boxes (Name, Address, Description), a save button, and a listview which displays the above fields. When the save button is clicked I want to save the fields into database as well as show the record in the listview.

How do I design my Model, ViewModel for this interface ?

答:
This is how we are implementing MVVM in my company, and naturally also the way I would prefer:

The model should reflect what you need to present on the View, and your database should also adapt to this. This means that your model(and your DB) should contain fields for Name, Address and Description.

I prefer to pass a Model to my ViewModel. Some people would argue that this is wrong according to the MVVM pattern, but it ensures that your model is preserved in the right form, from the View and all the way down to your DAL layer.

So, your ViewModel contains a Model, which has some properties you could bind to. When you hi the Save button, the ViewModel intercepts the command specified, and parses the Model to the Bll layer. The Bll layer uses the DAL layer to persist the Model in the database. You could also make some checks in the Bll layer to ensure you don't make dulicates. You might want to override an existing entry instead of creating a new one.

Edit:
Just a quick example:

Title: Model and ViewModel for View


答:
This is how I see (and do) it.

In your case (which is rather simple), I would have a ViewModel holding a list of Models and a SelectedModel property. The view would have a form and a list of course. The form would be bound to the currently selected model. The View would be bound to the ViewModel and indirectly to the Model (the data in the list and the form). Your ViewModel would also take care of validating and saving the data to the database by calling a method on your repository (or the Context, which is basically a repository, if you're using EF).

The Model is your business logic, the Domain Model. The objects here will have all the data relevant to the business and the methods to manipulate that data. The model should be designed to be as simple as possible while accomplishing the business needs. This means normalized relationships, decoupled design and so on. Make it as easy to maintain as possible, regardless of the view. This means the same Model can be reused in different applications (a desktop and a web app can use the same model). In your case this is an object with the Name, Address and Description. This is all you need to accomplish your goal.

The View will not always be this simple. Sometimes you will need to aggregate data from multiple models, or do some other manipulation of the data just to show the data on a view. A report for instance, can have lots of data from lots of models. Other times, the view will really need to simplify a lot of complex things that are going on in the model, to give you a high level overview without too many details. In your case, the view is also a bit more complex than your domain model. You need a list to see all your domain models and a form to edit one at the same time.

This is where the ViewModel comes in. The VM will be between the model and the view. It will wrap a model object (or multiple model objects), introduce new properties that are a combination of other properties in the model and so on. The ViewModel is the one that is designed in a way that it makes presentation easier. This means simple properties your view can bind to and similar things. No matter how complex your Model or your View is, your ViewModel sits in between and makes all the necessary transformations of the data that you want to display. The same thing but in reverse happens when a view is sending data back (form submission or other input). The ViewModel is the one that transforms the view data into something that your Model understands. In your case the ViewModel will be rather simple, holding just the list of Models and a Selected Model, but in more complex examples, it might do some calculations or whatnot to accomplish what the view needs.

Title: Model and ViewModel for View

Body:
I am new to the MVVM pattern. I have a window which has 3 text boxes (Name, Address, Description), a save button, and a listview which displays the above fields. When the save button is clicked I want to save the fields into database as well as show the record in the listview.

How do I design my Model, ViewModel for this interface ?


问:
What is Component Oriented Programming, and how is it different from OOP?
What exactly is Component Oriented Programming, and how is it different from Object Oriented Programming?

Thanks

答:
Whilst the OOP approach focuses on the relationship between classes, COP focuses more on interchangeable modules that work independently and don't require the need to know exactly how they work.

Edit - I don't think this is unclear, the question addresses the difference in approach, they are not entirely separate. In COP, a module can be considered a reusable, function-driven object (often a group of classes) that can be used and reused as is. OOP is more granular, focusing on the individual classes themselves which, likely require specific interaction with other classes to perform functionally.


问:
Does this justify goto statements?
I came across this question a second ago, and I'm pulling some of the material off of there: Is there a name for the 'break n' construct?

This appears to be a needlessly complex way for people to have to instruct the program to break out of a double-nested for loop:

```<code>for (i = 0; i < 10; i++) {
    bool broken = false;
    for (j = 10; j > 0; j--) {
        if (j == i) {
            broken = true;
            break;
        }
    }
    if (broken)
        break;
}
</code>```

I know textbooks like to say goto statements are the devil, and I'm not fond of them at all myself, but does this justify an exception to the rule?

I'm looking for answers that deal with n-nested for loops.

NOTE: Whether you answer yes, no, or somewhere in between, completely close-minded answers are not welcome.  Especially if the answer is no, then provide a good, legitimate reason why (which is not too far from Stack Exchange regulations anyway).

答:
TLD;DR: No in specific, yes in general

For the specific example you used I would say no for the same reasons many other have pointed out.  You can easily refactor the code into an equivalently good form which eliminates the need for the goto.

In general the proscription against goto is a generality based on the understood nature of goto and the cost of using it.  Part of software engineering is making implementation decisions.  Justification of those decisions occurs by weighing the cost against the benefits and whenever the benefits outweigh the cost the implementation is justified.  Controversy arises because of different valuations, both of cost and benefit.

The point is there will always be exceptions where a goto is justified, but only for some because of different valuations.  The pity is many engineers simply exclude techniques in purposeful ignorance because they read it on the internet rather than taking the time to understand why.

Title: Does this justify goto statements?


答:
In my experience a characterisation test of some sort works well. It gives you a broad but not very specific test coverage relatively quickly, but can be tricky to implement for GUI applications.

I would then write unit tests for parts that you want to change and do so every time you want to make a change thereby increasing your unit test coverage over time.

This approach gives you a good idea if changes are affecting other parts of the system and let's you get into a position to make any required changes sooner.

Title: Does it make sense to write tests for legacy code when there is no time for a complete refactoring?

Body:
I usually try to follow the advice of the book Working Effectively with Legacy Code. I break dependencies, move parts of the code to @VisibleForTesting public static methods and to new classes to make the code (or at least some part of it) testable. And I write tests to make sure that I don't break anything when I'm modifying or adding new functions.

A colleague says that I shouldn't do this. His reasoning:

The original code might not work properly in the first place. And writing tests for it makes future fixes and modifications harder since devs have to understand and modify the tests too.

If it's GUI code with some logic (~12 lines, 2-3 if/else block, for example), a test isn't worth the trouble since the code is too trivial to begin with.

Similar bad patterns could exist in other parts of the codebase, too (which I haven't seen yet, I'm rather new); it will be easier to clean them all up in one big refactoring. Extracting out logic could undermine this future possibility.

Should I avoid extracting out testable parts and writing tests if we don't have time for complete refactoring? Is there any disadvantage to this that I should consider?


问:
Are (mostly) client-side JavaScript web apps slower or less efficient?
I am in the midst of writing a web application for work.  Everything is from scratch.  I have been a PHP programmer for about 13 years, Node.js programmer for the past 2 years, and have no shortage of experience with JavaScript.  I love Node.js, and recently rebuilt the company's API in it...

So, in planning this web application, the approach I'm considering is, have the Node.js API for getting data from the server, but render everything in the browser.  Use AJAX for retrieving data, History API for loading pages, and a MVC-like pattern for the different components.

I have read articles detailing twitters rebuild a few years ago.  It was more or less a client-side JavaScript app, but a couple years after launching it, they started moving a lot of processing/rendering back to the server, claiming the app improved dramatically in terms of speed.

So, my question is as the title asks, is a client-side centric app substantially slower?

答:
The answer is that it's entirely situational.

The intricacy and scale of user interaction, customer experience, the functionality of the application, server load, security concerns and other factors have to be taken into consideration in order to address this question with any degree of accuracy.

To be honest this question should not be answered in generalised terms - there is no wrong answer. If you can provide more details of the nature of the application, we might be able to give some useful advice.


答:
A client centric application tends to generate a lot more network traffic than a server centric application that sends just the end result of the processing to the client.

This client centric application will often make more network calls, each involving more data, than the server centric application.

As network latency is by now often the largest performance bottleneck for applications, that often leads to slower client side performance.

Another thing to consider is security. Pretty much every bit of validation you do on the client will need to be repeated on the server. If not you get the infamous situation where a customer fills his shopping cart on the client, edits the amount to be paid to be negative, then submits the whole thing and the server, blissfuly unaware anything is amiss pays the client AND sends him the products.

This may or may not be an issue for your system, depending on what it does and how it is intended to be secured.

Overall then, you're better off limiting the amount of data being transmitted between client and server both in volume and possibly number of requests (a high number of small requests might make for a seemingly faster user interface, think partial page submits, despite being technically slower in total CPU time needed).

Title: Are (mostly) client-side JavaScript web apps slower or less efficient?

Body:
I am in the midst of writing a web application for work.  Everything is from scratch.  I have been a PHP programmer for about 13 years, Node.js programmer for the past 2 years, and have no shortage of experience with JavaScript.  I love Node.js, and recently rebuilt the company's API in it...

So, in planning this web application, the approach I'm considering is, have the Node.js API for getting data from the server, but render everything in the browser.  Use AJAX for retrieving data, History API for loading pages, and a MVC-like pattern for the different components.

I have read articles detailing twitters rebuild a few years ago.  It was more or less a client-side JavaScript app, but a couple years after launching it, they started moving a lot of processing/rendering back to the server, claiming the app improved dramatically in terms of speed.

So, my question is as the title asks, is a client-side centric app substantially slower?


问:
Is there a compliance test for C++ compilers?
Is there, somewhere, a freely usable/accessible script, source file, or whatever, that is able to measure the compliance of a given C++ compiler?

For example, the Acid3 test for browsers: http://acid3.acidtests.org/

The results I dream of would be a global percentage note (or multiple notes, one for each standard, e.g. , c++98, c++11, c++14, etc.), and then detailed tests with "success" or "failure" for each of them.

Background: I had a discussion at work about boost and some challenged compilers. My interlocutor spoke about boost being an academic project, because it won't work in major C++ compilers, and me answering that mentally challenged compilers should not count. Being able to measure with code the actual conformance of a compiler would help both in evaluating the compiler, and discovering the "corner cases" that should be avoided in cross-platform code compiled with them.

Edit: 2013-06-22

Not an answer, but apparently, the C++ committee is working on the subject:

SG10, Feature Test: Clark Nelson (Intel). Investigation into whether and how to standardize a way for portable code to check whether a particular C++ product implements a feature yet, as we continue to extend the standard.

Source: http://isocpp.org/std/the-committee

答:
One way to test compliance of a given C++ compiler is to run a (large) testsuite, i.e. a bunch of C++ files that test all aspects of the language.

Well known testsuites are the gcc and llvm testsuites. These test all kinds of aspects of the compiler, obviously including conformance. However it is hard to particularly assess conformance specifically as (to the best of my knowledge) there are no special reports generated on conformance.

In this realm you have:

the GCC C-torture tests used to test the gcc compiler

the LLVM testsuite: a mix of directed tests for the clang compiler and llvm backend plus a set of full-fledged applications to test the compiler.

the LLVM libcxx test (part of the libcxx repository) to test C++11 support.

There are some extensive testsuites that to test C/C++ conformance available. Alas these are all commercial licenses in the order of 10k-40k.

SuperTest: The most extensive of this list. Roughly 3 million directed tests towards C99, C++, EmbeddedC, DSP-C conformance.

Plum Hall. C and C++, including the C++ library. Includes ANSI C conformance, random program generator, test templating, and a scripting interpretor to control the overall testing process.

Perennial. C and C++.

Nullstone. C only.


问:
How to combine Google Analytics with Relational Database
I have a website with quite a lot of registered users, they are stored in a PostgreSQL database. I also running Google Analytics on the website to track the users. Is there a way to individually combine the GA data with the registration data from the website, e.g. finding out the e-mail address of a user we found in GA?

Also, is there a way for non-technical people to access the SQL database without knowing SQL?

Thanks!

答:
Is there a way to individually combine the GA data with the registration data from the website, e.g. finding out the e-mail address of a user we found in GA?

Yes, there is a way. You can set custom variables to your visitors: Custom Variables @ GA docs

So, for example, if you want to identify your logged-in visitors by their emails, you should programmatically add this JS on the page (e.g. when the user logs in):

```<code>_gaq.push(['_setCustomVar',
     1,                   // Slot #1
     'email',             // Variable name
     'email@example.com', // Variable value
     1                    // Scope = visitor-level, optional
]);
</code>```

It doesn't matter which type of DB engine you use, GA doesn't work with it directly anyway.

is there a way for non-technical people to access the SQL database without knowing SQL?

You can provide them a user interface which they can understand and work with.

Body:
Is there a way to individually combine the GA data with the registration data from the website, e.g. finding out the e-mail address of a user we found in GA?

Yes, there is a way. You can set custom variables to your visitors: Custom Variables @ GA docs

So, for example, if you want to identify your logged-in visitors by their emails, you should programmatically add this JS on the page (e.g. when the user logs in):

_gaq.push(['_setCustomVar',
     1,                   // Slot #1
     'email',             // Variable name
     'email@example.com', // Variable value
     1                    // Scope = visitor-level, optional
]);

It doesn't matter which type of DB engine you use, GA doesn't work with it directly anyway.

is there a way for non-technical people to access the SQL database without knowing SQL?

You can provide them a user interface which they can understand and work with.


答:
I'd call Component Oriented Programming a specialized descendant of Object-Oriented Programming, in that the goal is to produce easily-reusable generic objects.

In the late 1990s, I attended an Open House at the UT Austin Department of Computer Science.  My goal was to talk to an old friend, a professor, to get some insight into a problem I'd encountered at work.  (He gave me the exact pointer I needed, and also suggested I talk with another old friend, who also gave me very good help.)  While I was there, I talked with some other people, one of them being Don Batory, who was working on building program generators that made it easy to construct and compose (fit together) component objects.

His comment was that object-oriented programming was not enough.  It gave you objects with defined interfaces, but they weren't necessarily cleanly reusable.  It takes an extra level of design effort to keep extraneous concerns from creeping into the object.  Dr. Batory had come into this from the database world, trying to make it easier to build database systems.  At one point, he'd heard about guys working a somewhat similar problem in operating systems construction, and was shocked to discover that the solution they were working was darned near identical to what he was doing, indicating that there was an underlying body of reusable knowledge.

Real Example: On a project I worked in the mid-1990s, there was a "business rule" that the laser rangefinder should not be fired unless the tracker was locked on a target.  The object-oriented method allows passing the lock status into the rangefinder object, as a final interlock on the firing command.  The component model says that the rangefinder object exports a Fire() method, and the business logic that uses the rangefinder checks the target lock status before pulling the trigger.

Title: What is Component Oriented Programming, and how is it different from OOP?

Body:
What exactly is Component Oriented Programming, and how is it different from Object Oriented Programming?

Thanks


问:
Data Access Layer for application
I am working on a retail application where currently I'm using raw SQL like

```<code>insert into some_table values (Textbox1.Text, Textbox2.Text, ...)
</code>```

and

```<code>update some_table set some_column = value
</code>```

for save and update, but the problem is I need to write this everywhere that a save or update is needed.

Is there a better solution for handling CRUD operations, like a separate class to contain data access logic which would use methods in the data access layer to perform CRUD operations?

答:
Generally speaking, you are supposed to bottleneck where your actual CRUD operations are contained and use one interface to deal with it.  Since this is the sort of thing that tends to change often as you need to develop more CRUD operations, you risk that you'd have to change each and every call to a method that you've changed or at the least, rethink how it gets called in the context of how you've changed it.

If you're talking about a small project, this is not such a big deal, however in larger projects, this gets very tedious very quickly and thus good structure becomes paramount.  What I recommend you do is make an object representative of the operations you're performing on the database.  In other words, if I have CRUD operations for writing "Student" table, then you create class Student which handles the actual CRUD calls.  At that point, to update information pertaining to Student, you'd only have to, say, implement a method "Save" which updates the database using the information it currently contains.

At this point, you no longer have to worry about providing a Database connection, session, whether or not it should insert or update.  Callers merely have to call "Save" and your class worries about that sort of logic.  You'll find that not only does this simplify your code, but it allows you to wall off logic pertaining to the database from the rest of your program, thus keeping it cleaner in general.

Title: Data Access Layer for application


答:
I think the way you are phrasing the question mixes together two different things: why you would contribute to an open source project and how an open source license can be enforced when binaries are distributed.  The point of contributing to an open source project is to contribute to the project and people do it for all kinds of reasons. The second question is the more interesting one.

There are a lot of different open source licenses and some, most importantly the GPL, forbid incorporation into proprietary (closed source) software that is distributed and comes with a set of rules to be followed if the code is redistributed (you could have something where GPL code is part of what is distributed but it is not actually incorporated into the proprietary application.). So how is the GPL enforced in general? Even for code that is in PHP or Javascript that doesn't go out in binaries you can still ask the question. The way it gets enforced is that there might be a whistle blower internally, a customer may report suspicions, or the author of the code may become aware of the other code and be suspicious about it for some reasons. (@Simon-barker pointed out some of the ways you can investigate suspicious code.) In other words, it is just like any other kind of wrong doing, probably there are a lot of unreported incidents but some instances are discovered.

At that point different things may happen. Most larger projects have actual teams or individual people who take on the job of investigating licensing issues or an individual developer may have to just manage this herself. Usually the way the process would work is just like with any other civil legal issue. First there is a lawyer-approved or drafted letter sent to the authors of the suspicious code from the author or project.  Then there is a lawyer-approved letter that  responds. That can resolve the whole thing sometimes. For example, maybe they say "We clean room reverse engineered your code and here is  our documentation of that." or "No, our code actually does something different or has a different signature" or "It has come to our attention that, unknown to us, a contractor has used code that is similar to yours. Our company would never knowingly use code contrary to its license, and this was specified in the contract. We have removed it and released an update to all customers, and that contractor no longer works with us."  Then the original developer and the lawyer decide how to respond. And so on. In rare cases they may proceed to an actual court filing and have a discovery phase. In a discovery phase a judge may require that the source code be shared.

A lot of times with GPL violations the violation is failure to notify customers that they have a right to a copy of the code, adding an inappropriate EULA, failure to include a copy of the license, or distributing outdated versions when customers ask for the copies.

Many permissive open source licenses require that the original licensing information be included with the code, so it is not just GPL that has these kinds of issues.

Title: What is stopping people from copy-pasting open-sourced codes into their own projects and releasing only the compiled binaries?

Body: Hi I'm new to programming, and I've always wondered what would be the point of contributing open-sourced codes if there is no way to ensure everybody who uses the code will adhere to the licenses (or is there?).</p>


问:
Is it ever justifiable to write code without tests when doing TDD?
Is it ever justifiable to write production-code without also writing tests for it when doing Test Driven Development?</p>

答:
Strict TDD? Absolutely not. How can you write a test, make it fail, make it pass, without writing a test?

In the real world, very few people do strict TDD. It's an ideal that shouldn't be allowed to get in the way of common sense. Every rule has a scenario where it's justifiable to break it, and that's fine. But we shouldn't lie to ourselves or others and claim we do TDD when we don't. If for no other reason than it gives a bad impression of TDD, when it fails to achieve its goals.

(Replace TDD with any other process and the point stands.)

Also, the most common justification for not doing TDD is time. And that's very rarely a good reason.

If a change isn't complex, it shouldn't take long to write the test. If it is complex then you're inviting issues down the line by not writing tests first, so the time isn't often truly saved.

But, perhaps there is a justification even for that. Perhaps it's better to get something imperfect into the market and then fix it.

Without knowing the justification being disputed, it's hard to know whether it's valid. But I will reiterate that most rules can be broken, with good justification. As long as we're honest with ourselves about it and acknowledge when it turns out to be a mistake.


答:
If you're doing server-side rendering to HTML, your architecture looks like this:

User requests URL, server generates HTML for complete page

Browser renders HTML, page is shown, javascript is initialized

Javascript adds event handlers, page is interactive

If you're doing client-side rendering, your architecture looks like this:

User requests URL, server generates HTML for container page

Browser renders empty container ("loading..."), javascript is initialized

Javascript performs routing, derives what page the user must see, launches ajax request for content

The content is returned, the javascript handler renders it and inserts it into the page

Javascript adds event handlers, page is interactive

You can shortcut things a bit by inserting the initial data into the page, but the reality is that with client-side rendering the page is always rendered twice, once for the container to bootstrap an environment, and once in your javascript templating code for the actual content, which is one more time than in a server-side rendering architecture.

That means that if you have a situation where users are likely to request a page and then walk away after reading it, like with twitter, they are ill served by client-side rendering, because the performance is always inferior to server-side rendering (provided you optimize both in the same ways where possible).

However, if your users are expected to stay on the page, loading more data piece by piece and having a rich interaction with that data, like a typical web app, then client-side rendering can be a better architecture for delivering the same set of features faster. It is often easier to implement the rendering / event handling logic if it is all in the same client-side codebase, and there is no big performance downside.


问:
What to do when your company doesn't encrypt passwords
Background

I'm been contracted to help a company maintain their server. I work on some minor PHP projects but also look over performance issues and recently, scan logs for hackers.

These guys have been running their server for some time and have what I would call a legacy application on its last legs. It uses magic quotes, global variables (which allows $id to be overwritten by $_GET['id']), use .htaccess as their only security in some instances, you name it. A security and programming nightmare.

We have been hacked in the past, mostly with SQL injections, which would run SLEEP(99999999) commands and act as a DOS-attack. Luckily they didn't run "little bobby tables",

XKCD: http://xkcd.com/327/

So I re-wrote their vulnerable SQL statements from mysql_query() (not mysqli) to PDO transactions. I'm also analyzing the queries for SLEEP and UNION, which we don't use but the injections have. So far, so good.

Latest Issue

Recently we've been told records are changing in the DB for users, such as their e-mail addresses to ones presumably made by spammers.

I noticed their columns didn't have a last_modified column, so we weren't able to even know when they were being changed, let alone by who. I added that column, but that's barely a first step.

When I was looking in to this table, I noticed the passwords weren't salted nor even hashed, just saved as plaintext.

Client Communication

How can I approach them about the entire situation, as a contractor, without flailing my arms like a madman? Any advice? I was thinking a calm approach of,

```
    ISSUE #1
        Synopsis
        Why this is an issue
        What can happen if this is not fixed
        Suggested fix

    ISSUE #2
        Synopsis
        Why this is an issue
        What can happen if this is not fixed
        Suggested fix
        ```

答:
If as you say you've been contracted to maintain their server, surely this contract must include in the job description tasks such as ensuring the integrity, security and availability of the operating system, applications software and all data etc?! If there is even a vague hint that the contract expects (and holds you responsible) for making sure the server is secure then I wouldn't waste time putting business cases together and just do a good job of making sure the issues are rectified (taking a backup before and after, keeping a version history of your code changes).

I wouldn't expect a change like this to take more than a morning's worth of work and if they ask what you've spent your time working on then you can keep a journal to explain and justify your actions. Provided you are working within the scope of your contract there should be no issues here. Sometimes going all security crazy in front of decision makers causes panic or in the worst case creates an opportunity for them to say they don't care about those issues so don't fix it, meanwhile you contract still holds you responsible in the event of a breach! Perhaps this isn't always the most business-friendly approach but my professional ethics would not allow me to leave unencrypted passwords in any system I've ever been responsible for having had it come to my attention.

From personal experience I tend to find whenever I start working for a new employer or client, discussing scenarios and expectations upfront can save a lot of stress on your part, for example: if I find any security problems that I can fix are you happy for me to go ahead and complete this work without coming to you every time, only notifying you of suspected breaches/incidents? They will almost always say yes to this because from their point of view they're not interested in worrying about security or computer stuff - that's why they've hired you! Perhaps this doesn't answer the question in the way you were expecting but I hope it gives food for thought. Wish you all the best and hope the issue gets rectified!

OwnerDisplayName: bafromca


答:
Open source does not necessarily mean that the code can't be taken into closed source. There are two kinds of schools of thoughts on this: Some licenses like the BSD and MIT license family allow that given some attribution is being made. And this is used - Microsoft for instance used BSD's TCP/IP stack for a long time in Windows (Win 95 till XP, I think). The reasons there are that people think it is great that their code runs in so many places and are happy to make the world better. It allows helps to ensure that TP/IP implementations of different systems are compatible. Part of the thought there is that even if some closed source product includes this code the open version will be more attractive. In this side creators and users are quite equal and have both quite somefreedom in usin the code.

The other school of thought is around the Free Software Foundation's GPL license. Here the thought is that ensuring "freedom" of the software is more important than ubiquitous availability. The freedom here is that the code will always be available to everybody and thus the user can always fix bugs and continue using it even if the vendor goes down.

Now in both cases taking the code into other software can be illegal (with BSD missing attribution etc, with GPL not making the software GPL etc.). This might go unseen often but binary analysis or even test of functionality can prove that the code was included and legal action can be taken. http://www.gpl-violations.org/ documents cases where this was the case and provides legal assistance.


问:
Good idea to put bug numbers in a comment in the beginning of the source file?
Is it a good practice to put bug numbers in the file itself inside a header comment?

The comments would look something like this:

```<code> MODIFIED    (MM/DD/YY)
 abc 01/21/14 - Bug 17452317 - npe in drill across in dashboard edit mode

 cde 01/17/14 - Bug 2314558  - some other error description
</code>```

It seems helpful, but is it considered bad practice?

答:
I know Git doesn't do this and the simple answer is "why on earth would it go there?"

It's a less modular design in general. Under this solution, now files are some mix between content and meta-data. Amazon S3 is another example of a service for storing files that doesn't add YAML front-matter or the like to files.

Any consumer of a file is required to process it through the version control system first. This is tight coupling, e.g. your favorite IDE will break if it does not support your VCS.


答:
It is, IMHO, a very bad idea. After revision number 100, you will have 90% comments and 10% code. I would not consider that as clean and readable.

The only point in this I see is when you have to interchange your code between SCCs and, for whatever reason, you cannot transfer the history between the two systems (but even when you save the history comments that way, you will loose the diff history as well, so saving the comments will only help you a little).

Title: Good idea to put bug numbers in a comment in the beginning of the source file?

Body:
Is it a good practice to put bug numbers in the file itself inside a header comment?

The comments would look something like this:

```<code> MODIFIED    (MM/DD/YY)
 abc 01/21/14 - Bug 17452317 - npe in drill across in dashboard edit mode

 cde 01/17/14 - Bug 2314558  - some other error description
</code>```

It seems helpful, but is it considered bad practice?


答:
It is an altogether horrible practice. It adds effort in order to achieve an effect that is pure duplication; in other words, the only thing that it adds over just using commit logs is the possibility of creating inconsistency. Your source files become cluttered with unlimited amounts of stuff that you never look at.

The only upside I can discern at all is that you could reconstruct the source history without access to the version control, e.g. when studying a printout. But very few people are competent enough to follow the intricacies of software development, while simultaneously unable to understand version control.


答:
I've seen this done before, both manually by authors and automatically by scripts and triggers integrated with version control systems to add author, check-in comment, and date information to the file.

I think both methods are pretty terrible for two primary reasons. First, it adds clutter and noise to the file, especially as these comments age and become irrelevant to the current state of the file. Second, it's duplicate information from what's already maintained in the version control system, and if you are using a modern version control system that supports change-sets, then it's actually losing information about changes.

If anything, consider integration with your defect tracking system. Some tools allow you to link a defect or task ID number in a check-in comment to an item in the tracking tool. If you have all of your defects, enhancement requests, and work tasks in the tool, you can provide linkage that way. Of course, this comes with the downside of a dependency on those tools for the project.


答:
No.

That's what people did before they used a version control system (i.e. when source code was just backups in zipfiles).


答:
Depending on your definition of "also writing tests", it may be acceptable :

At the Refactor step. Refactoring doesn't require writing new tests (but does imply a test suite already in place)

When you make adjustments in purely cosmetic UI code or other non directly testable code.

Also, I won't write tests when I set up a preliminary quick and dirty 10- lines of code prototype to prove some technical detail is working. Here, TDD's feedback loop is slightly too long for what I want. But I guess that doesn't count as being inside of a normal TDD process. And I do delete this code and start a regular TDD cycle after.

Title: Is it ever justifiable to write code without tests when doing TDD?

Body: Is it ever justifiable to write production-code without also writing tests for it when doing Test Driven Development?</p>


答:
There is exactly one case where I would do this, namely as part of a warning for future programmers: "Don't call function foo() here directly; this has caused bug #1234, namely ...", and then a short description of the bug follows.

And if the code has changed in a way that there is no temptation to call foo() directly, remove that comment. It would only irritate and blow up the code.


答:
One of the points in the Joel test is

Do you have a bug database?

Such information might be kept in a bug database if you think they're important, but they would only be noise in comments.


问:
Difference between a pointer and a reference?
In Java and other high-level languages, a reference leads to an object.

In C++, as far as I know, a pointer can also lead to an object.

So what's the difference between a reference leading to an object, and a pointer leading to an object?

答:
In my humble opinion it's almost just a conceptual difference.

With pointers you handle the direct memory address. You can even make some operations, like iterate over it! It's clearly a low level stuff. When you fulfill a pointer, you need a memory address. One like (very similar) the processor itself would receive. So, by definitions:

```<code>Pointers are variables who points to direct memory addresses.
</code>```

Well, so I've been told in college! :D

With references, on the other hand, the "language" make all the hard work for you! When you reference anything in a high-level language you don't pass directly a memory address to the variable. You pass it, but as a reference, to a variable that you don't have to concern about being a pointer, reference, a int or what the hell you though that it'd be! (That part my vary between languages)

Pratically:  Same goddamm thing!

Conceptualy: The references are a masked way to treat pointers.

Body:
In my humble opinion it's almost just a conceptual difference.

With pointers you handle the direct memory address. You can even make some operations, like iterate over it! It's clearly a low level stuff. When you fulfill a pointer, you need a memory address. One like (very similar) the processor itself would receive. So, by definitions:

Pointers are variables who points to direct memory addresses.

Well, so I've been told in college! :D

With references, on the other hand, the "language" make all the hard work for you! When you reference anything in a high-level language you don't pass directly a memory address to the variable. You pass it, but as a reference, to a variable that you don't have to concern about being a pointer, reference, a int or what the hell you though that it'd be! (That part my vary between languages)

Pratically:  Same goddamm thing!

Conceptualy: The references are a masked way to treat pointers.


问:
ANSI C pointers corrupted values
I am working on ANSI C and having some issues with the pointers.

That is that after a point in my program the pointer's values change without me interfering, is something like overwriting them.

I know that this could happen in C, but while being a beginner, can not find a remedy for that.

Is there a straightforward way of solving this? As I understand, many people will have faced similar issues.

Thank you guys for your answers,were very helpful,was indeed a memory problem solved by just allocating larger blocks of memory!!!
Thank you again!!!!

答:
The single-most common pointer bug among beginners seems to trying to store a value into a pointer which is not pointing at a valid memory location.

Typical example:

```<code>char* ptr;  // initialized pointer, could point anywhere
*ptr = something; // bug, the program tries to write to "anywhere"
</code>```

Almost all beginner bugs are different flavours of the above.

The good news is that such bugs are quite easy to track down. Simply single-step with a debugger until the program crashes. The line where it crashed is most likely the incorrect one.

Title: ANSI C pointers corrupted values

Body:
The single-most common pointer bug among beginners seems to trying to store a value into a pointer which is not pointing at a valid memory location.

Typical example:

char* ptr;  // initialized pointer, could point anywhere
*ptr = something; // bug, the program tries to write to "anywhere"

Almost all beginner bugs are different flavours of the above.

The good news is that such bugs are quite easy to track down. Simply single-step with a debugger until the program crashes. The line where it crashed is most likely the incorrect one.


答:
I think you have two problems here. First, why should you purely rely on the diff when most systems allow you to enter revision comments? Like good code comments, you discover why the change was made and not just the change itself.

Second, if you have this capability, make it a good practice to put all of them in the same place. There isn't any need to look through the file for marked out lines of code that are no longer needed. Comments inside working code are there to tell you why it is coded this way.

Once you put this into practice, the habits formed make the code base easier to work on for everyone.

Associated bug and feature tracking along with why you're changing this file, can give you an idea about how deep you need to dig into the history and possibly looking at the diffs. I had a request to "Change back to the original formula." I knew right where to go within the revision history and only reviewed one or two diffs.

Personally, remarked out code looks like a work in progress for a problem that is being solved by trial and error. Get this mess out of production code. Being able to easily slip lines of code in and out only makes it easier to be confused.


答:
They are very similar; they both do pointing to object instances in memory, but how the language lets you manipulate them is different.

In Java, a reference points to an instance of object in memory. You can reassign this reference so that it points to a different instance in memory at any time:

```<code>SomeObject ref = new SomeObject();
ref.doSomeWork();
...
ref = new SomeObject();
</code>```

In C++, a reference cannot be reassigned to point to a different object -- it always points to the same memory location.

Pointers in C++ are more similar to Java references than C++ references are -- you can change which object they point to. They are also a bit more flexible than Java references, because you can manipulate the pointer itself, like incrementing it to point to another object in a list:

```<code>SomeObject* ptr = {instance1, instance2, instance3};
ptr->doSomeWork(); // calls instance1's doSomeWork method
ptr++;
ptr->doSomeWork(); // calls instance2's doSomeWork method
</code>```

As @DennisBraga pointed out (pun), with pointers you get access to the memory address of the object, but with references (in Java) you don't. Also, with pointers you have to dereference it somehow to get at the object, but with Java references this happens behind the scenes for you.

Title: Difference between a pointer and a reference?

Body:
In Java and other high-level languages, a reference leads to an object.

In C++, as far as I know, a pointer can also lead to an object.

So what's the difference between a reference leading to an object, and a pointer leading to an object?

Body:
They are very similar; they both do pointing to object instances in memory, but how the language lets you manipulate them is different.

In Java, a reference points to an instance of object in memory. You can reassign this reference so that it points to a different instance in memory at any time:

SomeObject ref = new SomeObject();
ref.doSomeWork();
...
ref = new SomeObject();

In C++, a reference cannot be reassigned to point to a different object -- it always points to the same memory location.

Pointers in C++ are more similar to Java references than C++ references are -- you can change which object they point to. They are also a bit more flexible than Java references, because you can manipulate the pointer itself, like incrementing it to point to another object in a list:

SomeObject* ptr = {instance1, instance2, instance3};
ptr->doSomeWork(); // calls instance1's doSomeWork method
ptr++;
ptr->doSomeWork(); // calls instance2's doSomeWork method

As @DennisBraga pointed out (pun), with pointers you get access to the memory address of the object, but with references (in Java) you don't. Also, with pointers you have to dereference it somehow to get at the object, but with Java references this happens behind the scenes for you.


问:
How do I integrate a browser-based JavaScript unit testing framework into my workflow?
I'm wondering how I seamlessly include a JavaScript unit testing framework into my workflow.

The context is, we have an existing data processing algorithm + webapp to display it, with no automated testing or continuous integration.

We use Eclipse as our IDE.

For the webapp JavaScript modification, it would be nice to add some unit tests, and qUnit looks straightforward, plenty of community support etc.

Here's how I'm currently thinking the workflow would go:

Branch the JavaScript code, check it out, modify it. Refactor it to make it more testable if needed.

Write qUnit unit tests in accordance to the above tutorial.

Start Tomcat in eclipse, run the qUnit test page.

Open the browser, check that all the tests have passed.

Commit the code back to the branch.

Merge the branch back into to trunk.

At this point there might have been a merge conflict, and so unit tests would need to be run again for the trunk to check that they're still working.

The issue here, it still seems a little cumbersome to be running the unit tests, several clicks involved to run and check the results.

Now with the merge back to trunk issue, clearly a continuous integration solution like Jenkins would be good here, but given that that's out of the question for now, let's just focus on how we can make it easy to run the tests as a developer.

Do you think I'm missing something here, or is what I'm proposing reasonable sensible?

答:
There are various ways that this can be integrated better into your workflow.

I have used qunit for various projects that I have worked on and find it to be a very capable javascript testing framework. However integrating it into the workflow was a little trickier. I'm using Visual Studio and there's a plugin which does quite a lot of the integration work for me, but I've also experimented with various different ways of running qunit unit tests.

First thing I found useful was the ability to run the javascript unit tests from a HTML page. This allowed me to quickly work out which tests succeed and which tests fail. The qunit website gives details of how to run the unit tests in a HTML page. This would at least stop the need for running tomcat and would save a couple of clicks.

The next thing that's possible is to use phantomjs and some scripting to be able to run the tests from the command line. This means that you can run all the tests quickly (both before and after the merge). Here's something that might be useful. Although it refers to ant, everything before that point is useful information about getting the tests running through phantomjs (phantomjs is cross platform so this should work pretty with any OS you're using).

Finally it might be worth checking out some of the QUnit plugins here: http://qunitjs.com/plugins/. Looks like they have plugins to run your qunit tests via phantomjs (I've not used it so I can't vouch for how useful it actually is), and a plugin to format the output (again I've not used it so I can't really tell you how good the result is).


答:
If you have no VCS with commit messages, and no bug tracking system with an option for you to leave comments, it's one option, and not the optimal one, to keep track of changes.

Better to have a spreadsheet with that information, or if you're in an environment without such "luxuries", a text file sitting somewhere near your sources.

But I'd strongly recommend if you're in such an environment to start building a case towards investing in a VCS and bug tracking system :)