问:
Is there an issue with closing our database connections in the "Finally" block of a Try statement?
I'm doing some refactoring for our application, and trying to reduce the number of issues reported in our ISO Scan (a static code analysis tool based on HP Fortify).  Right now, what I'm trying to address is the "Unreleased Resource: Database" issues our application has built up.  One of the most prominent reasons for this is constructs like this:

```<code>Connection conn = null;
Boolean myConn = false;
try{
   if(conn == null){
     conn = DatabaseUtil.getConnection();
     myConn = true;
   }
   result = DbClass.getObject(conn, otherParameters);
}catch(DatabaseException de){
  throw de;
}catch(SQLException sqle){
  throw new DatabaseException("Error Message");
}finally{
  if(myConn && conn != null){
    try{
      <b>conn.rollback();</b>
      <b>conn.close();</b>
    }catch(SQLException sqle){}
}</code>```

This is a fairly standard construct in our application to ensure the database connection is closed at the end of our Try block.  Yet every time we use it, the tool reports it as an issue.

Is there anything incorrect about this construct, and is there anything we can do to fix it if it is an issue?

答:
Because your release of resources is conditional on the state of a boolean variable and encased in another try block, the static analyzer must be deciding that rollback() and close() are not guaranteed to execute.

Check the documentation for the Connection object of the type returned by the getConnection() factory method, and see if the methods rollback() and close() will even throw an exception.  If they won't, you don't need that additional try catch block when calling those methods.

But first, eliminate the boolean variable that you're using to signal an open connection.  You shouldn't need it; you shouldn't get a connection object back from the getConnection() factory method unless it was successful at establishing a connection.

Note that Fortify's security report suggests the following code structure:

```<code>public void execCxnSql(Connection conn) {
    Statement stmt;
    try {
        stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(CXN_SQL);
        ...
    }
    finally {
        if (stmt != null) {
            safeClose(stmt);
        }
    }
}
public static void safeClose(Statement stmt) {
    if (stmt != null) {
        try {
            stmt.close();
        } catch (SQLException e) {
            log(e);
        }
    }
}
</code>```

...which suggests that the boolean variable is the problem, not the additional try block.

Body:
Because your release of resources is conditional on the state of a boolean variable and encased in another try block, the static analyzer must be deciding that rollback() and close() are not guaranteed to execute.

Check the documentation for the Connection object of the type returned by the getConnection() factory method, and see if the methods rollback() and close() will even throw an exception.  If they won't, you don't need that additional try catch block when calling those methods.

But first, eliminate the boolean variable that you're using to signal an open connection.  You shouldn't need it; you shouldn't get a connection object back from the getConnection() factory method unless it was successful at establishing a connection.

Note that Fortify's security report suggests the following code structure:

public void execCxnSql(Connection conn) {
    Statement stmt;
    try {
        stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(CXN_SQL);
        ...
    }
    finally {
        if (stmt != null) {
            safeClose(stmt);
        }
    }
}
public static void safeClose(Statement stmt) {
    if (stmt != null) {
        try {
            stmt.close();
        } catch (SQLException e) {
            log(e);
        }
    }
}

...which suggests that the boolean variable is the problem, not the additional try block.


答:
And the tools are right!

Apart from the (possible) limitations of the analysis - it may or may not understand that (conn != null) == myConn, observe that rollback throws an SqlException. If it does, then close is never called, which is precisely the definition of a resource leak. Now, it may be the case that with your current DB, drivers and pooling libraries if rollback throws, then the connection is already released, but this is not true in the general case, hence a potential problem.

As noted in comments you can simplify much of this construct by using try-with-resources if using Java 7. It also becomes much simpler to reason about and include a rollback via a custom class that does rollback in its close() method in a try block:

```<code>@Override
public void close() throws SQLException {
    try {
        rollback();
    catch (...) {
        //Do stuff
    finally {
        super.close();
    }
}
</code>```

Here you are 100% guaranteed that close() will actually run, whatever rollback does.

If working with legacy software, the above code can be directly put into the try:

```<code>Connection conn = null;
try {
   conn = DatabaseUtil.getConnection();
   result = DbClass.getObject(conn, otherParameters);
} catch(SQLException sqle) {
  throw new DatabaseException("Error Message");
} finally {
  if (conn != null) {
    try{
        conn.rollback();
    } catch(SQLException sqle) {
        //try-with-resources would add this to suppressed exceptions, you can either log or rethrow
    } finally {
        conn.close();
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Is there an issue with closing our database connections in the "Finally" block of a Try statement?

Body:
I'm doing some refactoring for our application, and trying to reduce the number of issues reported in our ISO Scan (a static code analysis tool based on HP Fortify).  Right now, what I'm trying to address is the "Unreleased Resource: Database" issues our application has built up.  One of the most prominent reasons for this is constructs like this:

```<code>Connection conn = null;
Boolean myConn = false;
try{
   if(conn == null){
     conn = DatabaseUtil.getConnection();
     myConn = true;
   }
   result = DbClass.getObject(conn, otherParameters);
}catch(DatabaseException de){
  throw de;
}catch(SQLException sqle){
  throw new DatabaseException("Error Message");
}finally{
  if(myConn && conn != null){
    try{
      <b>conn.rollback();</b>
      <b>conn.close();</b>
    }catch(SQLException sqle){}
}</code>```

This is a fairly standard construct in our application to ensure the database connection is closed at the end of our Try block.  Yet every time we use it, the tool reports it as an issue.

Is there anything incorrect about this construct, and is there anything we can do to fix it if it is an issue?

Body:
And the tools are right!

Apart from the (possible) limitations of the analysis - it may or may not understand that (conn != null) == myConn, observe that rollback throws an SqlException. If it does, then close is never called, which is precisely the definition of a resource leak. Now, it may be the case that with your current DB, drivers and pooling libraries if rollback throws, then the connection is already released, but this is not true in the general case, hence a potential problem.

As noted in comments you can simplify much of this construct by using try-with-resources if using Java 7. It also becomes much simpler to reason about and include a rollback via a custom class that does rollback in its close() method in a try block:

@Override
public void close() throws SQLException {
    try {
        rollback();
    catch (...) {
        //Do stuff
    finally {
        super.close();
    }
}

Here you are 100% guaranteed that close() will actually run, whatever rollback does.

If working with legacy software, the above code can be directly put into the try:

Connection conn = null;
try {
   conn = DatabaseUtil.getConnection();
   result = DbClass.getObject(conn, otherParameters);
} catch(SQLException sqle) {
  throw new DatabaseException("Error Message");
} finally {
  if (conn != null) {
    try{
        conn.rollback();
    } catch(SQLException sqle) {
        //try-with-resources would add this to suppressed exceptions, you can either log or rethrow
    } finally {
        conn.close();
    }
}


答:
Eliminate the condition, since the compiler things the code could not run at all.

Then catch Exception instead of SQLException so it catches NullPointerException in case the connections are not initialized. I usually set the object to null after closing it, because a recommendation I read in a Sybase's EAServer paper and, maybe,  it has nothing to do with Java's garbage collector but with EAServer's connection pool, and maybe I'm "cargo-culting" here.

```<code>Connection conn = null;
Boolean myConn = false;
try{
   if(conn == null){
     conn = DatabaseUtil.getConnection();
     // myConn = true; no need for this
   }
   result = DbClass.getObject(conn, otherParameters);
}catch(DatabaseException de){
  throw de;
}catch(SQLException sqle){
  throw new DatabaseException("Error Message");
}finally{
    try{
      conn.rollback();
      conn.close();
      conn=null; // good practice according to people at Sybase
    }catch(Exception e){
         //fails silently when conn is not initialized.
    }
}
</code>```

Body:
Eliminate the condition, since the compiler things the code could not run at all.

Then catch Exception instead of SQLException so it catches NullPointerException in case the connections are not initialized. I usually set the object to null after closing it, because a recommendation I read in a Sybase's EAServer paper and, maybe,  it has nothing to do with Java's garbage collector but with EAServer's connection pool, and maybe I'm "cargo-culting" here.

Connection conn = null;
Boolean myConn = false;
try{
   if(conn == null){
     conn = DatabaseUtil.getConnection();
     // myConn = true; no need for this
   }
   result = DbClass.getObject(conn, otherParameters);
}catch(DatabaseException de){
  throw de;
}catch(SQLException sqle){
  throw new DatabaseException("Error Message");
}finally{
    try{
      conn.rollback();
      conn.close();
      conn=null; // good practice according to people at Sybase
    }catch(Exception e){
         //fails silently when conn is not initialized.
    }
}


问:
One Enum vs Multiple Enums
I am developing an application where a user submits a mission and other users accept the mission.

Pretty simple.

I want to keep a track of the mission progress status and store it into a database.

Which would be more appropriately:

1.having the following enums in a database column:

```<code>PRICE_NEGOTIATION,
DEPOSIT_NEGOTIATION,
MISSION_STARTED,
DEMO_RECEIVED,
DEMO_APPROVED,
DEMO_UNAPPROVED,
PAYMENT_DONE,
PAYMENT_PENDING,

PRICE_NEGOTIATION_UNAPPROVED_BY_CREATOR,
PRICE_NEGOTIATION_UNAPPROVED_BY_ACCEPTOR,
DEPOSIT_NEGOTIATION_UNAPPROVED_BY_CREATOR,
DEPOSIT_NEGOTIATION_UNAPPROVED_BY_ACCEPTOR,
MISSION_CANCELED_AFTER_START_BY_CREATOR,
MISSION_CANCELED_AFTER_START_BY_ACCEPTOR,
MISSION_CANCELED_AFTER_DEMO_UNAPPROVEMENT,
</code>```

and so on..

having more than one column in the database where one of them gives a cancel reason, another one that holds who canceled the mission and another one about the payment status.

any better suggestions?

10x in advance and sorry if the question is too much opinion based.

答:
I think the way you want to split it into multiple enums is not bad, but it requires changes in DB.

It will also enable you to create a successful payment with cancel reason etc. When you have a single (huge) enum, it covers this logic by enumerating all allowed combinations. Without it, you either need some application logic or you allow the full carthesian multiplication of the enums.

Anyway, as enums can have fields and methods, you can just upgrade the existing enum. Add some private fields and getters in it and you can do something like this:

```<code>if (missionProgress.getPaymentStatus() == PaymentStatus.CANCEL) {...}
</code>```

Anyway, if you don't have the application running on any customer's server yet (with tons of data already), I would advise not to use a huge enum like that.

Title: One Enum vs Multiple Enums

Body:
I think the way you want to split it into multiple enums is not bad, but it requires changes in DB.

It will also enable you to create a successful payment with cancel reason etc. When you have a single (huge) enum, it covers this logic by enumerating all allowed combinations. Without it, you either need some application logic or you allow the full carthesian multiplication of the enums.

Anyway, as enums can have fields and methods, you can just upgrade the existing enum. Add some private fields and getters in it and you can do something like this:

if (missionProgress.getPaymentStatus() == PaymentStatus.CANCEL) {...}

Anyway, if you don't have the application running on any customer's server yet (with tons of data already), I would advise not to use a huge enum like that.

OwnerDisplayName: Vlasec


问:
How to deal with dependency when you have separate projects?
I know there is all this talk about having only one composition root that set all your dependencies and that you should always prefer constructor injection to other types, but sometimes it just doesn't make any sense for me. Here is my pseudo code :

```<code>    public class FakeModel
    {
        private FakeDependency Dependency = ServiceLocator.Get<FakeDependency>();

        public string Name { get; private set; }

        public FakeModel(string name)
        {
            Name = name;
        }

        public void UpdateName(string name)
        {
            Dependency.RandomAction();
            Name = name;
        }
    }
</code>```

Special considerations :

FakeModel and FakeDependency sit in a class library project that is reused my many other projects.

All the other projects using this class library doesn't know, and shouldn't even know, that FakeDependency exists.

There will always be only one (+test) implementation of FakeDependency.

The only reason to replace the FakeDependcy is to run tests that only test the class library.

Would you rewrite this code differently, or it makes sense considering the requirements?

EDIT

There seems to be some confusion about the dependency, the service locator and how to use the class library. Think about the model as the public interface of this class library. Everything else is hidden from other projects, is undocumented and subject to changes anytime. You should not ever used any other methods than those define by the model.

About the service locator; it lives inside the class library project. It's only purpose is to make it possible to test the class library and absolutely not to inject new dependencies into this library. If I wanted to make it possible to replace the dependency I would of course have used constructor injection like that public FakeModel(string name, FakeDependency dependency) but that is not the case.

Then how do you use this class library currently? Just like that :

```<code>public void Test()
{
    var model = new FakeModel("MyName");
    model.UpdateName("NewName");
}
</code>```

The class library should be self contained. Maybe using the word "dependency" is confusing as it's not something that you need to provide to the class library.

答:
Yes I would rewrite it.

Edit: new code based on your expanded comments and question:

```<code>[assembly: InternalsVisibleTo("TestAssembly")]
    public class FakeModel
    {
        private IFakeDependency dependency;
        public string Name { get; private set; }

        public FakeModel(string name)
        {
            Name = name;
            this.dependency = new FakeDependency();
        }
        //use this constructor in tests
        internal FakeModel(string name, IFakeDependency dependency)
        {
            Name = name;
            this.dependency = dependency;
        }
        public void UpdateName(string name)
        {
            dependency.RandomAction();
            Name = name;
        }
    }
</code>```

Body:
Yes I would rewrite it.

Edit: new code based on your expanded comments and question:

[assembly: InternalsVisibleTo("TestAssembly")]
    public class FakeModel
    {
        private IFakeDependency dependency;
        public string Name { get; private set; }

        public FakeModel(string name)
        {
            Name = name;
            this.dependency = new FakeDependency();
        }
        //use this constructor in tests
        internal FakeModel(string name, IFakeDependency dependency)
        {
            Name = name;
            this.dependency = dependency;
        }
        public void UpdateName(string name)
        {
            dependency.RandomAction();
            Name = name;
        }
    }


问:
Sync client-side data after service invocation in SPAs
Here's a simple scenario:

We have a list of tasks and can mark a task as completed by invoking a web service. Doing so will transition the status of the task to completed as well as initialize a completedOn data member.

Is it a good practice for services to return additional data members required for the UI to sync the client data state? To me, it feels a bit weird that the markTaskCompleted service or PUT /tasks/completed/ ... returns a completedOn data member in the response.

What's the preferred way of dealing with similar situations in the industry? Is there a widely adopted practice?

In the above case, I could probably just infer the completedOn value client-side, but that's not always possible.

答:
As far as I can tell, there's no reason to be concerned about a field like completedOn. Can you say more specifically about what concerns you? It would help us to understand your concerns if you could provide an example of an implementation that you think is more correct.

There are some downsides to determining the time stamp on the client in my view, mostly around clock synchronization, timezones, and multiple clients having different ideas of the value of the time stamp.

Edit:  One thing to consider is where the actual knowledge that the task was completed takes place. If the task is executed and complete on the client, then the client can and should be responsible for setting the time. If the task executes and completes on the server, then the completedOn field should be set there.


问:
TDD in theory only
A little over a year ago I was fortunate enough to be able to take a 9 month break from work.  I decided that in that time time I would hone my C# skills.  I started working on a bunch of projects and forced myself to follow TDD.

It was a fairly enlightening process.

It was tough at first, but over time I learned how to write more testable code (which, as it turns out, tends to be more SOLID code) and in the process I also sharpened my OO design skill.

Now I'm back in the workforce and I'm noticing something odd.

I prefer not to follow TDD.

I find TDD slows me down and actually makes it harder to design a clean application.

Instead, I've adopted a slightly (massively) different approach:

Pick a vertical slice of work

Develop a functioning prototype

Refactor until everything is nice and tidy

Sit back an appreciate the beautifully SOLID and testable code I've written.

You may have noticed that step 1 wasn't "define the public surface of my test target" and step 2 wasn't "test the bejesus out of said public surface."  You may have also noticed that none of the steps involve testing.  I'm writing testable code, but I'm not testing it... just yet.

Now, I'd like to make it clear that I'm not actually foregoing any kind of testing.  The code I'm writing works.  It works because I'm testing it manually.

I'd also like to make it clear that I'm not foregoing all automated testing either.  This is where my process is different.  And this is why I'm asking this question.

TDD in theory.  Not in practice.

My process has evolved a bit and I've struck a balance between TDD and no tests that I find very productive and also reasonably safe.  It goes as follows:

Implement a working vertical slice of work with testing in mind, but don't write any tests.

If down the road (eg, a month later) that slice needs modification

Write Unit Tests, Integration Tests, Behaviour Tests, etc that guarantee the slice of work is correct

Modify the code

If that slice doesn't need modification,

Do nothing

By simply shifting the burden of writing tests from before writing the code to before modifying the code I've been able to produce much more working code.  And, when I do get around to writing tests I write far fewer of them but cover nearly as much ground (higher ROI).

I like this process, but I'm concerned it might not scale well.  Its success hinges on developers being diligent about writing tests before they change things.  And that seems like a pretty big risk.  But, TDD has the very same risk.

So, am I going to [BT]DD hell, or is this a common form of pragmatic coding and testing?

I'd like to keep working this way.  What can I do to make this process work in the long term?

Note:

I am the sole developer on my projects and I am responsible for everything:  Requirements gathering, design, architecture, testing, deployment, etc.  I suspect this is why my process is working.

答:
Although TDD is tough to implement 100% there is a flaw in your approach

Implement a working vertical slice of work

1.1 1 year passes....

1.2 A new dev starts work on the project

If that slice needs modification

2.3 Parse 'Clean Coding' style method names and parameters 'GetUnicorn(colourOfUnicorn)'

2.4 Read xml comments 'Gets A gold unicorn (for riding)(obvs)'

2.5 Hunt down the original dev

2.6 Hope they remember what the code is supposed to do

2.7 Get them to explain it all

Write Unit Tests, Integration Tests, Behaviour Tests, etc that
hopefully guarantee the slice of work is correct

Modify the code

I think you are correct to identify that unit tests really show their value when modifications are required.

Title: TDD in theory only


问:
Clean Code comments vs class documentation
I'm having some discussions with my new colleagues regarding commenting. We both like Clean Code, and I'm perfectly fine with the fact that inline code comments should be avoided and that class and methods names should be used to express what they do.

However, I'm a big fan of adding small class summaries that tries to explain the purpose of the class and what is actually represents, primarily so that its easy to maintain the single responsibility principle pattern. I'm also used to adding one-line summaries to methods that explains what the method is supposed to do. A typical example is the simple method

```<code>public Product GetById(int productId) {...}
</code>```

I'm adding the following method summary

```<code>/// <summary>
/// Retrieves a product by its id, returns null if no product was found.
/// </summary
</code>```

I believe that the fact that the method returns null should be documented. A developer that wants to call a method should not have to open up my code in order to see if the method returns null or throws an exception. Sometimes it's part of an interface, so the developer doesn't even know which underlying code is running?

However, my colleagues think that these kinds of comments are "code smell" and that "comments are always failures" (Robert C. Martin).

Is there a way to express and communicate these types of knowledge without adding comments? Since I'm a big fan of Robert C. Martin, I'm getting a bit confused. Are summaries the same as comments and therefore always failures?

This is not a question about in-line comments.

答:
The value of a comment is measured in the value of the information it gives minus the effort needed to read it and/or ignore it. So if we analyze the comment

```<code>/// <summary>
/// Retrieves a product by its id, returns null if no product was found.
/// </summary>
</code>```

for value and cost, we see three things:

Retrieves a product by its id repeats what the name of the function says, so it's cost without value. It should be deleted.

returns null if no product was found is very valuable information. It likely reduces the times other coders will have to look at the implementation of the function. I'm quite certain that it saves more reading than the reading cost it introduces itself. It should stay.

The lines

```<code>/// <summary>
/// </summary>
</code>```

carry no information whatsoever. They are pure cost to the reader of the comment. They may be justified if your documentation generator needs them but in that case you should probably think about a different documentation generator.

This is the reason why the use of documentation generators is a disputable idea: They generally require a lot of additional comments that carry no information or repeat obvious stuff, just for the sake of a polished document.

An observation that I have not found in any of the other answers:

Even comments that are not necessary to understand/use the code can be very valuable. Here is one such example:

```<code>//XXX: The obvious way to do this would have been ...
//     However, since we need this functionality primarily for ...
//     doing this the non-obvious way of ...
//     gives us the advantage of ...
</code>```

Likely a lot of text, completely unnecessary to understand/use the code. However, it explains a reason why the code looks the way it does. It will stop people short that look at the code, wonder why it's not done the obvious way, and would start refactoring the code until they realize why the code was written like this in the first place. And even if the reader is smart enough to not jump to refactoring directly, they still need to figure out why the code looks the way it does before they realize that it should best stay the way it is. This comment could literally save hours of work. Thus the value is higher than the cost.

Likewise, comments can communicate the intentions of a code, instead of just how it works. And they can paint the big picture that's usually lost in the minute detail of the code itself. As such, you are right in being in favor class comments. I value class comments the most if they explain the intention of the class, how it interacts with other classes, how it is meant to be used, etc. Alas, I'm not a big author of such comments...

Body:
The value of a comment is measured in the value of the information it gives minus the effort needed to read it and/or ignore it. So if we analyze the comment

/// <summary>
/// Retrieves a product by its id, returns null if no product was found.
/// </summary>

for value and cost, we see three things:

Retrieves a product by its id repeats what the name of the function says, so it's cost without value. It should be deleted.

returns null if no product was found is very valuable information. It likely reduces the times other coders will have to look at the implementation of the function. I'm quite certain that it saves more reading than the reading cost it introduces itself. It should stay.

The lines

/// <summary>
/// </summary>

carry no information whatsoever. They are pure cost to the reader of the comment. They may be justified if your documentation generator needs them but in that case you should probably think about a different documentation generator.

This is the reason why the use of documentation generators is a disputable idea: They generally require a lot of additional comments that carry no information or repeat obvious stuff, just for the sake of a polished document.

An observation that I have not found in any of the other answers:

Even comments that are not necessary to understand/use the code can be very valuable. Here is one such example:

//XXX: The obvious way to do this would have been ...
//     However, since we need this functionality primarily for ...
//     doing this the non-obvious way of ...
//     gives us the advantage of ...

Likely a lot of text, completely unnecessary to understand/use the code. However, it explains a reason why the code looks the way it does. It will stop people short that look at the code, wonder why it's not done the obvious way, and would start refactoring the code until they realize why the code was written like this in the first place. And even if the reader is smart enough to not jump to refactoring directly, they still need to figure out why the code looks the way it does before they realize that it should best stay the way it is. This comment could literally save hours of work. Thus the value is higher than the cost.

Likewise, comments can communicate the intentions of a code, instead of just how it works. And they can paint the big picture that's usually lost in the minute detail of the code itself. As such, you are right in being in favor class comments. I value class comments the most if they explain the intention of the class, how it interacts with other classes, how it is meant to be used, etc. Alas, I'm not a big author of such comments...


问:
How do you judge if you're paid enough?
How do you evaluate how much you feel you ought to be paid as a junior programmer?</p>

答:
I keep a nose out on the market and occasionally get some offers I listen to. They give a rough estimate around how much you could achieve in terms of payment.

Also if you look at consultant firms they usually have a "ladder" with titles such as junior, senior etc. each with a pay-level and expected performance. If you meet up at consultant firms reqruitment events every now and then you can get the chance to see what the levels are like.

ContentLicense: CC BY-SA 2.5

Title: How do you judge if you're paid enough?


问:
Why do we use the word "sprint"?
One of the founding principles of the Agile Manifesto is

Agile processes promote sustainable development.  The sponsors,
  developers, and users should be able  to maintain a constant pace
  indefinitely.

Scrum teams use the term sprint to refer to a work cycle (also known as an iteration).

However this doesn't make sense to me. According to Google a sprint is:

run at full speed over a short distance.

In other words it's not sustainable. Why do Scrum teams use the word sprint? It appears to me to conflict one of the basic principles of Agile.

答: The idea is that between sprints, you have meetings to communicate project status, fix pressing issues, and generally regroup. In Agile terminology's mixed metaphor, you can imagine sprints are separated by rests (meetings, planning, etc).</p>

Title: Why do we use the word "sprint"?


答:
I would assume it's because in a sprint, you know where you are and you know where you need to get to, and it's a fairly linear path to get there. It's not sustainable over the long term, but sprints in software development are not very long before you plot out your next destination.

Similarly, you could run a short sprint each day (in workout terms, I mean). As long as you are taking rests and plotting out goals and destinations it is attainable.

Title: Why do we use the word "sprint"?

Body:
One of the founding principles of the Agile Manifesto is

Agile processes promote sustainable development.  The sponsors,
  developers, and users should be able  to maintain a constant pace
  indefinitely.

Scrum teams use the term sprint to refer to a work cycle (also known as an iteration).

However this doesn't make sense to me. According to Google a sprint is:

run at full speed over a short distance.

In other words it's not sustainable. Why do Scrum teams use the word sprint? It appears to me to conflict one of the basic principles of Agile.


答:
In other words it's not sustainable.

Right.

You don't run a sprint for months at a time in most Agile (well functioning ones, I'm sure some "we wanted buzzwords so we're an Agile waterfall shop" do), you have short sprints, followed by new planning/retros/etc.

That's the point.

Why do Scrum teams use the word "Sprint"? It appears to me to conflict one of the basic principals of Agile.

The basic principles of Agile are relatively broad, but the main point is to not run a "marathon" that's planned initially (ie waterfall), but to break it into very short pieces.

Hence, "sprint."

As for where the term came from within Agile, the SCRUM Development Process seminal work used the term. I suspect no one has changed it since.

For those of you curious about length, from that work:

A Sprint is a set of development activities conducted over a pre-defined period, usually
  one to four weeks. The interval is based on product complexity, risk assessment, and
  degree of oversight desired. Sprint speed and intensity are driven by the selected duration of the Sprint.

Title: Why do we use the word "sprint"?


问:
On testing the testers
My question is similar to Leaving intentional bugs in code for testers to find:

We don't do this at our firm, but one of my friends says that his
  project manager asked every dev to add intentional bugs just before
  the product goes to QA...

...If you ignore the scenario were one of these intentional bugs gets
  shipped with the final product, what are the other drawbacks we should
  consider before even thinking of adopting this approach?

The difference is that I had different premises. I wanted to make a point without messing with anyone. Intended bugs not for motivation but for testing the testers, to point out that quality assurance process is dysfunctional.

I was working on a rather large and important feature. Critical part the of feature was that users could get a discount under certain circumstances. Problem that we had with that project was that QA was very sloppy and missed a lot of important bugs. On the other side project manager had a lot of faith in QA. In my opinion bad QA is worse than no QA, because it only adds illusions about quality. Couple of times I got into arguments with PM but I gave up and just decided that I should be my own tester and just assume that QA doesn't exist.

At some point a brilliant idea came to my mind - to test the QA. I found completely outrageous bug and decided that instead of fixing it I would leave it as is and see if the QA finds it. Bug was really bad. When user placed an order and got a discount, the browser redirects to payment provider and there user sees price without discount and is charged accordingly. This was a critical path bug.

Long story short, QA didn't find a bug, I fixed it before release of course and even created a ticket and politely announced it without blaming anyone to see the reaction. Both QA and PM didn't really cared, just said okay and that's it.

After that I finalized my conclusions about our QA but PM still had a lot of faith in him. I told some time after to assistant PM in private conversation, she told me to speak to his management, but I decided not to pursue and just carry on on my own because I really didn't know how to present the case.

So my questions are:

Is it good idea to test testers by leaving bugs or even creating them?

How to handle the situation where it happened, intentionally or not?

How to otherwise point out low efficiency of QA?

How to do it without forcing people losing face and creating tensions and conflicts?

答:
Is it good idea to test testers by leaving bugs or even creating them?

No, you don't want your employees playing petty games about who can stump who, rather than delivering actual value.

If your QA department is not delivering value you likely:

Have a company who assumes testing is not worth paying for and hires duds for QA roles

Don't have documentation about functionality to test

Have bad/nonexistent tests for key functionality

How to handle the situation where it happened, intentionally or not?

You are a professional.

Professionals don't play silly jokes to "gotcha!" their coworkers. So, don't do it again.

How to otherwise point out low efficiency of QA?

Do your customers complain? Most people with pay levels able to affect this sort of problem don't care if a dev is upset.. but they care if the customer starts having significant problems, bugs, or otherwise lost revenue.

How to do it without forcing people losing face and creating tensions and conflicts?

Document how this affects the end user and show management that insufficient QA processes exist.

Realistically, you probably need a combination of:

More automated testing

Better defined QA requirements (if you have user requirements, convert these into stories/activities QA must do before a release)

Title: On testing the testers


问:
GPLv3 frontend and BSD backend, do I have to disclose the backend source?
I've gone through a couple of Question on GPL here, but all of them are related to the compiled languages, libraries and distribution.

My web project has a backend that is BSD licensed. The front end is a GPLv3 licensed JavaScript framework which renders a background image that doesn't link to anything from the backend and only renders in the web browser.

Am I required to make available the backend code to the public if I use the GPLv3 licensed library? We are not modifying the GPLv3 licensed library, just using it as is.

Update

I've contacted the library author here is his reply:

I am not a lawyer, so all I can say is that The Library is made
  available under the GPLv3. Including it as a dependency in a
  commercial program does not, to my understanding, violate GPLv3.
  Including a modified version of it without releasing the source to the
  modified version would.

答:
The GPL is not capable of "infecting" software it talks to over a network, so no, you do not have to disclose your server-side code.

In fact, this is closely related to why the Affero GPL exists:

The GNU Affero General Public License is a modified version of the
ordinary GNU GPL version 3. It has one added requirement: if you run a
modified program on a server and let other users communicate with it
there, your server must also allow them to download the source code
corresponding to the modified version running there.

The AGPL does not "infect across networks" either; even this extra condition is only meant to close the "but the user never runs it" loophole for server-side AGPL'd code. So your client-side Javascript library being GPL or LGPL or AGPL or whatever does not create a disclosure requirement for any server-side code. Only if your server-side code was linked to an AGPL library would you have to make it available.

Edit: I just noticed this section in the FSF's GPL FAQ is highly relevant:

Q: A company is running a modified version of a GPL'ed program on a web
site. Does the GPL say they must release their modified sources?
(#UnreleasedMods)

A: The GPL permits anyone to make a modified version
and use it without ever distributing it to others. What this company
is doing is a special case of that. Therefore, the company does not
have to release the modified sources.

It is essential for people to have the freedom to make modifications
and use them privately, without ever publishing those modifications.
However, putting the program on a server machine for the public to
talk to is hardly “private” use, so it would be legitimate to require
release of the source code in that special case. Developers who wish
to address this might want to use the GNU Affero GPL for programs
designed for network server use.


答:
I think this is the critical part of the issue here:

I was working on a rather large and important feature. Critical part
  the of feature was that users could get a discount under certain
  circumstances. Problem that we had with that project was that QA was
  very sloppy and missed a lot of important bugs. On the other side
  project manager had a lot of faith in QA. In my opinion bad QA is
  worse than no QA, because it only adds illusions about quality. Couple
  of times I got into arguments with PM but I gave up and just decided
  that I should be my own tester and just assume that QA doesn't exist.

I will answer your questions in the context of that paragraph.

Is it good idea to test testers by leaving bugs or even creating them?

No, you test your testers by measuring legitimate defects that made it through QA. Sure, if they miss an esoteric bug that is nigh impossible to reproduce or find then go easy on them. If they report a bug that project management chooses to ignore then it blows up with the customer you absolutely do not make it into an issue with QA.

How to handle the situation where it happened, intentionally or not?

If your QA are lazy and let obvious or major bugs through and your testing procedures would have caught them then this becomes a performance evaluation issue. I would not advocate employee performance being strictly related to bugs (e.g. you let 25% of the defects through this year, your annual raise is being docked 25%) but clearly if a QA employee is not finding obvious bugs (you know, his job) then maybe he should not be employed anymore.

How to otherwise point out low efficiency of QA?

Measure it, but be reasonable. See my explanation above. Everyone makes mistakes. But if a manager is hesitant to assign a QA employee to a high profile project because of performance concerns, well, his gut feeling just figured it out.

Yes, I have seen this happen.

How to do it without forcing people losing face and creating tensions and conflicts?

Not going to happen. You can be polite and professional all you want. At some point, QA are simply allowing too many bugs to slip through and management must address it or face economic consequences (e.g. customers jumping ship to competing products).

The alternative is to use management tools to address the poor performance: training, assign to an easy project, paired testing, and eventually, the other path: written reprimands for poor performance, and eventually, termination.

Title: On testing the testers

Body:
My question is similar to Leaving intentional bugs in code for testers to find:

We don't do this at our firm, but one of my friends says that his
  project manager asked every dev to add intentional bugs just before
  the product goes to QA...

...If you ignore the scenario were one of these intentional bugs gets
  shipped with the final product, what are the other drawbacks we should
  consider before even thinking of adopting this approach?

The difference is that I had different premises. I wanted to make a point without messing with anyone. Intended bugs not for motivation but for testing the testers, to point out that quality assurance process is dysfunctional.

I was working on a rather large and important feature. Critical part the of feature was that users could get a discount under certain circumstances. Problem that we had with that project was that QA was very sloppy and missed a lot of important bugs. On the other side project manager had a lot of faith in QA. In my opinion bad QA is worse than no QA, because it only adds illusions about quality. Couple of times I got into arguments with PM but I gave up and just decided that I should be my own tester and just assume that QA doesn't exist.

At some point a brilliant idea came to my mind - to test the QA. I found completely outrageous bug and decided that instead of fixing it I would leave it as is and see if the QA finds it. Bug was really bad. When user placed an order and got a discount, the browser redirects to payment provider and there user sees price without discount and is charged accordingly. This was a critical path bug.

Long story short, QA didn't find a bug, I fixed it before release of course and even created a ticket and politely announced it without blaming anyone to see the reaction. Both QA and PM didn't really cared, just said okay and that's it.

After that I finalized my conclusions about our QA but PM still had a lot of faith in him. I told some time after to assistant PM in private conversation, she told me to speak to his management, but I decided not to pursue and just carry on on my own because I really didn't know how to present the case.

So my questions are:

Is it good idea to test testers by leaving bugs or even creating them?

How to handle the situation where it happened, intentionally or not?

How to otherwise point out low efficiency of QA?

How to do it without forcing people losing face and creating tensions and conflicts?


答:
Low-quality QA is wretched, and if you can't get Management to recognize that they're not doing their job, that's even worse.  But the only person that's going to be blamed for intentionally putting in a terrible bug is you - for wasting everyone else's time, and for putting in a bug that, if QA is as bad as you say it is, will go into production and ruin the company.

Best case scenario - you get blamed and lose your job.  Worst case scenario - you get blamed and everyone loses their job.

Title: On testing the testers


问:
What are my options for exposing customization settings to the admin user?
I'm writing a blog system as a learning exercise and I would like to allow the admin (or blog owner) to select/change some custom options based on features that I choose to expose to them such as:

change blog name (string)

select layout (int)

number of blog entries per page (int)

more stuff like this...

The only way that I can really think of to do this is by creating a class, with a property for each option and letting the owner get and set the properties.

What are my options for exposing customization settings to the admin / owner?

This is how I've implemented it for the time-being, although I am aware that this may not be the best way to do this:

I've created a class called Setting.cs

```<code>    public class Setting : IEntity
    {
        [Key]
        public int Id { get; set; }
        public string BlogName { get; set; }
        public string SubTitle { get; set; }
        public int PostsPerPage { get; set; }

    }
</code>```

Then I added a settings method to my Admin Dashboard controller like this:

```<code>    public ActionResult Settings(int? id = 1)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Setting set = db.Settings.Find(id);

        if (set == null)
        {
            return HttpNotFound();
        }
        return View(set);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    [ValidateInput(false)]
    public ActionResult Settings([Bind(Include = "Id,BlogName,SubTitle,PostsPerPage")] Setting sets)
    {
        if (ModelState.IsValid)
        {
            db.Entry(sets).State = System.Data.Entity.EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index", "Dashboard");
        }
        return View(sets);
    }
</code>```

I then seed the record and just retrieve the same record and update it with the new settings each time.

I suppose I should state my concerns:

It seems strange to store a single row of data in it's own table of my database.

It also seems strange that if one wanted to, one could instantiate the Settings.cs class and possibly make multiple records of it.

I've hard-coded my controller with the record ID, as well as any calls to the controller, which to me feels like I'm abusing the intended purpose of using a controller by hard coding it.

I'm new to programming but this doesn't seem right to me. In Swift iOS programming I could create a pList (flat-file) or store settings in the NSUserDefaults. I'm just wondering what my options are in ASP.NET MVC.

I originally wanted to ask "What's the best way to implement admin/owner settings?" but I didn't want my question closed as being subjective. I am, however, hoping to deduce what the preferred method is ultimately to adhere to best practices.

答:
My experience is that the "settings" supported by C# out of the box are not very useful.

Storing the settings in the database is a much better idea for a number of reasons.

It will be possible to take a complete backup of the blog by backing up the database without having to remember what other files you need.

If you one day decide to take this system of yours, which currently implements a single blog for a single user, and turn it into a blogging platform supporting many blogs operated by multiple users, you will just create multiple settings records, one for each user, and at least that part will be taken care of.  With a settings file, such a thing would be impossible, you would certainly have to rewrite your settings mechanism to make use of the database at that point.

Your settings may need to refer to rows in the database, in which case it only makes sense to also store the settings in the database in order to enjoy the benefits of referential integrity checking. For example, you may wish to add a setting for a "sticky post" which is to always be displayed first, regardless of how old it is. If you go with a settings file, then the "sticky post id" setting will be just a meaningless number, interpreted by your code to (hopefully) correspond to a blog post.  If you store your settings in the database, then the RDBMS will ensure that this number will in fact be the actual id of an existing row in the blog posts table.  (Or NULL, if you don't want a sticky post.)

Need I go on?

The way this is usually accomplished is by having a settings table with a single row in it.  This is not just a wild idea that you had, it is a legitimate technique which has actual application in the real world.

There is no way to guarantee that additional rows will never be accidentally added to the settings table, but at least you can count the rows during startup and display an error message if more than one row is found.

You can easily guarantee that there will always be only one instance of the settings object by adding a private static bool member to it, and Asserting from the constructor of the object that this bool is false, then setting it to true. This means that the constructor may only be invoked once.


问:
Are imperative events an anti-pattern?
Are events which are intended to tell listeners to carry out explicit actions an anti-pattern?

Imagine a worker service which raises the event WorkStarted at its beginning and the event WorkFinised at its end.

These events convey information about what that worker service did and they are not inherently imperative to any of the potential subscribers of that event.

Consider that it may be the intention of the application to use this event to show or hide a loading icon. Is it an anti-pattern for the worker service to raise a ShowLoadingIcon and HideLoadingIcon event instead?

In this case no information about what the worker service did is conveyed, only an instructive request is made.

In what cases, if any, are either these approaches inappropriate or preferred?

EDIT: To clarify, I'm asking about the existence of standards for event-driven programming. All standardization questions include some amount of opinion, and yet the site is littered with them because there is a different between a question of personal preference and one of generally accepted good practice.

答:
The way to decide what an event should represent is the good old Single Responsibility Principle.

If, for instance, you have a long-running tax computation process and an incremental GUI visualization that displays its progress, then the tax processor should raise "started", "progress" or "finish" events. A GUI class should listen to these events and do whatever is appropriate GUI-wise, e.g. show or hide the "wait..." icon.

That way, the tax processor processes taxes, and the GUI class renders a GUI. If you defined a "HideWaitIcon" Event, then the tax processor would have to know about GUI details, which isn't it's job (and which would make it harder to write a different front-end for the same back-end). That's why our first solution is superior.

Title: Are imperative events an anti-pattern?


答:
One thing I have always associated with "sprint" is that it encourages the attitude of putting the head down and pushing to the end of the sprint without as much concern for what happens beyond the sprint, or for changing environments during the sprint.

It is my opinion that this mindset is actually more important for management than it is for the developers. The developers are exposed to the nitty-gritty reality of development. They know what has to be done and how to do it.

However, management is not always in tune with this part of the reality of the business. The word "sprint" is something they can hold in their mind which defends the explanation of why you can't change direction mid-sprint. The team is sprinting, committed to achieving the product in the shortest possible time.  Consider the difference between a 100 yard sprint and a 100 yard hurdle.

Title: Why do we use the word "sprint"?


问:
Multiple MySQL update calls per second, can some of them be "missed"?
I have simple question, I think its not that big of a deal, but I'd still like to ask it as its boggling my mind for past 2 days a lot.

What if I have a poll where instead of inserting answers to MySQL table one per row, it would just change the amount of votes answer got in row with poll data?

So basically my code would just call UPDATE polls SET optionX=optionX+1 WHERE id='$poll_id' instead of INSERT INTO poll_votes (option, ip, poll) VALUES ('X', '$user_ip', '$poll_id') - this is simplified version, but base is the same.

My question is, what happens if 1.000 people would submit their answer at same time. Its there any remote chance of server taking data from MySQL where optionX was not updated by previous call yet, and as the previous call (user) updates it, then new one would override it basically loosing that one vote?

TL;DR: Can this happen?

User 1 sends vote for Option 4

PHP downloads data from MySQL where Option 4 has 49 votes

User 2 sends vote for Option 4

PHP downloads data from MySQL where Option 4 has still 49 votes

PHP finishes updating request and sets MySQL for Option 4 to have 50 votes

PHP Finishes updating second request and sets Option to have 50 votes instead of 51

Main concern for me is, that I am storing all options as one array in one cell, so I can allow users to have stupidly long polls without need to have extremely messy MySQL table structure.

I think chances are really thin, but I am not sure if it can happen or if there are some safeties for such things.

答:
No ACID-compliant database will cause an error or incorrect data in this situation unless you actively try to work against it by explicitly messing with locking hints or other weird stuff that most people do not do.

MySQL is ACID-compliant by default. I have not checked lately, but you may be able to use ancient table types that do not guarantee this. As long as you are using a MySQL version no more than about ten years old and are not pointing a gun at your foot and pulling the trigger, you will not accidentally have a non-ACID-compliant table type.

A: Atomicity. An operation succeeds or fails as a whole. Either the increment works as a unit or it fails as a unit.

I: Isolation. Threads cannot see "partial" results of other threads.

The atomicity ensures that the statement cannot fail halfway through (the Consistency helps here too, e.g. if there is a crash while the SQL is updating a table). Isolation guarantees you do not have the classic threading example of interleaving two increments (which you describe in your question).


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
Non blocking SQL Queries (Like insert some log, but don't wait for result of query)

Parallel SQL Queries

just a dream

OwnerDisplayName: Erlango


问:
How do Java AOT compilers work?
There are a few number of tools out there (Excelsior JET, etc.) that claim to transform Java app's into native executables (*.exe). However it is my understanding that these tools are really just creating native wrappers that invoke/execute java from a shell or command-line.

If that understanding is incorrect, I don't see how it could be. If a running JVM (java process) is essentially a high performance interpreter, loading bytecode from Java classfiles on the fly, then I don't see how a Java app (a collection of bytecode files that serve as input to a JVM) could ever be truly converted into an executable.

This is because the JVM process is already a native executable that takes sets of bytecode files as input. To merge those bytecode files and the JVM process into a single, unified native executable doesn't seem possible without completely rewriting the JVM and de-railing from the JVM specification.

So I ask: how do these tools actually "transform" Java class files into a native executable, or do they?

答:
All programs have a runtime environment. We tend to forget this, but its there. Standard lib for C that wraps system calls to the operating system.  Objective-C has its runtime that wraps all of its message passing.

With Java, the runtime is the JVM.  Most of the Java implementations that people are familiar with are similar to the HotSpot JVM which is a byte code interpreter and JIT compiler.

This doesn't have to be the only implementation. There is absolutely nothing saying you can't build a standard lib-esque runtime for Java and compile the code to native machine code and run that within the runtime that handles calls for new objects into mallocs and file access into system calls on the machine. And thats what the Ahead Of Time (AOT rather than JIT) compiler does.  Call that runtime what you will... you could call it a JVM implementation (and it does follow the JVM specification) or a runtime environment or standard lib for Java. Its there and it does essentially the same thing.

It could be done either by reimplementing javac to target the native machine (that's kind of what GCJ did).  Or it could be done with translating the byte code generated by javac into machine (or byte) code for another machine - that's what Android does.  Based on Wikipedia that's what Excelsior JET does too ("The compiler transforms the portable Java byte code into optimized executables for the desired hardware and operating system (OS)"), and the same is true for RoboVM.

There are additional complications with Java that means this is very hard to do as an exclusive approach. Dynamic loading of classes (class.forName()) or proxied objects require dynamics that AOT compilers do not easily provide and so their respective JVMs must also include either a JIT compiler (Excelsior JET) or an interpreter (GCJ) to handle classes that couldn't be precompiled into native.

Remember, the JVM is a specification, with many implementations.  The C standard library is also a specification with many different implementations.

With Java8, a fair bit of work has been done on AOT compilation. At best, one can only summarize AOT in general within the confines of textbox.  However, in the JVM Language Summit for 2015 (August of 2015), there was a presentation: Java Goes AOT (youtube video).  This video is 40 minutes long and goes into many of the deeper technical aspects and performance benchmarks.

Title: How do Java AOT compilers work?


问:
Should I write complex Linq queries?
I often find complex Linq queries that span over 10-15 lines in our code base.

I find such queries hard to understand and impossible to debug.

I've tried to split the query to smaller parts, but it's hard to do since usually inner parts depend on the outer scope variables. Think of nested loops in imperative code.

Is this an indication of my inproficiency with Linq? Are complex Linq queries justified?

Would imperative solution be better in such cases?

Below is a sample query...

```<code> var xItems = (
            from responseData in filteredItems
            let parentLevelItems = responseData.Items.Where(adi => ids.Contains(adi.Id))
            select new
            {
                secondLevelData =
                (from c in secondLevelLabels
                    join secondLevel in responseData.children on c
                    equals string.IsNullOrEmpty(secondLevel.Label) ?
                                           Constants.BlankData : secondLevel.Label into coun
                    from cn in coun.DefaultIfEmpty()
                    select new
                    {
                        secondLevelLabel = c,
                        parentLevelItems = parentLevelItems,
                        dataItems = cn == null ? response :
                                                 cn.Items.Where(adi => ids.Contains(adi.Id))
                    })
            });
</code>```

答:
Let's rewrite that without any LINQ or LINQ extensions:

```<code>var xItems = new List<object>();
foreach(var responseData in filteredItems)
{
    var parentLevelItems = new List<Item>();
    foreach(var adi in responseData.Items)
    {
        if(ids.Contains(adi.Id))
        {
            parentLevelItems.Add(adi);
        }
    }

    var coun = new Dictionary<Label, List<Data>>();
    foreach(var c in secondLevelLabels)
    {
        foreach(var secondLevel in responseData.Children)
        {

            if(c == string.IsNullOrEmpty(secondLevel.Label) ?
                                           Constants.BlankData : secondLevel.Label)
            {
                if(!coun.ContainsKey(c))
                {
                   coun[c] = new List<Data>();
                }
                count[c].Add(secondLevel);
            }
        }
        var secondLevelData = new List<object>();
        foreach(var cn in coun.DefaultIfEmpty())
        {
            secondLevelData.Add(new
            {
                secondLevelLabel = c,
                parentLevelItems = parentLevelItems,
                dataItems = cn == null ? response :
                                                 cn.Values.Where(adi => ids.Contains(adi.Id))
            });
        }
    }

    xItems.Add(new
    {
        secondLevelData = secondLevelData;
    });
}
</code>```

I took some liberties with making up type names, translating the group join, and I did in fact keep some simple LINQ extensions (Contains and DefaultIfEmpty) to avoid going too mad. Nonetheless, looking at the above, I think it's relatively clear that your root problem isn't the choice of LINQ over loops.

Actually, the right way to deal with this code is probably with the usual refactorings: rename and extract method.

Names range from terrible (cn,coun) to the pretty-bad (xItems, secondLevelItems). It's hard to say for sure without knowing the context of this code, but you should be able to find more expressive names for these. This is a lot of complex logic, it seems like what it applies to should be more specific than just an "item"!

As for extracting methods, you say:

I've tried to split the query to smaller parts, but it's hard to do since usually inner parts depend on the outer scope variables.

Well, this is where parameters come in handy! If loops are still more natural to you, you could always try translating from LINQ to loops, extracting out your methods, then translating the individual bits back to LINQ again.

More generally, you don't get any kind of automatic bonus points for using LINQ. There are two reasons it might be preferable:

It's more declarative than loop-writing, making your code more expressive by letting you write what you're trying to achieve rather than how you're doing it.

It may be easier to keep lazy evaluation.

The latter is very situation-specific, so let's focus on the former. That's really just a particular type of readability benefit. Usually it's enough, but I've definitely seen cases (often involving the Aggregate extension method) where the LINQ version is just plain harder to decipher than the loop version. In that case, go for the loops! It'd be crazy to pick the less readable option in the name of readability.

If you're worried that lack of experience with LINQ means your judgement may not be good on readability, there's really not too much you can do about that other than seek out the judgement of others and gain more experience. But if, as in your example, complexity is about the sheer length rather than too stuff much being packed into too few statements, there's a good chance that the choice of LINQ isn't ultimately what's causing the problem.

Title: Should I write complex Linq queries?

Body:
Let's rewrite that without any LINQ or LINQ extensions:

var xItems = new List<object>();
foreach(var responseData in filteredItems)
{
    var parentLevelItems = new List<Item>();
    foreach(var adi in responseData.Items)
    {
        if(ids.Contains(adi.Id))
        {
            parentLevelItems.Add(adi);
        }
    }

    var coun = new Dictionary<Label, List<Data>>();
    foreach(var c in secondLevelLabels)
    {
        foreach(var secondLevel in responseData.Children)
        {

            if(c == string.IsNullOrEmpty(secondLevel.Label) ?
                                           Constants.BlankData : secondLevel.Label)
            {
                if(!coun.ContainsKey(c))
                {
                   coun[c] = new List<Data>();
                }
                count[c].Add(secondLevel);
            }
        }
        var secondLevelData = new List<object>();
        foreach(var cn in coun.DefaultIfEmpty())
        {
            secondLevelData.Add(new
            {
                secondLevelLabel = c,
                parentLevelItems = parentLevelItems,
                dataItems = cn == null ? response :
                                                 cn.Values.Where(adi => ids.Contains(adi.Id))
            });
        }
    }

    xItems.Add(new
    {
        secondLevelData = secondLevelData;
    });
}

I took some liberties with making up type names, translating the group join, and I did in fact keep some simple LINQ extensions (Contains and DefaultIfEmpty) to avoid going too mad. Nonetheless, looking at the above, I think it's relatively clear that your root problem isn't the choice of LINQ over loops.

Actually, the right way to deal with this code is probably with the usual refactorings: rename and extract method.

Names range from terrible (cn,coun) to the pretty-bad (xItems, secondLevelItems). It's hard to say for sure without knowing the context of this code, but you should be able to find more expressive names for these. This is a lot of complex logic, it seems like what it applies to should be more specific than just an "item"!

As for extracting methods, you say:

I've tried to split the query to smaller parts, but it's hard to do since usually inner parts depend on the outer scope variables.

Well, this is where parameters come in handy! If loops are still more natural to you, you could always try translating from LINQ to loops, extracting out your methods, then translating the individual bits back to LINQ again.

More generally, you don't get any kind of automatic bonus points for using LINQ. There are two reasons it might be preferable:

It's more declarative than loop-writing, making your code more expressive by letting you write what you're trying to achieve rather than how you're doing it.

It may be easier to keep lazy evaluation.

The latter is very situation-specific, so let's focus on the former. That's really just a particular type of readability benefit. Usually it's enough, but I've definitely seen cases (often involving the Aggregate extension method) where the LINQ version is just plain harder to decipher than the loop version. In that case, go for the loops! It'd be crazy to pick the less readable option in the name of readability.

If you're worried that lack of experience with LINQ means your judgement may not be good on readability, there's really not too much you can do about that other than seek out the judgement of others and gain more experience. But if, as in your example, complexity is about the sheer length rather than too stuff much being packed into too few statements, there's a good chance that the choice of LINQ isn't ultimately what's causing the problem.


问:
How can a computer round the last digit in a floating point representation?
I'm confused by how a computer rounds off the last digit in the floating point representation. For example, I'm told that x=1.24327789 is stored in a computer with a 6-digit capacity then it;s floating point representation would be x=0.124328x101, where clearly the last digit has been rounded.

My confusion refers to how the computer can have the capacity to round this last digit, if it hasn't a 7-digit capacity in order to know the 'last' digit.

I probably have a half-assed way of understanding this representation, but I really have no background in CompSci.

答:
With a few odd exceptions, a floating point number is stored as binary in the standard known as IEEE 754.  These are most often 32 bit (single percision) and 64 bit (double precision) representations. The 32 bit representation can store approximately 7 decimal digits, but remember that the underlying representation is in binary.

The representation of 1.2432778910 is actually 00111111100111110010001110111011 as a single precision IEEE 754 floating point number in binary.

This is made up of three parts:

The sign bit (0 indicating it is positive)

The exponent (01111111 which is 127) giving 2127-127 coming out to be 20

The mantissa (00111110010001110111011) which has a leading 1 implicit.

This gives us +20 * 1.00111110010001110111011 which then gives you your number.  If you look at the first couple bits there of 1.00111112 you will see that this is rather close to 1.2510 or 1.012.

On reading binary numbers past the binary (not decimal) point...

Just as 10012 represents 1*23 + 0*22 + 0*21 + 1*20, the value 1.0112 represets 1*20 + 0*2-1 + 1*2-2 + 1*2-3  or 1 + (1/4) + (1/8)

Now, that conversion I did a bit above - I grabbed it from an IEEE 754 converter because doing it by hand is tedious - its typically a good part of an assignment at the college level.

Rounding is actually a big deal.  As described in Lecture Notes on the Status of
IEEE Standard 754 for Binary Floating-Point Arithmetic from '97, rounding issues abounded in the 70s.

The number 1.24327789 in binary is 1.0011111001000111011101011011010101100011110011111000100000111...2

So, the 1 is assumed and the mantissa is 23 bits of that...

```<code>         1         2   |
12345678901234567890123v
0011111001000111011101011011010101100011110011111000100000111
</code>```

And you see at the arrow that this number should be rounded up which gives us 001111100100011101110112 which is the mantissa from above.  And thats how it is represented and rounded. You should note that as this is rounded up it is slightly greater than the original and closer to  1.24327790737152110.

Body:
With a few odd exceptions, a floating point number is stored as binary in the standard known as IEEE 754.  These are most often 32 bit (single percision) and 64 bit (double precision) representations. The 32 bit representation can store approximately 7 decimal digits, but remember that the underlying representation is in binary.

The representation of 1.2432778910 is actually 00111111100111110010001110111011 as a single precision IEEE 754 floating point number in binary.

This is made up of three parts:

The sign bit (0 indicating it is positive)

The exponent (01111111 which is 127) giving 2127-127 coming out to be 20

The mantissa (00111110010001110111011) which has a leading 1 implicit.

This gives us +20 * 1.00111110010001110111011 which then gives you your number.  If you look at the first couple bits there of 1.00111112 you will see that this is rather close to 1.2510 or 1.012.

On reading binary numbers past the binary (not decimal) point...

Just as 10012 represents 1*23 + 0*22 + 0*21 + 1*20, the value 1.0112 represets 1*20 + 0*2-1 + 1*2-2 + 1*2-3  or 1 + (1/4) + (1/8)

Now, that conversion I did a bit above - I grabbed it from an IEEE 754 converter because doing it by hand is tedious - its typically a good part of an assignment at the college level.

Rounding is actually a big deal.  As described in Lecture Notes on the Status of
IEEE Standard 754 for Binary Floating-Point Arithmetic from '97, rounding issues abounded in the 70s.

The number 1.24327789 in binary is 1.0011111001000111011101011011010101100011110011111000100000111...2

So, the 1 is assumed and the mantissa is 23 bits of that...

         1         2   |
12345678901234567890123v
0011111001000111011101011011010101100011110011111000100000111

And you see at the arrow that this number should be rounded up which gives us 001111100100011101110112 which is the mantissa from above.  And thats how it is represented and rounded. You should note that as this is rounded up it is slightly greater than the original and closer to  1.24327790737152110.


问:
Should heavy initialization be stored as a static variable or instance variable?
I have a that class does not really specify any real object on its own but is more of a utility class. It has some data whose initialization is expensive. I see two options on how to store the data:

Store it in a static variable(initialized in a static block).

Pro: I can call the utility methods without having to create an
instance of this class.

Con: The heavy initialization code is run
when the class is loaded, independent of whether it is used or not.

Store it in an instance variable(initialized in the constructor):

Pro: The heavy initialization is only done if the class is used.

Con: In this case I will have to create an object of the class and then call the utility methods through this object. I will also need to avoid creating multiple objects of the utility class.

Which of these two approaches is better?

答:
If you're storing data of any kind in the class, especially if it's an expensive item of data, you should be storing it as an instance variable.

Here's why: you need to manage the lifetime of your classes that store data.  When the object goes out of scope, your memory gets cleaned up by the garbage collector automatically, including the instance variable.

If memory serves, you can still call static utility methods on the class; you'll just have to pass your expensive data into the utility method, just like you would with any static utility method.  In general, I would avoid static state unless you have a very good reason for needing it.


问:
I would like to know if there are special terms for differnt types of inheritance
Are there terms to distinguish these two different types of inheritance?

The one type of inheritance is

```<code>vehicle - car.
</code>```

(these classes have some similarities).

But then there is for example

```<code>event - car
</code>```

Of course there are also similarities (as in the above example), but here is more a special notion of "to enhance a class with a funtionality" rather than "two classes have similarities and now I create a class where I put the common attributes".

I use the last example in JavaScript to make the car class "eventable", so I can call "register_event" or "trigger_event" on car objects.

Thanks alot in advance

答: In the second form of inheritance, event or eventable could be called a mixin. A mixin provides a specialized behavior through inheritance, and possibly additional members in languages that support multiple inheritance of classes.


问:
C Module - Where to put prototypes and definitions that do not belong to the public interface?
Since I am mainly an Electrical Engineer, forgive me if I am somewhat off with some terminology.

I am currently programming a display driver/interface module. And like so many times before, I have reached a point where I am unsure on how to separate function prototypes and definitions that are meant for internal use of the module from the public interface.

Consider the following code as as an example:

C-file:

```<code>// display.c
#include "display.h"

// Belongs to public Interface
void SetFont(Font_t fnt) {
    // implementation
}

// Belongs to public Interface
void PrintCharAt(int x, int y, char ch) {
    // implementation
}

// For internal use only
void SendDataToDisplay(DisplayTelegram_t telegram) {

}
</code>```

Header:

```<code>// display.h
typedef struct {
    // implementation
} Font_t;

typedef struct {
    // implementation
} DisplayTelegram_t;

void SetFont(Font_t fnt);
void PrintCharAt(int x, int y, char ch);
void SendDataToDisplay(DisplayTelegram_t telegram);
</code>```

The article What Belongs in a C .h Header File? covers several points that I mostly agree with.

DO include in the header file all of the function prototypes for the public interface of the module it describes.

DON’T include in the header file any other function or macro that may lie inside the module source code. It is desirable to hide these internal “helper” functions inside the implementation. If it’s not called from any other module, hide it!

So far so good, but what is the best practice for hiding the internal prototypes etc? There is no reason to have the DisplayTelegram_t type and the SendDataToDisplay() prototype in the header. It may even confuse someone who just wants to use the interface when things get more complex.

I can think of three options:

Just put all internal prototypes, typedefs, defines etc. to the top of the .c-file. I have done this in the past, but I do not like it. It does not seem consistent to pollute the .c-file with header-material.

Create a second header file like display_internal.h and put everything for internal use only there. I have read a lot about this approach, but barely seen it used.

Don't care about hiding internal prototypes etc. and just put everything in the header-file. Maybe grouping public and internal stuff together respectively and leaving a comment. This is dirty from a responsibility-perspective but at least its consistent and clean for the author of the code.

Is there any approach I am missing? How is this handled on a professional level?

答:
1.Just put all internal prototypes, typedefs, defines etc. to the top of the .c-file. I have done this in the past, but I do not like it. It does not seem consistent to pollute the .c-file with header-material.

Function prototypes are not header-material. Public API function prototypes are header-material.

If you had a single compilation unit, you would not need the header file at all. Then, you could add all prototypes (that are needed in that compilation unit in order to compile) to the top of the C file.

You can still do so, but since you usually have more compilation units, and they reuse each other's public APIs, it makes sense that the public APIs are in separate files, which are then reused (thus avoiding duplicate code).

Your second alternative ( create a second header file like display_internal.h and put everything for internal use only there ) is not really an alternative: the moment you add function prototypes to a header file to use it in other compilation units, that is public interface by definition (and should be in the public API header).

The third alternative is bad for project maintenance (very bad!). In practice, people working on client code, find the prototypes and figure "hey, I'm doing code reuse ;)" without caring that there is a comment in the header saying "part of the private api". This way, they end up adding undocumented interdependencies on private APIs.

TLDR: The first option is the correct one to take.


问:
Git(flow) workflow for web development
In my (small) company, we are currently thinking about dumping our current versioning system (svn) and release procedures, which are crap TBH, and switching to git. It will mainly be used for one large web project which we will be continously developing for some years, at least. Considering what I found on the web and some questions here on Programmers.SE, I came up with the following workflow (based on the gitflow workflow):

We have three web servers called live, webtest and webdev, and three main branches, master, testing (branched from master) and development (branched from testing). The code in master will always be exactly the one deployed in the live (production) system, and the code in testing will always be exactly the one deployed on the webtest server. The webdev server, however, will be continously used by the developers to upload their code, so it does not necessarily correspond to the development branch.

Whenever a developer starts working on a new feature, he creates a feature branch from development,  works on it (and frequently uploads his current progress to webdev), commits to development from time to time, and whenever he thinks he's done, he merges back his feature branch back into development (1).

Whenever a bunch of features is ready (and possibly reviewed by other developers), we merge development into testing (and this code is deployed on webtest), so it can be tested (2). When the testing in done and everything seems fine, we merge testing back into master (3), and the code in master is deployed on the live production server.

I have some questions about this: In (1), (2) and (3), would it make sense to create pull requests rather than just merging? How would we approach errors found in testing - by creating branches off testing or by fixing it in the respective feature branch and then merging back into development and testing? Are there any other major drawbacks or caveats I have overlooked? Do you have any other enhancements or suggestions?

答:
This is very similar to a successful git branching model that we've employed in my workplace - it works wonders for us (though we differ slightly from your branching a little, and put the git tag on production server so that devs don't patch live and update git via production server (and possibly fubar the branches)).

When developing

Your proposed method is great. Every developer has their own workplace (on the server) and they have their own [feature] branches - this will be great help as you'll be able to track what features are in development, where in the development lifecycle they are, and who is responsible for them (though if you adopt agile workflow, you'll know this; it's nice to know when you look back in the past).

Developers having their own [feature] branch when developing will allow you to work on different features without overwriting each others work.

This stage is fine, no caveats

When testing

Testing can become confusing, because what if you find a major bug that needs patching but feature X is ready to go live? Who is responsible for the testing?

Fixing a bug during testing

When you have your testing branch on the test server and you find a bug that needs patching, it can be addressed 2 ways;

Checkout of testing branch into a bug fix (bf-) branch. When there is a bug, usually I create an issue detailing what needs patching and name the bug fix branch after it (ie: opened issue #293, the branch will be bf-293). This will greatly help you track what was fixed.

Directly patch the testing branch.

Testing multiple features

Again, very easy to do with your proposed branching model. Ensure you create a pull/merge request to document what code was changed (this has saved my bacon many times in the past) and at what stage in the products lifecycle a particular feature went into testing and production.

Once all features have been merged into the development branch, ensure you create a fresh testing branch (I usually name these release candidates. Ie: we are testing v2.42, I will name this testing branch rc-2.42) and push up to the testing server.

This stage is fine, no caveats

Go live

Going live with git is great. Once you're happy with your test results and ready to push live, ensure you open a pull/merge request so that it's documented what is going live when (as previously mentioned).

! If you fixed some bugs during testing then make sure you merge the testing branch back into development. You don't want things that are in master and not development - things will get messy and confusing very quickly.

Once merged into master, ensure you tag it to create a point in time to roll back to (I'll explain later). When you go live, ensure you checkout into the new tag so that you cannot patch live without going through the git procedure.

When you've gone live, I like to create a post in the wiki to document the new version and link the pull/merge request. It will be much easier to track what went live.

Why use the tag?

Tagging creates a point in time that is very easy to rollback to should something go terribly wrong on the production server. It also manages your visioning and nice to look back in time to see what went live when.

Conclusion;

Your branching model is fine

Make sure you open pull/merge requests before merging

Ensure you tag your master branch

Ensure you document the push to production (in the wiki)

When patching (either hot fix or bug fix), ensure you create an issue to document the bug.

Title: Git(flow) workflow for web development


问:
Should dependency inversion be used only with Adapters everywhere?
As I understand the purpose of DI is that I can easily swap a lower level implementation. But it forces the lower level abstraction to be defined inside the higher level.

A lower level becomes dependent on the abstraction defined in the higher level and can't be used without it. But what if I would ever want to reuse my lower-level Logger class in another application?

Should I use Adapter everywhere with DI? In my example Adapter could implement ILogger interface from the higher-level code and reroute calls to the Logger class which now becomes reusable and independent from my application.

Is it a good approach?

答:
You are very confused.

A lower level becomes dependent on the abstraction defined in the higher level

No it doesn't. It depends only on the abstraction that it has defined itself. For instance, a TaxAuditImpl might depend on the interface TaxAuditor that it satisfies. However, it does not depend on the SuperDuperPersonalFinanceManager that uses the TaxAuditor. Everything stays nicely within its own level.

Admittedly, the FinanceManager does depend on the lower-level TaxAuditor, but that's okay - it can't very well use it without depending on it. And dependency injection serves to reduce this kind of dependency, because the FinanceManager doesn't have to know the Impl, just the interface.


问:
How to handle rating?
I want to implement like/dislike system, but I don't know how to achieve best performance. I have to tables: blog posts and comments that need rating.

Should I store all data in one rating table? Or should I create separate tables for posts and for comments?

Should I store total result into one record in post table or should I query for all +1 click in that rating tables? I want one person to rate on comment/post just one time.

Should I mark if person already voted for comment or post or is it just damage performance?

I haven't launch big systems, but looking at the same projects I think there will be 15 000 hits a day but running on average VPS with 1-2Gb of RAM, 1-2 Cores and without SSD. It could be fast upgraded to much more powerful dedicated server but it's too expensive.

答:
You have to have knowledge of whether any given user has voted on any given post and on any given comment.  This means that you have to introduce a new user_post_votes table with a user_id column and a post_id column, as well as a user_comment_votes table with a user_id column and a comment_id column.

If it is only possible to upvote, then the presence of a row in each of these tables means that the user with the given user_id has upvoted the post or comment with the given id.  However, if it is possible to either upvote or downvote, then you will need one more column to stand for "upvote" or "downvote".  The best type for that column is actually INTEGER, with valid values being either -1 or +1, so that SELECT SUM(vote) FROM user_post_votes WHERE post_id = X will give you the total votes for a post, taking into account the downvotes.  (TINYINT might also do, but I am not sure if it will be correctly summed into an integer if there are more than 128 upvotes, you will need to check that.)

Should I store all data in one rating table? Or should I create
  separate tables for posts and for comments?

I shall presume that in fact you already have separate tables for posts and for comments, and what you actually meant to ask with the above question was whether you should also create separate tables for votes on posts and for votes on comments.  Yes, you should.  And if you tried doing anything else, you would very quickly find out that nothing else makes sense.  Posts have to be identified by a post_id column in a user_post_votes table, and comments have to be identified by a comment_id column in a user_comment_votes table.  There is no way around that.  You cannot have a column which contains an id which in some cases refers to one table, and in some cases refers to another table. (Technically you could, but such a thing would be in blatant violation of relational database theory, against all best practices, and practically a nightmare to work with.)

Should I store total result into one record in post table or should I
  query for all +1 click in that rating tables? I want one person to
  rate on comment/post just one time.

Do not store the total result anywhere.  First, complete the development of your system and bring it to a fully working state by recomputing the vote count every time it is needed, as I have already shown.  Then, if and only if there appears to be a performance problem, and if and only if you can prove that the performance problem is located in this computation, then go optimize that part by caching the total vote count for each post.  Most chances are, you will not need to.

Should I mark if person already voted for comment or post or is it
  just damage performance?

You cannot just "mark" if a person has already voted, because you have N persons, X comments, and Y posts.  This is a many-to-many relationship, so as I have already explained, you have to have a user_comment_votes table and a user_post_votes table.  Whether it hurts performance or not is inconsequential, since you have already established that this information is necessary. So, if it is necessary, then you will need to keep track of it.

Title: How to handle rating?


问:
How were the first compilers made?
I always wonder this, and perhaps I need a good history lesson on programming languages.
But since most compilers nowadays are made in C, how were the very first compilers made (AKA before C) or were all the languages just interpreted?

With that being said, I still don't understand how even the first assembly language was done, I understand what assembly language is but I don't see how they got the VERY first assembly language working (like, how did they make the first commands (like mov R21) or w/e set to the binary equivalent?

答:
A VERY SIMPLE ANSWER
Suppose that we write a hardwired program and store it in ROM. It can be considered as compiler. So I simply want to say is that the very first compiler was hardwired. As the technology improved these simple compilers were then used to write high level compilers.</p>

Title: How were the first compilers made?


答:
It is possible (if tedious) to write direct machine code. Maybe you write the program down in assembler on a piece of paper, and then you translate it by hand into the numeric machine code instructions which you enter into the machine memory. You can even skip the assembler-on-paper step if you have memorized the numeric values of all the machine code instructions - not uncommon in those days, believe it or not!

The very first computers were directly programmed in binary by toggling physical switches. It was a great productivity improvement when hardware evolved to let the programmer (or the data entry assistant) enter code in hexdecimal numbers via a keypad!

A software assembler only became relevant when more memory became available (since assembler code takes up more space than raw machine code) and hardware evolved to allow alphanumeric input. So the first assemblers were written directly by people fluent in machine code.

When you have an assembler, you can write a compiler for a higher level language in assembler.

The story for C has multiple steps. The first C compiler was written in B (a predecessor to C) which in turn was written in BCPL. BCPL is a pretty simple language (for example it doesn't have types at all), but still a step up from raw assembler. So you see how gradually more complex languages is build in simpler languages all the way back to assembler. And itself C is a pretty small and simple language by todays standards.

Today, the first compiler for a new language is often written in C, but when the language reaches a certain maturity it is often rewritten "in itself". The first Java compiler was written in C, but later rewritten in Java. The first C# compiler were written in C++, but recently it has been rewritten in C#. The Python compiler/interpreter is written in C, but the PyPy project is an attempt to rewrite it in Python.

It is not always feasible to write a compiler/interpreter for a language in the language itself though. A JavaScript interpreter written in JavaScript exists, but the compilers/interpreters in current browsers are still written in C or C++ for performance reasons. JavaScript written in JavaScript is simply too slow.

But you don't have to use C as the "starting language" for a compiler. The first F# compiler was written in OCaml, which is the other language which is most closely related to F#. When the compiler was complete, it was rewritten in F#. The first compiler for Perl 6 was written in Haskell (a pure functional language very different from Perl) but now has a compiler written in C.

An interesting case is Rust, where the first compiler was written in OCaml (now it is rewritten in Rust). This is notable because OCaml is generally considered higher level than Rust, which is a closer-to-the-metal systems language. So it is not always higher-level languages implemented in lower-level languages, it might also be the other way around.

Title: How were the first compilers made?

Body:
I always wonder this, and perhaps I need a good history lesson on programming languages.
But since most compilers nowadays are made in C, how were the very first compilers made (AKA before C) or were all the languages just interpreted?

With that being said, I still don't understand how even the first assembly language was done, I understand what assembly language is but I don't see how they got the VERY first assembly language working (like, how did they make the first commands (like mov R21) or w/e set to the binary equivalent?


问:
Testing concurrency/thread-safety
A program I have wrote uses multiple threads and I believe my program is thread-safe but how can I really know?

I've read a number of examples online and none of them describe how to test the code is actually thread-safe or not, nor have I found a reliable way to cause a conflict.

Most of what I've tested regarding concurrency has mostly been cross your fingers and hope stuff. Indeed there have been a few instances where the code would conflict on a regular basis, but what can I do to reassure the people using my code, and myself, that the code is robust and reliable?

答:
Demonstrating thread-safety means proving that every possible interleaving of the instructions in two opcode streams leads to the correct result. Therefore, in order to test this property, you must be able to interleave those instructions as desired.

In practice, this means that you must have some kind of hook within code that is normally run as a unit. This usually involves adding hooks of some kind to the code that allow you to start and stop the processing at well-defined points. It can be done via AOP, or via reflection, or of course manually; Jaroslav Tulach once described a cool technique in which he exploits the log4j statements that are already present in his business code for this purpose. But all of those possibilities tend to be high-effort endeavours. That is only one reason why thread-safety is rare, and proper thread-safety testing is even rarer.

Title: Testing concurrency/thread-safety