问:
When should you start unit testing? (during which development stage?)
I'm currently learning about unit testing, specifically JUnit (with Java).

Searching the web I see many threads talking about why you should use it, what type of methods you should use it with but I can't seem to find much information on when you should implement a unit test.

Is it best to incorporate it from the very beginning of a project and then with every method you create, you add a unit test? Or is it something that it's done towards the latter stages when the logic/structure of the program is closer to completion?

答:
I would use the Test-Driven Development method if I were you.

It's pretty straightforward, you unit test the method before they exist, run the test. They will fail. You will then fix them by making your methods work.


问:
How do I handle 3rd party search result data (via cache)
I have a search function on my site and it is taking data from 6 different 3rd party resources. The problem is, it takes too long requesting the data over and over again on the results page.

I've read for questions like this on SO about session not being a good choice but for me 'memcache' is not an option, because the server doesn't have memcached installed and I have no way to install it now.

Is there any other approach to do this? Storing in the database seem inappropriate because the data depends on the search terms requested.

What I've been thinking is writing a file on the server that would act as a cache for this file but I don't know how I would know when to delete it after.

答:
there is also APC, Alternative PHP Cache, it is common in shared hosting php servers.

It has also the ability to define a timeout for each variable.
The syntax is pretty simple.

```<code>    <?php
    if (apc_exists($s_lang)) { // array in ram
        $l = apc_fetch($s_lang);
    } else {
        //fetch the resource here. example:
        require_once(__DIR__ . "/" .$s_lang. "/language.php");
        apc_store($s_lang, $l, 60); //save for 1 min.
    }
</code>```

However, if you reboot the server, the data is lost.

ContentLicense: CC BY-SA 3.0

Body:
there is also APC, Alternative PHP Cache, it is common in shared hosting php servers.

It has also the ability to define a timeout for each variable.
The syntax is pretty simple.

    <?php
    if (apc_exists($s_lang)) { // array in ram
        $l = apc_fetch($s_lang);
    } else {
        //fetch the resource here. example:
        require_once(__DIR__ . "/" .$s_lang. "/language.php");
        apc_store($s_lang, $l, 60); //save for 1 min.
    }

However, if you reboot the server, the data is lost.


答:
Start early! Why wait?

Once your system is more complex than a simple "Hello, World!" application, you can start writing unit tests to ensure that what you've coded works correctly. If you use a tool like maven for your builds, you can have the tests run with every build so you should know pretty quickly if newly written code has issues with existing code.

Title: When should you start unit testing? (during which development stage?)

Body:
I'm currently learning about unit testing, specifically JUnit (with Java).

Searching the web I see many threads talking about why you should use it, what type of methods you should use it with but I can't seem to find much information on when you should implement a unit test.

Is it best to incorporate it from the very beginning of a project and then with every method you create, you add a unit test? Or is it something that it's done towards the latter stages when the logic/structure of the program is closer to completion?


答:
You can start unit testing as soon as you have a notion of a class you want to create.  The meaning of "unit" will depend on the programming language.  For example, suppose you want to create a function to parse roman numerals.  You might start with this unit test:

```<code>public class RomanTest {
  public void iEquals1() {
    assertEquals(1, Roman.toInteger("I"));
  }
}
</code>```

Your test won't compile, because you haven't created the Roman class.  So you write:

```<code>public class Roman {
  public static toInteger(String s) {
    return 1;
  }
}
</code>```

Wow, your first test passed!

Body:
You can start unit testing as soon as you have a notion of a class you want to create.  The meaning of "unit" will depend on the programming language.  For example, suppose you want to create a function to parse roman numerals.  You might start with this unit test:

public class RomanTest {
  public void iEquals1() {
    assertEquals(1, Roman.toInteger("I"));
  }
}

Your test won't compile, because you haven't created the Roman class.  So you write:

public class Roman {
  public static toInteger(String s) {
    return 1;
  }
}

Wow, your first test passed!


答:
You should write your unit tests very near to when you write your code. "Timely" is one of the five core tenets of unit testing per Clean Code. There's even an approach that advocates writing your unit tests before your code. It's called Test Driven or Test First Development, depending on who you're talking to.

In my experience, it doesn't matter too much if the tests are done first or second, as long as the tests are done before the work as a whole is considered "done". This means having the unit tests done to consider your story/task done.

Doing the tests near the time you do your code lets you:

Write better tests since you remember better what the code should be doing. And you remember how the code does it, making bugs quicker to fix once your unit tests find them.

Catch bugs earlier, before others use your code. Catching bugs earlier means they're cheaper to fix.

Not fall into the "oh, I'll do it later" trap.


问:
Why in cyclomatic complexity we add 1 for operators within a condition?
I know that basically, CC can be computed as number of decision + 1. In addition, every logical operator in the condition causes CC to increase by 1. But why?

Having the code if(A || B || C) else... the control flow graph would simply be a node with two outcomes - two branches. So I always thought branch coverage is about covering the edges of the graph, branches, which would mean to the compbound condition to evaluate to TRUE and FALSE.
As for the paths, the paths can only be either TRUE or FALSE, so why the CC inreases with operators if there is no other branch of code run?

答:
In the example you use, there are four (4) possible paths of execution, and hence four (4) tests that must be performed.  They may be enumerated as follows, where x denotes "don't care":

1xx: A is true, don't care about B and C - then path

01x: A is false, B is true, don't care about C - then path

001: A and B are false, C is true - then path

000: A, B, and C are all false - else path

(It may be easier to see if you consider the generated assembly language.)

Cyclomatic complexity is intended to give you a handle on possible number of tests you have to run.


答:
Just because the programming language abstracts the branches away into a boolean expression, doesn't mean they aren't there.  If you looked at what actually gets executed, it looks like this:

```<code> +-----------+
 |is A true? +------------------+
 +----+------+                  |
      |                         |
 +----v------+                  |
 |is B true? +------------------+
 +----+------+                  |
      |                         |
 +----v------+                  |
 |is C true? +------------------+
 +----+------+                  |
      |                         |
+-----v-------------+   +-------v------+
| Do something else |   | Do something |
+-------------------+   +--------------+
</code>```

Even without short-circuit evaluation, you have a case that it increases the complexity, because there are multiple ways to choose a given path, and you have to test and maintain all of them.

Title: Why in cyclomatic complexity we add 1 for operators within a condition?

Body:
I know that basically, CC can be computed as number of decision + 1. In addition, every logical operator in the condition causes CC to increase by 1. But why?

Having the code if(A || B || C) else... the control flow graph would simply be a node with two outcomes - two branches. So I always thought branch coverage is about covering the edges of the graph, branches, which would mean to the compbound condition to evaluate to TRUE and FALSE.
As for the paths, the paths can only be either TRUE or FALSE, so why the CC inreases with operators if there is no other branch of code run?

Body:
Just because the programming language abstracts the branches away into a boolean expression, doesn't mean they aren't there.  If you looked at what actually gets executed, it looks like this:

 +-----------+
 |is A true? +------------------+
 +----+------+                  |
      |                         |
 +----v------+                  |
 |is B true? +------------------+
 +----+------+                  |
      |                         |
 +----v------+                  |
 |is C true? +------------------+
 +----+------+                  |
      |                         |
+-----v-------------+   +-------v------+
| Do something else |   | Do something |
+-------------------+   +--------------+

Even without short-circuit evaluation, you have a case that it increases the complexity, because there are multiple ways to choose a given path, and you have to test and maintain all of them.


问:
Entirely separate business logic layer from MVC
We are currently refactoring our controller methods in ASP.NET MVC application.

At the beginning we've separated data access layer (our goal was to remove LINQ from controllers entirely). Now we are thinking about another step - how to create a business logic layer to reduce number of lines and logic in controller. Currently we have something like this:

```<code>public ActionResult CustomerProjects(some parameters)
{
    var collectionOfSomeType = this.CustomerRepository.GetSomeData();
    var anothercollection = this.ProjectsRepository.GetAnotherData(collectionOfSomeType);

    var viewModel = CreateSomeViewModel(anotherCollection);

    return View("Index", viewModel);
}
</code>```

Of course it's just an example with four lines of code. We have some methods which are bigger (but still IMO not so bad). We injected our helper classes through IoC container, more complex logic sits there. But now we'd like to remove even that parts.

Is it worth our time to create another layer which would be our 'last gate' before controllers? The final result would be:

```<code>public ActionResult CustomerProjects(some parameters)
{
    var viewModel = someSource.PrepareCustomerProjectsViewModel(params);

    return View("Index", viewModel);
}
</code>```

What do you think?

答:
It doesn't seem to me these layers are really separate unless they are different applications entirely.

Though the idea of separate classes like BL and DAL etc sounds good, I rather think the UI should only handle UI functions and receive from the BL only strings and numbers in an expected order to be passed into the appropriate controls.

The BL can receive petitions from the UI, but I think those could be passed straight to the DAL if they are only retrievals and upon editing the UI can send just the edited strings and numbers back to the BL for reinsertion to the DAL. Working that way the DAL would be data only and its language only transaction language.

The BL can then work with the requested information to validate and format it as new strings with the appropriate data typing etc. for example the phone number from the DAL goes to the BL as a string of numbers  and the BL re-formats it to the (areaCode)sector-number.

Any further formatting as in color, fonts and the like happens in the UI. The BL would be the only app dealing with logical classes and the UI app would only need presentation classes and objects. The DAL only needs to transact.

This makes it possible to make truly modular programs where UI, BL, and DAL are independent. It is a way to give customers options to buy apps from developers like buying custom car parts. You can buy the performance parts (BL) from one company and the body dress ups from another company and they will all bolt together.


答: Forget the unit testing. Write and test yourself by being a user. deliberately try to break what you wrote even to the point of doing things you would never do but someone else might. This way you will discover things you could not foresee when writing unit tests. Your unit tests will, like your code make sense, but users are free from such restrictions. Bring in some users often to test as you go. Make sure your instructions are understandable by engaging with users, which unit testing cannot do. create a class or even a function, test it now! Don't move on until you are satisfied it is well done.</p>


问:
Real AI in a compiled language
possibly a newbie question here.

I heard that if a real AI were to exist it would have to evolve, by that I think it means it should be able to write new code then run itself with the new code.
Could this be possible in a compiled language like C/C++?

Just wondering, thanks.

答: In the old days, languages (often forms of Assembly) used to be designed with instructions specifically set aside for self-mutating code.  This means you could easily tell the program to change itself while it's running, which was used for performance improvements.  The key word here is "easily", because although this went out of style decades ago, as a result of computers getting fast enough to not need something this cryptic and hard to follow, hackers today still use Assembly to play tricks on the computer hardware to overwrite memory they shouldn't have access to - potentially the instructions of their currently executing program that have been loaded into memory.  And since you can embed a good bit of Assembly into C++, that's one way you could say a C++ program can self-mutate; although a good operating system these days should have reasonable security measures to block things like this in either case.

Title: Real AI in a compiled language


答:
First of all, if by "real AI" you are referring to Strong AI, this is a yet undecided question. That question has some scientific, some ontological, and some religious aspects, and opinions widely differ.

What was commonly referred to as AI by software programmers is merely branches of machine learning, or computer science / electrical engineering / signal processing / linguistics in general.

In one kind of machine learning algorithms, the inputs and outputs are matrices of numbers. The "system" that map the inputs to the outputs are also matrices of numbers. Thus, those algorithms reduce a practical problem down to some mathematical calculations.

There are many other practical AI algorithms and implementations, employing many other mechanism and branches of domain knowledge.

Title: Real AI in a compiled language

Body:
possibly a newbie question here.

I heard that if a real AI were to exist it would have to evolve, by that I think it means it should be able to write new code then run itself with the new code.
Could this be possible in a compiled language like C/C++?

Just wondering, thanks.


答:
You can write an interpreter in a compiled language that executes a self-modifying, domain-specific language whose instructions are held in a mutable data structure of some sort.

So yes, it's possible.

If your question is "can I do it with the original target language using the original compiler," that, too, is possible, if you write a program that writes a program in the original language and then runs a script to compile and execute it.  But that would be very difficult to do, and probably impractical.

Title: Real AI in a compiled language


答:
You should start writing your tests when you start writing your code.

The important part is that any code you write is driven by a unit-test; instead of stepping through the code manually, do it with a test. It doesn't take that much more work to write a test than it does to step through the code.

By writing a test to drive your newly written code, you essentially capture that work; if you manually test the code all that effort just dissipates into the ether. If in, say, six months you or another programmer breaks the code, that test will be there to save you from having to repeat the testing effort. This is how unit-tests protect against regressions!

Over time you will see the benefits of writing unit-tests. One example, you can refactor your code and the unit-tests will tell you if you broke anything.


问:
What did people do before templates in C++?
I am not new to programming, but I am one that started a few years ago, and I do love templates.

But in the before times, how did people deal with situations where they needed compile-time code generation like templates? I'm guessing horrible, horrible macros (at least that's how I'd do it), but googling the above question only gets me pages and pages of template tutorials.

There are many arguments against using templates, and while it typically boils down to readability, "YAGNI", and complaining about how poorly it is implemented, there is not a lot out there on the alternatives with similar power. When I do need to do some sort of compile-time generics and do want to keep my code DRY, how does/did one avoid using templates?

答:
What did people do before templates in C++?

The answer is, of course, they (we) didn't use them.  Yes, I am being tongue-in-cheek, but the details of the question in the body seem to (perhaps exaggeratedly) assume that everyone loves templates and that no coding could ever have been done without them.

As an example, I completed many many coding projects in various languages without needing compile-time code generation, and believe others have also.  Sure, the problem solved by templates was an itch large enough that someone actually scratched it, but the scenario posited by this question was, largely, non-existent.

Consider a similar question in cars:

How did drivers shift from one gear to another, using an automated method which shifted gears for you, before the automatic transmission was invented?

The question is, of course, silly.  Asking how a person did X before X was invented isn't really a valid question.  The answer is generally, 'we didn't do it and didn't miss it because we didn't know it ever would exist'.  Yes, it's easy to see the benefit after-the-fact, but to assume that everyone was standing around, kicking their heels, waiting for automatic transmission, or for C++ templates, is really not true.

To the question, 'how did drivers shift gears before the automatic transmission was invented?' one can reasonably answer, 'manually,' and that's the type of answers you are getting here.  It may even be the type of question that you meant to ask.

But it wasn't the one you did ask.

So:

Q: How did people use templates before templates were invented?

A: We didn't.

Q: How did people use templates before templates were invented, when they needed to use templates?

A: We didn't need to use them.  Why assume we did?  (Why assume we do?)

Q: What are alternative ways to achieve the results that templates provide?

A: Many good answers exist above.

ContentLicense: CC BY-SA 4.0


答:
Yes, but…

It has been long known that machine code for Von Neumann architecture machines is too "brittle" to reasonably mimic some life-based dataprocessing.

As a simple example, if you alter a single bit in a machine instruction, you won't necessarily get something useful, you may very well crash the processor or program.

Contrariwise, biological systems are more resilient to alterations. If you change a DNA base from A to C, you will get a protein out which might even be more useful than the unaltered state (it is more likely to have no effect or deleterious effect, but the whole machine doesn't stop). Similarly if you have less of enzyme Q for some reason, things won't crash, they'll just not work as well as they might otherwise.

Very productive work has been done with less fragile "machine code" running on virtual machines, but the last detailed reading I'd done on the subject was from an an ancient Proceedings from the Santa Fe Institute for the study of Complexity so I'm sure the approach has been refined considerably since then.

Title: Real AI in a compiled language


问:
Can regexp be used to check for palindromes?
Can regexp pattern matching be used to check for palindromes within a given text in Java?

My intuition is that in order to check for palindromes, we may need to remember the character that was parsed, which cannot be done using regexp. Is that correct?

答:
An answer from SO.

https://stackoverflow.com/questions/233243/how-to-check-that-a-string-is-a-palindrome-using-regular-expressions

I played around with these, and I had some success.

(.?)(.?)(.?)(.?)(.?).?\5\4\3\2\1

\W(.?)(.?)(.?)(.?)(.?).?\5\4\3\2\1\W

I think the real answer is that RE is a poor method for finding palindromes.


问:
What's the best semantic html5 tag for an action menu
I want to create an action menu to trigger some actions on a single page application and I wonder what's the most appropriated html5 tag for this?

I know the nav tag but it seems more suited for navigation than actions.

Should I use a simple div tag or is it a more semantical tag?

答:
There is no element designed for the purpose in HTML5 as recently approved by the W3C. There was a menu element (or, rather, the old menu as completely revamped) in drafts, but it was dropped due to lack of implementations; it’s still in HTML 5.1 drafts and might become useable some day.

You can use just a sequence of button elements, or you can wrap them in a div element if this is useful for styling or scripting, and some people would favor a ul wrapper. But asking which is “best” is like asking which food is best.

What you should be asking is which approach is most practical for programming and styling and for accessibility (though accessibility is here mainly a matter of adding ARIA attributes), with the constraint that it should work across all imaginable browsers. This depends on the context and type of the menu, the application as a whole, etc.


问:
Understanding of concatenation, union and iteration at regular language
I'm trying to understand what a regular language is. There are 3 compound regular expressions for regular language: concat {AB}, union {A+B} and iteration {A*}. When they are used in a simple ways it's clear for me how operate with them. But I'm frustrated with questions like this:

```<code>Find regular language equivalent to: (0 + 1)*1(0 + 1)*
(01 + 11)*(0 + 1)*
(0 + 1)*(10 + 11 + 1)(0 + 1)*
(1 + 0)*1(1 + 0)*
(0 + 1)*(0 + 1)(0 + 1)*
</code>```

As I understand that instead of (0 + 1)* it can be "", so equivalent language should have at least 1 and any number of symbols before and after it.

```<code>(01 + 11)*(0 + 1)* can evaluate to "", wrong
(0 + 1)*(10 + 11 + 1)(0 + 1)* can evaluate to 10 or 11 or 1, can be solution
(1 + 0)*1(1 + 0)* has middle one, can be a solution
(0 + 1)*(0 + 1)(0 + 1)* has (0+1) and can be or 0 or 1 or "", wrong
</code>```

Are my guesses correct?

答:
The given language amounts to "any bit string with at least one 1 in it", so your guesses are correct. Option 4 is equivalent because union is symmetrical, so (0 + 1) is equivalent to (1 + 0). Option 2 is equivalent because however you expand the iterations in option 2, you can just expand the iterations in the given regex once more to make up the difference, and conversely, if you expand both iterations in the given regex to "", then you get just 1, which is explicitly allowed by option 2 as well.

In general, proving equivalence amounts to (1) proving that any string generated by A can be generated by B and vice versa or (2) transforming both expressions until they are identical. Noticing that (1 + 0) is equivalent to (0 + 1) is an instance of method (2), arguing like "you can always choose one iteration more" is an instance of method (1).


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

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

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

答:
The best books I have found regarding the things a programmer should do before coding are:

Frederick P. Brooks, The Design of Design: Essays from a Computer Scientist Paperback. Brooks is also the author of the outstanding Mythical-Man Month book (also recommended, however the scope of this one is more on the project management side of software). In The Design of Deign, Brooks talks about the problem and design exploration process.

Michael Jackson, Software Requirements and Specifications: A Lexicon of Practice. This is a syllabus on very different concepts that appear during the design and requirements phases. The books is organized as a dictionary which is unusual. I have learned something from each entry.

L. Lamport, Specifying Systems. This is the more mathematically oriented, and therefore, hard. This book is specifically targeted to writing formal specification using TLA+ formalism. From this book I learned how difficult and nevertheless beautiful is the specification of concurrent systems. Notice that there are other formalisms and tools, however this book is really a gem.


问:
How to implement a RESTful API that updates a list which might have exclusion and addition of related resources?
We have an application where there is an API to create a document with a POST and update it with a PUT. There is a separate API to share document with users.

Now, How should we approach updating the list of users who the document is shared with ?

Should it be a POST or PUT that actually deletes the whole association and replace it with new ?

How are things like these sanely implemented in a RESTful way ?

答:
When using the HTTP protocol for your REST API (the common situation), PUT is used to replace a resource and POST to modify a resource.

If the list of document recipients is modeled as a sub-resource of your document, you can either use POST to add users to the list or PUT to replace the whole list, whatever is most convenient to you and/or the users of your API.

If the list of document recipients is not modeled as a sub-resource, but is a simple property of the document, then you should use POST (on the document) to modify the list without overwriting the rest of the document resource.


问:
Mocking the context of application
We have a context of the application which is a static class named Holder containing several static properties initialized by objects that are used throughout the application.

All over the unit tests we need to initialize the context by mocks.
In the current implementation, the context defense itself from reinitializing, so it contains Singletons. Because of that all tests share mocks, hence they take a responsibility to correctly clear them, I mean to clear their's behaviour.

What do you think about is it normally to have such a shared state between unit tests?
And if you consider that as a bad practice, than I'll be appreciated for some advices.

Update. I'm sorry for misleading. One of the most important thing to mention is that I can't recreate many times the inner state of the Holder class. What options do I have in such a case?

答:
Yes, it's better not to share state between unit-tests, and have them independent from each other. But it doesn't mean that you can't share code between unit-tests.

For example(using NUnit + FluentAssertions + FakeItEasy):

```<code>    [TestFixture]
    [Category("Unit")]
    public class when_rolling_back_unit_of_work : UnitOfWorkScenario
    {
        [Test]
        public void should_rollback_and_dispose()
        {
            //act
            UnitOfWork.Do(uow => uow.Rollback());

            //assert
            A.CallTo(() => SessionScope.Commit()).MustNotHaveHappened();
            A.CallTo(() => SessionScope.Rollback()).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => SessionScope.Dispose()).MustHaveHappened(Repeated.Exactly.Once);
        }
    }
</code>```

In the example above, we derive our test from UnitOfWorkScenario class which shares common initialization logic between our tests for UnitOfWork.

This class looks like:

```<code>public class UnitOfWorkScenario
    {
        protected ISessionScopeFactory SessionScopeFactory { get; set; }
        protected ISessionScope SessionScope { get; set; }
        public UnitOfWorkScenario()
        {
            SessionScopeFactory = A.Fake<ISessionScopeFactory>();
            SessionScope = A.Fake<ISessionScope>();
            A.CallTo(() => SessionScopeFactory.Open()).Returns(SessionScope);
            Func<string, ISessionScopeFactory> sessionScopeFactoryExtractor = name => (name == UnitOfWorkSettings.Default.StorageName ? SessionScopeFactory : null);
            UnitOfWork.SessionScopeFactoryExtractor = sessionScopeFactoryExtractor;
        }
    }
</code>```

The point is that you could share common initialization logic between your tests, at the same time keeping them independent from each other. Nevertheless, if you need to clean-up something(static property as an example), you could do it in base class constructor, or use features of your unit-test framework(e.g. method with TearDown attribute in NUnit) to do it, BUT specifying this logic in the only one place in your base class.

Sorry if I misunderstood your question a bit.

Title: Mocking the context of application

Body:
Yes, it's better not to share state between unit-tests, and have them independent from each other. But it doesn't mean that you can't share code between unit-tests.

For example(using NUnit + FluentAssertions + FakeItEasy):

    [TestFixture]
    [Category("Unit")]
    public class when_rolling_back_unit_of_work : UnitOfWorkScenario
    {
        [Test]
        public void should_rollback_and_dispose()
        {
            //act
            UnitOfWork.Do(uow => uow.Rollback());

            //assert
            A.CallTo(() => SessionScope.Commit()).MustNotHaveHappened();
            A.CallTo(() => SessionScope.Rollback()).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => SessionScope.Dispose()).MustHaveHappened(Repeated.Exactly.Once);
        }
    }

In the example above, we derive our test from UnitOfWorkScenario class which shares common initialization logic between our tests for UnitOfWork.

This class looks like:

public class UnitOfWorkScenario
    {
        protected ISessionScopeFactory SessionScopeFactory { get; set; }
        protected ISessionScope SessionScope { get; set; }
        public UnitOfWorkScenario()
        {
            SessionScopeFactory = A.Fake<ISessionScopeFactory>();
            SessionScope = A.Fake<ISessionScope>();
            A.CallTo(() => SessionScopeFactory.Open()).Returns(SessionScope);
            Func<string, ISessionScopeFactory> sessionScopeFactoryExtractor = name => (name == UnitOfWorkSettings.Default.StorageName ? SessionScopeFactory : null);
            UnitOfWork.SessionScopeFactoryExtractor = sessionScopeFactoryExtractor;
        }
    }

The point is that you could share common initialization logic between your tests, at the same time keeping them independent from each other. Nevertheless, if you need to clean-up something(static property as an example), you could do it in base class constructor, or use features of your unit-test framework(e.g. method with TearDown attribute in NUnit) to do it, BUT specifying this logic in the only one place in your base class.

Sorry if I misunderstood your question a bit.


问:
An algorithm that spreads similar items across a list
I need an algorithm that distributes same items across a list, so maximizing the distance between occurrences.

E.g.
I have a list of 15 items:

```<code>{a,b,c,c,c,d,e,f,f,f,g,h,h,i,j}
</code>```

The algorithm should reorder these in such a way that all the duplicates are spread as uniformly as possible.

The mentioned list should result in something like this:

```<code>{c,f,a,h,b,c,d,e,c,f,g,c,h,i,j,f}
</code>```

Preferably I'd like pseudo code, and even better would be TSQL (since that is the platform it needs to run on). It needs to process hundreds of these lists in one go.

I also tested a proposed method called 'Weighted shuffle' but this will still allow two of the same items in the list to appear next to each other even when this is not needed.

答:
First, make sure there is a solution according to your requirements (that means, there is not a single letter which occurs more that n/2 times, when n is the total number of elements).

Then I suggest you try the following

start with a random shuffle or weighted shuffle

afterwards, for each remaining pair of similar neighbours, pick one of the items, pick another randomly choosen item among those with different neighbours, and switch their places

repeat the last step until all pairs are removed.

This approach will just make sure you get no neighboured pairs, but it does not maximize the possible distances between similar letters. If you want to achieve the latter (which is not clear from your question), I suggest you introduce a score function to your list, for example like this:

```<code> Score(list) := Sum(1/(abs(a-b)-0.999))
                a,b
</code>```

where the sum goes over all pairs (a,b) of positions of equal letters. The "-0.999" in the denominator makes sure the whole expression will become very big when there are 2 equal neighbours. Now, you can apply random swaps to your list and try to minimize the score function, for example by hill climbing or simulated annealing.

Body:
First, make sure there is a solution according to your requirements (that means, there is not a single letter which occurs more that n/2 times, when n is the total number of elements).

Then I suggest you try the following

start with a random shuffle or weighted shuffle

afterwards, for each remaining pair of similar neighbours, pick one of the items, pick another randomly choosen item among those with different neighbours, and switch their places

repeat the last step until all pairs are removed.

This approach will just make sure you get no neighboured pairs, but it does not maximize the possible distances between similar letters. If you want to achieve the latter (which is not clear from your question), I suggest you introduce a score function to your list, for example like this:

 Score(list) := Sum(1/(abs(a-b)-0.999))
                a,b

where the sum goes over all pairs (a,b) of positions of equal letters. The "-0.999" in the denominator makes sure the whole expression will become very big when there are 2 equal neighbours. Now, you can apply random swaps to your list and try to minimize the score function, for example by hill climbing or simulated annealing.


问:
Socket Connecting to Large number of IPs
I have a text file of ~600 CIDR notation IP blocks which, when expanded, amount to ~17.5M IP addresses. I need to socket connect to each one. If it connects, I add it to a "live" list, if it returns an error/refusal, to a "dead" list. Then the socket is closed. I don't need to read from it, I don't need to write to it. Obviously, this is a problem of scale, if we generously assume that the connection takes only one second to return success or failure, it would take months to complete, but likely several years. I need to get it down to <24 hours.

Right now I'm using Python to expand/count each of the IP addresses, because it is trivial to do so. I am writing a simple multi-threaded C program to address the above problem. There are a few ways I have thought of to tackle this:

Purely using C: I have not found a way to expand a CIDR block in C, (handling strings in general is a pain). I could probably cook something up, but if something already exists I'd love to hear about it.
Will I be able to spawn enough threads? Even if I spawn a thread for each block, that 600 threads! I feel like I need to shrink the stack space allotted to the threads to do this maybe? Even so, I need to be able to handle a large number of strings because the blocks need to be expanded. Regardless, I have looked at the list by hand, and one of the blocks has a /10 CIDR notation, which amounts to >4M IPs by itself. This would still take far too long.

Spawning C processes from Python: This would trivialize the string problem, and each individual IP could be sent to an instance of a C function called from Python, which would then end. The question I have is: when Python calls an external C function, does it continue running with the C process in parallel? Or does it wait for the C function to complete? I know Python does not allow multi-threading (or rather, it does, but it's somewhat of a joke since only one line is interpreted at a time), so is this the correct way to "export" multi-threading?

Vice versa: As above, but with C calling Python code, is this "more" correct? Which is to say, can C initiate multiple Python processes and continue to do it's own thing?

Something completely different.

Any questions, suggestions, or concerns are welcome. Please point out anything I might be missing or incorrect assumptions I have made.

Thank you for your help.

答: Focus on the problem, not the solution. Taking this problem back to abstract terms, you've got a scenario that screams out for multiple processes communicating via queues.  One process (the "input reader") would loop reading items from your input list (CIDR blocks) and append them to a to-be-enumerated queue.  A second set of processes (the "enumerators") would loop grabbing the topmost to-be-enumerated item, expand them and append the results (individual IP addresses), one at a time, to a to-be-checked queue.  A third set of processes (the "checkers") would loop grabbing the topmost to-be-checked item, perform the check, and append the results to a to-be-reported queue.  The last process (the "reporter") would loop grabbing the topmost item from the to-be-reported queue and writing it to the final results.


答:
I remember when gcc shipped with genclass - a program which took as input a set of parameter types (e.g. key and value for a Map) and a special syntax file which described a parameterized type (say, a Map or a Vector)  and generated a valid C++ implementations with the param types filled in.

So if you needed Map<int, string> and Map<string, string> (this was not the actual syntax, mind that) you had to run that program twice to generate something like map_string_string.h and map_int_string.h and then use these in your code.

See the man page for genclass and the documentation from GNU C++ Library 2.0 for more detail.

Title: What did people do before templates in C++?

Body:
I am not new to programming, but I am one that started a few years ago, and I do love templates.

But in the before times, how did people deal with situations where they needed compile-time code generation like templates? I'm guessing horrible, horrible macros (at least that's how I'd do it), but googling the above question only gets me pages and pages of template tutorials.

There are many arguments against using templates, and while it typically boils down to readability, "YAGNI", and complaining about how poorly it is implemented, there is not a lot out there on the alternatives with similar power. When I do need to do some sort of compile-time generics and do want to keep my code DRY, how does/did one avoid using templates?


问:
Why isn't it possible to switch between header and cpp in Visual Studio?
For the last eight years I wait for Microsoft to add the basic C++ functionality of switching back and forth between .h and .cpp files, and it keeps astonishing me it is still not supported in Visual Studio 2010. Does anyone know why they refuse to add this essential feature?  </p>

答:
It's easy to write a macro that does it: Switch between Header and CPP File for Visual Studio .NET by Pavel Sokolov, Pierre Arnaud

Pavel Sokolov's Solution

A simple macro that allows you to quickly switch between the associated header and implementation files. This is a modification for Visual Studio .NET of the macro by Nooruddin Kapasi.

This macro simply switches between a *.h file and a *.cpp file, without any errors (if the *.h or the *.cpp file does not exist)...

Pierre Arnaud's Solution

The Switch_H_CPP macro switches between the active document (either source file or header file) and its counterpart (either header file or source file). Whereas simpler macros get this job done more efficiently (see the above), they do not work if the header files and source files are not stored in the same directory...

Switch_H_CPP looks for a matching counterpart by walking through all the loaded project files. It can, therefore, deduce the full path of the file and open it even if it is in a different directory as the active document...

ContentLicense: CC BY-SA 2.5


答:
I had a similar problem with my code with global state via singelton.

As @Thomas-Junk-s and @SHODAN-s comment suggested i refactored my code to make the static global state non-static through constructor Dependency injection.

Example

original code

```<code>public static class Global {
    public static int getSomeGlobalState() {...}
}

public class MyClass {
    public MyClass(...) {...}

    public myFunction(....) {
        ....
        int i = Global.getSomeGlobalState()
        ....
    }
}
</code>```

refactored static global method to nonstatic global method

```<code>public class Global {
    private Global global = new Global();

    // singelton to keep old code compatible
    public static Global getGlobal() {return global;}

    // not static anymore
    public int getSomeGlobalState() {...}
}

public class MyClass {
    public MyClass(...) {...}

    public myFunction(....) {
        ....
        // replacing call to static member Global.getSomeGlobalState()
        int i = Global.getGlobal().getSomeGlobalState()
        ....
    }
}
</code>```

refactored removed depency to static class Global from method myFunction to constructor

```<code>public class MyClass {
    Global global;

    // depricated constructor compatible with old api.
    public MyClass(...) {this(..., ...;Global.getGlobal());}

    // new constructor to be used in future
    public MyClass(..., Global global) {...;this.global=global;}

    public myFunction(....) {
        ....
        int i = global.getSomeGlobalState()
        ....
    }
}
</code>```

after introducing a di-container: refactored to replace static singelton class Gloal to container

```<code>public class Global {
    public Global() {...}

    public int getSomeGlobalState() {...}
}

public class MyClass {
    public MyClass(..., Global global) {...;this.global=global;}

    public myFunction(....) {
        ....
        int i = global.getSomeGlobalState()
        ....
    }
}
</code>```

Each refactoring made shure that the code, that ueses MyClass needs no modification.

In the last refactoring i added a di-container that is responsible for creating a singelton Global-Class and that injects the global instance into its customers like MyClass this way the old MyClass constructor could be removed.

[update 2014-12-11]

if you donot want to add a dependency all over the codebase as your comment suggests you can onmit the last refactoring step:

```<code>public class MyClass {
    // constructor used in consuming classes.
    public MyClass(...) {this(..., ...;Global.getGlobal());}

    // constructor used for unittests where you can replace global.
    public MyClass(..., Global global) {...;this.global=global;}

}
</code>```

Title: Mocking the context of application

Body:
We have a context of the application which is a static class named Holder containing several static properties initialized by objects that are used throughout the application.

All over the unit tests we need to initialize the context by mocks.
In the current implementation, the context defense itself from reinitializing, so it contains Singletons. Because of that all tests share mocks, hence they take a responsibility to correctly clear them, I mean to clear their's behaviour.

What do you think about is it normally to have such a shared state between unit tests?
And if you consider that as a bad practice, than I'll be appreciated for some advices.

Update. I'm sorry for misleading. One of the most important thing to mention is that I can't recreate many times the inner state of the Holder class. What options do I have in such a case?

Body:
I had a similar problem with my code with global state via singelton.

As @Thomas-Junk-s and @SHODAN-s comment suggested i refactored my code to make the static global state non-static through constructor Dependency injection.

Example

original code

public static class Global {
    public static int getSomeGlobalState() {...}
}

public class MyClass {
    public MyClass(...) {...}

    public myFunction(....) {
        ....
        int i = Global.getSomeGlobalState()
        ....
    }
}

refactored static global method to nonstatic global method

public class Global {
    private Global global = new Global();

    // singelton to keep old code compatible
    public static Global getGlobal() {return global;}

    // not static anymore
    public int getSomeGlobalState() {...}
}

public class MyClass {
    public MyClass(...) {...}

    public myFunction(....) {
        ....
        // replacing call to static member Global.getSomeGlobalState()
        int i = Global.getGlobal().getSomeGlobalState()
        ....
    }
}

refactored removed depency to static class Global from method myFunction to constructor

public class MyClass {
    Global global;

    // depricated constructor compatible with old api.
    public MyClass(...) {this(..., ...;Global.getGlobal());}

    // new constructor to be used in future
    public MyClass(..., Global global) {...;this.global=global;}

    public myFunction(....) {
        ....
        int i = global.getSomeGlobalState()
        ....
    }
}

after introducing a di-container: refactored to replace static singelton class Gloal to container

public class Global {
    public Global() {...}

    public int getSomeGlobalState() {...}
}

public class MyClass {
    public MyClass(..., Global global) {...;this.global=global;}

    public myFunction(....) {
        ....
        int i = global.getSomeGlobalState()
        ....
    }
}

Each refactoring made shure that the code, that ueses MyClass needs no modification.

In the last refactoring i added a di-container that is responsible for creating a singelton Global-Class and that injects the global instance into its customers like MyClass this way the old MyClass constructor could be removed.

[update 2014-12-11]

if you donot want to add a dependency all over the codebase as your comment suggests you can onmit the last refactoring step:

public class MyClass {
    // constructor used in consuming classes.
    public MyClass(...) {this(..., ...;Global.getGlobal());}

    // constructor used for unittests where you can replace global.
    public MyClass(..., Global global) {...;this.global=global;}

}


问:
The usage of server under GNU GPL
I have found an open sourced server that is licensed under GNU GPL. We would like to use that server at our client's hardware as a part of our solution for him (we provide our own software but we need a server to run on). However our software is under no-disclosure agreement.

Can we use the server?
What do we have to do to be able to use the server?

答:
If your software only interacts with the server through the standard OS interfaces or other standardized interfaces, then you can use the GPL server without question.

The GPL license applies to entire applications, but there are limits to what is considered part of such an application. In particular, the boundaries are:

system APIs

API's that conform to well known standards

separate processes that communicate "at arms length". At arms length essentially means here that the processes communicate through a standard interface without knowing about each others internals.

It essentially means that if your software communicates through a defined interface to the server, where that interface is not specific to that particular server, then the server's license doesn't carry over to your application.

Title: The usage of server under GNU GPL


问:
2 questions about TDD
I'm just starting to get to grips with TDD, and I have 2 quick questions;

I'm assuming that if I were writing software for a software company, that TDD would work alongside the software design? i.e all the UML, ERD diagrams, flow diagrams etc...

My second question is, the way I'm doing my tests at the minute, I think about what will be called in the code (e.g a method) and I think about all the possible erroneous inputs and correct inputs.  So for example, lets assume I know I need to call a "loadfile", so I write just enough code to make the test pass...

But then I also start thinking about, what if you don't specify a parameter, or an invalid file, so I write a few more tests to test for exceptions - which then involves adding a bit of logic into the method (so the correct exception is returned)

Is this the correct approach to TDD?

答:
TDD is primarily an implementation technique, so it works as orthogonal as writing other code to the "graphical" design techniques you mentioned. (If the latter techniques are used in all software companies, for all kind of professional software, is a completely different question.) When you have UML diagrams on the abstraction level of your public class API, with method signatures, then feedback from the implementation level, or maybe from coded tests can influence parts of your public class API and so influence your UML models, but that is always the case, if your are doing TDD or not.

If I understand your 2nd question correctly, you are talking about small cycles of writing tests, implementing, extending the tests, extending the implemented methods to fulfill the new tests? Actually, that is exactly how TDD ideally should be done "by the book".

In fact, there are some (IMHO wrong) myths around that TDD is about writing "all tests first". I think that is a misunderstanding: TDD is about writing ideally only one test at a time, then implement a little, write the next one test, and so on.

Title: 2 questions about TDD


问:
How to Design Database with User-Contributed Content
I'm building an application where there are different "Locations".  There are Stores, Bars, Schools, and Churches (and so on) all of which are geocoded and defined by existing data sets.  While not exactly alike, these entities can probably all fit into a "Locations" table. This will be helpful because users will constantly run reports and maps on these different locations and it will be far easier to run a single query on Locations than try to join 4 (or more) tables.

This data will change daily as stores go out of business or change their name.   There will be some complexity in terms of updating these data sets but we can keep track of them with a Location.type field (type = school, or type = bar, etc).

So that's pretty straightforward.  But I also want to allow users to add their own custom locations to the app.  These will be of type = "custom".  User contributed locations will also need to have a userId associated with them, which the other locations won't have.  Is there a design issue with allow users to contribute content to the Location table? I'm worried about user data getting mixed up with system data during updates, or when users delete their data.

So, should we have a second, nearly identical CustomLocation table?  But then how do we keep the Location IDs unique between the two tables?  And we're increasing the code complexity of the application.

The easiest path seems like forcing everything into a single giant Location table, which will really simplify running reports and generating maps, but that doesn't "feel" like the right approach.  It seems like a single giant table is really using "type" to create multiple tables within a table.  Is there another approach where the Location table just handles IDs and where maybe I have a PredefinedLocation Table and a UserCustomLocation table?  Thanks for your help!

答:
If the number of fields that are not shared by all different types of Location are small, I would just go for a single table for all Locations (including the custom ones) and just put a NULL value in the fields that are irrelevant for that location type.

If there are more than a few non-shared fields, I would go for a "shared primary key" approach. Here you have one table for the common fields (Location) and additional tables with the fields for each specific type of location (SchoolLocation, ChurchLocation, CustomLocation, etc.).

The trick here is that the type-specific tables don't have their own primary key, but they share the primary key with the Location table.

For example, you could have these tables and entries:

```<code>Location:
id |  Type  | Name
 1 | School | MIT
 2 | Custom | Home
 3 | Church | St. Pauls Cathedral

CustomLocation:
id | UserId
 2 | 12345

ChurchLocation:
id | Religion
 3 | Roman Catholic
</code>```

Note each <Type>Location table only contains entries for the corresponding type and that the values in the id column match with the corresponding entry in the Location table.

With regard to your concerns for data integrity, it should be rare that all the non-custom data will get updated at the same time, so you need to design your update process such that changes to part of the database don't corrupt unrelated entries. And unless you were thinking of having separate tables for each user, the same goes with deleting custom entries after a user closes their account. That is all standard practice when working with databases.

The technique I described for using shared primary keys is also a know technique for modeling an inheritance relationship between classes onto the database.

Body:
If the number of fields that are not shared by all different types of Location are small, I would just go for a single table for all Locations (including the custom ones) and just put a NULL value in the fields that are irrelevant for that location type.

If there are more than a few non-shared fields, I would go for a "shared primary key" approach. Here you have one table for the common fields (Location) and additional tables with the fields for each specific type of location (SchoolLocation, ChurchLocation, CustomLocation, etc.).

The trick here is that the type-specific tables don't have their own primary key, but they share the primary key with the Location table.

For example, you could have these tables and entries:

Location:
id |  Type  | Name
 1 | School | MIT
 2 | Custom | Home
 3 | Church | St. Pauls Cathedral

CustomLocation:
id | UserId
 2 | 12345

ChurchLocation:
id | Religion
 3 | Roman Catholic

Note each <Type>Location table only contains entries for the corresponding type and that the values in the id column match with the corresponding entry in the Location table.

With regard to your concerns for data integrity, it should be rare that all the non-custom data will get updated at the same time, so you need to design your update process such that changes to part of the database don't corrupt unrelated entries. And unless you were thinking of having separate tables for each user, the same goes with deleting custom entries after a user closes their account. That is all standard practice when working with databases.

The technique I described for using shared primary keys is also a know technique for modeling an inheritance relationship between classes onto the database.


问:
What possible things to log in mvc webapp
I'm about to learn to handle logging in my c# asp.net mvc app and are going to store my log in a noSQL-db. How to handle the logging is done. The thing is I'm having a hard time to figure out possible things to log.

The app I'm building is a quite regular website, were a admin-user can login and edit content on the site using a wysiwyg-editor. Visiting users can send mail using a simple form.

The things I'm planning to log info about is functionalities like:

admin login/logout

visiting user send-mail status

admin changing content in the wysiwyg-editor(driven by js-function sending data to a c#-method through ajax. So basiclly log info when the c#-method gets hit)

To my question: what other possible things can I log in this type of application?

Any suggestions would be helpful

答:
Sounds like you are unsure about why you are doing any logging in the first place? Well, here's 3 examples:

Auditing: Knowing who does what on your site, and when..?

Bug detection: having stack traces or similar information available can be crucial when tracking down a bug in production

Performance: For example; you want to know what the median time was for that huge picture to render

If you are still trying to learn I would argue you should try and log for one case of each of the above scenarios, just to get a feel for how it works, but remember writing log-statements is one thing; writing the right log statements is something completely different, and it is really only something you can learn from experience (I am yet to see a good article about what to log :) )

Good luck


问:
How can I specify user stories for processes with third-party involvement?
Suppose we have a process like the following:

Super user receives an internal request to initiate a process.

Super user approves the request.

An external process belonging to a third-party is triggered.

Once third-party process is complete, super user receives the result and either accepts or rejects it.

It is easy to see how to formulate user stories for 1, 2 and 4 but 3 is a bit trickier. Do I:

Skip it because it is external to our system and treat 3 as an implementation detail of 4 (after all, 4 is dependent on 3 happening); this may require external documentation of the actual process or potentially bloated user stories/tasks for 4.

Treat the external system or one of its users as a user and write the user story from their perspective ("as a [system x] user, I want to process..."); this seems like it should be out of the scope of our functional requirements.

Treat it as a "task" against 2; this doesn't seem quite right as the functionality of approving something doesn't really imply the triggering of some other process.

Something else entirely.

It seems that the act of the user approving the request and approving the response should be seen (functionally) as independent of the fact that the process happened in the middle but - without specifying that somewhere - 4 could conceivably be "implemented" even though it will never actually happen (i.e. if the response is available, the user sees it but a response will never actually be available because the third-party process is never actually triggered).

Is there a prescribed or conventional way for dealing with these types of scenarios?

答:
As the third-party process is not a part of the system you are developing, but your system needs to interact with it, the third-party process is an actor for your system.

Generally, an actor can be regarded as a generalization of a user. Actors can be human users, but also external computer systems that your system communicates with.

You could write the user story for step 3 with the external system as the user:

As <external system>, I want to receive a notification in <this way> when a request is approved, so I can perform <external process>. I will indicate completion of <external process> in <this way>.


问:
What is the appropriate way to handle implicit requirements?
I'm in R&D working on a new software product.

Management understandably focuses on the primary features that most obviously give a customer an advantage. But there are many requirements that can be seen as important as well (ex. performance, future extensibility, data traceability, security, smooth UI). These implicit requirements are probably the larger in number for any product, and if unfulfilled can lead to an unhappy customer.

I'm afraid that it is somehow expected that during development these things will become automatically implemented. For me though, everything is an atomic aspect that requires it's own attention and development effort.

I have a feeling that management may be too busy to pay too much attention to such aspects. For the sake my own developer pride, quality control, and being able to account the effort I spend, when and how should I document and communicate implicit requirements?

(i.e. features that exist in a product, but which haven't been explicitly talked about with either the customer or management)

Clarification

Thanks for the interest in the question, the main gist of the answers up to now seems to be:

"You need to make implicit requirements explicit."

Rats... that didn't occur to me.

The requirements I mean can be of the following types:

The customer can't hear about these requirements, because  I will be presenting a long list of ways in which the product can fail, instead of talking about how it will make them happy.

Busy management feels that I'm wasting their time, when I talk about "obvious" features.

I will only be able to describe some of these requirements during implementation. During planning I may just have a gut feeling that a particular issue might require focused effort during development.

I'm not at the necessary height in the company totem-pole to dictate my working conditions.

I'm asking for guidelines how to semi-formalize [implicit] requirements, while putting in less effort than for full-blown requirements, but keeping me prepared for judgement day, so that I'm not caught empty handed.

答:
As it happens, we had some of those implicit requirements bite us because they were not defined and thus QA didn't test them and the bugs went to production and were not found for some time causing not only the hassle of explaining to the customers the problem and why it wasn't found earlier but an actual legal problem for our company. (It was a report that dealt with information that had to be reported to the government.)

If it is important enough to do, it needs to be tested and thus it needs to be part of the requirements.

OwnerDisplayName: Rafael Cichocki

OwnerDisplayName: HLGEM


答:
Define everything. The only potential negative to doing so is that you may get something back complaining that they feel you're stating the obvious.

State the obvious then.

This is key: Anything you don't define can get thrown back in your face with "you never told us..."

Anything that isn't defined can potentially blow up in your face. "Better safe than sorry" are excellent words to live by.

Title: What is the appropriate way to handle implicit requirements?

Body:
I'm in R&D working on a new software product.

Management understandably focuses on the primary features that most obviously give a customer an advantage. But there are many requirements that can be seen as important as well (ex. performance, future extensibility, data traceability, security, smooth UI). These implicit requirements are probably the larger in number for any product, and if unfulfilled can lead to an unhappy customer.

I'm afraid that it is somehow expected that during development these things will become automatically implemented. For me though, everything is an atomic aspect that requires it's own attention and development effort.

I have a feeling that management may be too busy to pay too much attention to such aspects. For the sake my own developer pride, quality control, and being able to account the effort I spend, when and how should I document and communicate implicit requirements?

(i.e. features that exist in a product, but which haven't been explicitly talked about with either the customer or management)

Clarification

Thanks for the interest in the question, the main gist of the answers up to now seems to be:

"You need to make implicit requirements explicit."

Rats... that didn't occur to me.

The requirements I mean can be of the following types:

The customer can't hear about these requirements, because  I will be presenting a long list of ways in which the product can fail, instead of talking about how it will make them happy.

Busy management feels that I'm wasting their time, when I talk about "obvious" features.

I will only be able to describe some of these requirements during implementation. During planning I may just have a gut feeling that a particular issue might require focused effort during development.

I'm not at the necessary height in the company totem-pole to dictate my working conditions.

I'm asking for guidelines how to semi-formalize [implicit] requirements, while putting in less effort than for full-blown requirements, but keeping me prepared for judgement day, so that I'm not caught empty handed.

OwnerDisplayName: Christopher Estep


答:
This is when having a diverse team that has people who specialize in different areas comes in. It also requires more sr. people on the team to lead the rest.

For example performance, future extensibility, and data traceability should really all be things that are thought of from the start. They aren't a checkbox that you can just go back and add in later, they need to be in the foundation of your design.

As for security, this is when having someone who is familiar with this area be on your team from the beginning to help with the design process.

UI design has the tendency to bite a product if not done properly. Having a UX person on the team doing mock-ups and screen flows for the team is where this comes into play. But, again, this is something that should be done up front.

Your requirements might be a website that allows users to look up current the current inventory of a local store. How you design that system is where those implicit requirements fall into play.

From a project management stand point, this means that there needs to be design time in the budget, as well as proper testing time. There should also be check-ins with the client to show them what has been done to make sure you're on the right track.

OwnerDisplayName: Tyanna


答:
The industry term for such requirements as you describe is called:

Non-Functional Requirements

They should under every aspect be identified by technical resources and added to the project plan as atomic units of work.  If you are doing an Agile project then they would be written in user story form and added to the backlog to be dealt with.  As the technical resource you need to advocate for the time to work on these and make sure that they have appropriate priority during your sprint planning or project planning session with the business.  Furthermore QA needs to devise an appropriate test plan for these units of work as well.


答:
I find it helpful in these situations to step back from the 'functional requirements' for a second and try to view it as the higher level business process that is occurring.  For me, it seems to me like you only have 3 stories:

Primary Stories

As a Process Initiator, I need to be able to submit an internal request to the Super User for approval.

As a Super User, I need to be able to approve requests in order to ensure only qualified requests are sent to the external system.

As a Super User, I need to be able to accept or reject the results of the external system processing.

The fact that data is being transferred in some way between systems is an implementation issue and, in my opinion, should not be part of the acceptance criteria. If the Super User can approve the request and a pigeon flies it over to some folks in Elbonia for further processing, that is just as valid as long as the data gets to the external system and a result comes back in some way for accept/reject.

However, my pigeon analogy may have triggered a "but that would take too long" which indicates you likely have an acceptance criteria on the story regarding the acceptable transaction times for sending and receiving requests.

From an implementation perspective, this allows you to deliver stories against a stubbed API and complete stories, keeping them independent of each other.

External System Stories

If you were also developing the external system, I would suggest an additional story for the external development team:

As a Super User, I need approved requests to be processed and have a value returned for acceptance.

You would then have the acceptance criteria over how to process and return values in that story for the team developing the external system.

Other Hidden Acceptance Criteria

The above stories seem to have an incomplete picture. If the data is never actually processed and stored, you wouldn't be able to go back and see it later. Does that matter? If you built up an API stub and didn't do the external system, why would that be bad?

(It would be bad, but the question should trigger a thought about other stories you probably need)

Title: How can I specify user stories for processes with third-party involvement?

Body:
Suppose we have a process like the following:

Super user receives an internal request to initiate a process.

Super user approves the request.

An external process belonging to a third-party is triggered.

Once third-party process is complete, super user receives the result and either accepts or rejects it.

It is easy to see how to formulate user stories for 1, 2 and 4 but 3 is a bit trickier. Do I:

Skip it because it is external to our system and treat 3 as an implementation detail of 4 (after all, 4 is dependent on 3 happening); this may require external documentation of the actual process or potentially bloated user stories/tasks for 4.

Treat the external system or one of its users as a user and write the user story from their perspective ("as a [system x] user, I want to process..."); this seems like it should be out of the scope of our functional requirements.

Treat it as a "task" against 2; this doesn't seem quite right as the functionality of approving something doesn't really imply the triggering of some other process.

Something else entirely.

It seems that the act of the user approving the request and approving the response should be seen (functionally) as independent of the fact that the process happened in the middle but - without specifying that somewhere - 4 could conceivably be "implemented" even though it will never actually happen (i.e. if the response is available, the user sees it but a response will never actually be available because the third-party process is never actually triggered).

Is there a prescribed or conventional way for dealing with these types of scenarios?


答:
Any implicit requirements that will end up causing work for the team should be made explicit.

If not, they will end up either

biting you later when people bring them up anyway, causing overruns on development

ignored and later reported as bugs

being implemented anyway, despite not having been scheduled, causing overruns and bug reports because they were not implemented as the customer had thought they should have been but never mentioned.

So by making implicit requirements explicit you save yourself a lot of headaches.


答:
Requirements can come from any source, as long as they are traceable to where they came from and not in conflict with each other. Customers can provide their requirements, but requirements also come from laws and regulations, industry standards, business needs, and even prior experiences learned by delivering similar products to other customers.

Each of these requirements should be captured in whatever method you use to capture requirements so that it's not forgotten. Doing this will also allow them to be compared to ensure that an added requirement isn't actually in conflict with a customer requirement or a customer requirement isn't in conflict with regulations, for example.

You should be capturing these requirements and managing them right from the start of the project and flowing them down to the staff that is designing, implementing, and testing the software. Doing this will ensure that everyone fully understands what the delivered software is supposed to be.

However, when you do add one of these requirements, you should verify it with the appropriate stakeholders. You can't simply add requirements without ensuring that you can still deliver the software within the intended schedule and budget.


问:
What's the idea behind mocking data access in unit tests
I understand that you're not actually supposed to hit the database or disk when doing unit tests... Why is that?

Also, taking something like Moq, what is it actually supposed to mock and where? For example, let's say I want to create a method called "loadconfig" that loads an XML document. This would be a void method, so I would check that it has worked by writing tests around the get/set value methods...

So is Moq supposed to mimick a file being loaded? And I'm also to mock returning/setting values? I can see that Moq has assert methods, should these be used in the test method (seems unlikely since the document is stored in a private property)? If its supposed to be used in the get/set methods, then they must return a Boolean instead of the actual value - which means at some point the whole method would need to be changed?

Lastly, at some point you would surely need to remove all the Moq stuff and replace it with a real implementation? But then doesn't that mean the unit tests couldn't or shouldn't be used?

答:
Because hitting a database is slow, requires an elaborate environment set up just right in order to work, and spends most time in code not written by you. A unit test is supposed to test your code, not Oracle's code.

2./3. No, you don't replace mocked things with real things. You leave mocked collaborators in your testing code, and then you don't ship your test code to the customer. You only ship your business code.

It can seem like a horrible waste at first to have huge amounts of code that aren't even delivered to anyone, but it isn't. Trust me. The point of testing is to improve the quality of business code, and a large, well-maintained test suite achieves exactly that, even though it never sees the light of day. Think of it as part of your tool set rather than part of the product - a baker sells bagels, he doesn't sell his oven.


答:
When you are testing a unit of code (say a single method or class), you want to only test that unit and have no other dependencies (with possibly unknown state).

If you don't use mocks in unit tests, you are putting yourself in a position of uncertainty - if a class your method/class depends on changes, it can break your test even though your code has not changed.

This is particularly true for tests that depend on IO (disk, network, DB), as they may fail for reasons that have nothing to do with software - latency increases, network congestion, changes to the data in the database...

Again - unit tests are about testing a unit. In isolation.

Lastly, at some point you would surely need to remove all the Moq stuff and replace it with a real implementation?

Um. No. Not in you unit tests. Sure, in your actual codebase, where you use the class/method, you will pass it its actual dependencies, but in your test code? Always use the mocks.

Now for the implementation question:

If its supposed to be used in the get/set methods, then they must return a Boolean instead of the actual value - which means at some point the whole method would need to be changed??

Huh? If you are going to test via get/set methods, make sure they return what they should. In your test, your asserts are checking that what's returned is correct - not that what's returned is a boolean.

Title: What's the idea behind mocking data access in unit tests

Body:
I understand that you're not actually supposed to hit the database or disk when doing unit tests... Why is that?

Also, taking something like Moq, what is it actually supposed to mock and where? For example, let's say I want to create a method called "loadconfig" that loads an XML document. This would be a void method, so I would check that it has worked by writing tests around the get/set value methods...

So is Moq supposed to mimick a file being loaded? And I'm also to mock returning/setting values? I can see that Moq has assert methods, should these be used in the test method (seems unlikely since the document is stored in a private property)? If its supposed to be used in the get/set methods, then they must return a Boolean instead of the actual value - which means at some point the whole method would need to be changed?

Lastly, at some point you would surely need to remove all the Moq stuff and replace it with a real implementation? But then doesn't that mean the unit tests couldn't or shouldn't be used?


答:
You can manage all locations in a single table and then move columns into other tables that are unique to a location group (System or Custom). Creating a new table for each type can be cumbersome and difficult to manage. This also gives you flexibility as this system grows. My gut feeling at this point is, you're not going to need it, but keep your positive attitude that you'll have millions of locations.

It sounds like you're relying on some data structuring to handle security and integrity concerns.

I'm worried about user data getting mixed up with system data during
  updates, or when users delete their data.

Your app is going to have different "view" or whatever your development environment calls them, for system locations and custom/user locations. Two different tables will help, but since you need more than that, one table will work as well. Even if you deny permission to users to alter the system location table, you still need to make sure each user can only alter their records in the custom table.

So, should we have a second, nearly identical CustomLocation table?
  But then how do we keep the Location IDs unique between the two
  tables? And we're increasing the code complexity of the application.

You could use GUIDs to make sure the identifiers are unique or just start one of the table with a number that you can predict will exceed the other.

As far as one big table, be more concerned with unused columns instead of too many rows. Most RDBMS have plenty of strategies using indexing, files and other techniques to aid performance with large datasets.

Title: How to Design Database with User-Contributed Content

Body:
I'm building an application where there are different "Locations".  There are Stores, Bars, Schools, and Churches (and so on) all of which are geocoded and defined by existing data sets.  While not exactly alike, these entities can probably all fit into a "Locations" table. This will be helpful because users will constantly run reports and maps on these different locations and it will be far easier to run a single query on Locations than try to join 4 (or more) tables.

This data will change daily as stores go out of business or change their name.   There will be some complexity in terms of updating these data sets but we can keep track of them with a Location.type field (type = school, or type = bar, etc).

So that's pretty straightforward.  But I also want to allow users to add their own custom locations to the app.  These will be of type = "custom".  User contributed locations will also need to have a userId associated with them, which the other locations won't have.  Is there a design issue with allow users to contribute content to the Location table? I'm worried about user data getting mixed up with system data during updates, or when users delete their data.

So, should we have a second, nearly identical CustomLocation table?  But then how do we keep the Location IDs unique between the two tables?  And we're increasing the code complexity of the application.

The easiest path seems like forcing everything into a single giant Location table, which will really simplify running reports and generating maps, but that doesn't "feel" like the right approach.  It seems like a single giant table is really using "type" to create multiple tables within a table.  Is there another approach where the Location table just handles IDs and where maybe I have a PredefinedLocation Table and a UserCustomLocation table?  Thanks for your help!


答:
What's the idea behind mocking data access in unit tests ?

-

The speed of tests.

It's certainly true that you don't need to test the database, file system or other external dependency, but in reality it's often not that hard to set up the database, etc. and the actually code works aginst it so it's really easy to just use the database and it is closest to the real world.

Writing a whole of bunch of tests that have mocking and stubbing just to test 'only your code' with a separation of concerns is a high principle but not one that generally justifies the expense of actually doing it.

Except for one little thing.

Speed.

-

There is also another key component to consider in this area:

Integration Tests

These tests, for example browser ui automated tests really do test the whole stack and so they are great at making sure that, with real database connections, the application DOES really work as desired.

Using Integration tests is a key component in being comfortable about mocking and stubbing in unit tests.

Tests - hundreds and thousands of them - that access the database will be slow.  For example, in the framework I know best - Ruby on Rails - a test that creates and uses several database objects (through active record) may take several thousand milliseconds.  The code under test though may itself may take less than 100 milliseconds.  Ultimately this can lead to test suites that take hours instead of minutes or seconds.  A fast running test suite is key for modern rapid agile development and so this factor is key.

Smoke / Volume / Performance Tests

There may also be smoke tests, volume tests and performance tests that also exercise the full stack and provide coverage for mocking and stubbing in unit tests.


问:
Should we add constructors to structs?
We often use c++ structs to define data structure as opposed to class which can be a complete module with member methods. Now deep down, we know they both are the same (loosely speaking).

The fact that we often use/treat structs as data only entities creates this urge that we not add default constructors as well. But constructors are always great, they make things simpler and help eliminate errors.

Would it be frown upon if add default constructors to my data structures?

Does implementing default constructor also make the struct Non-POD (plain old data type) provided other criteria are met?

To put things in perspective, consider a simple example but in reality the struct would be much larger.

```<code>struct method
{
    char    name[32];
    float   temperature;
    int     duration;
};
</code>```

Every time I create a method, I have to worry about (to say the least) if I forgot to set some value. Imagine I forget to set temperature and apply the method to system which is now a random high value and causes mayhem. Or I forgot to set duration and now the method applies itself for an unknown high duration.

Why should I take responsibility to initialize the object every time instead of implementing its constructor which guarantees it?

答:
With C++11 you can do

```<code>struct method
{
    char    name[32] {};
    float   temperature = 42.141521;
    int     duration = -6;
};
</code>```

And whenever you forget to initialize something, you get default initialization.

Title: Should we add constructors to structs?

Body:
With C++11 you can do

struct method
{
    char    name[32] {};
    float   temperature = 42.141521;
    int     duration = -6;
};

And whenever you forget to initialize something, you get default initialization.


问:
Why use iFrames in a web application?
I am new at a company that has a saas web application, which uses iframes to load content from several different servers (all operated by us). Is there any known compelling reasons to use iFrames instead of DOM manipulation?

I've tried searching google, stack overflow and programmers, but most questions and answers seem to be related to content pages, and not software. SEO is not a concern. We have a known user base with specific browser/os requirements.

答:
It's just easier, and a pragmatic solution. iFrame keeps everything in it's own semi-private window, so there's little risk of CSS or JS conflicts.

Not the greatest for user experience, but simple and effective especially for internal facing apps.

Title: Why use iFrames in a web application?


问:
What traits do the best managers you've worked for have in common?
I have been listening to Scott Hanselman and Rob Conery's podcast, This Developer's Life.

In the latest episode, they discuss personality traits:

1.0.4 - Being Mean.

What makes people mean in our
  industry? What about aggressive?
  Confident? What's the difference?
  Would you rather have a drill sergeant
  for a boss, or a zen master? We talk
  to Cyra Richardson and Giles Bowkett.

It got me thinking, what traits did the best managers you've worked for have in common?

EDIT: Just to clarify, as there have been a few close votes, I'm interested in whether there are traits common to managers of developers that are not necessarily those traits that a manager of some other profession requires.

As for whether this is programming related or not, well I don't want to ask this question on a site that isn't about programming because, frankly, I'm not as interested in what people who make cans of soup for a living want from their managers as I am interested in what developers want from their managers.

答:
I've had good managers and bad. These are some traits I've noted in bad managers:

Get's out of the way so you can do your job

A good manager will see to it that you have the right equipment to write code.

Micro-manages the wrong details

This sort of manager will chew you out over failing to attach a signature to your email while ignoring the extra work you did prior to that email.

Has no interest in the development process

This is really a bad sign for a manager in charge of software developers. He doesn't care about investigating other development approaches, will not know what version number the next release of the software should be, will not read blogs like Joel on Software or anything related to managing developers, like Peopleware.

Thinks that he's there for me to report to

This sort of manager gets off on having people report to him about everything.

Misallocates time

Given a month to deliver a development project from start to completion this manager will allocate 3/4 of the month to the design and requirements team to generate 1000 line word documents and expect the dev team to implement it all in a week. He'll also iterate on requirements until they're 'perfect', adding copious amounts of detail until the document becomes unusable. But then later on in the development process you'll find bugs in the design and requirements documentation and realize that the emphasis on trying to write the perfect document was a mistake.


问:
Is it safe to catch ImportError when trying to import optional modules?
I usually see this pattern at least once in every Python project I work on.  For example, in a Django project, this is often added at the bottom of the base settings file:

```<code>try:
  from .local_settings import *
except ImportError:
  pass
</code>```

Also:

```<code>try:
  import simplejson as json
except ImportError:
  import json
</code>```

This has always bothered me a little bit though; what if the module is imported successfully, but then it triggers an ImportError itself?  E.g., in the first example, the local_settings module exists, but then local_settings tries to import a non-existent module.

Is this the safest way to import an optional module, is there a better way to achieve this functionality, or does it depend on the context/usage (and if so, what are the guidelines to deciding when to use this approach)?

答:
It should generally be assumed that the optional dependency you are importing can work on its own. There is little difference between trying to import a missing optional dependency and one that cannot be imported because a required transitive dependency is missing.

In other words, why would your program need to care about simplejson not being available because it is not installed, or because a dependency of simplejson is not installed? Either way you cannot use simplejson.

For optional dependencies, it is up to the package installer to ensure that a dependency is correctly installed, including transitive dependencies.

For something like local_settings, there is indeed a (small) risk that a transitive ImportError is masked. You can always log the caught ImportError exception at level DEBUG or similar to make it easier to review what might have caused the exception:

```<code>try:
    from .local_settings import *
except ImportError:
    log.debug('local_settings failed to import', exc_info=True)
</code>```

The logging package will include the exception information in the log for later inspection when you set exc_info to true.

Another option is to issue a warning with the warnings module, the standard library has a ImportWarning class for this:

```<code>import warnings

try:
    from .local_settings import *
except ImportError:
    warnings.warn('local_settings failed to import', ImportWarning)
</code>```

Body:
It should generally be assumed that the optional dependency you are importing can work on its own. There is little difference between trying to import a missing optional dependency and one that cannot be imported because a required transitive dependency is missing.

In other words, why would your program need to care about simplejson not being available because it is not installed, or because a dependency of simplejson is not installed? Either way you cannot use simplejson.

For optional dependencies, it is up to the package installer to ensure that a dependency is correctly installed, including transitive dependencies.

For something like local_settings, there is indeed a (small) risk that a transitive ImportError is masked. You can always log the caught ImportError exception at level DEBUG or similar to make it easier to review what might have caused the exception:

try:
    from .local_settings import *
except ImportError:
    log.debug('local_settings failed to import', exc_info=True)

The logging package will include the exception information in the log for later inspection when you set exc_info to true.

Another option is to issue a warning with the warnings module, the standard library has a ImportWarning class for this:

import warnings

try:
    from .local_settings import *
except ImportError:
    warnings.warn('local_settings failed to import', ImportWarning)


问:
Is it a bad choice to consume the REST API from the back-end too?
Using a REST API for front-end code is a desiderable and quite common practice.

However, I was wondering if using it also for the back-end could be a good choice.

What I mean is leaving the burden of retrieving data from the database all to the API, and then call it from other parts of my back-end (mainly views and controllers) whenever I need to query the database, instead of doing it directly.

One thing I'm really concerned about is sharing some code between front-end and back-end, and using the API as a common source of data would be very handy.

So the question is, are there some reasons which make this a bad idea?

答:
Not necessarily. Middleware cannot handle everything. There are three examples I always bring up to show this: batching, forwards and api chaining. These all benefit by staying within the bounds of the original request but in applications, often have to leave and come back in via the proxy/api gate.

By abstracting I/O from the api and moving it to an interceptor, you can use a prehandler/posthandler to hand off the communications and use one thread to handle the loop.

The the I/O flow from api gate to application instance to response tooling is one constan flow and isn't broken.

See api abstraction and api chaining for more information (http://www.slideshare.net/bobdobbes/api-abstraction-api-chaining)


问:
Domain/Model objects attributes good practices
Simple question: Should model/domain objects only include attributes that are meant to be persisted in a database or serialized to any other specific format?

My understanding of a domain/model object is that it should reflect the data store (the model) as tightly as possible, rather than carrying "off-topic" attributes.

Am I on the right track?

答:
It sounds like you are. If you have metadata for the model object that doesn't get persisted, I suppose you could wrap the model object in another object that contains the metadata to reduce confusion about what is and is not part of the model.

One way to do it might look something like:

```<code>//Model that will actually be persisted
class UserProfile
{
   String name;
   String address;
   String age;
   ...
}

//"enhanced" version of the model.
class ApplicationUserProfile
{
    UserProfile userProfile;
    String webSessionID;
    Timestamp lastActiveTS;
    bool useABCServer;
    int someThresholdValue;
    //other related metadata fields that aren't persisted
 }
</code>```

Or if you want to keep things a little more organized:

```<code>//Model that will actually be persisted
class UserProfile
{
   String name;
   String address;
   String age;
   ...
}

class UserProfileMetadata //extends Metadata //(if you have some common metadata class)
{
    String webSessionID;
    Timestamp lastActiveTS;
    bool useABCServer;
    int someThresholdValue;
    ...
    //other related metadata fields that aren't persisted
}

//"enhanced" version of the model.
class ApplicationUserProfile
{
    UserProfile userProfile;
    UserProfileMetadata metadata;
}
</code>```

Body:
It sounds like you are. If you have metadata for the model object that doesn't get persisted, I suppose you could wrap the model object in another object that contains the metadata to reduce confusion about what is and is not part of the model.

One way to do it might look something like:

//Model that will actually be persisted
class UserProfile
{
   String name;
   String address;
   String age;
   ...
}

//"enhanced" version of the model.
class ApplicationUserProfile
{
    UserProfile userProfile;
    String webSessionID;
    Timestamp lastActiveTS;
    bool useABCServer;
    int someThresholdValue;
    //other related metadata fields that aren't persisted
 }

Or if you want to keep things a little more organized:

//Model that will actually be persisted
class UserProfile
{
   String name;
   String address;
   String age;
   ...
}

class UserProfileMetadata //extends Metadata //(if you have some common metadata class)
{
    String webSessionID;
    Timestamp lastActiveTS;
    bool useABCServer;
    int someThresholdValue;
    ...
    //other related metadata fields that aren't persisted
}

//"enhanced" version of the model.
class ApplicationUserProfile
{
    UserProfile userProfile;
    UserProfileMetadata metadata;
}


问:
Why 'List<E>' is an 'interface' but not 'abstract class'?
Amidst defining the hierarchy, firstly,  one can think to embed the abstract method(behavior) in abstract class only because the derive concrete class possess that behavior as core behavior with it's specific implementation, secondly, one can think to embed the abstract method(behavior) in interface only because derived concrete class possess that behavior as non-core behavior(peripheral) having it's specific implementation.

As I would not rely on this example which supports above point, below are the two references, I would rely on.

1) First reference that supports this point:

Interfaces are ideal for defining mixins.  Loosely speaking, a mixin is a type that a class can implement in addition to its "primary type" to declare that it provides some optional behavior.  For example, Comparable is a mixing interface that allows a class to declare that its instances are ordered with respect to other mutually comparable objects.  Such an interface is called a mixin because it allows the optional functionality to be "mixed in" to the type's primary functionality.  Abstract classes can't be sued to define mixins for the same reason that they can't be retrofitted onto existing classes: a class cannot have more than one parent, and there is no reasonable place in the class hierarchy to insert a mixin.

2) Second reference that support this point:

In UML sketch, the relation between interface model and concrete class model is named Realisation, where as, the relation between abstract class model and concrete class model is named is-a relation. Here is-a can be told, when concrete class has core behavior unlike realisation relation.

So, with these two references, It looks list<E> and Collection<E> are abstract class but not interface.

With this above explanation, I would like to understand,

Why Collection<E> and List<E> is designed to be interface in  java.util package?

Is my understanding correct?

答:
So an interface implies a contract - You guarantee that any class implementing the interface contains these methods, with these parameter types, and returns this type. This is great when you know there are many different ways of doing the same thing (maintaining lists, sorting, etc)

An abstract class, on the other hand, says that there are different ways of implementing this thing, but they will all share some set of functionality and I'll provide that functionality in this class. This is where the two diverge. One says that you have some knowledge that lets you know that ALL implementations will do one part the exact same way. This may apply in many cases, but for things like Lists or Sorting, there's almost always going to be some new, novel way to do things that you haven't thought of yet. That's why you use an interface and not an abstract class.