答:
The thing about interruptions is that for given individuals or teams they tend to happen within a relatively small range of probabilities.  For example, you have around the same number of meetings every week, or around the same number of hours spent on urgent bug fixes every month, or the same amount of time spent answering questions for people who drop by your desk, especially when averaged over a long period of time.

A lot of modern scheduling techniques take that into account.  Scrum factors it into velocity.  Evidence based scheduling also uses a velocity with a confidence interval for any given estimate.  Pomodoro takes interruptions into account when you decide how many "pomodoros" you can count on completing in any given week.  All of these depend on tracking historical measurements of your interruptions and factoring them into your estimates somehow.  I recommend you take a look at all of them and devise a technique that will work for your team.


问:
Designing Subclasses for an abstract base class in C++
I'm doing a small assignment in C++ where I have to use concepts like virtual functions and inheritance in a domain of my choice. I'm implementing the prototype for a package manager in Linux.

I have the base class Package, this has attributes like package_id, name, version, dependencies etc.
There are two types of packages MetaPackages and ConcretePackages which differ in the way they must be installed and removed.

I am thinking of declaring the methods install and remove in Package as virtual.
While storing these packages in a datafile can I somehow know if the stored package is Meta or Concrete.

I'm not sure as to how I should best design this. Can anybody point me to a resource so that I can better learn this stuff.

We have Grady Booch in our curriculum and honestly it's a pain to read much less comprehend.

答:
I am thinking of declaring the methods install and remove in Package as virtual.

Sounds like a good idea.

While storing these packages in a datafile can I somehow know if the stored package is Meta or Concrete.

Why do you need to know it? The point of polymorphism (and probably of this specific exercise) is that the user of the object doesn't need to know its concrete type, just call its methods. If said methods adhere to the "contract" defined by the base interface, their implementation details aren't important for the caller.

You should implement the install and remove methods in each concrete subclass according to the specifities of meta and concrete packages. Then the installer of the packages needs only to iterate through the collection of packages and call the respective method on each.

ContentLicense: CC BY-SA 3.0


问:
Would a NoSQL DB be more efficient than a relational DB for storing JSON objects?
I am using a library that returns a JSON object (as a string, but I think that's standard), and I would like to store the contents of this object into a local database.

I'm fairly fresh-faced in terms of interfacing with DBs, but I can find my way around.  I was using a MySQL database to store the data, but this involved using methods to extract the fields of the raw object, and slicing and dicing.

I'm wondering if it would be more efficient to use a NoSQL solution to store the data, as it's already in the right form.

答:
well that really depend on your need. for small data you can live with the RDBMS, but for a real system n big data you need have object database. your question can be narrowed down to ODBMS from no-sql.

Cache DB from intersystems is a good candidate for solution. cache is object database with no strictness on the schema. here your objects can be mapped to db objects. so you have 1-to-1 mapping and therefore no translation (slicing) is required.

as you have mentioned Json you can also use total free solution from intersystems GloblasDB which have its bindings to Java.

as mentioned earlier this totally depends on your need what system you are building.


问:
Why are Coldfusion CFM and CFC files not in clear text?
I am learning Coldfusion, however when I try to open CFM and CFC files they appear to be unreadable.

Some of the data look like java code, but other data looks like this: "¸ aº*3¶ H**´ !½ zY¼S¶".

I thought that this might be compiled with Java, but http://java.decompiler.free.fr does not seem to be able to decompile it.

答: It sounds like you may have some encrypted files you're looking at.  Most of us CF developers don't really encrypt our code, even though it's possible.  You might be able to decrypt it but it could be a license violation against whoever wrote/licensed the code.  Do a Google search for 'decrypt coldfusion code' and you might find something that will help you.</p>


问:
If someone says Android message API what it related to? What classes it consists in?
Recently started Android programming. Developed 3 apps using threads, UI API, telephony API.
My quesion is if someone says Android message API what it related to? What classes it consists in?

"Actually I have seen this in an Android job post"

Thanks

答:
They are referring to android.os.Message, android.os.Handler, android.os.MessageQueue, android.os.Messenger; all of which are documented in the API. There may be a few utility classes I've not mentioned, but those are the ones I make use of.

If you have seen this mentioned in a job specification, they are expecting you to have knowledge of the messaging API and how to make effective use of it, which is a fair requirement since you would be writing code that runs on a mobile platform.


问:
Definition of a Software bug. Blizzard Entertainment insists that my "bug" is not a bug at all. Are they right?
According to Wikipepdia,

A software bug is the common term used to describe an error, flaw, mistake, failure, or fault in a computer program or system that
  produces an incorrect or unexpected result, or causes it to behave in
  unintended ways.

Recently I've found a "bug" in StarCraft 2 which produces an unexpected result:
http://eu.battle.net/sc2/en/forum/topic/2868627470

The problem is that if I keep StarCraft 2 minimized for a long time, the game does not disconnect or generate any form of timeout. It does disconnects however after first battle and sometimes also loses game data (match statistics).

Unfortunatly, according to Blizzard:

The game is not designed to be kept minimized for such a long period of time. (Blizzard) cannot consider such behaviour as erroneous as
  StarCraft II is not meant to be minimized for hours.

So, is my "bug" really a bug?

答:
I think this is a case of software not being used as defined by the specs. They say

The game is not designed to be kept minimized for such a long period of time.

Which to means that they have some definition somewhere of what counts as a "long period of time". If you minimize the program for more than a "long period of time", it goes beyond their specifications and beyond what they tested for (assuming they formally tesed this) and they do not guarantee what will happen. Of course, it would have been nice if the manual somewhere said "we have only tested this program to be minimized for periods of time not exceeding 10 minutes. Minimize for longer than this at your own risk!".

So no, I don't think this is really a bug. In my office, this would be called a "user training issue" (which I'd say is a form of a communication problem, because in this  case because no maximum period for minimize-time was communicated to the user) since the user is not using the program properly. Not that it helps much for Blizzard, unless they put it in the manual...


答:
To a software team, a bug is a software problem that needs to be fixed.  Not all software problems need to be fixed.

Updating software is expensive.  Blizzard is telling you that your problem is an edge case.  In other words, the edge case problem you discovered is not necessarily something they tested for or otherwise care to account for.  Fixing the problem will help you, but in all likelihood it will not help many others.  Yet, the cost to fix the bug could be high.  Instead, they can invest their resources into new features or even finish Diablo III.

Title: Definition of a Software bug. Blizzard Entertainment insists that my "bug" is not a bug at all. Are they right?

Body:
According to Wikipepdia,

A software bug is the common term used to describe an error, flaw, mistake, failure, or fault in a computer program or system that
  produces an incorrect or unexpected result, or causes it to behave in
  unintended ways.

Recently I've found a "bug" in StarCraft 2 which produces an unexpected result:
http://eu.battle.net/sc2/en/forum/topic/2868627470

The problem is that if I keep StarCraft 2 minimized for a long time, the game does not disconnect or generate any form of timeout. It does disconnects however after first battle and sometimes also loses game data (match statistics).

Unfortunatly, according to Blizzard:

The game is not designed to be kept minimized for such a long period of time. (Blizzard) cannot consider such behaviour as erroneous as
  StarCraft II is not meant to be minimized for hours.

So, is my "bug" really a bug?


问:
How much design to do first?
I have never worked with a professional software development team. As such, analyzing and thinking about each and every aspect of my software does not come naturally to me.

Whenever I strike an idea that excites me I just start a new project in my IDE (after finishing the previous one) and I start designing the interface—which means to me as placing menubars, buttons and other components at their appropriate places—and start coding for them. Recently I started a chess game in Java and I followed that pattern: first programmed the black-white grid, then registered a mouse listener etc. without thinking about warriors/objects of chess game.

One thing that annoys me is that I have never been able to completely use object-oriented features of object-oriented programming, though I understand it. I have the habit of taking on things when it comes. This could be the reason of the poor design I end up with.

I complete all the projects that I start, but since they are personal projects I have never felt the need to refactor the code. But I know that if I am asked to modify any function of my program I could be in a mess because they are not properly designed (though they work as asked).

What is the correct/better way to start to design software that is somewhat complicated like a chess game?

答:
Whenever I strike an idea that excites me I just start a new project in my IDE .That.. and I start designing the interface—which means to me as placing menubars ...  Recently I started a chess game in Java and I followed that pattern: first programmed the black-white grid, then registered a mouse listener etc. without thinking about warriors/objects of chess game.

Nothing wrong with that, we have to start somewhere.

One thing that annoys me is that I have never been able to completely use object-oriented features of object-oriented programming, though I understand it. I have the habit of taking on things when it comes. This could be the reason of the poor design I end up with.

I think your poor designs are a result of a lack of experience and knowledge.  You know that your designs are not good because they are hard to modify, but you don't know how to make them better.  The fun thing about software is that it is infinitely changeable; you can keep adding code bit by bit, and improving the design as you go.  But you still have to know what changes would improve the design.  I recommend that you read Martin Fowler's Refactoring, and Design Patterns by Gemma et. al.  However, keep in mind that the idea is not to choose design patterns before coding, but to recognize the applicable design patterns as you code.

Title: How much design to do first?


答:
If I was a development team lead on that project I'd call it a bug but a minor one since it's well outside of the normal operating expectations of the software. If it was going to be worked on at all I'd probably assign it to a junior programmer or a new hire more as a learning exercise for them than anything else.

It's a good idea to have these minor bugs tracked since they can indicate potentially more far reaching problems. For example, the data save bug you encountered. It seems minor due to how it happened but there might be other cases where data is being lost. By using a bug reporting system you can find all of the cases where a similar problem came up and see if there's a common element. In a complex system, having this kind of thing documented can help you find more serious and subtle bugs.


答:
A bug could reasonably be defined as "any deviation from the intended behaviour of the software".

Clearly they (and it's their software so they get to determine how it should behave) never intended the software to handle this scenario so it doesn't meet this definition of a bug.

However what I would say is, at the very least, suboptimal is the way it's handling this condition.

Garbage in, garbage out (that is the user does something stupid or bad or unexpected and something bad happens as a result) has been considered a poor standard of behaviour. I'd say at the very least it should be more elegant in the way it handles this condition.

So not strictly a bug, but a poor handling of an edge case.

That said if I were them it's not something I'd likely consider worth fixing (to expensive for too little benefit), though I might mention it to the team for future reference that it was something they might have handled better.


答:
Not a bug. A bug is behaviour that does not comply with the specification. If the spec says that the use case is not supported behaviour then any behaviour - perceived as valid or not - in that use case is 'by design'.

In this scenario, the game working at all could be perceived as undefined behaviour.


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答: I prefer two monitors,Quiet office, good machine. </p>

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: RedsDevils


问:
Is it poor technique to have functions within a class depend on one another in a "cascade" type fashion?
I am fairly new to PHP and OOP.  Having said that, I wanted to know how independent functions should be within a class.  I know that each function should be responsible for doing just one thing.  However, as you can see in my class below, I occasionally find myself creating functions that build upon one another in a "cascade" type fashion.

Is this good practice?  Is there a different way I should be structuring this class/these types of functions?  I want to make sure I am developing good habits.

Thanks in advance for your help.

```<code>class PubMedQuery {

private $query;
private $searchParameters;
private $searchURL;
private $fetchParameters;
private $fetchURL;
private $searchResults;
private $fetchResults;
private $matches;
private $matchRegex;
private $emailAddresses;

public function __construct($query) {
    $this->query = $query;
}

public function setSearchParameters() {
    $this->searchParameters = array(
        'db'         => 'pubmed',
        'term'       => $this->query,
        'retmode'    => 'xml',
        'retstart'   => '0',
        'retmax'     => '1000',
        'usehistory' => 'y'
    );
}

public function getSearchParameters() {
    return $this->searchParameters;
}

public function setFetchParameters() {
    $this->fetchParameters = array(
        'db'        => 'pubmed',
        'retmax'    => '1000',
        'query_key' => (string) $this->searchResults->QueryKey,
        'WebEnv'    => (string) $this->searchResults->WebEnv
    );
}

public function getFetchParameters() {
    return $this->fetchParameters;
}

public function setSearchURL() {
    $this->baseSearchURL = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils /esearch.fcgi?';
    $this->searchURL = $this->baseSearchURL . http_build_query($this->getSearchParameters());
}

public function getSearchURL() {
    return $this->searchURL;
}

public function setFetchURL() {
    $this->baseFetchURL = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?';
    $this->fetchURL = $this->baseFetchURL . http_build_query($this->getFetchParameters());
}

public function getFetchURL() {
    return $this->fetchURL;
}

public function setSearchResults() {
    $this->setSearchParameters();
    $this->setSearchURL();
    $this->searchResults = simplexml_load_file($this->getSearchURL());
}

public function getSearchResults() {
    $this->setFetchParameters();
    $this->setFetchURL();
    return file_get_contents($this->getFetchURL());
}

public function setEmailAddresses() {
    $this->matches = array();
    $this->matchRegex = '/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}/';
    preg_match_all($this->matchRegex, $this->getSearchResults(), $this->matches);
    $this->emailAddresses = array_unique(array_values($this->matches[0]));
}

public function getEmailAddresses() {
    $this->setSearchResults();
    $this->getSearchResults();
    $this->setEmailAddresses();
    return $this->emailAddresses;
}
}

//Example using search term "psoriasis"
$query  = new PubMedQuery('psoriasis');
echo implode('<br />', $query->getEmailAddresses());
</code>```

答:
What you have looks fine.

You have several actions setEmailAddresses, getEmailAddresses each of which comprise of a series of steps. Some of these steps are common across multiple actions so it makes perfect sense to factor them out into their own methods.

The remaining part of the action could be coded in the top level method, but having it in it's own "sub method" is not a problem - in fact it could be said it's better practice as you are keeping each method responsible for just one thing.


问:
Should I reuse variables?
Should I reuse variables?

I know that many best practices say you should not do it, however, later, when different developer is debugging the code and have 3 variables that look alike and the only difference is that they are created in different places in the code, he might be confused. Unit-testing is a great example of this.

However, I do know that best practices are most of the time against it.
For example they say not to "override" method parameters.

Best practices are even are against nulling the previous variables (in Java there is Sonar that gives a warning when you assign null to variable, that you don't need to do it to call the garbage collector since Java 6. You can't always control which warnings are turned off; most of the time the default is on.)

答:
I would say NO.

Think about this scenario: your program crashed and you need to work out what happened by inspecting a core dump... can you see the difference? ;-)

Title: Should I reuse variables?


问:
How can I justify software testing to management?
I work for a small company (less than 200 employees) whose software group only makes up a small part of our staff (4 employees, occasionally with a few contractors).  The four of us have been making strides in transitioning to better practices, and one of the next logical steps is to improve our testing.

As anyone who has done any meaningful tests knows, testing takes a lot of time - and at my company, it takes too much time to justify to management, so we generally do what little we do on the sly.  I don't think this is serving us well, as we keep coming up against otherwise avoidable problems when we ship under-tested software.

I would like to be able to come to management with a justification for hiring a dedicated software test engineer (someone who can both write automated tests and perform manual ones).  Are there any good published studies that show the benefits of adding such a position to a small company?  Where can I find information about costs associated with the position?  I plan on doing a little number crunching on our own history, but having some external sources to point to would help bolster my case.

答:
I believe that you should convince your management not by using numbers, but by explaining the rational.

Joel Spolsky makes some very smart points on the benefits of hiring testers in his article Top Five (Wrong) Reasons You Don't Have Testers, that may help convincing management.

Also here:

If your team doesn't have dedicated testers, at least one for every
  two or three programmers, you are either shipping buggy products, or
  you're wasting money by having $100/hour programmers do work that can
  be done by $30/hour testers. Skimping on testers is such an outrageous
  false economy that I'm simply blown away that more people don't
  recognize it.

Some more pearls of wisdom here:

There is no better way to improve a programmer’s morale, happiness, and subjective sense of well-being than to have dedicated testers who get frequent releases from the developers, try them out, and give negative and positive feedback.
  Otherwise it’s depressing to be a programmer. Here I am, typing away, writing all this awesome code, and nobody cares. Boo hoo.


答:
Don't waste time on number crunching.  It's not compelling.  Everyone disputes the details.

Instead, focus on specific risk scenarios.

Poor (or no) testing == failure in production == loss of revenue (or worse).  Follow this line of reasoning with specific losses that can accrue from software failures.

Be detailed and focused so that the logic of "loss comes from bad software comes from bad testing" is inescapable.

What happens is -- of course -- focus on the specific risk scenarios.  But that's better than no focus at all.

Very, very specific stories are easier to use than general studies and summarized numbers.  It's even better when you can tie historical events, specific customers or products, or other factual details to your risk scenario.

"Remember when we spent 18 hours trying to fix the [X] product software?  How much revenue did we lose from cancelled orders?  And help desk calls?"

Title: How can I justify software testing to management?

Body:
I work for a small company (less than 200 employees) whose software group only makes up a small part of our staff (4 employees, occasionally with a few contractors).  The four of us have been making strides in transitioning to better practices, and one of the next logical steps is to improve our testing.

As anyone who has done any meaningful tests knows, testing takes a lot of time - and at my company, it takes too much time to justify to management, so we generally do what little we do on the sly.  I don't think this is serving us well, as we keep coming up against otherwise avoidable problems when we ship under-tested software.

I would like to be able to come to management with a justification for hiring a dedicated software test engineer (someone who can both write automated tests and perform manual ones).  Are there any good published studies that show the benefits of adding such a position to a small company?  Where can I find information about costs associated with the position?  I plan on doing a little number crunching on our own history, but having some external sources to point to would help bolster my case.


问:
How can we plan projects realistically while accounting for support issues?
We're having a problem at work: we're trying to schedule work so that we can assess time scales and get deadline dates.

The problem is that it's difficult to plan for a project without knowing everything that's going to happen.

For instance, right now we've planned all our projects through the start of December, however in that time we will have various in house and external meetings, teleconferences and extra work. It's all well and good to say that a project will take three weeks, but if there is a week's worth of interruption in that time then the date of completion will be pushed back a week.

The problem is 3 fold:

When we schedule projects the time scales are taken literally. If we estimate three weeks, the deadline is set for three week's time, the client is told, and there is no room for extension.

Interim work and such means that we lose productive time working on the project.

Sometimes clients don't have the time that we need to take to do the work, so they'll sometimes come to us and say they need a project done by the end of the month even when we think that the work will take two months - not to mention we already have work to be doing.

We have a Gantt chart which we are trying to fill in with all the projects we have and we fill in timesheets, but they're not compared to the Gantt chart at all. This makes it difficult to say "Well, we scheduled 3 weeks for this project, but we've lost a week here so the deadline has to move back a week."

It's also not professional to keep missing deadlines we've communicated to the client.

How do other people deal with this type of situation? How do you manage the planning of projects? How much "extra" time do you schedule into a project to account for non-project work that occurs during a project? How do you deal with support issues and bugs and stuff? Things you can't account for during planning?

UPDATE

Lots of good answers thank you.

答:
Seems like there is a lot of hidden effort drawn from your project teams through which you are losing focus and velocity. It might be benneficial to actually separate the task for dealing with

..support issues and bugs and stuff?

to a specific group of people so that the other team members can focus on the new development tasks. Through this their overall production might drop a bit but quality will improve because there is less distraction. This in return will reduce the number of bugs, hence a-hoc work that makes it's way into your projects.

As for the planning part, I completely agree with Thomas Owens answer.


答:
This kind of reminds me of the cat in the microwave, specifically the case of Mrs. Smith in 1983.

The point is, you expect the product to work in such a way. Mostly because a number of similar products work like that, i.e. if you minimize them for hours and then open them up, they work (although the opposite is not as uncommon as you might think).

Mrs. Smith knew from her experience, that drying her cats in the oven wouldn't harm them (presuming some caution of course). More precisely from experience she had with all the ovens she tried. She then assumed it would be the same for the microwave oven she was given. This assumption was wrong. Microwaves are not designed to dry cats. Neither are conventional ovens. They just happen to not kill the cat in the process as a side effect of the physical processes they employ to generate heat.

Now as a producer of microwaves, you could place a heating coil and number of sensors into the microwave. The latter would determine, whether the current content is a cat and use the coil instead of microwaves.

In the same manner, that one could produce a microwave suitable to dry cats, Blizzard could create a version of SC2 that is suitable to stay in minimized state for extended periods of time.

Personally, I'd be willing to pay more money for a cat-drying-enabled microwave just for the fun of it (assuming there is a big cat-drying-suitability-logo in front I can proudly point at). But I wouldn't care for a game that can stay minimized for hours.

SC2 was designed to meet certain requirements. Your expectation is not part of those. You are free to measure SC2 in respect to your expectations. But whether or not Blizzard includes all of them in the scope of their requirements is ultimately their choice.

All you could really argue about is, that it's a design failure. Common sense dictates that unless a substantial fraction of the users are confused by the design or unhappy with it, it's good enough. I am sure if enough users state that they share your expectation, Blizzard would yield and include it in the design. This would render your problem an actual bug and Blizzard would fix it.


问:
How can I get my startup working with Agile development?
In our startup, we've worked until now using the traditional waterfall model, but we want to try our next project using Agile Methodology.

We are pretty much alien to the entire Agile process, so considering this, what is the best way to understand Agile (resources and a practical handbook can be of help), decide on a specific methodology (Scrum, etc), and start it in our next project?

答:
You have said that you want to adopt Agile because it decreases the time-to-market and increases the productivity of your developers, so I'd like to focus on those particular aspects.

Time to market

In traditional Waterfall products, stakeholders only get one chance to sign up for requirements. In Agile, you can produce a much smaller vision and then add additional requirements afterwards. That's your best way to get to market quickly. To do this, you'll need to ensure that

your codebase remains easy to change

you can deploy your code easily, repeatably and reliably

your stakeholders are prepared to engage and talk about what they truly need, instead of what they want.

So you'll need to do a bit of educating your stakeholders. Read around subjects like Story Mapping and Feature Injection, and talk to them about what they'd like to get from Agile. Bear in mind that the certainty they used to get with Waterfall's analysis won't be there (if it ever was!), but they'll get more chance to change their mind and shape the direction of the product, instead.

For the practices which will help you keep your codebase easy to change, I suggest Kent Beck's "XP Explained". Also look extensively at TDD, BDD and Continuous Integration and Deployment.

Having showcases to your stakeholders within an environment that's as close to production as possible really helps. I recommend doing this every two weeks. If you find it's very easy to deploy and your stakeholders want more engagement, you can shorten iterations to one week. If you find it's very hard to deploy, make sure that you can get feedback in some form every two weeks - even if it has to be on a developer machine - then release every month or two if you can. While you're doing this, work out what's making deployment so hard and start automating that. If there are political bodies stopping you from deploying regularly, work out what you might be able to show them to shortcut their gatekeeping processes, and see if you can move them into a role where they educate the team and continually check instead of having one big check at the end.

Increased Productivity

Agile isn't really a way of getting developers to do more work in less time. Instead, developers have less rework, less wasted effort in terms of work done "just in case", and a more collaborative approach that lets them learn from each other and from the rest of the team.

Having the team co-located is the single biggest factor in enabling this to happen, IMO. Developers have to be able to collaborate with testers to find bugs early, while they still remember how to fix them; with analysts so that they can question any part of the requirements they don't understand; and with each other so that they can share new ideas, designs, and things they learn. Most of the XP practices, especially pair-programming, collaborative code ownership, and TDD, will reduce bugs and therefore rework too.

A warning about Scrum

This applies particularly if you're using estimation and velocity measurements.

A lot of what you're about to do will be new to you, and it'll be hard to work out to start with just how long things are going to take. If you start using estimates and velocity measurements to track the work, the estimates might be quite a way out to start with. This is normal.

Scrum also doesn't mandate any technical practices which will help keep code easy to change. For the things you're after - time to market and productivity - those technical practices will be essential. For that reason, please don't just put Scrum in place - also start adopting excellence within your development work, and flex your process around that. You'll get a lot of benefits just from having higher quality, collaborative code and a high-learning environment.

Coaching and training

It's highly likely that you'll run into problems. I've only met one company who self-coached from a couple of CSM classes, and they had an amazing culture. Don't be afraid to ask for help, and read extensively. Scrum isn't the only methodology out there and you may get ideas from other sources too.

OwnerDisplayName: andy


答:
If you don't test enough, you lose profit to pay to fix buggy software in the field.
If you test a lot and deliver late, you lose revenues because software was delivered late.

From a business leader's point of view, the former is usually preferable because delivered software is actually getting used, was probably paid for, and it is therefore easier to justify bug-fixing expenses after it was deployed and paid for.

If you want better testing, you need to show how testing will help the business leader get the software to market faster, within the same budget. In a large-ish software project, time-to market is enhanced when test coverage is good at the lowest layers of the system (e.g. OS, data layer) because that means that the folks developing on top of that don't have to fix their bugs and the lower layer bugs. It also helps to ensure good testing of success paths of key use cases.

You may want to consider outsourcing some testing to a shop in India or Vietnam. They do good work, and their loaded labour rates are much less than those in N. America. And they'll test while you sleep.


问:
How to create scalable & side-effect free integration tests?
In my current project, I am having a hard time coming up with a good solution to create scalable integration tests that have no side effects. A little clarification on the side effect free property: it is mostly about the database; there shouldn't be any changes in the database after the tests are completed (state should be preserved). Maybe scalability and state preservation don't come together, but I really want to push for a better solution.

Here is a typical integration test (these tests touch the database layer):

```<code>public class OrderTests {

    List<Order> ordersToDelete = new ArrayList<Order>();

    public testOrderCreation() {
        Order order = new Order();
        assertTrue(order.save());
        orderToDelete.add(order);
    }

    public testOrderComparison() {
        Order order = new Order();
        Order order2 = new Order();
        assertFalse(order.isEqual(order2);
        orderToDelete.add(order);
        orderToDelete.add(order2);
    }
    // More tests

    public teardown() {
         for(Order order : ordersToDelete)
             order.delete();
    }
}
</code>```

As one might imagine, this approach yields tests that are extremely slow. And, when applied to the whole integration tests, it takes around 5 seconds to test only a small portion of the system. I can imagine this number going up when the coverage is increased.

What would be another approach for writing such tests? One alternative I can think of is having kind of global variables (within a class) and all test methods share this variable. As a result, only few orders get created & deleted; resulting in faster tests. However, I think this introduces a bigger problem; the tests are no longer isolated and it gets more and more difficult to understand & analyze them.

It might just be that integration tests are not meant to be run as often as unit tests; therefore low performance might be acceptable for those. In any case, it would be great to know if someone came up with alternatives for improving scalability.

答:
On scalability

I've had this problem some times before, that the integration tests were taking too long to run and were not practical for a single developer to continuously run in a tight feedback loop of changes. Some strategies to cope with this are:

Write fewer integration tests - if you have good coverage with unit tests in the system, the integration tests should be more focused on (ahem) integration issues, on how different components work together. They're more similar to smoke tests, that just try to see if the system still works as a whole. So, ideally, your unit tests cover most of the functional parts of the application, and the integration tests just check how those parts interact with each other. You don't need extensive coverage of logical paths here, just some critical paths through the system.

Run only a subset of the tests at a time - as a single developer working on some functionality, you normally have a sense for which tests are necessary to cover that functionality. Run only those tests that make sense to cover your changes. Frameworks like JUnit allow you to group fixtures in a category. Create the groupings which allow for the best coverage for each feature that you have. Of course, you still want to run all the integration tests at some point, maybe before commiting to the source control system and certainly at the continuous integration server.

Optimize the system - Integration tests coupled with some performance tests might give you the necessary input to tune slow parts of the system, so that the tests will run faster later. This might help uncover needed indexes in the database, chatty interfaces between subsystems or other performance bottlenecks that need addressing.

Run your tests in parallel - If you have a good grouping of orthogonal tests, you could try running them in parallel. Be attentive to the orthogonal requirement I mentioned though, you don't want your tests stepping in each others feet.

Try combining these techniques for greater effect.


答:
I have found a lot of great guidance in the presentations from the NDC2011 conference:
http://ndc2011.no/agenda.aspx?cat=1071&id=-1&day=3726
look for the Agile tags on the schedule.
As for how to get started. Start with something small, preferrably a project that will be targeted for internal use of your organisation. That way you have more insight in the effects and choices you have to make to make the process work for you.</p>

Title: How can I get my startup working with Agile development?

Body:
In our startup, we've worked until now using the traditional waterfall model, but we want to try our next project using Agile Methodology.

We are pretty much alien to the entire Agile process, so considering this, what is the best way to understand Agile (resources and a practical handbook can be of help), decide on a specific methodology (Scrum, etc), and start it in our next project?


问:
Thread safe graph libraries
I am looking for a good Java Graph Library which is thread safe for concurrent access. JGraphT, JUNG, JTS are very good but again for concurrent access I will have to synchronize it externally which is becoming a pain. It is a pain because say If thread A have to access 50 vertices, Thread B for another 50 with the intersection of vertices being 20 vertices. Now while writing code I need to know this 20 before so that I can synchronize it accordingly. Pl suggest if there exists some framework for graphs which has inbuilt support for concurrency</p>

答: Neo4J.org sits in this space IIRC.</p>

Title: Thread safe graph libraries

Body: Neo4J.org sits in this space IIRC.


问:
How does one minimize or prevent User lawsuits?
I work in a bunch of tools that do things to customer's computers. Some of these tools allow scripting, which allows someone to run a script to nuke files, registry keys, or the like. Of course, if the script is bad, or if there's a serious bug in the tool, it could cause damage to the person's system. I'm concerned that a user might become... angry... with me if something goes wrong.

How do I minimize the likelihood of being sued as a result of publishing such a tool?

答:
I'm guessing you need the infamous "Disclaimer" message saying blah-blah-blah with the Accept \ Not Accept buttons.

If they do not accept, you do not install or run your software.

Does that prevent lawsuits?  No.  But it's ammunition for your defense lawyer should it come to that.

Of course, IF your software is the explicit CAUSE of any damage, then no disclaimer will probably help you.

In the US, you can't really prevent lawsuits in this happy litigation society, but you can prevent some of the damage by setting up a corporation-- this will prevent (in most cases) any lawsuits against your personal assets.

To add my own disclaimer: I am not a lawyer, seek professional council, yada-yada-yada.


答: No, you're not improving the code that the machine is running (... the assembly code). Leave reusing whatever memory the compiler uses for the variable to the compiler. Quite often it's going to be a register, and reusing bought you nothing. Focus on making the code easier to read.</p>

Title: Should I reuse variables?

Body:
Should I reuse variables?

I know that many best practices say you should not do it, however, later, when different developer is debugging the code and have 3 variables that look alike and the only difference is that they are created in different places in the code, he might be confused. Unit-testing is a great example of this.

However, I do know that best practices are most of the time against it.
For example they say not to "override" method parameters.

Best practices are even are against nulling the previous variables (in Java there is Sonar that gives a warning when you assign null to variable, that you don't need to do it to call the garbage collector since Java 6. You can't always control which warnings are turned off; most of the time the default is on.)


答:
It's a function of location.

If you are in the USA there is a 100% chance you will be sued by somebody, it's just part of doing business. It doesn't mean they will be successful or even have a chance - but just like Typhoons in SE Asia, snow in Scandinavia or rain in Seattle, it comes with the territory.

Title: How does one minimize or prevent User lawsuits?

Body:
I work in a bunch of tools that do things to customer's computers. Some of these tools allow scripting, which allows someone to run a script to nuke files, registry keys, or the like. Of course, if the script is bad, or if there's a serious bug in the tool, it could cause damage to the person's system. I'm concerned that a user might become... angry... with me if something goes wrong.

How do I minimize the likelihood of being sued as a result of publishing such a tool?


答:
This is a skill that really comes with experience, and often people are asked before they are able to accurately judge such a thing. I've always worked in a fairly close-knit group with an informal style, but we developed a few rules of thumb that seemed to hold up well.

First, no task takes less than a week. Always estimate in weeks, even if a task only seems like it would take a few days to accomplish. There will be some reason it will not be done before the end of the week.

Second, Give it your best effort in estimating the amount of time the task will take, including interruptions, customer support issues, getting it through testing, etc. Now, double that number. That is your estimate (in weeks).

Third, make sure your manager isn't already adding some padding to your estimates. Our team had a manager complain about our estimates. It turned out he was already going to multiply it by 2.1 (his empirically derived padding estimate) and we had already doubled it before telling him.

It is not a fancy tool, and may not be a perfect method, but it works surprisingly well.

Title: How can we plan projects realistically while accounting for support issues?

Body:
We're having a problem at work: we're trying to schedule work so that we can assess time scales and get deadline dates.

The problem is that it's difficult to plan for a project without knowing everything that's going to happen.

For instance, right now we've planned all our projects through the start of December, however in that time we will have various in house and external meetings, teleconferences and extra work. It's all well and good to say that a project will take three weeks, but if there is a week's worth of interruption in that time then the date of completion will be pushed back a week.

The problem is 3 fold:

When we schedule projects the time scales are taken literally. If we estimate three weeks, the deadline is set for three week's time, the client is told, and there is no room for extension.

Interim work and such means that we lose productive time working on the project.

Sometimes clients don't have the time that we need to take to do the work, so they'll sometimes come to us and say they need a project done by the end of the month even when we think that the work will take two months - not to mention we already have work to be doing.

We have a Gantt chart which we are trying to fill in with all the projects we have and we fill in timesheets, but they're not compared to the Gantt chart at all. This makes it difficult to say "Well, we scheduled 3 weeks for this project, but we've lost a week here so the deadline has to move back a week."

It's also not professional to keep missing deadlines we've communicated to the client.

How do other people deal with this type of situation? How do you manage the planning of projects? How much "extra" time do you schedule into a project to account for non-project work that occurs during a project? How do you deal with support issues and bugs and stuff? Things you can't account for during planning?

UPDATE

Lots of good answers thank you.


答:
The definition of a bug has nothing to do with the behavior of the software.  A bug is defined based on whether the behavior of the software matches it's intent.  And who is to say what the intent was?  (Since I'm dealing with programmers here, I'll clarify the first sentence - there is no possible software behavior that, in and of itself, constitutes a bug).

Bear in mind that generally a bug is something software developers are supposed to fix.  So the definition of a bug is based on what they want to fix.  For example, "working correctly more than 50% of the time is a feature we plan to release in future versions".  Anything can be defined as not being a bug by pretending the software was never intended to address that particular problem.  So, in practice, what constitutes a bug is a purely political consideration.

(As an aside, this cuts both ways.  To a client that doesn't have to pay for bug fixes but does have to pay for new development "it doesn't do some feature that I just thought of but which I've now decided is 100% implied by the things I did mention" is clearly a bug.)


问:
How does minecraft use a seed to generate a completely unique world?
In minecraft, before creating a world you have an option to input a seed. The algorithm takes the seed and creates a completely unique world. How does this work?</p>

答:
It gives the seed to a pseudorandom number generator (PRNG) and uses that PRNG to generate the world.

Giving the same seed will give the same sequence from the PRNG and thus generate the same world.


答: THe people doing the estimation need to understand that no team is ever 100% on a project. You have sick leave, vacation, jury duty, bereavement leave, required HR meetings (it's benefits time!), team meetings that aren't project related, unavoidable delay, bathroom breaks, support work on items already in production, dealing with emails, , configuring the new computer after the old one died, answering questions about future work and doing estimates for that work, mentoring juniors, etc. that have to be factored in. It is irresponsible for an estimator to assume more than 6 out of 8 hours available per day. That is a guarantee the deadline cannot be met. If you are guaranteeing the deadline can't be met, you are guaranteeing an unhappy customer.


答:
Good advice all around.

One other thing that might be helpful for dealing with support issues is to dedicate folks to support on a fixed "round-robin" basis.

For instance, if you have 5 developers assign one to each day of the week. When that day comes, the assigned developer works for that day ONLY on support. The next day another developer takes over support. This way everyone has a chance to stay in their "flow", everyone gets a taste of the dogfood.

How you ACTUALLY choose to divide up the regular support work doesn't really matter (the days-of-week round robin is just an example). What does matter is to limit the support-time to fixed regular intervals. This makes development time more predictable with the trade-off that you can't have "everyone drop everything" to deal with support issues.


答:
I would not consider not disconnecting a bug.  Its only a bug if it was supposed to (by design, intent) disconnect and it doesnt.  I'd call what you submitted a feature request.

That said, losing data after the battle - that might be the bug.  I dont know much about Starcraft, but I suspect thats not by design.


答:
I'm going to disagree with most people here.

As an ex-Starcraft (original) player, I can attest that this is (or was, at least) very common behavior.  Users leave the game on 24/7 to hold their position in chat rooms, and join games when they are back again.  I'm sure the updated Battle.net has some improvements which may lessen the need for this, but it still happens a lot.

It would make much more sense that it doesn't let you join a game without re-connecting if your session has in some way, shape or form, expired.  The fact that it allows you to join games after you have expired your session is a bug to me.  The disturbing thing here, and something that hasn't really been brought up yet, is that the developers need to understand their users.  This may very well be an edge case, but its an edge case to the very dedicated gamers that they should be set to please.

Technically, they can argue that it's by design, and it's not something they intend on fixing. It's still a fault in my eyes, which is ultimately up to them whether or not they classify it as a bug.  That doesn't mean players agree.

Anyway, I thought I'd pose a slightly different answer than what's been posted so far.


问:
Are there any jobs in the programming field that don't require you to sit at a desk all day?
I'm new in the field of programming. I really enjoy it as a career, but I'm not sure I can handle sitting at a desk for eight hours a day. I don't mind it for short stretches of time of course, but I can't do it day in and day out.

Is there a field of programming that possibly has jobs that require less time spent at the desk?

答:
There are a lot of fields and industries where there is more to a programming job than sitting in front of a desk. From personal experience:-

Consultancy - lots of work on client sites, lots of interaction with the business users

Finance - Working on a trading desk can be a lot of fun

But really anything where you are directly dealing with the users of your software is likely to be more varied


答: In my current job I see programmers for the car industry, which too work with specialized equipment. It doesn't always mean working at the desk, but it can mean going off site to connect to a car's CAN bus. </p>

Title: Are there any jobs in the programming field that don't require you to sit at a desk all day?

Body:
I'm new in the field of programming. I really enjoy it as a career, but I'm not sure I can handle sitting at a desk for eight hours a day. I don't mind it for short stretches of time of course, but I can't do it day in and day out.

Is there a field of programming that possibly has jobs that require less time spent at the desk?


问:
Is there a Django reference?
I am new to Django. I have found the official topic guides https://docs.djangoproject.com/en/1.3/ an excellent place to learn from. But now I am in a place where I need quick reference to see what methods an object has, what arguments it takes, what it returns etc, kind of like the Python docs or Java docs. More of a reference than a tutorial. The official docs are tutorial style and do not necessarily have reference to all the methods.

Am I missing something here? Do the Django official docs suffice for everyone?

答:
I may be incorrect but I've been using django for over a year now and never found such a guide.

Slightly unfortunate - I would like to have a function reference like you mentioned.
However, as an additional resource the http://www.djangobook.com/ is very good.
I've always considered building one, but I'm very lazy.

There is also another reference you may use when you're stuck http://www.thedjangoforum.com

edit:

http://ccbv.co.uk/ Classy Class-Based Views. Detailed descriptions, with full methods and attributes, for each of Django's class-based generic views.

OwnerDisplayName: superxor

Title: Is there a Django reference?

OwnerDisplayName: Glycerine

ContentLicense: CC BY-SA 4.0


答:
Python has a built-in mechanism for that: docstrings.  Example:

```<code>>>> import django.forms
>>> help(django.forms.ModelForm)
Help on class ModelForm in module django.forms.models:

class ModelForm(BaseModelForm)
 |  Method resolution order:
 |      ModelForm
 |      BaseModelForm
 |      django.forms.forms.BaseForm
 |      django.utils.encoding.StrAndUnicode
 |      __builtin__.object
 |
 |  Data and other attributes defined here:
 |
 |  __metaclass__ = <class 'django.forms.models.ModelFormMetaclass'>
 |
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from BaseModelForm:
 |
 |  __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=<class 'django.forms.util.ErrorList'>, label_suffix=':', empty_permitted=False, instance=None)
 |
 |  clean(self)

 |
 |  save(self, commit=True)
 |      Saves this ``form``'s cleaned_data into model instance
 |      ``self.instance``.
 |
 |      If commit=True, then the changes to ``instance`` will be saved to the
 |      database. Returns ``instance``.
 |
 |  validate_unique(self)
 |      Calls the instance's validate_unique() method and updates the form's
 |      validation errors if any were raised.
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from django.forms.forms.BaseForm:
 |
 |  __getitem__(self, name)
 |      Returns a BoundField with the given name.
 |
 |  __iter__(self)
 |
 |  __unicode__(self)
 |
 |  add_initial_prefix(self, field_name)

 |      Add a 'initial' prefix for checking dynamic initial values
 |
 |  add_prefix(self, field_name)
 |      Returns the field name with a prefix appended, if this Form has a
 |      prefix set.
 |
 |      Subclasses may wish to override.
 |
 |  as_p(self)
 |      Returns this form rendered as HTML <p>s.
 |
 |  as_table(self)
 |      Returns this form rendered as HTML <tr>s -- excluding the <table></table>.
 |
 |  as_ul(self)
 |      Returns this form rendered as HTML <li>s -- excluding the <ul></ul>.
 |
 |  full_clean(self)
 |      Cleans all of self.data and populates self._errors and
 |      self.cleaned_data.
 |
 |  has_changed(self)
 |      Returns True if data differs from initial.
 |
 |  hidden_fields(self)
 |      Returns a list of all the BoundField objects that are hidden fields.
 |      Useful for manual form layout in templates.
 |
 |  is_multipart(self)
 |      Returns True if the form needs to be multipart-encrypted, i.e. it has
 |      FileInput. Otherwise, False.
 |
 |  is_valid(self)
 |      Returns True if the form has no errors. Otherwise, False. If errors are
 |      being ignored, returns False.
 |
 |  non_field_errors(self)
 |      Returns an ErrorList of errors that aren't associated with a particular
 |      field -- i.e., from Form.clean(). Returns an empty ErrorList if there
 |      are none.
 |
 |  visible_fields(self)
 |      Returns a list of BoundField objects that aren't hidden fields.
 |      The opposite of the hidden_fields() method.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from django.forms.forms.BaseForm:
 |
 |  changed_data
 |
 |  errors
 |      Returns an ErrorDict for the data provided for the form
 |
 |  media
 |      Provide a description of all media required to render the widgets on this form
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from django.utils.encoding.StrAndUnicode:
 |
 |  __str__(self)
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from django.utils.encoding.StrAndUnicode:
 |
 |  __dict__
 |      dictionary for instance variables (if defined)
 |
 |  __weakref__
 |      list of weak references to the object (if defined)
</code>```

Then you can look up the docstrings of individual methods:

```<code>>>> help(django.forms.ModelForm.is_valid)
Help on method is_valid in module django.forms.forms:

is_valid(self) unbound django.forms.models.ModelForm method
    Returns True if the form has no errors. Otherwise, False. If errors are
    being ignored, returns False.
</code>```

Title: Is there a Django reference?

Body:
I am new to Django. I have found the official topic guides https://docs.djangoproject.com/en/1.3/ an excellent place to learn from. But now I am in a place where I need quick reference to see what methods an object has, what arguments it takes, what it returns etc, kind of like the Python docs or Java docs. More of a reference than a tutorial. The official docs are tutorial style and do not necessarily have reference to all the methods.

Am I missing something here? Do the Django official docs suffice for everyone?

Body:
Python has a built-in mechanism for that: docstrings.  Example:

>>> import django.forms
>>> help(django.forms.ModelForm)
Help on class ModelForm in module django.forms.models:

class ModelForm(BaseModelForm)
 |  Method resolution order:
 |      ModelForm
 |      BaseModelForm
 |      django.forms.forms.BaseForm
 |      django.utils.encoding.StrAndUnicode
 |      __builtin__.object
 |
 |  Data and other attributes defined here:
 |
 |  __metaclass__ = <class 'django.forms.models.ModelFormMetaclass'>
 |
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from BaseModelForm:
 |
 |  __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, initial=None, error_class=<class 'django.forms.util.ErrorList'>, label_suffix=':', empty_permitted=False, instance=None)
 |
 |  clean(self)

 |
 |  save(self, commit=True)
 |      Saves this ``form``'s cleaned_data into model instance
 |      ``self.instance``.
 |
 |      If commit=True, then the changes to ``instance`` will be saved to the
 |      database. Returns ``instance``.
 |
 |  validate_unique(self)
 |      Calls the instance's validate_unique() method and updates the form's
 |      validation errors if any were raised.
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from django.forms.forms.BaseForm:
 |
 |  __getitem__(self, name)
 |      Returns a BoundField with the given name.
 |
 |  __iter__(self)
 |
 |  __unicode__(self)
 |
 |  add_initial_prefix(self, field_name)

 |      Add a 'initial' prefix for checking dynamic initial values
 |
 |  add_prefix(self, field_name)
 |      Returns the field name with a prefix appended, if this Form has a
 |      prefix set.
 |
 |      Subclasses may wish to override.
 |
 |  as_p(self)
 |      Returns this form rendered as HTML <p>s.
 |
 |  as_table(self)
 |      Returns this form rendered as HTML <tr>s -- excluding the <table></table>.
 |
 |  as_ul(self)
 |      Returns this form rendered as HTML <li>s -- excluding the <ul></ul>.
 |
 |  full_clean(self)
 |      Cleans all of self.data and populates self._errors and
 |      self.cleaned_data.
 |
 |  has_changed(self)
 |      Returns True if data differs from initial.
 |
 |  hidden_fields(self)
 |      Returns a list of all the BoundField objects that are hidden fields.
 |      Useful for manual form layout in templates.
 |
 |  is_multipart(self)
 |      Returns True if the form needs to be multipart-encrypted, i.e. it has
 |      FileInput. Otherwise, False.
 |
 |  is_valid(self)
 |      Returns True if the form has no errors. Otherwise, False. If errors are
 |      being ignored, returns False.
 |
 |  non_field_errors(self)
 |      Returns an ErrorList of errors that aren't associated with a particular
 |      field -- i.e., from Form.clean(). Returns an empty ErrorList if there
 |      are none.
 |
 |  visible_fields(self)
 |      Returns a list of BoundField objects that aren't hidden fields.
 |      The opposite of the hidden_fields() method.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from django.forms.forms.BaseForm:
 |
 |  changed_data
 |
 |  errors
 |      Returns an ErrorDict for the data provided for the form
 |
 |  media
 |      Provide a description of all media required to render the widgets on this form
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from django.utils.encoding.StrAndUnicode:
 |
 |  __str__(self)
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from django.utils.encoding.StrAndUnicode:
 |
 |  __dict__
 |      dictionary for instance variables (if defined)
 |
 |  __weakref__
 |      list of weak references to the object (if defined)

Then you can look up the docstrings of individual methods:

>>> help(django.forms.ModelForm.is_valid)
Help on method is_valid in module django.forms.forms:

is_valid(self) unbound django.forms.models.ModelForm method
    Returns True if the form has no errors. Otherwise, False. If errors are
    being ignored, returns False.

OwnerDisplayName: Vebjorn Ljosa


答:
Integration tests should always be run against the production set-up. In your case it means you should have the same database and application server. Of course, for the sake of performance you could decide to use an in-memory DB.

What you should never do though is to extend your transaction scope. Some people suggested to take over control over the transaction and to roll it back after the tests. When you do this, all entities (assuming you are using the JPA) will stay attached to the persistence context throughout the test execution. This may result in some very nasty bugs which are very hard to find.

Instead, you should clear the database manually after every test through a library like JPAUnit or similar to this approach (clear all tables using JDBC).

As of your performance problems, you shouldn't execute the integration tests on every build. Let your continuous integration server do this. If you use Maven, you might enjoy the failsafe plug-in which allows you to separate your tests into unit and integration tests.

Also, you shouldn't mock anything. Remember you are integration testing, i.e. testing behavior within the run-time execution environment.

Title: How to create scalable & side-effect free integration tests?

Body:
In my current project, I am having a hard time coming up with a good solution to create scalable integration tests that have no side effects. A little clarification on the side effect free property: it is mostly about the database; there shouldn't be any changes in the database after the tests are completed (state should be preserved). Maybe scalability and state preservation don't come together, but I really want to push for a better solution.

Here is a typical integration test (these tests touch the database layer):

```<code>public class OrderTests {

    List<Order> ordersToDelete = new ArrayList<Order>();

    public testOrderCreation() {
        Order order = new Order();
        assertTrue(order.save());
        orderToDelete.add(order);
    }

    public testOrderComparison() {
        Order order = new Order();
        Order order2 = new Order();
        assertFalse(order.isEqual(order2);
        orderToDelete.add(order);
        orderToDelete.add(order2);
    }
    // More tests

    public teardown() {
         for(Order order : ordersToDelete)
             order.delete();
    }
}
</code>```

As one might imagine, this approach yields tests that are extremely slow. And, when applied to the whole integration tests, it takes around 5 seconds to test only a small portion of the system. I can imagine this number going up when the coverage is increased.

What would be another approach for writing such tests? One alternative I can think of is having kind of global variables (within a class) and all test methods share this variable. As a result, only few orders get created & deleted; resulting in faster tests. However, I think this introduces a bigger problem; the tests are no longer isolated and it gets more and more difficult to understand & analyze them.

It might just be that integration tests are not meant to be run as often as unit tests; therefore low performance might be acceptable for those. In any case, it would be great to know if someone came up with alternatives for improving scalability.


答: For testing purposes we have used a file based deployment of an SQLite database(just copy a resource). This was done so we could also test schema migrations. As far as I'm aware, schema changes are not transactional so will not be rolled back after a transaction is aboted. Also not having to rely on transaction support for test setup allows to test the behaviour of transactions from your application properly. </p>


答:
Personally, I find using pycharm IDE helps speed up django development significantly.  Also in the django shell you can use the ipython feature to get docstrings and source code, by typing something in and followed by ? (basic info) or ?? (source code).  Also other ipython features like tab completion (only one level deep) are very helpful.</p>

```<code>In [1]: from django.contrib.auth.models import User

In [2]: User ?
Type:       ModelBase
Base Class: <class 'django.db.models.base.ModelBase'>
String Form:    <class 'django.contrib.auth.models.User'>
Namespace:  Interactive
File:       /usr/local/lib/python2.6/dist-packages/Django-1.2.5-py2.6.egg/django/contrib/auth/models.py
Docstring:
    Users within the Django authentication system are represented by this model.

    Username and password are required. Other fields are optional.

Constructor information:
Definition: User(self, *args, **kwargs)

In [3]: User ??
Type:             ModelBase
Base Class:       <class 'django.db.models.base.ModelBase'>
String Form:   <class 'django.contrib.auth.models.User'>
Namespace:        Interactive
File:             /usr/local/lib/python2.6/dist-packages/Django-1.2.5-py2.6.egg/django/contrib/auth/models.py
Source:

class User(models.Model):
    """
    Users within the Django authentication system are represented by this model.

    Username and password are required. Other fields are optional.
    """
    username = models.CharField(_('username'), max_length=30, unique=True, help_text=_("Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters"))
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    email = models.EmailField(_('e-mail address'), blank=True)
    password = models.CharField(_('password'), max_length=128, help_text=_("Use '[algo]$[salt]$[hexdigest]' or use the <a href=\"password/\">change password form</a>."))
    is_staff = models.BooleanField(_('staff status'), default=False, help_text=_("Designates whether the user can log into this admin site."))
    is_active = models.BooleanField(_('active'), default=True, help_text=_("Designates whether this user should be treated as active. Unselect this instead of deleting accounts."))
    is_superuser = models.BooleanField(_('superuser status'), default=False, help_text=_("Designates that this user has all permissions without explicitly assigning them."))
    last_login = models.DateTimeField(_('last login'), default=datetime.datetime.now)
    date_joined = models.DateTimeField(_('date joined'), default=datetime.datetime.now)
    groups = models.ManyToManyField(Group, verbose_name=_('groups'), blank=True,
        help_text=_("In addition to the permissions manually assigned, this user will also get all permissions granted to each group he/she is in."))
    user_permissions = models.ManyToManyField(Permission, verbose_name=_('user permissions'), blank=True)
    objects = UserManager()

        class Meta:
        verbose_name = _('user')
[...]
</code>```

Title: Is there a Django reference?

Body:
Personally, I find using pycharm IDE helps speed up django development significantly.  Also in the django shell you can use the ipython feature to get docstrings and source code, by typing something in and followed by ? (basic info) or ?? (source code).  Also other ipython features like tab completion (only one level deep) are very helpful.

In [1]: from django.contrib.auth.models import User

In [2]: User ?
Type:       ModelBase
Base Class: <class 'django.db.models.base.ModelBase'>
String Form:    <class 'django.contrib.auth.models.User'>
Namespace:  Interactive
File:       /usr/local/lib/python2.6/dist-packages/Django-1.2.5-py2.6.egg/django/contrib/auth/models.py
Docstring:
    Users within the Django authentication system are represented by this model.

    Username and password are required. Other fields are optional.

Constructor information:
Definition: User(self, *args, **kwargs)

In [3]: User ??
Type:             ModelBase
Base Class:       <class 'django.db.models.base.ModelBase'>
String Form:   <class 'django.contrib.auth.models.User'>
Namespace:        Interactive
File:             /usr/local/lib/python2.6/dist-packages/Django-1.2.5-py2.6.egg/django/contrib/auth/models.py
Source:

class User(models.Model):
    """
    Users within the Django authentication system are represented by this model.

    Username and password are required. Other fields are optional.
    """
    username = models.CharField(_('username'), max_length=30, unique=True, help_text=_("Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters"))
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)
    email = models.EmailField(_('e-mail address'), blank=True)
    password = models.CharField(_('password'), max_length=128, help_text=_("Use '[algo]$[salt]$[hexdigest]' or use the <a href=\"password/\">change password form</a>."))
    is_staff = models.BooleanField(_('staff status'), default=False, help_text=_("Designates whether the user can log into this admin site."))
    is_active = models.BooleanField(_('active'), default=True, help_text=_("Designates whether this user should be treated as active. Unselect this instead of deleting accounts."))
    is_superuser = models.BooleanField(_('superuser status'), default=False, help_text=_("Designates that this user has all permissions without explicitly assigning them."))
    last_login = models.DateTimeField(_('last login'), default=datetime.datetime.now)
    date_joined = models.DateTimeField(_('date joined'), default=datetime.datetime.now)
    groups = models.ManyToManyField(Group, verbose_name=_('groups'), blank=True,
        help_text=_("In addition to the permissions manually assigned, this user will also get all permissions granted to each group he/she is in."))
    user_permissions = models.ManyToManyField(Permission, verbose_name=_('user permissions'), blank=True)
    objects = UserManager()

        class Meta:
        verbose_name = _('user')
[...]


问:
Is there a canonical book on functional design specifications?
I have seen and read quite a few books about software design (using UML, etc.), and others about user experience, GUIs, etc. but I'm looking for books that describe the process that happens before all of that.

I'm looking for the pre-development stuff. How to develop a cohesive and comprehensive plan for what the application is functionally supposed to do, leading to flow-charts and a functional specification, etc. So I guess my question is in two parts:

Is there a book out there that's the de-facto standard for describing best practices, design methodologies, and other helpful information about functional requirements analysis? What about that book makes it special?

答:
Functional design is I reckon a bit of an older term used during the times (D)SDM was popular. I reckon nowadays it's called Analysis or gathering requirements.

I've been introduced to the subject of requirements analysis through a book written by Ian Sommerville called "Software engineering" That helped me put processes involved in creating software in perspective. The book explains what needs to be acomplished, why and how it can be done.

Ian Sommerville also has written a book on the specific subject of requirements analysis.
http://www.amazon.com/Requirements-Engineering-Good-Practice-Guide/dp/0471974447/ref=sr_1_5?s=books&ie=UTF8&qid=1319274316&sr=1-5


问:
Software testing automation documentation
What document types could be used when describing software testing automation (on any phase, automation planning, test design, implementation, reporting)? Is there any standard types of documents?
If someone could provide any examples and templates for different types of documents?
What is the difference between manual testing documentation and automated?</p>

答:
In my project, the automation tests are essentially documented using the same means as manual tests. In addition to all the other information, we also point to the test case in code.

We maintain an automation suite which the whole team knows how to execute. With both these pieces of information, any member on the team is able to identify the test case as well as run it.

Also, like our production code, we also version and review the automated test cases. These serve as living documentation for the code representation of the test.

So in a way, we are reusing our documentation ways for manual tests and production code for automated tests.

OwnerDisplayName: Nitesh Baranwal


问:
Hooking up a Business Layer and Repository using Unit of Work Pattern
My question is similar to this one on Stack Overflow: What is the correct way to use Unit of Work/Repositories within the business layer?

Scenario:

.Net solution

IRepository used to retrieve objects from DB

IUnitOfWork used to allow transactions across multiple repositories

This makes sense to me and I have implemented something along these lines that works fine. Now I want to introduce a business logic layer and am having trouble organising the three elements (BLL, UnitOfWork and Repository) in my mind.

My understanding:

Repository - data retrieval, manipulation

UnitOfWork - persistence

BLL - logic relevant to the business ('real world') (dislike that term!)

Consider we have an ASP.Net MVC front end.

What does a BLL look like and what does the MVC controller that uses it look like?

For reference:
I wonder if perhaps my IUnitOfWork/IRepository implementation might be the underlying cause of my confusion.

public class IRepository<T>
{
    private IObjectSet<T> objSet;
    public IRepository<T>(IUnitOfWork uow)
    {
        objSet = uow.CreateObjectSet<T>();
    }

    public IQueryable<T> Add(T entity)
    {
        objSet.Add(entity);
    }
    //etc. etc. for delete, attach, getall
}
```

So I feel like if I have a BLL, I should be passing it the IUnitOfWork, so that it can use that to create the IRepository instances that it needs. But how will the BLL (separate DLL from the front end) 'know' what implementation of IRepository to build?

答:
Please note that I only have minor experience with the .NET framework and that this answer only relates to the architecture part of your question.

As far as I understood it, you are basically applying the following architectural patterns in your application:

Layers: It seems you have a persistence layer (Repository Pattern), a business logic layer and a view layer.

Model-View-Controller: This pattern is applied in the view layer using ASP.NET MVC.

I guess the question is: what does a BLL look like and what does the MVC controller that uses it look like?

First of all, this architecture is intended for large-scale, enterprise applications as Robert Harvey mentioned in his comment to your question. What is characteristic for such systems is that the domain logic (which you encapsulated in the business logic layer) should be accessible through various interfaces.

Consider Twitter for instance - Twitter could have a business logic layer which provides services for registering and validating users, posting tweets and much more. On top of this business logic layer, multiple other components could exist in the view layer, e.g. a web interface and web service component. Since all business logic is encapsulated in the business logic layer, you can follow the DRY principle and improve maintainability and other quality attributes.

To come back to your question - you should encapsulate business logic and data access in the BLL. The controller (think MVC) should make use of the BLL and should not have direct access to the database. Consider the view layer as an interface to your application.

So I feel like if I have a BLL, I should be passing it the IUnitOfWork, so that it can use that to create the IRepository instances that it needs. But how will the BLL (separate DLL from the front end) 'know' what implementation of IRepository to build?

The BLL should know which repository (data source?) it uses. The layers above shouldn't control this. Again, consider the view layer only as an interface to your business logic.

If you don't need the overhead of a business logic layer, you may also choose to use it solely for data access in form of data access objects.

I hope this helped clarifying the various components' responsibilities.


问:
Build a Platform API for public
I am looking for some advices, resources or articles about how to expose a Platform API to outside developers.

My main concern is what is the standards or best approach to do that, basically I have a set of REST API services of the platform and need to understand how to address the following issus :

API Hosting and Management in general (should we use online api management tools like apigee or mashrey?)

Developer Keys, permissions

Developer tools, documentations

throttling

Reporting

Logging/Auditing

Authentication and Authorization

It is also great if you can point out to some articles that explain how Facebook or Twitter or Google are doing this, or abstract architecture and management best practices on how to open Platform API to the public users.

Thanks,

答:
Step 1: read the Facebook and Amazon development documents.

(Don't read Google, some folks think they're not as good at creating an API.  Read this to see what mistakes Google may have made. https://plus.google.com/112678702228711889851/posts/eVeouesvaVX)

http://developers.facebook.com/docs/reference/api/

http://aws.amazon.com/

These documents will cover most of your questions.  They will show a number of good practices.  You'll have to choose which you think is best.

OwnerDisplayName: Ahmad Alkhawaja

Title: Build a Platform API for public


问:
Is there such a thing as a "when" statement?
Is there a language or language feature that can handle "when" cases? That is, whenever some condition becomes true, in any scope or context, that extra code could be specified to execute?

Note that this is different from a simple if, which must be in a particular scope and explicitly written. This when clause would almost be like an if that applied to every case in the execution of the program after it.

答:
In most OOP languages it would be possible to spawn an extra thread, have this as the context:</p>

```<code>    while (!value)
{
}

//Execute code
</code>```

Body:
In most OOP languages it would be possible to spawn an extra thread, have this as the context:

    while (!value)
{
}

//Execute code


问:
Tracking feature requests for small-scale components
I'm curious how other development teams (especially those that work in moderate to large development groups) track "future" features/wishlists for functionality for internally developed frameworks or components.

I know the standard advice is that a development team should find one good tool for tracking bugs/features and use that for everything and I agree with that if the future requests are for the product itself.

In my company we have an engineering department, which is broken up into multiple groups and within each there can be one to several agile teams.  The bug tracking product we use has been "a leader since 1997" (their UI/usability seems to also be evaluated against that year even today) but my agile team or even group doesn't really control what is being used by the whole department.

What we are looking to track is not necessarily product features but expansion/nice to have functionality for internal components that go into our product.  So to name a few for example...

framework/utility library on top of CppUnit which our developers share

low-level IPC communications framework

Common development SDK that myself and several other team leads started to help share some common code/tools at the department-wide level  (this SDK is released as internal "product" to each of the groups).

Is the standard practice to use the one bug tracking tool? Or would it make more sense to setup something more localized specifically for our needs and maintain it ourselves? It's also unclear how management will feel if developers start performing "IT" roles of maintaining software and servers.

At the same time, right now, we use excel files, internal wiki and MS OneNote for this kind of stuff and that just doesn't feel right.

(I'm afraid to ask for actual software recommendations, since that might make this question more localized or something. Also developers needs this way more than management, so it would be nice to find something either free or no more than the cost of a happy hour).

答:
With regards to how management might feel about setting up something localized, I think that the most obvious answer is to simply meet with management and asked outright for their opinion on the matter.  Better yet, have a couple of ideas to introduce and see if you can encourage your managers to take those ideas on board.

A tool is a tool.  It's only as good as the person using it. If something doesn't feel correct, ask yourself what aspects of the presently used tools are the things that cause you to feel this way, and then look at your options.  You might customise, improve, or replace depending on how you and your colleagues feel about it.  Also, you need to have the entire team buy into the idea. If everyone else likes the system already in place, then you might be fighting a losing battle. On the other hand, you'll probably find that many of the issues you raise with regards to your present tracking system will probably be seen by your colleagues as problems and they just might have some good ideas of their own to share.

As for what to use, any good issue tracking system could be customised to the purpose you wish.  For example (forgive the plug), we use a Redmine system (yes, it's free as in gratis) where we work, and we have set up a kind of meta-project that we use as a kind of dumping ground for ideas and requests that don't seem to fit well within any existing project.  Every few months, we go through the list, remove items that are no longer relevant, and expand on ideas that require more discussion. The nice thing for us is that Redmine allows us to create new projects that we can link back to the original feature/issue in our "dumping ground", and we can easily move these offline issues to other projects as necessary.  We find this works for us, and we have tuned the tool to suit our purposes in this regard.  What I'm getting at is that with a little lateral thinking, you may find that your existing issue tracking system might be able to be tuned to suit your needs in this regard.  The benefit of this is that management will be happy that you didn't spend any real money, and your IT department won't have to worry that you are trying to do them out of a job!  ;-)


问:
Does this licensing clause allow redistribution of this application?
As a software developer, I find a frequent need to create icons for my applications. Nothing has ever worked as well as IcoFX for this purpose. Unfortunately, the program is no longer free - but I still have the installer for an older version.

My question is whether or not I can distribute copies of the installer. The license agreement contains the following pertinent clauses:

```
6. All redistributions of the Software's files must retain all
   copyright notices and web site addresses that are
   currently in place, and must include this list of
   conditions without modification.

7. None of the Software's files may be redistributed for
   profit or as part of another Software package without
   express written permission of the Author.

10. The Author reserves his rights to modify this agreement
    in the future.
```

The first two clauses would seem to suggest that I can legally distribute verbatim copies of the installer but the last clause has me confused. If the author modifies the agreement and removes the ability to distribute copies, does it apply to my copy that I downloaded a while back?

答: The danger here is that the author included a clause that basically states "I can change the licensing terms any time I want to," without providing any provisions for allowing existing users to be "grandfathered" under the original license terms. That makes the license agreement too unsafe to be relied upon in any redistribution context.</p>


问:
How to divide work among development team members in a website project using MVC pattern
I am working on a webapp project using flask framework and sqlalchemy orm in python. Its the first time I am working on a project like this and I am having trouble in how to divide work properly among my teammates. We are 5 guys, one is handling designing, two front end and 2 on backend. I am on the backend. Flask follows MVC type pattern. How does teams divide work in MVC pattern?
Moreover I am more confused in dividing work with my team mate in backend. Should one handle all the database queries and let the other one handle processing on those returned results?
Need some advise on work division in web projects.</p>

答:
We had a similar situation in our team; the technology was different but the concept is universal.

I think the first thing you can do as a team is to agree upon a domain model. This will be skeleton of your implementation. Each team member needs to understand (and actively contribute if possible) to the creation of this model. The model contains the entities (they are not database tables or classes or views) of your project.

When the model is ready, each layer can start working independently (front-end and backend). Everyone has a clear idea of the domain; and a model that they can use to communicate. This creates nice and clear interfaces between the teams.

Regarding the separation within the teams (backend), one option would be to do pair-programming (since there are only 2 members). The other option would be to break the model into two parts and each person gets to work on their part.

Again, the key is to have clear interfaces between the teams. That would let the teams work in isolation.


问:
Have objects delivered in terms of code reuse?
I have often heard it said that objects have not delivered in terms of code reuse. Do you agree? If you believe that they haven't, why not?</p>

答:
Some Programmers will copy and paste in any language and style.

Really good programmers can avoid most copy and paste in nearly any language.

I find OO patterns tend to encourage reuse.  I've seen Java code that was written in a non-OO style (where the data was separated from the code due to crappy ORM) and the reuse was truly miserable--but in OO the same programmers did a better job at design (and reuse).

Also in cases where we use non-oo patterns or oo anti-patters such as setters/getters, switch statements, anonymous inner classes, huge functions and the like I've seen code reuse go down and boilerplate go up...significantly.

ps. I know people will have problems with the previous paragraph, so I'll explain a bit.

Setters and getters cause OO problems because they allow you to operate on the members of an object (an object should manipulate it's OWN members) This distributes the code that operates on your class throughout other classes requiring you to copy the functionality around the setter/getter.  This applies to Properties as well--just because Properties are easier doesn't make them "Good" in all situations.

The code in Anonymous inner classes can't be reused at all and people forget that many things (like listeners) can and should be full-fledged classes--this applies to closures as well!  If you have used an anonymous inner class to implement something like a listener, you are much more likely to just copy and paste your implementation than to extract the code into a method or it's own class and call it instead.  Closures can also improve reusability--just depends on how you use them.

In many cases the features available to you shape how you structure your code.  OO is even more powerful when it comes to helping you visualize all your code and how it interacts, but that's another question.


问:
Is Iteration Context a pattern? Should it be?
The following is more of a statement than a question - it describes something that may be a pattern. The question is: is this a known pattern? Or, if it's not, should it be?

I've had a situation where I had to iterate over two dissimilar multi-layer data structures and copy information from one to the other. Depending on particular use case, I had around eight different kinds of layers, combined in about eight different combinations:

```<code>A-B-C
B-C
A-C
D-E
A-D-E
</code>```

and so on

After a few unsuccessful attempts to factor out the repetition of per-layer iteration code, I realized that the key difficulty in this refactoring was the fact that the bottom level needed access to data gathered at higher levels. To explicitly accommodate this requirement, I introduced IterationContext class with a number of get() and set()  methods for accumulating the necessary information.

In the end, I had the following class structure:

```<code>class Iterator {
  virtual void iterateOver(const Structure &dataStructure1, IterationContext &ctx) const = 0;
};

class RecursingIterator : public Iterator {
  RecursingIterator(const Iterator &below);
};

class IterateOverA : public RecursingIterator {
  virtual void iterateOver(const Structure &dataStructure1, IterationContext &ctx) const {
    // Iterate over members in dataStructure1
      // locate corresponding item in dataStructure2 (passed via context)
      // and set it in the context
      // invoke the sub-iterator
};

class IterateOverB : public RecursingIterator {
  virtual void iterateOver(const Structure &dataStructure1, IterationContext &ctx) const {
    // iterate over members dataStructure2 (form context)
      // set dataStructure2's item in the context
      // locate corresponding item in dataStructure2 (passed via context)
      // invoke the sub-iterator
};

void main()
{
  class FinalCopy : public Iterator {
      virtual void iterateOver(const Structure &dataStructure1, IterationContext &ctx) const {
          // copy data from structure 1 to structure 2 in the context,
          // using some data from higher levels as needed
      }
   }

  IterationContext ctx(dateStructure2);
  IterateOverA(IterateOverB(FinalCopy())).iterate(dataStructure1, ctx);
}
</code>```

It so happens that dataStructure1 is a uniform data structure, similar to XML DOM in that respect, while dataStructure2 is a legacy data structure made of various structs and arrays. This allows me to pass dataStructure1 outside of the context for convenience. In general, either side of the iteration or both sides may be passed via context, as convenient.

The key situation points are:

complicated code that needs to be invoked in "layers", with multiple combinations of layer types possible

at the bottom layer, the information from top layers needs to be visible.

The key implementation points are:

use of context class to access the data from all levels of iteration

complicated iteration code encapsulated in implementation of pure virtual function

two interfaces - one aware of underlying iterator, one not aware of it.

use of const & to simplify the usage syntax.

答: The pattern I see is the Decorator pattern whereby you have a class that performs the work (FinalCopy) which can be 'decorated' by the classes IterateOverA and IterateOverB. The 'decorating' classes augment the FinalCopy class by performing additional tasks before and after invocations on it. Since all three of these classes implement the same interface (Iterator), they are interchangeable and the client need not know of their nesting.


答:
There is nothing you can do to prevent getting sued.  My company is getting sued right now despite a diamond solid TOS, Disclaimer, and EULA.

They know they won't win, but then winning in court is not the goal sometimes.  If your product is so good that it embarrasses a well established corporation with a mediocre product and 80% market share, and then this corporation will either offer to buy out your company or sue you just trying to force you to pay lots of money for legal fees defending yourself.  Or both just to drive their point home.

Form an LLC, keep its assets low and liabilities high and you should be safe personally.


问:
Should I reuse variables?
Should I reuse variables?

I know that many best practices say you should not do it, however, later, when different developer is debugging the code and have 3 variables that look alike and the only difference is that they are created in different places in the code, he might be confused. Unit-testing is a great example of this.

However, I do know that best practices are most of the time against it.
For example they say not to "override" method parameters.

Best practices are even are against nulling the previous variables (in Java there is Sonar that gives a warning when you assign null to variable, that you don't need to do it to call the garbage collector since Java 6. You can't always control which warnings are turned off; most of the time the default is on.)

答:
Use global variables when you need to maintain a state or store constants.
By reusing variables you are only reusing the name that points to a location in memory. Descriptive names on initializations can only win you clarity (Assuming Java and no primitive OCD).

Unless you're into code obfuscation by hand or irritating other developers.

Title: Should I reuse variables?


问:
Pesky bugs - nonexistant?
Very short introduction (this is quite a context-heavy question):

I'm a 17 year old programmer, doing some projects, usually netting around 20 files of 200 lines each. I usually don't program very low-level, more high-level with battery included API's like Python + pygame and Lua + WoW API. Nevertheless I've written quite some code in the lower levels of the computer too (mostly C/C++).

Now, I read a lot of programmer discussion and a common returning argument is preventing pesky bugs, for example in "reusing variable names". I always nodded and thought that it was a valid argument, but just now I wondered, how valid is it?

To be honest, after thinking for a while, I figured I have no idea what they mean with pesky bugs. We all heard stories about phenomenal impossible-to-debug bugs, we all have spent useless evenings on that one annoying bug, but apart from a few cases I have never been busy with a programming-related bug for longer than a few hours.

Though on the other hand, the projects I work(ed) on aren't huge 10 million line projects like the linux kernel, and are quite simple... scripts. I have a good understanding of them (or at least my part in collaborations) and are not very error-prone.

So I'm wondering, do these pesky bugs occur exponentially more as the amount of code increases, or ...?

答:
So I'm wondering, do these pesky bugs occur exponentially more as the amount of code increases, or ...?

I'd argue that the number of "pesky" bugs (heisenbugs, etc.) does indeed have some correlation to sheer amount of code.  But I believe KLOC is only a rough metric for what is really at issue, and that is complexity and interactions.  The more variables you have, the more state you have, and the more branch points you have, the more complex your code is.  The more various parts of your code interact with other parts, or interact with external systems, the more complex things are.  The more complex things are, the more opportunities you have for those "weird" bugs to sneak in.

When you mix in concurrency, shared state, and an external system or two, even a fairly short program can be very complex and can manifest difficult-to-diagnose behavior.

Read up on things like Cyclomatic Complexity and software Correctness for more on this topic.

Title: Pesky bugs - nonexistant?