答:
In your statistics report on the number of defects you should differentiate between different kinds of defects:

Defects on stories that have been delivered in previous sprints. Unless the teams consistently work on separate parts of the application (i.e. a front-end and a back-end team), there is not really a point in separating these defects out per team.

Defects on stories in the current sprint that were found and fully fixed.

Defects on stories in the current sprint that are open at the end of the sprint. It doesn't matter here if the issues has been closed and reopened during the sprint. Only the status at the moment of the demo is relevant.

The first two categories can then be subdivided further by issue resolution (fixed, duplicate, rejected).

This way, there is a clear distinction between the number of issues related to current work and the number of issues related to past work.

When dealing with defect statistics, there are two things that you should be careful with:

Multiple defects in one report.

Morphing defects: After fixing the original defect, the same ticket gets reused to report a different issue.

Both are a nuisance when solving/verifying issues, but they are an outright nightmare for the statistics. In both cases, it should really be reported as multiple, distinct, issues.

Regarding whether stories are done if there are defects open on them: Generally, a story should not be considered to be done if it has open defects associated with it, but you should also allow the Product Owner to accept a story anyway if, in the opinion of the PO, the defects are not important enough to block the story on.

There can be business reasons to accept minor issues with a product, but that call can only be made by the representative of the customer (i.e. the Product Owner).

Title: Reporting defects in Agile

Body:
   I am working in sprint. At the end of sprint I need to send a defect report per sprint. Considering the below scenario please let me know your views.

Two teams(A & B) are working at different locations in Sprint-2 and I am a tester from Team-A and report the defects for the items developed by Team-A in each sprint

Question

1. I reported few defects in Sprint-2 for the functionality developed by Team-B in previous sprint. Do I have to consider this as observation or defect and report to Team-A?

2. I reported 5 defects of Sprint-2 for the functionality developed by team-A. All the defects are fixed and closed by me in the same sprint. Before the end of sprint I observed 2 defects got reopened for some reason. Now the defect count should be 5 or 7(5+2) should be considered for this sprint?

Thanks

Khan


问:
How to name a method that both performs a task and returns a boolean as a status?
If there is a method

```<code>bool DoStuff() {
    try {
        // doing stuff...
        return true;
    }
    catch (SomeSpecificException ex) {
        return false;
    }
}
</code>```

should it rather be called IsStuffDone()?

Both names could be misinterpreted by the user:
If the name is DoStuff() why does it return a boolean?
If the name is IsStuffDone() it is not clear whether the method performs a task or only checks its result.

Is there a convention for this case? Or an alternative approach, as this one is considered flawed? For example in languages that have output parameters, like C#, a boolean status variable could be passed to the method as one and the method's return type would be void.

EDIT: In my particular problem exception handling cannot be directly delegated to the caller, because the method is a part of an interface implementation. Therefore, the caller can't be charged with dealing with all the exceptions of different implementations. It is not familiar with those exceptions. However, the caller can deal with a custom exception like StuffHasNotBeenDoneForSomeReasonException as was suggested in npinti's answer and comment.

答:
DoStuff() is enough, and the returning value of the function should be documented, and
you don't need to mention it in the function name,
looking for many of API available:

PHP

```<code>// this method update and return the number affected rows
// called update instead of updateAndGetAffectedCount
$affected = $query->update(/* values */);
</code>```

C-Sharp

```<code>// Remove item from the List
// returns true if item is successfully removed; otherwise, false.
public bool Remove( T item )
</code>```

ContentLicense: CC BY-SA 3.0

Body:
DoStuff() is enough, and the returning value of the function should be documented, and
you don't need to mention it in the function name,
looking for many of API available:

PHP

// this method update and return the number affected rows
// called update instead of updateAndGetAffectedCount
$affected = $query->update(/* values */);

C-Sharp

// Remove item from the List
// returns true if item is successfully removed; otherwise, false.
public bool Remove( T item )


问:
What happens if you're unable to solve a problem?
I'm a year away from graduating from university, and I'm really looking forward to solving practical problems. Especially non-trivial ones which require a bit of research and a lot of thinking.

But at the same time, that is also my greatest fear - being faced with a problem that I'm unable to solve, no matter how hard I try. And with pressure to deliver code on impending deadlines just around the corner, it does look a bit scary when viewing it from the safe playgrounds on uni (where the worst thing that can happen is that you have to redo a course or exam).

So for those who have been in industry for any longer length of time, what would happen if you were told to solve a problem that you couldn't? Has it happened, and if so, what did happen? Did they just drop it and said "Oh well, guess we can make do with something else"? Were there consequences? Were you reprimanded, or even fired?

答:
As others have said, communication is critical - letting people know (who will be impacted) when you're stuck: your boss, team members, clients, etc.

A sharp co-worker once instilled upon me that success has roots in two things:

Relationships

Expectations

Having a good relationship, I suppose, is a function of good communication and setting expectations up front.

ContentLicense: CC BY-SA 2.5


问:
How to handle updated configuration when it's already been cloned for editing
Really sorry about the title that probably doesn't make much sense. Hopefully I can explain myself better here as it's something that's kinda bugged me for ages, and is now becoming a pressing concern as I write a bit of software with configuration.

Most software comes with default configuration options stored in the app itself, and then there's a configuration file (let's say) that a user can edit. Once created/edited for the first time, subsequent updates to the application can not (easily) modify this configuration file for fear of clobbering the user's own changes to the default configuration. So my question is, if my application adds a new configurable parameter, what's the best way to aid discoverability of the setting and allow the user (developer) to override it as nicely as possible given the following constraints:

I actually don't have a canonical default config in the application per se, it's more of a 'cascading filesystem'-like affair - the config template is stored in default/config.json and when the user wishes to edit the configuration, it's copied to user/config.json. If a user config is found it is used - there is no automatic overriding of a subset of keys, the whole new file is used and that's that. If there's no user config the default config is used. When a user wishes to edit the config they run a command to 'generate' it for them (which simply copies the config.json file from the default to the user directory).

There is no UI for the configuration options as it's not appropriate to the userbase (think of my software as a library or something, the users are developers, the config is done in the user/config.json file).

Due to my software being library-like there's no simple way to, on updating of the software, run some tasks automatically (so any ideas of look at the current config, compare to template config, add ing missing keys) aren't appropriate.

The only solution I can think of right now is to say "there's a new config setting X" in release notes, but this doesn't seem ideal to me.

If you want any more information let me know. The above specifics are not actually 100% true to my situation, but they represent the problem equally well with lower complexity. If you do want specifics, however, I can explain the exact setup.

Further clarification of the type of configuration I mean: think of the Atom code editor. There appears to be a default 'template' config file somewhere, but as soon as a configuration option is edited ~/.atom/config.cson is generated and the setting goes in there. From now on is Atom is updated and gets a new configuration key, this file cannot be overwritten by Atom without a lot of effort to ensure that the addition/modification of the key does not clobber. In Atom's case, because there is a GUI for editing settings, they can get away with just adding the UI for the new setting into the UI to aid 'discoverability' of the new setting. I don't have that luxury.

Clarification of my constraints and what I'm actually looking for:

The software I'm writing is actually a package for a larger system. This larger system is what provides the configuration, and the way it works is kinda fixed - I just do a config('some.key') kinda call and it knows to look to see if the user has a config clone and if so use it, otherwise use the default config which is part of my package.

Now, while I could make my application edit the user's configuration files (there is a convention about where they're stored), it's generally not done, so I'd like to live with the constraints of the system I'm using if possible.

And it's not just about discoverability either, one large concern is that the addition of a configuration key won't actually work as soon as the user has their own copy of the original template. Adding the key to the template won't make a difference as that file is never read. As such, I think this is actually quite a big flaw in the design of the configuration cascading system and thus needs to be taken up with my upstream.

So, thinking about it, based on my constraints, I don't think there's going to be a good solution save for either editing the user's configuration or using a new config file every time there are updates to the default configuration. Even the release notes idea from above isn't doable as, if the user does not follow the advice, suddenly I have a config key with no value (user-defined or default).

So the new question is this: what is the general way to solve the problem of having a default configuration in template config files and allowing a user to make user-specific version of these in order to override the defaults? A per-key cascade (rather than per-file cascade) where the user only specifies their overrides?

In this case, what happens if a configuration value is an array - do we replace or append to the default (or, more realistically, how does the user specify whether they wish to replace or append to)?

It seems like configuration is kinda hard, so how is it solved in the wild?

答:
I'd do the following. When the updated software runs and reads the configuration (already cloned), it can see it knows new configuration X but that's not inside the configuration file.

So you can show a message to the user and, if you like, add the option inside one or both the configuration files, maybe with a default value (usually a value that doesn't change previous behavour of the software). I don't know if this violates your 3rd condition.

Duplication gives always some kind of problems. Maybe you can do a clone of the configuration file just in case the edited version cause your application to break (and should be used only by developer, and not your software, to check the last working (backup) version and fix the error in the edited version).


答:
Since your format is json, it should be relatively safe to do this:

Read and parse the whole config file. If parsing fails, probably the user has made a fatal mistake and this should be corrected before any attempts to automatically append it are made

Check for the existence of your new options. If you don't find them, append them (with the default value) in the object model that results from parsing the config file

If any such changes have been made, rename the old config.json to config.json.sav or similar and write the changed object model to config.json

The only likely problem is that the user has added whitespace to the file, or rearranged the some itmes, to make the config file more readable by his personal standards. Those changes would be gone. To mitigate this problem, the JSON file should be written in a readable manner by default (intention and linebreaks where appropriate).

Unfortunately, JSON doesn't allow for comments, so marking the new options in the file with comments is not an option.

Title: How to handle updated configuration when it's already been cloned for editing

Body:
Really sorry about the title that probably doesn't make much sense. Hopefully I can explain myself better here as it's something that's kinda bugged me for ages, and is now becoming a pressing concern as I write a bit of software with configuration.

Most software comes with default configuration options stored in the app itself, and then there's a configuration file (let's say) that a user can edit. Once created/edited for the first time, subsequent updates to the application can not (easily) modify this configuration file for fear of clobbering the user's own changes to the default configuration. So my question is, if my application adds a new configurable parameter, what's the best way to aid discoverability of the setting and allow the user (developer) to override it as nicely as possible given the following constraints:

I actually don't have a canonical default config in the application per se, it's more of a 'cascading filesystem'-like affair - the config template is stored in default/config.json and when the user wishes to edit the configuration, it's copied to user/config.json. If a user config is found it is used - there is no automatic overriding of a subset of keys, the whole new file is used and that's that. If there's no user config the default config is used. When a user wishes to edit the config they run a command to 'generate' it for them (which simply copies the config.json file from the default to the user directory).

There is no UI for the configuration options as it's not appropriate to the userbase (think of my software as a library or something, the users are developers, the config is done in the user/config.json file).

Due to my software being library-like there's no simple way to, on updating of the software, run some tasks automatically (so any ideas of look at the current config, compare to template config, add ing missing keys) aren't appropriate.

The only solution I can think of right now is to say "there's a new config setting X" in release notes, but this doesn't seem ideal to me.

If you want any more information let me know. The above specifics are not actually 100% true to my situation, but they represent the problem equally well with lower complexity. If you do want specifics, however, I can explain the exact setup.

Further clarification of the type of configuration I mean: think of the Atom code editor. There appears to be a default 'template' config file somewhere, but as soon as a configuration option is edited ~/.atom/config.cson is generated and the setting goes in there. From now on is Atom is updated and gets a new configuration key, this file cannot be overwritten by Atom without a lot of effort to ensure that the addition/modification of the key does not clobber. In Atom's case, because there is a GUI for editing settings, they can get away with just adding the UI for the new setting into the UI to aid 'discoverability' of the new setting. I don't have that luxury.

Clarification of my constraints and what I'm actually looking for:

The software I'm writing is actually a package for a larger system. This larger system is what provides the configuration, and the way it works is kinda fixed - I just do a config('some.key') kinda call and it knows to look to see if the user has a config clone and if so use it, otherwise use the default config which is part of my package.

Now, while I could make my application edit the user's configuration files (there is a convention about where they're stored), it's generally not done, so I'd like to live with the constraints of the system I'm using if possible.

And it's not just about discoverability either, one large concern is that the addition of a configuration key won't actually work as soon as the user has their own copy of the original template. Adding the key to the template won't make a difference as that file is never read. As such, I think this is actually quite a big flaw in the design of the configuration cascading system and thus needs to be taken up with my upstream.

So, thinking about it, based on my constraints, I don't think there's going to be a good solution save for either editing the user's configuration or using a new config file every time there are updates to the default configuration. Even the release notes idea from above isn't doable as, if the user does not follow the advice, suddenly I have a config key with no value (user-defined or default).

So the new question is this: what is the general way to solve the problem of having a default configuration in template config files and allowing a user to make user-specific version of these in order to override the defaults? A per-key cascade (rather than per-file cascade) where the user only specifies their overrides?

In this case, what happens if a configuration value is an array - do we replace or append to the default (or, more realistically, how does the user specify whether they wish to replace or append to)?

It seems like configuration is kinda hard, so how is it solved in the wild?


问:
Open-sourcing a proprietary library without certain features
I hope I'm in the right place to ask that.

I have a question regarding the practice of open-sourcing a proprietary library that we built and use at work. The licence will probably be MIT. I like the idea, but here comes the unusual part : I have been tasked to remove some of the most advanced features. Those will remain on our servers, available as a service. We will open-source the (JavaScript in case it is of interest) library, along with a minimal associated server code.

I am not asking a question about the technical problems (I imagine we will have to maintain and synchronize somehow different repositories, maybe with incompatible pull requests, but this question is for another day).

What I would like to know is:

How that would be perceived by the community at large ? Does it risk killing the eventual interest in this library?

I don't personally know of any library that works like that. I'm pretty sure it is possible however, but any evidence of such a library is welcome (successful if possible). That's also because I'd like to see how they present it.

More importantly, what could be the rationale for/against it? I'm not sure I understand the consequences of doing it so.

EDIT

After learning a thing or two from the answers and comments, I've collected here a few examples :

http://www.jfrog.com/home/v_artifactorypro_overview

http://www.easyrtc.com/pricing/

http://rapidminer.com/the-core-of-rapidminer-is-open-source/  (note the angry comments on this one - but we're doing the opposite, from proprietary to open-core)

As a developer, I would use the product we are going to release it in personal projects, so I think it's useful. But I have been working on it and I have an obvious bias.

Also, most feedback I've seen basically says "you can try, but it won't work". See also http://blogs.gartner.com/brian_prentice/2010/03/31/open-core-the-emperors-new-clothes/

If someone is able to find a successful product doing open-core, I'd be grateful.

答:
Can you do it? Sure. It's no different in effect from taking an existing OSS project and building a proprietary layer on top of it to add functionality which you then sell, you're just doing it in reverse.

Will people react with hostility? Of course. The open source zealots already hate you for not being one of them and having any source at all you keep to yourself, that's not going to change. But as long as what you release is functional and not so limited as to have every method call respond with "contact us at www.somecompany.com to buy a license to use this" pragmatic people may well adopt it if it suits their needs.

What's the pros and cons? You potentially get other people to help with development of your product. But at the same time you're going to have to spend time guiding and controlling that process in order to not lose the interface with the code you do keep to yourself (I assume you're considering open sourcing it in order to shove part of the development effort towards free labour, a common reason). Whether that monitoring and controlling work is more or less expensive than doing your own maintenance is impossible for me to tell, and impossible for you to tell as well until the project is well underway as it depends on the maintainers you attract as well as on the amount of code and the amount of work that needs to be done on it that gets moved to an OSS license.

Overall I'd say it's a potentially smart marketing move, but a risky and possibly expensive technical move, unless you're effectively abandoning the codebase, freezing your own version and just moving on to something else.


问:
when to use a scaled/enterprise agile software development framework and when to let agile processes 'emerge'?
There are quite a few enterprise agile software development frameworks available:

Scott Ambler: Disciplined Agile Delivery

Dean Leffingwell: Scaled Agile Framework

Alan Shalloway: Enterprise Agile Book

Craig Larman: Scaling Lean and Agile

Barry Boehm: Balancing Agility and Discipline

Brian Wernham: Agile Project Management for Government - DSDM, Scrum and others

I've also spoken with people that state that your enterprise agile processes should just 'emerge' and that you shouldn't need or use a framework because they constrain you.

Question 1: When should one choose an enterprise agile software development framework, and when should one just let their agile processes 'emerge'.

Question 2: If choosing an enterprise agile software development framework, how does one select the appropriate framework to use for their organisation?

Please provide evidence of your experience or research when answering questions rather than just presenting opinions.

答:
Learn how to be agile first.

I think there is a problem with adopting agile for the first time along with an enterprise system? If you had a startup would you use something like QuickBooks or some large Enterprise accounting system like SAP? Seems like you should figure out how to handle the accounting and other systems for your company first with something more appropriate.  I would recommend starting with a small project going agile that has enough importance so everyone takes the process seriously, but not so super mission critical and timely which will probably suffer by trying anything new.

Question 1: When should one choose an enterprise agile software
  development framework, and when should one just let their agile
  processes 'emerge'.

Start with a small group. In my experience, agile like anything else should start with something established when possible. Why reinvent the wheel especially if you don't know how to invent a wheel?  A lot of agile methodologies have much in common. There will be some aspects where many of your team members will look at certain parts as absolute deal killers (e.g. pair-programming). You'll probably be able to weed many of them out. Select a few for review depending on how much resources you have to this process. Sure it would be great if you could pick 10, but may only have enough time for 3.

Yes, there will be constraints, but you can iterate this process (Which is in the spirit of agile.) and make adjustments based on some data and experience and not just pure personal preference. There is the risk of someone being a zealot to a particular process and wants to adhere to it at the detriment of the project, but that can happen with anything. The key here is to not have too many moving parts with too many changes much like good experimental design. If you exclude some aspects too soon, you risk losing the effect of certain parts working together (Pair-programming gets a bad rap, but so does replacing the lone developer on a project.). However, if there are aspects of a particular methodology that is going to be a massive undertaking for your team (e.g. No one has a clue about unit testing.), you may need to give it some time before trying to do everything at once.

Question 2: If choosing an enterprise agile software development
  framework, how does one select the appropriate framework to use for
  their organisation?

This should be a lot easier once you have adopted and possibly adjusted for your needs at a small scale. It will be easier to put a list of needs. You can ask others about particular types with more specific questions because you will be able to convey your particular needs.


答:
Question 1: When should one choose an enterprise agile software development framework, and when should one just let their agile processes 'emerge'.

You should always let your processes emerge, agile or not. Enforcing a process is a great way for that process to mismatch what you need to do, causing inefficiency at the very least. (See Rands' for good links and expert advice about why this is so).

Choosing a framework then depends on whether you want to emerge from nothing (read: some initial state your team decides on) or from some framework that worked really well for other people. There's no right answer there. If your company works very similarly to other companies, with similar personalities and similar corporate structures, then starting with someone else's framework is great. If your company is really weird in what it does, how it works, and who works there then maybe starting with what you think is best may prove better than using something that doesn't fit your situation well.

The goal in this choice is to pick some starting point that you think is closest to where you'll evolve the process too, so that evolution is not very painful.

Title: when to use a scaled/enterprise agile software development framework and when to let agile processes 'emerge'?

Body:
There are quite a few enterprise agile software development frameworks available:

Scott Ambler: Disciplined Agile Delivery

Dean Leffingwell: Scaled Agile Framework

Alan Shalloway: Enterprise Agile Book

Craig Larman: Scaling Lean and Agile

Barry Boehm: Balancing Agility and Discipline

Brian Wernham: Agile Project Management for Government - DSDM, Scrum and others

I've also spoken with people that state that your enterprise agile processes should just 'emerge' and that you shouldn't need or use a framework because they constrain you.

Question 1: When should one choose an enterprise agile software development framework, and when should one just let their agile processes 'emerge'.

Question 2: If choosing an enterprise agile software development framework, how does one select the appropriate framework to use for their organisation?

Please provide evidence of your experience or research when answering questions rather than just presenting opinions.


答: For new question: you can read the default configuration inside an array/associative mapping, so you have key->default values. Then you read the user configuration, overwriting (in RAM) only the options you encounter (new options will be probably missing), so you have the default values, eventually customized. The files remain the same.</p>


答:
This is called Open Core, and can refer either to two different editions of the product (Free and Enterprise, for example, in this case the "open core" refers to the core functionality) or to a single product with a plugin architecture, where the plugin host and a set of basic plugins are Open Source and the vendor sells additional proprietary plugins (here "core" refers to the core of the library/app).

The other popular Open Source business model is the service model, where your product is Open Source and you sell additional services, maintenance contracts, training, installation and so on.

Title: Open-sourcing a proprietary library without certain features

Body:
I hope I'm in the right place to ask that.

I have a question regarding the practice of open-sourcing a proprietary library that we built and use at work. The licence will probably be MIT. I like the idea, but here comes the unusual part : I have been tasked to remove some of the most advanced features. Those will remain on our servers, available as a service. We will open-source the (JavaScript in case it is of interest) library, along with a minimal associated server code.

I am not asking a question about the technical problems (I imagine we will have to maintain and synchronize somehow different repositories, maybe with incompatible pull requests, but this question is for another day).

What I would like to know is:

How that would be perceived by the community at large ? Does it risk killing the eventual interest in this library?

I don't personally know of any library that works like that. I'm pretty sure it is possible however, but any evidence of such a library is welcome (successful if possible). That's also because I'd like to see how they present it.

More importantly, what could be the rationale for/against it? I'm not sure I understand the consequences of doing it so.

EDIT

After learning a thing or two from the answers and comments, I've collected here a few examples :

http://www.jfrog.com/home/v_artifactorypro_overview

http://www.easyrtc.com/pricing/

http://rapidminer.com/the-core-of-rapidminer-is-open-source/  (note the angry comments on this one - but we're doing the opposite, from proprietary to open-core)

As a developer, I would use the product we are going to release it in personal projects, so I think it's useful. But I have been working on it and I have an obvious bias.

Also, most feedback I've seen basically says "you can try, but it won't work". See also http://blogs.gartner.com/brian_prentice/2010/03/31/open-core-the-emperors-new-clothes/

If someone is able to find a successful product doing open-core, I'd be grateful.


答:
If there is a "larger system" responsible for providing the configuration, and your program is something like a "plugin" to that system, the problem has to be solved at the level of that "larger system". And the general solution still remains exactly as described in the other answers: the "larger system" needs to update the user-config file, adding missing keys around the time when the config is read.

If the "larger system" does not know how, since it does not know the entries your program needs, you need a mechanic where the "larger system" asks your plugin to check the available entries in the config, and if some entries are missing, your plugin has to provide them to the system (which afterwards writes the user config for you).

A "per-key cascade", where the user only specifies overrides in the user config, is theoretically possible (for example: that's the way the Firefox user config works), and to make this work also the larger system should provide the mechanic. On the other hand, this solution has the drawback that when you look into the user config file with a text editor, you don't see all the available options - and since you don't want to provide a UI for the config, this is not very user-friendly.


问:
Reporting defects in Agile

   I am working in sprint. At the end of sprint I need to send a defect report per sprint. Considering the below scenario please let me know your views.

Two teams(A & B) are working at different locations in Sprint-2 and I am a tester from Team-A and report the defects for the items developed by Team-A in each sprint

Question

1. I reported few defects in Sprint-2 for the functionality developed by Team-B in previous sprint. Do I have to consider this as observation or defect and report to Team-A?

2. I reported 5 defects of Sprint-2 for the functionality developed by team-A. All the defects are fixed and closed by me in the same sprint. Before the end of sprint I observed 2 defects got reopened for some reason. Now the defect count should be 5 or 7(5+2) should be considered for this sprint?

Thanks

Khan

答:
I reported few defects in Sprint-2 for the functionality developed by Team-B in previous sprint. Do I have to consider this as
  observation or defect and report to Team-A?

This depends on whether or not a user story in Sprint-2 passed or failed. If it is a failed user story in sprint-2, report the failure and mention you think the cause is in Team-B's code and let the developers figure it out and get this test to pass. Or if the Sprint-2 user story test passed but you noticed something else failed, create a new bug report item so it can be fixed in the next sprint.

I reported 5 defects of Sprint-2 for the functionality developed by team-A. All the defects are fixed and closed by me in the same
  sprint. Before the end of sprint I observed 2 defects got reopened for
  some reason. Now the defect count should be 5 or 7(5+2) should be
  considered for this sprint?

This is purely up to your team/company on their rules for counting defects and how they are interpreted. If someone wants a low defect count to curry favor or avoid punishment, some may want to have rules that encourage "when in doubt, enter failure) or if someone is gaming the system and wants to look good because they found/fixed a lot of failures, the rules may be in such a way "when in doubt, don't create additional failure counts".  When too severe of consequences or rewards are contingent on these failure counts, regardless of the direction, people are going to skew the values and game the system.

Lines of code for example may be a better measurement of size/complexity of an app if calculated when an entire project is completed and compared to itself (more control of coding style, languages and frameworks used, etc.) during different versions/releases without the concern of those writing the code who may attempt to influence the numbers one way or the other.

Title: Reporting defects in Agile


问:
Global variable in a Linux shared library
Suppose we have the following setup under Linux, .so library named "libcnt.so" and 3 user space apps: "app1", "app2", "app3". This library does 1 simple thing, it says to the app (app dynamically links the library at runtime) by how many apps it is already linked. Apps should have access to link counter. My knowledge in C and Linux is somewhat limited in this aspect, but as I understand this information should be stored in a global variable inside the shared object. Something like:

in libcnt.h
extern int cnt_loads;

in libcnt.c
int cnt_loads = 0; // where each linking increments this counter

or something...

So, my question is how it should be declared and/or defined inside .so library to guaranty that multiple apps from user space get the same instance of that variable counter?

答:
In general, mutable memory location will not be shared between applications unless explicitly asked for. Thus, when libcnt writes to cnt_loads, the page on which cnt_loads resides on will be duplicated. This behaviour is known as copy-on-write (COW). The same thing happens if you duplicated a process with fork(): the child process will not share writeable memory with the parent, if any write occurs to "forked" page, the page will be duplicated.

If you want to use shared memory for interprocess communication, you should use SystemV shared memory, POSIX shared memory or mmap instead. Note that these methods are somewhat persistent, i.e. you will need to remove the shared memory object after use.

You can approximate the behaviour you originally wanted using shared memory by defining __attribute__((constructor)) and __attribute__((destructor)) functions for your shared library. The constructor function is run every time the library is opened, so you can use it to initialize/open the shared memory and increment the the load count. If you also maintain a reference count (how many times the shared library is open in the system right now) with the destructor---in addition to the load count---, your can properly remove the shared memory once the reference count falls to 0.

Note that using shared memory for inter-process communication absolutely requires some form of mutual exclusion, for example a semaphore or mutex. Failing to synchronize properly will lead to race conditions (for example, what happens when two processes open your library at precisely same time?). You may avoid mutual exclusion if you can increment/decrement the counters in an atomic way. I recommend you to use OS provided inter-process semaphores instead of atomics, because atomic operations are tricky to utilize properly, and your problem is not performance critial at all (thus no need for lock-free operations).


问:
Programmer VS Commercial Systems (ERP)
My question here is relative to jobs for programmers.

Why does employer still contract programmers if today we have a lot of good commercial system avaliable on the market?

I want to be very clear at this point, this question is relative only to a system, more specially to ERP systems.  Maybe this question looks a little bit useless, but right now I'm working and this doubt arose to me and my boss.

I have a few answers to my own question, but I really would like to speculate this subject a bit more.

Also I know, every good company needs a customized system, but ... the question is here. :-)

Any answer will make me feel better. Thanks.

答:
Off the Shelf Vs. Custom

Having been partially involved on a complex ERP project I would say its simple:

Off the shelf

Prositive:

Maybe Cheaper Initially.

Well tested, stable.

Excellent documentation.

Negative:

Generic functionality.

Vendor Lock in.

Total Cost Of Ownership may be higher due to license.

Upgrades could break existing set up etc.

Title: Programmer VS Commercial Systems (ERP)


问:
What is the concept behind writing a cancel operation in c++?
I'm attempting to write a cancel operation for a software download application. This application will first transfer the software to the device and then install the software on it. (These are givens I'm not allowed to change).

What should the cancel operation do? When a user presses 'cancel', the application should stop transferring/installing the software immediately.

Question: Since I've never written a "cancel" function, I'm wondering what are the types of things to consider when writing the code, and what are the common bugs I should expect and how to deal with them?

Couldn't find anything in google so if you have some links that would be good reads I'd really appreciate it since I'm not looking for answers I'm just looking for guidelines/macro/concept help

答:
From a macro perspective, we have the "Installation Transaction". I refer to it as a transaction, since it is a set of ACID operations, kinda.

When the transaction is initiated, you start with the download, into a temporary directory probably. That's the first operation.

After that, you start the installation operation, and that happens mostly by copying files to the appropriate places. You need to modify some other files, probably, you should back those up in your temp directory, as well.

Each task you perform, you can create a memento for. If the transaction is cancelled, simply go over the memos and roll back everything to restore the user's computer to it's initial state.

The devil is in the details, as well as the language. I don't think I can go any deeper.


问:
Array of pointers in C++.
I am not understanding the output of this ,

```<code>#include <iostream>
using namespace std;

// pointers and arrays
char ch1 = 'a' ,  ch2= 'b';

char ch3[6] = {'c', 'd', 'e', 'f', 'g' , 'h'};

char *ptr[3];

int main ()
{
    ptr[0] = &ch1 ;

    ptr[2] = ch3;
    cout << &ch1 << endl;
}
</code>```

The out put is abcdefgh .

isn't &ch1 supposed to give the address of ch1  ? I cannot make sense why the output should be abcdefgh.

答:
The expression &ch1 does indeed produce the address of ch1. The reason you see abcdefgh printed is cout has a char* overload that prints the NUL-terminated string starting at the given address. In this case, it just so happens that ch2, ch3, and a NUL immediately follow ch1 in memory so you get abcdefgh printed.

As @rachetfreak mentions, this is undefined behavior. It is illegal to access more than one character through &ch1 because it is a pointer to a single character. On different platforms you may get different output, or a crash.

If you want to actually print the address of ch1 you can cast it to void* so that cout won't assume it's a pointer to a string:

```<code>cout << (void*)&ch1 << endl;
</code>```

Title: Array of pointers in C++.

Body:
The expression &ch1 does indeed produce the address of ch1. The reason you see abcdefgh printed is cout has a char* overload that prints the NUL-terminated string starting at the given address. In this case, it just so happens that ch2, ch3, and a NUL immediately follow ch1 in memory so you get abcdefgh printed.

As @rachetfreak mentions, this is undefined behavior. It is illegal to access more than one character through &ch1 because it is a pointer to a single character. On different platforms you may get different output, or a crash.

If you want to actually print the address of ch1 you can cast it to void* so that cout won't assume it's a pointer to a string:

cout << (void*)&ch1 << endl;


答: In the code shown, ch1 and ch2 are characters which are declared consecutively, and ch3 is actually an array of characters. The << operator interprets the address of ch1 as a C-style string, which is just a pointer to a null-terminated character array. So, the interesting thing to me is that storing the address of ch1 into ptr[0] results in a null character (the number 0) appearing in the byte after 'g`. As @AndrewMedico stated, this is compiler-specific behavior. I think the code was intended to show how C-strings are interpreted by IO streams, and how easy it is for bugs and security holes to creep in to otherwise good code.

Title: Array of pointers in C++.

Body:
I am not understanding the output of this ,

```<code>#include <iostream>
using namespace std;

// pointers and arrays
char ch1 = 'a' ,  ch2= 'b';

char ch3[6] = {'c', 'd', 'e', 'f', 'g' , 'h'};

char *ptr[3];

int main ()
{
    ptr[0] = &ch1 ;

    ptr[2] = ch3;
    cout << &ch1 << endl;
}
</code>```

The out put is abcdefgh .

isn't &ch1 supposed to give the address of ch1  ? I cannot make sense why the output should be abcdefgh.


问:
What methods exist for assessing an organisation's development capability?
I have a bit of a challenge at work at the moment.  Presently (and in fact, for some time now), we have been experiencing the following problems with some in-house maintained applications:

Defects (sometimes quite serious) being released into production;

The Customer (that is, the relevant business unit) perpetually changing their minds (or appearing to do so) about what issue to work on next;

A situation where everyone seems to be in a "fire-fighting" mode a lot of the time;

Development staff responding to operational requests from business users; ("operational" here means something that needs to be done in order to continue with business, or perhaps just to make a business user's life a little less painful, as opposed to fixing a bug in the application, or enhancing the application);

Now I'm sure this doesn't sound particularly new or surprising to most of the participants on this Q&A site and no prizes for identifying the "usual suspects" when it comes to root causes.  My challenge is that I have to persuade the higher-ups to do uncomfortable things in order to address all of this.

The folk I need to persuade come from a mixture of the following two cultures:

Accounting;

IT Infrastructure.

I have therefore opted for a strategy that draws from things with-which folk from such a culture would be most comfortable (at least, in my estimation), namely: numbers and tangibles.  Of course modern development practitioners know all too well that this sort of thing isn't easily solved using an analytical mindset (some would argue that that mindset is, in fact, entirely inappropriate).  Never-the-less, this is the dichotomy with-which I am faced, so that's the stake that I've put in the ground.

I would like to be able to do research and use the outputs to present findings in the form of metrics and measures.  I am finding it quite difficult, though, to find an agreed-upon methodology and set of templates for assessing an organisations development capability--the only thing that seems applicable is the Software Engineering Institute's Capability Maturity Model.  The latter, however, seems dated and even then rather vague.

So, the question is: How do I go about assessing our organisation's software engineering capability such that I can present the findings in a way that is concrete and references a generally accepted industry standard?

UPDATE:

Doing a little more research, I came across this little oasis - a CMMI FAQ worded in laymans terms--just the sort of useful resource that one needs in this area ... and free.

答:
Six Sigma Methodology has a number of tools that can be used to assess your processes and determine costs and losses to the business.

Just realize that the task you are taking on is potentially huge.  I was on a team where one of our major projects was to do just this for a major manufacturers development and testing unit.  We identified over 500 major processes, most of which were undocumented at the time of the assessment.  The assessment process took 2 years, and then another year to come up with a 10 year plan to document and improve these processes to the point where the it would reach that control level.  This was at a company that was already ISO 9001 certified.  I suspect it would be a bigger effort at a company that was not used to the processes that are required to provide the metrics you are requesting.

One of the major problems with something like this is that many developers are creative types and that mindset often does not handle being forced to conform to processes well.  Chances are if you have a Cowboy Coder culture now it is going to be a challenge to channel those developers into the type of structured environment that can produce repeatable and predictable success.

Another major problem is that despite having a huge potential ROI, development is often done on a tight budget with unrealistic deadlines.  Imagine if I came to you and told you I wanted you to design and build me a Rolls Royce quality car, but I am only willing to give you a budget of $20kUS and you only have 2 months to get it done... that sort of thing happens far too often in software development.  To be repeatable you have to be realistic.


答:
There is a middle ground between off-the-shelf and completely custom:  large enterprise packages are usually customizable, and getting them to actually work in a given situation can take a lot of work.

This means there's a lot of demand for people who can customize SAP and Peoplesoft systems, for example.

Title: Programmer VS Commercial Systems (ERP)

Body:
My question here is relative to jobs for programmers.

Why does employer still contract programmers if today we have a lot of good commercial system avaliable on the market?

I want to be very clear at this point, this question is relative only to a system, more specially to ERP systems.  Maybe this question looks a little bit useless, but right now I'm working and this doubt arose to me and my boss.

I have a few answers to my own question, but I really would like to speculate this subject a bit more.

Also I know, every good company needs a customized system, but ... the question is here. :-)

Any answer will make me feel better. Thanks.


答:
Like my answer, most things are vague on the subject. No one can determine for you that 10 bugs are worse than 1.

Not sure about any particular methodology, but you should start with your client first whether they are external or internal. What are the problems they see with the system. Sorry, but this post sounds a little too much on how to make the developer's life better. There needs to be some conversations that lead to a better understanding by both parties.

To show you what I mean, I'm going to play Devil's Advocate and take the perspective of your client and show you why these are not problems to them.

•Defects (sometimes quite serious) being released into production;

You "said" it would be ready in 2-weeks so that's what we planned for. If you needed more time, why didn't you say so?   Don't you have tests?

•The Customer (that is, the relevant business unit) perpetually
  changing their minds (or appearing to do so) about what issue to work
  on next;

That's just the way business is. We can't predict these things. Some of the requests come from external agencies (government tax law), vendors, clients or upper-management, so there is nothing we can do about it. The earth isn't going to stop spinning just because we're not ready for quarter end. Aren't you guys agile?

•A situation where everyone seems to be in a "fire-fighting" mode a
  lot of the time;

We're the same way; nothing you can do about it. Things are out of our control just like the previous problem.

•Development staff responding to operational requests from business
  users; ("operational" here means something that needs to be done in
  order to continue with business, or perhaps just to make a business
  user's life a little less painful, as opposed to fixing a bug in the
  application, or enhancing the application);

We would love to be able to do these things on our own because development takes too much time and complains about EVERY SINGLE REQUEST we make. Build something that gives us this capability, but you don't trust us to do it. You can't take control, but also not want to do it. Can't have it both ways.

Strive for Balance. It's difficult to weigh the risks and severity with bugs to taking some chances to get things released. The business groups may prefer you to take longer. When they ask how long, don't assume it means the absolute minimal amount of time possible.

Document the process and get their feedback on priority. You want 10 things done and we only have enough people to do 5, which 5 do you want? Most people just want to be kept in the loop. Making them continually ask and providing no feedback makes the time seem longer. This is why phone systems try to tell you how long you'll have to hold to manage your expectations. Making changes is no different. Let them know the change will affect delivery. Then they can decide if it is important enough.

As far as presenting this to management, make sure you know both sides of the story so you can present problems that everyone agrees need to be fixed. Hopefully, you'll have some agreed upon solutions. One communication problem I always see is someone from higher-up asks "Hey, can you see if we can add one more column to this report?" and by the time it gets to the developer the message is, "Mr. Big wants a new column in the report ASAP or all of our first-borns are toast!" Management is in a quandary about your complaints about your situation.

Title: What methods exist for assessing an organisation's development capability?

Body:
I have a bit of a challenge at work at the moment.  Presently (and in fact, for some time now), we have been experiencing the following problems with some in-house maintained applications:

Defects (sometimes quite serious) being released into production;

The Customer (that is, the relevant business unit) perpetually changing their minds (or appearing to do so) about what issue to work on next;

A situation where everyone seems to be in a "fire-fighting" mode a lot of the time;

Development staff responding to operational requests from business users; ("operational" here means something that needs to be done in order to continue with business, or perhaps just to make a business user's life a little less painful, as opposed to fixing a bug in the application, or enhancing the application);

Now I'm sure this doesn't sound particularly new or surprising to most of the participants on this Q&A site and no prizes for identifying the "usual suspects" when it comes to root causes.  My challenge is that I have to persuade the higher-ups to do uncomfortable things in order to address all of this.

The folk I need to persuade come from a mixture of the following two cultures:

Accounting;

IT Infrastructure.

I have therefore opted for a strategy that draws from things with-which folk from such a culture would be most comfortable (at least, in my estimation), namely: numbers and tangibles.  Of course modern development practitioners know all too well that this sort of thing isn't easily solved using an analytical mindset (some would argue that that mindset is, in fact, entirely inappropriate).  Never-the-less, this is the dichotomy with-which I am faced, so that's the stake that I've put in the ground.

I would like to be able to do research and use the outputs to present findings in the form of metrics and measures.  I am finding it quite difficult, though, to find an agreed-upon methodology and set of templates for assessing an organisations development capability--the only thing that seems applicable is the Software Engineering Institute's Capability Maturity Model.  The latter, however, seems dated and even then rather vague.

So, the question is: How do I go about assessing our organisation's software engineering capability such that I can present the findings in a way that is concrete and references a generally accepted industry standard?

UPDATE:

Doing a little more research, I came across this little oasis - a CMMI FAQ worded in laymans terms--just the sort of useful resource that one needs in this area ... and free.


问:
Circular dependency and object creation when attempting DDD
I have a domain where an Organization has People.

Organization Entity

```<code>public class Organization {
    private readonly List<Person> _people = new List<Person>();

    public Person CreatePerson(string name) {
        var person = new Person(organization, name);
        _people.Add(person);
        return person;
    }

    public IEnumerable<Person> People {
        get { return _people; }
    }
}
</code>```

Person Entity

```<code>public class Person
{
    public Person(Organization organization, string name) {
        if (organization == null) {
            throw new ArgumentNullException("organization");
        }

        Organization = organization;
        Name = name;
    }

    public Organization { get; private set; }
    public Name { get; private set; }
}
</code>```

The rule for this relationship is that a Person must belong to exactly one Organization.

The invariants I want to guarantee are:

A person must have an organization

this is enforced via the Person's constuctor

An organization must know of its people

this is why the Organization has a CreatePerson method

A person must belong to only one organization

this is why the organization's people list is not publicly mutable (ignoring the casting to List, maybe ToEnumerable can enforce that, not too concerned about it though)

What I want out of this is that if a person is created, that the organization knows about its creation.

However, the problem with the model currently is that you are able to create a person without ever adding it to the organizations collection.

Here's a failing unit-test to describe my problem

```<code>[Test]
public void AnOrganizationMustKnowOfItsPeople()
{
    var organization = new Organization();
    var person = new Person(organization, "Steve McQueen");

    CollectionAssert.Contains(organization.People, person);
}
</code>```

What is the most idiomatic way to enforce the invariants and the circular relationship?

答:
Make either the Person constructor "internal", or make the _people list accessible by an internal property, so the Person constructor can add this to _people right after creation.

Of course, this solution is not perfect since it will still allow other classes belonging to the same domain assembly wrong usage of your objects, but at least it will forbid any wrong usage from outside (which is typically sufficient for most real world cases).

If you are thinking of a more restricted model, where only the Person class can access a certain method of Organization, or vice versa: the C# designers did not implement such a thing, AFAIK intentionally. See, for example, this SO post and the topmost answer.


问:
Object Oriented Design of a Small Java Game

This is the problem i am dealing with. I have to make a simple game of NIM. I am learning java using a book so far i have only coded programs that deal with 2 classes. This program would have about 4 classes i guess including the main class. My problem is i am having a difficult time designing classes how they will interact with each other. I really want to think and use a object oriented approach. So the first thing i did was design the Pile CLASS as it seemed the easiest and made the most sense to me in terms of what methods go in it.

Here is what i have got down for the Pile Class so far.

```<code>package Nim;

import java.util.Random;

public class Pile {

    private int initialSize;

    public Pile(){

    }

    Random rand = new Random();

    public void setPile(){

        initialSize = (rand.nextInt(100-10)+10);
    }

    public void reducePile(int x){

        initialSize = initialSize - x;
    }

    public int getPile(){

        return initialSize;
    }

    public boolean hasStick(){

        if(initialSize>0){

            return true;
        }

        else
        {
            return false;
        }
    }

}
</code>```

Now i need help in designing the Player Class. By that i mean i am not asking for anyone to write code for me as that defeats the purpose of learning i was just wondering how would i design the player class and what would go on it. My guess is that the player class would contain method for choosing move for computer and also receiving the move human user makes.  Lastly i am guessing in the Game class i am guessing the turns would be handeled. I am really lost right now so i was wondering if someone can help me think through this problem it would be great. Starting with the player class would be appreciated.

I know there are some solutions for this problem online but i refuse to look at because i want to develop my own approach to such problems and i am  confident if i can get through this problem i can solve other problems.

I apologize if this question is a bit poor but in specific i need help in designing the Player class.

答:
A player:

Stupid, Smart, or Human

Player is an interface and Stupid, Smart, or Human are concrete classes OR

Player is an Abstract Class and Stupid, Smart, or Human are concrete classes

The interface or abstract class Player would contain everything a Player should do. The concretes would implement Player behavior and extend it specific to Stupid, Smart, or Human.

Human would need to prompt for input and Stupid, Smart, or Human activities per the problem description.

This is a possible beginning to organize the obvious hierarchy and to help you separate in your own mind what each part of Player will do.

An example of how the Java code could look when starting out using an interface and abstract method:

```<code>public interface Player
{
    abstract void grabMarbles();
    abstract int howManyMarbles();

}

public abstract class GamePlayer implements Player
{

     // Give definitions to all Player classes
     // Add more as abstract
}

public class Stupid extends GamePlayer { // What is Stupid gonna do? }

public class Smart extends GamePlayer { // What is Smart gonna do? }

public class Human extends GamePlayer { // What is Human gonna do? }
</code>```

Body:
A player:

Stupid, Smart, or Human

Player is an interface and Stupid, Smart, or Human are concrete classes OR

Player is an Abstract Class and Stupid, Smart, or Human are concrete classes

The interface or abstract class Player would contain everything a Player should do. The concretes would implement Player behavior and extend it specific to Stupid, Smart, or Human.

Human would need to prompt for input and Stupid, Smart, or Human activities per the problem description.

This is a possible beginning to organize the obvious hierarchy and to help you separate in your own mind what each part of Player will do.

An example of how the Java code could look when starting out using an interface and abstract method:

public interface Player
{
    abstract void grabMarbles();
    abstract int howManyMarbles();

}

public abstract class GamePlayer implements Player
{

     // Give definitions to all Player classes
     // Add more as abstract
}

public class Stupid extends GamePlayer { // What is Stupid gonna do? }

public class Smart extends GamePlayer { // What is Smart gonna do? }

public class Human extends GamePlayer { // What is Human gonna do? }


问:
Fixing a spelling mistake in a method name
One of the methods that I commonly use in our codebase is misspelled (and it predated me).

This really irritates me not simply because it is mispelled but more importantly it makes me ALWAYS get the name wrong the first time I type it (and then I have to remember "Oh, right, it should be mispelled to this...")

I'm making a few changes around the original method. Should I take the opportunity to just rename the freaking method?

答:
Renaming the method:

Do it through refactoring lest you have more work to do than you want

If your IDE supports auto-completion, use it when referencing that method

Those are two options you could go for.  I would prefer auto-completion (ex. Eclipse IDE) and not need to type out the method name.  Going for the rename; just make sure you find out what calls that method and change direct references in each place.  Refactoring will be your friend for that but be most careful when doing so.


答:
Should I take the opportunity to just rename the freaking method?

Absolutely.

That said, if your code has been released as an API, you should also generally leave the misspelled method and have it forward to the correctly named method (marking it Obsolete if your language supports such things).

Title: Fixing a spelling mistake in a method name

Body:
One of the methods that I commonly use in our codebase is misspelled (and it predated me).

This really irritates me not simply because it is mispelled but more importantly it makes me ALWAYS get the name wrong the first time I type it (and then I have to remember "Oh, right, it should be mispelled to this...")

I'm making a few changes around the original method. Should I take the opportunity to just rename the freaking method?


答:
Do you realize how expensive some of those higher-end commercial systems can cost to buy in the first place?  If companies are spending hundreds of thousands if not millions of dollars, don't you think they would want someone to help them get the most out of this big purchase?

Paying for the customization is why the contractors come in and don't forget that the big guys like SAP and Oracle may well have other companies that work as "System Integrators" that help companies implement the system correctly at a rather high cost.  Think of this as the difference between having a personal chef cook your meals and getting them in bulk from McDonald's.  That personal chef can put in so many touches that while yes it is expensive, some people tend to believe you pay for what you get and want lots of little things that they do pay but they may be happy in the end.

Title: Programmer VS Commercial Systems (ERP)


答:
There are cases where you should avoid doing such refactorings:

If the method is used in a public interface. A canonical example is the misspelling of referrer in HTTP referer, the wrong spelling being kept, because changing the spelling now would have too many repercussions.

If the code base is not covered by any tests. Any refactoring should be done on tested code in order to be able to do regression testing. Refactoring the code base which is not under tests is particularly risky. If you do have a lot of time, start by adding tests; if you work under time pressure, taking a risk of introducing subtle bugs is not the best thing to do if you want to ship on time.

If the method could be used in an unusual way, which makes its uses practically impossible to find (through Ctrl+F or by an automated refactoring tool). For example, in C#, a method can be called through Reflection, making Rename dialog of Visual Studio ineffective. In JavaScript, the function called inside eval() is difficult to find as well. In PHP, variable variables could cause issues.

If the size of the project is huge and the method could be used by other teams. This is similar to the first point, i.e. the interface you provide to other teams can be considered a public interface.

If you deal with a life-critical project. Chances are, the misspelling is not too important to justify a few months of paperwork in order to change the name of the method and ensure it won't cause any patient to receive ten times the authorized radiation or any shuttle to miscalculate its speed.

In any other situation, feel free to rename the method.


问:
Creating an Interface To a Language's Standard Library?
In the process of learning test-driven development, I've been introduced to dependency injection and the use of interfaces, and have started using these concepts in my own PHP code in order to make it more testable.

There have been times when I've needed to test code that was doing things like calling the PHP time() function. In order to make these tests predictable, it seemed logical to create an interface to the standard PHP functions I use so that I can mock them out in my tests.

Is this good software design? What are the pros and cons of doing this? I've found myself groaning at how quickly my PHP interface can stick its fingers into everything I do. Is there a better way to make code that relies on PHP-accessed state and functions more testable?

答:
You can either

create interfaces to system state methods like date or the content of session/cookie as you suggested or,

put these infos into business-method as additional parameters.

Example:

the invoice module can get the invoice date itself through an interface or,

the caller of the invoice module can provide the invoice date.

I prefer the 2nd method although this means that every time the module needs more state infos you have to change the method signature. On the other side in testing it is much easier to provide parameter than to mock methods.

I've found myself groaning at how quickly
  my PHP interface can stick its fingers into everything I do.

If your module needs too many parameters or too many interfaces, this might be an indicator that your module is doing too much and violates "separations of concerns."


问:
Breaking up classes and methods into smaller units
During code reviews a couple devs have recommended I break up my methods into smaller methods.

Their justification was (1) increased readability and (2) the back trace that comes back from production showing the method name is more specific to the line of code that failed. There may have also been some colorful words about functional programming.

Additionally I think I may have failed an interview a while back because I didn't give an acceptable answer about when to break things up.

My inclination is that when I see a bunch of methods in a class or across a bunch of files, it isn't clear to me how they flow together, and how many times each one gets called. I don't really have a good feel for the linearity of it as quickly just by eye-balling it.

The other thing is a lot of people seem to place a premium of organization over content (e.g. 'Look at how organized my sock drawer is!' Me: 'Overall, I think I can get to my socks faster if you count the time it took to organize them').

Our business requirements are not very stable. I'm afraid that if the classes/methods are very granular it will take longer to refactor to requirement changes. I'm not sure how much of a factor this should be.

Anyway, computer science is part art / part science, but I'm not sure how much this applies to this issue.

EDIT:

Check out: What is the ideal length of a method for you?

答: In any good language it's easy to compose two small functions into a bigger function, but there's no way to split a big function into two smaller functions. Likewise, it's easier to understand a big function in terms of what smaller functions do than it is to keep track of all the state in a big monolithic function. Human memory is at a premium; if we could reliably track large amounts of data we'd just code in assembly.</p>


问:
Should Maven generate JAXB java code or just use Java code from source control?
We're trying to plan how to mash together a build server for our shiny new Java backend.  We use a lot of JAXB XSD code generation and I was getting into a heated argument with whoever cared that the build server should:

Delete JAXB created structures that were checked in.

Generate the code from XSD's.

Use code generated from those XSD's.

Everyone else thought that it made more sense to just use the code they checked in (we check in the code generated from the XSD because Eclipse pretty much forces you to do this as far as I can tell).

My only stale argument is in my reading of the Joel test is that making the build in one step means generating from the source code and the source code is not the Java source, but the XSD's because if you're messing around with the generated code you're gonna get pinched eventually.

So, given that we all agree (you may not agree) we should probably be checking in our generate Java files, should we use them to generate our code or should we generate it using the XSD's?

答:
We have a similar situation here, but the schemas don't change that often so the Java doesn't need to be regenerated very often.

The way we deal with it is to create a new Maven project with just the schema files as source and generate Java code from that. We then deploy the generated Java as a jar to a local Nexus repository, but the only things that go into source control are the POM file, schema files, and any other necessary files (such as binding files). Any projects that require the generated Java get it as a dependency, from Nexus.

When the schema does change, the changes are checked in to source control, a new jar is generated and deployed to Nexus. Any projects that require the new version can simply update the dependencies to use the new version number.

The build server doesn't have to generate anything and the libraries are available for all teams to use, as dependencies in their own projects.

Our motivation to do it this way was that often many other teams need the generated Java for independent applications, and that once the schemas stabilize, they usually stay stable and don't need to be regenerated with every build/release.


答:
When I first started coding (and still a little now) I thought much the same way as you:

Why break things apart, when it's so much easier to find everything in this one place?

Until I started getting in bigger and bigger and bigger applications.  Now, writing my own content from scratch, I am seeing more and more opportunity to segment, decouple and reuse.

Mentally you have to wrap your head around the procedural (unless threadding) nature of how the computer will run your application.  It's going to init, fetch, cache and output in the way you told it to, even when using objects.  So if it helps, as it does for me, arrange your files visually in the way you expect them to flow logically.

For example I might have 3 files open at a time: Model, View, Template.

The tabs will be in my IDE in that order.  My brain reads that as "get data", "do something with data", "display data".

Then, within each of those files the classes, and their methods, are organized in a similar way.  While it's not specifically necessary to have __init__ or main() in a specific order in most languages it certainly makes sense to put that thing first when you are writing.  Now extrapolate that same thought process out against the entire project.

As you are writing and find yourself saying, "Hm, I need to do xzy here." check whether xyz was already written.  It if was pull that thing out of wherever it was, make it into a reusable function.  Now both methods do the exact same thing and you saved yourself time. Both now and in the future when you need to do xyz again.

Title: Breaking up classes and methods into smaller units

Body:
During code reviews a couple devs have recommended I break up my methods into smaller methods.

Their justification was (1) increased readability and (2) the back trace that comes back from production showing the method name is more specific to the line of code that failed. There may have also been some colorful words about functional programming.

Additionally I think I may have failed an interview a while back because I didn't give an acceptable answer about when to break things up.

My inclination is that when I see a bunch of methods in a class or across a bunch of files, it isn't clear to me how they flow together, and how many times each one gets called. I don't really have a good feel for the linearity of it as quickly just by eye-balling it.

The other thing is a lot of people seem to place a premium of organization over content (e.g. 'Look at how organized my sock drawer is!' Me: 'Overall, I think I can get to my socks faster if you count the time it took to organize them').

Our business requirements are not very stable. I'm afraid that if the classes/methods are very granular it will take longer to refactor to requirement changes. I'm not sure how much of a factor this should be.

Anyway, computer science is part art / part science, but I'm not sure how much this applies to this issue.

EDIT:

Check out: What is the ideal length of a method for you?


答:
You should abstract away calls to time() like you should abstract away calls to rand() and its ilk. The reason for doing that is because functions like that are forms of global, non-deterministic state. Global, non-deterministic state makes testing much more difficult because you cannot isolate your tests and test all conditions at once. Imagine if I had to wait until after noon to see if my code said "Good afternoon" instead of "Good morning" or "Good evening"!

If you see your interface starting to permeate your application, this may not be a bad thing. If anything, it is telling you how much you are using these built-in functions. You can depend on you to maintain your code and your interfaces within your code base, so you should not have as many worries about a shifting interface causing shotgun surgery. Abstracting away time() should be a pretty stable interface and probably should not see any changes for the most part.

The alternative to an interface is to simply inject the result of a call to time() rather than calling it in the method. So write getGreeting(time()); rather than writing getGreeting($timeUtil); (which in the method does $time = $timeUtil->getTime()). This adheres more closely to the Law of Demeter as you are not reaching for one thing through another, but it also means that the time you want must be the time at which the method is invoked.

An alternative alternative is to pass in a function reference rather than generating a separate interface. In PHP, you could do something like:

```<code>function getTime($timeFunc) {
    return call_user_func($timeFunc);
}

echo getTime('time')."\n"; # Call the built-in time function
echo getTime(function() { # Call a custom function
    return 1;
})."\n";
</code>```

This has less overhead than the full-blown interface while still allowing the function to be lazily called and allowing dependency injection.

Title: Creating an Interface To a Language's Standard Library?

Body:
In the process of learning test-driven development, I've been introduced to dependency injection and the use of interfaces, and have started using these concepts in my own PHP code in order to make it more testable.

There have been times when I've needed to test code that was doing things like calling the PHP time() function. In order to make these tests predictable, it seemed logical to create an interface to the standard PHP functions I use so that I can mock them out in my tests.

Is this good software design? What are the pros and cons of doing this? I've found myself groaning at how quickly my PHP interface can stick its fingers into everything I do. Is there a better way to make code that relies on PHP-accessed state and functions more testable?

Body:
You should abstract away calls to time() like you should abstract away calls to rand() and its ilk. The reason for doing that is because functions like that are forms of global, non-deterministic state. Global, non-deterministic state makes testing much more difficult because you cannot isolate your tests and test all conditions at once. Imagine if I had to wait until after noon to see if my code said "Good afternoon" instead of "Good morning" or "Good evening"!

If you see your interface starting to permeate your application, this may not be a bad thing. If anything, it is telling you how much you are using these built-in functions. You can depend on you to maintain your code and your interfaces within your code base, so you should not have as many worries about a shifting interface causing shotgun surgery. Abstracting away time() should be a pretty stable interface and probably should not see any changes for the most part.

The alternative to an interface is to simply inject the result of a call to time() rather than calling it in the method. So write getGreeting(time()); rather than writing getGreeting($timeUtil); (which in the method does $time = $timeUtil->getTime()). This adheres more closely to the Law of Demeter as you are not reaching for one thing through another, but it also means that the time you want must be the time at which the method is invoked.

An alternative alternative is to pass in a function reference rather than generating a separate interface. In PHP, you could do something like:

function getTime($timeFunc) {
    return call_user_func($timeFunc);
}

echo getTime('time')."\n"; # Call the built-in time function
echo getTime(function() { # Call a custom function
    return 1;
})."\n";

This has less overhead than the full-blown interface while still allowing the function to be lazily called and allowing dependency injection.


答:
Seems like this would be easier to do if there were a third entity: Membership. Your three rules are enforced:

Person handles - must have a Membership (which requires an Organization)

Organization - gets it's list of people from the membership, so it knows about them.

Membership - maintains unique Person and prevents same person from joining another Organization.

As part of the new membership process, you can pass the Person to the Organization to see if it meets any criteria and visa versa. You can enforce mutual agreement to membership or not.

I realize in the real world, Membership is an abstract concept, but exists in a way. It's typically a mutual agreement that binds these two entities together. Can an Organization make a Person a member without the Person's approval, cooperation, etc? Spam is a form of non-mutual membership into an organization's list. It's not practical in this case to enforce any rules in either direction: You're a member, pay your dues and I paid my dues so provide the services that comes with my membership.

Title: Circular dependency and object creation when attempting DDD

Body:
I have a domain where an Organization has People.

Organization Entity

```<code>public class Organization {
    private readonly List<Person> _people = new List<Person>();

    public Person CreatePerson(string name) {
        var person = new Person(organization, name);
        _people.Add(person);
        return person;
    }

    public IEnumerable<Person> People {
        get { return _people; }
    }
}
</code>```

Person Entity

```<code>public class Person
{
    public Person(Organization organization, string name) {
        if (organization == null) {
            throw new ArgumentNullException("organization");
        }

        Organization = organization;
        Name = name;
    }

    public Organization { get; private set; }
    public Name { get; private set; }
}
</code>```

The rule for this relationship is that a Person must belong to exactly one Organization.

The invariants I want to guarantee are:

A person must have an organization

this is enforced via the Person's constuctor

An organization must know of its people

this is why the Organization has a CreatePerson method

A person must belong to only one organization

this is why the organization's people list is not publicly mutable (ignoring the casting to List, maybe ToEnumerable can enforce that, not too concerned about it though)

What I want out of this is that if a person is created, that the organization knows about its creation.

However, the problem with the model currently is that you are able to create a person without ever adding it to the organizations collection.

Here's a failing unit-test to describe my problem

```<code>[Test]
public void AnOrganizationMustKnowOfItsPeople()
{
    var organization = new Organization();
    var person = new Person(organization, "Steve McQueen");

    CollectionAssert.Contains(organization.People, person);
}
</code>```

What is the most idiomatic way to enforce the invariants and the circular relationship?


问:
In C++ Good reasons for NOT using symmetrical memory management (i.e. new and delete)
I try to learn C++ and programming in general. Currently I am studying
open source with help of UML. Learning is my hobby and great one too.

My understanding of memory allocation in C++ is that it should be
symmetrical. A class is responsible for its resources. If memory is
allocated using new it should be returned using delete in the same
class. It is like in a library you, the class, are responsibility for
the books you have borrowed and you return them then you are done.

This, in my mind, makes sense. It makes memory management more
manageable so to speak.

So far so good. The problem is that this is not how it works in the
real world.

In Qt for instance, you create QtObjects with new and then hand over
the ownership of the object to Qt. In other words you create QtObjects
and Qt destroys them for you. Thus unsymmetrical memory management.
Obviously the people behind Qt must have a good reason for doing this.
It must be beneficial in some kind of way,

My questions is:

What is the problem with Bjarne Stroustrups idea about a symmetrical
memory management contained within a class?

What do you gain by splitting new and delete so you create an
object and destroy it in different classes like you do in Qt.

Is it common to split new and delete and why in such case, in other
projects not involving Qt?

Thanks for any help shedding light on this mystery!

答:
In modern C++ you typically want to use the Resource Acquisition Is Initialization (RAII) idiom. The idea is that any resource that you allocate should be wrapped into a class, and it should be deleted/closed/cleaned up by the class's destructor. A resource is anything that you need to de-allocate, close, or otherwise clean up when you are done with it. Most often a resource is memory, but it could be other things like files or network connections.

In some cases the wrapping class can be complex, representing some piece of program logic.  In most cases the wrapping class can be very simple, existing solely for the purpose of de-allocating the resource at the right time in the right way. An example of that is a smart pointer.

I haven't looked at Qt in a very long time. However, letting the user allocate an object, and pass a raw pointer into a library function that later de-allocates it is a rather outdated pattern. If the Qt function throws an exception before it has a chance to delete your object, you will inevitably have a memory leak. The object should be wrapped into a smart pointer, whose destructor will delete it automagically, including the case when an exception is thrown.


问:
How to name a method that both performs a task and returns a boolean as a status?
If there is a method

```<code>bool DoStuff() {
    try {
        // doing stuff...
        return true;
    }
    catch (SomeSpecificException ex) {
        return false;
    }
}
</code>```

should it rather be called IsStuffDone()?

Both names could be misinterpreted by the user:
If the name is DoStuff() why does it return a boolean?
If the name is IsStuffDone() it is not clear whether the method performs a task or only checks its result.

Is there a convention for this case? Or an alternative approach, as this one is considered flawed? For example in languages that have output parameters, like C#, a boolean status variable could be passed to the method as one and the method's return type would be void.

EDIT: In my particular problem exception handling cannot be directly delegated to the caller, because the method is a part of an interface implementation. Therefore, the caller can't be charged with dealing with all the exceptions of different implementations. It is not familiar with those exceptions. However, the caller can deal with a custom exception like StuffHasNotBeenDoneForSomeReasonException as was suggested in npinti's answer and comment.

答:
It really depends on the language that you're using. Like for some languages there are conventions and protocols that really don't exist in many languages or any at all.

For example, in the Objective-C language and the iOS/Mac OS X SDK method names usually go along the lines of:

```<code>- (returndatatype) viewDidLoad {
- (returndatatype) isVisible {
- (returndatatype) appendMessage:datatype variablename with:datatype variablename {
</code>```

As you can see, there's a method there called viewDidLoad. I prefer to use this type of naming whenever I make my own applications. This could be used to check if something was supposed to happen as you said. I believe that you're thinking too deeply about what it is you name your methods. Most methods return the status of what it is they do regardless, take example:

In PHP, mysql_connect() will return false if the connection fails. It doesn't say it will, but it does and the documentation says it does so it can't be misinterpreted to the programmer.

Body:
It really depends on the language that you're using. Like for some languages there are conventions and protocols that really don't exist in many languages or any at all.

For example, in the Objective-C language and the iOS/Mac OS X SDK method names usually go along the lines of:

- (returndatatype) viewDidLoad {
- (returndatatype) isVisible {
- (returndatatype) appendMessage:datatype variablename with:datatype variablename {

As you can see, there's a method there called viewDidLoad. I prefer to use this type of naming whenever I make my own applications. This could be used to check if something was supposed to happen as you said. I believe that you're thinking too deeply about what it is you name your methods. Most methods return the status of what it is they do regardless, take example:

In PHP, mysql_connect() will return false if the connection fails. It doesn't say it will, but it does and the documentation says it does so it can't be misinterpreted to the programmer.


答:
What is the problem with Bjarne Stroustrups idea about a symmetrical
  memory management contained within a class?

What do you gain by splitting new and delete so you create an object
  and destroy it in different classes like you do in Qt.

When you use symmetrical memory management you have to remember if you called "delete" operator on object or not. It increases complexity of programming (which can increase amount of memory leaks) but gives you control over variable's lifecycle. On the other hand if you use some kind of garbage collecting (i.e. like in Java - you can create object but don't handle its deletion) it decreases complexity but sometimes it can lead to problems with performance.

Is it common to split new and delete and why in such case, in other
  projects not involving Qt?

Depends on projects. It is question of performance needed for project.

The idea is choice between lower complexity (in case of GC) or higher performance (in case of manual memory management).

P.S. Idea behind garbage collection and passing pointer to some master object is all the same: encapsulation of memory management details. But GC is much better way (you don't have to control if you passed pointer to master object - it is hidden from user, so complexity is lower).

Title: In C++ Good reasons for NOT using symmetrical memory management (i.e. new and delete)

Body:
I try to learn C++ and programming in general. Currently I am studying
open source with help of UML. Learning is my hobby and great one too.

My understanding of memory allocation in C++ is that it should be
symmetrical. A class is responsible for its resources. If memory is
allocated using new it should be returned using delete in the same
class. It is like in a library you, the class, are responsibility for
the books you have borrowed and you return them then you are done.

This, in my mind, makes sense. It makes memory management more
manageable so to speak.

So far so good. The problem is that this is not how it works in the
real world.

In Qt for instance, you create QtObjects with new and then hand over
the ownership of the object to Qt. In other words you create QtObjects
and Qt destroys them for you. Thus unsymmetrical memory management.
Obviously the people behind Qt must have a good reason for doing this.
It must be beneficial in some kind of way,

My questions is:

What is the problem with Bjarne Stroustrups idea about a symmetrical
memory management contained within a class?

What do you gain by splitting new and delete so you create an
object and destroy it in different classes like you do in Qt.

Is it common to split new and delete and why in such case, in other
projects not involving Qt?

Thanks for any help shedding light on this mystery!


问:
Why do we need fork to create new process
In Unix whenever we want to create a new process, we fork the current process i.e. we create a new child process which is exactly the same as the parent process and then we do exec system call to replace the child process with a new process i.e. we replace all the data for the parent process eith that for the new process.
Why do we create a copy of the parent process in the first place and why don't we create a new process directly? I am new to Unix please explain in lay-man terms.</p>

答:
By separating fork() and execve() you let the parent control the environment that the child inherits.

The most common example is the shell redirecting IO, for example in the following command:

```<code>find . -name '*.java' | grep Frob
</code>```

In this example, the standard output of find is attached to the standard input of grep. These are two distinct file descriptors, which are in-memory objects.

In a world where fork and exec are separate, the shell contains code that re-assigns file descriptors in the forked child, before exec-ing the new program. In a world where fork and exec are separate, you would need some sort of mechanism to pass this information to the child program, perhaps via some "well-known" shared memory ID.

The former (fork/exec) model is a lot simpler to implement, and allows a default case where the parent and child share many of the same resources.

Body:
By separating fork() and execve() you let the parent control the environment that the child inherits.

The most common example is the shell redirecting IO, for example in the following command:

find . -name '*.java' | grep Frob

In this example, the standard output of find is attached to the standard input of grep. These are two distinct file descriptors, which are in-memory objects.

In a world where fork and exec are separate, the shell contains code that re-assigns file descriptors in the forked child, before exec-ing the new program. In a world where fork and exec are separate, you would need some sort of mechanism to pass this information to the child program, perhaps via some "well-known" shared memory ID.

The former (fork/exec) model is a lot simpler to implement, and allows a default case where the parent and child share many of the same resources.


问:
What kind of code would Kent Beck avoid unit testing?
I've been watching a few of the Is TDD Dead? talks on youtube, and one of the things that surprised me is Kent Beck seems to acknowledge that there are just some kinds of programs that aren't worth unit testing.  For example, right here DHH says that Kent Beck is

... very happy to say "Well, TDD doesn't fit in this case, I'm just going to bail"

It's frustrating to me that Kent Beck seems to acknowledge this, but nobody asks him to elaborate on it or give concrete examples.  I'd like to know the situations where Kent Beck thinks TDD is a bad fit.  Nobody can read his mind or speak for him, but I'm hoping he's been transparent enough through his books/tweets/whatever for someone to be able to answer.

I'm not necessarily going to take what he says as gospel, but it would be useful to know that the times I've tried TDD and it just felt impossible/useless are situations that he would have bailed on it himself.  Or, if it turned out he would have tested that code it'd suggest to me that I was approaching the process very wrong.  I also think it would be enlightening to understand why he would bail on such projects.

My opinion on why this is not a duplicate of "When is it appropriate to not unit test?"

After skimming those answers I'm not satisfied.  For example, look at UncleBob's answer.  He doesn't even acknowledge that such a situation exists.  I really think there's value in understanding Kent Beck's position, not just a general, "What's your opinion?" type of question.  After all, he's the father of TDD.

答:
In Extreme Programming Explained, Kent Beck doesn't say much about what specifically to not unit test, but he does give his rationale of what should be tested (p. 116-118 in my edition):

It is impossible to test absolutely everything, without the tests being as complicated and error-prone as the code. It is suicide to test nothing (in this sense of isolated, automatic tests). So, of all the things you can imagine testing, what should you test?

You should test things that might break. If code is so simple that it can't possibly break, and you measure that the code in question doesn't actually break in practice, then you shouldn't write a test for it...

Testing is a bet. The bet pays off when your expectations are violated [when a test that you expect to pass fails, or when a test that you expect to fail passes]... So, if you could, you would only write those tests that pay off. Since you can't know which tests would pay off (if you did, then you would already know and you wouldn't be learning anything), you write tests that might pay off. As you test, you reflect on which kinds of tests tend to pay off and which don't, and you write more of the ones that do pay off, and fewer of the ones that don't.

To summarize his position, he apparently would not recommend testing:

Trivially straightforward code

Anything that you can't test "without the tests being as complicated and error-prone as the code." (However, he would no doubt strongly recommend various agile, XP, and OO techniques to reduce the complexity so that it can be tested.  For example, he writes, "The more experience I get writing tests, the more I discover I can write tests for non-functional requirements - like performance or adherence of code to standards" (p. 45).)

Legacy code (code for which to tests exists) that doesn't need to be touched (see p. 126)

Anything for which testing doesn't "pay off"

One specific case: Kent Beck has said that he's not a fan of mocks, and he strongly emphasizes that unit tests need to be "independent" (in the sense that tests don't interact with each other; one failing test doesn't cause others to fail).  I infer from this that he would not test code that depends heavily on integration or on many objects collaborating together.  (Again, though, I'm sure he'd advocate agile, XP, and OO techniques to minimize this.)