问:
Logging errors caused by exceptions deep in the application
What are best-practices for logging deep within an application's source? Is it bad practice to have multiple event log entries for a single error?

For example, let's say that I have an ETL system whose transform step involves: a transformer, pipeline, processing algorithm, and processing engine.

In brief, the transformer takes in an input file, parses out records, and sends the records through the pipeline. The pipeline aggregates the results of the processing algorithm (which could do serial or parallel processing). The processing algorithm sends each record through one or more processing engines. So, I have at least four levels: Transformer -> Pipeline -> Algorithm -> Engine.

My code might then look something like the following:

```<code>class Transformer {
    void Process(InputSource input) {
        try {
            var inRecords = _parser.Parse(input.Stream);
            var outRecords = _pipeline.Transform(inRecords);
        } catch (Exception ex) {
            var inner = new ProcessException(input, ex);
            _logger.Error("Unable to parse source " + input.Name, inner);
            throw inner;
        }
    }
}

class Pipeline {
    IEnumerable<Result> Transform(IEnumerable<Record> records) {
        // NOTE: no try/catch as I have no useful information to provide
        // at this point in the process
        var results = _algorithm.Process(records);

        // examine and do useful things with results
        return results;
    }
}

class Algorithm {
    IEnumerable<Result> Process(IEnumerable<Record> records) {
        var results = new List<Result>();
        foreach (var engine in Engines) {
            foreach (var record in records) {
                try {
                    engine.Process(record);
                } catch (Exception ex) {
                    var inner = new EngineProcessingException(engine, record, ex);
                    _logger.Error("Engine {0} unable to parse record {1}", engine, record);
                    throw inner;
                }
            }
        }
    }
}

class Engine {
    Result Process(Record record) {
        for (int i=0; i<record.SubRecords.Count; ++i) {
            try {
                Validate(record.subRecords[i]);
            } catch (Exception ex) {
                var inner = new RecordValidationException(record, i, ex);
                _logger.Error(
                    "Validation of subrecord {0} failed for record {1}",
                    i, record
                    );
            }
        }
    }
}
</code>```

There's a few important things to notice:

A single error at the deepest level causes three log entries (ugly? DOS?)

Thrown exceptions contain all important and useful information

Logging only happens when failure to do so would cause loss of useful information at a lower level.

Thoughts and concerns:

I don't like having so many log entries for each error

I don't want to lose important, useful data; the exceptions contain all the important but the stacktrace is typically the only thing displayed besides the message.

I can log at different levels (e.g., warning, informational)

The higher level classes should be completely unaware of the structure of the lower-level exceptions (which may change as the different implementations are replaced).

The information available at higher levels should not be passed to the lower levels.

So, to restate the main questions:

What are best-practices for logging deep within an application's source? Is it bad practice to have multiple event log entries for a single error?

答:
I believe the Aspect Oriented Programming paradigm may offer some insight into the general solution to your problem. In researching various languages / technologies, i've read that AOP is especially suited for "cross cutting" needs including ideas such as "logging"

Logging exemplifies a crosscutting concern because a logging strategy
  necessarily affects every logged part of the system. Logging thereby
  crosscuts all logged classes and methods.

Some technologies make it easy to implement, others do not. Wish i could offer you more insight.


问:
How to teach Exception Handling for New Programmers?
How do you go about teaching Exception Handling to Programmers. All other things are taught easily - Data Structures, ASP.NET, WinForms, WPF, WCF - you name it, everything can be taught easily.

With Exception Handling, teaching them try-catch-finally is just the syntactic nature of Exception Handling.

What should be taught however is - What part of your code do you put in the try block? What do you do in the catch block?

Let me illustrate it with an example.

You are working on a Windows Forms Project (a small utility) and you have designed it as below with 3 different projects.

UILayer

BusinessLayer

DataLayer

If an Exception (let us say of loading an XDocument throws an exception) is raised at DataLayer (the UILayer calls BusinessLayer which in turns calls the DataLayer), do you just do the following

```<code>//In DataLayer
try {
    XDocument xd_XmlDocument = XDocument.Load("systems.xml");
}
catch(Exception ex)
{
    throw ex;
}
</code>```

which gets thrown again in the BusinessLayer and which is caught in UILayer where I write it to the log file?

Is this how you go about Exception Handling?

答:
I would start with Design Guidelines for Exceptions its short and includes DO, DO NOT and AVOID. It also gives the reasons why.

In your example case the revelvent section would be Wrapping Exceptions

And would expect it to be written this way. Note that it catches a specific exception and attempts to add information so that a more meaningful message is propagated. Also note that the inner exception is still maintained for logging purposes

```<code>//In DataLayer

try
{
XDocument xd_XmlDocument = XDocument.Load("systems.xml");
}
catch(FileNotFoundException ex)
{
        throw new TransactionFileMissingException(
                     "Cannot Access System Information",ex);
}
</code>```

UPDATE
Kanini asks is it even right to have this exception block in the Data Layer or should the checking the file be available to Business Layer.

Well first I'd like to point out that the rationale for Wrapping Exceptions is this

Consider wrapping specific exceptions
  thrown from a lower layer in a more
  appropriate exception, if the lower
  layer exception does not make sense in
  the context of the higher-layer
  operation.

So if you feel that have a higher layer should know about the file at all then your data layer should look like this

```<code>//In DataLayer

XDocument xd_XmlDocument = XDocument.Load("systems.xml");
</code>```

No Try No Catch.

Personally I feel that unless your data layer can do something usefull like use a default systems.xml that is an assembly resource, doing nothing or wrapping the exception is a good bet since your logging will tell you what method and what file was the problem. (throw ex in this case or the preferred throw does too but adds no value). This means that once identified you'll be able to fix the problem quickly.

As an asside this particular example also has the following problem in that XDocument.Load can throw four execeptions

ArgumentNullException

SecurityException

FileNotFoundException

UriFormatException

We cannot safely guarantee that the following code won't throw and FileNotFoundException, simply because it could be there when we do existence check and gone when we do load. Having that available to the business layer would not help.

```<code> if (File.Exists("systems.xml"))
     XDocument.Load("systems.xml");
</code>```

SecurityException is even worse because among other reasons for this being thrown if another process grabs has an exclusive file lock you'll won't get the error until you try an open it for reading because there's no File.CanIOpenThis() method. And if such a method existed you still have the same problem as with File.Exists

ContentLicense: CC BY-SA 3.0

Body:
I would start with Design Guidelines for Exceptions its short and includes DO, DO NOT and AVOID. It also gives the reasons why.

In your example case the revelvent section would be Wrapping Exceptions

And would expect it to be written this way. Note that it catches a specific exception and attempts to add information so that a more meaningful message is propagated. Also note that the inner exception is still maintained for logging purposes

//In DataLayer

try
{
XDocument xd_XmlDocument = XDocument.Load("systems.xml");
}
catch(FileNotFoundException ex)
{
        throw new TransactionFileMissingException(
                     "Cannot Access System Information",ex);
}

UPDATE
Kanini asks is it even right to have this exception block in the Data Layer or should the checking the file be available to Business Layer.

Well first I'd like to point out that the rationale for Wrapping Exceptions is this

Consider wrapping specific exceptions
  thrown from a lower layer in a more
  appropriate exception, if the lower
  layer exception does not make sense in
  the context of the higher-layer
  operation.

So if you feel that have a higher layer should know about the file at all then your data layer should look like this

//In DataLayer

XDocument xd_XmlDocument = XDocument.Load("systems.xml");

No Try No Catch.

Personally I feel that unless your data layer can do something usefull like use a default systems.xml that is an assembly resource, doing nothing or wrapping the exception is a good bet since your logging will tell you what method and what file was the problem. (throw ex in this case or the preferred throw does too but adds no value). This means that once identified you'll be able to fix the problem quickly.

As an asside this particular example also has the following problem in that XDocument.Load can throw four execeptions

ArgumentNullException

SecurityException

FileNotFoundException

UriFormatException

We cannot safely guarantee that the following code won't throw and FileNotFoundException, simply because it could be there when we do existence check and gone when we do load. Having that available to the business layer would not help.

 if (File.Exists("systems.xml"))
     XDocument.Load("systems.xml");

SecurityException is even worse because among other reasons for this being thrown if another process grabs has an exclusive file lock you'll won't get the error until you try an open it for reading because there's no File.CanIOpenThis() method. And if such a method existed you still have the same problem as with File.Exists

ContentLicense: CC BY-SA 2.5


答:
If you add some sort of component information to your log messages, you will be able to filter out everything but the top levels when viewing the logs. Then if you need more information about an error you can go and look for it.

I don't find it wrong to log multiple entries for a single error. Many programs do it already.

For example, if you are using Windows and have security event audits turned on, you may get a sequence of events that includes a failed access attempt error from the OS and then a service error for being unable to open a configuration file or registry entry. Then you might get an event from the service for being unable to start because of missing configuration.

Title: Logging errors caused by exceptions deep in the application

Body:
What are best-practices for logging deep within an application's source? Is it bad practice to have multiple event log entries for a single error?

For example, let's say that I have an ETL system whose transform step involves: a transformer, pipeline, processing algorithm, and processing engine.

In brief, the transformer takes in an input file, parses out records, and sends the records through the pipeline. The pipeline aggregates the results of the processing algorithm (which could do serial or parallel processing). The processing algorithm sends each record through one or more processing engines. So, I have at least four levels: Transformer -> Pipeline -> Algorithm -> Engine.

My code might then look something like the following:

```<code>class Transformer {
    void Process(InputSource input) {
        try {
            var inRecords = _parser.Parse(input.Stream);
            var outRecords = _pipeline.Transform(inRecords);
        } catch (Exception ex) {
            var inner = new ProcessException(input, ex);
            _logger.Error("Unable to parse source " + input.Name, inner);
            throw inner;
        }
    }
}

class Pipeline {
    IEnumerable<Result> Transform(IEnumerable<Record> records) {
        // NOTE: no try/catch as I have no useful information to provide
        // at this point in the process
        var results = _algorithm.Process(records);

        // examine and do useful things with results
        return results;
    }
}

class Algorithm {
    IEnumerable<Result> Process(IEnumerable<Record> records) {
        var results = new List<Result>();
        foreach (var engine in Engines) {
            foreach (var record in records) {
                try {
                    engine.Process(record);
                } catch (Exception ex) {
                    var inner = new EngineProcessingException(engine, record, ex);
                    _logger.Error("Engine {0} unable to parse record {1}", engine, record);
                    throw inner;
                }
            }
        }
    }
}

class Engine {
    Result Process(Record record) {
        for (int i=0; i<record.SubRecords.Count; ++i) {
            try {
                Validate(record.subRecords[i]);
            } catch (Exception ex) {
                var inner = new RecordValidationException(record, i, ex);
                _logger.Error(
                    "Validation of subrecord {0} failed for record {1}",
                    i, record
                    );
            }
        }
    }
}
</code>```

There's a few important things to notice:

A single error at the deepest level causes three log entries (ugly? DOS?)

Thrown exceptions contain all important and useful information

Logging only happens when failure to do so would cause loss of useful information at a lower level.

Thoughts and concerns:

I don't like having so many log entries for each error

I don't want to lose important, useful data; the exceptions contain all the important but the stacktrace is typically the only thing displayed besides the message.

I can log at different levels (e.g., warning, informational)

The higher level classes should be completely unaware of the structure of the lower-level exceptions (which may change as the different implementations are replaced).

The information available at higher levels should not be passed to the lower levels.

So, to restate the main questions:

What are best-practices for logging deep within an application's source? Is it bad practice to have multiple event log entries for a single error?


问:
C++ and system exceptions
Why standard C++ doesn't respect system (foreign or hardware) exceptions?

E.g. when null pointer dereference occurs, stack isn't unwound, destructors aren't called, and RAII doesn't work.

The common advice is "to use system API". But on certain systems, specifically Win32, this doesn't work. To enable stack unwinding for this C++ code

```<code>// class Foo;
// void bar(const Foo&);
bar(Foo(1, 2));
</code>```

one should generate something like this C code

```<code>Foo tempFoo;
Foo_ctor(&tempFoo);
__try {
    bar(&tempFoo);
}
__finally {
    Foo_dtor(&tempFoo);
}
Foo_dtor(&tempFoo);
</code>```

and it's impossible to implement this as C++ library.

Upd:
Standard doesn't forbid handling system exceptions. But it seems that popular compilers like g++ doesn't respect system exceptions on any platforms just because standard doesn't require this.

The only thing that I want - is to use RAII to make code readable and program reliable. I don't want to put hand-crafted try\finally around every call to unknown code. For example in this reusable code, AbstractA::foo is such unknown code:

```<code>void func(AbstractA* a, AbstractB* b) {
    TempFile file;
    a->foo(b, file);
}
</code>```

Maybe one will pass to func such implementation of AbstractA, which every Friday will not check if b is NULL, so access violation will happen, application will terminate and temporary file will not be deleted. How many months uses will suffer because of this issue, until either author of func or author of AbstractA will do something with it?

Related: Is `catch(...) { throw; }` a bad practice?

答:
As a C++ programmer I am glad that hardware exceptions are completely different things.

Imagine if they were not. Suddenly, code that has no throw statements in it is now throwing an exception. It might even be coming from inside a function which is declared as throw() or nothrow.

Besides that, in order to handle these exceptions properly, the programmer must know the hardware and platform quite well. In that case, he may as well use the platform provided functions to handle it. Just writing a catch block does not come anywhere close to properly fixing a bad pointer reference or a division-by-zero.

Title: C++ and system exceptions


答:
I used work writing software for reference boards. We had no debugger facilities for these boards (employer too cheap to buy JTAG HW) only writing logs out through serial ports. Logging as a debugging scheme is extremely useful but you need to know what to log and when. I've found the following quite useful:

Make the difference between 'got here' logs and error logs very obvious. I used prefix error logs with 3 asterixes, i.e. "* Call to foo(ptr=0x00000000, value=6) failed with -2 *", so I could search the log file quickly for errors in a text editor (they'd be several megabytes in size).

Don't just record that something went wrong, record what went wrong, preferably in the function where the exception is thrown or, if you don't have access to the code, as close as possible to that point.

Don't record something for the sake of it; only if it'll be of use to you. I used encounter situations where the entire call stack would continually be logged. It sounds useful but all it did was pollute logs and when you're dealing with asynchronous behaviour it turns out not to be all that useful. Excessive logging can even change the runtime behaviour and hide multi-threaded issues that only appear when you use Release builds. If you do go down the route of logging the execution trace you may as well log the parameter values passed to functions where possible.

As for multiple logs entires for the same error... no big deal. The first one is usually the culprit and as long as you can find it, and have logs that provide enough information for you to quickly reproduce/isolate the error, the rest should only be confirmation that your program doesn't fall over itself when an error does occur.


答:
I prefer to:

Wrap exceptions with any useful information that I may have available at the level where they are caught.

Always log exceptions if they are not getting rethrown.

Only log exceptions if they are not getting rethrown.

It looks like you're following #1 and #2 already, so you just need to apply #3, and you can ensure that each error is only logged once, with the maximum amount of information possible.

```<code>class Transformer {
    void Process(InputSource input) {
        try {
            var inRecords = _parser.Parse(input.Stream);
            var outRecords = _pipeline.Transform(inRecords);
        } catch (Exception ex) {
            // Make sure the message string on this exception class produces
            // a verbose error message like "Unable to parse source " + input.Name
            throw new ProcessException(input, ex);
        }
    }
}

class Pipeline {
    IEnumerable<Result> Transform(IEnumerable<Record> records) {
        // NOTE: no try/catch as I have no useful information to provide
        // at this point in the process
        var results = _algorithm.Process(records);

        // examine and do useful things with results
        return results;
    }
}

class Algorithm {
    IEnumerable<Result> Process(IEnumerable<Record> records) {
        var results = new List<Result>();
        foreach (var engine in Engines) {
            foreach (var record in records) {
                try {
                    engine.Process(record);
                } catch (Exception ex) {
                    // Likewise, ensure the message string for this class records
                    // the specifics, so that logging a stack trace will contain
                    // all the necessary details to reproduce.
                    throw new EngineProcessingException(engine, record, ex);
                }
            }
        }
    }
}

class Engine {
    Result Process(Record record) {
        for (int i=0; i<record.SubRecords.Count; ++i) {
            try {
                Validate(record.subRecords[i]);
            } catch (Exception ex) {
                var inner = new RecordValidationException(record, i, ex);
                // Since you're not rethrowing, make sure you log this error.
                _logger.Error(
                    ex,
                    "Validation of subrecord {0} failed for record {1}",
                    i, record
                    );
            }
        }
    }
}
</code>```

Be aware that this does open up the possibility that your exception could end up in code where the author didn't follow rule #2, and no log is produced. But if you can ensure that these three rules are followed consistently, I've found this to be an ideal approach.

Body:
I prefer to:

Wrap exceptions with any useful information that I may have available at the level where they are caught.

Always log exceptions if they are not getting rethrown.

Only log exceptions if they are not getting rethrown.

It looks like you're following #1 and #2 already, so you just need to apply #3, and you can ensure that each error is only logged once, with the maximum amount of information possible.

class Transformer {
    void Process(InputSource input) {
        try {
            var inRecords = _parser.Parse(input.Stream);
            var outRecords = _pipeline.Transform(inRecords);
        } catch (Exception ex) {
            // Make sure the message string on this exception class produces
            // a verbose error message like "Unable to parse source " + input.Name
            throw new ProcessException(input, ex);
        }
    }
}

class Pipeline {
    IEnumerable<Result> Transform(IEnumerable<Record> records) {
        // NOTE: no try/catch as I have no useful information to provide
        // at this point in the process
        var results = _algorithm.Process(records);

        // examine and do useful things with results
        return results;
    }
}

class Algorithm {
    IEnumerable<Result> Process(IEnumerable<Record> records) {
        var results = new List<Result>();
        foreach (var engine in Engines) {
            foreach (var record in records) {
                try {
                    engine.Process(record);
                } catch (Exception ex) {
                    // Likewise, ensure the message string for this class records
                    // the specifics, so that logging a stack trace will contain
                    // all the necessary details to reproduce.
                    throw new EngineProcessingException(engine, record, ex);
                }
            }
        }
    }
}

class Engine {
    Result Process(Record record) {
        for (int i=0; i<record.SubRecords.Count; ++i) {
            try {
                Validate(record.subRecords[i]);
            } catch (Exception ex) {
                var inner = new RecordValidationException(record, i, ex);
                // Since you're not rethrowing, make sure you log this error.
                _logger.Error(
                    ex,
                    "Validation of subrecord {0} failed for record {1}",
                    i, record
                    );
            }
        }
    }
}

Be aware that this does open up the possibility that your exception could end up in code where the author didn't follow rule #2, and no log is produced. But if you can ensure that these three rules are followed consistently, I've found this to be an ideal approach.


问:
dvcs - is "clone to branch" a common workflow?
I was recently discussing dvcs with a coworker, because our office is beginning to consider switching from TFS (we're a MS shop). In the process, I got very confused because he said that although he uses Mercurial, he hadn't heard of a "branch" or "checkout" command, and these terms were unfamiliar to him. After wondering how it was possible that he didn't know about them and explaining how dvcs branches work "in place" on your local files, he was quite confused.

He explained that, similar to how TFS works, when he wants to create a "branch" he does it by cloning, so he has an entire copy of his repo. This seemed really strange to me, but the benefit, which I have to concede, is that you can look at or work on two branches simultaneously because the files are separate.

In searching this site to see if this has been asked before I saw a comment that many online resources promote this "clone to branch" methodology, to the poster's dismay. Is this actually common in the dvcs community? And what are some of the pros and cons of going this way? I would never do it since I have no need to see multiple branches at once, switching is fast, and I don't need all the clones filling up my disk.

答:
Every time you make a commit in a DVCS you are technically making a branch in the history, every time you push it back to the blessed repository you integrate it back, here comes the interesting part:

If no one made a change during your commit, it won't look like a branch in the DAG (directed acyclic graph)

If someone else made a change during your commit, it will look like a branch in the DAG, only unnamed

Remember the "fork" button in Bitbucket/github?, forking can be regarded as a synonymous of branching, and what the "fork" button does is just a clone of that repository to your account.

The only advantage of "cloning to branch" is being able to work simultaneously at two points in the history, and ironically for your coworker, it is a common workflow for working on different branches at the same time (without having to go back and forth).

Tell your coworker to learn how to branch, it is very easy, here, have a tutorial:

```<code>D:\>mkdir lol

D:\>cd lol

D:\lol>hg init

D:\lol>hg branch
default

D:\lol>touch lol

D:\lol>hg add lol

D:\lol>hg commit -m "lol"

D:\lol>hg branch lol
marked working directory as branch lol
(branches are permanent and global, did you want a bookmark?)

D:\lol>hg branches
default                        0:35d562fafaf2

D:\lol>echo "lol" > lol

D:\lol>hg commit -m "New lol branch"

D:\lol>hg branches
lol                            1:9384f923e78d
default                        0:35d562fafaf2 (inactive)

D:\lol>hg branch
lol

D:\lol>hg update default
1 files updated, 0 files merged, 0 files removed, 0 files unresolved

D:\lol>hg branch
default

D:\lol>hg update lol
1 files updated, 0 files merged, 0 files removed, 0 files unresolved

D:\lol>hg branch
lol

D:\lol>hg update default
1 files updated, 0 files merged, 0 files removed, 0 files unresolved

D:\lol>hg branch
default

D:\lol>hg merge lol
1 files updated, 0 files merged, 0 files removed, 0 files unresolved
(branch merge, don't forget to commit)

D:\lol>hg commit -m "lol merge"

D:\lol>hg branch
default

D:\lol>hg update lol
0 files updated, 0 files merged, 0 files removed, 0 files unresolved

D:\lol>hg branch
lol
</code>```

"Cloning to branch" makes sense when you are working in different branches at the same time, or, when you want to try out an experiment without creating a permanent branch in the history and still be able to integrate it back to an already existing branch.

I personally don't like this practice and prefer to do branches and close them if necessary. Here, this is how you do it:

```<code>D:\lol>hg branches
default                        2:46420aca1612
lol                            1:9384f923e78d (inactive)

D:\lol>hg branch
lol

D:\lol>hg commit --close-branch -m "Obai, glorious lol branch"

D:\lol>hg branches
default                        2:46420aca1612

D:\lol>hg branch
lol

D:\lol>hg update default
0 files updated, 0 files merged, 0 files removed, 0 files unresolved

D:\lol>hg branches
default                        2:46420aca1612

D:\lol>hg branches --closed
default                        2:46420aca1612
lol                            3:4b79c577e029 (closed)
</code>```

Hope this clears out your DVCS branching doubts, here branches are not scary anymore.

Body:
Every time you make a commit in a DVCS you are technically making a branch in the history, every time you push it back to the blessed repository you integrate it back, here comes the interesting part:

If no one made a change during your commit, it won't look like a branch in the DAG (directed acyclic graph)

If someone else made a change during your commit, it will look like a branch in the DAG, only unnamed

Remember the "fork" button in Bitbucket/github?, forking can be regarded as a synonymous of branching, and what the "fork" button does is just a clone of that repository to your account.

The only advantage of "cloning to branch" is being able to work simultaneously at two points in the history, and ironically for your coworker, it is a common workflow for working on different branches at the same time (without having to go back and forth).

Tell your coworker to learn how to branch, it is very easy, here, have a tutorial:

D:\>mkdir lol

D:\>cd lol

D:\lol>hg init

D:\lol>hg branch
default

D:\lol>touch lol

D:\lol>hg add lol

D:\lol>hg commit -m "lol"

D:\lol>hg branch lol
marked working directory as branch lol
(branches are permanent and global, did you want a bookmark?)

D:\lol>hg branches
default                        0:35d562fafaf2

D:\lol>echo "lol" > lol

D:\lol>hg commit -m "New lol branch"

D:\lol>hg branches
lol                            1:9384f923e78d
default                        0:35d562fafaf2 (inactive)

D:\lol>hg branch
lol

D:\lol>hg update default
1 files updated, 0 files merged, 0 files removed, 0 files unresolved

D:\lol>hg branch
default

D:\lol>hg update lol
1 files updated, 0 files merged, 0 files removed, 0 files unresolved

D:\lol>hg branch
lol

D:\lol>hg update default
1 files updated, 0 files merged, 0 files removed, 0 files unresolved

D:\lol>hg branch
default

D:\lol>hg merge lol
1 files updated, 0 files merged, 0 files removed, 0 files unresolved
(branch merge, don't forget to commit)

D:\lol>hg commit -m "lol merge"

D:\lol>hg branch
default

D:\lol>hg update lol
0 files updated, 0 files merged, 0 files removed, 0 files unresolved

D:\lol>hg branch
lol

"Cloning to branch" makes sense when you are working in different branches at the same time, or, when you want to try out an experiment without creating a permanent branch in the history and still be able to integrate it back to an already existing branch.

I personally don't like this practice and prefer to do branches and close them if necessary. Here, this is how you do it:

D:\lol>hg branches
default                        2:46420aca1612
lol                            1:9384f923e78d (inactive)

D:\lol>hg branch
lol

D:\lol>hg commit --close-branch -m "Obai, glorious lol branch"

D:\lol>hg branches
default                        2:46420aca1612

D:\lol>hg branch
lol

D:\lol>hg update default
0 files updated, 0 files merged, 0 files removed, 0 files unresolved

D:\lol>hg branches
default                        2:46420aca1612

D:\lol>hg branches --closed
default                        2:46420aca1612
lol                            3:4b79c577e029 (closed)

Hope this clears out your DVCS branching doubts, here branches are not scary anymore.


问:
Do you start migrating your Swing project to JavaFX
I have a 4 years old project which is written in Swing + SwingX. Currently, it is still alive and still kicking.

However, as more GUI related feature requests coming in (For instance, a sortable tree table), I start to feel the difficulty in fulling the requests. This is true especially since there isn't any active development going around SwingX project.

Also, I can hardly find any good, yet actively maintained/ developed/ evolving GUI Java framework.

I was wondering, do any of the Swing developers feel the same thing? Have you start to migrate your Swing project to a much more active developed GUI framework, like JavaFX?

答:
I ask myself the same thing often, but I don't think I would migrate existing projects to JavaFX. At least not for now, and not for medium- to large-size projects. I would, however, considering JavaFX for new projects, and consider a migration again in the future and re-evaluate question based on JavaFX's progress.

At the moment, my concerns are:

Immaturity

Yes, we're going to 3.0 soon, but it hasn't been around this long, and still went through major changes. So for large and risk-averse corporate software, this is a relatively sore spot.

Performance

I haven't seen enough hard-data on performance differences.

Widgets and Components

I haven't seen enough gain in the new components. This can relate to immaturity, I guess. I also don't know yet how well they can be extended and composited, in contrast with Swing.

Overall, I guess hard-data on the advantages is what I'm missing to be fully convinced by JavaFX.

On the other hand, Swing is proven and tested. Yes, the API is clunky and invoking the auto-completion in your IDE on a Swing object like the JTextPane will make it weep and cry for its mommy, but, if you're knowledgeable enough, you can build awesome UIs with Swing, that are performing well (I never bought the Swing-has-bad-performance fallacy, see Romain Guy's former blog posts on Sun's blogs) and allow you to do pretty neat things.

So, before switching anything, I'd recommend you try a small prototype first, and maybe try to port some of your application's dialogs and see how it goes.


问:
Random Cache Expiry
I've been experimenting with random cache expiry times to avoid situations where an individual request forces multiple things to update at once. For example, a web page might include five different components. If each is set to time out in 30 minutes, the user will have a long wait time every 30 minutes. So instead, you set them all to a random time between 15 and 45 minutes to make it likely at most only one component will reload for any given page load.

I'm trying to find any research or guidelines on this topic, e.g. optimal variance parameters. I do recall seeing one article about how Google (?) uses this technique, but can't locate it, and there doesn't seem to be much written about the topic.

答:
Some documents:

Optimizing Caching from the Let's Make the Web Faster Google series (I assume you meant this one?)

The Caching Tutorial on mnot.net

There are some relevant SO questions as well:

Set HTTP Caching Expiration, Recommended by Google PageSpeed

Set HTTP Caching Expiration, Recommended by Google and Yahoo

And some other StackExchange-hosted questions as well:

What are the Hard and Fast Rules for Cache Control?

Title: Random Cache Expiry


问:
How does the Java Virtual Machine execute code written in other languages?
Since Java 1.6 the JVM can run a myriad of programming languages on top of instead of just Java. I conceptually understand how Java is run on the Java VM, but not how other languages can run on it as well. To me, it all looks like black magic. Do you have any articles to point me to so I can better understand how this all fits together?</p>

答: For a moment just think of the JVM as a processor with its own instruction set like maybe the x86. The processor can execute say C code that has been compiled into into its machine language. Applying the same analogy to the JVM, Other languages can be executed on the JVM just like on other processors if those languages are compiled down to the machine instructions of the JVM. The JVM can then run these instructions for language X.</p>


问:
scalablity of Scala over Java
I read an article that says Scala handles concurrency better than Java.

http://www.theserverside.com/feature/Solving-the-Scalability-Paradox-with-Scala-Clojure-and-Groovy

...the scalability limitation is confined specifically to the Java programming language itself, but it is not a limitation of the Java platform as a whole...

The scalability issues with Java aren't a new revelation. In fact, plenty of work has been done to address these very issues, with two of the most successful projects being the programming languages named Scala and Clojure...

...Scala is finding ways around the problematic thread and locking paradigm of the Java language...

How is this possible? Doesn't Scala use Java's core libraries which brings all the threading and locking issues from Java to Scala?

答:
Doesn't Scala use Java's core libraries which brings all the threading
  and locking issues from Java to Scala?

Well, yes, and if you do locking in Scala you'll face the same issues. The point, however, is that you are not supposed to, as Scala provides you with abstractions that handle this problem in a safer manner.

Now, Scala does two things that really helps. One of them is the actor model, which can be thought of as a concurrency pattern, provided by Scala as a library. If you are a Java programmer, I suggest you go to Akka site and look at their Java stuff. This is the library that will replace Scala's current actor library, and you can use it from Java.

The second thing that Scala does that helps is using immutable data structures. There's nothing preventing Java from using immutable data structures -- String, for one, is itself immutable! Immutable data structures do not suffer from concurrency problems since threads can't change them.

There are other things that add to these, to make up full solutions, such as agents and stm (both available from Akka), or latches (from Java).

Now, the two things above can be done in Java, as I said myself. You can use Akka in Java, and you can write immutable data structures in Java (or use from libraries that provide them). However, Java makes it a pain to use this stuff, because it supports neither higher order types, nor closures and first-class functions.

So, while you can do it, programmers usually won't because, in Java, writing such code is very verbose (I mean, much more so than the standard for Java).

Title: scalablity of Scala over Java


问:
How did programming work when programmers used punchcards?
I saw this: Learning to program on punchcards

and I've seen this: http://en.wikipedia.org/wiki/Computer_programming_in_the_punched_card_era

but they leave much to be desired.

Can anyone explain to me how programmers programmed when they used punchcards? Specifically, the system of input computers used to derive instructions from the punched card itself.

I do not know much about retrocomputers, so any one system of input you are familiar with would be fine. More general answers are also appreciated.

答:
Very slowly.

My mother was such a programmer, so I had tons of these cards at home while growing up. What they would do was encoding the program on the cards, and then feeding the cards into the card reader one by one (similar to how the voting machines work now). If you dropped the cards - you would be in a lot of trouble, because you only have X machine time allocated for you and you'd have to get them arranged in the right order and restart feeding the machine all over again and try to make it on time before the next programmer kicks you out. A trivial (in our current standards) program might have required hundreds, if not thousands, of such cards, and hours of machine time to load it and run it.

Very tedious.


答:
In a word, poorly.

At least on any machine I ever used or heard of, you did not feed cards one at a time though. There were automated card readers that would feed and read hundreds of cards a minute (probably around 1000/minute, but I'm not sure of the exact specs).

In a typical case you wrote the code by hand, then punched it onto cards. Each card holds one line of code (up to 80 columns). You took the card deck to be executed. Depending on backlog, anywhere from an hour or so to a day or so later, you got your deck back along with a printout of the results.

I should probably add: since your card deck ran as a job, you didn't just submit the code for the program itself -- you had to write something vaguely similar to a batch file/shell script with the directions to compile and execute your code. IBM JCL (for one example) remains heavily influenced by its Hollerith-card origins.

Another minor point: on most systems I remember, you normally included a line number on each punch card. You obviously avoided dropping a deck if you could, but when (not if) one got dropped, it wasn't really nearly the tragedy many imagine. Interesting side point: at least the card sorters I saw used a radix sort -- they'd separate the cards into 10 bins, based on one digit of the line number, then "merge" those together (drop all the cards into a single bin in order) then repeat as many times as you had digits in the line numbers.

Hollerith cards were extremely influential -- 80 columns as a limit still survives to an almost disturbing degree. At least on the Control Data mainframes, things like the file system were influenced quite heavily as well. Well after Hollerith cards were mostly gone, remnants of them were visible in the OS -- for example, text files were often stored as a series of 80-character records, regardless of how few/many characters a line actually contained. I can still remember my surprise at the "backwardness" of a system like Unix where you had to read all the preceding lines to find line N of a text file, instead of just being able to seek to it directly.

Title: How did programming work when programmers used punchcards?

Body:
I saw this: Learning to program on punchcards

and I've seen this: http://en.wikipedia.org/wiki/Computer_programming_in_the_punched_card_era

but they leave much to be desired.

Can anyone explain to me how programmers programmed when they used punchcards? Specifically, the system of input computers used to derive instructions from the punched card itself.

I do not know much about retrocomputers, so any one system of input you are familiar with would be fine. More general answers are also appreciated.


问:
Learning to program on punchcards
I'd like to try programming with punch cards once in my life. How can I do this?

I'm in my 30s, and grew up entirely in the PC era, programming on computers with screens and keyboards. I want to experience the way my father and grandfather used to work. I imagine the hardware (and probably the cards themselves) are no longer manufactured. Are there any universities or museums with functioning punch card readers anymore? I'm in Boston, but I'm willing to travel to do this.

I asked MetaFilter, and I got some mixed answers (along with a lot of "no, don't do this" nay-saying). I did get a pointer to the Retro-Computing Society Of Rhode Island, but I haven't received a response to my email to them yet.

答:
Maybe you could just get close to this by using an emulator, like:

http://www.kloth.net/services/cardpunch.php

This gentleman here seems to have some nice information on rolling out your own emulator:

http://www.divms.uiowa.edu/~jones/cards/

Which partly inspired:

http://dev.technikum29.de/projects/checkout/paper-tape-project/documentation/index.php/punch-card/README.htm

Personally, I like your idea/approach :)

Title: Learning to program on punchcards


问:
Is it customary to write Java domain objects / data transfer objects with public member variables on mobile platforms?
We performed a code review recently of mobile application Java code that was developed by an outside contractor and noticed that all of the domain objects / data transfer objects are written in this style:

```<code>public class Category {
    public String name;
    public int id;
    public String description;
    public int parentId;
}

public class EmergencyContact {
    public long id;
    public RelationshipType relationshipType;
    public String medicalProviderType;
    public Contact contact;
    public String otherPhone;
    public String notes;
    public PersonName personName;
}
</code>```

Of course, these members are then accessed directly everywhere else in the code. When we asked about this, the developers told us that this is a customary performance enhancement design pattern that is used on mobile platforms, because mobile devices are resource-limited environments. It doesn't seem to make sense; accessing private members via public getters/setters doesn't seem like it could add much overhead. And the added benefits of encapsulation seem to outweigh the benefits of this coding style.

Is this generally true? Is this something that is normally done on mobile platforms for the reasons given above? All feedback welcome and appreciated -

答:
There is a grain of truth in your contractor's assertion.

For some time, Android game developers were encouraged to avoid internal getters and setters for performance reasons. However, this advice only applies to game developers who need to push devices to the limit, and are required to sacrifice other benefits to achieve their aims. Moreover, with the release of Gingerbread, this even gamed benefit little from this practice.

More than once, I've met developers give "best practice" advice or follow guidelines that is perfectly valid in one scenario (often historic) but which simply doesn't apply to the case in hand. More often than not, this is because the developer has forgotten (or never knew) the reasons why their advice applied the first place, so they assume it must be valid for all cases at all times. In my experience, this is particularly common when discussing performance tuning. That seems to be the case here.

The correct approach to performance is:

to get it right before you make if fast

use metrics to tell you what to optimise and again to determine whether your efforts are succeeding


答:
You used the card punch as an editor.

Insert == punch a new card.

Move == pick up the card and move it to the right spot.

Delete == take out the card and throw it in the bin

Copy -- better card punches had a copy function which could copy another card column by column.

Repace a character -- use the copy function but type in the replacement characters when you reach the character you need to replace.

Delete a character -- use the copy function but hold the copied card to stop it moving and hit space for each character you want to "delete"

Insert characters -- use the copy function but hold the original card immobile while typing in the new text.

For the most part cards were "immutable" but you could remove characters by taping over the holes with thin opaque sticky tape.

You read in your program surrounded by the appropriate JCL and waited for the printer to spit out the results. (Could be hours!)


问:
non-volatile virtual memory for C++ containers
Is there a virtual memory management process that would allow a program to use the standard container structures and classes, but retain these structures and their data when the program is not running (or being used), for use by the program at a later time?
This should be possible, but can it be done without changing the source code and its (container) declarations?
Is there a standard way of doing this?</p>

答: There have been a couple of projects along this line. Neither of those seems to have come into particularly wide use. Stxxl seems to be the most widely used of the projects along this line.</p>


问:
Of which bad practice is require calling functions in order a sign?
Sometimes I find myself writing comments on class methods like this:

```<code>class A : public Base
{
public:
    /**
      * Sets variable;
      * should be called before ImplementsInterfaceMtehod(),
      * else has no effect.
      */
  void SetSomeVariable( var_type value );

  virtual void ImplementsInterfaceMethod();
}
</code>```

The callers of Base::ImplementsInterfaceMethod obviously do not know about the variable, and should not. But the users of A should set the variable if they want it to take effect. It is not required to set the variable (else it could be a parameter for the constructor), so I cannot throw exceptions in ImplementsInterfaceMethod if it is not set.

Is this a sign of some typical bad practice? Is there a better way than writing a comment as shown to deal with this?

edit here's a more concrete example resembling part of some realtime 3D image processing code; because of the realtime part and the fact images can get huge, everything has to be preallocated.

```<code>class DataProcessor
{
public:
    /**
      * Sets dimensions of the data for the next call to Process().
      * Can be used by implementations to setup internals, eg preallocate.
      * Upon returning out contains the dimensions that will be returned
      * by the Process call, given dims as input dimensions.
      * (A)
      */
  virtual bool SetInputDimensions( const Dimensions& dims, Dimensions& out ) = 0;

  virtual bool Process( const Data& in, Data& out ) = 0;
};

class ImageStitcher : public DataProcessor
{
    /**
      * Set size of the output image returned by Process() as a factor,
      * eg when size == 2, image will be twice as big.
      * (B)
      */
  void SetOutputSize( const double size );

    /**
      * Set the position at which the next Data object passed to Process()
      * will be stitched.
      * (C)
      */
  void SetStitchPosition( double x, double y, double alpha );
}
</code>```

So here (A) must be called at least once before Process() is called. Which I enforce by returning an error in Process() if that was not the case. Most of the time the dimensions are not known when constructing the object though so a constructor parameter is not an option. Two main components use the DataProcessor interface: all processors are in a network of processors, and that network is unaware of the type of processor, it just takes care of transferring data between them by calling Process() multiple time. Another component takes care of setting up the network by calling SetInputDimensions(), again unaware of what type the processor is.

(B) should be called before SetInputDimensions() gets called, as it defines the size of the resulting image.

(C) should be called before each call to process else the stitcher doesn't know where to put the image

Now this whole processing network is actually used in commercial applications and works extremely well since I made sure everything is called nicely in order. Yet each time I write 'must/should be called before' bells start ringing all over the place..

答:
As always it depends on context. If your class was an XML parser, and SetSomeVariable was a flag for modifying whether whitespace nodes are returned from parsing then there's no problem.

The only times when this is an issue is when there is a requirement for SetSomeVariable to be invoked before the other method. This would cause tight coupling.

As you asked, perhaps a better comment is required:

```<code>/**
  * Modifies the behaviour of the ImplementsInterfaceMethod() method in way xyz.
  */
void SetSomeVariable( var_type value );
</code>```

Of course, in this example you could probably use an optional parameter:

```<code>virtual void ImplementsInterfaceMethod(int i = 1);
</code>```

Body:
As always it depends on context. If your class was an XML parser, and SetSomeVariable was a flag for modifying whether whitespace nodes are returned from parsing then there's no problem.

The only times when this is an issue is when there is a requirement for SetSomeVariable to be invoked before the other method. This would cause tight coupling.

As you asked, perhaps a better comment is required:

/**
  * Modifies the behaviour of the ImplementsInterfaceMethod() method in way xyz.
  */
void SetSomeVariable( var_type value );

Of course, in this example you could probably use an optional parameter:

virtual void ImplementsInterfaceMethod(int i = 1);


问:
What is the best C++ source code to read for a beginner?
I'm trying to improve my c++ coding technique by reading c++ source code. Which open source project would you recommend? Is the code of Boost C++ Libraries a good one?</p>

答:
Try reading something that has been existing for years and is large in size.  It will take a few months of time to start to understand the code and getting to do something in it.

Firefox, Thunderbird, OpenOffice.org, LibreOffice come to the mind.  There should be many more similar ones too.  These projects run on many operating systems and hardware platforms.  Also, they have to score on readability.  These could should you the techniques you look for.


问:
What was the first commercial open-source software?
According to the Wikipedia article on open-source, the philosophy of sharing code has been used in projects since the early computer days (mostly through Universities sharing code). However, I'm interested to know what (and when) was the first commercial open-source software (successfull or not)?

If there's any confusion on commercial, I define it as thus: "Having profit as a chief aim".

答:
In the good old days of Apple II and Commodore 64 and many others and before IBM PC, there were magazines which published source code of BASIC programs to be typed and run on these early computers. Customers paid the magazine and progammers got paid by the line of code.

I think this qualifies as commercial open source software, though I would not be so sure that this is the first example.


问:
Security aspects of an ASP.NET that can be pointed out to the client
I need to write several passages of text in an offer to the client about the security layer in ASP.NET MVC web solution.

I am aware of security that comes along with MVC 3 and an improvements in MVC 4. But all of them are non conceptual, except for AntiForgeryToken (AntiXSS) and built-in SQL Injection immunity (with a little of encoding needed by hand).

What would be the main point of ASP.NET security I can "show off" in an offer to the client?

答:
I think that if you want to impress, start with a well-respected security report, for example WhiteHat Website Security Statistics Report
Winter 2011

Then go through e.g. the top 10 security vulnerabilities, and describe how the .NET framework deals with these issues. I haven't read the report, but I know that the top 10 include SQL injection and XSite scripting.


问:
Tabs versus spaces—what is the proper indentation character for everything, in every situation, ever?
The coding standards for the code hosted in drupal.org suggest to use two spaces to indent the code; other sites suggest to use tabs to indent the code.

What is the proper indentation character for everything, and in every situation? Please explain the answer you give.

答:
You obviously need a combination approach.

If you're sharing code with other developers, you need to standardize, and since that's impossible (koff koff), you need to make everyone do four spaces.

Then you need an editor that's smart enough not to be stupid about that, to know that it should treat a line with four spaces at the front of it like it's indented. Any modern IDE or programmers' editor can auto-flow code with spaces instead of tabs.


答: Using an existing punch card machine is only half the fun of retro-computing. How about building your own from Lego?</p>

Title: Learning to program on punchcards

Body:
I'd like to try programming with punch cards once in my life. How can I do this?

I'm in my 30s, and grew up entirely in the PC era, programming on computers with screens and keyboards. I want to experience the way my father and grandfather used to work. I imagine the hardware (and probably the cards themselves) are no longer manufactured. Are there any universities or museums with functioning punch card readers anymore? I'm in Boston, but I'm willing to travel to do this.

I asked MetaFilter, and I got some mixed answers (along with a lot of "no, don't do this" nay-saying). I did get a pointer to the Retro-Computing Society Of Rhode Island, but I haven't received a response to my email to them yet.


答:
As always, it depends.

If the object exists some of the time in state when the variable is not set and another time in state when it is set and in both cases the ImplementsInterfaceMethod does the thing one expects from looking at Base alone, than it's right.

In the object has to have the variable set before it's usable as implementation of Base, than it's a code smell. I would probably call it contract violation, since the object claims to implement an interface, but only implements it sometimes.

In this case it would be preferred to either require the value in constructor, or to create an object with parametric method and wrapper which implements the interface, again taking the value in constructor. But it might easily be best of bad solutions if you are constrained by some existing interfaces.

Title: Of which bad practice is require calling functions in order a sign?

Body:
Sometimes I find myself writing comments on class methods like this:

```<code>class A : public Base
{
public:
    /**
      * Sets variable;
      * should be called before ImplementsInterfaceMtehod(),
      * else has no effect.
      */
  void SetSomeVariable( var_type value );

  virtual void ImplementsInterfaceMethod();
}
</code>```

The callers of Base::ImplementsInterfaceMethod obviously do not know about the variable, and should not. But the users of A should set the variable if they want it to take effect. It is not required to set the variable (else it could be a parameter for the constructor), so I cannot throw exceptions in ImplementsInterfaceMethod if it is not set.

Is this a sign of some typical bad practice? Is there a better way than writing a comment as shown to deal with this?

edit here's a more concrete example resembling part of some realtime 3D image processing code; because of the realtime part and the fact images can get huge, everything has to be preallocated.

```<code>class DataProcessor
{
public:
    /**
      * Sets dimensions of the data for the next call to Process().
      * Can be used by implementations to setup internals, eg preallocate.
      * Upon returning out contains the dimensions that will be returned
      * by the Process call, given dims as input dimensions.
      * (A)
      */
  virtual bool SetInputDimensions( const Dimensions& dims, Dimensions& out ) = 0;

  virtual bool Process( const Data& in, Data& out ) = 0;
};

class ImageStitcher : public DataProcessor
{
    /**
      * Set size of the output image returned by Process() as a factor,
      * eg when size == 2, image will be twice as big.
      * (B)
      */
  void SetOutputSize( const double size );

    /**
      * Set the position at which the next Data object passed to Process()
      * will be stitched.
      * (C)
      */
  void SetStitchPosition( double x, double y, double alpha );
}
</code>```

So here (A) must be called at least once before Process() is called. Which I enforce by returning an error in Process() if that was not the case. Most of the time the dimensions are not known when constructing the object though so a constructor parameter is not an option. Two main components use the DataProcessor interface: all processors are in a network of processors, and that network is unaware of the type of processor, it just takes care of transferring data between them by calling Process() multiple time. Another component takes care of setting up the network by calling SetInputDimensions(), again unaware of what type the processor is.

(B) should be called before SetInputDimensions() gets called, as it defines the size of the resulting image.

(C) should be called before each call to process else the stitcher doesn't know where to put the image

Now this whole processing network is actually used in commercial applications and works extremely well since I made sure everything is called nicely in order. Yet each time I write 'must/should be called before' bells start ringing all over the place..


答: It probably indicates that you should have taken that value as an argument in an overload of ImplementsInterfaceMethod, as the setter serves no other purpose. However, if it sets general state good for many functions, and it's optional, then I don't believe it is bad design.


答:
Even better than reading the code would be to work with that code in form of fixing bugs and adding small improvements here and there. Pick some program, preferably one you have use for, sign up to the mailing list, start going through their bug tracker and try to diagnose some bugs. Ask on the mailing list if you find solution for something whether it's reasonable or when you get stuck. That will give you some specific goals when reading the code, force you to really understand and is what you'll be doing most of the time in any work.

You can perhaps look at some KDE application. Most are written in C++ and you can start with some smaller one first.

Title: What is the best C++ source code to read for a beginner?

Body: I'm trying to improve my c++ coding technique by reading c++ source code. Which open source project would you recommend? Is the code of Boost C++ Libraries a good one?</p>


答: I would suggest reading the "Effective C++" by Scott Meyers and using the suggestions he has in little toy programs.


问:
Java web app, with plugin framework and ability to connect to source for updates
I've searched all around for some good sources, but either have been searching for the wrong keywords, or I'm just missing something. I'm looking to redevelop a web app I've been using for some time now. Many parts are out of date, and we're constantly throwing in little hacks to attempt to give it new life.

So what I'd like to do is re-engineer it from the ground up, built on some sort of plug-in framework. Before I continue, I'm more or less an intermediate Java programmer. In some ways, I'm hoping to use this project as a big learning experience.

I've read a lot about OSGi, and it seems that's the most complete framework. Ideally, I would like an end result web app which I can run one instance as my hosting environment, and other instances can connect to it to grab new and updated plug-ins. Eventually I'll want to lock down these plug-ins based on some undecided criteria of who can get them (basically some will simply be updates, others will provide new functionality and should be "purchased" through an external system). But that will probably be handled in a later phase. There should be an administration view for managing bundles in a hot environment (looking to avoid having to restart the server for an update).

I know all these things are possible, I'm just trying to find some good resources for reference. All the OSGi tutorials I'm finding seem to be too simplistic. If anyone here can guide me in the right direction on any or all of the items I'm looking for, it would be much appreciated. Also, this is my first post, so I'll take any comments/criticisms about the content of my post. Thanks!

答:
In OSGi there are a variety of available solutions for provisioning OSGi modules/plugins.

One of the approaches is the OSGi Bundle Repository (OBR). This is a system that can contain OSGi modules and serve as a provisioning system for your applications.
It can be accessed from shell or an OBR Service API to resolve resources. It seems as a good foundation for a pluggable framework. You would need to have a central OBR which contains your plugins and an update module that uses the API to connect to it and resolve.

OBR is used in e.g. Bndtools for provision resources to Eclipse OSGi projects.
Applications such as Artifactory and Nexus also provide support for OBR.
More on OBR, OBR explained in OSGi In Action book.

As mentioned in the beginning there are other provisioning systems. Most runtimes (Eclipse Virgo, Apache Karaf) offer some sort of repository system (not always OBR) to provision bundles. They already have web applications available to view and interract with them. More on this in the answer given on this SO question. From OSGi R5 there are standardisation services for interacting with a lot of them.
See these slides at eclipsecon.org about Subsystem Service, Repository Service and Resolver Service.

Finally I'd like to mention the Apache Sling project. It is a framework to build OSGi web applications but the interesting thing is that it uses the Java Content Repository specification to manage content. You can deploy Sling to any servlet container and it has a admin web application where you can manage OSGi bundles. It is fast to get up and running and try it out. You just have to deploy the Sling launchpad war. See more about Sling launchpad at sling.apache.org. I do not have much experience with developing with Sling, I have just used it to deploy OSGi web applications.

Basically, when using OSGi a plugin system is at your fingertips without implementing all of it yourself. Although it is hard to find real world examples I recommend using an existing provisioning system from an OSGi runtime or Sling to get your started quickly. A good resource are the Manning books on OSGi (OSGi In Action, In Depth & Enterprise) they helped me a lot in grasping the concepts and the examples are really good.


问:
Is a readonly field in VB.NET thread safe?
Is a readonly field in VB.NET thread safe? For example, see the code below:</p>

```<code>Class Customer
  ReadOnly Name As String

  ReadOnly ZIP As Integer = 98112

  Sub New(ByVal Name As String)

    Me.Name = Name

  End Sub
End Class
</code>```

答:
Yes, if nobody can write it, everyone is synced on its value.

Besides, you could make this integer constant (or shared readonly)


问:
Javascript: Safely upload a client data file
I'm (still) working on a template-based XML editing program. It's a GUI-based XML editor that only allows users to add certain tags and attributes based off the requirements. You can see the current version here for an idea.

Now, I'd like to allow users to upload their own data templates, but I'm concerned about potential XSS hacks. Currently, the template file is in Javascript object literal notation, which unsurprisingly is a security nightmare if the user can upload their own. I was thinking of using XML instead, but is there an even better alternative?

答:
As long as the only person to see what has been uploaded is the user who did that, then per definition it's not cross site scripting, and not a security issue. (The user can already break his own browser to his heart's content)

It might however become a usability issue, and you might want to protect the user from breaking your system through invalid templates.

Also, if you are thinking of possibly allowing users to share templates, then it might make sense to have a safe template system. This could however just mean that you parse the upload with a json parser (and possibly store the result of the parsing, not the original), and reject anything that fails the parser.


答: Yes, the code of Boost C++ Libraries is a great resource to learn from, if not one of the best on the Planet. However, for a novice, learning from Boost code may make learning curve very steep. If you really want to try reading Boost, start with some small and simple libraries like Boost.Array.</p>


问:
Is version history really sacred or is it better to rebase?
I've always agreed with Mercurial's mantra 1, however, now that Mercurial comes bundled with the rebase extension and it is a popular practice in git, I'm wondering if it could really be regarded as a "bad practice", or at least bad enough to avoid using. In any case, I'm aware of rebasing being dangerous after pushing.

OTOH, I see the point of trying to package 5 commits in a single one to make it look niftier (specially at in a production branch), however, personally I think would be better to be able to see partial commits to a feature where some experimentation is done, even if it is not as nifty, but seeing something like "Tried to do it way X but it is not as optimal as Y after all, doing it Z taking Y as base" would IMHO have good value to those studying the codebase and follow the developers train of thought.

My very opinionated (as in dumb, visceral, biased) point of view is that programmers like rebase to hide mistakes... and I don't think this is good for the project at all.

So my question is: have you really found valuable to have such "organic commits" (i.e. untampered history) in practice?, or conversely, do you prefer to run into nifty well-packed commits and disregard the programmers' experimentation process?; whichever one you chose, why does that work for you? (having other team members to keep history, or alternatively, rebasing it).

1 per Google DVCS analysis, in Mercurial "History is Sacred".

答:
The History is sacred, the Present is not. You can split your DVCS "tree" in two parts:

The past/history which contains an accurate view of how you have reached the current state of the code. This part of the history grow over time

The present which part you are currently working on to make you code evolve. This tip most part of the history have about always the same size.

Every code you released or used somehow is part of the past. The past is sacred because you need to be able to reproduce a setup or understand what introduced a regression. You shall never ever rewrite the past. In git you usually never rewrite anything once it is in master: master is the past part of the history. In Mercurial you have this public phase concept that keep track of the past part of your "tree" and enforce its immutability.

The present part of the code are the changeset you are currently working on. The feature branch that you are trying to make usable, bugfree and properly refactored. It is perfectly fine to rewrite it it is even a good idea because it make the past part more pretty, simple and usable. Mercurial track this in the draft phase.

So yes, please rebase if it improves your history. Mercurial will prevent you to shoot yourself in the foot if you are rebasing stuff you should not.


答:
Here's an excerpt from Curly's Law..

"A variable should mean one thing, and one thing only. It should not mean one thing in one circumstance, and carry a different value from a different domain some other time. It should not mean two things at once. It must not be both a floor polish and a dessert topping. It should mean One Thing, and should mean it all of the time."

The same principle applies to objects and their behaviour (replace the word 'variable' with 'object', and the word 'mean' with 'do').

"An object should do one thing, and one thing only. It should not do one thing in one circumstance, and exhibit a different behaviour from a different domain some other time. It should not do two things at once. It must not be both a floor polisher and a dessert topper. It should do One Thing, and should do it all of the time."


问:
Dual Inspection / Four Eyes Principle
I have the requirement to implement some kind of dual inspection or four-eyes principle as a feature of my software, meaning that every change of an object done by user A has to be checked by user B.

A trivial example would be a publishing system where an author writes an article and another has to proofread it before it is published.

I am a little bit surprised that you find nearly nothing about it on the net. No patterns, no libraries (besides cibet), no workflow solutions etc.

Is this requirement really so uncommon? Or am I searching for the wrong terms?

I am not looking for a specific solution. More for a pattern or best practice approach.

Update: the above example is really trivial. Let's add some more complexity to it. The article has been published, but it now needs an update. Putting the article offline for the update is not an option, but the update has to be proof read, too.

答:
I have worked for organizations where there were code reviews. I have also worked for organizations where a configuration control board would not approve changes to the code base until there was a review, and testing. The workflow required these steps before the code could be moved from the development machine, to the testing machine, and then to the production machine.

Look for information regarding software development for the space program, and for critical industries like Nuclear power, or medical instruments.

Title: Dual Inspection / Four Eyes Principle


答:
I am a little bit surprised that you find nearly nothing about it, [...] no workflow solutions [...]

Looking for "workflow framework" or "workflow engine" at google gives you some million hits. Add your favorite programming language like Java, C# or PHP to it and you will probably find some solutions for your environment.

Your requirement can be viewed as a formalized workflow, and when you are going to model it in some kind of software, you can indeed try to use a workflow engine for it. However, in many real-world cases it will be enough just to assign your data some kind of state information (for example, your document to be published could have the states "under construction", "written", "proof-read", and "published"; if you like, you can add some timestamp).

If that is all you need, and the communication between the author, the proof-reader and the publisher is not modeled in your software, then using a workflow engine for that requirement may be overkill.

Edit: when talking about proof-reading and publishing of documents:  the keywords which will help you may be "document management systems (DMS)" and "enterprise content management (ECM)". There is a whole part of the software industry producing DMS and ECM systems. Most of them allow explicit modeling of such a workflow you described.

Title: Dual Inspection / Four Eyes Principle

Body:
I have the requirement to implement some kind of dual inspection or four-eyes principle as a feature of my software, meaning that every change of an object done by user A has to be checked by user B.

A trivial example would be a publishing system where an author writes an article and another has to proofread it before it is published.

I am a little bit surprised that you find nearly nothing about it on the net. No patterns, no libraries (besides cibet), no workflow solutions etc.

Is this requirement really so uncommon? Or am I searching for the wrong terms?

I am not looking for a specific solution. More for a pattern or best practice approach.

Update: the above example is really trivial. Let's add some more complexity to it. The article has been published, but it now needs an update. Putting the article offline for the update is not an option, but the update has to be proof read, too.


问:
Is constantly looking for code examples a sign of a bad developer?
I am a CS student with several years of experience in C and C++, and for the last few years I've been constantly working with Java/Objective C doing app development and now I have switched to web development and am mainly focused on ruby on rails and I came to the realization that (as with app development , really) I reference other code way too much. I constantly Google functionality for lots of things I imagine I should be able to do from scratch and it's really cracked my confidence a bit.

Basic fundamentals are not an issue, I hate to use this as an example but I can run through javabat in both java/python at a sprint - obviously not an accomplishment and but what I mean to say is I have a strong base for the fundamentals I think?

I know what I need to use typically but reference syntax constantly. Would love some advice and input on this, as it has been holding me back pretty solidly in terms of looking for work in this field even though I'm finishing my degree. My main reason for asking is not really about employment, but more that I don't want to be the only guy at a hackathon not hammering out nonstop code and sitting there with 20 Google/github tabs open, and I have refrained from attending any due to a slight lack of confidence...

Is a person a bad developer by constantly looking to code examples for moderate to complex tasks?

答:
Looking for code examples is not a sign of bad developer. One rarely needs so few things to remember all the interfaces they need precisely, so it's natural to look things up and code examples are usually the reference that is easiest to use.

What you shouldn't do is copy&paste examples because they work there, so they must work here too, without understanding how they work. That usually leads to lot of useless bits that got copied along incidentally with result being hard to maintain because if you didn't know how it works when you wrote it, you won't know six months later either and won't be able to fix it.

But as long as you understand the code you are copying from an example, it's a valid way to get the work done faster, and that is usually good thing.


答:
If you code your solutions in a maintainable way and actually UNDERSTAND what you copy/paste/modify then there is no problem.

I die inside every time I ask a senior developer questions about why he did what and the answer is "I don't know, I copy pasted the code and it worked at that given time".

Title: Is constantly looking for code examples a sign of a bad developer?

Body:
I am a CS student with several years of experience in C and C++, and for the last few years I've been constantly working with Java/Objective C doing app development and now I have switched to web development and am mainly focused on ruby on rails and I came to the realization that (as with app development , really) I reference other code way too much. I constantly Google functionality for lots of things I imagine I should be able to do from scratch and it's really cracked my confidence a bit.

Basic fundamentals are not an issue, I hate to use this as an example but I can run through javabat in both java/python at a sprint - obviously not an accomplishment and but what I mean to say is I have a strong base for the fundamentals I think?

I know what I need to use typically but reference syntax constantly. Would love some advice and input on this, as it has been holding me back pretty solidly in terms of looking for work in this field even though I'm finishing my degree. My main reason for asking is not really about employment, but more that I don't want to be the only guy at a hackathon not hammering out nonstop code and sitting there with 20 Google/github tabs open, and I have refrained from attending any due to a slight lack of confidence...

Is a person a bad developer by constantly looking to code examples for moderate to complex tasks?


答:
Copy-paste blindly: bad.

Look up documentation, read code examples to get a better understanding: good.

I'd rather work with someone who looks up things all the time and makes sure everything works as intended than someone over-confident who thinks he knows it all but doesn't. But the worst is someone who doesn't bother understanding how things work, and just uncritically copies code from the web (and then when the bug reports start raining down is unable to fix anything properly).


答:
I think if you focus on coming up with moderate code yourself, your efficiency and productivity will increase. It probably takes more time to be looking up code, reading/understanding it, copying it your source, modifying it accordingly, etc..

If you come up with it yourself, it is most likely more adapted to your specific situation, and after a while these solutions will come faster to you than looking them up.

The way I look at it, is that it's like you want a second opinion on a certain solution, so you look up how others (on the Internet) do it. If you find yourself doing/wanting this too much, think of it as asking a colleague about what he/she thinks of a solution. If you ask your colleague a question every 15 minutes, he/she will probably be annoyed. Therefore you will ask fewer questions and try to come up with it yourself.

Visualize this when wanting to look things up on the Internet.


答:
I think a lot of it depends on how your mind works.  My memory stinks, so I'd much rather grab code that is as close to what I want as possible and rework it so it does the new job.  It serves as an example and a reminder of all the things I have to do.  For instance, I've used simple SQL for 20 years, but I can never remember the layout of a SELECT, or UPDATE statement.  (I think one needs parentheses, but I can't remember which.)  On the other hand, some few things I can remember; I can throw together a Java Iterator implementation with my eyes closed.

Most of the code I copy is my own, but I certainly copy other's when I'm learning something new.

I don't know about hackathons.  They may draw on a subset of programmers with photographic memories.  I'd give it a try and see.  If looking like an idiot bothers you, you shouldn't be programming.

I'd urge you understand, thoroughly, all the code you copy and modify, but, until I read some of the other answers, it never occurred to me someone might copy without understanding.  (I seem to be learning new vices all the time on this site...)


答:
Just like with the skill to program with/out API documentation, looking for code examples is a sign not of a bad programmer, but of one who lacks fluency...

...Here, I am talking about fluency. About being not just capable of something but fluent.

Do you know what it is to be fluent? It's when for someone looking at you it appears as if you code as you type...

...As if the right code simply flows from your fingers to the screen. As if you don't check the API docs, tutorials and manuals. Actually, you do check them all, but that's invisible because it's all in your head. You've got all the knowledge you need right there in your brain - charged, loaded and ready to use.

...That's fluent knowledge. It's when it takes you a minute to do what takes newbie an hour. It's worth the effort, really. It smells like victory.

...and the practice is to me the only reliable way to acquire fluency.


答:
Pure uncritical copy and paste as stated many times in these answers is bad.  But so is writing everything from scratch.  If it is not a critical component that is core to your business, look for a library or code snippet to do it first.  The exception to finding a snippet would be that the problem is very simple, you have a very clear picture on how to do it and if you're not using a library: that you will unlikely need to do anything more.

I know personally if I write something that is common, I'm likely to have some subtle bugs and perhaps one or two not so subtle ones without a lot of testing.  So I look for a similar solution, modify and test that to save some time on testing and developing over all.  Because in the end I'm responsible for delivering a product that works, is extensible, is on or under budget and meets deadlines.  Reusing code and libraries is a good step towards that objective.


答:
...I came to the realization that...I reference other code wayyyy too
  much. I constantly google functionality for lots of things I imagine I
  should be able to do from scratch and it's really cracked my
  confidence a bit.

Then stop. Head in the other direction for a while. Implement everything yourself, even if you know you could find exactly the thing you need in much less time.

What has happened is that your problem solving muscle (Latin name gluteus mojo) has atrophied from disuse, and you now avoid using it because you know how weak it is. You need to start building and toning that muscle just as you'd work on your biceps at the gym. Start with high repetitions and low resistance -- lots of easy problems. As you build some confidence, move on to longer, harder problems.

You'll gradually feel your mojo return and your need to rely on Google will diminish. Keep exercising that muscle, though, and make sure that you don't fall back into your old ways. Challenge yourself to solve a problem first and only then look up other solutions. Sometimes you'll find that others have found a better way to do the same thing, other times you'll decide that your own solution is better.

Is a person a bad developer by constantly looking to code examples for
  moderate to complex tasks?

A person who is unable to get anything done without finding examples is a bad developer. The thing is: you won't know whether you're able or not until you try.


答:
You're young, and you've worked with a lot of programming languages. I'm going to guess that you probably pick up on the new languages faster than the old ones. You still have not put enough time into a single language on a large enough application to develop fluency.

Are you looking for broad solutions every time like: the entire process of connecting a web grid to a database table or a smaller part like formatting the connections string (I have to look that up just about every time since I write about four a year.)?

You'll always be looking for references to the syntax of different lines of code or functions. The more you program, the more challenges and different environments and language changes you run into. If you need an entire tutorial everytime you do something, then you have a problem.


答:
If you understand the problem you are trying to solve, and understand how you want to solve it, looking up the correct syntax is not a big deal in my opinion.

I graduated about two years ago and was thrown to the wolves when I got my job.  I had to learn, maintain, and upgrade a large application written in a language I had never touched before.
I would get a bug report, go through the code and find out how I wanted to fix it, and then have to google examples of how to do the stuff I wanted in that language.

If you are getting things done, and understanding it enough to not produce unneeded churn, then you are probably OK.


答:
I had a professor that used to say he hated giving tests based on trying to retain a bunch of information you crammed the night before because you forget a lot of it afterwards anyway.  It is better to know your resources and that you can use them properly to find the information that you do not know.  I like to apply a similar principle to everything I do, including work.

I think the most important tools you have are your resources, as long as you use them properly.  So when I am writing code, I get as far as I can with my existing knowledge and then do research by asking other programmers or searching the Internet, in order to better understand the appropriate solution.  The knowledge will build over time and after a while you will naturally know and understand the skills better.  I am constantly looking things up whether I actually need the information or not, and I can honestly say I learn something new every day.


问:
Reporting in Visual Studio 2010 Express
I want to download Visual Studio 2010 Express Edition to learn all that is new in it. I find it insufficient as there is no Crystal Reports integration in it. Apart from that I want to learn other enterprise features that are bundled with the Professional Edition.

If I download the VS 2010 Professional Edition, it is just limited to 90 days. Is there any other alternative for learners?

Also, is there any FREE alternative for reporting in Express Edition.

答:
It depends on what you want to learn. Is Crystal Reports essential for you ?
Otherwise for learning .Net it is quite full featured. Granted it doesn't comer with built in MS Test framework but learning unit testing with NUnit and using the NUnit GUI runner is quite easy anyway. The other thing is source control integration but that can be done externally (e.g. Subversion and Tortoise) quite easily.

As a perspective when I was doing C++ programming on Visual Studio 6 there was no free edition to learn with. The express editions are a great option for today's students and learners.

Title: Reporting in Visual Studio 2010 Express


答:
These answers are pretty good. But you suffer from a much deeper problem than copy/paste or lack of "skill."

Comparison is lethal. The more you compare yourself with other people and let their talent affect the way you view yourself, the more you will shrivel up and die inside. You don't go to hackathons because of fear that people will see how untalented you are. And the only reason you think you're untalented is because you compare yourself with hackers who can bang out more code from scratch, faster.

Even if "Lines of Code per Minute" were a good metric for measuring skill, you need to accept the fact that there will always be better developers out there than you. And it's ok to show others that you lack in skill.

You do not need to be as good as, or better than, anyone else. You need to be content with the fact that you will always lack in some way, and that you're learning constantly. If you can't be happy with being an inferior developer, you'll NEVER be happy.

One more thing: your fear of rejection by people that you think are "superior" is exactly what is preventing you from rubbing shoulders with better developers and learning from them. So your fear prevents you from growing, which maintains your fear. Which prevents you from growing. See the cycle? You have to break the cycle somewhere.


答:
There's a theory of learning called the Kolb cycle (after the person who described it). The entries in this cycle are:

```<code>Concrete experience -> Reflective observation
    ^                        |
    |                        v
Active experimentation <- Abstract conceptualisation
</code>```

Different people like to start at different places in the cycle. So it's entirely possible to be learning by looking for samples (the reflective observation phase), then working out from those samples to the big picture via abstraction.

Other people will learn in different ways: some people like to start by trying (that is, with experimentation) then reflecting on what went right or wrong. The point is that these are just different ways of attacking the problem of learning things: none of them are incorrect.

Body:
There's a theory of learning called the Kolb cycle (after the person who described it). The entries in this cycle are:

Concrete experience -> Reflective observation
    ^                        |
    |                        v
Active experimentation <- Abstract conceptualisation

Different people like to start at different places in the cycle. So it's entirely possible to be learning by looking for samples (the reflective observation phase), then working out from those samples to the big picture via abstraction.

Other people will learn in different ways: some people like to start by trying (that is, with experimentation) then reflecting on what went right or wrong. The point is that these are just different ways of attacking the problem of learning things: none of them are incorrect.


问:
Create new variable or make multiple chained calls?
What is the best way to get this attributes, thinking in performance and code quality?

Using chained calls:

```<code>    name = this.product.getStock().getItems().get(index).getName();
    id = this.product.getStock().getItems().get(index).getId();
</code>```

Creating new variable:

```<code>    final item = this.product.getStock().getItems().get(index);
    name = item.getName();
    it = item.getId();
</code>```

I prefer the second way, to let the code cleaner. But I would like to see some opinions about it.

Thank you!

答:
Your chained approach isn't so bad (I admit I've done it for short and simple chains) but the question is what happens when one of the items in the middle of this get-chain you're trying to get returns null?

I recently had to debug something similar and it was a pain. I eventually split it up into something like this:

```<code>a = incomingObject.getA();
b = a.getB();
c = b.getC();
</code>```

...well actually the chain I was dealing with was 7 gets deep. And then once that was resolved (tried and caught) I discovered that a different method (not a get, but it was used like one) was throwing a webservice exception. Re-writing it as multiple statements was tedious but much easier to debug when things went wrong.

Body:
Your chained approach isn't so bad (I admit I've done it for short and simple chains) but the question is what happens when one of the items in the middle of this get-chain you're trying to get returns null?

I recently had to debug something similar and it was a pain. I eventually split it up into something like this:

a = incomingObject.getA();
b = a.getB();
c = b.getC();

...well actually the chain I was dealing with was 7 gets deep. And then once that was resolved (tried and caught) I discovered that a different method (not a get, but it was used like one) was throwing a webservice exception. Re-writing it as multiple statements was tedious but much easier to debug when things went wrong.


问:
Given the presentation model pattern, is the view, presentation model, or model responsible for adding child views to an existing view at runtime?
I am building a Flex 4 based application using the presentation model design pattern. This application will have several different components to it as shown in the image below.

The MainView and DashboardView will always be visible and they each have corresponding presentation models and models as necessary. These views are easily created by declaring their MXML in the application root.

```<code><s:HGroup width="100%" height="100%">
    <MainView width="75% height="100%"/>
    <DashboardView width="25%" height="100%"/>
</s:HGroup>
</code>```

There will also be many WidgetViewN views that can be added to the DashboardView by the user at runtime through a simple drop down list. This will need to be accomplished via ActionScript.

The drop down list should always show what WidgetViewN has already been added to the DashboardView. Therefore some state about which WidgetViewN's have been created needs to be stored. Since the list of available WidgetViewN and which ones are added to the DashboardView also need to be accessible from other components in the system I think this needs to be stored in a Model object.

My understanding of the presentation model design pattern is that the view is very lean. It contains as close to zero logic as is practical. The view communicates/binds to the presentation model which contains all the necessary view logic. The presentation model is effectively an abstract representation of the view which supports low coupling and eases testability. The presentation model may have one or more models injected in in order to display the necessary information. The models themselves contain no view logic whatsoever.

So I have a several questions around this design.

Who should be responsible for creating the WidgetViewN components and adding these to the DashboardView? Is this the responsibility of the DashboardView, DashboardPresentationModel, DashboardModel or something else entirely? It seems like the DashboardPresentationModel would be responsible for creating/adding/removing any child views from it's display but how do you do this without passing in the DashboardView to the DashboardPresentationModel?

The list of available and visible WidgetViewN components needs to be accessible to a few other components as well. Is it okay for a reference to a WidgetViewN to be stored/referenced in a model?

Are there any good examples of the presentation model pattern online in Flex that also include creating child views at runtime?

答:
MVP is somewhat open to interpretation.  I've written a large scale Flex 3 app with MVP so I'll give my input based on experience.

From the presenter's perspective it would be the view's responsibility to add subviews (because views are interfaced -- think console app replacement).  Nothing view-specific should exist in the presenter (ie. you should be able to unit test it having a mock view).

You are correct, the main view shouldn't be doing this either.

The presenter for that view would assign a WidgetPresenterCatalog (populated elsewhere in the application based on business logic) that the view can choose from.  The view would delegate all widget presentation, selection, and interaction to your DashboardView component.  That component selects from the catalog and displays them.

Problem #2 - how to display them!  The same way you connect a presenter and a view.  You have a class that knows how to couple a presenter and view and return the view for presentation.  Again, the presenter would pass this to the MainView and the MainView would provide it to the DashboardView.

Now your MainView and Presenter should be ultra lightweight and the widgets have very little surface area on them.


答:
Well I think that the second option you posted is cleaner, and sometimes the compiler might just do it for you in the background as an optimization. Because one pointer jump (or function call) is better that 5. So the code is cleaner and quicker.

So the only question you should ask yourself is: Could it be that one object in the chain changes its result? If the answer is No, just go with the short and nice way. If its Yes, its simply the correctness of the program.

Edit

I was just studying for an exam, and came across the Introduce Explaining Variable refactoring, which reminded me of your question. I think you will find the discussion there interesting. The main points are:

Your second option is the preferred one.

If Extract Method is applicable, do it instead. And create a general accessor method for the desired objects. (That way you have more readable code, and less copy-paste code)

Title: Create new variable or make multiple chained calls?

Body:
What is the best way to get this attributes, thinking in performance and code quality?

Using chained calls:

```<code>    name = this.product.getStock().getItems().get(index).getName();
    id = this.product.getStock().getItems().get(index).getId();
</code>```

Creating new variable:

```<code>    final item = this.product.getStock().getItems().get(index);
    name = item.getName();
    it = item.getId();
</code>```

I prefer the second way, to let the code cleaner. But I would like to see some opinions about it.

Thank you!


答:
The best way to learn what you don't know: google it!  I feel you are right on par with most developers. Put the inferiority complex in your backpack and go in with an open mind.

Don't be afraid to ask questions, do research on Google, try and fail. It's all part of it.