问:
What is a good measure of testing/tester efficiency?
I am about to participate in a discussion with management regarding measuring our testing efficiency as a QA organization. The main reason behind this is that half of our team is contracted out and our business would like to provide some metrics of how effective/efficient we are, so that we have basis data on which to negotiate contract parameters with the service agreement of our contractors.

I have poked around a little and most of the opinion I have found on this subject revolves around developer efficiency: lines of code, story points delivered, defects introduced, etc.

But what about testers? Our testing is mostly requirements based, and a mix of manual, semi-automated, and automated testing (not because we haven't gotten around to automating everything, but because some things are not automatable in our test system).

答:
The company I work uses a number of QA metrics.

The one that I feel is most relevant is code coverage. A tool like EMMA works great as they write thorough automated tests in addition to their manual tests.

Whatever you do, do not focus on number of tests.
That's about as useful as LOC per day.


答:
QA should be measured by two main metrics: how many bugs get past QA to be found in the field? What are their severity?

You might be able to ding QA for finding severe bugs closer to release than dev-complete. You might be able to ding QA for not completing testing by their estimated completion date (per feature).

Though in the end, I fear you'll spend more money trying to measure the effectiveness of your contracting staff than savings gained by using a contracting staff...

ContentLicense: CC BY-SA 3.0

Title: What is a good measure of testing/tester efficiency?

Body:
I am about to participate in a discussion with management regarding measuring our testing efficiency as a QA organization. The main reason behind this is that half of our team is contracted out and our business would like to provide some metrics of how effective/efficient we are, so that we have basis data on which to negotiate contract parameters with the service agreement of our contractors.

I have poked around a little and most of the opinion I have found on this subject revolves around developer efficiency: lines of code, story points delivered, defects introduced, etc.

But what about testers? Our testing is mostly requirements based, and a mix of manual, semi-automated, and automated testing (not because we haven't gotten around to automating everything, but because some things are not automatable in our test system).


答:
There are a few metrics that we used at my last job to evaluate QA:

Number of bugs found. I hate this one. It's like "Number of lines of code written" for a developer.

Number of automated test cases produced.

Percentage of total application covered in functional testing.

Number of bugs found in staging vs production.

In the end, your QA team's job is to find the bugs before they get out in the wild. Their metrics should be based on actually achieving that goal. If there is a low coverage of test cases, minimal amount of automated tests, and a high rate of bugs in production, then they aren't doing a good job. However, if they have a good track record of finding the bugs long before they hit prod, their metrics should be pretty high.


问:
Alternative to "Passing/Broken build" indicator?
When having a continuous integration executing the tests at each commit, a common best practice is to have all the tests passing at all times (aka "do not break the build").

I find some problems with that:

For example one cannot help an open source project by creating tests corresponding to tickets. I know if I propose a Pull Request to an open source project containing failing test, the build will be marked as failed and the project will not want that merged into its repository because it would "break the build".

And I don't believe it is a bad thing to have failing tests in your repo, it's like having open issues in your tracker. These are just things waiting to be fixed.

The same goes in a company. If you work with TDD, you can't write tests, commit and then write the logic code that fulfills the test. That means if I have written 4-5 tests on my laptop, I can't commit them before going on holidays. Nobody can take back my work. I can't even "share" them with a colleague except by sending them by email for example. It also prevents working with one person writing the tests, the other one writing the model.

All that to say, am I misusing/misunderstanding the build process/continuous integration? It seems to me that "passing"/"not passing" is a too narrow indicator.

Is there a way to make continuous integration and TDD compatible?

Maybe there is a standard solution/practice to distinguish "new tests" (that can fail) and "regression tests" (that should not fail because they used to work)?

答:
You could consider two different CI build "concepts".

Regular CI builds.  The regular CI build should compile and run only those tests for which code has been written to make them pass, so that CI reports of test pass/fails is a clear, unambiguous indicator of regression against the previously accepted state of the code.

A "future" CI build.  This build compiles and runs only those tests for which no code has been written specifically to make them pass.  There can be several reasons to have such a test:

Tests can added for specific failure cases from the issue tracker, for which no fix has been attempted yet.  It's clearly useful to already have a codified, running test for an issue even without a fix.

Tests added for new required functionality that has not been implemented yet.

Often it's easier to know how to test a failure or feature than to know how to implement the feature or fix, and separating the two steps by committing the test to source control can be useful to ensure no information is lost.

As in "standard" CI, in the regular development regime the team would only be looking at the daily build results of the regular build.

The team can also keep an eye on the evolution of test cases from the "future" CI build - specifically to see if any changes made for the regular CI actually fix issues from the "future" build, which can be an indication of an important underlying issue or design improvement.

Finally, if a team member has extra time on their hands they could take a look at fixing one of the issues from "future", and if they succeed migrate it to "regular" (while updating the issue tracker status).


问:
Whats the greatest most impressive programing feat you ever witnessed?
Everyone knows of the old adage that the best programmers can be orders of magnitude better than the average. I've personally seen good code and programmers, but never something so absurd. So the questions is, what is the most impressive feat of programming you ever witnessed or heard of?

You can define impressive by:

The scope of the task at hand e.g. John single handedly developed the framework for his company, a work comparable in scope to what the other 200 employed were doing combined.

Speed e.g. Stu programmed an entire real time multi-tasking app OS on an weekened including  its own C compiler and shell command line tools

Complexity e.g. Jane rearchitected our entire 10 millon LOC app to work in a cluster of servers. And she did it in an afternoon.

Quality e.g. Charles's code had a rate of defects per LOC 100 times lesser than the company average. Furthermore he code was clean and understandable by all.

Obviously, the more of these characteristics combined, and the more extreme each of them, the more impressive is the feat.

So, let me have it. What's the most absurd feat you can recount? Please provide as much detail as possible and try to avoid urban legends or exaggerations. Post only what you can actually vouch for.

Bonus questions:

Was the herculean task a one-of, or did the individual regularly amazed people?

How do you explain such impressive performance?

How was the programmer recognized for such awesome work?

答:
My training supervisor at Gemplus (now Gemalto) wrote the first JavaCard interpreter and OS during his own 3 month undergraduate training period. He single-handedly produced code from the spec. To produce the v.2, Gemplus put up a 30+ men team, without the guy, which worked for more than a year. When done but unable to get decent performance, they called him for help, and in a few days he and a colleague of his pointed out dozens of bottlenecks.

Java Card is a subset of Java intended to run in very small devices. His implementation ran in smartcards, which have a few MHz clock and 2 or 3 KB RAM.

Just for fun: another personal everyday feat of his was diving into a work trance, answering none of the questions we trainees yelled in the room, and then, suddenly 2 hours later popping alive again when his work was done and answering the 5 or 10 questions in a row.

ContentLicense: CC BY-SA 2.5


问:
In good Scrum, when and how should the ideation and story writing occur?
It seems like most of the Scrum articles and books that I've read as well as the lectures I've heard have very little to say about the process of creating the items on the backlog. How should a team on a medium or large project (i.e. more than a few team members) go about creating and detailing the items on the backlog?  When and how should the ideation and story writing occur? Who should be involved and when?  When should team members (other than the product owner, of course) join the process?  How much of the team is needed?

Note that I am not asking about how a small group would create a user story or other backlog item from ideas.  I'm asking more about when and how this ideation and story writing should occur and who should be involved.  How can we be more Agile in the ideating/story writing stages?

答:
Creation of the backlog is defined as an input to scrum.  A few things are said about what it should look like, but not about how to get there.  The most agile way is really to figure out what works for your company.

Our company starts out with a giant prioritized list made by product management with input from the product owners.  This list is at an extremely high level, like an entire new product or a major feature, a few dozen user stories worth of work spread across two or three scrum teams.  They prioritize those features based on what will make us the most money the soonest, or keep us from losing money.

They occasionally ask the scrum teams for a very rough estimate, with a resolution of tens of weeks, on how long it will take us.  If that estimate is large, they will reduce the scope until it meets customer needs, or decide to do something else first.

Once every ten weeks, they assign out the highest priority epics to the scrum teams.  The teams break them down to the user story level, assign story points, coordinate dependencies on other teams, and put the stories in order.  At that point we have a "real" backlog per team.  Management reviews that backlog to make sure the smaller milestones are appropriate, that we are meeting the business needs, and that the estimates work with their larger plan.  Usually they accept the judgement of the individual teams at that point.  Sometimes, the detailed backlog creation reveals problems that management has to rethink at the higher levels.

There are also non big picture items on our backlog that the scrum teams create themselves based on only general ongoing guidance from management.  These are things like bugs or support issues that come up, tools we think would help improve productivity, or refactoring.  The rule on our scrum team is anyone can create a user story for any reason at any time, but the product owner decides when it is high enough priority to be pulled into a sprint.

We based our approach on Dean Leffingwell's Scaling Software Agility: Best Practices for Large Enterprises.  He actually came to our company and trained us when we first started agile, but in true agile form, we've evolved our processes to work better for our company, and continue to do so.


问:
Why Bootstrap 3 changes camelCase to dashes - is it more readable?
I'm wondering what's the reasoning behind Bootstrap's decision to change all camel case names into hyphenated names in v3.0. I searched on Google, and looked in a few books, but I can only find opinions one way or the other - no hard data.

Are there any studies that suggest camel case variable names are more readable than dashes, or is this just a matter of personal preference?

答:
I'm stealing Robert's comment:

There are lots of things in software design and development that are driven, not by the result of formal studies, but by convention and pragmatism. That's why defacto standards exist; they arise out of everyday use, and many people discovering over time what works and what doesn't.

When it comes to choosing between camelCase and hyphenated names this is particularly true, as studies are inconclusive:

To camelCase or under_score - Dave Binkley, Marcia Davis, Dawn Lawrie, Christopher Morrell

The study described in this paper shows that although those without training take longer to recognize identiﬁers in the camel case style, all subjects are more accurate when identifying a camel-cased identiﬁer. In addition, subjects trained to use camel casing take less time to identify a camel-cased identiﬁer than an underscore identiﬁer.

The next step is to consider higher-level tasks in more realistic settings. One task would investigate the impact of camel casing versus underscores when reading blocks of code. For example, subjects might be asked to search for a particular identiﬁer. Another task would ask subjects to read natural language paragraphs modiﬁed to use camel casing or underscores. This would enable more direct comparisons with previous work done in psychology such as Epelboim et al.

An Eye Tracking Study on camelCase and under_score Identifier Styles - Bonita Sharif, Jonathan Maletic

An eye-tracking study analyzing the effect of identifier style (camel-case and underscore) on accuracy, time, and visual effort is presented with respect to the task of recognizing a correct identifier, given a phrase.  Visual effort is determined using six measures based on eye gaze  data namely: fixation counts and durations.  Although, no difference was found between identifier styles with respect to accuracy, results indicate a significant improvement in time and lower visual effort with the underscore style. The interaction of Experience with Style indicates that novices benefit twice as much with respect to time, with the underscore style.  This implies that with experience or training, the performance difference between styles is reduced.  These results add to the findings of Binkley et al.’s study.  Future work includes conducting more eyetracking studies (with a larger subset of identifiers and larger subject sample), on reading source code consisting  of both identifier styles, in the context of a specific task such as debugging.  Another possible direction is to determine if there is an advantage for a programmer to change their current style to what is determined to be a better  overall style.

Note: The study referenced here as Binkley et al. is the first study I linked to.


问:
Design Pattern for enterprise application
I read few articles about composite pattern and I want to know whether its applicable in following situation,

I found that "A Composite Entity object can represent a coarse-grained
object and all its related dependent objects"

```<code>public class PatientRegistrationDTO
{
    public string RegistrationNo;
    public string ID;
    public DateTime AdmitDate;
}

public class PersonDTO
{
     public string ID{ get; set; }
     public string FullName { get; set; }
     public string FirstName { get; set; }
}
</code>```

by using these two objects I need to create

```<code>public class Patient
  {
        public string ID{ get; set; }
        public string FullName { get; set; }
        public DateTime AdmitDate;
  }
</code>```

Can I use Composite pattern for enterprise applications in here?

Is it possible for me to add some class like below?

```<code>public class PatientDTO
{
    public static Patient ConvertToEntity(PatientRegistrationDTO pregDTO, PersonDTO person)
    {
        Patient p = new Patient();
        p.ID= pregDTO.ID;
        p.FullName = person.FullName;
        p.AdmitDate = pregDTO.AdmitDate;

        return p;
    }
}
</code>```

答:
Your classes are allowing data to be modified by external forces via the public members. Since these are supposed to be Entity objects, enforce the immutability of the data. If you need to change a piece of the data, throw away the stale object and create a new one with the new data. Example:

```<code>public sealed class PatientRegistrationDTO
{
    private readonly string registrationNo;

    private readonly string id;

    private readonly DateTime admitDate;

    public PatientRegistrationDTO(string registrationNo, string id, DateTime admitDate)
    {
        this.registrationNo = registrationNo;
        this.id = id;
        this.admitDate = admitDate;
    }

    public string RegistrationNo
    {
        get
        {
            return this.registrationNo;
        }
    }

    public string ID
    {
        get
        {
            return this.id;
        }
    }

    public DateTime AdmitDate
    {
        get
        {
            return this.admitDate;
        }
    }
}

public sealed class PersonDTO
{
     private readonly string id;

     private readonly string fullName;

     private readonly string firstName;

     public PersonDTO(string id, string fullName, string firstName)
     {
         this.id = id;
         this.fullName = fullName;
         this.firstName = firstName;
     }

     public string ID
     {
         get
         {
             return this.id;
         }
     }

     public string FullName
     {
         get
         {
             return this.fullName;
         }
     }

     public string FirstName
     {
         get
         {
             return this.firstName;
         }
     }
}
</code>```

And, finally, I would use composition to do this:

```<code>public sealed class Patient
{
    private readonly PatientRegistrationDTO patientRegistration;

    private readonly PersonDTO person;

    public Patient(PatientRegistrationDTO patientRegistration, PersonDTO person)
    {
        // Appropriate nullity checks as needed here.
        this.patientRegistration = patientRegistration;
        this.person = person;
    }

    public string ID
    {
        get
        {
            return this.patientRegistration.ID;
        }
    }

    public string FullName
    {
        get
        {
            return this.person.FullName;
        }
    }

    public DateTime AdmitDate
    {
        get
        {
            return this.patientRegistration.AdmitDate;
        }
    }
}
</code>```

Body:
Your classes are allowing data to be modified by external forces via the public members. Since these are supposed to be Entity objects, enforce the immutability of the data. If you need to change a piece of the data, throw away the stale object and create a new one with the new data. Example:

public sealed class PatientRegistrationDTO
{
    private readonly string registrationNo;

    private readonly string id;

    private readonly DateTime admitDate;

    public PatientRegistrationDTO(string registrationNo, string id, DateTime admitDate)
    {
        this.registrationNo = registrationNo;
        this.id = id;
        this.admitDate = admitDate;
    }

    public string RegistrationNo
    {
        get
        {
            return this.registrationNo;
        }
    }

    public string ID
    {
        get
        {
            return this.id;
        }
    }

    public DateTime AdmitDate
    {
        get
        {
            return this.admitDate;
        }
    }
}

public sealed class PersonDTO
{
     private readonly string id;

     private readonly string fullName;

     private readonly string firstName;

     public PersonDTO(string id, string fullName, string firstName)
     {
         this.id = id;
         this.fullName = fullName;
         this.firstName = firstName;
     }

     public string ID
     {
         get
         {
             return this.id;
         }
     }

     public string FullName
     {
         get
         {
             return this.fullName;
         }
     }

     public string FirstName
     {
         get
         {
             return this.firstName;
         }
     }
}

And, finally, I would use composition to do this:

public sealed class Patient
{
    private readonly PatientRegistrationDTO patientRegistration;

    private readonly PersonDTO person;

    public Patient(PatientRegistrationDTO patientRegistration, PersonDTO person)
    {
        // Appropriate nullity checks as needed here.
        this.patientRegistration = patientRegistration;
        this.person = person;
    }

    public string ID
    {
        get
        {
            return this.patientRegistration.ID;
        }
    }

    public string FullName
    {
        get
        {
            return this.person.FullName;
        }
    }

    public DateTime AdmitDate
    {
        get
        {
            return this.patientRegistration.AdmitDate;
        }
    }
}


问:
What is the point of using lists over vectors, in C++?
I've run 3 different experiments involving C++ lists and vectors.

Those with vectors proved more efficient, even when a lot of insertions in the middle were involved.

Hence the question: in which case do lists make more sense than vectors?

If vectors seem more efficient in most cases, and considering how alike their members are, then which advantages are left for lists?

Generate N integers and put them in a container so that the container remains sorted. The insertion has been performed naively, by reading elements one by one and inserting the new one right before the first larger one.

With a list, time goes through the roof when dimension increases, compared to vectors.

Insert N integers at the end of the container.

For lists and vectors, time increased by the same order of magnitude, though it was 3 times faster with vectors.

Insert N integers in a container.

Start timer.

Sort the container using list.sort for lists, and std::sort for vectors.
Stop timer.

Again, time increases by the same order of magnitude, but it is in average 5 times faster with vectors.

I might continue to perform tests and figure out a couple of examples where lists would prove better.

But the joint experience of you guys reading this message might provide more productive answers.

You might have come across situations where lists were more convenient to use, or performed better?

答:
According to Bjarne Stroustrup himself, vectors should always be the default collection for sequences of data. You can choose the list if you want to optimize for insertion and deletion of elements, but normally you shouldn't. The costs of the list is slow traversal and memory usage.

He talks about this in this presentation.

At about 0:44 he talks about vectors vs. lists in general.

Compactness matters. Vectors are more compact than lists. And
  predictable usage patterns matters enormously. With vectors you have
  to shove a lot of elements over but caches are really, really good at
  that. ... Lists don't have random access. But when you traverse a
  list, you keep doing random access. There's a node here, and it goes
  to that node, in memory. So you are actually random accessing your
  memory, and you are maximizing your cache misses, which is exactly the
  opposite of what you want.

At about 1:08, he is given a question about this issue.

What we should see it that we need a sequence of elements. And the
  default sequence of elements in C++ is the vector. Now, because that
  is compact and efficient. Implementation, mapping to hardware,
  matters. Now, if you want to optimize for insertion and deletion - you
  say, 'well, I don't want the default version of a sequence. I want the
  specialized one, which is a list'. And if you do that, you should know
  enough to say, 'I'm accepting some costs and some problems, like slow
  traversals and more memory usage'.


答:
Number of test written is useless, and a high number of bugs found can be a measure of poor development rather than efficient QA.

Automation measures (code coverage, feature coverage...) can be good, but I think they're a more help to development (as a developer, will I know if I break something accidentally) than customers (i want to do that and it doesn't work).

Since quality is good if customers don't encounter problems, so a good measure of the effectiveness (not the efficiency) of a QA team and process is the measure of bugs found by customers that haven't been found by QA.

The main problem with that metric is that there can be a considerable delay between the work done and when you start having meaningful numbers.


问:
Rigorous Definition of Syntactic Sugar?
It seems like in language holy wars, people constantly denigrate any feature they don't find particularly useful as being "just syntactic sugar".  The line between "real features" and "syntactic sugar" tends to get blurred in these debates.  What do you believe is a reasonable and unambiguous definition of syntactic sugar that avoids it being defined as any feature the speaker/writer doesn't find useful?</p>

答:
"Syntactic sugar" is not a rigorously-defined term. Depending on who you ask, you will most likely get one of the following sorts of definitions:

No true Scotsman approach. Things I like are real programming, and things I don't like are syntactic sugar.

Everything after MIPS was syntactic sugar, and even some of those instructions probably aren't necessary.

Anything that makes programming easier for somebody somewhere is useful and not syntactic sugar. Since a feature wouldn't have been added if nobody found it useful in any circumstance, it follows that every existing feature is not syntactic sugar. Hypothetical features may be syntactic sugar, until someone decides that feature is useful to them.

Title: Rigorous Definition of Syntactic Sugar?


问:
Why does Clang/LLVM warn me about using default in a switch statement where all enumerated cases are covered?
Consider the following enum and switch statement:

```<code>typedef enum {
    MaskValueUno,
    MaskValueDos
} testingMask;

void myFunction(testingMask theMask) {
    switch (theMask) {
        case MaskValueUno: {}// deal with it
        case MaskValueDos: {}// deal with it
        default: {} //deal with an unexpected or uninitialized value
    }
};
</code>```

I'm an Objective-C programmer, but I've written this in pure C for a wider audience.

Clang/LLVM 4.1 with -Weverything warns me at the default line:

Default label in switch which covers all enumeration values

Now, I can sort of see why this is there: in a perfect world, the only values entering in the argument theMask would be in the enum, so no default is necessary. But what if some hack comes along and throws an uninitialized int into my beautiful function? My function will be provided as a drop in library, and I have no control over what could go in there. Using default is a very neat way of handling this.

Why do the LLVM gods deem this behaviour unworthy of their infernal device? Should I be preceding this by an if statement to check the argument?

答:
Here's an alternative suggestion:

The OP is trying to protect against the case where someone passes in an int where an enum is expected. Or, more likely, where someone has linked an old library with a newer program using a newer header with more cases.

Why not change the switch to handle the int case? Adding a cast in front of the value in the switch eliminates the warning and even provides a degree of hint about why the default exists.

```<code>void myFunction(testingMask theMask) {
    int maskValue = int(theMask);
    switch(maskValue) {
        case MaskValueUno: {} // deal with it
        case MaskValueDos: {}// deal with it
        default: {} //deal with an unexpected or uninitialized value
    }
}
</code>```

I find this much less objectionable than the assert() testing each of the possible values or even making the assumption that the range of enum values is well-ordered so that a simpler test works. This is just an ugly way of doing what default does precisely and beautifully.

ContentLicense: CC BY-SA 4.0

Body:
Here's an alternative suggestion:

The OP is trying to protect against the case where someone passes in an int where an enum is expected. Or, more likely, where someone has linked an old library with a newer program using a newer header with more cases.

Why not change the switch to handle the int case? Adding a cast in front of the value in the switch eliminates the warning and even provides a degree of hint about why the default exists.

void myFunction(testingMask theMask) {
    int maskValue = int(theMask);
    switch(maskValue) {
        case MaskValueUno: {} // deal with it
        case MaskValueDos: {}// deal with it
        default: {} //deal with an unexpected or uninitialized value
    }
}

I find this much less objectionable than the assert() testing each of the possible values or even making the assumption that the range of enum values is well-ordered so that a simpler test works. This is just an ugly way of doing what default does precisely and beautifully.


问:
What are the criteria for evaluating an ORM for.NET?
I'm looking at evaluating ORMs.

I've used SubSonic, Linq-to-SQL and Entity Framework. I've got a team of developers ranging from juniors to seniors.

What are the criterias for evaluating an ORM for.NET?

答:
NHibernate (+ FluentNHibernate) would be the default option for me. It is very flexible, extensible and robust. It's got a huge amount of users and it's very actively maintained. The downside is the steep learning curve. </p>

<p>MindScape's LightSpeed is simple and user friendly, but still fairly flexible and capable. It has a designer surface like L2S/EF and a UnitOfWork implementation. </p>

Body:
NHibernate (+ FluentNHibernate) would be the default option for me. It is very flexible, extensible and robust. It's got a huge amount of users and it's very actively maintained. The downside is the steep learning curve.

MindScape's LightSpeed is simple and user friendly, but still fairly flexible and capable. It has a designer surface like L2S/EF and a UnitOfWork implementation.


问:
In Java, should private helpers go above or below public methods?
I've noticed that a coworker and I have opposite practices regarding the ordering of methods in our Java classes. One of us begins a class with its major public methods, and then put all of the private helpers afterwards. The other one of us makes sure that public methods are at the very end.

Clearly, this is just a style issue and there is no right answer. However, before we decide that this matter is just another Yooks vs Zooks fight and just pick one or the other arbitrarily, I was wondering if perhaps there was a standard Java style guide recommendation or some practical reason why one approach is better than the other.

答:
I tend to prefer seing my classes where members are listed in order of importance/visibility (here by importance I mean that have direct impact on the public interface).

Thus private functions have a tendency to be pushed down.

There are exceptions to this where I will also tend to group similar functionnalities together so it is still possible to find small private functions intermingled with the public stuff.

This is, as you said, a matter of taste.

However when working on code that is not mine I will try nd follow whatever conventions that is used in the project.

One nice way I found to keep track of this is to (assuming here you work with Eclipse) create a code formatting configuration and export it with the project source and commit it to source control.  That way the latest and greatest in code convention for the project is a mere few clicks away to setup and making a habbit of CTRL-SHIFT-F jufore you commit will prevent a lot of arguments.

Added bonus of using automatic formatters is that you can do things in whatever convention that makes you happy and just format the code before commit.  YMMV depending on said convention and formatting tool.


答:
While it does come down to preference normally, you should certainly try to adhere to a common standard within your organization. So whatever you decide, pick a standard and universally adopt it.

As for which to choose, if you were to follow the suggestions as offered in Clean Code, you would be able to read down the file from top to bottom like a newspaper article, which would naturally suggest that helper methods appear after the methods they are helping. This would lead to maximum readability of the code structure. So if you were to have

```<code>public void doSomething()
{
     helpMe();
     helpMeAgain();
}
</code>```

Your file would be structured as

```<code>public void doSomething() { }
private void helpMe() { }
private void helpMeAgain() { }
</code>```

Another side effect of this is that you discover your helpers have their own helpers, and it helps you figure out what you really have is another class living within your file, and you can cleanly refactor to extract it to its own class since those methods are already grouped together in order. But that's a secondary benefit.

Title: In Java, should private helpers go above or below public methods?

Body:
I've noticed that a coworker and I have opposite practices regarding the ordering of methods in our Java classes. One of us begins a class with its major public methods, and then put all of the private helpers afterwards. The other one of us makes sure that public methods are at the very end.

Clearly, this is just a style issue and there is no right answer. However, before we decide that this matter is just another Yooks vs Zooks fight and just pick one or the other arbitrarily, I was wondering if perhaps there was a standard Java style guide recommendation or some practical reason why one approach is better than the other.

Body:
While it does come down to preference normally, you should certainly try to adhere to a common standard within your organization. So whatever you decide, pick a standard and universally adopt it.

As for which to choose, if you were to follow the suggestions as offered in Clean Code, you would be able to read down the file from top to bottom like a newspaper article, which would naturally suggest that helper methods appear after the methods they are helping. This would lead to maximum readability of the code structure. So if you were to have

public void doSomething()
{
     helpMe();
     helpMeAgain();
}

Your file would be structured as

public void doSomething() { }
private void helpMe() { }
private void helpMeAgain() { }

Another side effect of this is that you discover your helpers have their own helpers, and it helps you figure out what you really have is another class living within your file, and you can cleanly refactor to extract it to its own class since those methods are already grouped together in order. But that's a secondary benefit.


答: Public methods are the interface of the class.  Someone interested in using your class will only care about the interface. From the perspective of a class user, it would be useful to have the public methods first to reduce scrolling.</p>


答:
In C and C++, helper methods are often put first because then you don't need a declaration.  A lot of people carried that habit over into other languages where it doesn't matter.

I prefer the public methods on top because usually when I open a file I'm looking for its public interface.  I don't want to have to scroll past all the implementation details.  It also happens to be the most popular style I've seen, so there's that to be said for convention.


答:
I like order of methods in a class to be based on readability and context, not visibility.

i.e. an 'open' method probably belongs before a 'close'. If two public methods 'a' and 'b' call a private 'c', and they're the only ones calling it - then I like 'c' to be next to them.

I don't think a convention of method ordering based on visibility is a good thing.


问:
Is it wise to include something like OpenSSL or GnuTLS with a project in a repository?
I am currently working on a project that makes use of the OpenSSL library for secure communications. Since this library is a requirement for building the project, I am considering including it in the project's repository. Here are the pros and cons as I see them:

Pros:

Self-contained build - with one exception, everything needed for building the project is contained in the repository. It would be nice if the user didn't need to go through the trouble of installing and configuring the development headers / libraries for OpenSSL.

Cons:

Security concerns - it goes without saying that the only version of OpenSSL that anyone should be using is always the latest. As soon as a new release is issued, I will need to update the version of OpenSSL in the project's repository.

So the question boils down to this:

Is it wise to include a security library with the project that we need to always ensure gets updated whenever a new release is issued?

答:
The main reason it is not wise to bundle your own copy of OpenSSL (or other commonly used libraries) is that your project will not be the only thing your end users install that uses those libraries.

If you depend on the installed system version of OpenSSL on the host where you run, your users need only update that copy of OpenSSL when a new security issue in OpenSSL is discovered.  If you bundle your own copy, they need to update the system copy (for all of the other software they use that links against it) and your application.  And that, of course, is assuming they realize -- and remember -- that your application is not using the system copy of OpenSSL.

Worse, to get a copy of your application which links with the new version of OpenSSL, they have to rebuild (or re-download) not just your copy of OpenSSL, but the rest of your application.  In contrast, if you use the system OpenSSL libraries, then as long as the version of OpenSSL they are upgrading to is a new minor release, with no ABI changes since the version they had been using, they need only rebuild OpenSSL, not your application.

This only gets worse, of course, if other third-party applications they are using also have their own private copies of OpenSSL...


问:
User session timeout handling in SaaS apps - discussing several approaches
I know this has a great chance of being marked as duplicate, but couldn't find exactly what I'm looking for

This is a common problem and I'm sure it has some well defined best practice solution

Background

A single page SaaS app, has lot's of drag and drop, user can
interact with it without much server communication for periods of
time

Server session only holds user object, using a non persistent session cookie

Session expires on the server after X hours

Some things are loaded only during log-in

Problem

User works on the app, when done, user doesn't log out, just keeps the browser open

User comes back after more than X hours (session is invalidated on server)

User interacts with the app without needing a server connection (drags and drops things, text edits...)

Only on the next server interaction (let's assume there is no auto save) user is thrown to login page and loses some of their work

Possible solutions

Here are some solutions I have in mind, would like to hear if there are any others, and if there is anything fundamentally wrong with any of them.

1. Never log the user out

How? either keep a long session, keep a persistent cookie, or javaScript "keep alive" ping

Pros: user doesn't need to worry about anything, fixes the problem for them

Cons: not PCI compliant, not secure, and needs development changes, e.g. things loaded to session only on user log in need to move to either a pub sub model (listening on event changes) or have cache timeout.

2. Local Storage

How? use new local storage to temporarily store state if logged out, redirect to login page, persist once logged in

Pros: Also base for "work offline" support, not just handling session timeout

Cons: harder to implement, need to do state merge of data tree, not all browsers support

3. Auto save

Every user action that changes the model, should persist immediately (or via some sort of a client side queue), e.g. if they check a checkbox,  change a text field, or drag and drop something, once they are done, persist the changes.

How? Use an MV** framework (Backbone.js / Knockout.js / Ember.js / Angular.js etc) to bind the model, and persist on changes.

Pros: Seems like a clean solution, session is active as long as user is active, no client side work is done without persisting it.

Cons: The last action user is doing after a session timeout is lost.

4. Log the user out after session expires

this can have several approaches

Ask the server "has session expired" - this is a bit of a catch 22 / Schrodinger's cat, as the mere question to the server extends the session (restarts the timeout),

How? Either have a server that supports such question (I don't know of any, but I come form Java land)  or, one can just keep a table of session IDs, and last access time manually, and ask the server by passing the session ID as a parameter instead of the cookie, I'm not sure if this is even possible, but it sounds dangerous, insecure and bad design whatsoever.login page, persist once logged in

Pros: If there was such native support in servers, sounds like a clean, legitimate question (asking if user X still has a session or not without renewing it if they do)

Cons: If the server doesn't support it (and again, I don't know if any server or framework has this functionality) then the workaround has huge security risks potentially.

One workaround I've heard is have a short session on the server side, and a keep alive client side ping, that has a maximum number of pings

How? Short session on server, client pings every sessionTimeOut/2, has max retries of Y.

Pros: Kind of fixes the problem, quick and dirty

Cons: Feels like a hack, handling the session renewal yourself instead of letting the server do it

Client side timer

How? Have a timer on the client side and sync it with the server one by restarting it on every request to be equal to the max server session timeout minus some padding, after user is not sending any request to the server, UI shows a "sessions is about to time out, do you want to continue?" (like you have on online banking )

Pros: Fixes the problem

Cons: Can't think of any except the need to make sure the sync works

The Question

I'm probably missing something in the above analysis, might have some silly mistakes, and I would like your help to correct them. What other solutions I can have for this?

答:
One workaround I've heard is have a short session on the server side, and a keep >alive client side ping, that has a maximum number of

How? Short session on server, client pings every sessionTime/2, has max >retries of Y.
     Pros: Kind of fixes the problem, quick and dirty
     Cons: Feels like a hack, handling the session renewal yourself instead of >letting the server do it

This is in my opinion the best solution. Why you consider it a "dirty hack"?

It makes exactly what have to be done. While the user works with the program the session will stay opened.

After the user stops to work with the program, the session will be closed.

Simple enough to be implemented.

Exactly what is needed, if I understood the question right.


答:
I think the most common simple solution is where you set a timer on the client end that shows a message after a certain portion of the normal timeout window has passed then forcibly logs them out right before the session would expire anyway if they take no action.

Local storage and auto-save introduce some issues with transactions and what saved really means.  I have been on quite a few projects where this has turned out to be more trouble than it is worth when the user base does not understand the mechanics behind it.

Never logging out can be done where regulations permit, but it leads you into mistakes where you do not correctly handle what happens if someone is logged out unexpectedly, and all the state business becomes a little intensive to maintain if there is very much to track on an "active" user.

Title: User session timeout handling in SaaS apps - discussing several approaches

Body:
I know this has a great chance of being marked as duplicate, but couldn't find exactly what I'm looking for

This is a common problem and I'm sure it has some well defined best practice solution

Background

A single page SaaS app, has lot's of drag and drop, user can
interact with it without much server communication for periods of
time

Server session only holds user object, using a non persistent session cookie

Session expires on the server after X hours

Some things are loaded only during log-in

Problem

User works on the app, when done, user doesn't log out, just keeps the browser open

User comes back after more than X hours (session is invalidated on server)

User interacts with the app without needing a server connection (drags and drops things, text edits...)

Only on the next server interaction (let's assume there is no auto save) user is thrown to login page and loses some of their work

Possible solutions

Here are some solutions I have in mind, would like to hear if there are any others, and if there is anything fundamentally wrong with any of them.

1. Never log the user out

How? either keep a long session, keep a persistent cookie, or javaScript "keep alive" ping

Pros: user doesn't need to worry about anything, fixes the problem for them

Cons: not PCI compliant, not secure, and needs development changes, e.g. things loaded to session only on user log in need to move to either a pub sub model (listening on event changes) or have cache timeout.

2. Local Storage

How? use new local storage to temporarily store state if logged out, redirect to login page, persist once logged in

Pros: Also base for "work offline" support, not just handling session timeout

Cons: harder to implement, need to do state merge of data tree, not all browsers support

3. Auto save

Every user action that changes the model, should persist immediately (or via some sort of a client side queue), e.g. if they check a checkbox,  change a text field, or drag and drop something, once they are done, persist the changes.

How? Use an MV** framework (Backbone.js / Knockout.js / Ember.js / Angular.js etc) to bind the model, and persist on changes.

Pros: Seems like a clean solution, session is active as long as user is active, no client side work is done without persisting it.

Cons: The last action user is doing after a session timeout is lost.

4. Log the user out after session expires

this can have several approaches

Ask the server "has session expired" - this is a bit of a catch 22 / Schrodinger's cat, as the mere question to the server extends the session (restarts the timeout),

How? Either have a server that supports such question (I don't know of any, but I come form Java land)  or, one can just keep a table of session IDs, and last access time manually, and ask the server by passing the session ID as a parameter instead of the cookie, I'm not sure if this is even possible, but it sounds dangerous, insecure and bad design whatsoever.login page, persist once logged in

Pros: If there was such native support in servers, sounds like a clean, legitimate question (asking if user X still has a session or not without renewing it if they do)

Cons: If the server doesn't support it (and again, I don't know if any server or framework has this functionality) then the workaround has huge security risks potentially.

One workaround I've heard is have a short session on the server side, and a keep alive client side ping, that has a maximum number of pings

How? Short session on server, client pings every sessionTimeOut/2, has max retries of Y.

Pros: Kind of fixes the problem, quick and dirty

Cons: Feels like a hack, handling the session renewal yourself instead of letting the server do it

Client side timer

How? Have a timer on the client side and sync it with the server one by restarting it on every request to be equal to the max server session timeout minus some padding, after user is not sending any request to the server, UI shows a "sessions is about to time out, do you want to continue?" (like you have on online banking )

Pros: Fixes the problem

Cons: Can't think of any except the need to make sure the sync works

The Question

I'm probably missing something in the above analysis, might have some silly mistakes, and I would like your help to correct them. What other solutions I can have for this?


问:
Why does File.Open in .Net throw exceptions and not follow exception handling best practices?
I have read at many places including this - http://msdn.microsoft.com/en-us/library/seyhszts.aspx - that you should use exception handling when something is truly exceptional.

The .Net File.Open function throws FileNotFoundException, etc. instead of returning error codes. Now it can frequently happen that the filename passed does not exist. This does not appear to me a truly exceptional situation.

Why may be the reason behind File.Open not following exception handling best practices?

答:
It is expected that you call File.Open(...) only on files that you know (or expect) to exist. If you don't know whether the filepath passed exists or not, you're expected to call File.Exists(...) before trying to open it.

If you try to open a file you expect to exist, but it doesn't, that's an exception.


答:
The way exceptions are handled in .NET is materially different than the way they are handled in, say, Java.  Exceptions in Java demand more from the programmer than .NET does, and so the argument could be made that you reserve exception handling in Java for the truly exceptional cases.

In .NET, an exceptional condition is one that you cannot reasonably recover from without user intervention.  If the user passes the name of a file to a method which expects the file to exist, but the file doesn't exist, that's an exceptional condition.

As a programmer, you still have the option of checking for the existence of the file first, before calling the method that requires it.

In any case, the guidance that Microsoft offers seems relatively straightforward:

If the event is truly exceptional and is an error (such as an
  unexpected end-of-file), using exception handling is better because
  less code is executed in the normal case. If the event happens
  routinely, using the programmatic method to check for errors is
  better.

Title: Why does File.Open in .Net throw exceptions and not follow exception handling best practices?

Body:
I have read at many places including this - http://msdn.microsoft.com/en-us/library/seyhszts.aspx - that you should use exception handling when something is truly exceptional.

The .Net File.Open function throws FileNotFoundException, etc. instead of returning error codes. Now it can frequently happen that the filename passed does not exist. This does not appear to me a truly exceptional situation.

Why may be the reason behind File.Open not following exception handling best practices?


问:
Is declaring fields on classes actually harmful in PHP?
Consider the following code, in which the setter is deliberately broken due to a mundane programming error that I have made for real a few times in the past:

```<code><?php

    class TestClass {

        private $testField;

        function setField($newVal) {
            $testField = $newVal;
            // deliberately broken; should be `$this->testField = $newVal`
        }

        function getField() {
            return $this->testField;
        }

    }

    $testInstance = new TestClass();
    $testInstance->setField("Hello world!");

    // Actually prints nothing; getField() returns null
    echo $testInstance->getField();

?>
</code>```

The fact that I declared $testField at the top of the class helps conceal that programming error from me. If I hadn't declared the field, then I would get something similar to the following warning printed to my error log upon calling this script, which would potentially be valuable to helping my debugging  - especially if I were to make an error like this in a large and complicated real-world application:

PHP Notice:  Undefined property: TestClass::$testField in /var/www/test.php on line 13

With the declaration, there is no warning.

Perhaps I'm missing something, but I'm aware of only two reasons to declare class fields in PHP: firstly, that the declarations act as documentation, and secondly, that without declarations one can't use the private and protected access modifiers, which are arguably useful. Since the latter argument doesn't apply to public fields - assigning to an undeclared field of an object makes it public - it seems to me that I ought to at least comment out all my public field declarations. The comments will provide the exact same documentation value, but I will benefit from warnings if I try to read an uninitialized field.

On further thought, though, it doesn't seem to make sense to stop there. Since in my experience trying to read an uninitialized field is a much more common cause of error than trying to inappropriately read or modify a private or protected field (I've done the former several times already in my short programming career, but never the latter), it looks to me like commenting out all field declarations - not just public ones - would be best practice.

What makes me hesitate is that I've never seen anybody else do it in their code. Why not? Is there a benefit to declaring class fields that I'm not aware of? Or can I modify PHP's configuration in some way to change the behavior of field declarations so that I can use real field declarations and still benefit from "Undefined property" warnings? Or is there anything else at all that I've missed in my analysis?

答:
You should always declare your class properties ahead of time. While PHP is a dynamic language and will happily go right along with you creating your properties at runtime, there are several downsides to this path.

The compiler can optimize declared properties. When you dynamically declare a property this is a performance hit as the compiler has to create a dynamic hash table to store your dynamic properties.

I'm not 100% on this one but I believe that bytecode optimizers like APC won't be as useful since they won't have a full picture of your class. (And optimizers like APC are a must)

Makes your code 1000x harder to read. People will hate you.

Makes it 1000x more likely that you will make a mistake. (Was it getId or getID? Wait, you used both. Fail.)

No IDE autocompleting or type hinting.

Documentation generators won't see your property.

The problem you described is actually a minor one when compared to the problem of not declaring your properties in your class definition. Here's a good solution.

Get used to declaring defaults for your properties.

```<code>private $testField = null;
private $testField = '';
private $testField = 0;
private $testField = []; //array()
private $testField = false;
</code>```

Except for properties that will be storing objects, this will cover the majority of base types that you will be storing. The properties that will be storing objects can be set in your constructor.

A good rule for class design is that after your object has been created and your constructor has run you shouldn't have any properties out there "undefined".

OwnerDisplayName: Mark Amery

Body:
You should always declare your class properties ahead of time. While PHP is a dynamic language and will happily go right along with you creating your properties at runtime, there are several downsides to this path.

The compiler can optimize declared properties. When you dynamically declare a property this is a performance hit as the compiler has to create a dynamic hash table to store your dynamic properties.

I'm not 100% on this one but I believe that bytecode optimizers like APC won't be as useful since they won't have a full picture of your class. (And optimizers like APC are a must)

Makes your code 1000x harder to read. People will hate you.

Makes it 1000x more likely that you will make a mistake. (Was it getId or getID? Wait, you used both. Fail.)

No IDE autocompleting or type hinting.

Documentation generators won't see your property.

The problem you described is actually a minor one when compared to the problem of not declaring your properties in your class definition. Here's a good solution.

Get used to declaring defaults for your properties.

private $testField = null;
private $testField = '';
private $testField = 0;
private $testField = []; //array()
private $testField = false;

Except for properties that will be storing objects, this will cover the majority of base types that you will be storing. The properties that will be storing objects can be set in your constructor.

A good rule for class design is that after your object has been created and your constructor has run you shouldn't have any properties out there "undefined".


问:
How do i speedily traverse a file system while extracting/extrapolating various data and provide user feedback?
I'm working on a system file scanner that reveals info about various files (e.g. size, last used, duplicates, etc).  Currently I'm traversing the file system once just to get a good measure of the files I'll be processing, I then loop through doing the actual processing (size info, hash info, etc).  Obviously that immediately creates an entire layer of "extra" processing, but it allows me to use the previously acquired info to provide the user with some "progress data".

I've been looking for a good mechanism to use in order to speed up the process while still showing progress data for end users.  I thought about creating separate threads (one for appending files to a stack, and the other for reading from the stack as they became available), but that might get out of hand programmatically quickly.

In the interest of speeding up the initial scan, I currently perform a "find path" (or the equivalent depending on what OS is being used) and grab all of the output.  This, however, prevents me from negating entire subfolders (if the user desires) as it simply recursively lists everything.  Certain OSes do have command line options for negating directories, etc, but I need a cross-platform solution.

So, aaaaaaall that said, does anyone have any algorithmic suggestions for being speedy while providing quality progress?  I'm not fundamentally tied to any specific language.  I'm looking more for a higher level view of what needs to occur.

Best.

答:
I wrote a library to do something similiar, but it's only really suited for filesystems that have many drive heads (like lustre or panfs). We gather information on hundreds of millions of files (about 20PB of data) on a regular basis. Take a look at the paper we wrote as well as the library to distribute the workload and tools to analyze the data.

If you have a smaller filesystem, CEA wrote a program called Robinhood to do something similiar.


问:
What is the most egregious waste of money you have seen, and what did you do about it?
Often we as programmers see large organisations wasting huge sums of money on bloated and inefficient solutions to problems. This pains me greatly because I like organisations to benefit from best of breed solutions. However, my abilities as a programmer are limited when it comes to influencing the key decision makers and often my perspective on the matter is constrained to my own little technical world.

So, my question is this. After encountering an egregious waste of money on some software and/or hardware that really got your goat, what did you do about it to get it fixed or were you doomed to bite the bullet and mutter forever under your breath? I'm interested in hearing your overall experiences and especially what lessons you learned about how to tackle this sort of thing in the future. Let's not name names, the experience of how to tackle the problem is more important than the actual offending product.

答: One project I worked on with a large financial institution. There were huge amounts of conference calls daily, and I estimated that they burned about $100k per day just on conference calls. The project lasted about 2 years. They had tons of legacy systems and when the daylight savings changes were made a couple years ago, they paid Microsoft about half a million dollars to come up with a DST patch for NT 3.51. </p>


问:
Should I refactor my unit tests when I extract a class out of the System Under Test?
I wrote this class that does a few things (perhaps this is a violation of the Single Responsibility Principle).  I realize now that some other part of the project needs a piece of that logic and the way I'm going to expose it is to extract a class out of my original System Under Test.

I anticipate being able to do this without having to change any test code, but when I finish, you could argue that the test isn't a unit test anymore.  It'll be testing the original class and the class I've extracted.  In other words, I'll have one test case, but two systems under test.

Am I supposed to refactor my test code after I'm done?  IE: Create an ExtractedClassTest and move all the relevant tests from OriginalClassTest into it?  This seems like it could be a little risky: I may lose some coverage in the process, it may not be as simple as moving a test and I'd end up rewriting some test code that I know used to work but may not anymore, etc.

On the other hand, if I leave the OriginalClassTest as-is, I can see this being a test maintenance issue.  It'll be a little confusing to find where the ExtractedClass's tests are. Your first impression will be that it doesn't exist.  Over time with lots of production code refactorings, this could become a serious issue.

I'm new to TDD so I'd like an expert's advice.  Thanks!

答:
For the duration of the development, have both. Keep the old tests as assurance that you haven't broken anything, write new tests (from scratch) to help you design the classes as they should be.

At the end, run through and remove anything that's defunct in the old tests. Be careful in this analysis; don't remove something because you think it should be defunct. Demonstrate to yourself (or someone else, or a rubber duck) why it isn't needed any more. Break the test and make sure that another test breaks with it.

Anything that's left in the old tests should be taken on a case-by-case basis, but mostly they should be rewritten into the new structure.

Because you're right, you don't want to get left with a maintenance nightmare. But you don't want less path-coverage than you had before.


问:
C/C++ in applications that do not concern performance
C is the best language (or maybe the single language) suitable for operating systems, drivers, embedded systems etc. For more complex domains like computer graphics C++ is a better choice. But these applications have thorough performance requirements and they are only feasible to be built in C/C++.

Now the question is, if the performance requirements can be achieved in another language, are there any technical reasons to choose C/C++?

答:
Yes. Portability.

Famously, the reason Unix was written in C was for portability across the systems of the time.

Today, A C++ Qt application is still easier package for multiple platforms (even if they're just Windows, Linux and Mac) than an equivalent PyQt application.


答: Yes.  Almost every single language under the sun can link to C; by using C you're ensuring that someone can come along with whatever language they like and successfully link to your API.</p>

Title: C/C++ in applications that do not concern performance

Body:
C is the best language (or maybe the single language) suitable for operating systems, drivers, embedded systems etc. For more complex domains like computer graphics C++ is a better choice. But these applications have thorough performance requirements and they are only feasible to be built in C/C++.

Now the question is, if the performance requirements can be achieved in another language, are there any technical reasons to choose C/C++?


答:
Of course, there are many.

Just a few of the reasons include:

code size (some of us work in the embedded world without gigabytes of RAM)

programmer proficiency / competence

tool / platform support

legacy code considerations (e.g. older code written in C or C++)

I could go on & on.  If I take your question literally, it's basically, "What other criteria other than performance could ever matter when choosing a programming language?"


问:
Best practice to sync long paths to filesystems where path length is limited?
I wrote a sync tool to synchronize folders/files from Alfresco to Windows.

PROBLEM:

In Alfresco, /files/can/have/very/very/very/long/filepaths/like/this.txt

The Windows API prevents me from creating a path with more than 260 characters.

In addition to telling the user there is a problem, what is the best practice in such a case?

Shorten the file's name?

Skip the file?

Create a sort of "folder's carriage return", a special folder from which the path can continue?

Something else?

Files need to be 100% usable by other applications. If necessary directory names can be modified, I can keep a mapping.

答:
The problem you mention doesn't exist, since the limit you specified in your question is wrong.

Until Vista, Explorer was limited to 248 characters.

.NET Framework File is limited to 260 characters (MAX_PATH).

The real maximum path for Windows itself is approx. 32,767 characters.

I have no idea where have you found the mention of 255 characters.

Now, if you're syncing files to an operating system which doesn't allow 32,767 characters-length paths (like very old versions of Windows), then:

Skip the file,

Inform the user that there is an issue with the length of the given files. Do it only at the end of the process, not file by file. There is nothing more annoying that being disturbed dozens of times during a process because there are dozens of files that cannot be synced.

Don't shorten the file name. You have a good chance to cause more trouble with collisions.


答:
See the MSDN article on maximum path length limitations for some additional ideas.

You can try some of the following depending on what is available to you:

Attempt to use "extended-length paths" starting with \\?\ but be aware of the limitations such as no relative path names.

Map a longer path to a drive using subst to artificially shorten the path.

If you absolutely are unable to sync the file, then the best practice would be to skip the file and note all skipped files in some sort of error report, or quit early, noting that you are unable to complete the sync as desired.

Title: Best practice to sync long paths to filesystems where path length is limited?

Body:
I wrote a sync tool to synchronize folders/files from Alfresco to Windows.

PROBLEM:

In Alfresco, /files/can/have/very/very/very/long/filepaths/like/this.txt

The Windows API prevents me from creating a path with more than 260 characters.

In addition to telling the user there is a problem, what is the best practice in such a case?

Shorten the file's name?

Skip the file?

Create a sort of "folder's carriage return", a special folder from which the path can continue?

Something else?

Files need to be 100% usable by other applications. If necessary directory names can be modified, I can keep a mapping.


问:
Alternative to "Passing/Broken build" indicator?
When having a continuous integration executing the tests at each commit, a common best practice is to have all the tests passing at all times (aka "do not break the build").

I find some problems with that:

For example one cannot help an open source project by creating tests corresponding to tickets. I know if I propose a Pull Request to an open source project containing failing test, the build will be marked as failed and the project will not want that merged into its repository because it would "break the build".

And I don't believe it is a bad thing to have failing tests in your repo, it's like having open issues in your tracker. These are just things waiting to be fixed.

The same goes in a company. If you work with TDD, you can't write tests, commit and then write the logic code that fulfills the test. That means if I have written 4-5 tests on my laptop, I can't commit them before going on holidays. Nobody can take back my work. I can't even "share" them with a colleague except by sending them by email for example. It also prevents working with one person writing the tests, the other one writing the model.

All that to say, am I misusing/misunderstanding the build process/continuous integration? It seems to me that "passing"/"not passing" is a too narrow indicator.

Is there a way to make continuous integration and TDD compatible?

Maybe there is a standard solution/practice to distinguish "new tests" (that can fail) and "regression tests" (that should not fail because they used to work)?

答:
There are ways to solve your problems without throwing away well understood and accepted practices about continuous integration.

I will start with the problem of committing a 'broken test' that corresponds to a ticket. One solution is to create one or more breaking tests exposing the problem, then actually fix the problem, so they can be merged back to the main code line together. Second solution is to have the broken tests, but use some type of ignore flag so they do not actually run and break the build. Possibly add a comment or a special annotation that makes it very obvious that this is a broken test for Ticket#N. Also attach a note to the ticket itself that refers to the created tests that are waiting to be unignored and ran. This would help a person fixing the ticket, but also would not be a red-flag for someone who comes across the test.

And onto your next problem with TDD. TDD is about writing a small test and then writing a small chunk of code to make that test pass. Then keep iterating until you have a small functional module. I feel that if you write 4-5 tests, then you go on vacation, you might be doing it wrong. You can pair program with someone in a way that one of you write the test, the other the corresponding code. You should however not use the main code line repository to share this code between you two before a completed module is ready to be committed. As others suggested, a shared branch would solve your problems there.

Trying to break the continuous integration mantra can lead down to unexpected and scary paths. For example, what would code coverage mean in this type of environment? How would developers not feel that the system has many "Broken Windows"? How would one make a change, run the test and know whether they are actually breaking anything new, or its just the old stuff?


问:
Application deployment with Puppet
I've been researching puppet lately, and I think it could be useful to integrate into my deployment pipeline.

Currently, I deploy my apps by manually adding users, creating vhosts, setting directories, and then git cloning my repo from GitHub. I deploy changes with a simple Git pull (Git hooks take care of database migrations, clearing the cache, etc).

With puppet, I could setup a manifest to do the directory creation, permissions and virtual host management for me. To deploy an app to a dev/prod environment, I'd pull the manifest from GitHub and run it locally. I was also thinking about adding the puppet manifest process to the Git hook so every pull, Puppet could ensure directory permissions are OK.

Are there issues with this approach? Things I could do better?

答:
This sounds like an effective approach; I like the creativity. Since you asked for comments, I will offer a few:

1) While puppet is a very powerful tool, it seems like a bit of overkill for just directory creation and permissions. A simple bash script might do the trick in as many lines as Puppet, with no Puppet executable dependency.

2) Consider using Puppet to do your deployment too: PuppetLabs provides a manifest to check out of a git repository. Then you can run it periodically, or on some other form of trigger. This obviously would invert the directionality of your deployment, turning it from a "push" model to a "pull" model. It can have advantages, including simplicity.

3) A more advanced usage of Puppet would have you set up your entire production environment from scratch, including installing your app. This would create a fully automated instance of your app, making virtualized instances easy and portable, and causing horizontal scaling to be simple.

Title: Application deployment with Puppet


答:
This is just a rehash of existing answers by MainMa and Jay Lindquist.

Use the underlying Windows API which supports the maximum path length of 32,767.

Create the document with the full path, but also create a symbolic link somewhere in a folder at a shorter depth:

C:\exported files\Links to documents with path names too long\shortened_name.doc

Then, a list of such documents and their full path location can be reported at the end of the operation.

Note about the .NET framework: this blog article at MSDN more accurately describes the recommended practices with regard to compatibility with other applications.


答:
I think your fundamental problem is that you are including test RESULTS as part of the build.  While obviously some people agree with you, others don't.  Breaking the build occurs when it doesn't build.  Not when it doesn't build without errors.

Consider a major project like Windows or Linux, or even something like Firefox -- do you think they ship bug free?  Of course not.  Now these projects aren't doing TDD, but that's really irrelevant -- TDD doesn't change two fundemental facts: bugs exist, and it takes time to fix them.  Time which a project (open source or not) just can't afford to waste on low priority bugs.  KDE recently had a bug that was over a decade old fixed.   When was the last time you heard someone say "I'm glad we waited a decade to ship our project"?

TDD, in a way, probably makes it EASIER to ship with bugs -- because you have a better understanding of what the flaw is.  If you can precisely define what causes the bug, you have an excellent basis for weighing the cost of fixing it.

My recommendation is to find a project that doesn't mind some red amoung the green.

Title: Alternative to "Passing/Broken build" indicator?

Body:
When having a continuous integration executing the tests at each commit, a common best practice is to have all the tests passing at all times (aka "do not break the build").

I find some problems with that:

For example one cannot help an open source project by creating tests corresponding to tickets. I know if I propose a Pull Request to an open source project containing failing test, the build will be marked as failed and the project will not want that merged into its repository because it would "break the build".

And I don't believe it is a bad thing to have failing tests in your repo, it's like having open issues in your tracker. These are just things waiting to be fixed.

The same goes in a company. If you work with TDD, you can't write tests, commit and then write the logic code that fulfills the test. That means if I have written 4-5 tests on my laptop, I can't commit them before going on holidays. Nobody can take back my work. I can't even "share" them with a colleague except by sending them by email for example. It also prevents working with one person writing the tests, the other one writing the model.

All that to say, am I misusing/misunderstanding the build process/continuous integration? It seems to me that "passing"/"not passing" is a too narrow indicator.

Is there a way to make continuous integration and TDD compatible?

Maybe there is a standard solution/practice to distinguish "new tests" (that can fail) and "regression tests" (that should not fail because they used to work)?


问:
What's a good way to explain the need for pointing to a pointer?
Understanding what a pointer (an address) is, is fairly easy and an eleven-year old can understand it. But how do we express why we have a need for a pointer to a pointer? what is a very pedagogical example? Does it extend to pointing to a pointer to a pointer (and/or onward)?

Example problem

T[][] does not decay to a T**

Example problem 2

```<code>brainfuck command   C equivalent
(Program Start) char array[30000];
                char *ptr=array;
>   ++ptr;
<   --ptr;
+   ++*ptr;
-   --*ptr;
.   putchar(*ptr);
,   *ptr=getchar();
[   while (*ptr) {
]   }
</code>```

答:
What does it mean that a pointer is an address? It means that it refers to a memory location where the value pointing to is stored, usually a variable. When you say that a pointer points to something, you really mean a pointer pointing to a something variable.

This variable can hold an int, but it can as well hold another pointer. Thus more correctly, you have a pointer to a pointer variable. This makes the explanation easy: You need a pointer to a pointer variable for the same reasons you need a pointer to an integer variable.

A pointer to a pointer doesn't exist as its own type. If you have this:

```<code>int **p;
</code>```

then p ist still a single leveled pointer. Don't read it as this:

```<code>int (**)p;  // wrong
</code>```

but as this:

```<code>(int *) *p;  // correct
</code>```

because it is a pointer to another pointer variable that holds a pointer to an int variable.

```<code>int i = 125;
int *p1 = &i;
int **p2 = &p1;

Address     Value
0x10000000  [0x20000000]  p2
0x20000000  [0x30000000]  p1
0x30000000  [125]         i
</code>```

EDIT:

If you still find this confusing, then don't try to think about the pointer to infinity. It works in plain C, is completely undefined behavior (and thus bad), and requires sizeof(unsigned int) == sizeof(unsigned int *). But then it works with any amount of * the compiler supports.

```<code>unsigned int **********p;

p = (void *)&p;

printf("%x\n", **********p);
printf("%p\n", (void *)p);
</code>```

Body:
What does it mean that a pointer is an address? It means that it refers to a memory location where the value pointing to is stored, usually a variable. When you say that a pointer points to something, you really mean a pointer pointing to a something variable.

This variable can hold an int, but it can as well hold another pointer. Thus more correctly, you have a pointer to a pointer variable. This makes the explanation easy: You need a pointer to a pointer variable for the same reasons you need a pointer to an integer variable.

A pointer to a pointer doesn't exist as its own type. If you have this:

int **p;

then p ist still a single leveled pointer. Don't read it as this:

int (**)p;  // wrong

but as this:

(int *) *p;  // correct

because it is a pointer to another pointer variable that holds a pointer to an int variable.

int i = 125;
int *p1 = &i;
int **p2 = &p1;

Address     Value
0x10000000  [0x20000000]  p2
0x20000000  [0x30000000]  p1
0x30000000  [125]         i

EDIT:

If you still find this confusing, then don't try to think about the pointer to infinity. It works in plain C, is completely undefined behavior (and thus bad), and requires sizeof(unsigned int) == sizeof(unsigned int *). But then it works with any amount of * the compiler supports.

unsigned int **********p;

p = (void *)&p;

printf("%x\n", **********p);
printf("%p\n", (void *)p);


问:
Does this situation call for well specified associations, single table inheritance, or polymorphic association?
I'm building a web-app where users can keep track of who owes whom money.

I have users and debts.
Given a user I want to be able to find out all the debts to other users, and all the loans to other users.
Given a debt I want to be able to find out who the debtor and lender are.

The asker of this question ran into a similar situation, but I don't belive our situations similar enough to warrant just using the top answer:

https://stackoverflow.com/questions/4729725/how-do-i-do-two-has-many-belongs-to-relationships-between-two-models

Taken from that question, the three paterns sugested there are

well specified associations

single table inheritance

polymorphic association

What pattern should I use in my situation? One of these three, or is there an even more appropriate one?

答:
Looks like a straightforward one-many problem

I would approach it as

User 1 - * Debt

User 1 - * Loan

Then all you need are the tables User, Debt and Loan. The relationships are bi-directional.

From your pick list this is "well-specified associations". I don't think inheritance or polymorphism is required in this situation.


问:
Whats the greatest most impressive programing feat you ever witnessed?
Everyone knows of the old adage that the best programmers can be orders of magnitude better than the average. I've personally seen good code and programmers, but never something so absurd. So the questions is, what is the most impressive feat of programming you ever witnessed or heard of?

You can define impressive by:

The scope of the task at hand e.g. John single handedly developed the framework for his company, a work comparable in scope to what the other 200 employed were doing combined.

Speed e.g. Stu programmed an entire real time multi-tasking app OS on an weekened including  its own C compiler and shell command line tools

Complexity e.g. Jane rearchitected our entire 10 millon LOC app to work in a cluster of servers. And she did it in an afternoon.

Quality e.g. Charles's code had a rate of defects per LOC 100 times lesser than the company average. Furthermore he code was clean and understandable by all.

Obviously, the more of these characteristics combined, and the more extreme each of them, the more impressive is the feat.

So, let me have it. What's the most absurd feat you can recount? Please provide as much detail as possible and try to avoid urban legends or exaggerations. Post only what you can actually vouch for.

Bonus questions:

Was the herculean task a one-of, or did the individual regularly amazed people?

How do you explain such impressive performance?

How was the programmer recognized for such awesome work?

答: John Carmack regularly impresses me with his feats of epic programming.  According to one story, he was bored in his hotel room, so he wrote the Doom 3 lighting engine on his laptop over a weekend.</p>


答:
```<code> > a common best practice is to have all the tests passing (green) at all times.
</code>```

I prefer to have all tests not failing (not red).

With this slightly different definition you can also define tests that are

not implemented yet (grey in nunit if there is a NotImplementedException)

known to be failing="needs a to do" by marking/annotating the test as ignored (yellow)

I you check these into the repository your continous build is not broken and therefore valid.

Body:
 > a common best practice is to have all the tests passing (green) at all times.

I prefer to have all tests not failing (not red).

With this slightly different definition you can also define tests that are

not implemented yet (grey in nunit if there is a NotImplementedException)

known to be failing="needs a to do" by marking/annotating the test as ignored (yellow)

I you check these into the repository your continous build is not broken and therefore valid.


答:
I would advice a simpler solution.  2 one-to-many relations, let me explain:

One debt table with  2 user_ids as debitor_id and creditor_id.

like that a user has many loans and many debts, but each debt has only one creditor and one debitor.
Both your models and querying are straightforward, and the cases you have mentioned seem to be covered.

NB: while it is possible to for the same 2 users to have multiple loan and debt records, I would recommend against this by validating the uniqueness of the debitor_id, creditor_id combination (if that functionality is not required) in order to simplify querying and having cleaner ORM attributes.

Title: Does this situation call for well specified associations, single table inheritance, or polymorphic association?

Body:
I'm building a web-app where users can keep track of who owes whom money.

I have users and debts.
Given a user I want to be able to find out all the debts to other users, and all the loans to other users.
Given a debt I want to be able to find out who the debtor and lender are.

The asker of this question ran into a similar situation, but I don't belive our situations similar enough to warrant just using the top answer:

https://stackoverflow.com/questions/4729725/how-do-i-do-two-has-many-belongs-to-relationships-between-two-models

Taken from that question, the three paterns sugested there are

well specified associations

single table inheritance

polymorphic association

What pattern should I use in my situation? One of these three, or is there an even more appropriate one?


问:
What should junior developer expect from their senior team lead
Disclaimer: Opinions expressed are solely my own and do not express the views or opinions of my employer.

I work for a small company, in which few people are  developers, others are QA/Test and 1 is a Manager. I joined this company 1.5 years ago. 3 senior developers have 8+ years of experience.

These are the observations which I made about the team lead. (considering me as a fresher with less experience compared to them in all aspects )

They never discuss 1:1 or they never consider the junior suggestion (I agree that it's up to them, whether they accept it or not, at least they should consider an opinion).

As senior team leader they can try to refactor the codebase with new technologies ( including the factor of rolling out new technologies is possible and other developer and infrastructure also ready), but these team leader feel less in-secure to work with new technologies, as they are not up to date. (reason I am telling, they don't know what current programming trend, *(such as popular open source projects like modernizr, bootstrap and many others).

In our codebase more than 10000+ lines are repeated, so I told them  about DRY: Don't Repeat yourself.  Their reply was : "It is a fascinating article, but never works in practice".  I just told them if we do not make it 100% DRY, we can at least use interfaces, but that also was not considered. *(interfaces can be added for new features, not touching the previous codebase, if they are not ready to refactor)

All senior developers do maintenance and hot fixing of patches. The rest of the time they just spend on entertainment sites. They are just happy to finish the task.

Introducing new technology is bad? *(including factor of feasibility can be done).

Manager also least concerned about the things which I am talking about.

Junior expects they can learn many things from team lead. *(not by asking help or senior coding for them).

My questions are:

Am I too aggressive about the changes which I am proposing?

What should I expect from senior dev leads who have 8+ years experience?

Am I wrong to expect to learn and gain experience from a company?

Update :

Why they feel DRY is impractical: because they don't want get involved with OOP concepts. They are happy with repeating tasks.

New technologies I am proposing:

Usage of Minification of CSS, JS, SPrite images

Usage of Interfaces and .net framework 4, generics and many others.

Client side libraries such as modernizr, knockout js, bootstrap for responsive,

答:
I think you are right in your aggressiveness. This is a big pleasure to work with passionated people and a big punishment to work with mentally dead. 8 years of experience means nothing.
Of course, you might not been right. Often new technologies are tightly binded with marketing and are not always better. But if you are not right, seniors should explain you where are wrong. Otherwise, you do not get any advantages from your job.
Maybe, you are young and hot. If so, this is your advantage. Do not spend your time on job where you cannot grow. Concern to find a new job, where you can discuss your solutions and get feedback from others.</p>


答:
Paying large software companies not only for their product, but for their "support."

I was working at a Government agency for a team that was deep in bed with Oracle. Over the course of many years, they had been paid bajillions of dollars for their software. Coming from a startup background this made no sense to me - "why not use MySQL or Postgres?" I was told that it was mainly because of the support that Oracle provides, if something goes wrong they help you find the solution quickly.

The support was an absolute joke. There was a problem where one web app kept crashing the whole system. It appeared to be a result of a slow database query with a combination of horribly written code (which was written by a team of consultants, which should be a whole other answer). A "task force" (groan) was assembled to pinpoint the issue and fix it. Included on the task force was an Oracle support member. Every day at EOB there would be a conference call where the task force members would update the rest of the team with the findings. It was a long enough call that nobody wanted to be on b/c it started at 5, and the Oracle person just made it worse. Why? Well, saying "person" isn't even correct. It was a number of people. It seemed like every two or three conference calls, the Oracle rep would be somebody new, who explained their predecessor was now on another project or had gone on vacation. The new people were never briefed by anybody at Oracle, so every time somebody new came in we had to waste ten minutes of the conference call explaining the problem again. Their contribution would then be asking for J2EE log files, which not only can any monkey read, but were also useless because the horribly written code was doing things like throwing IndexOutOfBounds exceptions when the programmer found errors in parsing XML.

Title: What is the most egregious waste of money you have seen, and what did you do about it?

Body:
Often we as programmers see large organisations wasting huge sums of money on bloated and inefficient solutions to problems. This pains me greatly because I like organisations to benefit from best of breed solutions. However, my abilities as a programmer are limited when it comes to influencing the key decision makers and often my perspective on the matter is constrained to my own little technical world.

So, my question is this. After encountering an egregious waste of money on some software and/or hardware that really got your goat, what did you do about it to get it fixed or were you doomed to bite the bullet and mutter forever under your breath? I'm interested in hearing your overall experiences and especially what lessons you learned about how to tackle this sort of thing in the future. Let's not name names, the experience of how to tackle the problem is more important than the actual offending product.


问:
Which programming language for text editing?
I need a programming language for text editing and processing (replace, formatting, regular expressions, string comparison, word processing, text analysis, etc.). Which programming language is more powerful and has more functions for this purpose?

Since I work PHP for my web projects, I currently use PHP, but the fact is that PHP is a scripting language for web applications; my current project is offline.

I am curious if other programming languages such as Perl, Python, C, C++, Java, etc. have more functionality for this purpose, and worth of shifting the project?

答:
Learn Regular Expressions (regex)

Regex is a small technology that you can master in a week or two (1-2 hours/day), but it's so useful that it will pay off that investment of time on the first project you use it on.  Most programming languages support them including PHP.  There is a wonderful book on regex, Mastering Regular Expressions by Jeff Friedl.  It starts slow, but speeds up quickly and really has everything you need to know about Regex.  It's one of my favorite technical books.

AWK

Once you know Regex, you can do amazing things with awk (gawk), sed, and grep, or really with any modern programming language.  Regular Expressions are not a programming language, so I suppose that's technically not an answer to your question, but Awk is a complete language and it rocks for one-off text processing.

emacs

One other thing that I feel compelled to mention is emacs.  For crunching data from one format to another, I write little combinations of regular expressions and elisp right in the same buffer as the data I'm transforming.  Ctrl-x Ctrl-e evaluates the previous lisp code.  Ctrl-x r d deletes a currently highlighted rectangle.  Between these functions, you can experiment with transforming text in a buffer until you have just what you want.  It's truly interactive and wonderful.  Not to mention that it's written by Richard Stallman, who also created the GNU Public License (copyleft) and started the movement most people call Open Source Software.

The Dark Side of emacs

The learning curve for emacs is very steep.  It took me 6 months to be able to use emacs and 6 years to not think about it any more.  Common regex characters require three back-slashes to escape them properly for emacs, which can lead to what Friedl calls, "Leaning Toothpick Syndrome."

Emacs a modeless editor, so there are lengthy key sequences for everything that can really wear out your little and ring fingers on each hand from holding down Alt, Ctrl, and Shift all day long.  People jokingly call it Escape-Meta-Alt-Ctrl-Shift, but it's kind of true.  Evil Mode for Emacs makes it much easier on the tendons.

Since some clown decided to add "Windows Keys" between the Alt and Ctrl keys on computer keyboards, using Emacs has become more difficult.  I use an old ThinkPad keyboard from before the days of Windows Keys and have an extra in the closet in case it breaks.  On newer keyboards, I like to pop off the offending keys.  Hmm... That's probably too much information...

Conclusion

Learn Regex - it makes every language better!


问:
Terminology: Really Delete vs set IsDeleted ("soft delete") flag
I have a site where a regular user can delete records, where what happens is that an IsDeleted flag gets set. On administrative pages, a privileged user can delete records where an actual SQL DELETE permanently discards such records. The difference is important for obvious reasons, and I want to use a consistent term to refer to the one form of deletion vs. the other. I've been playing with the words Remove, Delete, Discard and possibly Recycle, and Archive.

My question is: are there standard user-facing terms that distinguish these two behaviors?

答:
For regular users they click the Trash icon to flag a record for deleting. The privileged users can then view the contents of the Trash and delete those icons.

Delete is permanent, where as Trash can be thought of as a location.

The user can move records to the Trash.

and

The privileged user deleted records in the Trash.

The other words don't work well for me.

I don't like Recycle because it implies a different meaning then simply deleting records.

Archive implies permanent storage, and possibly moving the records to offline storage.


答:
And I don't believe it is a bad thing to have failing tests in your repo, it's like having open issues in your tracker. These are just things waiting to be fixed.

The problem isn't failing tests, it's a simple, context less indicator of regression.
Aka: as a developer, can I check a single indicator and know if I introduced a regression or breaking code.

The moment you introduce the concept of 'soft' failures (it's ok, we're working on it/not implemented yet/we're waiting for the new version/it's going to pass again once this other build is fixed), you require everyone that might run or look at the test to know the expected state. Which in a large enough team is going to change by the hour: your indicator becomes meaningless. In a smaller context (team private integration test for instance), then I think it's like technical debt and is ok - just needs to be managed.

The way most tool address that is that 'green/passing' reflects what the expected result is - not that the code is working:

Fitness has the concept of expected failure.

JUnit has @Ignored / @Test(expect=)

Cucumber has the 'not yet implemented' (or whatever it's called) status

Those come with their own issues (how do you distinguish between 'yes, we know it's broken, working on it' and 'the correct behavior is an exception') - but they help.


问:
Where to find the source code for the Linux command line functions
I would like to study the source code of the standard command line functions in Linux such as ls, echo, cat, etc. But I have been unable to find the source code (a Google search was useless).

Does someone know where it's available? I know it's a naive question but I really can't find this source code.

答:
Those commands are the GNU core utilities. The latest code can be retrieved from a git repository here:

http://git.savannah.gnu.org/cgit/coreutils.git

To check it out anonymously use git clone like this:

```<code>$ git clone git://git.savannah.gnu.org/coreutils.git
</code>```

Body:
Those commands are the GNU core utilities. The latest code can be retrieved from a git repository here:

http://git.savannah.gnu.org/cgit/coreutils.git

To check it out anonymously use git clone like this:

$ git clone git://git.savannah.gnu.org/coreutils.git