问:
Unit test express controllers?
I'm using meanjs for a project.  It includes a yeoman generator with some express tests (model.test.js & routes.test.js)

The tests do exactly what they advertise. My question is though, should I be writing tests for my express controllers as well?

Right now the routes tests make sure the server responds with the appropriate data as a whole, but should I be writing more granular tests for each part of my controller as well?  I don't see many examples of this online....

答:
TLDR

There are two options:

Continue testing as a whole with functional tests (because these as a whole tests are not unit tests). You can feel this is not the right way, but it can be the only way to go with your current code base.

Refactor code to smaller units (classes / functions) to make real unit testing possible. Then create unit tests for these smaller "units".

Long Explanation

First, to make sure we are talking about the same, the example of the controller code:

```<code>// Controller code
exports.changePassword = function (req, res, next) {
  // Init Variables
  var passwordDetails = req.body;
  var message = null;

  if (req.user) {
    if (passwordDetails.newPassword) {
      User.findById(req.user.id, function (err, user) {
        if (!err && user) {
          if (user.authenticate(passwordDetails.currentPassword)) {
            if (passwordDetails.newPassword === passwordDetails.verifyPassword) {
              user.password = passwordDetails.newPassword;

              user.save(function (err) {
                  ...
                  res.send({ message: 'Password changed successfully' });
              });
            } else {
              res.status(400).send({ message: 'Passwords do not match' });
            }
          } else {
              res.status(400).send({ message: 'Current password is incorrect' });
          }
        } else {
          res.status(400).send({ message: 'User is not found' });
        }
      });
    } else {
      res.status(400).send({ message: 'Please provide a new password' });
    }
  } else {
    res.status(400).send({ message: 'User is not signed in' });
  }
};
</code>```

And the test code:

```<code>// Change password
...
// agent performs the http request to the application
agent.post('/api/users/password')
  .send({
    newPassword: '1234567890Aa$', ...
  })
  .expect(200)
  .end(function (err, res) {
    ...
    res.body.message.should.equal('Password changed successfully');
    return done();
  });
</code>```

This approach works, but these tests are actually not unit tests, but functional tests which verify the system as a black-box.
That means they are slower and less granular.

So how can we write unit tests for the controllers?
With the existing structure it can be done like this (this is not a real code, just to demonstrate the idea):

```<code>var users = require('../controllers/users.server.controller');

describe('User Controller Unit Tests:', function () {

  describe('Change Password', function () {
    it('should change the password', function (done) {
      req = RequestMock({
          'body': {
              'newPassword': 'xxx', 'passwordVerify': 'xxx'
          }
      );
      res = ResponseMock();
      users.changePassword(req, res).then(function() {
        res.body.message.should.equal('Password changed successfully');
      });
    });
</code>```

We get closer to the unit test and now we have request / response mocks and call our changePassword directly, but we still test it as a whole.
The test structure didn't change much.

The solution is to make the code testable first, re-factor it to extract the units from the changePassword code, which now does too much:

Get the incoming data from the request

Validate incoming data

Change the password

Handle possible errors

Format the output

Send the output

The better code structure could contain following objects:

Controller - get the incoming data from the request, format and send the output

NewPasswordConstraints - validate / verify incoming data

User - change the password

The controller code could be something like this:

```<code>// Controller code
exports.changePassword = function (req, res, next) {
  // Get the incoming data
  var passwordDetails = req.body;
  // Validate the incoming data
  NewPasswordConstraints(passwordDetails).validate().then(function(user) {
    // Actually change the password
    return user.set_new_password(passwordDetails.newPassword);
  }).then(function(user) {
    // Format and send the success response
    res.send({ message: 'Password changed successfully' });
    // Format and send the error response
  }).catch(function(error) {
    res.status(error.code).send({ message: error.message });
  });
}
</code>```

Again, this is more a pseudo-code than real code, but I think the idea should be clear.

Now you can create unit tests for the business logic - NewPasswordConstraints and User classes.

At the same time, controller code becomes slim and only integrates other objects. I usually don't write unit tests for these 'slim' controllers and leave them for the functional tests.

Title: Unit test express controllers?

Body:
TLDR

There are two options:

Continue testing as a whole with functional tests (because these as a whole tests are not unit tests). You can feel this is not the right way, but it can be the only way to go with your current code base.

Refactor code to smaller units (classes / functions) to make real unit testing possible. Then create unit tests for these smaller "units".

Long Explanation

First, to make sure we are talking about the same, the example of the controller code:

// Controller code
exports.changePassword = function (req, res, next) {
  // Init Variables
  var passwordDetails = req.body;
  var message = null;

  if (req.user) {
    if (passwordDetails.newPassword) {
      User.findById(req.user.id, function (err, user) {
        if (!err && user) {
          if (user.authenticate(passwordDetails.currentPassword)) {
            if (passwordDetails.newPassword === passwordDetails.verifyPassword) {
              user.password = passwordDetails.newPassword;

              user.save(function (err) {
                  ...
                  res.send({ message: 'Password changed successfully' });
              });
            } else {
              res.status(400).send({ message: 'Passwords do not match' });
            }
          } else {
              res.status(400).send({ message: 'Current password is incorrect' });
          }
        } else {
          res.status(400).send({ message: 'User is not found' });
        }
      });
    } else {
      res.status(400).send({ message: 'Please provide a new password' });
    }
  } else {
    res.status(400).send({ message: 'User is not signed in' });
  }
};

And the test code:

// Change password
...
// agent performs the http request to the application
agent.post('/api/users/password')
  .send({
    newPassword: '1234567890Aa$', ...
  })
  .expect(200)
  .end(function (err, res) {
    ...
    res.body.message.should.equal('Password changed successfully');
    return done();
  });

This approach works, but these tests are actually not unit tests, but functional tests which verify the system as a black-box.
That means they are slower and less granular.

So how can we write unit tests for the controllers?
With the existing structure it can be done like this (this is not a real code, just to demonstrate the idea):

var users = require('../controllers/users.server.controller');

describe('User Controller Unit Tests:', function () {

  describe('Change Password', function () {
    it('should change the password', function (done) {
      req = RequestMock({
          'body': {
              'newPassword': 'xxx', 'passwordVerify': 'xxx'
          }
      );
      res = ResponseMock();
      users.changePassword(req, res).then(function() {
        res.body.message.should.equal('Password changed successfully');
      });
    });

We get closer to the unit test and now we have request / response mocks and call our changePassword directly, but we still test it as a whole.
The test structure didn't change much.

The solution is to make the code testable first, re-factor it to extract the units from the changePassword code, which now does too much:

Get the incoming data from the request

Validate incoming data

Change the password

Handle possible errors

Format the output

Send the output

The better code structure could contain following objects:

Controller - get the incoming data from the request, format and send the output

NewPasswordConstraints - validate / verify incoming data

User - change the password

The controller code could be something like this:

// Controller code
exports.changePassword = function (req, res, next) {
  // Get the incoming data
  var passwordDetails = req.body;
  // Validate the incoming data
  NewPasswordConstraints(passwordDetails).validate().then(function(user) {
    // Actually change the password
    return user.set_new_password(passwordDetails.newPassword);
  }).then(function(user) {
    // Format and send the success response
    res.send({ message: 'Password changed successfully' });
    // Format and send the error response
  }).catch(function(error) {
    res.status(error.code).send({ message: error.message });
  });
}

Again, this is more a pseudo-code than real code, but I think the idea should be clear.

Now you can create unit tests for the business logic - NewPasswordConstraints and User classes.

At the same time, controller code becomes slim and only integrates other objects. I usually don't write unit tests for these 'slim' controllers and leave them for the functional tests.


问:
Concurrent and atomic updates to multiple properties/variable of an object
I have a class with multiple setters and want to make atomic updates to multiple properties/variables. As far as I can see there are three methods that could work:

Call all setters in synchronized block.

```<code>synchronized {
  obj.setA(a);
  obj.setB(b);
  // ...
}
</code>```

Use explicit locks.

```<code>obj.lock();
obj.setA(a);
obj.setB(b);
// ...
obj.unlock();
</code>```

Use an update object.

```<code>update = new UpdateObject();
update.setA(a);
update.setB(b);
// ...
obj.update(update);
</code>```

Update objects are often used by the Windows API to make atomic changes to an object without explicit locking in a single system call.

Is there any method that I missed?

Concurrency control is a cross-cutting concern. What are the architectural implication of each method? What is the most idiomatic method in Java?

答:
What all these methods have in common is that the update to multiple properties is only atomic if everybody updating the properties uses the same method, but also everybody reading the properties and wanting them updated atomically reads the properties using one of these locking methods.

Your chances improve mightily if instead of having multiple properties, you have one object representing all the properties, and only have a getter / setter for that one object.

ContentLicense: CC BY-SA 3.0


问:
ASP.NET MVC Middle tier object naming
As a corporate developer who works alone I find myself creating and writing a lot of websites that consist of screens that are basically wrappers for a DB table. So for instance on a screen that updates companies I would have a controller like this:

```<code> public class CompaniesController
{
    private readonly ICompaniesManager manager;

    public CompaniesController(ICompaniesManager manager)
    {
        this.manager = manager;
    }

    [HttpPost]
    public JsonResult Update(Company company)
    {
            // validation goes here
            this.manager.Update(company);
            // handle update result
    }
}
</code>```

this controller is talking to a middle tier "Manager" class.

```<code> public class CompaniesManager : ICompaniesManager
{
    private readonly ICompaniesRepository repository;

    public CompaniesManager(ICompaniesRepository repository)
    {
        this.repository = repository;
    }

    public void Update(Company company)
    {
        // business logic & caching code
        this.repository.Update(company);
    }
}
</code>```

As you can see this is talking to a repository class that actually handles updating the database.

So I always seem to end up with the pattern xxxController -> xxxManager -> xxxRepository (where xxx is the object/table). I keep finding myself wondering if I am missing something fundamental about how a 3 tier app should work or how middle tier classes should be named.

Would this be considered a correct 3-tier architecture or am I missing something?

答:
What you have there seems like a standard architectural solution for MVC applications. Since MVC does not provide a solution for the data layer you have a repository. So the 3-layers are:

Business layer: where your classes appended by "Manager" are

Data layer: repository

Presentation layer: View and Controller

EDIT:

You should change the word "Manager" to "Service" since what you have there is called a service layer. We usually append the word "Manager" (or "Helper", or "Util") to static classes - something which may be a code smell.

Title: ASP.NET MVC Middle tier object naming


问:
Handling exceptions I don't know about
When I work with handling exceptions, I notice that I often have to deal with the ones I had no idea about. Especially it is noticeable when I program a method that grabs data from web. An error may occur, for example, due to connection loss, I can handle it. But then another error occurs, a different error with the same cause - connection loss. Okay, added it. Sometimes even yet another occurs. So, the problem is, I am never sure enough if I've handled all the possible errors that may occur due to a certain cause.

At first, I thought about going wildcard and do something like (example in Python):

```<code>try:
    #do stuff
except:
    #handle error
</code>```

But it proved to be a wrong approach soon, cause if I need to handle, say, KeyboardInterrupt, which is raised when a user terminates the program, instead of being handled by a scope I want it to be handled by, it is handled by this wildcard, which is not supposed to have anything to do with it.

So how do I handle exceptions I don't know of but that may possibly occur (or not occur)? Some kind of exceptEverythingBut KeyboardInterrupt:? I doubt many languages have that in their syntax.

EDIT1: a really simplified example:

```<code>#!/usr/bin/python3 -u
# -*- coding: utf-8 -*-

try:
    while True:
        try:
            print(1)
        except:
            print(2)
except KeyboardInterrupt:
    print('end')
</code>```

When I press Ctrl+C, I want it to print 'end' and finish. But instead it prints 2 and continues execution.

If I try this:

```<code>#!/usr/bin/python3 -u
# -*- coding: utf-8 -*-

try:
    while True:
        try:
            print(1)
        except KeyboardInterrupt:
            break
        except:
            print(2)
except KeyboardInterrupt:
    print('end')
</code>```

it finishes, but it skips the outer except and doesn't print 'end'. And that's not what I want. So, the only way I see is to prevent the inner scope from handling KeyboardInterrupt altogether. But it is not possible if there is a except: or except KeyboardInterrupt: in there. So, I need to specify exactly which errors I want to handle in the inner except. But, as I mentioned in the beginning, I don't always know what they can be.

I'm asking this question, because my common way to do it is to just let the program unexpectedly fail several times, read the logs and add handling of errors I didn't know about to new versions; however this could just be a naïve approach, so I want to know how it is done by experienced people.

答:
And this is why I like Java - no such surprises there (every function explicitly tells you what Exceptions it might throw).

Wouldn't that be something like this?

```<code>try:
    #do stuff
except(KeyboardInterrupt):
    pass
else:
    #handle error
</code>```

Title: Handling exceptions I don't know about

Body:
And this is why I like Java - no such surprises there (every function explicitly tells you what Exceptions it might throw).

Wouldn't that be something like this?

try:
    #do stuff
except(KeyboardInterrupt):
    pass
else:
    #handle error


问:
Having an discussion about security concerns with another software engineer
Background: The company I work for uses different systems to hold their insurance data which is customer related. They want to have an app for their customers where they can find their insurance related things in. Some of these systems provide web services to get the necessary information, so proper user authentication and whatsoever is possible. However, some provide direct database access without anything which comes even close to user authentication, because it was not designed to do that.

To solve this issue we are building an adapter-service, which can connect to all the different systems to get the necessary data. However the user-authentication is still an issue for the systems which don't provide that.

Another software engineer suggested (we are the only engineers) we build a general authentication mechanism which provides authentication to all the systems to get the necessary customer information. We both have the same background, we are young, we don't have that much experience in designing such a system or understanding all the security issues for such a system.

Question: With the background as stated above, I am concerned about all the security concerns which may come up if we would do that. That for the serious kind of information (insurance data) we may lack the experience to set up a system like that, to ensure the best kind of security is possible and not limited by our knowledge (or Google).

His opinion on this matter is that a general authentication mechanism should be build for all systems. So with one login on our side they can get all the data from the different systems if it is available there. If we follow up with things such as OAuth that we don't have to fear the security issue that much. And if we (re)search these things on the internet, that it will be OK.

My opinion on this matter is that a general authentication mechanism will be a good thing for all the systems which don't provide the necessarry things for user authentication (which is also possible the only solution). However we should not override systems which provide their own authentication to access their system to get the necessary data from a customer. Perhaps information can be exchanged between all the systems to ensure the same kind of login is  available everywhere (if user exists in a system which provides authentication and with a systems which uses the general authentication). If an password for example is changed. This idea would make sure if our general authentication mechanism is breached somehow, that not all the systems will be exposed to the attacker, and who knows what the consequences might be.

Should we just go through with the idea to make a general authentication mechanism or limit it to the systems who need it and possible exchange login-details if the user should exist in the two different kind of systems (system which supports authentication or doesn't). What are good arguments for or against these ideas?

Edit: The general public would be using it, each system would provide the contract(s) with its data (if the customer exists in the different systems). Example: for customer '1' system A (database) and B (web-service) contains both different contracts from him. However, for customer '2' only system A (database) contains a contract. Depending on the customer their kind of contract(s) they are stored in different systems. All of these systems are third party.

答:
Single-sign on makes it very convenient for your users to log-on to all your system, and it also provides improved security. Imagine that it will be extremely cumbersome for users if they have to log-on to ten different databases with different accounts and different passwords each day over-and over again. That leads them to ignore any recommendation about no reuse of passwords, to use weak (because easier to remember) passwords, or password lists written down on a "postit" fixed on the back of their smartphone.

But I think there is no need for you to develop this only the one way or the other. Start with a general, reusable authentication mechanism. As you wrote, you need it either for at least some of your systems. Make sure you do not reinvent the wheel, inform yourself well about available single sign-on mechanisms beforehand.

Afterwards, take one system with an existing custom authentication, and try out what is necessary to connect this to your new general authentication system. Collect experience. Maybe you find out you do not need to throw the old system away, but you just need to write a small adapter for that system. Maybe you find out that the task becomes harder than you expected - but then you at least know the reasons why. But instead of hoping here to find "the answer" on Programmers by people who actually don't know anything about the details of your system, just try it out, step-by-step. If it does not work or takes more effort than expected, you can stop further development any time, you do not have much to lose.


问:
Secure way in authenticating credentials when Reading an xml file from the outside source
I started working on a project where I need to read and parse an xml file from  a url. This url needs a credentials to successfully read the data from it, so I'm thinking while reading the file there will be a modal window that will accept a username and password to authenticate the source.

This url is from the outside source and needed a credential to authenticate the connection for us to successfully connect and read the xml file. Also this is only available privately on request.

My concern is how could I prevent a user to see the credential being passed in the modal form then processed it in the background? It's like instead of getting the actual password I'm thinking like hash it? But by doing that the authentication would fail? Any suggestion if there is a better approach for this?

答:
if you are open to a different option: you could try having a response/request pattern, where you[the request] calls a service[the response] and pass a network credential object [built into .net] then upon successful authentication pass back the xml though the service call</p>

```<code>public XElement GetXml(IProviderInformation input)
{
    using (var svc = new Service())
    {
        svc.PreAuthenticate = true;
        svc.UseDefaultCredentials = false;
        svc.Credentials = new NetworkCredential
        {
            UserName = input.ProviderAccountInfo.AccountUserName,
            Password = input.ProviderAccountInfo.AccountPassword
        };

        var rslt = svc.GetXmlFromService();
        var result = XElement.Parse(rslt);
        return result;
    }
}
</code>```

Body:
if you are open to a different option: you could try having a response/request pattern, where you[the request] calls a service[the response] and pass a network credential object [built into .net] then upon successful authentication pass back the xml though the service call

public XElement GetXml(IProviderInformation input)
{
    using (var svc = new Service())
    {
        svc.PreAuthenticate = true;
        svc.UseDefaultCredentials = false;
        svc.Credentials = new NetworkCredential
        {
            UserName = input.ProviderAccountInfo.AccountUserName,
            Password = input.ProviderAccountInfo.AccountPassword
        };

        var rslt = svc.GetXmlFromService();
        var result = XElement.Parse(rslt);
        return result;
    }
}


问:
What are important things to remember when reengineering a legacy application?
About to embark on the initial phases of a project to rewrite a legacy application from the ground up (existing business rules will change somewhat, and be extended to incorporate a large number of new requirements that the existing infrastructure cannot handle). I am looking for items that are important to remember when working to reengineer an existing application.</p>

答:
There are a lot of good answers here that are really good points. There is one thing that I think is also important. Look at how technology has progressed from the point where the original code was written and what is out there now:

Windows Presentation Foundation

Windows Communication Foundation

Managed Extensibility Framework

By all means, you must assess the existing code; unit test, plan, research, development, more testing. But you also have to take into consideration new technologies that may extend the lifetime of version 2.

ContentLicense: CC BY-SA 2.5


答:
Just rethrow the exception when you get it:

```<code>try:
  #do stuff
except KeyboardInterrupt:
  raise
except:
  #do other stuff
</code>```

You specify that you get an exception that you know that you want to handle differently than default case, but you don't know how to handle it - so you just pass it, by throwing it again.

Some working example:

```<code>#!/usr/bin/python2

if __name__ == "__main__":
    try:
        while True:
            try:
                print(1)
            except KeyboardInterrupt:
                raise
            except:
                print(2)
    except KeyboardInterrupt:
        print('end')
</code>```

Please note that you shouldn't use except:, as this is a bad practice. except: used in this example is used in sole purpose to make things as simple as possible.

Title: Handling exceptions I don't know about

Body:
When I work with handling exceptions, I notice that I often have to deal with the ones I had no idea about. Especially it is noticeable when I program a method that grabs data from web. An error may occur, for example, due to connection loss, I can handle it. But then another error occurs, a different error with the same cause - connection loss. Okay, added it. Sometimes even yet another occurs. So, the problem is, I am never sure enough if I've handled all the possible errors that may occur due to a certain cause.

At first, I thought about going wildcard and do something like (example in Python):

```<code>try:
    #do stuff
except:
    #handle error
</code>```

But it proved to be a wrong approach soon, cause if I need to handle, say, KeyboardInterrupt, which is raised when a user terminates the program, instead of being handled by a scope I want it to be handled by, it is handled by this wildcard, which is not supposed to have anything to do with it.

So how do I handle exceptions I don't know of but that may possibly occur (or not occur)? Some kind of exceptEverythingBut KeyboardInterrupt:? I doubt many languages have that in their syntax.

EDIT1: a really simplified example:

```<code>#!/usr/bin/python3 -u
# -*- coding: utf-8 -*-

try:
    while True:
        try:
            print(1)
        except:
            print(2)
except KeyboardInterrupt:
    print('end')
</code>```

When I press Ctrl+C, I want it to print 'end' and finish. But instead it prints 2 and continues execution.

If I try this:

```<code>#!/usr/bin/python3 -u
# -*- coding: utf-8 -*-

try:
    while True:
        try:
            print(1)
        except KeyboardInterrupt:
            break
        except:
            print(2)
except KeyboardInterrupt:
    print('end')
</code>```

it finishes, but it skips the outer except and doesn't print 'end'. And that's not what I want. So, the only way I see is to prevent the inner scope from handling KeyboardInterrupt altogether. But it is not possible if there is a except: or except KeyboardInterrupt: in there. So, I need to specify exactly which errors I want to handle in the inner except. But, as I mentioned in the beginning, I don't always know what they can be.

I'm asking this question, because my common way to do it is to just let the program unexpectedly fail several times, read the logs and add handling of errors I didn't know about to new versions; however this could just be a naïve approach, so I want to know how it is done by experienced people.

Body:
Just rethrow the exception when you get it:

try:
  #do stuff
except KeyboardInterrupt:
  raise
except:
  #do other stuff

You specify that you get an exception that you know that you want to handle differently than default case, but you don't know how to handle it - so you just pass it, by throwing it again.

Some working example:

#!/usr/bin/python2

if __name__ == "__main__":
    try:
        while True:
            try:
                print(1)
            except KeyboardInterrupt:
                raise
            except:
                print(2)
    except KeyboardInterrupt:
        print('end')

Please note that you shouldn't use except:, as this is a bad practice. except: used in this example is used in sole purpose to make things as simple as possible.


问:
Does an interface including several methods that return instances of Object make sense?
I am in the process of writing my first true API. In the process, I am defining an interface for mapping complex data structures onto other complex data structures.

At the moment, the interface contains a set method for the input data structure, a run method to kick off the mapping process, and several methods which basically have the same signature, but of course different names and different documentation. The latter all return java.lang.Object. Something as follows.

public interface DataCompiler {

  public void setInputDataStructure(IDS ids);

  public void run();

  /**
   * Maps a "this" structure to a target "this" structure and
   * returns the resulting target "this" structure.
   */
  public Object mapThisStructure();

  /**
   * Maps a "that" structure to a target "that" structure and
   * returns the resulting target "that" structure.
   */
  public Object mapThatStructure();

  /**
   * Maps an "other" structure to a target "other" structure and
   * returns the resulting target "other" structure.
   */
  public Object mapOtherStructure();

}
```

So, an interface is meant to define a contract that must be fulfilled by implementations of the interface.

However, with my interface there is no safety catch in the method signatures themselves to prevent a misuse of any of the last three methods. E.g., mapThisStructure could actually be implemented in the exact way that mapThatStructure is meant to be implemented. Or, someone could put all mapping work into either one of the three mappings (which would of course breach the principle of one method doing one and only one thing), and simply let the other two return null.

Thus actual contract is defined in the JavaDoc. So, does the set up of such an interface make sense?

答:
The type system can do many things for you, but even the best type system cannot do everything. There is no problem with having several methods with the same type signature but different contracts. Look at it this way: if everything could be expressed machine-verifiable via the signature, we wouldn't need programmers - just spec writers and compilers. The leeway afforded by this incompleteness is what keeps us all employed.

However, I'm certain returning Object is not the best solution, no matter whether once or thrice. Surely your structures obey some common rules and expected access patterns? That's what you should express via the type system.


问:
Can the "level 256 bug" in the game of Pacman be considered an unhandled segfault?
I am trying to explain segmentation faults to someone, and I was thinking about the level 256 kill-screen in Pacman, and how it's triggered by integer overflow, and how similar the behavior is to the "unknown state" oft-described in a segmentation fault.

I want to say this is a good example of what I call an "unhandled segfault", but I would rather get a second opinion before I potentially spread misinformation.

I tried looking it up, but all I'm getting are documents on the bug itself, as well as that collab between Hipster Whale and Namco.

So, would you consider the behavior in level 256 of Pacman to be an example of unhandled segmentation violation?

答:
As said before no it's not a seg fault. I'll add why the problem occurs: it's an overflow.

Level number are store on a byte so the range is 0-255. Each time you complete a level the counter is incremented. At level 256 the counter is in fact 0 due to the overflow.

However the game try to display some fruits on the bottom of the level. The fruit number/type depend on the level. The formula display one fruit per finished level under level 8. According to the counter you are on level 0 so under 8. The test is true then and you have to print 255 fruits (the old level value). Which is impossible and gives this glitched screen.


问:
What's the point of running unit tests on a CI server?
Why would you run unit tests on a CI server?

Surely, by the time something gets committed to master, a developer has already run all the unit tests before and fixed any errors that might've occurred with their new code. Isn't that the point of unit tests? Otherwise they've just committed broken code.

答:
You'd think so wouldn't you - but developers are human and they sometimes forget.

Also, developers often fail to pull the latest code. Their latest tests might run fine then at the point of check-in, someone else commits a breaking change.

Your tests may also rely on a local (unchecked-in) resource. Something that your local unit tests wouldn't pick up.

If you think all the above is fanciful, there is a level above CI (on TFS at least) called Gated where builds that have failing tests are shelved and aren't committed to the code base.


答:
Surely, by the time something gets committed to master, a developer has already run all the unit tests before and fixed any errors that might've occurred with their new code.

Or not. There can be many reasons why this can happen:

The developer doesn't have the discipline to do that

They have forgotten

They didn't commit everything and pushed an incomplete commit set (thanks Matthieu M.)

They only ran some tests, but not the whole suite (thanks [nhgrif][2])

They tested on their branch prior to merging (thanks [nhgrif][2] * 2)

But the real point is to run the tests on a machine that is not the developer machine. One that is configured differently.

This helps catch out issues where tests and/or code depend on something specific to a developer box (configuration, data, timezone, locale, whatever).

Other good reasons for CI builds to run tests:

Testing on different platforms other than the main development platforms, which may be difficult for a developer to do. (thanks [TZHX][3])

Acceptance/Integration/End to End/Really long running tests may be run on the CI server that would not be run on a developer box usually. (thanks [Ixrec][4])

A developer may make a tiny change before pushing/committing (thinking this is a safe change and therefore not running the tests). (thanks [Ixrec][4] * 2)

The CI server configuration doesn't usually include all the developer tools and configuration and thus is closer to the production system

CI systems build the project from scratch every time, meaning builds are repeatable

A library change could cause problems downstream - a CI server can be configured to build all dependent codebases, not just the library one

[2]: What's the point of running unit tests on a CI server?)
[3]: What's the point of running unit tests on a CI server?
[4]: https://softwareengineering.stackexchange.com/users/161917/ixrec

Body:
Why would you run unit tests on a CI server?

Surely, by the time something gets committed to master, a developer has already run all the unit tests before and fixed any errors that might've occurred with their new code. Isn't that the point of unit tests? Otherwise they've just committed broken code.

ContentLicense: CC BY-SA 4.0


答:
By the time something gets committed to master, a developer should have already run all the unit tests ... but what if they haven't? If you don't run the unit tests on the CI server, you'll not know until someone else pulls the changes to their machine and discovers the tests just broke on them.

In addition, the developer may have made a mistake and referenced a local resource specific to their machine. When they check in the code and the CI run fails, the problem is immediately identified and can be corrected.

Title: What's the point of running unit tests on a CI server?


问:
Differences between Given When Then (GWT) and Arrange Act Assert (AAA)?
In TDD there is Arrange Act Assert (AAA) syntax:

```<code>[Test]
public void Test_ReturnItemForRefund_ReturnsStockOfBlackSweatersAsTwo_WhenOneInStockAndOneIsReturned()
{
    //Arrange
    ShopStock shopStock = new ShopStock();
    Item blackSweater = new Item("ID: 25");
    shopStock.AddStock(blackSweater);
    int expectedResult = 2;
    Item blackSweaterToReturn = new Item("ID: 25");

    //Act
    shopStock.ReturnItemForRefund(blackSweaterToReturn);
    int actualResult = shopStock.GetStock("ID: 25");

    //Assert
    Assert.AreEqual(expectedResult, actualResult);
}
</code>```

In BDD writing tests uses a similar structure but with Given When Then (GWT) syntax:

```<code>    [Given(@"a customer previously bought a black sweater from me")]
    public void GivenACustomerPreviouslyBoughtABlackSweaterFromMe()
    { /* Code goes here */   }

    [Given(@"I currently have three black sweaters left in stock")]
    public void GivenICurrentlyHaveThreeBlackSweatersLeftInStock()
    { /* Code goes here */   }

    [When(@"he returns the sweater for a refund")]
    public void WhenHeReturnsTheSweaterForARefund()
    { /* Code goes here */   }

    [Then(@"I should have four black sweaters in stock")]
    public void ThenIShouldHaveFourBlackSweatersInStock()
    { /* Code goes here */   }
</code>```

Although they are often considered the same there are differences. A few key ones are:

GWT can be mapped directly to the specification of a feature file in BDD frameworks

GWT is easier for non-developers to understand by encouraging use of plain English, and having a short description of what each part is doing

Given When and Then are keywords in various BDD frameworks such as SpecFlow, and Cucumber

My question is are there any other differences (besides the names) between AAA and GWT? And is there any reason besides the ones specified above that one should be preferred over the other?

答: I guess it's dependent upon the framework you're using. Generally, so far as my understanding, AAA is supported by the NUnit framework, and thus is the natural choice in that regard. As for the theoretical differences between TDD and BDD, they appear to be slight. See this link, someone more qualified than myself to give you an explanation.</p>


答:
by the time something gets committed to master

I usually set up my CI to run on every single commit. Branches don't get merged into master until the branch has been tested. If you're relying on running tests on master, then that opens a window for the build to be broken.

Running the tests on a CI machine is about reproducible results. Because the CI server has a known clean environment pulled from your VCS, you know that the test results are correct. When running locally, you could forget to commit some code needed for them to pass, or have uncommitted code that makes them pass when they should be failing.

It also can save the developers time by running different suites in parallel, especially if some are slow, multi-minute tests that aren't likely to be run locally after each change.

At my current work our production deployment is gated on CI passing all tests. The deploy scripts will prevent deployment unless they're passing. This makes it impossible to accidentally forget to run them.

CI being part of the workflow takes burden off of developers as well. As a developer, do you usually run a linter, static analyzer, unit test, code coverage, and integration test for every single change? CI can, completely automatically and without needing to think about it - reducing decision fatigue.


答:
Assuming (contrary to other answers) that developers are quite disciplined and do run unit tests before committing, there can be several reasons :

running unit tests can take long for some special set up. For example, running unit tests with memory checker (like valgrind) can take much longer. Although all unit tests are passing, memory check can fail.

the result is not that important for some special settings - for example, running unit tests to check the code coverage requires special compiling flags. For normal developers, code coverage is not that important - it is more for people taking care that code maintains certain quality, like team leads.


答:
As a developer who doesn't run all the integration and unit tests before making a commit to source control, I'll offer up my defense here.

I would have to build, test and verify that an application runs correctly on:

Microsoft Windows XP and Vista with Visual Studio 2008 compiler.

Microsoft Windows 7 with Visual Studio 2010 compiler.

Oh, and the MSI builds for each of those.

RHEL 5 and 6 with 4.1 and 4.4 respectively (similarly CentOS)

7 soon. Woop-de-woop.

Fedora Workstation with GCC for last three recent versions.

Debian (and derivatives like Ubuntu) for last three recent versions.

Mac OSX in last three recent versions.

And the packages (rpm, dmg, etc)

Add in the Fortran (with both Intel and GNU compilers), Python (and it's various versions depending on OS) and bash / bat script components and, well, I think you can see things spiral out

So that's sixteen machines I'd have to have, just to run a few tests a couple of times a day. It would be almost a full time job just to manage the infrastructure for that. I think almost anyone would agree that's unreasonable, especially multiplying it out to the number of people in the project. So we let our CI servers do the work.

Unit tests don't stop you committing broken code, they tell you if they know you've broken something. People can say "unit tests should be fast", and go on about principles and design patterns and methodologies, but in reality sometimes its just better to let the computers we've designed for repetitive, monotonous tasks do those and only get involved if they tell us they've found something.


问:
Preparing to remove a tightly coupled service provider out of source code
I'm working on a huge legacy codebase that uses Bing Maps API as a service provider and I have got the task to scrap Bing which is the foundation of the software and has been referenced through the source code everywhere.

There are no unit tests at all. Very few pages of documentation. Also it's a JavaScript code-base, built on top of ExtJS 3.4, a badly designed custom wrapper around objects to mock classic inheritance and class hierarchies, and Bing being used all over the code and referenced through functions everywhere.

My question is: How should I document and count the references of Bing through out the code? I'm hoping to use this to make a better time estimation, and later, help ease the refactoring process.

I have already started browsing the code-base but I'm not sure what's the best way of documenting references.

答:
If your IDE supports task tagging (e.g. TODO/FIXME comments), then you can use them to annotate your usages on the same line they occur on. Define a new tag (if you can), mark up your source as you go along, and let the IDE do the work of aggregating the results into a neat little report.

As you make changes to the code and remove/consolidate unwanted usages, your report will stay up-to-date. You can also include information after the comment tag and parse it out with regex. For example, including an estimate of effort:

```<code>var foo = Bing.bar();  // LEGACY: 3
</code>```

Body:
If your IDE supports task tagging (e.g. TODO/FIXME comments), then you can use them to annotate your usages on the same line they occur on. Define a new tag (if you can), mark up your source as you go along, and let the IDE do the work of aggregating the results into a neat little report.

As you make changes to the code and remove/consolidate unwanted usages, your report will stay up-to-date. You can also include information after the comment tag and parse it out with regex. For example, including an estimate of effort:

var foo = Bing.bar();  // LEGACY: 3


问:
What is the difference between 'expected but not desired behavior' and a software bug
Recently I asked this question.  As commented in the answer by someone who sounds like a numPy developer, this behavior is clearly not desired.  The issue posted was closed stating that this is expected behavior but not a bug.  Additionally there are plans to fix it.

What is the difference between a bug and behavior which is expected but not desired?  Do those terms have precise and consistent definitions?

As a silly extreme, if a program always returns 3 when asked to compute 1+1, returning 3 is certainly expected behavior by the program since it has always worked that way, but it certainly isn't desired behavior, so is it a bug or not?

Recently I've been studying philosophy and this question has struck my interest.

答:
A "bug" is an informal term for a defect in the software. It usually refers to something wrong in the code. If you want to use formal terms, you would want to use words like "error" (a human action or inaction that led to an incorrect result), "fault" or "defect" (a wrong step, process, or definition), and "failure" (an inaccurate result). An error will lead to a fault or defect that can manifest itself as a failure. This answer by dukeofgaming (along with other answers in that question) is a good explanation of the difference between defects, failures, and bugs.

These terms can be applied to more than just source code. For example, an error made in your requirements can manifest as a defect in your design. If a user sees this behavior, they may interpret it as a failure, even if your testing doesn't. Your software code could be a reflection of your understanding of your requirements, but that understanding is incorrect. This sounds very much like what happened in your situation - the software is behaving as the developers intended it to. Still, their intentions and the expectations of the users did not align.


答:
It is known as a wart.

From a comment on the original post on Stack Overflow,

To be clear, this is not desired behavior, although there are good (historical) reasons for it. We (numpy devs) have preliminary plans to deprecate it in a future release, and provide easier to understand functionality that works as you might expect. See http://github.com/numpy/numpy/pull/6256 for more details. -- Stephan

Every design decision is a trade off somewhere.  Make something simpler somewhere, and somewhere else something may become more complicated.

Consider this bit of JavaScript:

>>> '5' + 3 - 3
50
>>> '5' - 3 + 3
5
```

<p>Is that a bug? No. Is it desired behavior... eh... I don't want to say people <em>want</em> it to work that way, but that's what you get with the 'this is how it was decided <code>+</code> works.'</p>

<p>Or in ruby that <code>x?2:3</code> is a syntax error (it needs to be <code>x ?2:3</code> - notice the space). Why? Because it was decided functions may end in a <code>?</code> and so <code>x?2:3</code> is ambiguous - a space between the variable and the <code>?</code> part of the ternary expression resolves that.</p>

<p>Or in PhP the decision to mimic Perl's auto-increment feature on Strings but lacking the restriction on the pattern leads to:</p>

<pre class="lang-php prettyprint-override"><code>$foo = "3d8";
echo "$foo\n";
$foo++;
echo "$foo\n";
$foo++;
echo "$foo\n";
$foo++;
echo "$foo\n";
</code>```

(ideone)

printing out:

```<code>3d8
3d9
3e0
4
</code>```

And without too much difficulty one could probably find examples of design warts in libraries and languages across the entire spectrum of software that were made that had unintended that had unintended and possibly undesired but nonetheless expected behavior.

There were indeed (debatably) good historical reasons the design decisions to make it work a certain way. And the code works that way - its not a bug, it is working exactly as intended.  With the benefit of hindsight, maybe those decisions weren't good and lead to undesired behavior, but the code is working as intended - there isn't a bug there, its a wart.

While I have listed a few warts that I can quickly show and tickle, there are countless ones out there. I really don't need more examples. I would frankly be surprised if one were to find a language or library that doesn't contain a wart.

Title: What is the difference between 'expected but not desired behavior' and a software bug

Body:
Recently I asked this question.  As commented in the answer by someone who sounds like a numPy developer, this behavior is clearly not desired.  The issue posted was closed stating that this is expected behavior but not a bug.  Additionally there are plans to fix it.

What is the difference between a bug and behavior which is expected but not desired?  Do those terms have precise and consistent definitions?

As a silly extreme, if a program always returns 3 when asked to compute 1+1, returning 3 is certainly expected behavior by the program since it has always worked that way, but it certainly isn't desired behavior, so is it a bug or not?

Recently I've been studying philosophy and this question has struck my interest.

Body:
It is known as a wart.

From a comment on the original post on Stack Overflow,

To be clear, this is not desired behavior, although there are good (historical) reasons for it. We (numpy devs) have preliminary plans to deprecate it in a future release, and provide easier to understand functionality that works as you might expect. See http://github.com/numpy/numpy/pull/6256 for more details. -- Stephan

Every design decision is a trade off somewhere.  Make something simpler somewhere, and somewhere else something may become more complicated.

Consider this bit of JavaScript:

>>> '5' + 3 - 3
50
>>> '5' - 3 + 3
5

Is that a bug? No. Is it desired behavior... eh... I don't want to say people want it to work that way, but that's what you get with the 'this is how it was decided + works.'

Or in ruby that x?2:3 is a syntax error (it needs to be x ?2:3 - notice the space). Why? Because it was decided functions may end in a ? and so x?2:3 is ambiguous - a space between the variable and the ? part of the ternary expression resolves that.

Or in PhP the decision to mimic Perl's auto-increment feature on Strings but lacking the restriction on the pattern leads to:

$foo = "3d8";
echo "$foo\n";
$foo++;
echo "$foo\n";
$foo++;
echo "$foo\n";
$foo++;
echo "$foo\n";

(ideone)

printing out:

3d8
3d9
3e0
4

And without too much difficulty one could probably find examples of design warts in libraries and languages across the entire spectrum of software that were made that had unintended that had unintended and possibly undesired but nonetheless expected behavior.

There were indeed (debatably) good historical reasons the design decisions to make it work a certain way. And the code works that way - its not a bug, it is working exactly as intended.  With the benefit of hindsight, maybe those decisions weren't good and lead to undesired behavior, but the code is working as intended - there isn't a bug there, its a wart.

While I have listed a few warts that I can quickly show and tickle, there are countless ones out there. I really don't need more examples. I would frankly be surprised if one were to find a language or library that doesn't contain a wart.


问:
Why are interfaces necessary in MVP design pattern?
I am trying to understands MVP using Winforms.

I found this example. Why do UserModel and UserView need to implement the IUserModel and IUserView interfaces ?

答:
Interfaces are required in good quality implementations of MVP for the same reason they are required in all good "OO" designs:

They help reduce coupling

They discourage inheritance (which further reduces coupling)

Arguably most importantly, they simplify unit test writing


答:
The difference is that "bug" implies the software is doing something wrong, and that it should be able to do that thing better than it currently is.

Most undesirable behaviors that I would not consider bugs would fall into one of these categories:

A flaw that's inherent in the nature of the application, and simply cannot be avoided. Your mobile phone's browser may take a long time to load a web page when you have a very weak cell signal. It may also display vulgar, offensive, or just plain irritating content that you did not want to see. In general, these are not problems the browser can ever completely solve.

A tradeoff with another design goal. Many programming languages allow floating point numbers to have rounding error, because doing all their math with arbitrary-precision arithmetic would be too performance intensive. There have been many arguments about which rounding errors do and do not qualify as bugs.

A simple mistake in the design that, for whatever reason, is no longer feasible to change.

A flaw, tradeoff or design error in the specification that a program needs to conform to. Most C++ compilers will allow you to compile code that is very obviously broken, because otherwise they wouldn't be conformant to the C++ Standard.

I don't fully understand the numpy array indexing issue you've linked to, but it sounds like it's in the third category.


答:
Apart from the excellent Oded answer:

You test the code from the repository. It may work on your machine with your files... that you forgot to commit. It may depend on a new table that does not have the creation script (In liquibase for example), some configuration data or properties files.

You avoid code integration problems. One developer downloads the last version, creates unit and integration test, adds code, pass all test in his machine, commits and push. Another developer has just done the same. Both changes are right on their own but when merged causes a bug. This could be the repository merging or just that it is not detected as a conflict. E.g. Dev 1 deletes file that was not used at all. Dev 2 codes against this file and tests without Dev 1 changes.

You develop an script to deploy automatically from the repository. Having an universal building and deploying script solves a lot of issues. Some developer may have added a lib or compiling option that is not shared by everybody. Not only does this save you time, but more importantly, it makes the deployment safe and predictable. Furthermore, you can go back in your repository to version 2.3.1 and deploy this version with a script that works with this version. It includes database objects like views, stored procedures, views, and triggers that should be versioned. (Or you won't be able to go back to a workable version).

Other tests: Like integration, performance and end to end tests. This can be slow and might include testing tools like Selenium. You may need a full set of data with a real database instead of mock objects or HSQL.

I once worked on a firm that had a lot of bugs on deployment due to the merging and deployment process. This was caused by a weird propietary framework that made testing and CI hard. It was not a happy experience to find that code that worked perfectly on development didn't arrive right to production.


答:
A bug would be behaviour that appears because someone, somewhere made a mistake. It might be the UI designer who told the developers to implement wrong behaviour, it might be a developer making a mistake, or the compiler. </p>

<p>On the other hand, if it was decided that the action for some button will not be implemented because it's too much cost and effort for the gain, that's certainly undesired behaviour, but it is intentional, not a bug. </p>

Body:
A bug would be behaviour that appears because someone, somewhere made a mistake. It might be the UI designer who told the developers to implement wrong behaviour, it might be a developer making a mistake, or the compiler.

On the other hand, if it was decided that the action for some button will not be implemented because it's too much cost and effort for the gain, that's certainly undesired behaviour, but it is intentional, not a bug.


问:
How is this Java Keystore cert still valid?
I maintain an old Java app that deploys to Tomcat and which uses SSL (and hence a keystore). It is important to note that this app will not even start up if the SSL cert is bad/expired/invalid!

Every year the SSL cert expires, and so someone has to replace the old/expiring cert stored in the JKS with a new one (provided to us by IT). I am now starting that process/fun for this year.

I started by running the keytool command that prints the contents of the JKS:

```<code>keytool -list -v -keystore myapp.jks
</code>```

Unless I'm reading its output wrong, I only see a cert that expired in 2015! If that's the case, how in the heck has this app been running for the last year?!? The one thing I do see is a cert in the "chain" that expires in 2034. I guess I don't understand SSL chains as well as I should, but my theory is that (somehow) the cert that expires in 2034 is somehow keeping my main cert alive/valid - is that possible? Here's a censored/summary of the output of that list command from above:

```<code>Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

Alias name: blah
Creation date: May 1, 2014
Entry type: PrivateKeyEntry
Certificate chain length: 3
Certificate[1]:
Owner: blah
Issuer: blah
Serial number: blah
Valid from: Thu Feb 16 15:49:19 EST 2012 until: Mon Feb 16 15:49:19 EST 2015
Certificate fingerprints:
    MD5:  blah
    SHA1: blah
    SHA256: blah
    Signature algorithm name: SHA1withRSA
    Version: 3

Extensions:

#1: ObjectId: blah Criticality=false
AuthorityInfoAccess [

...a lot of stuff omitted for brevity

Certificate[3]:
Owner: OU=Go Daddy Class 2 Certification Authority, O="The Go Daddy Group, Inc.", C=US
Issuer: OU=Go Daddy Class 2 Certification Authority, O="The Go Daddy Group, Inc.", C=US
Serial number: 0
Valid from: Tue Jun 29 13:06:20 EDT 2004 until: Thu Jun 29 13:06:20 EDT 2034
Certificate fingerprints:
    MD5:  blah
    SHA1: blah
    SHA256: blah
    Signature algorithm name: SHA1withRSA
    Version: 3

...a lot more stuff, again omitted for brevity
</code>```

Can anybody see any reason why this cert would still be valid?!?

答:
In certificate chaining, you are essentially allowing the issuer of certificates to validate your certificates on your behalf.  The GoDaddy certificate in this instance is your Root Certificate Authority and validates the identity of the Root CA.  They also will issue you an intermediary certificate to represent your organization as well and this is just another certificate on the chain.

If at any point along the way if your certificate is compromised then they can stop validating your intermediary certificate and this invalidates all other domain certificates that GoDaddy issued to you.  Why are they doing this?  It is so a client, if they so wish, can ask GoDaddy as the CA if the identity of the server is legit.  The Root CA cert identifies GoDaddy and is known to be trusted already, and then the Root CA will give the client a thumbs up or thumbs down.  Most browsers have this validation functionality built in.  You notice that on the browser where the certificate is presented for a secure site shows up in Green.  That generally means the browser validated the presented certificate against the CA and it was deemed valid.  When any certificate expires in this chain then trust cannot be established with the server by the client.

So what happens in Java?  Well a JKS file is essentially not only a keystore, but also a trust store for a Java application.  A trust store is something that a Java client will use to validate the identity of trusted servers that it is allowed to talk to.  Generally on a typical Java application running in a typical JVM, it will not establish an SSL connection with a secure network resource unless the presented certificate exists in its truststore.  Keep in mind, this certificate may not even be technically valid or it can EVEN be self signed and not validated by a Root CA, but if it exists on the specified Truststore that has been loaded into the Java application then it will still trust it.

What you didn't describe is if this certificate is for a network resource that you are providing as a server or a network resource that you require as a client.  If the latter then you might get a warning about the certificate being expired, but it will still work because it is in your trust store.


答:
Trying to come up with things not already said:

Secure management involvement. Remember that the success of a high-risk project often depends on management buy-in. Make sure you have legit and active stakeholders who want this badly. If not, you may find serious roadblocks if you meet resistance to change, and when changing systems, you will meet resistance to change. In one project where we were moving people to a new system, all they could talk about was how much better the old system was. Management gave people a chance to get on board, and if there were serious dissenters, they were released. The sad truth is that there were parts of the old system that were indeed better (a long story that's too depressing for me to retell here) but because management was serious, the implementation team got the backing it needed.

Secure a champion on the user side for the project. If the previous application's product manager is on board and actively involved, that's a plus. If not, an expert user that's respected in the community will be important. Demarco and Lister said something once to the effect of, "Every time a new system comes online, someone gains power and someone loses power." If a good leader on the user side is onboard with things, they'll potentially smooth the way for user acceptance.

Treat the new system like a new project and have a really good analyst involved. That analyst might be a senior developer, but whatever, you don't want to make the mistake of saying, "Oh, this'll be easy, just do what the old system does, but better." The problem is that if the old system is anything like most of those in corporate America, then identifying exactly "what the old system does" might not be as easy as it sounds...there's probably outdated, if any, documentation, and lots of crufty old ways of doing things in the system that might not even be relevant anymore. Lots of times systems do things just because that's the way it was done in the old manual process, and you can save a lot of work and wipe out a lot of convoluted logic by removing unneeded complications. Sometimes the best code is the line you don't write.

Look at the reporting component first. Reporting is often forgotten or left do finish as an afterthought, but this is losing out on a great tool for information. The old system's reports can tell you what the users needed most, and can be a good starting point for verifying what the new system's output should be. Be careful though to vet every report...probably some are not even used anymore.

Title: What are important things to remember when reengineering a legacy application?

Body: About to embark on the initial phases of a project to rewrite a legacy application from the ground up (existing business rules will change somewhat, and be extended to incorporate a large number of new requirements that the existing infrastructure cannot handle). I am looking for items that are important to remember when working to reengineer an existing application.</p>


答:
I think you listed the differences very well in your question, however I'll add some of my opinions regarding the two approaches.

AAA is very useful for me when I'm testing my own code.  If I'm working on a project or a library for myself, AAA is the way that I go.  It lets me set up whatever I need to execute my test and then just test it.  It's quick to setup, and quick to verify that my code is working as I expect.

GWT is useful in business environments, where work that is done by programmers needs to be mapped to business value.  Business value is mapped by features, and hopefully features that don't introduce bugs.  There are many strategies for mapping features to programming tasks, but one of them is through requirements.  In my experience, requirements range from user-level requirements all the way down to small tasks for the user to execute.  This is useful because it's easy for the managers to understand how the work the programmer is doing is impacting their customers/users, and therefore why the programmers are adding value to their business

User-Level Requirement: Given the warehouse has at least N item(s) in inventory, when a user purchases N item(s), then the warehouse ships N item(s) to the user

System-Level Requirement 1: Given the inventory system has N item(s) in inventory, when a request for N item(s) is input into the inventory system then the inventory system decreases the inventory count for that type of item

System-Level Requirement 2: Given the payment system has N item(s) in inventory, when a request for N item(s) is input into the payment system then the payment system charges the user for N item(s)

...

Programmer-Level Requirement 1: Given 5 sweaters are in inventory, when 3 sweaters are removed from inventory then 2 sweaters are left in the inventory

...

This sort of requirement structure allows for a tree-like design where all of the Programmer-Level Requirements map up the tree to the User-Level Requirements.  In this way, when a Programmer-Level Requirement fails then you know which User-Level Requirement is affected.

In contrast, an AAA test might look like this.  This to me is very programmer-facing and not useful to the business.  That's not to say a similar tree structure of requirements couldn't be made from an AAA testing strategy, but nothing in the language of AAA makes it easier to do so.

```<code>public void Test_CaseWhereThereAreEnoughSweatersLeft() {
    // Arrange
    // setup Sweater Inventory mock (DB mocks, etc)
    // count = 5
    // when The number of sweaters remaining is request, return count
    // when Inventory is requested to remove N items, then count = count - N

    // Act
    // call the Unit Under Test to remove 3 items from inventory

    // Assert
    // the number of sweaters in the inventory is 2
    // the removal should return indicating a successful removal of items from the inventory
}

public void Test_CaseWhereThereAreNotEnoughSweatersLeft() {
    // Arrange
    // setup Sweater Inventory mock (DB mocks, etc)
    // count = 2
    // when The number of sweaters remaining is request, return count
    // when Inventory is requested to remove N items, then count = count - N

    // Act
    // call the Unit Under Test to remove 3 items from inventory

    // Assert
    // the number of sweaters remaining is still 2
    // the removal should return an error indicating not enough items in the inventory
}
</code>```

Title: Differences between Given When Then (GWT) and Arrange Act Assert (AAA)?

Body:
In TDD there is Arrange Act Assert (AAA) syntax:

```<code>[Test]
public void Test_ReturnItemForRefund_ReturnsStockOfBlackSweatersAsTwo_WhenOneInStockAndOneIsReturned()
{
    //Arrange
    ShopStock shopStock = new ShopStock();
    Item blackSweater = new Item("ID: 25");
    shopStock.AddStock(blackSweater);
    int expectedResult = 2;
    Item blackSweaterToReturn = new Item("ID: 25");

    //Act
    shopStock.ReturnItemForRefund(blackSweaterToReturn);
    int actualResult = shopStock.GetStock("ID: 25");

    //Assert
    Assert.AreEqual(expectedResult, actualResult);
}
</code>```

In BDD writing tests uses a similar structure but with Given When Then (GWT) syntax:

```<code>    [Given(@"a customer previously bought a black sweater from me")]
    public void GivenACustomerPreviouslyBoughtABlackSweaterFromMe()
    { /* Code goes here */   }

    [Given(@"I currently have three black sweaters left in stock")]
    public void GivenICurrentlyHaveThreeBlackSweatersLeftInStock()
    { /* Code goes here */   }

    [When(@"he returns the sweater for a refund")]
    public void WhenHeReturnsTheSweaterForARefund()
    { /* Code goes here */   }

    [Then(@"I should have four black sweaters in stock")]
    public void ThenIShouldHaveFourBlackSweatersInStock()
    { /* Code goes here */   }
</code>```

Although they are often considered the same there are differences. A few key ones are:

GWT can be mapped directly to the specification of a feature file in BDD frameworks

GWT is easier for non-developers to understand by encouraging use of plain English, and having a short description of what each part is doing

Given When and Then are keywords in various BDD frameworks such as SpecFlow, and Cucumber

My question is are there any other differences (besides the names) between AAA and GWT? And is there any reason besides the ones specified above that one should be preferred over the other?

Body:
I think you listed the differences very well in your question, however I'll add some of my opinions regarding the two approaches.

AAA is very useful for me when I'm testing my own code.  If I'm working on a project or a library for myself, AAA is the way that I go.  It lets me set up whatever I need to execute my test and then just test it.  It's quick to setup, and quick to verify that my code is working as I expect.

GWT is useful in business environments, where work that is done by programmers needs to be mapped to business value.  Business value is mapped by features, and hopefully features that don't introduce bugs.  There are many strategies for mapping features to programming tasks, but one of them is through requirements.  In my experience, requirements range from user-level requirements all the way down to small tasks for the user to execute.  This is useful because it's easy for the managers to understand how the work the programmer is doing is impacting their customers/users, and therefore why the programmers are adding value to their business

User-Level Requirement: Given the warehouse has at least N item(s) in inventory, when a user purchases N item(s), then the warehouse ships N item(s) to the user

System-Level Requirement 1: Given the inventory system has N item(s) in inventory, when a request for N item(s) is input into the inventory system then the inventory system decreases the inventory count for that type of item

System-Level Requirement 2: Given the payment system has N item(s) in inventory, when a request for N item(s) is input into the payment system then the payment system charges the user for N item(s)

...

Programmer-Level Requirement 1: Given 5 sweaters are in inventory, when 3 sweaters are removed from inventory then 2 sweaters are left in the inventory

...

This sort of requirement structure allows for a tree-like design where all of the Programmer-Level Requirements map up the tree to the User-Level Requirements.  In this way, when a Programmer-Level Requirement fails then you know which User-Level Requirement is affected.

In contrast, an AAA test might look like this.  This to me is very programmer-facing and not useful to the business.  That's not to say a similar tree structure of requirements couldn't be made from an AAA testing strategy, but nothing in the language of AAA makes it easier to do so.

public void Test_CaseWhereThereAreEnoughSweatersLeft() {
    // Arrange
    // setup Sweater Inventory mock (DB mocks, etc)
    // count = 5
    // when The number of sweaters remaining is request, return count
    // when Inventory is requested to remove N items, then count = count - N

    // Act
    // call the Unit Under Test to remove 3 items from inventory

    // Assert
    // the number of sweaters in the inventory is 2
    // the removal should return indicating a successful removal of items from the inventory
}

public void Test_CaseWhereThereAreNotEnoughSweatersLeft() {
    // Arrange
    // setup Sweater Inventory mock (DB mocks, etc)
    // count = 2
    // when The number of sweaters remaining is request, return count
    // when Inventory is requested to remove N items, then count = count - N

    // Act
    // call the Unit Under Test to remove 3 items from inventory

    // Assert
    // the number of sweaters remaining is still 2
    // the removal should return an error indicating not enough items in the inventory
}


答:
As you are creating an app that faces the general public, it doesn't really matter how the contracts are stored internally and what access controls are used by those different systems.

If the company offers a portal to its customers to see their contracts and associated data, then as a customer, I expect to have a single login to the "My Company X" app and to be able to see all contracts that I have with Company X.

It is the job of this app to collect those contracts from the different storage locations and I should not even be aware that the contracts might be spread out over multiple systems.

The internal systems that currently do authentication will most likely not have accounts for all the customers of the company, but rather accounts for the employees that need to have access to the data that is stored there.

For the app you are developing, that will also have to authenticate itself to those systems to be able to read the relevant information. So, you will not be able to piggyback on the existing authentication databases for authenticating the customers using your app.

Title: Having an discussion about security concerns with another software engineer

Body:
Background: The company I work for uses different systems to hold their insurance data which is customer related. They want to have an app for their customers where they can find their insurance related things in. Some of these systems provide web services to get the necessary information, so proper user authentication and whatsoever is possible. However, some provide direct database access without anything which comes even close to user authentication, because it was not designed to do that.

To solve this issue we are building an adapter-service, which can connect to all the different systems to get the necessary data. However the user-authentication is still an issue for the systems which don't provide that.

Another software engineer suggested (we are the only engineers) we build a general authentication mechanism which provides authentication to all the systems to get the necessary customer information. We both have the same background, we are young, we don't have that much experience in designing such a system or understanding all the security issues for such a system.

Question: With the background as stated above, I am concerned about all the security concerns which may come up if we would do that. That for the serious kind of information (insurance data) we may lack the experience to set up a system like that, to ensure the best kind of security is possible and not limited by our knowledge (or Google).

His opinion on this matter is that a general authentication mechanism should be build for all systems. So with one login on our side they can get all the data from the different systems if it is available there. If we follow up with things such as OAuth that we don't have to fear the security issue that much. And if we (re)search these things on the internet, that it will be OK.

My opinion on this matter is that a general authentication mechanism will be a good thing for all the systems which don't provide the necessarry things for user authentication (which is also possible the only solution). However we should not override systems which provide their own authentication to access their system to get the necessary data from a customer. Perhaps information can be exchanged between all the systems to ensure the same kind of login is  available everywhere (if user exists in a system which provides authentication and with a systems which uses the general authentication). If an password for example is changed. This idea would make sure if our general authentication mechanism is breached somehow, that not all the systems will be exposed to the attacker, and who knows what the consequences might be.

Should we just go through with the idea to make a general authentication mechanism or limit it to the systems who need it and possible exchange login-details if the user should exist in the two different kind of systems (system which supports authentication or doesn't). What are good arguments for or against these ideas?

Edit: The general public would be using it, each system would provide the contract(s) with its data (if the customer exists in the different systems). Example: for customer '1' system A (database) and B (web-service) contains both different contracts from him. However, for customer '2' only system A (database) contains a contract. Depending on the customer their kind of contract(s) they are stored in different systems. All of these systems are third party.


答: Whether or not you use generic parameters as @DavidArno suggests, your interface should probably be written in terms of other interaces, not in terms of classes.  It is perfectly reasonable for an abstraction of concepts to require several interfaces.  But an interface that consumes and returns classes is probably not fully abstracted. So, keep going until you reach that set of abstract concepts, that set of coordinated interfaces that accomplish a good abstraction.</p>

Title: Does an interface including several methods that return instances of Object make sense?

Body:
I am in the process of writing my first true API. In the process, I am defining an interface for mapping complex data structures onto other complex data structures.

At the moment, the interface contains a set method for the input data structure, a run method to kick off the mapping process, and several methods which basically have the same signature, but of course different names and different documentation. The latter all return java.lang.Object. Something as follows.

public interface DataCompiler {

  public void setInputDataStructure(IDS ids);

  public void run();

  /**
   * Maps a "this" structure to a target "this" structure and
   * returns the resulting target "this" structure.
   */
  public Object mapThisStructure();

  /**
   * Maps a "that" structure to a target "that" structure and
   * returns the resulting target "that" structure.
   */
  public Object mapThatStructure();

  /**
   * Maps an "other" structure to a target "other" structure and
   * returns the resulting target "other" structure.
   */
  public Object mapOtherStructure();

}
```

So, an interface is meant to define a contract that must be fulfilled by implementations of the interface.

However, with my interface there is no safety catch in the method signatures themselves to prevent a misuse of any of the last three methods. E.g., mapThisStructure could actually be implemented in the exact way that mapThatStructure is meant to be implemented. Or, someone could put all mapping work into either one of the three mappings (which would of course breach the principle of one method doing one and only one thing), and simply let the other two return null.

Thus actual contract is defined in the JavaDoc. So, does the set up of such an interface make sense?


问:
Is using this complex data structure bad practice?
Right now in my current company I must "parse" a csv and extract some data out of it (in the sense of data mining).

I surprised myself by defining the following data structure (Java 8):

```<code>static List<Map<String, Map<String, LocalDate[]>>> intervalStructure
</code>```

Is this considered bad practice? Should I use a self-define class instead to store some data?

答:
This is a dumb, stringly typed data structure.  It is a:

List

of Maps

keyed by String

of Maps

keyed by String

of Local date array

This makes it difficult to create, traverse, and could very well get you into code that looks like:

```<code>foo.get(1).get("bar").get("qux")[42]
</code>```

And guess what... you've got a null pointer exception that was thrown on that line.

Setting up the structure isn't much fun either.  That this is a rawish data structure means that you have to do all of the adds and deletes by hand working on the interfaces (that can be rather deep) rather than working with a Constructor or Builder.

You've linked the representation that is passed around in your code to the representation of the file. When one needs to change, the other needs to change - and possibly in multiple locations.  Think of the joys you will have when you have an xml or json or yaml data file behind it and need to go through and change things.

This all in all is a bad idea.

A better idea would be to have one or more classes that exposes the logic of fetching the data.  You have a Structure.  It exposes a get(String bar, String qux) and returns back a List.  This allows you to isolate the traversal of the structure (if it is that) in private fields so that it can change as needed.  It also exposes an add(String bar, String qux, LocalDate date) which allows you to clearly isolate the logic for building it in a testable way.

You may find that you want other questions of that data that you want answered.  Maybe you want a isInRange(...) or contains(...) or something else that you ask.  Failing to have this as a nice class with corresponding methods to answer those questions, you will find that you either have a static method in a helper class (this is beginning to smell) that acts on that data.

```<code>public static boolean contains(List<Map<String, Map<String, LocalDate[]>>> arg, LocalDate value)
</code>```

That looks as ugly as it is.  Don't do that.

If you don't do that, you will have a copy of that logic each time you use it which is not at all DRY.

Either way, working on raw data structures like this is undesirable.

Body:
This is a dumb, stringly typed data structure.  It is a:

List

of Maps

keyed by String

of Maps

keyed by String

of Local date array

This makes it difficult to create, traverse, and could very well get you into code that looks like:

foo.get(1).get("bar").get("qux")[42]

And guess what... you've got a null pointer exception that was thrown on that line.

Setting up the structure isn't much fun either.  That this is a rawish data structure means that you have to do all of the adds and deletes by hand working on the interfaces (that can be rather deep) rather than working with a Constructor or Builder.

You've linked the representation that is passed around in your code to the representation of the file. When one needs to change, the other needs to change - and possibly in multiple locations.  Think of the joys you will have when you have an xml or json or yaml data file behind it and need to go through and change things.

This all in all is a bad idea.

A better idea would be to have one or more classes that exposes the logic of fetching the data.  You have a Structure.  It exposes a get(String bar, String qux) and returns back a List.  This allows you to isolate the traversal of the structure (if it is that) in private fields so that it can change as needed.  It also exposes an add(String bar, String qux, LocalDate date) which allows you to clearly isolate the logic for building it in a testable way.

You may find that you want other questions of that data that you want answered.  Maybe you want a isInRange(...) or contains(...) or something else that you ask.  Failing to have this as a nice class with corresponding methods to answer those questions, you will find that you either have a static method in a helper class (this is beginning to smell) that acts on that data.

public static boolean contains(List<Map<String, Map<String, LocalDate[]>>> arg, LocalDate value)

That looks as ugly as it is.  Don't do that.

If you don't do that, you will have a copy of that logic each time you use it which is not at all DRY.

Either way, working on raw data structures like this is undesirable.


问:
Relation between developers and clients
I'm currently working in a small company that its taking care of implementing lots of systems, most of them for goverment institutions, in witch it generally means taking software developted 20 years ago and refurbish them so fit up-to-date needs. The clients generally are very used to them and tend to discourage change (they are in their 50s 60s give or take, so not technologie-friendly in general).

As you can imagine, dev-team in most cases starts taking care of relation with clients, generating the documentation needed in this cases (CU usually), assisting to weekly meets to see improvements with clients.

As for experience, this is a gold mine for me, because gives a nice perspective on all the aspects of software development, but also some problems rise because, if developers come from mars then clients are from venus. There is a fine gap on the vocabulary/experience/capability-to-interpret-needs that generates a noise in the communication, and some times affecting the final product.

Should a developer be in direct contact with the client, or there should be an "adapter" guy that translates client needs in pseudo formal requirements understandable to us?

答:
Developers should absolutely be in contact with the clients! Even if a business analyst writes a formal specification, its always beneficial to have access to the client to ask specific questions or get instant feedback on a feature you are working on. Business analysts are very helpful, but I would never want to work solely through them for requirements. Also, I would never want to wait more than a week or two to show off a feature to a client. Even if they make changes, its always easier to make a small change closer to the time of development rather than piling all the changes to the end of the project.

Newer software methodologies are also geared toward bringing the client and the software development teams closer together. One of the main principles of Agile/Scrum is that the client be on the team and always be available for questions. Agile teams also demo their software after every sprint or iteration. Agile was formed under the assumption that software changes and that teams should be "agile" and adapt to changing business requirements.

Title: Relation between developers and clients


答: If you're on a Unix-type system, find(1) and grep(1) will enable you to pull together a list of references by file to the calls you want to identify. If you put this in a script, you can run it periodically to verify that you've removed all the references. Just remember to skip any compressed/minified versions of your files, or you'll get duplicate references.

Title: Preparing to remove a tightly coupled service provider out of source code

Body:
I'm working on a huge legacy codebase that uses Bing Maps API as a service provider and I have got the task to scrap Bing which is the foundation of the software and has been referenced through the source code everywhere.

There are no unit tests at all. Very few pages of documentation. Also it's a JavaScript code-base, built on top of ExtJS 3.4, a badly designed custom wrapper around objects to mock classic inheritance and class hierarchies, and Bing being used all over the code and referenced through functions everywhere.

My question is: How should I document and count the references of Bing through out the code? I'm hoping to use this to make a better time estimation, and later, help ease the refactoring process.

I have already started browsing the code-base but I'm not sure what's the best way of documenting references.


问:
Can "return this" pattern be optimized to no cost performance?
return this (or similar construct) allows method chaining. Lack of it is painful, because you have to write such code (C#):

```<code>var list = new List<string>();
list.Add("hello");
list.Add("world");
</code>```

instead of

```<code>list.Add("hello").Add("world");
</code>```

Elixir solves it nicely for function chaining, instead of relying on callee it relies on caller (forgive me my mistakes, I don't know Elixir):

```<code>list |> add("hello") |> add("world");
</code>```

But now I have just read this sentence at wikipedia:

Returning an object of built-in type from a function usually carries
  little to no overhead, since the object typically fits in a CPU
  register.

On one hand callee does not know if the result will be used or not, on the other hand caller cannot stop callee from setting the result value. So I am skeptical about this "little", but "no overhead"?

Thus MY QUESTION for this very particular pattern (i.e return this with method chaining) -- can it be optimized with no overhead? How?

Question by example -- say I will write a framework and sprinkle every possible method with return this just to give ability for method chaining. The question arise -- will user who does not use method chaining will pay the price of lowered performance? How compiler could optimize code that this feature will have zero cost.

Update after first 2 comments -- "cheap"!="free", so maybe another perspective for my question, why the difference "little" vs. "no cost". If it can be guaranteed it is at no cost, we write "no cost", period. So I assume it cannot be guaranteed, thus "little".

Clarification I am not asking how to make another Elixir-like syntax in other language. I am asking how it is possible for compiler to optimize callee-caller interaction on return this + method chaining (or lack of it, when not used).

答:
Dart has this feature. So you can do

```<code>StringList myList = new StringList()
    ..Add("hello")
    ..Add("world");
</code>```

Here we can treat F(expr..m(...)) as syntax sugar for:

```<code>var _generated_temp = expr;
_generated_temp.m(...);
F(_generated_temp);
</code>```

You can see Dart also allows setting properties to be chained in the same way:

```<code>Person myPerson = new Person()
    ..Name = "Jane Doe"
    ..Age  = 31;
</code>```

C# gives you a subset of these features with initialization syntax. So you can translate the above into

```<code>StringList myList = new StringList { "hello", "world" };

Person myPerson = new Person{ Name = "Jane Doe", Age = 31 };
</code>```

However, this syntax sugar is available only at initialization and not available for arbitrary method calls, so it is strictly less expressive than Dart's version.

So it is possible to offer fluent interfaces as a language feature, which would remove any performance cost. However, the performance cost of a fluid interface is so negligible as to be effectively nil, so one should not argue for it on those bases. (Note that it might be in theory possible for non-virtual methods that just return this to be optimized away. This optimization would not be worth performing.) Rather, the benefit would be the opportunity to use a fluent interface even when it was not designed for.

Body:
Dart has this feature. So you can do

StringList myList = new StringList()
    ..Add("hello")
    ..Add("world");

Here we can treat F(expr..m(...)) as syntax sugar for:

var _generated_temp = expr;
_generated_temp.m(...);
F(_generated_temp);

You can see Dart also allows setting properties to be chained in the same way:

Person myPerson = new Person()
    ..Name = "Jane Doe"
    ..Age  = 31;

C# gives you a subset of these features with initialization syntax. So you can translate the above into

StringList myList = new StringList { "hello", "world" };

Person myPerson = new Person{ Name = "Jane Doe", Age = 31 };

However, this syntax sugar is available only at initialization and not available for arbitrary method calls, so it is strictly less expressive than Dart's version.

So it is possible to offer fluent interfaces as a language feature, which would remove any performance cost. However, the performance cost of a fluid interface is so negligible as to be effectively nil, so one should not argue for it on those bases. (Note that it might be in theory possible for non-virtual methods that just return this to be optimized away. This optimization would not be worth performing.) Rather, the benefit would be the opportunity to use a fluent interface even when it was not designed for.


答:
A bug is when the user-observable behavior differs from the documented behavior. An undesired behavior is when the user-observable behavior correctly corresponds to the documented behavior, but you would rather like to have a different behavior.

"Bug": the system doesn't do what it promises

"Undesired behavior": the system makes stupid promises


答:
First off,

```<code>var list = new List<string>();
list.Add("hello");
list.Add("world");
</code>```

Is just as, if not more readable than

```<code>var list = new List<string>().Add("hello").Add("world");
</code>```

Lines of code is not, in any way a proxy for code's cleanliness or simplicity.

Thus my question for this very particular pattern (i.e "return this" for method chaining) -- can it be optimized with no overhead? How?

So theoretically, sure. This would be similar to tail call optimization, where you wouldn't need to completely unwind the stack frame when moving between functions, you could leave the this argument where it is when you're done (or just peek rather than pop it in a stack based model). The challenge comes that you can only do that if you know the next call will be a chain. Since functions don't really know about their callers, they don't know if they should clean up after themselves or not. You could have some internal flag, which the function could check to know which path to take, but that would be more expensive than just passing in this all the time.

The compiler could also make two versions of the function, and pick the right one at compile time. That would bloat the resultant executable, slow compilation time, but probably shave an instruction or two from actual runtime.

Title: Can "return this" pattern be optimized to no cost performance?

Body:
return this (or similar construct) allows method chaining. Lack of it is painful, because you have to write such code (C#):

```<code>var list = new List<string>();
list.Add("hello");
list.Add("world");
</code>```

instead of

```<code>list.Add("hello").Add("world");
</code>```

Elixir solves it nicely for function chaining, instead of relying on callee it relies on caller (forgive me my mistakes, I don't know Elixir):

```<code>list |> add("hello") |> add("world");
</code>```

But now I have just read this sentence at wikipedia:

Returning an object of built-in type from a function usually carries
  little to no overhead, since the object typically fits in a CPU
  register.

On one hand callee does not know if the result will be used or not, on the other hand caller cannot stop callee from setting the result value. So I am skeptical about this "little", but "no overhead"?

Thus MY QUESTION for this very particular pattern (i.e return this with method chaining) -- can it be optimized with no overhead? How?

Question by example -- say I will write a framework and sprinkle every possible method with return this just to give ability for method chaining. The question arise -- will user who does not use method chaining will pay the price of lowered performance? How compiler could optimize code that this feature will have zero cost.

Update after first 2 comments -- "cheap"!="free", so maybe another perspective for my question, why the difference "little" vs. "no cost". If it can be guaranteed it is at no cost, we write "no cost", period. So I assume it cannot be guaranteed, thus "little".

Clarification I am not asking how to make another Elixir-like syntax in other language. I am asking how it is possible for compiler to optimize callee-caller interaction on return this + method chaining (or lack of it, when not used).

Body:
First off,

var list = new List<string>();
list.Add("hello");
list.Add("world");

Is just as, if not more readable than

var list = new List<string>().Add("hello").Add("world");

Lines of code is not, in any way a proxy for code's cleanliness or simplicity.

Thus my question for this very particular pattern (i.e "return this" for method chaining) -- can it be optimized with no overhead? How?

So theoretically, sure. This would be similar to tail call optimization, where you wouldn't need to completely unwind the stack frame when moving between functions, you could leave the this argument where it is when you're done (or just peek rather than pop it in a stack based model). The challenge comes that you can only do that if you know the next call will be a chain. Since functions don't really know about their callers, they don't know if they should clean up after themselves or not. You could have some internal flag, which the function could check to know which path to take, but that would be more expensive than just passing in this all the time.

The compiler could also make two versions of the function, and pick the right one at compile time. That would bloat the resultant executable, slow compilation time, but probably shave an instruction or two from actual runtime.