答:
As other users said both are logically same, but different representations are used  based on your inputs. For simple stuff "if ... else if" are enough, but for complex ones nested "if ... else" would make more sense and is easily readable.

For example, lets assume we are checking if an input is string/number/special character after that we'll check if its in upper/lower case for string, positive/negative for number and some other check for special characters.

Now lets write it in both the representations.

Representation - 1

```<code>if (input is number && input is positive)
{
...
}
else if (input is number && input is negative)
{
...
}
else if (input is string && input is in uppercase)
{
...
}
else if (input is string && input is in lowercase)
{
...
}
else if (input is special-char && input is a currency-symbol)
{
...
}
else if (input is special-char && input is an-operator)
{
...
}
else
{
...
}
</code>```

Representation - 2

```<code>if (input is number)
{
    if (number is positive)
    {
    ...
    }
    else
    {
    ...
    }
}
else if (input is string)
{
    if (string is in uppercase)
    {
    ...
    }
    else
    {
    ...
    }
}
else if (input is special-char)
{
    if (special-char is currency symbol)
    {
    ....
    }
    else
    {
    ...
    }
}
</code>```

Title: Differences in If... Else... statement

Body:
As other users said both are logically same, but different representations are used  based on your inputs. For simple stuff "if ... else if" are enough, but for complex ones nested "if ... else" would make more sense and is easily readable.

For example, lets assume we are checking if an input is string/number/special character after that we'll check if its in upper/lower case for string, positive/negative for number and some other check for special characters.

Now lets write it in both the representations.

Representation - 1

if (input is number && input is positive)
{
...
}
else if (input is number && input is negative)
{
...
}
else if (input is string && input is in uppercase)
{
...
}
else if (input is string && input is in lowercase)
{
...
}
else if (input is special-char && input is a currency-symbol)
{
...
}
else if (input is special-char && input is an-operator)
{
...
}
else
{
...
}

Representation - 2

if (input is number)
{
    if (number is positive)
    {
    ...
    }
    else
    {
    ...
    }
}
else if (input is string)
{
    if (string is in uppercase)
    {
    ...
    }
    else
    {
    ...
    }
}
else if (input is special-char)
{
    if (special-char is currency symbol)
    {
    ....
    }
    else
    {
    ...
    }
}


问:
Would md5 hashes allow detection of synced files?
We have to develop our own file management system in Java web application. We need to sync files between our main server and client severs and find out whether all the client server has all the latest version of files.

Our files are in pdf, doc and xls format they changes every now and then as and when it is required.

What we are thinking of using MD5 checksum to find out hashcode of files on Main server and store it in database. Same would be there in Client Servers database. After comparing records on database we would come to know whether client servers are synced or not.

Please suggest if there are any better ways to do the same.

答:
Yes. You know all client files are sync'ed from the server. Therefore, if you keep sufficient history on the server, the client only needs to send its file version. Expensive MD5 calculations are unnecessary.

In the (hypothetical) case that a client can update its copy, you have a much more complicated problem anyway. You cannot support concurrent modifications (not with Excel or PDF) so you would need a checkout-modify-checkin system. At that point you're re-inventing a VCS, so you'd just choose SVN instead.

ContentLicense: CC BY-SA 3.0


问:
Differences in If... Else... statement
When I first started to learn programming I remember having an argument with my teacher about If Else statements. I was arguing that:

```<code> if {
      ...
 } else if {
      ...
 } ...
</code>```

is basically the same as:

```<code> if {
      ...
 else {
      if {
           ...
      } else {
           if {
                ...
           } else {
                ...
           }
      }
 }
</code>```

but he said they were completely different. After a while of arguing I accepted they are different. Now, over the years I have come back to this and looked over them to see the apparent major difference but for the life of me I cannot see it.

Can someone please clarify why exactly they  are different (apart from the obvious nesting)

答:
I'll be writing about the syntactical difference, since both forms are semantically equivalent (i.e. both programs compute the same result for any possible input).

An if-else-statement will be represented in the abstract syntax tree (AST) as a node with three children. One is the condition, one is the statement to be executed if the conditions evaluates to true and one is the statement that is to be executed if the conditions evaluates to false. The important observation here is that both statements are single statements. So what do you do if you want to execute more than one statement? You use a block and blocks are marked with curly braces in Java. A block statement may contain arbitrarily many statements (each separated by a semicolon).

So in your first example the parser will (aside from complaining about the missing condition) interpret your input as an if-node with a block statement as "then"-statement and a second if-statement as else-statement. In the second example the parser will recognize again an if-statement with a block as "then"-statement and a second block statement (with just a single if-statement in it) as else-statement.

Title: Differences in If... Else... statement


问:
Is LINQ to SQL dead?
Is there any reason to keep using Linq to SQL, or is it better to move to ORM techniques like EF, NHibernate etc.

We are using Linq to SQL in a new large enterprise application that will exist for a long time. The motivation for this new enterprise application is that the application was ordinary written in Visual Basic and since Microsoft stopped the support we where forced to rewrite the application. It’s seems that we are already there but this time with our DAL (Data Access Layer).

I have already read this article, but it only compare to EF's weakness.

答:
It's not dead as it still works, but if it's not being developed further then it can make sense to move to something else.

However, if it works for your application there's no point in changing for the sake of changing.

ContentLicense: CC BY-SA 2.5

Title: Is LINQ to SQL dead?


问:
Why does automated testing keep failing in my company?
We have tried to introduce developer automated testing several times at my company. Our QA team uses Selenium to automate UI tests, but I always wanted to introduce unit tests and integration tests. In the past, each time we tried it, everyone got excited for the first month or two. Then, several months in, people simply stop doing it.

A few observations and questions:

Does automated testing actually work? Most of of my colleagues who used to work at other companies have tried and failed to implement an automated testing strategy. I still haven't seen a real-life software company that actually uses it and doesn't just talk about it. So many developers see automated testing as something that is great in theory but doesn't work in reality. Our business team would love developers to do it even at a cost of 30% extra time (at least they say so). But developers are skeptics.

No one really knows how to properly do automated testing. Yes we have all read the unit testing examples on the internet, but using them for a big project is something else altogether. The main culprit is mocking/stubbing the database or anything else that is non-trivial. You end up spending more time mocking than writing actual tests. Then when it starts taking longer to write tests than code, that's when you give up.

Are there any good examples of unit tests/system integration tests used in a complex data centric web applications? Any open source projects? Our application is data centric but also has plenty of domain logic. I tried the repository approach at some point and found it pretty good for unit testing, but it came at the price of being able to optimize data access easily and it added another layer of complexity.

We have a big project undertaken by 20 experienced developers. This would seem to be an ideal environment to introduce unit testing/integration testing.

Why doesn't it work for us? How did you make it work at your company?

答:
You need to start with something small, simple to automate, and high value.  Pull down some sweet, low hanging fruit, and you will be able to sell the process.  Show how it saved someone a late night or a weekend call.  Then you can expand out from there.

To do automated testing well, you need someone who is a resource and an evangelist, and who has buy in from higher level managements.

Treat your automated test development like any other agile project.  Produce completed tests on a regular basis.

Adding from comment:  That is more of a management issue. Is the code considered "done" before it is documented? Before it is checked in? Before it includes and passes unit tests?

How you approach this really depends on your role. Are you a peer? If so, show others how it makes your code easier for them to reuse and maintain. Are you a lead? Pick your programmer who has the most code problems and help them add tests to avoid those problems. Are you a boss? Set it as a standard that "the code isn't done until the unit tests are in and passing.


问:
Detect frameworks and/or CMS utilized on websites in Firefox
I'm redesigning the website for my academic library and am examining other sites to determine to identify the technologies used. Things like:

Web frameworks

Javascript frameworks

Server-side technology

Content management system

Now I've had some real success in Firefox using plugins like Wappalyzer, Firebug, and the DOM Inspector. But some sites just don't display any of the info. I'm looking for using these tools, especially it seems it an enterprise-level CMS is being used.

Does anyone know of any other tools to detect this kind of data? Also with Firebug & the DOM Inspector, there is a lot of info. displayed and I wondered if there was a way to derive the presence of server-side technologies, CMS's, etc. within certain elements of a web page?

Also, if this question is more relevant to another Stack Exchange site, please let me know and I'll post it there instead.

Much thanks,

Jason

答:
http://guess.scritch.org/ does this for CMSs.

Just pop in the URL and it'll try to guess the CMS. In this case it tells me my blog is running wordpress 3.4.2 (which is correct, I just checked!)


问:
How to make Classic ASP interesting if you are stuck with it?
I used to work on a really small outsourcing company (4 programmers and the boss), then when the stress and the frequent long shifts made the situation unbearable I made the switch to a better paid job with a more relaxed schedule that allows me some more free time.

The problem, however, is that for the most part, everything is coded in Classic ASP that interfaces with a custom made C++ queueing system that stores everything in AS400 systems. My boss used to be one of the developers that made the initial efforts towards this, and naturally won't ever approve a switch to another languages / technologies despite the increasing difficulty that represents developing today business needs with yesterday tools.

I'm pretty much stuck coding with Classic ASP in the foreseeable future, and I'm struggling to find ways to make it at least interesting, as I used to work with .NET and Java previously, and I feel like I'm going backwards... Any advice?

答:
I work with Classic ASP at work too, and I've managed (to some extent) to make it interesting. Here are the steps:

Classic ASP can be coded either in VBScript or JScript (Javascript), without any modifications to the architecture. Switch to Javascript.

Gain access to various libraries: json2.js, underscore, mustache... You can look at Node.JS libraries or client-side libraries, with various amount of modifications.

Build a MVC framework or download one. You can manage templating and views by loading a file  from the server and read its content, and use one of the numerous JS templating libraries out there. For the controller, you can use variables in the query to redirect requests the way you would use the URL usually (less clean but it works).

You can also build a (simplified) REST API!

Create an ORM (if you have access to the database), or download one. You can even make some LINQ-to-SQL based on underscore.

Work on your views. Use advanced JS libraries like Angular or Backbone. Swtich from CSS to LESS, Stylus or SASS.

Make proxy-to-ugly-code classes. Those are classes made for the sole purpose of interfacing with the old ugly code so you don't have to touch it.


答:
If you're already using it and not encountering any difficulties, I'd stick with it on existing projects.

Linq2SQL is quite a nice, but limited, ORM - if you want to map your objects in more complex ways than the basic ones provided by Linq2SQL then you're going to be stuck. Microsoft did fix a few bugs when they came out with .net 4 but have stated that they're not going to be devoting resources to extending it.

I'd say if you have a fairly simple project which possibly has a limited lifespan then Linq2SQL is a decent lightweight choice so long as you're careful not to leak dependencies to Linq2SQL all over the place. For anything more I'd go with something else (NHibernate or EF for example) as Linq2SQL is pretty much a dead end.

Title: Is LINQ to SQL dead?

Body:
Is there any reason to keep using Linq to SQL, or is it better to move to ORM techniques like EF, NHibernate etc.

We are using Linq to SQL in a new large enterprise application that will exist for a long time. The motivation for this new enterprise application is that the application was ordinary written in Visual Basic and since Microsoft stopped the support we where forced to rewrite the application. It’s seems that we are already there but this time with our DAL (Data Access Layer).

I have already read this article, but it only compare to EF's weakness.


问:
git: having separate folder for development, why?
until now I was using dropbox as my main vcs (it is not, but for a single dev does the job pretty decent).

However I decided to give git a go and see if it fits my needs. Today I was reading this tutorial and at some point it says:

One of the things you should get used to is doing development in a
  separate area, not where you're serving your files from, for obvious
  reasons

I am doing development in django, and I can't find these "obvious reasons". Why can't I just use my project's folder to serve files to github?

I would be happy if someone clarified this for me now that I am new to git.

答:
I think the meaning is that you should release only stable and working versions, and not every  intermediate (maybe broken) version you get when you are working on a new feature.

So you should make sure that whenever someone logs on your website, it should work reasonably well.

This is done by developping in a git repository, and deploying a working versions in the production directory when you are ready to do so.

This tutorial suggests that you use fabric for such deployements. I have never used it, but it is a well know deployement framework, and might be a sane choice in most cases.


问:
Shift Javascript framework - What pattern is this? MVP, MVC or something else
I have created a very tiny framework to be able to get away from all the clutter while developing. The point of the framework is not to replace any library of choice but simply segregate the code to it's correct logic.

You can see the source on github along with a few code examples: https://github.com/erik-landvall/shift

While I try to describe the pattern I'm using I'm starting to wonder how this should be defined. And that's my question for you. What would you say the following chart symbolizes?

I like to think of it as an MVP pattern, but would like to hear your opinion.

Also, if you feel that the flowchart poorly resampling the code, give me a comment about it and I will attempt to fix it.

答:
MVP. In classic MVC, both the view and controller can access the model. In your case you have a coordinating object logical layer (the Presenter in your case, see diagram below) with knowledge of both the model and view, keeping those two isolated.

An additional comment to this. Fowler retired MVP from his catalog of patterns and split it into two: Supervising Controller and Passive View. I haven't looked into your code, but it's worth reading about them.


答: You're not supposed to expose your versioning control files on "published" servers as private information may be gleaned from them that would aid in an attack on your system.</p>

Title: git: having separate folder for development, why?

Body:
until now I was using dropbox as my main vcs (it is not, but for a single dev does the job pretty decent).

However I decided to give git a go and see if it fits my needs. Today I was reading this tutorial and at some point it says:

One of the things you should get used to is doing development in a
  separate area, not where you're serving your files from, for obvious
  reasons

I am doing development in django, and I can't find these "obvious reasons". Why can't I just use my project's folder to serve files to github?

I would be happy if someone clarified this for me now that I am new to git.


答:
You may think that i can guarantee there is no bugs in the codes, caus i am an excellent programer and i make no mistakes.

But the truth is you make mistakes sometime.

If you code in the directory which serving the clients, the clients get unstable service, let's say one client change his balance in the bank the moment you just modify a py file and make a wrong indent. As a result, the client may get a 500 error, what a urgly page it is.

Doing development in a separate area also guarantee you a runnable project. It also make sense if you doing development under a dev branch instead of a new directory.


问:
What's a good math textbook to have on my desk while studying Haskell?
I just started learning Haskell and it seems like you can't get too far in the language without being comfortable ( or at least exposed ) to certain branches of mathematics. Unfortunately I have major holes in such areas and am wondering what is a good introductory textbook that covers all the concepts Haskell uses?

For what it's worth, I have an undergraduate engineering degree ( not comp-sci or EE ), though the math I was exposed to was of the hand-wave and memorize variety. I also took an intro to comp-sci course where we did a few weeks of oCaml.

答:
I doubt any such book exists, and the closest you'll get would be from a book about Haskell.

The problem is that Haskell makes shallow use of concepts from a wide range of relatively deep mathematics. For anyone who isn't already a mathematician, learning enough of the math to help understand Haskell is very unlikely to be easier than just learning Haskell directly.

This is particularly true of category theory, where introductions aimed at mathematicians tend to use motivating examples that assume substantial prior knowledge of other fields of mathematics, and introductions aimed at Haskell programmers, unsurprisingly, use motivating examples in Haskell.

I recommend just continuing with Haskell. You can look up unfamiliar terms on Wikipedia--it often has definitions that are accessible enough that you can at least relate things back to programming. If you get stuck and need help on something specific, ask about it on Stack Overflow or the #haskell IRC channel on Freenode.

In short, just treat the math as opaque jargon--it's not like programming isn't full of that already, good grief--and learn what it means as you go. You can return to the mathematics itself later, if you're interested, to get a deeper understanding of the underlying abstractions.


答:
The hardest part of doing unit testing is getting the discipline to write tests first / early.  Most developers are used to just diving into code.  It also slows down the development process early on as you are trying to figure out how to write a test for the code.  However, as you get better at testing, this speeds up.  And because of the writing tests, the initial quality of the code starts off higher.

When starting out, try just to write tests.  Don't worry so much about mocking/stubbing things in the beginning.  Keep the tests simple.  Tests are code and can/should be refactored.  Though along those lines if something is hard to test, it could also be the design.  TDD does drive towards using most design patterns (in my experience, particularly the Factory pattern).

Make sure that the tests get a level of visibility.  Integrate them in the release process, during code review ask about them.  Any bugs found should get a test.  These things are where TDD shines.

Here are a couple of resources that I have found useful:

http://misko.hevery.com/attachments/Guide-Writing%20Testable%20Code.pdf

http://www.agitar.com/downloads/TheWayOfTestivus.pdf

Edit:

One thing to keep in mind when you are writing tests.  You are not trying to specify anything about the implementation of the code, only the behavior.  When you write code, you test it all the time.  Trying to execute it with debug statements and so on.  Writing tests formalizes this and provides a record of the tests that you have.  That way you can check your functionality confidently without accidentally skipping a test case that you remembered halfway through the development process.

Title: Why does automated testing keep failing in my company?

Body:
We have tried to introduce developer automated testing several times at my company. Our QA team uses Selenium to automate UI tests, but I always wanted to introduce unit tests and integration tests. In the past, each time we tried it, everyone got excited for the first month or two. Then, several months in, people simply stop doing it.

A few observations and questions:

Does automated testing actually work? Most of of my colleagues who used to work at other companies have tried and failed to implement an automated testing strategy. I still haven't seen a real-life software company that actually uses it and doesn't just talk about it. So many developers see automated testing as something that is great in theory but doesn't work in reality. Our business team would love developers to do it even at a cost of 30% extra time (at least they say so). But developers are skeptics.

No one really knows how to properly do automated testing. Yes we have all read the unit testing examples on the internet, but using them for a big project is something else altogether. The main culprit is mocking/stubbing the database or anything else that is non-trivial. You end up spending more time mocking than writing actual tests. Then when it starts taking longer to write tests than code, that's when you give up.

Are there any good examples of unit tests/system integration tests used in a complex data centric web applications? Any open source projects? Our application is data centric but also has plenty of domain logic. I tried the repository approach at some point and found it pretty good for unit testing, but it came at the price of being able to optimize data access easily and it added another layer of complexity.

We have a big project undertaken by 20 experienced developers. This would seem to be an ideal environment to introduce unit testing/integration testing.

Why doesn't it work for us? How did you make it work at your company?


答:
Adding lots of unit tests to a large pre-existing project is hard work. If you've already found a good mocking framework that works for you then you should have solved the hardest problem.

I suggest trying to add tests as you add features/fix bugs. Fixing bugs being the easiest one. Write a test that fails due to your bug and then fix the bug. At the same time you'll probably find yourself writing some simpler tests that do pass. Of course you really want to use a small and easily tested bit of code for this.

Once people start getting used to writing tests for the easier things you should hopefully find they write their code to be more testable.

I would also recommend that you measure the code coverage of your tests (I've used cobertura for Java in the past). You'll want to have some continous integration server running the tests and producing the metrics on a regular basis (every day, every check-in). If your fellow developers are keen then they will want to see the coverage increase over time and they can see the gaping coverage holes in some of your


答:
In many ways I agree with your team.

Most unit tests are questionable in value. Since the vast majority of tests seem to be too simple.

It is much harder to write good testable code than just working code. There's a large percentage of the developer community that believes in just get it to work, versus code/design quality in itself. And an even larger percentage who don't even know what quality code is.

It can take much longer to write the unit test code than the actual code itself.

Figuring out how to adequately test the more complicated code (ie. the stuff you really are interested in thoroughly testing) is beyond many developers capabilities.

Maintaining unit tests takes too much time. Small changes can have big ripple effects. The main goal of automated unit tests is to find out if changes broke the code. However, 99% of the time what ends up breaking are the tests and not the code.

With all the above problems, there still isn't a better way to be able to make code changes and have some level of confidence that something didn't unexpectantly break than automating your tests.

Some of the above can be alleviated to some degree by not going by the textbook of unit testing.

Many types of designs/applications are better tested by automating tests at the module/package level. In my experience, most coding errors are not because the code in a class was coded incorrectly but because the coder didn't understand how their class was supposed to work with other classes. I have seen a lot of bang for the buck in this type of testing. But once again, these tests are harder to write than unit (class level) tests.

It really boils down to whether the developers believe in the process or not. If they do, then they'll write good unit tests, find errors early and be proponents. If they don't, then their unit tests will be by and large useless and won't find any errors and their theory of unit tests being useless will be proven true (in their minds).

Bottom line is that I've never seen the full blown automated unit testing approach work for more than a couple months myself, but the idea of automated unit tests still persists although we are selective in what really needs testing. This approach tends to have far less critics and is more accepted by all the developers rather than just a few.


问:
Declaring functions in order to avoid explicit nested loops
My programming professor has told me that it is a good programming practice (at least in C/C++) to declare a function with the inner loop when nesting loops (not for loops, since when, i.e. looping through a multidimensional array this is very intuitive). For example, if I write

```<code>int main()
{
    while (cond1)
    {
        // ...(1)...
        while (cond2)
        {
            // ...(2)...
        }
    }
}
</code>```

then it is better:

```<code>type inner_loop(param)
{
    // ...(1)...

    while (cond2)
    {
        // ...(2)...
    }
}

int main()
{
    while (cond1)
    {
        inner_loop(param);
    }
}
</code>```

What improvements do imply this method? Is there any case in which this way of programming nested loops can be counterproductive? Thanks in advance.

答:
It adds a lot of readability at the expense of a little function call overhead, assuming you choose a better name than inner_loop.  Unless you truly need every ounce of performance, there aren't many situations where it isn't advisable.

One thing to take note is that it hides the complexity of your algorithm.  In general, this is a good thing.  However, I once saw similar nested loops in functions create an O(n^6) function out of what should be O(n) or better, simply because maintainers way down the road didn't notice the nested loops when they were working on the outer layers.


答:
There are advantages and disadvantages to both approaches.  Which approach you prefer should depend upon your team's style and guidelines.  For now, since your professor doesn't like a particular method, you shouldn't use it for the code you submit.

But don't get too hung up on either approach.

Calling a function from within the outer loop simplifies the task of analyzing the outer loop.  But it also increases the overhead from the stack creation / deletion with a large number of function calls.  It can also be more difficult to code since shared variables between the loops will need to be passed and returned with each function call.

Nested loops are a little quicker to write.  But they can drag out the length of the function.  Longer functions tend to be more brittle, which makes maintenance more difficult.  Longer functions are also more difficult to wrap your head around since they're ... longer.  It's a bit obvious, but worth pointing out.

There's a lot of existing C code written with nested loops without additional function calls.  So you'll see a lot of it in the wild.  However, just because "it's always been done that way" doesn't necessarily mean it's the right way.

Title: Declaring functions in order to avoid explicit nested loops

Body:
My programming professor has told me that it is a good programming practice (at least in C/C++) to declare a function with the inner loop when nesting loops (not for loops, since when, i.e. looping through a multidimensional array this is very intuitive). For example, if I write

```<code>int main()
{
    while (cond1)
    {
        // ...(1)...
        while (cond2)
        {
            // ...(2)...
        }
    }
}
</code>```

then it is better:

```<code>type inner_loop(param)
{
    // ...(1)...

    while (cond2)
    {
        // ...(2)...
    }
}

int main()
{
    while (cond1)
    {
        inner_loop(param);
    }
}
</code>```

What improvements do imply this method? Is there any case in which this way of programming nested loops can be counterproductive? Thanks in advance.


答:
1. Does it really work?

Yes, it does - if done properly. The point is that testers needs to adjust and extend their automated scripts after engineers implement new features.

2. No one is really experienced or knows how to properly do automated testing.

Get a consultant (someone who knows how it is done properly). Or, invest more time. The alternative is to have bigger testing team, who do the same testing manually (which is error prone).

3. We have a big project with 20 good experienced developers working on it. So it should be a great environment to introduce unit testing/integration testing. Why doesn't it work for us? How did you make it work in your company?

I wouldn't call them "good experienced developers", if they refuse to do unit tests. There are many great articles of the positive benefits of testing (both unit and integration testing), and at the end it boils down to how much a bug costs your company. For example, I work in a company where a quality matters, therefore unit and integration tests are unavoidable. You can easily find lots of articles which tells that unit tests only are reducing number of bugs by 30%! (Actually, it is in the 20-90% range, on average 30%, but it is still a lot.)

To make it work in your company, either hire a consultant, or assign this task to a senior engineer (it will take him a while to do it). And then, force everybody to stick to the rules.


答:
The advantage is that your main() is now simpler and easier to read (especially if  the body of the inner loop is at all complicated).

It would be a disadvantage if the inner loop were very obvious, since it would then take slightly more effort to read something that should take almost no effort.

Do whatever results in more readable code.


问:
Objective Metrics for Software Quality
There are various types of quality that can be measured in software products, e.g. fitness for purpose (e.g. end use), maintainability, efficiency. Some of these are somewhat subjective or domain specific (e.g. good GUI design principles may be different across cultures or dependent on usage context, think military versus consumer usage).

What I'm interested in is a deeper form of quality related to the network (or graph) of types and their inter-relatedness, that is, what types does each type refer to, are there clearly identifiable clusters of interconnectivity relating to a properly tiered architecture, or conversely is there a big 'ball' of type references ('monolithic' code). Also the size of each type and/or method (e.g. measured in quantity of Java byte code or .Net IL) should give some indication of where large complex algorithms have been implemented as monolithic blocks of code instead of being decomposed into more manageable/maintainable chunks.

An analyis based on such ideas may be able to calculate metrics that are at least a proxy for quality. The exact threshold/decision points between high and low quality would I suspect be subjective, e.g. since by maintainability we mean maintainability by human programmers and thus the functional decomposition must be compatible with how human minds work. As such I wonder if there can ever be a mathematically pure definition of software quality that transcends all possible software in all possible scenarios.

I also wonder if this a dangerous idea, that if objective proxies for quality become popular that business pressures will cause developers to pursue these metrics at the expense of the overall quality (those aspects of quality not measured by the proxies).

Another way of thinking about quality is from the point of view of entropy. Entropy is the tendency of systems to revert from ordered to disordered states. Anyone that has ever worked on a real world, medium to large scale software project will appreciate the degree to which quality of the code base tends to degrade over time. Business pressures generally result in changes that focus on new functionality (except where quality itself is the principle selling point, e.g. in avionics software), and the eroding of quality through regression issues and 'shoe-horning' functionaility where it does not fit well from a quality and maintenance perspective. So, can we measure the entropy of software? And if so, how?

答:
There's this fundamental problem with metrics.

Pretty much all of the metrics proposed have been shown, in the real world on real code, to be strongly or very strongly correlated with raw SLOC (source lines of code).

This is what killed Halstead's metrics, back in the 1970s.  (By accident one day, ca. 1978, I sat in on a talk by a new PhD about Halstead's metrics, in which he pointed this out.)

More recently, McCabe's cyclomatic complexity has been shown to be very strongly correlated with raw SLOC, to the point that the guy who did the study wondered out loud if McCabe's metric told us anything useful at all.

We've known for decades that big programs were more likely to have problems than small ones.  We've known for decades that big subroutines were likelier to have bugs than small ones.  Why do we need arcane metrics to tell us this, when looking at four printer pages spread out over a table should be convincing enough?

Title: Objective Metrics for Software Quality


答:
The advice to "develop in a separate area" is not specific to git. It's very popular to have a "development" environment that's separate from the "production" environment. The production environment (where you serve your files from) is only for code that has been tested and is complete and working.

The development environment is where you do the actual work. Here, you're free to break things, leave something half-finished and go to bed, try a feature and remove it, take your time working on a large change, roll back to an old version, really just do whatever you want.

And while you're messing with the development version, breaking it and putting it back together, all the user ever sees is the production version, which should be working properly at all times.

The tutorial is explaining how to set this up quickly with git, but git is not required to use multiple environments, and multiple environments are not required to use git.


答: This really has nothing to do with Git. It's a bad idea in general to edit a live website while your users are using it. You should make sure that your edits are complete, then "go live".


答:
I'm the author of the blog post in question. To clarify, what was meant was not that you shouldn't use the same directory to "serve files to GitHub", but rather you shouldn't do development in the same directory that your web server serves your content from.

Hope that clears things up.


问:
Design guidelines for this scenario in C#?
I have to create a validation system(I don't want to use Data Annotation or any other system) for my C# application using .Net Compact Framework, where I have an object which contains many other objects.

Many of the properties are dependent on each other means they have some sort of dependencies.

I can write a simple validator class which goes through all the properties
and checks them one by one with lots of if and else but I want to design something dynamic e.g. I should be able to specify list of dependencies on a property and specify a method which should be invoked during validation.

I mean some design guidelines would be appreciated ?

Example ( just for demo purpose ):

```<code>    public enum Category
        {
            Toyota,
            Mercedes,
            Tata,
            Maruti
        }

        class MyBigClass
        {
            public Category Category { get; set; }
            public double LowerPrice { get; set; }
            public double UpperPrice { get; set; }

            public SomeOtherObject OtherObject { get; set; }

public List<string> Validate()
        {
            List<string> listErrors = new List<string>();
            ParameterInfo pInfo = null;
            switch (Category)
            {
                case Category.Toyota:
                    pInfo = ParameterStorage.GetParameterInfo(PTYPE.Category_Toyota);
                    break;
                case Category.Mercedes:
                    pInfo = ParameterStorage.GetParameterInfo(PTYPE.Category_Mercedes);
                    break;
                case Category.Tata:
                    pInfo = ParameterStorage.GetParameterInfo(PTYPE.Category_Tata);
                    break;
                case Category.Maruti:
                    pInfo = ParameterStorage.GetParameterInfo(PTYPE.Category_Maruti);
                    break;
                default:
                    break;
            }

            if (LowerPrice < pInfo.Min || LowerPrice >= pInfo.Max)
            {
                listErrors.Add("LowerPrice");
            }

            if (UpperPrice > pInfo.Max || UpperPrice <= pInfo.Min)
            {
                listErrors.Add("UpperPrice");
            }

            return listErrors;
        }
        }

        public enum PTYPE
            {
                RATING,
                Category_Tata,
                Category_Toyota,
                Category_Mercedes,
                Category_Maruti
            }

            public class ParameterInfo
            {
                public PTYPE Type { get; set; }
                public int Min { get; set; }
                public int Max { get; set; }
                public int Default { get; set; }
            }

       public class ParameterStorage
        {
            private static Dictionary<PTYPE, ParameterInfo> _storage = new Dictionary<PTYPE, ParameterInfo>();
            static ParameterStorage()
            {
                _storage.Add(PTYPE.Category_Maruti, new ParameterInfo { Type = PTYPE.Category_Maruti, Min = 50000, Max = 200000 });
                _storage.Add(PTYPE.Category_Mercedes, new ParameterInfo { Type = PTYPE.Category_Mercedes, Min = 50000, Max = 800000 });
                _storage.Add(PTYPE.Category_Toyota, new ParameterInfo { Type = PTYPE.Category_Toyota, Min = 50000, Max = 700000 });
                _storage.Add(PTYPE.Category_Tata, new ParameterInfo { Type = PTYPE.Category_Tata, Min = 50000, Max = 500000 });
            }

            public static ParameterInfo GetParameterInfo(PTYPE type)
            {
                ParameterInfo pInfo = null;
                _storage.TryGetValue(type, out pInfo);
                return pInfo;
            }
        }
</code>```

In the above example I have a MyBigObject which contains some properties and some other objects and I have a storage class which keeps all the limits of properties which will be required to validate a property.

As described in the above example I have to get ParameterInfo for each property and then compare, I am looking for some kind of automatic way/dynamic way of doing the same.

答:
Objects that contain many other objects are probably doing too many things.

Requiring the programmer to specify dependencies is forcing them to repeat themselves, which will lead to errors/inconsistencies. If you can find a way to detect dependencies (statically or dynamically) that would be better.

Having a bundle of dependencies makes me concerned that your abstractions are not as clean as they should be. Dependencies between variables should (ideally) be isolated within a class. This might not apply in your case, but as a guideline - be sure you really need that tight coupling between variables in different classes.

And all that said, compact framework has had to do input validation for forever. Even if data annotations aren't supported, this is likely to be a solved problem.


问:
How do I avoid feature creep on a solo project?
So I have a program I'm worked on back in 2011 and all through 2012, but the last release was in December of 2011. I've been actively working on it, but feature creep lured its ugly head and now it is filled with tons on unfinished features.

The bad part is that as I implement a feature, a new one creeps in. What can I do to avoid feature creep in the future so I can actually get a release out in over a year?

The project is based around iOS and used to have releases around each iOS version update, but the last one was back with 5.1 (2011). I would like to be able to get that steady release cycle back, but it has proven too difficult.

答:
The answer is trite and frequently impossible: refuse to add additional features.

In more depth, the answer really comes down to what makes a new feature fall into the feature creep bin? If we assume that features that creep are those that are added to a project despite the fact that their functionality is only tangential to the intended use of the project and that the creeping features are useful, not superfluous, the answer is to move them to separate, but related tools. Use the Unix philosophy of building orthogonal tools and gluing them together.

From a project management standpoint, the answer is comparable. Decide how much time you are willing to devote to the next release and set a deadline. Estimate the features and cut enough to make the deadline. If there are stakeholders involved other than yourself, make them choose what matters most to them.

A good overview on Scheduling can be found on Joel on Software:

http://www.joelonsoftware.com/articles/fog0000000245.html


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

Example problem

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

Example problem 2

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

答:
A pointer lets you talk about some piece of information without specifying that information explicitly:

the value at location 0x007d32f8

the house at 105 West Street

A pointer to a pointer lets you talk about the location of something without specifying that location explicitly:

the address at location 0x012a0052

the street address listed on my business card

An easy to understand, practical use of pointers to pointers is when you want some other function or method to give you a pointer to some piece of data. Instead of asking for the data outright (after all, it might be very large) you can instead just ask for the address of the data. You can say: here's the address of a pointer that I'd like you to change so that it points to the data I want. To use the street address analogy, it's like telling your friend:

Please write your home address on this note pad.

The phrase "this note pad" specifies the location of a specific storage space, so it's like a pointer. Once the address is written down, it's like a pointer to your friend's home.

Another common example of a pointer to a pointer (pointed out in Brian's comment) is multidimensional arrays. In C, for example, a string is a null-terminated array of characters, and a string variable is just a pointer to the first element of the array. If you wanted to build an array of strings, you'd create an array of the pointers, each one pointing to a different string. If you wanted a 2-dimensional array of strings, you could repeat the process and create an array of arrays of strings.

Being able to talk about addresses allows for more sophisticated expression, both in code and in the real world.


答:
In my experience, it's easiest if you can have a development and release cadence that doesn't get in the way of what you want to get done. Here's how I've done it:

Write the features down, and give them a rating that reflects how much you want to work on it and how much you think it will benefit the user (it may be possible to engage actual users for this). Then write them in that order.

Before you check in/push a feature, make sure you have a stable, deployable build (strongly consider a CI system to facilitate that).

This way, you can just push a release after each feature if you want... or wait for a rollup that offers the value that you want a release to have.

Note:

A feature can never be given a higher priority than the one you're working on (or it can, but it can't interrupt the one you're working on). It can come next but never now. That means that when you go from now to next, you'll have the opportunity to cut a release build if you want.

Title: How do I avoid feature creep on a solo project?

Body:
So I have a program I'm worked on back in 2011 and all through 2012, but the last release was in December of 2011. I've been actively working on it, but feature creep lured its ugly head and now it is filled with tons on unfinished features.

The bad part is that as I implement a feature, a new one creeps in. What can I do to avoid feature creep in the future so I can actually get a release out in over a year?

The project is based around iOS and used to have releases around each iOS version update, but the last one was back with 5.1 (2011). I would like to be able to get that steady release cycle back, but it has proven too difficult.


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

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

答:
My two favorites:

Hiring consultants (freelance) just to add more production capacity, while they should invest in their own employees instead, by hiring consultants to bring new knowledge and coaching their existing people.

Hiring project managers that manage other project managers that manage other project managers that finally (think) they manage the development team. While they should let the team self manage and focus on business instead. I've seen software projects where they had more project managers than developers. Imagine the meetings.


答:
Follow these ground rules. Tests:

must run regularly! You can make tests run on every build, before/after every checkin, or just every morning. Automatically triggered is highly preferable to manually triggered. Because while in theory you can have everyone on the team be responsible for ensuring they run tests, if it's not automated, it probably isn't happening often enough! And if you don't run your tests often enough, they are both finding the bugs too late encouraging lots of broken tests, which leads on to point 2:

You are still only going to succeed if those tests, now running regularly, don't get in the way. By which we mean tests:

a. mustn't take too long to run (subjectively) for the value they provide! Make your tests blazing fast. Don't let people check in tests which are going to be a waste of your time to let them run!

b. mustn't be unreliable. Avoid multithreaded tests if at all possible. Apply engineering practices to your tests just like your other code: particularly - code review your tests!

c. mustn't be harder to fix and maintain than the actual code tested. Your coding velocity is really going to suck if a tiny one line change to your codebase requires you to fix 10 different tests.

And finally, rule number 3. Tests must not only fail to provide negative value, as in rule 2, they must provide positive value. Tests...

must actually be telling you something you care about when they fail! (No tests with obscure error messages, or merely giving you ridiculous complaints like 'you forgot to run the test on a Windows 2008 machine', please!).

One popular way to violate rule #3 is to test the wrong thing. This is sometimes because a test is too large or too unfocused. But usually it comes from not testing something a customer will care about, and testing irrelevant implementation details. (But sometimes testing implementation details makes an efficient test too - IMO it just takes practice deciding which.)

Conclusion: these ground rules point you in the general direction of a sustainable testing discipline, which is what you are desperately craving. When testing, ask yourself if this test is really sustainable and maintainable. Remember:

if tests aren't sustainable, they fall into disuse, and thereby become wasted effort

if tests aren't sustainable, you stop doing tests, and your team stops getting better at testing! And, final point:

Testing is actually hard. You should expect that your team's tests will basically suck when you start writing tests. Don't get discouraged. Do throw away old tests, whenever you notice they suck and are unsustainable.


答:
I think you may have to play the long game. One thing you can do to get some acceptance is to attempt to exhaustively unit test the next feature you write and then keep track of the number of bugs over time. You should hopefully find that the major bugs will be caught early on (particularly if you couple this with Test-Driven Design) and the number of regressions should be very low. After a period of time, say 1 year, compare the stats with non-unit tested features of similar complexity. If you can show that the number of new bugs and regressions is appreciably lower then you have provided a financial justification for it and it becomes harder for the product team to ignore.

I had a situation where I was able to use TDD and unit testing for a major feature. After the end of the development phase there wasn't a single bug reported in over 5 years. When a new -- and risky -- enhancement was requested, I was able to implement it and catch all the regressions in the unit tests.


答:
One of the most important lessons in development is knowing when its time to stop.

What typically happens is a developer adds a features.  That in turn inspires more ideas.  So more features get added.  That is, as you said, one of the ways a project becomes vaporware.  The developer never sees the project as 'finished', so it never gets released.

The habit you want to get into is to stop thinking in terms of a release/version as a 'finished' project.  Rather, look at development as a long-term process.  Think of releases as milestones along the path to what you one day hope the program will be.  Thus, a release/version is just a snapshot of where you are in the longer term process... a snapshot thats been well rounded out and tested.

What you can do, on the practical side, is sit down and spec out your next release.  It doesn't have to be terribly thorough.  Write down the 3-5 new major pieces of functionality you believe are essential for the next release. (actual number of features may vary depending on the type of app, not counting bug fixes or minor gui changes)  Work on those.  If you come up with other ideas, thats fine... just make notes and implement them in the following release.  When you get those 3-5 items done, your release is ready for beta.

When I start a new application, I typically think about the final 'vision' for the app.  That, to me, is what I want in version 3 of the app.  With that benchmark, I have an idea of what will make solid version 1 - just the basics.

Summary:

Each release does not have to be the finished 'vision' of the project.  Just a milestone towards that vision.


答:
It is interesting that the business is more pro-testing than developers!  It sounds to me like your biggest challenge will be to overcome your developers resistance to change; they need to re-define their understanding of their jobs to include unit testing.

Nothing can help you more than early unit-testing successes to help your developers overcome their resistance to writing these tests.  If you push them to do something new, make sure you push first for something with a nearly guaranteed reward.

@SkipHuffman touched on this, but I'm going to say it outright.  Some things are much more suited to automated testing than others.  For the first pass, I would NOT test the database or the UI.  Input from a database can be extremely difficult to set up and tear down.  UI output tests tend to be quickly broken by look and feel changes that are completely irrelevant to your tests.

What I'd call "middleware" is perfect for unit testing.  Code that has clearly defined input and output conditions.  If you follow the DRY principle (Don't Repeat Yourself), you will have written some little classes or functions to solve recurring problems that are unique to your application.

Unit testing is a great tool to limit the risk of changing existing internal components.  Write unit tests before changing an internal component that has worked for a long time.  These tests prove that the currently working functionality is preserved.  When you have made your change and all unit tests pass, you know you haven't broken anything "downstream."  If you do find a downstream issue, add a unit test for it!

Ron Heifitz would say to "address conflicts in the values people hold, or to diminish the gap between the values people stand for and the reality they face. Adaptive work requires a change in values, beliefs, or behavior."  After you overcome the human resistance to change, you can branch out into more difficult testing areas as appropriate.


答:
The main culprit is mocking/stubbing the Database or anything not simple.

And there is your problem.

Everyone makes good points about how to integrate unit testing into your environment. How to force people to do it enough that they see the practical value and it "sticks". But if it's super painful to do, and/or provides no benefit, it won't stick.

Stubbing out a database should be dead simple. Instead of your interface going to some DB backing to provide its results, you put in a simple hardcoded object. If you can't do that, then your design/architecture has problems. Your code assumes it is going to a database, or you don't have the interface abstraction to vary it.

This isn't simply a testing/quality concern. As soon as you want to change DB providers, or go to the cloud instead, or support unconnected mobile apps your design simply fails. If you cannot support the simplest of flexibility cases, you certainly cannot support the more complex things that your business will inevitably require.


问:
Does giving a developer a slower development machine result in faster/more efficient code?
Suppose I give my developers a screaming fast machine.  WPF-based VS2010 loads very quickly.  The developer then creates a WPF or WPF/e application that runs fine on his box, but much slower in the real world.

This question has two parts...

1) If I give a developer a slower machine, does that mean that the resulting code may be faster or more efficient?

2) What can I do to give my developers a fast IDE experience, while giving 'typical' runtime experiences?

Update:

For the record, I'm preparing my even-handed response to management. This isn't my idea, and you folks are helping me correct the misguided requests of my client.  Thanks for giving me more ammunition, and references to where and when to approach this.  I've +1'ed valid use cases such as:

- specific server side programming optimizations

- test labs

- the possibly buying a better server instead of top of the line graphics cards

答:
1) If I give a developer a slower machine, does that mean that the resulting code may be faster or more efficient?

No. Good Developers are spoiled. If they see they get bad tools at your company, they will go work somewhere else. (Good developers usually have the choice to go someplace else)


问:
Best practices for usage of "shall" and "must" when writing requirements
I sent out an email earlier reminding our developers that

the use of the word "shall" in your derived requirements should not follow over to your functional requirements. When writing functional requirements the word "must" is used to describe the function a derived requirement must do.

Derived = System Shall be requirement

Functional = System must do requirement*

It was sent back by one of our seniors that this was wrong and that "shall" should be used in every requirement.

Am I wrong here, and should "shall" be used in every requirement?  I haven't been able to find anything to back that up.

答:
Not sure where you came to the conclusion that shall and must belong at separate levels of documentation.  That's a pretty arbitrary distinction that isn't backed by any source I know of.

Shall and must are lexically equivalent.  It's an action that is required.

Whether you use shall or must really depends upon the rest of the document that you are writing within and what makes grammatical sense for that particular sentence.

So yes, you're wrong.  But you're also wrong on always using shall instead of must.  They represent the same degree of obligation.

OwnerDisplayName: Tim Lieberman

ContentLicense: CC BY-SA 4.0


答:
RFC 2119 "Key words for use in RFCs to Indicate Requirement Levels" goes into specifics of what different words on requirements mean.

The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED",  "MAY", and   "OPTIONAL" in this document are to be interpreted as described in RFC 2119.

From this document:

MUST is equivalent to REQUIRED and SHALL indicating that the definition is an absolute requirement.

MUST NOT is equivalent to SHALL NOT and indicates that it is an absolute prohibition of the specs.

SHOULD is equivalent to RECOMMENDED means that there are valid reasons to ignore a particular requirement, but the implications need to be weighed.

SHOULD NOT and NOT RECOMMENDED means that a particular behavior may be acceptable or useful, but again, the implications need to be weighed.

MAY means OPTIONAL and that the requirement is truly optional.  Interoperability with different systems that may or may not implement an optional requirement must be done.

Following this RFC SHOULD be done to help ensure consistency of communication between one's internal documents and the standards world at large.

Title: Best practices for usage of "shall" and "must" when writing requirements

Body:
I sent out an email earlier reminding our developers that

the use of the word "shall" in your derived requirements should not follow over to your functional requirements. When writing functional requirements the word "must" is used to describe the function a derived requirement must do.

Derived = System Shall be requirement

Functional = System must do requirement*

It was sent back by one of our seniors that this was wrong and that "shall" should be used in every requirement.

Am I wrong here, and should "shall" be used in every requirement?  I haven't been able to find anything to back that up.


问:
Is path coverage stronger than condition coverage?
I have encountered (even in literature) two contradicting opinions related to path vs condition coverage (not branch or edge!). Some say Path coverage is stronger than the condition coverage, some say the opposite.

Having code like this:

```<code>If(X<0 OR X>100)
   DoStuff();
</code>```

Path coverage - 1 test case is needed to cover the path. With X=-1, the second expression will not be tested and possible bug will be missed.

Condition coverage - test cases X=-1 and X=100 are needed to test both conditions.

Am I missing something or condition coverage is really stronger than path coverage?

Condition coverage (ISTQB):

Our next level of coverage is called condition coverage. The basic concept is that, when a decision is made by a complex expression that eventually evaluates to TRUE or FALSE, we want to make sure that each atomic condition is tested both ways.

Practical Insight Into CMMI

Condition coverage measures the true and false outcome of each Boolean
  subexpression.

References:

Software Testing: Principles and Practices from Srinivasan Desikan,Gopalaswamy Ramesh: page 61

Condition coverage is a much stronger criteria than path coverage,
  which in turns is a much stronger criteria than statement coverage.

答:
Neither one is "stronger" in the mathematical sense:

Path coverage does not imply condition coverage, as illustrated by an example in your question

Condition coverage does not imply path coverage, as illustrated by your comment (condition IF(A&&B) with pairs A=TRUE, B=FALSE and A=FALSE, B=TRUE).

This means that claims that either side is somehow "stronger" would be invalid.

If you "upgrade" the condition coverage to modified condition/decision coverage, however, the answer would be "yes": MC/DC always implies covering the path, but covering the path may not necessarily imply even covering the condition, let alone MC/DC.

However, this does not imply that 100% MC/DC is always better than path coverage: the tradeoff is that it comes at much steeper "price" than a 100% path coverage due to the need to write more tests. Sometimes, a lot more. This has a potential of complicating the maintenance of your test suite.

I think it is a good idea to maintain a good balance between condition/decision coverage and path coverage by path-covering simple conditions (such as argument checks of the "null or empty" sort) and condition/decision-covering statements with complex business logic.


答:
Path coverage is strictly more complete than branch coverage.

An example pulled from Wikipedia:

two properties of the cyclomatic complexity, M, for a specific module:

M is an upper bound for the number of test cases that are necessary to achieve a complete branch coverage.

M is a lower bound for the number of paths through the control flow graph (CFG).

```<code>if( c1() )
   f1();
else
   f2();

if( c2() )
   f3();
else
   f4();
</code>```

In this example, two test cases are sufficient to achieve a complete branch coverage, while four are necessary for complete path coverage. The cyclomatic complexity of the program is 3 (as the strongly connected graph for the program contains 9 edges, 7 nodes and 1 connected component) (9-7+1).

However, as noted a little further down (bolding mine for emphasis):

Unfortunately, it is not always practical to test all possible paths through a program. Considering the example above, each time an additional if-then-else statement is added, the number of possible paths doubles. As the program grew in this fashion, it would quickly reach the point where testing all of the paths was impractical.

EDIT

Okay, I think I see where @user970696 in the comments is coming from.  If I understand right, the answer is still strictly path coverage.  The only time you'll have a "special" result different from branch coverage is when there's functions being called in the conditional, which may or may not run due to short-circuiting.

But when that happens, they count as part of the path.

Take this, for example:

```<code>if (a() && b()):
   foo()
else:
   bar()
</code>```

Branch coverage has 2 cases:

(a() && b()) == True

(a() && b()) == False

Conditional coverage has 3 cases:

a() == False

a() == True && b() == False

a() == True && b() == True

Path coverage has the same 3 cases:

Path: a(), bar()

Path: a(), b(), bar()

Path: a(), b(), foo()

However, when you add in a second if statement, as mentioned above, the number of paths will multiply - while each individual if statement stays at the same complexity.

Title: Is path coverage stronger than condition coverage?

Body:
I have encountered (even in literature) two contradicting opinions related to path vs condition coverage (not branch or edge!). Some say Path coverage is stronger than the condition coverage, some say the opposite.

Having code like this:

```<code>If(X<0 OR X>100)
   DoStuff();
</code>```

Path coverage - 1 test case is needed to cover the path. With X=-1, the second expression will not be tested and possible bug will be missed.

Condition coverage - test cases X=-1 and X=100 are needed to test both conditions.

Am I missing something or condition coverage is really stronger than path coverage?

Condition coverage (ISTQB):

Our next level of coverage is called condition coverage. The basic concept is that, when a decision is made by a complex expression that eventually evaluates to TRUE or FALSE, we want to make sure that each atomic condition is tested both ways.

Practical Insight Into CMMI

Condition coverage measures the true and false outcome of each Boolean
  subexpression.

References:

Software Testing: Principles and Practices from Srinivasan Desikan,Gopalaswamy Ramesh: page 61

Condition coverage is a much stronger criteria than path coverage,
  which in turns is a much stronger criteria than statement coverage.

Body:
Path coverage is strictly more complete than branch coverage.

An example pulled from Wikipedia:

two properties of the cyclomatic complexity, M, for a specific module:

M is an upper bound for the number of test cases that are necessary to achieve a complete branch coverage.

M is a lower bound for the number of paths through the control flow graph (CFG).

if( c1() )
   f1();
else
   f2();

if( c2() )
   f3();
else
   f4();

In this example, two test cases are sufficient to achieve a complete branch coverage, while four are necessary for complete path coverage. The cyclomatic complexity of the program is 3 (as the strongly connected graph for the program contains 9 edges, 7 nodes and 1 connected component) (9-7+1).

However, as noted a little further down (bolding mine for emphasis):

Unfortunately, it is not always practical to test all possible paths through a program. Considering the example above, each time an additional if-then-else statement is added, the number of possible paths doubles. As the program grew in this fashion, it would quickly reach the point where testing all of the paths was impractical.

EDIT

Okay, I think I see where @user970696 in the comments is coming from.  If I understand right, the answer is still strictly path coverage.  The only time you'll have a "special" result different from branch coverage is when there's functions being called in the conditional, which may or may not run due to short-circuiting.

But when that happens, they count as part of the path.

Take this, for example:

if (a() && b()):
   foo()
else:
   bar()

Branch coverage has 2 cases:

(a() && b()) == True

(a() && b()) == False

Conditional coverage has 3 cases:

a() == False

a() == True && b() == False

a() == True && b() == True

Path coverage has the same 3 cases:

Path: a(), bar()

Path: a(), b(), bar()

Path: a(), b(), foo()

However, when you add in a second if statement, as mentioned above, the number of paths will multiply - while each individual if statement stays at the same complexity.


答:
Is there anyone at your company with extensive experience doing automated testing?

If not, automated testing initiatives will probably fail. Automated testing is a skill, like many other skills in programming, and if you don't have anyone with experience doing it, it's not easy to tell whether an automated test is a good automated test with real value, or a bad one which will fail randomly / require frequent updates / doesn't actually exercise any interesting code.

Does that someone have leadership power? Are they able to demand change?

If no one listens, it doesn't matter if they say the test is no good. (Note that the leadership power doesn't have to be formalized. Having a team that cares is good too.)

Are you developing tools and processes to make automated testing easier to implement and integrate into the development cycle?

Developers are lazy. You need to make the things you want them to do easy to accomplish, and the things you don't want them to do more difficult to accomplish. You should make sure the testing libraries make it easy to do the tasks associated with test setup and teardown, especially environment-related setup, like test databases or the like. (Mocking the database is discussed in some of these comments but should be used with caution. A real database should be easy to spin up, and lets you test the interaction of components and process lifecycles, often more important and more effective than unit-testing an individual data-accessor.)

You should also make sure that your IDEs have a good way to launch the test suite. You should run the test suite often so that people notice when it fails rather than letting it linger in misery. Developers also respond well to feedback, e.g. an automated integration system reverting their changes if they've broken a test. Or, better, positive feedback: an automated integration system which catches bugs, and saves you from breaking things.


问:
Should I be wary of signing a non-disclosure agreement with someone I just met?
1/22/12 update in case you were puzzled as to why I haven't accepted an answer: Pretty much all of the answers make the obvious point that working for him would have been silly, but none of them seemed to answer the question.

tl;dr: Some guy I just met says he wants me to join his company. Before he shows me what they do, he wants me to sign a non-disclosure agreement. Is this weird?

I'm traveling right now. Someone who saw me coding seemed to think I was smart or something and started talking with me. He explained that he owns a software company, told me a bit about what it does and told me that he was looking for a programmer who would work for a stake in the company. He explained that the company's product is being developed rather secretly, so he couldn't tell me much. But he did tell enough about the product to convince me that he's not completely making this up, which is a decent baseline.

He suggested that he show me more of what he's been working on and, after seeing that, I decide whether I want to join. Because of the secrecy behind the product, he wants me to sign a non-disclosure agreement before we talk.

I'm obviously somewhat skeptical because of the random nature by which we met.

In the short term, I'm wondering if I should be wary of signing such an agreement. He said it would be easier to show me the product in person rather than over the internet, and I'm leaving town tomorrow, so I'd have to figure this out by tomorrow. If I decide to talk with him, I could decide later whether I trust that it's worth spending any time on this company.

The concept of being able to avoid telling a secret seems strange to me for the same reason that things like certain aspects of copyright seem strange. Should I be wary of signing a non-disclosure agreement? Is this common practice?

I don't know the details of the agreement of which he was thinking, (If I end up meeting with him, I'll of course read over the agreement before I decide whether to sign it.) so I could consider alternatives according to the aspects of the agreement. Or I could just consider the case of an especially harsh agreement.

This question seems vaguely related.
Do we need a non-disclosure agreement (NDA)?

Thanks

答:
Other answers focused on his business proposition. I agree with those comments, but no answers gave me satisfying answers to the question.

I ran into similar situations a few more times over the past year, and I heard about similar situations involving other people. I actually never signed the agreements, but the aforementioned other people did in similar situations. Considering all of those situations, I think can answer this question now.

The person I just met probably thought he has some world-changing idea that he needs to protect. Not only was it probably not a world-changing, money-making idea, it was also probably particularly boring.

He was probably not trying to con me in any way other than trying to get me to work for free. That is, he's probably not trying to get lots of people to sign NDAs with him so that he can later claim that their success belongs to him. Rather, he was probably just afraid for silly reasons.

I find it hard to evaluate how interesting an ideas without having heard it, so I wouldn't be able to tell whether it is so amazing before agreeing not to disclose it. Moreover, the idea is probably particularly boring because the secrecy within which he has been sharing it has prevented it from growing.

If I knew that it was going to be a big new idea that would be interesting/useful to me under the terms of the NDA (without me working for him), it would make sense for me to sign it and hear his idea; I don't think I need to worry about him trying to con me based on this agreement alone. That said, the idea is probably particularly boring, so listening to him explain the idea would probably have been a waste of time.


答:
The main difference between condition coverage and path coverage is that condition coverage is local to some control structure (if, while, for, ...), whereas path coverage is global to the whole program and therefore includes all possible combinations of branches (not conditions).

On the local point of view, condition coverage is stronger.

On the global point of view, path coverage is stronger. So stronger that it is usually not achievable.


问:
How to setup TDD environment
In TDD, is it good practice to keep the tests in the same directory as the code its testing or is it better separate the tests in either a different directory or a separate project.

Would it be the same for a web site where you have the aspx/c# pages in one directory?

答:
Tests should go into a separate directory.  I wouldn't do a separate project because you want the tests to come along when the project is opened.

This way you can deploy only the code into production without having to separate out the tests.

Title: How to setup TDD environment


答:
Test code shouldn't be compiled into the final build.  TDD or not, tests belong in a separate directory structure (possibly in the same package) so that the build process can ignore all the tests when building the package.

Keeping tests in the same package, however, allows for some behind the scenes access that tests may need that a public interface doesn't want to provide.  There is debate on this point.

As a Java programmer (my apologies, I don't have access to a c#/.net environment), I find that unit testing the huge front end public call with all of the various variables daunting (often involving lots of mocks to get the right objects through to the right tests).  Making something protected (rather than private or exposing it to public) means that something in the same package (be it in another directory) will still be able to invoke it.

Title: How to setup TDD environment

Body:
In TDD, is it good practice to keep the tests in the same directory as the code its testing or is it better separate the tests in either a different directory or a separate project.

Would it be the same for a web site where you have the aspx/c# pages in one directory?


答:
Is it weird? Yes

Is it uncommon? No

Should you be wary? Always

I've worked with several start-ups.  Some were far more clandestine than others.  Personally, I was always  a little put off when someone withheld sharing their ideas without a non-disclosure agreement.  If there is an idea so good that someone can steal it and make millions of dollars on it after an hour of conversation, I haven't been privy to it.  It's difficult to make lots of money, and it should be.

The execution is what should be protected by an NDA.  However, almost everyone (that I've dealt with) operating at the stage where they are willing to offer a stake in the company doesn't have much done yet.

I read a great post by Jeff Atwood about this same thing, it helped me clarify my thinking on the subject.

Building a company on sweat equity is tough, and (personally) I have yet to see it succeed.  Every time I have agreed to work for part-ownership and no salary it didn't pay off.

In summary, I would sign the NDA if:

They are willing to fully explain the idea before signing

The idea seems solid

There is solid research behind the idea. Market research, technology research, and real numbers are a plus. Don't accept the answer that idea X is so new there is no way to test it's feasibility

I would consider working for the company if:

They have a business plan (and understand it)

They have reasonable expectations of return, based on real data (not: I know this product will make a billion bucks, I JUST KNOW IT)

They have reasonable expectations of your commitment.  I have found that companies that offer equity expect you to devote your every waking second to the business.  In many cases, this is completely unreasonable.

They are willing to pay you at least a modest salary.  Things often take longer than expected, don't go bankrupt in the meantime.

Most importantly, as a partner, there is no part of the business that is secret or off-limits to you.  This is a major red flag, don't be assured that "someone else is handling it" or that "you don't have to worry about it."  It's fine to trust your partners, but reserve your right to verify.

Title: Should I be wary of signing a non-disclosure agreement with someone I just met?

Body:
1/22/12 update in case you were puzzled as to why I haven't accepted an answer: Pretty much all of the answers make the obvious point that working for him would have been silly, but none of them seemed to answer the question.

tl;dr: Some guy I just met says he wants me to join his company. Before he shows me what they do, he wants me to sign a non-disclosure agreement. Is this weird?

I'm traveling right now. Someone who saw me coding seemed to think I was smart or something and started talking with me. He explained that he owns a software company, told me a bit about what it does and told me that he was looking for a programmer who would work for a stake in the company. He explained that the company's product is being developed rather secretly, so he couldn't tell me much. But he did tell enough about the product to convince me that he's not completely making this up, which is a decent baseline.

He suggested that he show me more of what he's been working on and, after seeing that, I decide whether I want to join. Because of the secrecy behind the product, he wants me to sign a non-disclosure agreement before we talk.

I'm obviously somewhat skeptical because of the random nature by which we met.

In the short term, I'm wondering if I should be wary of signing such an agreement. He said it would be easier to show me the product in person rather than over the internet, and I'm leaving town tomorrow, so I'd have to figure this out by tomorrow. If I decide to talk with him, I could decide later whether I trust that it's worth spending any time on this company.

The concept of being able to avoid telling a secret seems strange to me for the same reason that things like certain aspects of copyright seem strange. Should I be wary of signing a non-disclosure agreement? Is this common practice?

I don't know the details of the agreement of which he was thinking, (If I end up meeting with him, I'll of course read over the agreement before I decide whether to sign it.) so I could consider alternatives according to the aspects of the agreement. Or I could just consider the case of an especially harsh agreement.

This question seems vaguely related.
Do we need a non-disclosure agreement (NDA)?

Thanks


问:
Why does automated testing keep failing in my company?
We have tried to introduce developer automated testing several times at my company. Our QA team uses Selenium to automate UI tests, but I always wanted to introduce unit tests and integration tests. In the past, each time we tried it, everyone got excited for the first month or two. Then, several months in, people simply stop doing it.

A few observations and questions:

Does automated testing actually work? Most of of my colleagues who used to work at other companies have tried and failed to implement an automated testing strategy. I still haven't seen a real-life software company that actually uses it and doesn't just talk about it. So many developers see automated testing as something that is great in theory but doesn't work in reality. Our business team would love developers to do it even at a cost of 30% extra time (at least they say so). But developers are skeptics.

No one really knows how to properly do automated testing. Yes we have all read the unit testing examples on the internet, but using them for a big project is something else altogether. The main culprit is mocking/stubbing the database or anything else that is non-trivial. You end up spending more time mocking than writing actual tests. Then when it starts taking longer to write tests than code, that's when you give up.

Are there any good examples of unit tests/system integration tests used in a complex data centric web applications? Any open source projects? Our application is data centric but also has plenty of domain logic. I tried the repository approach at some point and found it pretty good for unit testing, but it came at the price of being able to optimize data access easily and it added another layer of complexity.

We have a big project undertaken by 20 experienced developers. This would seem to be an ideal environment to introduce unit testing/integration testing.

Why doesn't it work for us? How did you make it work at your company?

答:
It is my strong opinion that unit tests' value is largely underestimated by many teams because of several factors, many already highlighted in the answers.

Often developers are under pressure to "get things done", so proving that a code block works is a sufficient proof for the customer. This almost always applies to consulting company and human-driven QA: if the customer doesn't require unit testing and coniders a live demo sufficient then the customer has totally failed since he's going to sign approval for code that might hide faults.

Often developers are frustrated. Being a programmer is a hard job: finishing a task and going to the next is satisfying, so everyone wants to hurry and finish. Until they get hit by a bus with a major bug that rises months after original QA. In this scenario, automated and continuous QA is a management's problem rather than developers (they'll still get paid for their work, perhaps overtime).

But there is an exception

I strongly believe that the acceptance of the automated test model is a function of the "humanness" of the tests being done. If you are testing a web module with a front end, you are more likely, despite tools such as Selenium, to fill the form by yourself, see the result and believe in determinism. You'll forget to re-run tests later or you'll just be too lazy to do old tests again, and this is why bugs sometimes get discovered later. To leverage this, a strong modularization of the code and strict rules on "modifying old code" have been proved acceptable in a banking environment (in my personal work experience).

Instead, if the developer is in charge of developing a highly-automated and high-volume-data module, he'll be more likely to write thorough unit tests and submit them to the test batches. This because filling a large XML payload with data converted from an external data source (mocked or not) is not a human-prone job. Some test developers will eventually build a tiny and funny front end for this specific kind of tests. When I worked at my Master's thesis I was working on a logging bus that handled 6000+ syslog messages per second and I had to measure packet loss and corruption: I naturally wrote unit and stress tests for almost all components, especially the Syslog parser.

In order to make developers more unit test-prone

I believe they must be forced to. If you are a smart customer you'll require your consultants to run the full test suite at every QA. If you are a good team leader you may think assigning the following task to a smart developer: build an inner-test platform. That has nothing to see with inner effect platform antipatter, but instead is a set of helper classes, database mocks, configurations, parsers, converters, swiss army knives to help developers build tests in no time.

Current testing platforms such as NUnit are general-purpose and allow you to verify generic assertions. Correctly using dependency injection and project-specific factories help developers write less code for tests and be happier. I haven't had the chance yet to experiment this on a full project, I can't provide real-life feedback.


问:
We are spending more time implementing functional test than implementing the system itself, is this normal?
Basically, we have three main projects, two of them are web services, and the other is a web application. While I'm satisfied with covering as much as we can of our web services with functional tests (all three projects have their proper unit tests), functional tests for the web application are taking a lot of developer time to get implemented. By a lot I mean two times, or sometimes more, the time that takes to implement the functionality being tested with unit test included.

The manager policy is to test every single functionality we add, even if is not business critical (i.e a new C.R.U.D).

I do agree with testing all of the web services functionality, because is hard to manually test them, and also, this tests run fast and don't take to much to implement.

So, what's the value in spending more time writing functional test, than writing system code, unit test and fixing QA tikets? Is this normal? Shouldn't we be writing functional tests only for critical functionality and let QA to do regression tests over no critical functionality?

Note: we are not developing medical software or NASA software or nothing that critical.

答:
This is about quality.

If you need to get the market - you will develop your app as quickly as possible. You can even don't have automatic tests at all =) but you will give your app to your auditory before your competitors.

But if you know that your auditory won't go away you will do anything you can not to disappoint them. Every bug ticket will bring down your reputation. Imagine that one bug will remove 50 percent of your reputation, the next - another 25 percent and so one. So can there be too many tests?


答:
They are many reasons why introducing automated testing might fail. I think that it boils down to the fact that programmers tend not to change their coding habits and are not fully capable of embracing unit testing.

Many people who want to start with automated testing try to introduce them for an existing code base. They will try to write integration tests which test a lot of functionality of existing application at once. Such integration tests are notoriously too hard and too expensive to maintain. Advice: Introduce automated tests for a new code base.

Unit tests are good tests to be automated. Everything above (integration tests, component tests, system tests) can be also tested automatically, but the cost-benefit ratio rapidly declines the more functionality is tested at once. This negative effect is amplified, if you build such tests on poorly unit-tested functionality. Advice: Introduce automated tests on the unit test level and build automated integration tests on a solid foundation of unit tests.

From the points above much of the success of automated testing depend on how effective the unit tests are. You have effective unit tests if you feel productive with unit tests. When people start with unit testing, they tend to retrofit their existing code and coding habits into unit tests. Ironically this is the hardest way to learn unit testing. Also unit testing requires you change the way how you code (for instance applying the SOLID principles ). Most programmers soon stop writing unit tests because they think that the learing curve is too steep and find it awkward to wrap unit tests around a not so testable designed code. Advice: Learn unit testing from the ground up with new code and deal with the fact that you need to change your coding habits.

There are a lot other factors, but I found that for most programmers it is troublesome to change their way to code. Code written without test just looks different. If you cannot squeeze your code into a testable design, you will very probably fail to write effective unit tests. This destroys the ground for effective automated testing.

I experienced that by myself and I am now happy to work in a company which successfully introduced automated tests. I could write a lot more about the other factors, but I think that coding habits and unit testing are the most important ones. Luckily there are others who have more experience than me and fill books with their know-how. One of these books is Brownfield Application Development in .NET which I can really recommend, since you are using the Microsoft technology stack.


问:
What should you bring to the table as a Software Architect?
There have been many questions with good answers about the role of a Software Architect (SA) on StackOverflow and Programmers SE. I am trying to ask a slightly more focused question than those. The very definition of a SA is broad so for the sake of this question let's define a SA as follows:

A Software Architect guides the
  overall design of a project, gets
  involved with coding efforts, conducts
  code reviews, and selects the
  technologies to be used.

In other words, I am not talking about managerial rest and vest at the crest (further rhyming words elided) types of SAs. If I were to pursue any type of SA position I don't want to be away from coding. I might sacrifice some time to interface with clients and Business Analysts etc., but I am still technically involved and I'm not just aware of what's going on through meetings.

With these points in mind, what should a SA bring to the table? Should they come in with a mentality of "laying down the law" (so to speak) and enforcing the usage of certain tools to fit "their way," i.e., coding guidelines, source control, patterns, UML documentation, etc.? Or should they specify initial direction and strategy then be laid back and jump in as needed to correct the ship's direction?

Depending on the organization this might not work. An SA who relies on TFS to enforce everything may struggle to implement their plan at an employer that only uses StarTeam. Similarly, an SA needs to be flexible depending on the stage of the project. If it's a fresh project they have more choices, whereas they might have less for existing projects.

Here are some SA stories I have experienced as a way of sharing some background in hopes that answers to my questions might also shed some light on these issues:

I've worked with an SA who code reviewed literally every single line of code of the team. The SA would do this for not just our project but other projects in the organization (imagine the time spent on this). At first it was useful to enforce certain standards, but later it became crippling. FxCop was how the SA would find issues. Don't get me wrong, it was a good way to teach junior developers and force them to think of the consequences of their chosen approach, but for senior developers it was seen as somewhat draconian.

One particular SA was against the use of a certain library, claiming it was slow. This forced us to write tons of code to achieve things differently while the other library would've saved us a lot of time. Fast forward to the last month of the project and the clients were complaining about performance. The only solution was to change certain functionality to use the originally ignored approach despite early warnings from the devs. By that point a lot of code was thrown out and not reusable, leading to overtime and stress. Sadly the estimates used for the project were based on the old approach which my project was forbidden from using so it wasn't an appropriate indicator for estimation. I would hear the PM say "we've done this before," when in reality they had not since we were using a new library and the devs working on it were not the same devs used on the old project.

The SA who would enforce the usage of DTOs, DOs, BOs, Service layers and so on for all projects. New devs had to learn this architecture and the SA adamantly enforced usage guidelines. Exceptions to usage guidelines were made when it was absolutely difficult to follow the guidelines. The SA was grounded in their approach. Classes for DTOs and all CRUD operations were generated via CodeSmith and database schemas were another similar ball of wax. However, having used this setup everywhere, the SA was not open to new technologies such as LINQ to SQL or Entity Framework.

I am not using this post as a platform for venting. There were positive and negative aspects to my experiences with the SA stories mentioned above. My questions boil down to:

What should an SA bring to the table?

How can they strike a balance in their decision making?

Should one approach an SA job (as defined earlier) with the mentality that they must enforce certain ground rules?

Anything else to consider?

Thanks! I'm sure these job tasks are easily extended to people who are senior devs or technical leads, so feel free to answer at that capacity as well.

答:
I have never run into an Architect who was useful, primarily because they weren't practical.

For me the biggest issues I've seen are:

blind adherence to process for the sake of process

blind bias to technology before knowing the problem

creation and enforcement of rules without a good justification

rewrite from scratch mentality

The best "Architects" I've worked with brought to the table:

Questions that drove to a better understanding of the problem and the potential solutions.

Design options/technologies and their trade-offs.

Clear and rational explanations for both condemnations and endorsements of designs and technologies.

The problem for me is the best "Architects" I've worked with didn't have "Architect in their title.  They were most often Software Engineers who are grounded in the specific problem and projects.  They understood that in most businesses it isn't practical to rewrite a working codebase from scratch.  They make design decision or provide options and their reasons or justifications. They map out how to iterate the codebase to a new architecture over time and still keep everything functional.  They give conservative recommendations instead of recommending whatever is dejour or familiar. They would communicate a cohesive vision of how things should work and why, BUT more importantly they would map out how to get there and the cost.