答:
Bob Martin's Clean Code book dedicates the entire 5th chapter to formatting. There are a couple of key points that I feel summarize it nicely.

Most attempts to group variables and methods by visibility and cleanliness Not make a lot of sense, and cause you to navigate around the code a lot.

Keeping methods which call each other vertically close reduces the amount of navigation you need to do, and makes it easier to find things.

Your train of thought isn't going to be broken if you have to stop and think "which region does this bit of code belong in?" every few minutes.

Instance variables should usually be few, and likely to be used everywhere, therefore they belong at the top of the class where they will be easiest to locate. Variables and declarations that will only be used by one method need to exist inside that method. If used by only a couple of methods, then they should be vertically close but above the few methods that are using them.

Keeping your code arranged with commonly interacting elements vertically close together effectively removes any need to create specific regions. If your code is so long that it requires regions to hide a lot of code, then perhaps that is a code smell indicating that the class is trying to do too much. Perhaps some of the functionality can be moved out to a utility class, or pushed up to an ancestor.

If you need to "hide" the code because it's too long or too "ugly", then you've probably got bigger problems to worry about than whether or not to use regions. Personally I never need to use them, and when working on someone else's code, I find I always need to open them all up anyway, so why bother?

Title: How do you normally layout a class's regions?

Body:
I was wondering if there was a standard for laying out a class's regions.

I currently use

```<code>Fields
Constructor
Properties
Public Methods
Private Methods
</code>```

Fields being Private Properties and Properties being the public ones. I'll normally use subregions within that if needed, or will occasionally add other regions below (such as interface or baseClass members).


问:
reverse engineering js/html controls as part of development
I'm starting a project with a big client that has several websites across the world, and they want to integrate them into a single Sitecore codebase/structure.

All good in principle, but there are certain navigation controls that we have to use but, due to organizational complexities, we don't have the other sites sources available (not that they don't have it somewhere, just that our team will have a difficult time getting a hold on it).

So we are left with the task of going site by site (each site is in a different language), looking at the navigation controls, and more or less copy html and js and use that. Something that doesn't sound impossible, but i've never tried to do this before and i feel somewhat confused about how to go about this task.

Edit to reiterate, we aren't concerned about translations nor do we want to grab the display text from the other sites, what we are after is obtain the controls code so we can use it locally. And with code i mean html/css and js. The controls need to look exactly the same as those already on production

Do you have any general or concise recomendations to offer?

答:
If it is html and JS then you do have the sources, or at least the important part of the sources if UI is your main focus, available to you -- just snag it using whatever browser tool you prefer.

Having done a dynamic menu or four, my general experience has been you can port the logical theme of the menu but trying to directly port the code rarely works as there are lots of assumptions baked into most html and js as rendered for a particular site. One often ends up porting the concepts as things tend not to line up to the new site with the new features.

ContentLicense: CC BY-SA 3.0


问:
Private variable vs property?
When setting a value to a variable inside of a class most of the time we are presented with two options:

```<code>private string myValue;
public string MyValue
{
   get { return myValue; }
   set { myValue = value; }
}
</code>```

Is there a convention that determines how we should assign values to variables inside of our classes? For example if I have a method inside the same class should I assign it using the property or using the private variable. I've seen it done both ways, so I was wondering if this is a choice or performance is a factor (minor, probably).

答:
Always use the one that makes sense. Yes, I know that sounds pretty bogus to the point of being a non-answer.

The point of properties is to provide an interface through which you can safely access a data model. For most situations you always want to safely access the data model through that interface, such as:

```<code>public Foo Bar
{
  get { return _bar; }
  set { _bar = doSomethingTo(value); }
}
</code>```

But in other situations, you may simply be using a property as a view of a data model:

```<code>public Double SomeAngleDegrees
{
  get { return SomeAngleRadians * 180 / PI; }
  set { SomeAngleRadians = value * PI / 180; }
}
</code>```

If it makes sense to use the radians form of SomeAngle, then by all means use it.

In the end, be sure to drink your own kool-aid. Your public-facing api should be resilient enough to work internally.

Title: Private variable vs property?

Body:
Always use the one that makes sense. Yes, I know that sounds pretty bogus to the point of being a non-answer.

The point of properties is to provide an interface through which you can safely access a data model. For most situations you always want to safely access the data model through that interface, such as:

public Foo Bar
{
  get { return _bar; }
  set { _bar = doSomethingTo(value); }
}

But in other situations, you may simply be using a property as a view of a data model:

public Double SomeAngleDegrees
{
  get { return SomeAngleRadians * 180 / PI; }
  set { SomeAngleRadians = value * PI / 180; }
}

If it makes sense to use the radians form of SomeAngle, then by all means use it.

In the end, be sure to drink your own kool-aid. Your public-facing api should be resilient enough to work internally.


问:
Interesting questions about Behaviour-Driven Development
For my master thesis at Software Engineering, I want to investigate in the new development technique BDD (Behaviour-Driven Development). In my opinion this technique could really improve on customer satisfaction, code coverage and bugs because of the force of executable specifications and the customer-understandable language.

For my thesis however, I struggle with the way I am going to validate that BDD could work better in certain circumstances. At the company I work during my study, work is still mostly done in a traditional, iterative way, where it sometimes is hard to change requirements after the requirements elicitation stage.

My question is, are there any people who already did projects with BDD, what are their experiences and have you ever felt something about BDD that you would want to investigate in, commencing on the above paragraphs? This could help me a lot with constructing my research question. Thanks in advance!

答:
It will be difficult to do statistical analysis on the difference between two development methodologies. It's possibly beyond the scope of a Phd let alone a masters thesis.

One thing that could be interesting is a deep dive on a specific deliverable. For instance, how does the estimate (or test plan) differ in each?  If you keep it manageable you may find a way to convince your boss to try a baby step too.


问:
Single or multiple files for unit testing a single class?
In researching unit testing best practices to help put together guidelines for my organization, I've run into the question of whether it is better or useful to separate test fixtures (test classes) or to keep all tests for a single class in one file.

Fwiw, I am referring to "unit tests" in the pure sense that they are white-box tests targeting a single class, one assertion per test, all dependencies mocked, etc.

An example scenario is a class (call it Document) that has two methods: CheckIn and CheckOut.  Each method implements various rules, etc. that control their behavior.  Following the one-assertion-per-test rule, I will have multiple tests for each method.  I can either place all of the tests in a single DocumentTests class with names like CheckInShouldThrowExceptionWhenUserIsUnauthorized and CheckOutShouldThrowExceptionWhenUserIsUnauthorized.

Or, I could have two separate test classes: CheckInShould and CheckOutShould. In this case, my test names would be shortened but they'd be organized so all tests for a specific behavior (method) are together.

I'm sure there are pro's and con's to either approach and am wondering if anyone has gone the route with multiple files and, if so, why?  Or, if you've opted for the single file approach, why do you feel it is better?

答:
I wish I could remember/find the link where the technique I've chosen to adopt was first demonstrated.  Essentially I create a single, abstract class for each class under test that contains nested test fixtures (classes) for each member being tested.  This provides the separation originally desired but keeps all of the tests in the same file for each location.  In addition, this generates a class name that allows easy grouping and sorting in the test runner.

Here is an example how this approach is applied to my original scenario:

```<code>public abstract class DocumentTests : TestBase
{
    [TestClass()]
    public sealed class CheckInShould : DocumentTests
    {
        [TestMethod()]
        public void ThrowExceptionWhenUserIsNotAuthorized()
        {
        }
    }

    [TestClass()]
    public sealed class CheckOutShould : DocumentTests
    {
        [TestMethod()]
        public void ThrowExceptionWhenUserIsNotAuthorized()
        {
        }
    }
}
</code>```

This results in the following tests appearing in the test list:

```<code>DocumentTests+CheckInShould.ThrowExceptionWhenUserIsNotAuthorized
DocumentTests+CheckOutShould.ThrowExceptionWhenUserIsNotAuthorized
</code>```

As more tests are added, they are easily grouped and sorted by class name which also keeps all tests for the class under test listed together.

Another advantage of this approach that I've learned to leverage is the object-oriented nature of this structure means I can define code inside the startup and cleanup methods of the DocumentTests base class that will be shared by all nested classes as well as inside each nested class for the tests it contains.

Body:
I wish I could remember/find the link where the technique I've chosen to adopt was first demonstrated.  Essentially I create a single, abstract class for each class under test that contains nested test fixtures (classes) for each member being tested.  This provides the separation originally desired but keeps all of the tests in the same file for each location.  In addition, this generates a class name that allows easy grouping and sorting in the test runner.

Here is an example how this approach is applied to my original scenario:

public abstract class DocumentTests : TestBase
{
    [TestClass()]
    public sealed class CheckInShould : DocumentTests
    {
        [TestMethod()]
        public void ThrowExceptionWhenUserIsNotAuthorized()
        {
        }
    }

    [TestClass()]
    public sealed class CheckOutShould : DocumentTests
    {
        [TestMethod()]
        public void ThrowExceptionWhenUserIsNotAuthorized()
        {
        }
    }
}

This results in the following tests appearing in the test list:

DocumentTests+CheckInShould.ThrowExceptionWhenUserIsNotAuthorized
DocumentTests+CheckOutShould.ThrowExceptionWhenUserIsNotAuthorized

As more tests are added, they are easily grouped and sorted by class name which also keeps all tests for the class under test listed together.

Another advantage of this approach that I've learned to leverage is the object-oriented nature of this structure means I can define code inside the startup and cleanup methods of the DocumentTests base class that will be shared by all nested classes as well as inside each nested class for the tests it contains.


问:
Is it a really required skill to program without API documentation?
I barely passed my Java programming exam today. I had to answer some general questions about threading which I did well and to write a little threaded program which was worse. I had to connect my laptop to the projector screen and write the program right away. My first attempt was to use anonymous classes but I forgot the exact syntax. Maybe because of some excitement or maybe because last two weeks I was coding mostly in php. Then I asked is it allowed to use the API documentation. The answer was "NO". So I decided to go another way around and I implemented Runnable. The program was doing what was requested at the end. Of course the examiners noticed my first fail and that affected my score greatly. I was amazed that it was not allowed to use the API documentation.

So, my question is: Is it really important to be able to code flawlessly without API documentation? Should I develop this skill? Is it really important in the real world and in the work environment? While on programming courses I focused on learning patterns, developing skills to write good design applications, skills to use API and find the necessary information fast. I was not trying to learn how to program without API documentation. Is it must-have during job interviews (coding without API documentation)?

答:
IMHO, academia usually stinks at producing good software engineers. Only people who code for fun after the lessons have a chance to achieve something in real world projects.

Then again, academia is not about producing developers, the whole world is about how to solve abstract problems and do the research. It's very far from practical application most of the time. And researchers are not necessarily a good coders.

And learning API by heart stinks. There is autocomplete/google/msdn/javadocs to look up all the nooks and crannies, why would anyone want to keep all that in their brain at all times? Most common functions you'll learn in few weeks/months, everything else can be looked up in a matter of seconds if you know the syntax, structure and general ideas.

Then again, some people still code in text editors and remember function names by heart, that's not necessarily wrong, but if they're fanatic about it, you got your professor.

Moreover, even if you know function names and parameters by heart, it's still a good idea to verify them in the latest API doc. strtok was fine in single threaded scenario 10 years ago, it's not fine nowadays. If you just learn the names and parameters you'll never know that the functionality might be deprecated or better alternatives invented.

Languages change, so you need to change with them, remembering one true way is not good for that.


问:
Who should control navigation in an MVVM application?
Example #1: I have a view displayed in my MVVM application (let's use Silverlight for the purposes of the discussion) and I click on a button that should take me to a new page.

Example #2: That same view has another button that, when clicked, should open up a details view in a child window (dialog).

We know that there will be Command objects exposed by our ViewModel bound to the buttons with methods that respond to the user's click.  But, what then?  How do we complete the action?  Even if we use a so-called NavigationService, what are we telling it?

To be more specific, in a traditional View-first model (like URL-based navigation schemes such as on the web or the SL built-in navigation framework) the Command objects would have to know what View to display next.  That seems to cross the line when it comes to the separation of concerns promoted by the pattern.

On the other hand, if the button wasn't wired to a Command object and behaved like a hyperlink, the navigation rules could be defined in the markup.  But do we want the Views to control application flow and isn't navigation just another type of business logic?  (I can say yes in some cases and no in others.)

To me, the utopian implementation of the MVVM pattern (and I've heard others profess this) would be to have the ViewModel wired in such a way that the application can run headless (i.e. no Views).  This provides the most surface area for code-based testing and makes the Views a true skin on the application. And my ViewModel shouldn't care if it displayed in the main window, a floating panel or a child window, should it?

According to this apprach, it is up to some other mechanism at runtime to 'bind' what View should be displayed for each ViewModel. But what if we want to share a View with multiple ViewModels or vice versa?

So given the need to manage the View-ViewModel relationship so we know what to display when along with the need to navigate between views, including displaying child windows / dialogs, how do we truly accomplish this in the MVVM pattern?

答:
For the sake of closure, I thought I would post the direction I finally chose to solve this problem.

The first decision was to leverage the Silverlight Page Navigation framework provided out-of-the-box.  This decision was based on a several factors including knowledge that this type of navigation is being carried forward by Microsoft into Windows 8 Metro apps and is consistent with navigation in Phone 7 apps.

To make it work, I next looked at the work the ASP.NET MVC has done with convention-based navigation.  The Frame control uses URIs to locate the 'page' to display.  The similarity provided an opportunity to use a similar convention-based approach in the Silverlight app.  The trick was making it all work together in an MVVM way.

The solution is the NavigationService.  This service exposes several methods, such as NavigateTo and Back, that ViewModels can use to initiate a page change.  When a new page is requested, the NavigationService sends a CurrentPageChangedMessage using the MVVMLight Messenger feature.

The view that contains the Frame control has its own ViewModel set as the DataContext that is listening for this message.  When received, the name of the new view is put through a mapping function that applies our convention rules and set to the CurrentPage property.  The Source property of the Frame control is bound to the CurrentPage property.  As a result, setting the property updates the Source and triggers navigation.

Going back to the NavigationService.  The NavigateTo method accepts the name of the target page. To make sure that the ViewModels have no UI concerns, the name used is the name of the ViewModel to display.  I actually created an enumeration that has a field for each navigable ViewModel as a helper and to eliminate magic strings all over the app.  The mapping function I mentioned above will strip the "ViewModel" suffix from the name, append "Page" to the name and set the full name to "Views{Name}Page.xaml".

So, for example, to navigate to the customer details view, I can call:

```<code>NavigationService.NavigateTo(ViewModels.CustomerDetails);
</code>```

The value of CustomerDetails is "CustomerDetailsViewModel" which is mapped to "Views\CustomerDetailsPage.xaml".

The beauty of this approach is that the UI is completely decoupled from the ViewModels yet we have full navigation support.  I can now reskin my application however and whenever I see fit without any code changes.

Hope the explanation helps.

Body:
For the sake of closure, I thought I would post the direction I finally chose to solve this problem.

The first decision was to leverage the Silverlight Page Navigation framework provided out-of-the-box.  This decision was based on a several factors including knowledge that this type of navigation is being carried forward by Microsoft into Windows 8 Metro apps and is consistent with navigation in Phone 7 apps.

To make it work, I next looked at the work the ASP.NET MVC has done with convention-based navigation.  The Frame control uses URIs to locate the 'page' to display.  The similarity provided an opportunity to use a similar convention-based approach in the Silverlight app.  The trick was making it all work together in an MVVM way.

The solution is the NavigationService.  This service exposes several methods, such as NavigateTo and Back, that ViewModels can use to initiate a page change.  When a new page is requested, the NavigationService sends a CurrentPageChangedMessage using the MVVMLight Messenger feature.

The view that contains the Frame control has its own ViewModel set as the DataContext that is listening for this message.  When received, the name of the new view is put through a mapping function that applies our convention rules and set to the CurrentPage property.  The Source property of the Frame control is bound to the CurrentPage property.  As a result, setting the property updates the Source and triggers navigation.

Going back to the NavigationService.  The NavigateTo method accepts the name of the target page. To make sure that the ViewModels have no UI concerns, the name used is the name of the ViewModel to display.  I actually created an enumeration that has a field for each navigable ViewModel as a helper and to eliminate magic strings all over the app.  The mapping function I mentioned above will strip the "ViewModel" suffix from the name, append "Page" to the name and set the full name to "Views{Name}Page.xaml".

So, for example, to navigate to the customer details view, I can call:

NavigationService.NavigateTo(ViewModels.CustomerDetails);

The value of CustomerDetails is "CustomerDetailsViewModel" which is mapped to "Views\CustomerDetailsPage.xaml".

The beauty of this approach is that the UI is completely decoupled from the ViewModels yet we have full navigation support.  I can now reskin my application however and whenever I see fit without any code changes.

Hope the explanation helps.


问:
Is it OK to put a link to Q&A sites in a program's comments?
In quite some codebase you can see comments stating things like:

```<code> // Workaround for defect 'xxx', (See bug 1434594 on Sun's bugparade)
</code>```

So I've got a few questions, but they're all related.

Is it OK to put link to SO questions in a program's comments:

```<code> // We're now mapping from the "sorted-on column" to original indices.
 //
 // There's apparently no easy way to do this in Java, so we're
 // re-inventing a wheel.
 //
 // (see why here, in SO question: http://stackoverflow.com/questions/951848)
</code>```

Do you do it?

And what are the drawbacks in doing so? (see my first comment for a terrible drawback)

答:
Ideally your code needs no such comments because it's well structured, etc.  But yes, when your situation is less than ideal, it's acceptable to put in comments like this.  And links to stackoverflow.com are as good (and often better!) than others.

Hopefully they're temporary comments, and you'll be allowed to come back and improve the code and take these comments out.

I have not yet put a StackOverflow.com link in my code.  I try to avoid putting links in code, since it's a bad smell, but when the time comes I won't hesitate.

Edit:  I think my above answer gives the impression that the need for comments such as this is avoidable.  Of course sometimes it's not avoidable; it's a bug in a library or poor API design that you have no control over.  Comments like this, including links, is very helpful for the next developer to come along.

OwnerDisplayName: Tristan St.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Patrick Karcher


答: Generally, the best way to create this link is through the versionning system and/or the bug tracking system. The requirement for this to work though is that you can accurately link your code to the bug tracker or the place in the versionning system where you put your comments.</p>

Title: Is it OK to put a link to Q&A sites in a program's comments?

Body:
In quite some codebase you can see comments stating things like:

```<code> // Workaround for defect 'xxx', (See bug 1434594 on Sun's bugparade)
</code>```

So I've got a few questions, but they're all related.

Is it OK to put link to SO questions in a program's comments:

```<code> // We're now mapping from the "sorted-on column" to original indices.
 //
 // There's apparently no easy way to do this in Java, so we're
 // re-inventing a wheel.
 //
 // (see why here, in SO question: http://stackoverflow.com/questions/951848)
</code>```

Do you do it?

And what are the drawbacks in doing so? (see my first comment for a terrible drawback)

OwnerDisplayName: Loki


答:
I've done it, maybe not specifically for Stack Overflow, but for technical blogs, forums, Usenet, Google Groups, or any other places where the "why did I do this" may not be completely clear from the context.

I don't see why using SO like this would be a bad thing, unless they archive and purge off old questions (which I don't think they do, but I'm not sure) - but even if they do, it's no worse than any other site.

If you're really worried about that, you can always take screenshots or download these pages as text (or go through the trouble of getting the images, stylesheets, etc.), and saving them to a knowledge repository at your company, attaching a unique identifier to it, and putting that unique identifier in your comments to allow you to reference later - then you'd have a consistent place for this type of thing.  But that may be overkill, depending on the complexity and importance of your code.

OwnerDisplayName: Joe Enos


答:
I think it would be a very valuable contribution to validate / test the premise that BDD leads to a leaner, more user-oriented test suite.

Codebases become very difficult to evolve over time in part because it is difficult to differentiate accidental complexity from domain-driven exceptions. That is, when one looks at a piece of code that seems like it could be refactored to be more simple, one has to consider the very real possibility that the complexity derives from some domain rule. ("Can we refactor foo->bar->bat->baz to get rid of bar or bat?" "Gee, we must have bar and bat for some reason!")

In a modern codebase, we expect that that all this complexity is exercised by test code. The instant we delete bar or bat we expect the suite to break, not just bar and bat, but foo too, since it's dependent. The premise of BDD is that you have user-meaningful frames that show that bar is low user-value, bat is associated with more value, and foo is very high, so, theoretically, you should be able to say "Well, we have to restore every foo test to green, we have to get these bat behaviors back, but we can lose bar entirely."

But is that really how it works? Or do BDD test-suites just devolve into a thin cover of "As a user of foo I expect the bar to be valid?" (testing the implementation rather than the user-valuable behavior)?

Title: Interesting questions about Behaviour-Driven Development

Body:
For my master thesis at Software Engineering, I want to investigate in the new development technique BDD (Behaviour-Driven Development). In my opinion this technique could really improve on customer satisfaction, code coverage and bugs because of the force of executable specifications and the customer-understandable language.

For my thesis however, I struggle with the way I am going to validate that BDD could work better in certain circumstances. At the company I work during my study, work is still mostly done in a traditional, iterative way, where it sometimes is hard to change requirements after the requirements elicitation stage.

My question is, are there any people who already did projects with BDD, what are their experiences and have you ever felt something about BDD that you would want to investigate in, commencing on the above paragraphs? This could help me a lot with constructing my research question. Thanks in advance!


问:
Create Primary Interop Assemblies or generate them?
I've never seen this question answered definitively:

If you are maintaining a COM DLL that can be used by a .NET program, is it best to:

Import the COM DLL into each project, which generates an Interop assembly for each project? or

Generate the Primary Interop Assembly with TLBIMP every time the COM DLL is compiled? or

Write the Primary Interop Assembly in C# and compile that every time the COM DLL is compiled?

I would like to do either number 2 or number 3. Number 2 sounds compelling, but I cannot see how you set the AssemblyTitleAttribute (and other such attributes); I would assume you use custom attributes in the IDL which TLBIMP would pick up.

答:
I really hate giving you an "it depends" answer... but it depends!

Generally relying on the generated Interop file is fine if your project setup is quite trivial. When you have a lot of projects and/or when you use strong naming, then things can get a little trickier.  In our case, we basically have strong naming for everything, and this includes the Interop files.  We compile our projects via a script on our integration server, and generate all of our Interop files on the fly when we need them, but before we compile our project source. In this way, we don't have to think about all of those edge cases where accessing assemblies might not work. In this case it looks like we're implementing your second option, and usually don't bother with the first option unless it's something very trivial and we don't need to rely on strong naming or on a prior build - for whatever reason.

As for the 3rd option, I can't imagine how you'd ever need to create your own Interop files given you've got 2 other options at your disposal which do the task much more easily for you.


问:
Node.JS testing with Jasmine, databases, and pre-existing code
I've recently built the start of a core system which is likely going turn into a monster product.  I'm building the system with node.js, and decided after I got a small base built, that It'd be a great idea to start using some sort of automated test suite to test the application.

I decided to use jasmine, as it seems pretty solid and has a lot of features for stubbing spying and mocking methods and classes.  The application has a lot of external data stores and api access (kestrel, mysql, mongodb, facebook, and more).

My issue is, I've got a good amount of code written that I want to start testing - as it represents the underpinnings of the application.  What are the best practices for testing methods/classes that access external APIs that I may or may not have control over?

As an example, I have a data structure that fetches a bunch of data from a MySQL database.  I want to test the method that retrieves the data; and I'm not sure how to go about it.  I could test the fetch method which is supposed to return an array of objects, but to isolate the method from the database, I need to define my own fixture data.  So what I end up doing is stubbing the mysql execution, and returning a static dataset.  So, I end up writing a function that returns the dataset that makes my test pass.  That doesn't seem to actually test the code, other than verifying a method is being called.

I know this is kind of abstract and vague, it seems that the idea of testing is very much abstract though, so hopefully someone has some experience and can guide me in the right direction.

Any advice, or reading I can do is more than welcomed.

Thanks in advance.

答:
I'm definitely not an expert on testing, but I think you're on the right track, what you need are more tests: you should have a test for every type of thing that the database can return (eventually; you don't need to come up with all of them right away). Mock out a different type of return value you could expect from the database (returned one result row, returned multiple, no results, for example) for each test and make sure that your method returns the correct values.

This way your first implementation can just return the results that you'd expect from your test, but as you add more tests you keep revising the implementation until it's as complete as needed.


问:
Unit of work principle is causing a problem in MVC3 application
I am implementing a website using MVC3, Entity Framework 4.1 and Repositoty pattern, Unit of work principle. But I am facing a big problem while implementing this.

I have developed a static ObjectContext class. This class is used across all the repositories so unit of work pattern is followed. I have e.g. ICustomer, IProduct repositories. I use specifically only one repository in a controller and that too is injected using NInject.

```<code>CustomerController(ICustomer customer)
{
}

ProductController(IProduct product)
{
}
</code>```

Since object context class is static and IProduct, ICustomer have parameterised constructor which accepts the objectContext class, these two will share the same ObjectContext instance.

When the execution is single threaded everything goes fine, but in multi-threading I get an unhandled exception, because of one repository closing the connection which was being used by other. I think if I make ObjectContext class not-static then this will solve the problem(Not tested yet) but then Unit of Work will not be observed.

Can you please suggest a solution for this?

答:
What you want is to instantiate one ObjectContext per web request, regardless of how many different database accesses might be required by that request. And you don't want to share it with any other web requests, or else you'll get your multithreading issues.

The approach I take is based on this blog post: "LINQ-to-SQL: the multi-tier story" by Steve Sanderson. Yes, it's about LINQ-to-SQL, not Entity Framework, but the same approach can be taken. Where he talks about LINQ-to-SQL DataContexts, just think EF ObjectContexts.

The approach you're currently taking is what he describes as "Story two: DataContext per application", and you've discovered the problems he talks about, namely to do with thread safety. You want to be moving towards what he calls "Story three: DataContext per unit-of-work (i.e. per request)", which involves creating one ObjectContext per web request and storing it in HttpContext.Current.Items, whose lifespan is that of a web request, and is private to that request.

Since you're already using dependency injection, you'll definitely want to read on to the final section "Stop! That’s still not good enough" where he explains how to break the dependency on HttpContext.Current using some simple inversion of control.


问:
Is it better idea to call an external command-line application or to internalize that application's logic?
I have a "pipeline" sort of process that is essentially just linking together a bunch of existing tools to automate a workflow. For one of the steps, there is an existing command-line tool that already does the meat of what that step needs to do.

The external CLI tool is java-based, and so is my pipeline, so it would be possible to integrate the tool directly into the pipeline step, but the tool is very complex and is currently closely tied to having command-line input (something like 37 config flag options).

The question is: Is it a better idea to simply call out and invoke the external process, or would it be better to integrate the external code within my application?

What are the pros / cons of integrating vs. calling the external process?

答:
Ideally you'd want to integrate it.  Especially if this is an app that gets distributed - reducing the number of dependencies and configurations will make that easier.  But its of course a cost/benefit issue for your specific case.

That said, one thing to consider is stability.  I encountered something similar a couple of years ago and kept the cli program in place.  It was too unstable, and I didnt want its crashing to take down the parent application, which needed to run 24/7.  Now this wasnt a java app, but none the less, if its an issue that may apply you may want to keep that in consideration.


问:
Unit-testing of inherently random/non-deterministic algorithms
My current project, succinctly, involves the creation of "constrainably-random events". I'm basically generating a schedule of inspections. Some of them are based on strict schedule constraints; you perform an inspection once a week on Friday at 10:00AM. Other inspections are "random"; there are basic configurable requirements such as "an inspection must occur 3 times per week", "the inspection must happen between the hours of 9AM-9PM", and "there should not be two inspections within the same 8-hour period", but within whatever constraints were configured for a particular set of inspections, the resulting dates and times should not be predictable.

Unit tests and TDD, IMO, have great value in this system as they can be used to incrementally build it while its full set of requirements is still incomplete, and make sure I'm not "over-engineering" it to do things I don't currently know I need. The strict schedules were a piece-o'-cake to TDD. However, I'm finding it difficult to really define what I'm testing when I write tests for the random portion of the system. I can assert that all times produced by the scheduler must fall within the constraints, but I could implement an algorithm that passes all such tests without the actual times being very "random". In fact that's exactly what's happened; I found an issue where the times, though not predictable exactly, fell into a small subset of the allowable date/time ranges. The algorithm still passed all assertions I felt I could reasonably make, and I could not design an automated test that would fail in that situation, but pass when given "more random" results. I had to demonstrate the problem was solved by restructuring some existing tests to repeat themselves a number of times, and visually check that the times generated fell within the full allowable range.

Does anyone have any tips for designing tests that should expect non-deterministic behavior?

Thanks to all for the suggestions. The main opinion seems to be that I need a deterministic test in order to get deterministic, repeatable, assertable results. Makes sense.

I created a set of "sandbox" tests that contain candidate algorithms for the constraining process (the process by which a byte array that could be any long becomes a long between a min and max). I then run that code through a FOR loop that gives the algorithm several known byte arrays (values from 1 to 10,000,000 just to start) and has the algorithm constrain each to a value between 1009 and 7919 (I'm using prime numbers to ensure an algorithm wouldn't pass by some serendipitous GCF between the input and output ranges). The resulting constrained values are counted and a histogram produced. To "pass", all inputs must be reflected within the histogram (sanity to ensure we didn't "lose" any), and the difference between any two buckets in the histogram cannot be greater than 2 (it should really be <= 1, but stay tuned). The winning algorithm, if any, can be cut and pasted directly into production code and a permanent test put in place for regression.

Here's the code:

```<code>    private void TestConstraintAlgorithm(int min, int max, Func<byte[], long, long, long> constraintAlgorithm)
    {
        var histogram = new int[max-min+1];
        for (int i = 1; i <= 10000000; i++)
        {
            //This is the stand-in for the PRNG; produces a known byte array
            var buffer = BitConverter.GetBytes((long)i);

            long result = constraintAlgorithm(buffer, min, max);

            histogram[result - min]++;
        }

        var minCount = -1;
        var maxCount = -1;
        var total = 0;
        for (int i = 0; i < histogram.Length; i++)
        {
            Console.WriteLine("{0}: {1}".FormatWith(i + min, histogram[i]));
            if (minCount == -1 || minCount > histogram[i])
                minCount = histogram[i];
            if (maxCount == -1 || maxCount < histogram[i])
                maxCount = histogram[i];
            total += histogram[i];
        }

        Assert.AreEqual(10000000, total);
        Assert.LessOrEqual(maxCount - minCount, 2);
    }

    [Test, Explicit("sandbox, does not test production code")]
    public void TestRandomizerDistributionMSBRejection()
    {
        TestConstraintAlgorithm(1009, 7919, ConstrainByMSBRejection);
    }

    private long ConstrainByMSBRejection(byte[] buffer, long min, long max)
    {
        //Strip the sign bit (if any) off the most significant byte, before converting to long
        buffer[buffer.Length-1] &= 0x7f;
        var orig = BitConverter.ToInt64(buffer, 0);
        var result = orig;
        //Apply a bitmask to the value, removing the MSB on each loop until it falls in the range.
        var mask = long.MaxValue;
        while (result > max - min)
        {
            mask >>= 1;
            result &= mask;
        }
        result += min;

        return result;
    }

    [Test, Explicit("sandbox, does not test production code")]
    public void TestRandomizerDistributionLSBRejection()
    {
        TestConstraintAlgorithm(1009, 7919, ConstrainByLSBRejection);
    }

    private long ConstrainByLSBRejection(byte[] buffer, long min, long max)
    {
        //Strip the sign bit (if any) off the most significant byte, before converting to long
        buffer[buffer.Length - 1] &= 0x7f;
        var orig = BitConverter.ToInt64(buffer, 0);
        var result = orig;

        //Bit-shift the number 1 place to the right until it falls within the range
        while (result > max - min)
            result >>= 1;

        result += min;
        return result;
    }

    [Test, Explicit("sandbox, does not test production code")]
    public void TestRandomizerDistributionModulus()
    {
        TestConstraintAlgorithm(1009, 7919, ConstrainByModulo);
    }

    private long ConstrainByModulo(byte[] buffer, long min, long max)
    {
        buffer[buffer.Length - 1] &= 0x7f;
        var result = BitConverter.ToInt64(buffer, 0);

        //Modulo divide the value by the range to produce a value that falls within it.
        result %= max - min + 1;

        result += min;
        return result;
    }
</code>```

... and here's the results:

LSB rejection (bit-shifting the number until it falls within the range) was TERRIBLE, for a very easy-to-explain reason; when you divide any number by 2 until it's less than a maximum, you quit as soon as it is, and for any non-trivial range, that will bias the results towards the upper third (as was seen in the detailed results of the histogram). This was exactly the behavior I saw from the finished dates; all of the times were in the afternoon, on very specific days.

MSB rejection (removing the most significant bit off the number one at a time until it's within the range) is better, but again, because you're chopping off very large numbers with each bit, it's not evenly distributed; you're unlikely to get numbers in the upper and lower ends, so you get a bias toward the middle third. That might benefit someone looking to "normalize" random data into a bell-ish curve, but a sum of two or more smaller random numbers (similar to throwing dice) would give you a more natural curve. For my purposes, it fails.

The only one that passed this test was to constrain by modulo division, which also turned out to be the fastest of the three. Modulo will, by its definition, produce as even a distribution as possible given the available inputs.

答:
It is not possible to test a nebulous condition that has no concrete definition. If the generated dates pass all tests then theoretically your application is functioning correctly. The computer cannot tell you if the dates are "random enough" because it cannot acknowledge the criteria for such a test. If all tests pass but the behavior of the application is still not suitable then your test coverage is empirically inadequate (from a TDD perspective).

In my view, your best best is to implement some arbitrary date generation constraints so that the distribution passes a human smell test.

ContentLicense: CC BY-SA 4.0


问:
Company PC refresh, laptop or desktop?
My company is getting PC refreshes with a choice of to have a desktop or laptop.  Each one seems to have its pros and cons. Would you want the flexibility and freedom of the laptop but take the risk of working extra hours at home? Or a desktop limited to one place, but not having to worry about taking work home and disrupting home time?

I'm not asking what would be better for coding, but more for convenience and productivity.  I currently have a desktop and work about 8 to 9 hours a day, with only coming in on the weekends for when we get behind on major deadlines. I love developing but I also have quite a busy life after work. I feel that having a work laptop will only haze the line of work and home.

答:
In general, I would favor the desktop.  It'll give you better bang for the buck, and keep the lines between work and play clearly defined.

If you decide you want to try having a laptop and your company allows it, consider bringing in a personal one for a while.  If it goes well, you have the choice to use both, and you can make a more informed decision for the next round of upgrades.  I did this, and found I only use the laptop at a couple meetings per week - the rest of the time, the desktop is a nicer options (large multi-mon, more hardware).

Title: Company PC refresh, laptop or desktop?


答: Just record the output of your randomizer (whether pseudo or quantum/chaotic or real world).  Then save and replay those "random" sequences that fit your test requirements, or that expose potential issues and bugs, as you build your unit test cases.</p>

Title: Unit-testing of inherently random/non-deterministic algorithms

Body:
My current project, succinctly, involves the creation of "constrainably-random events". I'm basically generating a schedule of inspections. Some of them are based on strict schedule constraints; you perform an inspection once a week on Friday at 10:00AM. Other inspections are "random"; there are basic configurable requirements such as "an inspection must occur 3 times per week", "the inspection must happen between the hours of 9AM-9PM", and "there should not be two inspections within the same 8-hour period", but within whatever constraints were configured for a particular set of inspections, the resulting dates and times should not be predictable.

Unit tests and TDD, IMO, have great value in this system as they can be used to incrementally build it while its full set of requirements is still incomplete, and make sure I'm not "over-engineering" it to do things I don't currently know I need. The strict schedules were a piece-o'-cake to TDD. However, I'm finding it difficult to really define what I'm testing when I write tests for the random portion of the system. I can assert that all times produced by the scheduler must fall within the constraints, but I could implement an algorithm that passes all such tests without the actual times being very "random". In fact that's exactly what's happened; I found an issue where the times, though not predictable exactly, fell into a small subset of the allowable date/time ranges. The algorithm still passed all assertions I felt I could reasonably make, and I could not design an automated test that would fail in that situation, but pass when given "more random" results. I had to demonstrate the problem was solved by restructuring some existing tests to repeat themselves a number of times, and visually check that the times generated fell within the full allowable range.

Does anyone have any tips for designing tests that should expect non-deterministic behavior?

Thanks to all for the suggestions. The main opinion seems to be that I need a deterministic test in order to get deterministic, repeatable, assertable results. Makes sense.

I created a set of "sandbox" tests that contain candidate algorithms for the constraining process (the process by which a byte array that could be any long becomes a long between a min and max). I then run that code through a FOR loop that gives the algorithm several known byte arrays (values from 1 to 10,000,000 just to start) and has the algorithm constrain each to a value between 1009 and 7919 (I'm using prime numbers to ensure an algorithm wouldn't pass by some serendipitous GCF between the input and output ranges). The resulting constrained values are counted and a histogram produced. To "pass", all inputs must be reflected within the histogram (sanity to ensure we didn't "lose" any), and the difference between any two buckets in the histogram cannot be greater than 2 (it should really be <= 1, but stay tuned). The winning algorithm, if any, can be cut and pasted directly into production code and a permanent test put in place for regression.

Here's the code:

```<code>    private void TestConstraintAlgorithm(int min, int max, Func<byte[], long, long, long> constraintAlgorithm)
    {
        var histogram = new int[max-min+1];
        for (int i = 1; i <= 10000000; i++)
        {
            //This is the stand-in for the PRNG; produces a known byte array
            var buffer = BitConverter.GetBytes((long)i);

            long result = constraintAlgorithm(buffer, min, max);

            histogram[result - min]++;
        }

        var minCount = -1;
        var maxCount = -1;
        var total = 0;
        for (int i = 0; i < histogram.Length; i++)
        {
            Console.WriteLine("{0}: {1}".FormatWith(i + min, histogram[i]));
            if (minCount == -1 || minCount > histogram[i])
                minCount = histogram[i];
            if (maxCount == -1 || maxCount < histogram[i])
                maxCount = histogram[i];
            total += histogram[i];
        }

        Assert.AreEqual(10000000, total);
        Assert.LessOrEqual(maxCount - minCount, 2);
    }

    [Test, Explicit("sandbox, does not test production code")]
    public void TestRandomizerDistributionMSBRejection()
    {
        TestConstraintAlgorithm(1009, 7919, ConstrainByMSBRejection);
    }

    private long ConstrainByMSBRejection(byte[] buffer, long min, long max)
    {
        //Strip the sign bit (if any) off the most significant byte, before converting to long
        buffer[buffer.Length-1] &= 0x7f;
        var orig = BitConverter.ToInt64(buffer, 0);
        var result = orig;
        //Apply a bitmask to the value, removing the MSB on each loop until it falls in the range.
        var mask = long.MaxValue;
        while (result > max - min)
        {
            mask >>= 1;
            result &= mask;
        }
        result += min;

        return result;
    }

    [Test, Explicit("sandbox, does not test production code")]
    public void TestRandomizerDistributionLSBRejection()
    {
        TestConstraintAlgorithm(1009, 7919, ConstrainByLSBRejection);
    }

    private long ConstrainByLSBRejection(byte[] buffer, long min, long max)
    {
        //Strip the sign bit (if any) off the most significant byte, before converting to long
        buffer[buffer.Length - 1] &= 0x7f;
        var orig = BitConverter.ToInt64(buffer, 0);
        var result = orig;

        //Bit-shift the number 1 place to the right until it falls within the range
        while (result > max - min)
            result >>= 1;

        result += min;
        return result;
    }

    [Test, Explicit("sandbox, does not test production code")]
    public void TestRandomizerDistributionModulus()
    {
        TestConstraintAlgorithm(1009, 7919, ConstrainByModulo);
    }

    private long ConstrainByModulo(byte[] buffer, long min, long max)
    {
        buffer[buffer.Length - 1] &= 0x7f;
        var result = BitConverter.ToInt64(buffer, 0);

        //Modulo divide the value by the range to produce a value that falls within it.
        result %= max - min + 1;

        result += min;
        return result;
    }
</code>```

... and here's the results:

LSB rejection (bit-shifting the number until it falls within the range) was TERRIBLE, for a very easy-to-explain reason; when you divide any number by 2 until it's less than a maximum, you quit as soon as it is, and for any non-trivial range, that will bias the results towards the upper third (as was seen in the detailed results of the histogram). This was exactly the behavior I saw from the finished dates; all of the times were in the afternoon, on very specific days.

MSB rejection (removing the most significant bit off the number one at a time until it's within the range) is better, but again, because you're chopping off very large numbers with each bit, it's not evenly distributed; you're unlikely to get numbers in the upper and lower ends, so you get a bias toward the middle third. That might benefit someone looking to "normalize" random data into a bell-ish curve, but a sum of two or more smaller random numbers (similar to throwing dice) would give you a more natural curve. For my purposes, it fails.

The only one that passed this test was to constrain by modulo division, which also turned out to be the fastest of the three. Modulo will, by its definition, produce as even a distribution as possible given the available inputs.


答: Your company and you are less likely to compromise on optimizing the ergonomics of a desktop setup (matched desk, chair, pointer, lighting, etc.)  If you are coding hours per day, your body will thank you for making an ergo setup a higher priority than portability.</p>

Title: Company PC refresh, laptop or desktop?

Body:
My company is getting PC refreshes with a choice of to have a desktop or laptop.  Each one seems to have its pros and cons. Would you want the flexibility and freedom of the laptop but take the risk of working extra hours at home? Or a desktop limited to one place, but not having to worry about taking work home and disrupting home time?

I'm not asking what would be better for coding, but more for convenience and productivity.  I currently have a desktop and work about 8 to 9 hours a day, with only coming in on the weekends for when we get behind on major deadlines. I love developing but I also have quite a busy life after work. I feel that having a work laptop will only haze the line of work and home.


答:
For the unit tests, replace the random generator with a class that generates predictable results covering all corner cases. I.e. make sure your pseudo-randomizer generates the lowest possible value and the hightest possible value, and the same result several times in a row.

You don't want your unit tests to overlook e.g. off-by-one bugs happening when Random.nextInt(1000) returns 0 or 999.


问:
Dealing with management that does not see value in improvements that are not immediately visible to the user
I can understand schedule pressure.  You want to please your users, as they are the lifeblood of the company. However, it is also true that certain changes will make everything easier down the road. Unfortunately, management in my organization has an instinctive resistance to such changes and this resistance is so strong that it gets in the way of long-term improvements.

For example, Apple recently introduced Automatic Reference Counting for iOS programs.  This is a major improvement over the manual retain/release calls one previously had to use.  The code is easier to write and easier to maintain. The changeover itself is likely to produce some crashes. But once those are worked out, the number of random weird crashes is likely to go down.

I recently mentioned to my boss that I wanted to switch to automatic reference counting.  His response was that he wanted to concentrate on visible improvements. It is likely that this response was in turn driven by pressure he is getting from above him - and probably right from the CEO.

There are a lot of similar examples.  The common thread is that something needs to be fixed but the short-term costs of the fix outweigh the short-term benefits, where "short term" is defined as "within the next few weeks."

How should I handle the situation?

EDIT:  Thanks for the responses.  Keep 'em coming.  Because it is relevant to my situation, I should make it clear that my manager and the CEO are both programmers -- though the CEO may by now have forgotten what this is like.  Apparently their programmer sides have been overwhelmed by other pressures.

答:
The common language of business across all fields and industries is money. The problem that you are describing is not a programming problem: it is a business problem. If you want to get an appropriate response to a business proposition you need to frame it in the language of business. This means that you must be able to present an alternate project plan including all of the costs and benefits.

You need to learn about things like opportunity costs, ROI (return on investment), and NPV (net present value).  You don’t need an MBA to do this, but you do need access to data that may not be available to you, such as manpower costs, overhead costs, and potential for revenues.  If you can make a clear argument that one path will provide more value than another using hard numbers, you will get full attention from management.


问:
Do GUI programmers have an undue advantage over others?
It is easy for managers and customers to appreciate what they can see.

I have seen many GUI developers who are average programmers with minimal knowledge of design principles or other programming idioms. However, these shortcomings often go unnoticed, specially by management and customers, if the programmer can create an impressive looking user interface. So much so that many GUI developers I know spend hours beautifying the GUI at the expense of writing bad, unmaintainable code.

On the other hand, middle tier programmers who develop APIs or business functionality or database code (SQLs etc.) are at a disadvantage as there is nothing tangible to showcase. Perhaps a code reviewer or an architect may appreciate the elegance, good design, scalability etc. of code but it means nothing to the outside world. Your code may run for years without breaking, may be very easy to maintain and have good performance, yet it never elicits the 'wow' that a slick looking GUI does.

In my opinion, a corollary to this is (and I am going to get heavily downvoted for this, I know) that there is less motivation for a GUI programmer to write good clean code.

EDIT: I must explain here that by GUI programmer, I don't mean a full-fledged web/GUI designer but a front-end programmer e.g., a java-swing programmer.

Does the rest of the community agree ?

答:
Testing UI parts of the application is a nightmare.

Every person around feel competent to give an advice or to set a demand how you should do it.

After the system works OK, later even if somebody maybe accidently recalls who hes the virtue in it, nobody will remember who did what.

But if any error will be seen (some always happen), the first man to be convicted will be the GUI programmer, The user simply never had seen the others!


答:
I view it like writing a research paper.  If I use someone else's ideas, then I need to give credit for those ideas.  I have used an answer from stackoverflow in my code before, and I added the link to the comments of method.

As someone mentioned, SO is a wiki style, so it's possible that it could change, but generally the idea should still be the same.

You should still give credit to others when you use their ideas.


答:
```<code>> (...) have you ever felt something about BDD that you would want to
> investigate in (...) ?
> This could help me a lot with constructing my research question.
</code>```

When usig dotnet-specflow i found it difficuilt to keep track of reusable step/action-method definitions and correspondig textfragments. For me it feels like having software with many global variables and methods.

May be your research can cope with organising these?

Body:
> (...) have you ever felt something about BDD that you would want to
> investigate in (...) ?
> This could help me a lot with constructing my research question.

When usig dotnet-specflow i found it difficuilt to keep track of reusable step/action-method definitions and correspondig textfragments. For me it feels like having software with many global variables and methods.

May be your research can cope with organising these?


问:
Is there an alternative to bits?
Is there an alternative to bits as the smallest unit of data? Something that won't be only 0 or 1, but actually hold many possible states in between? Wouldn't it be more natural to store floats like that?</p>

答: If you define natural by being close to how mother nature works, the most natural way of information encoding are DNA-like combinations of adenine, cytosine, guanine, and thymine. </p>

Title: Is there an alternative to bits?


问:
How could I make automatic tests for GUI?
How can I check automatically what is seen and what not? Or at least, how can I organize some partly automatic tests?

IDE: Eclipse (could use also IntelliJ Idea if necessary)

Testing tool: Junit (again, could use something else if advised, but better if it is free)

Application OS: Android

Developer's OS: Linux (could change for MAC or Windows(reluctantly))

Language: Java

All the work goes in the external device. No emulator.

The application is a user wrapper for the firmware TV player, called as external activity. So, 70% of the code is for GUI. (The other 30% speak to servers and provides info to the GUI)

Before I programmed the testing function myself, not using any tools. Now I have a tool at hand. But I can't imagine how could I test the UI, with the tool or without it. (Strictly said, with the Internet connections I have problems too, but I'll leave them probably for the other question.) The answer needn't be too platform-dependent, the principles and ideas will help, too.

Of course, it is good to check, is some element in another and checked or not. Some regression checks would be nice for that. But I should also be sure that the element mentioned is not cut by some other elements and winks as I ordered by animation.

The advices here:
https://softwareengineering.stackexchange.com/questions/63245/is-there-a-tool-to-test-java-ui
won't help - there are only tools, not principles, and none of the tools could help in my situation.

答:
Most often the best advice for automatic GUI testing is to develop your application in a Model-View-Presenter style and write your tests against the Presenter. The topic is discussed here:

http://danbunea.blogspot.com/2005/11/model-view-presenter-is-testing_27.html

(there are further links at the end of that article).

Of course, that might not help you to "check automatically what is seen and what not", but it may help you to test the most of the UI logic.


答:
I use testcomplete. Its a most comprehensive tool I've used to automate GUI testing.
http://smartbear.com/products/qa-tools/automated-testing/
check them out I am really positive that this will be a good fit for you and it does support Java</p>

Title: How could I make automatic tests for GUI?

Body:
How can I check automatically what is seen and what not? Or at least, how can I organize some partly automatic tests?

IDE: Eclipse (could use also IntelliJ Idea if necessary)

Testing tool: Junit (again, could use something else if advised, but better if it is free)

Application OS: Android

Developer's OS: Linux (could change for MAC or Windows(reluctantly))

Language: Java

All the work goes in the external device. No emulator.

The application is a user wrapper for the firmware TV player, called as external activity. So, 70% of the code is for GUI. (The other 30% speak to servers and provides info to the GUI)

Before I programmed the testing function myself, not using any tools. Now I have a tool at hand. But I can't imagine how could I test the UI, with the tool or without it. (Strictly said, with the Internet connections I have problems too, but I'll leave them probably for the other question.) The answer needn't be too platform-dependent, the principles and ideas will help, too.

Of course, it is good to check, is some element in another and checked or not. Some regression checks would be nice for that. But I should also be sure that the element mentioned is not cut by some other elements and winks as I ordered by animation.

The advices here:
https://softwareengineering.stackexchange.com/questions/63245/is-there-a-tool-to-test-java-ui
won't help - there are only tools, not principles, and none of the tools could help in my situation.


答:
If you have needed to implement a work-around, and it is not obvious why the implementation was done a particular way, then a comment really should be let to identify the reasons why.  I think placing a link to an online reference is fine, but you really need to have made your comment succinct, yet complete enough that the link will only provide an expanded explanation should the reader feel a need to double check your reasoning.

If on the other hand the code has been copied verbatim, then a link to the original source is only fair, and may be required depending on the wording of the license under which you have been allowed to copy the original author's work.


问:
Advice for good web server development setup
A month or so ago I created my first LAMP stack and implemented a simple web site that exercised each letter in that acronym.  However my development setup was much less than ideal.
I don't really have a local test server, but instead I was writing all of my CGI scripts in vim while ssh'ed into the remote machine as root.  Now I intend to start more serious development.

Question: What is a good setup so that development goes as easily as possible?

I would like to understand what is available to me along the lines of an IDE, subversion (or alternatives), uploading and downloading content, and just best practices.  I'm pretty new at all of this.  Also, feel free to point me at good websites.  There's plenty of websites, but only people who are already heavily developing web content are able to quickly determine if they are good websites.

答:
I am a happy man while I use these.

Zend Community server this is your LAMP stack.

Eclipse, Netbeans or Zend Studio as your IDE (Google these names)

phpUnit for unit testing

last I will always prefer Mercurial over subversion as my code revision controller. (Read this tutorial on Mercurial. There is a bit of learning curve but you will be a satisfied individual at the end of the day)


问:
Is Model-View-Presenter (MVP) scheme useful for Android?
How to separate View and Presenter in Android, while the reactions on the user actions (Presenter part of MVP) are set into the same activities that shows GUI elements (View part of MVP).

"In model view presenter just as Martin Fowler  or Michael Feathers  [2] say, the logic of the UI is separated into a class called presenter, that handles all the input from the user and that tells the "dumb" view what and when to display" (cited from here).

Till now I thought that one of the main features of Android is the smart Activity that takes actions, reacts to them and shows the results. Is MVP scheme in contradiction with Android philosophy? Has it sense to try to realize it on Android? If yes, how could it be done?

答:
I don't have any experience on Android programming, but having a short look into some introductory Android programming tutorials I don't see a reason why MVP should be less useful as in any other event driven framework. The Activity class is not very different from the Dialogor Form in other frameworks, so it should be easy to create an "Activitity Presenter" class for any Activity subclass of your application and put the core logic there.

Events send to your "Activity" must be delegated to your presenter, and if your presenter is going to send events on its own, or call other system dependent features, your Activity must provide related functions via the interface it shares with the presenter. But that is basically the same as in any other GUI framework I know of.


问:
I need some counter-points to counter the argument of why NOT to use M-V-P
I whipped up a demo on Friday before the holiday weekend of using the Model-View-Presenter pattern (the "Passive View" version, I believe) that I want to show to my co-workers this week as an example of how to architect our WebForms application moving forward and get maintainable, clean code.  We currently keep almost all logic outside of some data access routines in the code-behind files.

I know immediately one of the points raised will be that it's faster/easier to just use code-behind rather than create a separate class library for the views and presenters, and having to create a separate view per page (that at least can get hairy as we have well over a hundred pages, although at this point I'm talking about future development and not retrofitting the rest of the code).  The argument will be that it's much faster to get a task done by doing something like this:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    DataSet ds = Customer.Get(Request.QueryString["custid"]);
    if (ds.Tables[0].Rows.Count > 0)
    {
       txtFirstName.Text = ds.Tables[0].Rows[0]["fname"].ToString();
       // other properties here..
    }
}
</code>```

than this:

```<code>// CustomerDetails.aspx
private CustomerDetailsPresenter _presenter;

protected void Page_Load(object sender, EventArgs e)
{
    long customerId = Convert.ToInt64(Request.QueryString["custid"]);
    _presenter = new CustomerDetailsPresenter(this);
    _presenter.Init(customerId);
}

// CustomerDetailsPresenter.cs
class CustomerDetailsPresenter
{
    private ICustomerDetailsView _view;

    // ctor here...

    public void Init(long customerId);
    {
        // get customer somehow, via ORM or DataSet or whatever...
        _view.FirstName = firstName; // some string, whether from dataset or ORM
    }
}
</code>```

What counter-arguments can I use to show the benefit of using the MVP pattern?  Specifically ways it would improve the speed and efficiency of getting things done.  Just saying "it's cleaner" or "you can properly abstract the code" isn't enough because code quality has never been a big issue, just speed (and now that mentality is biting us in the rear).

NOTE: This is for new features to an existing brownfield/legacy application, not for a new site (I would chose MVC for a brand new site).  New pages that have to interact with the application as a whole, radical changes to old pages, and the like is what we normally do and what I'm talking about using MVP for.

答:
Testability wouldn't matter since we have no automated tests at all

Did I get you right - you test everything manually? And your coworkers think that is "faster/easier" than writing the code in a way that it could be easily tested automatically?

Ask your coworkers that and show them how absurd that sounds, perhaps this the argument you are looking for.


问:
Need help with algorithm for sorting list
The answer is probably obvious but not to me at this moment, so I was wondering if somebody who is better with sorting algorithms can help lead me in the right direction.  This is not homework, I am legitimately trying to work within an existing design for something work related.

Essentially I start with an unordered list of data objects that represent something similar to forum comments.  These objects MAY explicitly have one and only one direct parent.  In other words

Parent (1...*) ----------- (1...1) Child

A child has a reference to its parent, however a parent cannot see its children (explicitly).

Typically when sorting a list one would pass a comparator which given any two data objects in the collection should return an integer number that represents the distance between the two objects in a graph.  The distance between two completely unrelated comments will be based on the Timestamp value of the data object.

The issue is that any two data objects can and should only be compared by timestamp with other data objects from the same parent branch.  Here is an example:

DO1 - Time(1000ms)

|___DO3 - Time(5000ms)

DO2 - Time(2000ms)

DO1 and DO2 compared will result in a negative number so those two are sorted correctly relative to each other.  DO3 to DO1 is likewise correct because I can assume that any branch above a comment must be less than.  The problem comes with comparing DO3 to DO2.  I thought that I should compare the highest order parent to DO2 in this case and that works until there are DO children under DO3.

I am trying to figure out if the current object graph is even enough information for a comparator to correctly return an appropriate number for any two comparisons.  Perhaps the comparator needs to be initialized with the unordered list first so that it can build a tree structure where I can see a list of children from any given parent explicitly?  Or perhaps I need to refactor?  At this stage I am not concerned about performance.  Thank you.

答:
The obvious approach is to walk the tree depth first, taking children of each node in order of their timestamp. That is the order you want.

Building the tree and than iterating it will obviously save you time, but you can just take all entries with given parent pointer while testing.

Alternatively you could define the ordering so that descendants come after their predecessors and other nodes are ordered by timestam of immediate children of their common ancestor. So:

```<code>ROOT
 +- DO1 T=1
 |   +- DO2 T=5
 |   +- DO3 T=8
 |       +- DO4 T=12
 +- DO5 T=3
     +- DO6 T=11
</code>```

DO2 > DO1 because it's a descendant, DO4 >DO1because it's also descendant,DO3>DO2because they are both immediate children to their ancestorDO1andDO3has higher timestamp andDO6>DO4because their ancestor isROOTto which you come fromDO6viaDO5and fromDO4viaDO1andDO5has higher timestamp thanDO1`.

But building and walking the tree is going to be faster.

Body:
The obvious approach is to walk the tree depth first, taking children of each node in order of their timestamp. That is the order you want.

Building the tree and than iterating it will obviously save you time, but you can just take all entries with given parent pointer while testing.

Alternatively you could define the ordering so that descendants come after their predecessors and other nodes are ordered by timestam of immediate children of their common ancestor. So:

ROOT
 +- DO1 T=1
 |   +- DO2 T=5
 |   +- DO3 T=8
 |       +- DO4 T=12
 +- DO5 T=3
     +- DO6 T=11

DO2 > DO1 because it's a descendant, DO4 >DO1because it's also descendant,DO3>DO2because they are both immediate children to their ancestorDO1andDO3has higher timestamp andDO6>DO4because their ancestor isROOTto which you come fromDO6viaDO5and fromDO4viaDO1andDO5has higher timestamp thanDO1`.

But building and walking the tree is going to be faster.


答:
Android applications are fundamentally built around Model-View-Controller (MVC) - MVP sounds like the same thing, although I've not heard the term before. Activities fill the role of Controller, XML Views are just that (although you can build them programmatically in the Activity - it's just easier and simpler to do it in XML), and the Model you write yourself. So yes, that model is quite practical.

A possible reason you may not have heard much about this design model is that the Android framework forces you to separate the view out. Because the application on mobile devices tend to be small, people don't tend to use full-on MVC; they tend toward view and action layers where the action layer does much of the model's (small) job.

If you are writing a cross platform app, you may want to look at a four-layer approach: View, Action, Business Logic, and Model. The View and Action layers would be platform specific, while the Business Logic and Model would not change. Basically, you split out the presenter and user interaction out to the Action layer, which calls the Business Logic layer to perform the action the user wants.

Title: Is Model-View-Presenter (MVP) scheme useful for Android?

Body:
How to separate View and Presenter in Android, while the reactions on the user actions (Presenter part of MVP) are set into the same activities that shows GUI elements (View part of MVP).

"In model view presenter just as Martin Fowler  or Michael Feathers  [2] say, the logic of the UI is separated into a class called presenter, that handles all the input from the user and that tells the "dumb" view what and when to display" (cited from here).

Till now I thought that one of the main features of Android is the smart Activity that takes actions, reacts to them and shows the results. Is MVP scheme in contradiction with Android philosophy? Has it sense to try to realize it on Android? If yes, how could it be done?


问:
Determining the right amount of documentation
Where I currently work the general approach is -

avoid documentation as much as possible

Only document if a different team will need it

just for clarification, I don't mean code-documentation - this we do, I mean all the documentation surrounding the design process - if it's UML or DB Schemas, class diagrams and word documents with specifications and the likes.

I will list my Boss' reason to not document:

it's time consuming - focus on implementing

if design change - then the documentation should change, double trouble

in the end you just get hundreds of pages nobody wants to read, and nobody really edits so by time it will get out of date

Its a pain - nobody really wants to do it

Now I realize we do work faster, but I also remember the time getting here and diving straight to some old code, not understanding anything.

Actually, I still don't get most of this old code, and sometimes when I get in I see many patches from different developers trying to make small tweaks.

I really think lack of documenting promotes these kind of patches and lack of system understanding in a broad sense.

my question is:

How can we balance documentation so that we will promote continuous knowledge among the team and still be fast and efficient?

答:
Your boss is right don't print any UML documentation that nobody will read.
What we do in our team is to navigate live in the model using class diagram views. The principle is to always update MOF, the UML model live from the code and let the class diagram only be a viewer of the model but not the model itself.

It works really well because all the complexity is done in backoffice at model level. I can refactor my project, write java doc or write uml documentation in the model. It is a kind of click and go. When you click you get the live documentation.
If something is not clear then I open the class diagram and start playing with it. Delete from diagram classifiers, add new classifiers, zoom in and out, show association, delete association etc...The model is not changed because I do not create any new model information, I just use them.

It is really important to open the diagram of a package and be able to read directly in the class diagram a comment on what this class is supposed to be. What this method is supposed to do and what is the flow etc....

UML is great, really helpful but we should stop using Model Driven Devleopment in order to give more flexibility and more iteration at modeling/development stages. The class diagram is live updated from the code and documentation is always accurate and available just by a click.
I will not mention a tool but if you use Java and Eclipse it is easy to find which tool I use :-)


答: There are testing frameworks that allow you to interact with the screen directly; at my job we use IBM Rational Functional Tester, which allows us to click buttons and so on as well as the usual programmatic testing. Obviously, that's not free, but looking it up on wikipedia provides this list of alternatives. Since you're looking at Java, there's CubicTest, which is an Eclipse plugin; alternatives include Maveryx and Abbot.</p>


问:
When using Git, is using the master branch for active development advisable?
First, some background, we are in the process of moving all of our project teams over to using git and are in the process of laying down the guidelines for how the repositories should be organized so that certain branches can also be monitored for continuous integration and automatic deployment to the testing servers. Currently there are two models that are developing:

Heavily influenced by the nvie.com article on successful branching with the master branch representing the most stable code, a development branch for the bleeding edge code, and an integration branch for code that is ready for QA testing.

An alternate model in which the master branch represents the bleeding edge development code, an integration branch for code that is ready for QA testing, and a production branch for the stable code that is ready for deployment.

At this point, it is partly a matter of semantics in regards to what the master branch represents, but is doing active development on the master branch actually a good practice or is it not really that relevant?

答:
No, it's not advisable, even in the beginning before you've gone to QA. As a best practice, the pattern for development should be consistent from start to finish. Your master branch should start out empty, you should branch your development branch off and begin adding files, merge into your integration branch, then subsequently to your master.

While no one may care during development that the master branch doesn't build, it lends itself to bad habits early on. The master should always build, and for major feature releases it also wouldn't be a bad idea to have archived branches of major builds so that stable release points can be returned to if necessary.


问:
Organizing projects in SVN
I'm fairly new to SVN and I would be interested in hearing about how other people would organize projects in SVN.

We have projects that have different types of source files: C#, SQL, and Matlab.  In addition to these types of files, we have Excel and Word file reports that we do not intend to put into SVN.

So let's say we have a projects directory:

```<code>Projects\
Projects\Project1
Projects\Project2
...
</code>```

Now for the SVN repository, would it make sense to categorize things by source file type (C#, SQL, Matlab) then project:

```<code>SVN\C#\Project1
SVN\C#\Project2
SVN\SQL\Project1
SVN\SQL\Project2
SVN\Matlab\Project1
SVN\Matlab\Project2
</code>```

Or would it make more sense to categorize things by project first then source file type:

```<code>SVN\Project1\C#
SVN\Project1\SQL
SVN\Project1\Matlab
SVN\Project2\C#
SVN\Project2\SQL
SVN\Project2\Matlab
</code>```

Or maybe there's a better way to do this?

Also, what is the best way to indicate in the Projects folders (not SVN) that a project contains files saved in SVN?  Like, if I went into a the project folder for Project1 (Projects\Project1) and only saw Excel and Word reports, what would be the best way to indicate that there are other files checked into an SVN repository?

Also, how does everyone feel about putting checked out SVN files on shared drives?  So for instance, let's say Projects\Project1 contains the following files:

```<code>Report1.doc
Script.sql (This is a checked out SVN files in the Projects folder, which is a shared network drive)
</code>```

In this situation, it would be very easy to see when there are SVN files used with a project, BUT having the checked out SVN file on a shared drive would make collaboration much more difficult.  Is this others do to?

答:
You have three questions there:

It makes more sense to group by project, i.e. svn\project1\whatever, since "project" is the most meaningful category. Why would you group completely unrelated projects just because they are implemented in C#?

Not sure I understand your second question. With SVN, files in your working copy may have several possible statuses: checked in, dirty (i.e. you have uncommitted local changes), ignored (i.e. local files not managed by the repository), etc. Use an UI such as TortoiseSVN (if you are using Windows) and it will nicely show you the "status" of each file. Or you could use the command line as well, but that's less user friendly.

"Also, how does everyone feel about putting checked out SVN files on shared drives?" This question makes me think you don't entirely understand the purpose of using a source versioning tool such as SVN. The purpose of checking out files is for you to have a local copy to work with. If you share this copy, especially if you provide write access to it, you are defeating part of the purpose of using SVN to begin with!

Note that SVN cannot gracefully handle conflicts in XLS and DOC reports, because they are binary files (you'll get a conflict if two people try to modify and commit the same file). Merge/diff in SVN is meant for text-based files, such as source code, not for binaries. One way to solve this problem is to lock your binaries for editing. This can be done using the svn lock command (or the corresponding option from an UI such as TortoiseSVN).

You may want to read an explanation of when locking is necessary. It's relatively easy to understand.

Title: Organizing projects in SVN


问:
Multiple source files vs. libraries for a single project
I write a lot of scientific software, and I originally got into programming with F77. I moved to C++ for my primary programming about 10 years ago now, but I do catch myself using F77 habits. One thing I cannot seem to get used to is library usage. To be clear, I understand why one would want to use one, but for most of the code I write, no one but the end user and the maintainers will ever use the routines I write, so I question the usefulness to me.

Okay, so libraries give you a good place to stash reusable code that's easy to follow and maintain. But didn't separate source files already solve that problem for my situation? What advantage would I gain by putting my source files into a library? I can understand executable file size savings with shared libraries, but is that all that important? I have a lot of math routines that are general and could be extracted to a shared library, but should I? Most of them are only called once by a single point in my code, and usually only by a single project, so do I gain anything? Isn't any memory savings gone the moment the symbol is resolved, and the code loaded? Thanks.

答:
In your situation, you'd gain very little.  In fact, you'd come up with a slight net loss as you now have a program and a library to maintain instead of just a program.

What you're really looking at is a question of where the object files for each of your sources end up, and maintaining them all in one place is perfectly acceptable until they need to be shared.  The important thing is make sure your code is well-organized and modular so that when the time comes to share the general-purpose parts with a second project, making the split won't be a headache.

As executable size is concerned, code is code no matter where it comes from.  Most modern operating systems demand page their executables and will share pages from the same binary across multiple copies running simultaneously.  Code that gets used across many programs (e.g., the C library) makes sense to have in a shared library.  For anything that's going to be used exactly once, it won't make a lot of difference whether it's in a static binary or one that links in shared libraries.  (There's some additional overhead in dynamic versus static linking, but in general those hairs don't need to be split.)


问:
Is a programmer supposed to be self-sufficient?
At my current workplace, we don't have any testers, the rationale for that from the management being: "if we had testers, you wouldn't test your own code at all". This kind of thinking seems to be detrimental to product quality, as while I do test my own code, there are a lot of things that I will miss just for the fact that I know the system inside out and don't know how to use it "wrong". Black box testing doesn't really work as I subconsciously avoid the pitfalls that a dedicated tester would fall into. A lot of my time goes into fixing bugs that have slid into production code and found by the end user.

The system in question is large but is developed solely by me. This has also caused some managemental duties to fall on my lap, such as defining schedules and working on specifications.

Should these kind of tasks be my responsibility? I see myself strictly as a programmer and nothing else. And if these are my responsibility, to what extent? When is a project so large that it requires testers? Should a programmer have to refine the specification, worry about management of the project or even provide customer support?

Note

Some might have got the impression that I am against widening my responsibilities – that is not the case, I'm eager to get a role that involves more management duties, but currently it is not in my job description. Until I'm officially employed as such or the additional duties start showing in my paycheck, I'm going to think of myself as 'just' a programmer. Unfortunately, as a junior developer, shifting to managerial duties is not going to happen very soon.

Excellent answers so far, keep them coming if you have something to add or personal experiences to share!

答:
We have testers. I would not want to work without them. Although I do write unit tests (using TDD), and automated integration test for all my code, testers still have a very valuable function.

They are highly skilled, and have different skills to programmers.

They have lots of experience and knowledge of how to do QA testing, and how to verify that the code that has been produced really matches both the user's expectation and the actual behavior of the users.

They have experienced many bugs, and are very good at thinking of situations that could break the software.

They tend to be cynical and systematic. I have observed that programmers are often much more optimistic.

They provide valuable early feedback on usability. For instance, when creating a REST API recently, areas which the QA testers could not understand easily were a good indication of areas that the user would also be unhappy with.

They test on the actual environment, in fact many configurations of the real hardware, OS, etc.

They know how to build large scale, realistic, test beds and do performance, load and stress testing

They are focused on preventing bad releases from getting out. Programmers tend to focus on getting the code released. Its almost like, a programmer will release the code by default, but a QA tester will need a reason to release it (it has been shown to work!)


问:
Creating controls dynamically in the code-behind or ViewModel?
Right now I'm working migrating an app I made entirely using code behind to MVVM and had a question on where I'm supposed to be creating controls dynamically.

Basically I have a web service that returns {#} of items. For each item a button will be created and the item will be assigned to its data context.

Now so far I know that I should set the Command to the ViewModel as well as the Command property. Also I know I should call those items in my web service inside of the view model (or model, right now its irrelevant to the question). The part that is questionable is where to create the buttons.

I didn't really like the idea of creating buttons in my ViewModel since it was, well, related to the View. Is this correct or should I be creating them inside the ViewModel and then some how pass them back to the View via Messaging?

答: Your viewmodel should expose the colleciton of items, and the view should consume those items through databinding, creating the buttons in whatever control (list etc) is consuming them.</p>


答:
What's the benefit of segregating source files based on language? Why put all the resources (code, images, configuration files, etc.) in the same project directory? I'd stick with the conventional SVN layout and have subdirectories for trunk, branches, and tags:

```<code>Projects\
    Project1\
        trunk\
        branches\
        tags\
    Project2\
        trunk\
        branches\
        tags\
    ...
</code>```

Within a project directory such as trunk, you'd have all the files that you need to build the project. If it makes sense to divide them into subdirectories, do it, but make sure that there's some benefit to the organization. For example, you might have a directory for artwork so that you can let your graphics team access those files but not the source code, and your programmers can access the source code but can't change the art. Or, it might just make it easier to copy all the image files to the right spot in the product during the build process. If it makes sense to segregate files by language, there's nothing wrong with doing that too. Just know why you're doing it.

Take a look at Version Control with Subversion for a great deal of helpful information. For example, there's a chapter on administering a repository that starts off by considering repository organization.

Title: Organizing projects in SVN

Body:
I'm fairly new to SVN and I would be interested in hearing about how other people would organize projects in SVN.

We have projects that have different types of source files: C#, SQL, and Matlab.  In addition to these types of files, we have Excel and Word file reports that we do not intend to put into SVN.

So let's say we have a projects directory:

```<code>Projects\
Projects\Project1
Projects\Project2
...
</code>```

Now for the SVN repository, would it make sense to categorize things by source file type (C#, SQL, Matlab) then project:

```<code>SVN\C#\Project1
SVN\C#\Project2
SVN\SQL\Project1
SVN\SQL\Project2
SVN\Matlab\Project1
SVN\Matlab\Project2
</code>```

Or would it make more sense to categorize things by project first then source file type:

```<code>SVN\Project1\C#
SVN\Project1\SQL
SVN\Project1\Matlab
SVN\Project2\C#
SVN\Project2\SQL
SVN\Project2\Matlab
</code>```

Or maybe there's a better way to do this?

Also, what is the best way to indicate in the Projects folders (not SVN) that a project contains files saved in SVN?  Like, if I went into a the project folder for Project1 (Projects\Project1) and only saw Excel and Word reports, what would be the best way to indicate that there are other files checked into an SVN repository?

Also, how does everyone feel about putting checked out SVN files on shared drives?  So for instance, let's say Projects\Project1 contains the following files:

```<code>Report1.doc
Script.sql (This is a checked out SVN files in the Projects folder, which is a shared network drive)
</code>```

In this situation, it would be very easy to see when there are SVN files used with a project, BUT having the checked out SVN file on a shared drive would make collaboration much more difficult.  Is this others do to?

Body:
What's the benefit of segregating source files based on language? Why put all the resources (code, images, configuration files, etc.) in the same project directory? I'd stick with the conventional SVN layout and have subdirectories for trunk, branches, and tags:

Projects\
    Project1\
        trunk\
        branches\
        tags\
    Project2\
        trunk\
        branches\
        tags\
    ...

Within a project directory such as trunk, you'd have all the files that you need to build the project. If it makes sense to divide them into subdirectories, do it, but make sure that there's some benefit to the organization. For example, you might have a directory for artwork so that you can let your graphics team access those files but not the source code, and your programmers can access the source code but can't change the art. Or, it might just make it easier to copy all the image files to the right spot in the product during the build process. If it makes sense to segregate files by language, there's nothing wrong with doing that too. Just know why you're doing it.

Take a look at Version Control with Subversion for a great deal of helpful information. For example, there's a chapter on administering a repository that starts off by considering repository organization.


问:
How do you convince management to "invest" in unit tests?
How did you convince your manager to let you unit test?

By "use", I mean being allowed to develop, check-in to source control and maintain the unit tests over time, etc.

Typical management objections are:

The customer didn't pay for unit tests

The project does not allow time for unit testing

Technical debt? What technical debt?

Do you know other objections? What were your answers?

Thanks in advance!

答:
For every customer facing production issues,

Write a Unit test and send an email to the manager saying that You
have added a Unit test to cover the scenario.

And tell him that This issue will not happen again in production
because our unit test is running nightly and we will come to know
before the code goes to production by watching this unit test
failure.

Tell him that if we already had this Unit test in place before the
code went to production, this production issue would never have
happened.

Do this consistently and persistently and soon he will be convinced. Managers do not like the customer facing production issues and he will buy into the Unit testing idea. Good luck.