问:
Are unit tests really that useful?
I just graduated with a degree in CS and I currently have a job as a Junior .NET Developer (C#, ASP.NET, and web forms). Back when I was still in university, the subject of unit testing did get covered but I never really saw the benefits of it. I understand what it's supposed to do, namely, determine whether or not a block of code is fit for use. However, i've never actually had to write a unit test before, nor did I ever feel the need to.

As I already mentioned, I'm usually developing with ASP.NET web forms, and recently I've been thinking of writing some unit tests. But I've got a few questions about this.

I've read that unit testing often happens through writing "mocks". While I understand this concept, I can't seem to figure out how I'm supposed to write mocks for websites that are completely dynamic, and where almost everything depends on data that comes from a database. For example: I use lot's of repeaters who have ItemDataBound events etc. (again depending on data that is "unknown").

So question number 1: Is writing unit tests for ASP.NET web forms something that is done often, and if it is: how do I resolve the "dynamic environment" issue?

When I'm developing I go through a lot of trial-and-error. That doesn't mean I don't know what I'm doing, but I mean that I usually write some code, hit Ctrl F5 and see what happens. While this approach does the job most of the time, sometimes I get the feeling that I'm being a little clueless (because of my little experience). I sometimes waste a lot of time like this as well.

So, question number 2: Would you guys advise me to start writing unit tests? I think it might help me in the actual implementation, but then again I feel like it might slow me down.

答:
Edit: I of course joined the TDD pro/con dogpile and skipped question #1:

1 - Implementing unit tests in ASP.net webforms:

First of all, if you think you can get them to go with MVC, fight for it like a rabid cavebear. As a front end/UI dev, .net MVC is what helped me stop hating .net so I could concentrate better on hating every Java web solution I've ever run into. Unit tests are problematic because webforms really blurs the lines between the server and the client-side. In any attempt to do unit testing I would put the focus on data manipulation and (hopefully) assume webforms handles the normalization of user input for you under the hood.

2 - On whether unit tests are worthwhile in the first place:

Alright, full-disclosure:

I am mostly self-taught. My formal training boils down to like one JavaScript, a PHP, and a C# class and my own personal study of OOP principles and reading from stuff like Design Patterns.

However,

I mostly write for the client-side web and the actual programming part of that is in one of the most fast and loose languages out there in regards to dynamic typing, first class functions and object mutability.

That means, I don't write for the same compiler or virtual machine. I write for like 4-20 varying interpretations of three languages (yes, two of them merely declarative but also determining the fundamental physical space of the UI I'm working with in different ways sometimes) and have been doing so since the interpretations were a lot more varied than they are today. And no, I'm not just some kid that plugs in JQuery stuff for disposable apps. I help build and maintain fairly sophisticated stuff with a lot of UI element complexity.

So yes, there are lots of opportunities for a few tweaks here and there to create a massive cascade of failures if your design skills are complete crap or you're throwing mediocre devs in large quantities at 1-2 quality dev problems.

My understanding of what TDD is supposed to do for you is that the tests are really more about forcing you to consider design more carefully and keep you focused on requirements. Fair enough, but the problem here is that it subverts what you should be doing, which is designing to an interface, to something subtly but fundamentally different, which is designing for tests of an interface. The difference to me is between drawing a clear picture that mommy won't have to guess the meaning of and filling the whole page in with green really fast so you can be the first kid to slap his crayons on the table and shout "done!" By shifting priority to results over process and design, you're basically encouraging continued implementation of garbage code, which is typically what was at the root of your problems in the first place.

And then of course there is the "not-the-real-point-of" yet often lauded side-benefit of the unit tests themselves helping you detect regression errors. TDD advocates tend to be a little wishy-washy on whether this is actually the goal or just a nifty side-effect, IMO, because they know damn well or suspect at least that this is simply not sufficient to establish the absence of bugs in your code, especially in a more dynamic language like JavaScript where assuming you even can predict every possible scenario in a long chain of dependencies is foolhardy.

There is a place for automated-testing in JS, but a much better use of your time than attaching a unit test to every single 'unit' of your code that comes into contact with another is making sure you don't have a bunch of garbage objects that duplicate work or whose intended usage is semantically ambiguous in there in the first place. You follow the DRY principle. You abstract things out for re-use/portability when the value of doing so becomes apparent (and not a minute before). You establish consistent processes and ways of doing things following more of a carrot than stick principle (i.e. it's too easy to use your stuff the right way to bother wanting to do it the wrong way). And for the love of all things foo and bar, you never indulge in massive cascading inheritance scheme anti-patterns as a means of code reuse.

All of the above have helped me reduce difficult-to-diagnose bugs in my code in a serious way and you can trust that's a big priority for somebody who came up as a developer with a browser set that had nothing better to tell you than "uh there's been a problem with an object of type 'Object' at this imaginary line number in an unspecified file." (gee, thanks IE6) TDD, in my line of work, would not encourage these things. It would shift focus to 100% results over process where what's between point A and B doesn't really matter as long as it works. It is a waste of time that would be better applied towards making sure your stuff is legible, portable, and easy to modify without a lot of confusing breakage in the first place.

Or maybe I'm just being overly curmudgeonly about the paradigm I'm rooted in, but in my opinion, doing it right in the first place is a much more effective use of time than covering your butt for when you or everybody else on your team does it wrong. And nothing should force you to consider design over just getting things implemented. Design should be every programmer's freaking altar. And anything that "forces you" to do the right thing or protects you from yourself should be viewed with the same suspicion reserved for bottles of snake oil, IMO. Snake oil in modern IT and general development, if you're not yet aware, is sold by the liquid ton.

Title: Are unit tests really that useful?


问:
Agile development challenges
With Scrum / user story / agile development, how does one handle scheduling out-of-sync tasks that are part of a user story?

We are a small gaming company working with a few remote consultants who do graphics and audio work. Typically, graphics work should be done at least a week (sometimes 2 weeks) in advance of the code so that it's ready for integration. However, since SCRUM is supposed to focus on user stories, how should I split the stories across iteration so that they still follow the user story model? Ideally, a user story should be completed by all the team members in the same iteration, I feel that splitting them in any way violates the core principle of user story driven development.

Also, one front end developer can work at 2X pace of backend developers. However, that throws the scheduling out of sync as well because he is either constantly ahead of them or what we have done is to have him work on tasks that not specific to this iteration just to keep busy. Either way, it's the same issue as above, splitting up user story tasks.

答:
I think @S.Lott really captured the essence of the issue here, but considering Bob's desire to maintain the idea of user stories, @JDMyers answer is excellent. You want to break a problem down into manageable chunks, and if it helps to create parent-child stories, then do so. And cross train so every member knows at least a little about their areas of non-expertise. If your front-end guy has extra time, let him learn more about back-end technologies so he can help in that area. He's a member of a team, and the team is trying to achieve the goal (i.e., quickly releasing useable software) together.

As for user stories, remember, it doesn't really matter whether all tasks for a given story are completed or not during a given iteration. What matters is that your team is delivering what it's supposed to when it's supposed to (assuming realistic expectations are being set). Make sure the real problem is understood. Is it that a certain process doesn't seem "right", or is it that business expectations aren't being met? Agile and user stories aren't an end in and of themselves. They're a means to an end, namely delivering product in a timely manner. Refine your process so it supports your ultimate goal.

OwnerDisplayName: Bob

ContentLicense: CC BY-SA 3.0

Title: Agile development challenges


问:
JavaScript application design patterns
I need to write a PhoneGap application with JavaScript and I'm thinking of the code design patterns. I've read some books of JavaScript design patterns but can't really see the advantages/disadvantages on them and I think I don't understand the implementation and usage right.

I would like to have some opinions of which might suit my needs best. I'd like the code to be readable and maintainable.

The application itself is quite small and simple. It has a player management (add/remove), a game management (add/remove players from a team, start/stop/reset a stopwatch).

In last app I created I had over 30 named functions in a global scope which I think is a big no no. So, now I want to make things right, and was thinking of either using an object literal or a module pattern... something like this perhaps:

```<code>var MYAPP = {
    init: function() {
        $(document).ready(function() {
            MYAPP.bind();
        });
    },

    bind: function() {
        // Bind jQuery click and page events
    },

    player: {
        add:            function(name) { ... },
        remove:         function(name) { ... }
    },

    team: {
        addPlayer:      function(name) { ... },
        removePlayer:   function(name) { ... }
    },

    game: {
        create:         function() { ... },
        startTime:      function() { ... },
        stopTime:       function() { ... },
        resetTime:      function() { ... }
    }
};

document.addEventListener('deviceready', MYAPP.init, false);
</code>```

... or perhaps this?

```<code>var MYAPP = {
    init: function() {
        $(document).ready(function() {
            MYAPP.bind();
        });
    },

    bind: function() {
        // Bind jQuery click and page events
    }
}

var PLAYER = (function () {

    // Some private variables
    var privateVar, privateMethod;

    return {
        add: function (name) { ... },
        remove: function (name) { ... }
    };

}());

document.addEventListener('deviceready', MYAPP.init, false);
</code>```

答: This article is the best I've come across explaining various JS design patters and how they can come together as your application grows.  I typically use something similar to the YUI pattern because it's easy for anyone to read and includes private and public methods and properties.</p>

Title: JavaScript application design patterns


问:
Reusing Mocks/Stubs as Test Specification
We use mock to ensure that a unit test only runs against the code that should be tested. This prevents that a bug in a module A causes tests of a dependent module B to fail. However, now we also have to test the interaction explicitly. It is not enough that A and B are green on their own, A has to work as B expects it, and B has to have the right expectations.

Now, B's expectations are already formally defined: in the mocks and stubs. If I have a stub where A returns certain output for certain input, this means I expect it must be possible to have A in a state where it shows this behavior.

So instead of writing long integration tests, I just have to set-up an A and test it against the stubs and mocks that are already there. Or, to turn it around, I can use an actual instance of A to test the correctness of my mocks.

Does this work in practice? Are there best practices (e.g., where do these pseudo-integration tests belong to, should A's test suite already provide some likely-to-be-used mocks)? Is this even possible with the popular mocking frameworks?

答:
Does this work in practice?

It can, but the problem comes in instantiating the mock. Often times the integration you're testing is some sort of instance resolution that spins up and glues together the different pieces; or your deployment scripts. If you change that to spin up mocks, then you've violated your test.

So it mostly depends on your specific scenario. There's nothing particularly wrong with re-use as a general practice here.


问:
Cloud computing platforms often default to one CPU. Does this mean I shouldn't use Parallel Programming?
Almost every cloud instance I can find defaults one CPU.  Why is this only one CPU now, and should I expect this to increase in the future?

Does this design impact my code design so that I exclude technologies like Task Parallel Library?

This is on topic to Programmers.SE because it impacts the long-term scalability of muti-threaded code on cloud platforms.

答:
For sure, you should plan for the execution environment you are expecting to use.

The cloud platform I use lets me define VMs with multiple CPUs.  If explicit parallelism is important to you, select a different vendor.


答:
If I understand your question correctly, you want to test integration without integrating. I consider that mocks and stubs and fakes and so on should be used to control the indirect input and output and to properly test behavior when necessary. That is what Gerard Meszaros says in xUnit Test Patterns: Refactoring Test Code.

If I would have a class A and a class B I would use mocks to test each separately, exactly as you specified.

However, an integration test should exercise both objects. The integration tests should only cover the paths leading to communication between the objects. These communications should happen, for real. What you suggest is not quite right for integration testing. It is doable from a technical point of view, but it is not right from the point of view of the level of testing you want to do.

Of course, you can mock, stub, fake, etc. any D, E, F ... Z classes needed to initialize A and B. In some more complex situations, you can even partially mock A and B, so that some methods will return what you want without doing tons of computations, but the parts communicating between the two classes should remain real, always.

Title: Reusing Mocks/Stubs as Test Specification

Body:
We use mock to ensure that a unit test only runs against the code that should be tested. This prevents that a bug in a module A causes tests of a dependent module B to fail. However, now we also have to test the interaction explicitly. It is not enough that A and B are green on their own, A has to work as B expects it, and B has to have the right expectations.

Now, B's expectations are already formally defined: in the mocks and stubs. If I have a stub where A returns certain output for certain input, this means I expect it must be possible to have A in a state where it shows this behavior.

So instead of writing long integration tests, I just have to set-up an A and test it against the stubs and mocks that are already there. Or, to turn it around, I can use an actual instance of A to test the correctness of my mocks.

Does this work in practice? Are there best practices (e.g., where do these pseudo-integration tests belong to, should A's test suite already provide some likely-to-be-used mocks)? Is this even possible with the popular mocking frameworks?


问:
Developing Razor Web Pages - Visual Studio and/or WebMatrix?
When I started learning about Web Pages I followed several of the Microsoft tutorials, all of which utilized WebMatrix. I did this until I realized that WebMatrix offered no debugging. Wait? What?? No way. And I quickly moved my Web Pages development to Visual Studio. While there were some things that I thought were nicely done in WebMatrix, I have found nothing that I cannot do in in Visual Studio. Also, unless someone who knows better than me enlightens me, I am vehemently against developing the same project with two different IDEs; It just seems like an unnecessary risk to me.

Nevertheless, I would like to ask for your thoughts/insights about this. I am very curious to know if any of you use them in tandem and, if so, what aspects of each do you utilize the most? And, of course, does it cause problems?

答:
The idea behind WebMatrix is that it provides a lightweight experience for web developers.  Debugging is one of those features we think belongs in Visual Studio :)  As far as things you can do in WebMatrix that are different, most of them center around the App Gallery, PHP, and Node.js.  We have a bunch of stuff that makes it easier to work with PHP/MySQL apps, and the next release has a node.js experience.  All of the experiences around ASP.NET Web Pages are available in VS as well.

You can't really hurt anything by using both at the same time.  If you're doing ASP.NET and you're comfortable with Visual Studio, there's really no reason to keep using WebMatrix at the same time.  Let me know if you have any other questions :)


答:
No, you actually should. I would even go as far as to say - everyone should.

Parallel programming is actually a huge problem for the whole industry, it's a topic universities, tutorials, project managers and architects usually shy away from. This is bad, very bad, and should be fixed ASAP.

Parallel programming is not actually that hard, but it needs a different mindset that most people are not comfortable with. Decent multi-threaded apps can be written with just knowing and abiding by the rule that all function calls should be reentrant and shared objects protected. This solves most of the problems.

But getting used to that is problematic. Documentation is not always threading aware, or does not explicitly talk about threads. Bread and butter safety nets like unit-tests fail miserably in parallel programming. Thread joining and abnormal termination/cancellation is a huge issue. And deadlocks are one scary thing as soon as people start getting overly creative.

This extra complexity is enough that most people just forget about extra threads, heck, even I used to, and even now I sometimes "forget" about threads. This is also a perfect way for cloud providers to forget about multi-cores, and run more VMs on the base hardware.

But this is wrong, computing power growth is in threads now, we as programmers have to get used to the new world, and we should try to use the threads whenever possible.

Title: Cloud computing platforms often default to one CPU. Does this mean I shouldn't use Parallel Programming?

Body:
Almost every cloud instance I can find defaults one CPU.  Why is this only one CPU now, and should I expect this to increase in the future?

Does this design impact my code design so that I exclude technologies like Task Parallel Library?

This is on topic to Programmers.SE because it impacts the long-term scalability of muti-threaded code on cloud platforms.


问:
How can calculus and linear algebra be useful to a system programmer?
I found a website saying that calculus and linear algebra are necessary for System Programming.

System Programming, as far as I know, is about osdev, drivers, utilities and so on. I just can't figure out how calculus and linear algebra can be helpful on that. I know that calculus has several applications in science, but in this particular field of programming I just can't imagine how calculus can be so important.

The information was on this site:
http://www.wikihow.com/Become-a-Programmer

Edit: Some answers here are explaining about algorithm complexity and optimization. When I made this question I was trying to be more specific about the area of System's Programming. Algorithm complexity and optimization can be applied to any area of programming not just System's Programming. That may be why I wasn't able to came up with such thinking at the time of the question.

答:
System Programming, as far as I know, is about osdev, drivers, utilities and so on. I just can't figure out how calculus and linear algebra can be helpful on that.

With calculus it's pretty easy, as soon as one takes a closer look at the course contents. It is closely related to algorithm complexity, Big-O notation - stuff like that, pretty fundamental in programming.

Equations are what you get when estimating algorithm complexity. Three-level nested loops from 0 to N are N3, two-level nested loops are N2, one is N. Evaluation you get could look like (N3 + 2 * N2 + N) - that's an equation.

Now, if you want to better understand how quickly execution time will grow when N increases, this is closely related to derivatives / differentiation. Other parts of calculus you may find helpful are limits and asymptotic analysis - these will lead you to understanding Big-O notation, better scoring at programming interviews and possibly, better doing systems programming.

You are assigned to design file allocation table, what data structure are you going to use? Assuming that there are many small files which are rarely modified, what would be preferable? Assuming a relatively small amount of large files that are always appended at the end, are you going to use the same structure? How would you decide?

As for Linear Algebra, here programming applications shoot at you from the very first picture.

If you ever will have to deal with raster graphics (eg in video drivers), pictures like above will be coming at you in your worst nightmares.

How come that test #12345 shows missing pixel? did I do something wrong implementing Bresenham? could it be just a mistake in test design not properly accounting for rounding errors?


问:
How to get developers to do code reviews in a timely manner
The company I work for requires all code to be reviewed by other developers before it is committed.  The members of my team are often frustrated because the other developers are too busy coding to do a review, especially if it is very long.  How do you incentivize other developers to do timely code reviews?

(We use git-svn so we are able to continue coding while waiting for a review.  However, I still find it frustrating when I have to wait a long time before I can commit my code.)

答: At most companies I have worked for, you have 3 days to complete a review. It isn't acceptable to not do the reviews. It's part of your job. If you don't do decent reviews on time it affects your performance appraisal. And yes, reviews always seem to happen at the most inopportune times. Too bad, learn to include review time in your estimates.  Anyways, if management truly believes that reviews are important (ie. they mandate that all code is reviewed) then they would push a similar policy. Additionally, if people don't complete the review in the allotted time, that goes as their acceptance of the material.</p>


答:
SomeKittens' comment is right on the money: You need calculus and linear algebra because those courses change the way that you think and the way that you understand the world. Linear algebra is all about mapping from one domain to another; calculus covers the way functions behave. They're powerful tools themselves, but the techniques you learn when studying those fields also become part of your mental picture of the world.

You also need those courses because people will expect you to be able to think in those terms. I don't often see my colleagues taking the derivative of a polynomial on their white boards, but I do often see sketches of functions with the tangent drawn at some interesting point, or the area under the curve shaded. We don't care enough about the actual values to bother calculating them, but understanding about how the values change is essential, and it's part of everyday conversations.

Any undergraduate computer science degree will require calculus, linear algebra, statistics, logic, and other math courses not because programmers need to apply the techniques directly on a regular basis (although they might, depending on what they do), but because you need that knowledge to understand the material that comes later.

Title: How can calculus and linear algebra be useful to a system programmer?

Body:
I found a website saying that calculus and linear algebra are necessary for System Programming.

System Programming, as far as I know, is about osdev, drivers, utilities and so on. I just can't figure out how calculus and linear algebra can be helpful on that. I know that calculus has several applications in science, but in this particular field of programming I just can't imagine how calculus can be so important.

The information was on this site:
http://www.wikihow.com/Become-a-Programmer

Edit: Some answers here are explaining about algorithm complexity and optimization. When I made this question I was trying to be more specific about the area of System's Programming. Algorithm complexity and optimization can be applied to any area of programming not just System's Programming. That may be why I wasn't able to came up with such thinking at the time of the question.


问:
Developing an iOS app for a single device - licensing issue
I'm developing an iOS app for a museum as a freelancer. It's a very simple video player, to be installed on a single iPad that will be part of a permanent exhibition, basically acting as a kiosk. It turns out the iPad is the ideal device for that if you're looking for a small and affordable touchscreen.

The problem is: as far as I can tell, none of the Apple Developer Program options available will allow me to distribute an app like that. The relevant options are (from the link above):

iOS Developer Program ($99/year)
Select this program if you would like to distribute apps on the App Store as an individual, sole proprietor, company, organization, government entity or educational institution.

iOS Developer Enterprise Program ($299/year)
Select this program if you would like to develop proprietary apps for internal distribution within your company, organization, government entity or educational institution.

The regular program requires distribution through the App Store. The Enterprise version is for internal distribution within my own organization. Neither is the case here! It seems like I'm doomed to violate Apple's terms of service (and I can think of at least two ways of doing that: jailbreaking, or changing the iPad's date so it won't know the provisioning profile expired).

Is that really so, or did I get the descriptions wrong? Has anyone here been in a similar situation?

答:
I acknowledge this is not a direct answer to your question (And I have no preference of Apple over Android or Windows - they all have their place).

Are you locked into the apple ecosystem? Why? - it does not appear to provide commercial framework needed for the job at hand. If it does not then another tool for the job may be required.

Android Development allows the distribution model you require, and an Droid tablet appear that it would do the job required equally well.  Windows 8 Tablets will also be able to provide the commercial framework you require.


问:
Do large test methods indicate a code smell?
I have a particular method called TranslateValues() (Cyclomatic-Complexity of 5) which I would like to test.

The test requires a substantial number of mock objects which take up most of the method; The method being tested is fairly straightforward with this exceptional requirement. I am suspicious of this. For me, I might do something like this to alleviate the issue:

```<code>namespace TestArea
{
    [TestClass]
    public class PrimaryTests
    {
        //commonly used classes should go up here
        private CoreServiceClient client;
        public CoreServiceClient Client
        {
            get { return client; }
            set { client = value; }
        }

        [TestMethod]
        public void TestMethodForXYZ()
        {
            try
            {
              //use the Client, do some stuff, and assert
            }
            catch
            {
             //catch any problems, report them, and assert.fail
            }
        }
   }
}
</code>```

But this will only take you so far in reducing the size and clutter of test methods, and so it begs the question: Are big test methods generally indicative of code smell? How do you gauge when your methods are becoming too big?

答:
No, not always. Big test methods are often results of testing/mocking frameworks and their workings (or, precisely - how you're supposed to use them).

For example, method might be perfectly fine and well-designed, but let's imagine it uses 2 or 3 dependencies - in order to test it, you'll probably have to stub/mock those dependencies. This adds extra lines of code to test method, which don't feel like attributing to tested method at all.

Having said that, too much dependencies might be good indicator (which, also will result in longer test method code due to extra setup work) and that's where I'd stay cautious, not the length itself.

Very trivial example of fairly common test, where test method will be "long", as compared to what it's actually testing (which probably is 1 line of code):

```<code>[Test]
public void GenerateReport_ThrowsInvalidOperationException_WhenTaskIsNotReady()
{
    var providerMock = new Mock<ITaskProvider>();
    providerMock.Setup(m => m.IsTaskReady).Returns(false);
    var sut = new ReportGenerator(providerMock);

    Assert.That(sut, Throws.InstanceOf<InvalidOperationException>());
}
</code>```

Now, add bit more complex .Setup call, bit more complex assertion - this results in even more extended size of test method.

OwnerDisplayName: Ray

Body:
No, not always. Big test methods are often results of testing/mocking frameworks and their workings (or, precisely - how you're supposed to use them).

For example, method might be perfectly fine and well-designed, but let's imagine it uses 2 or 3 dependencies - in order to test it, you'll probably have to stub/mock those dependencies. This adds extra lines of code to test method, which don't feel like attributing to tested method at all.

Having said that, too much dependencies might be good indicator (which, also will result in longer test method code due to extra setup work) and that's where I'd stay cautious, not the length itself.

Very trivial example of fairly common test, where test method will be "long", as compared to what it's actually testing (which probably is 1 line of code):

[Test]
public void GenerateReport_ThrowsInvalidOperationException_WhenTaskIsNotReady()
{
    var providerMock = new Mock<ITaskProvider>();
    providerMock.Setup(m => m.IsTaskReady).Returns(false);
    var sut = new ReportGenerator(providerMock);

    Assert.That(sut, Throws.InstanceOf<InvalidOperationException>());
}

Now, add bit more complex .Setup call, bit more complex assertion - this results in even more extended size of test method.


答:
I say yes.  You are testing too much.

I'm guilty of it myself but ideally you test one thing at a time (to be read as "one assert per test").  That's the Utopian view and so long as you're closer to that than the "one test for everything with a ton of asserts" side you're ok.

I think it really comes down to properly using the tool.  NUnit, for example, has TestCaseAttributes so that you can have one test that runs through several cases, which you've basically described.  Running them all through one test is less useful because it should stop at the first failure so you can only tell if you broke multiple cases by fixing the individual failures as you see them.

As for gauging when they are too big, it's pretty much as soon as I want to have a specific Assert run (and no others) but I can't because the test must run several other Asserts to remain valid.

In the end it really means following Single Responsibility when writing tests as well as code.

Title: Do large test methods indicate a code smell?

Body:
I have a particular method called TranslateValues() (Cyclomatic-Complexity of 5) which I would like to test.

The test requires a substantial number of mock objects which take up most of the method; The method being tested is fairly straightforward with this exceptional requirement. I am suspicious of this. For me, I might do something like this to alleviate the issue:

```<code>namespace TestArea
{
    [TestClass]
    public class PrimaryTests
    {
        //commonly used classes should go up here
        private CoreServiceClient client;
        public CoreServiceClient Client
        {
            get { return client; }
            set { client = value; }
        }

        [TestMethod]
        public void TestMethodForXYZ()
        {
            try
            {
              //use the Client, do some stuff, and assert
            }
            catch
            {
             //catch any problems, report them, and assert.fail
            }
        }
   }
}
</code>```

But this will only take you so far in reducing the size and clutter of test methods, and so it begs the question: Are big test methods generally indicative of code smell? How do you gauge when your methods are becoming too big?

OwnerDisplayName: Austin Salonen


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答:
In France, many people tend to code using French objects/methods/variables names if they work with non English speaking colleagues.
However, it is really depends on your environment.

The thumb rule is 'the more skilled people you are working / the projects you are working on are, the more likely it is that it is going to be in English'/

It seems to be the same in Germany.

OwnerDisplayName: Matteo

ContentLicense: CC BY-SA 2.5


问:
Advice for solo programmer whose team will expand in the near future
For 4 years now, I've been the solo developer for a small company. We have a handful of well establish products in a niche industry. We will be hiring 1-2 developers soon, and that will likely change the way things operate around here.

While I won't have a "real" title, I will be "in charge" of this team. What I want to do is establish a very organized and productive programming department for my company. I got this solo job right out of college, so while I've become proficient as a programmer in this industry, I lack a lot of team programming experience. I feel that starting out on the right foot will be key.

Right now it's just me, a few computers, and an SVN server. I'm looking for any general guidance on building a team from the ground up.

答:
It may be obvious, but make sure you think you'll actually like working with the new hires. Try to arrange for a couple of beers when they both start to try and get the team to feel like one.

You'll also need to make them aware of any coding standards you follow and any common techinques you use, common as in repeated in your code base.

Eventually you should all be able to feed back into the process and improve... assuming you follow other advise and hire someone with the skills to complement yours.


答:
I don't believe that a big test method is code smell by itself.

However, there are signs, for example when you

need to mock too much dependencies (too much is relative too)

need to setup too many things

need to know too many things about the actual implementation detail (when you do TDD it won't be a problem)

can't separate the testing of a method to well definied test cases (different test methods)

From my experience, one of the biggest sign that a method doing to much is when you can't really write a specific test case, just something like TestOfMyMethod(). That is probably not a test case, just a big mash of code covering the exact implementation of the actual method, which will break the next time you change anything.

OwnerDisplayName: pinusnegra


答:
Why your test could be long:

you are testing more than one thing

sut dependencies require lot of mocking (probably your case)

your sut requires lot of dependencies

If you are testing more than one thing

Write separate tests, for testing each thing. Each test will require less arranging, and less assertions. When some test will be broken, you will know what exactly is not working as expected.

If your mocks require lot of setup

First of all, you should verify why your sut asking it's dependency too much. Maybe you make decisions based on other object's state, thus violating Tell, Don't Ask principle. Consider moving that decisions logic to dependency.

```<code>// for this code you should setup mocks of person and address
if (person.Address != null) {
  Address address = person.Address;
  address.City = city;
}
</code>```

vs

```<code>person.RelocateTo(city);
</code>```

If you completely sure, that all logic in it's place, but your mock still requires some big setup, then consider moving mock creation to separate method. This also will allow to reuse that method in several tests.

```<code>Mock<Foo> fooMock = new Mock<Foo>();
fooMock.Setup(foo => foo.X).Returns("x");
fooMock.Setup(foo => foo.Y).Returns("y");
fooMock.Setup(foo => foo.Z).Returns("z");
Bar bar = new Bar(fooMock.Object);
</code>```

vs

```<code>Foo foo = CreateFoo("x", "y", "z");
Bar bar = new Bar(foo);
</code>```

If your sut requires lot of dependencies

If some of your dependencies always used together, than consider to introduce one object, which will hold them. Also check do you really need whole object to be passed. Maybe you just need one field from that object.

```<code>public void Foo(TimeProvider timeProvider)
{
   DateTime time = timeProvider.GetCurrentTime();
   ...
}
</code>```

vs

```<code>public void Foo(DateTime currentTime)
{
   ...
}
</code>```

Body:
Why your test could be long:

you are testing more than one thing

sut dependencies require lot of mocking (probably your case)

your sut requires lot of dependencies

If you are testing more than one thing

Write separate tests, for testing each thing. Each test will require less arranging, and less assertions. When some test will be broken, you will know what exactly is not working as expected.

If your mocks require lot of setup

First of all, you should verify why your sut asking it's dependency too much. Maybe you make decisions based on other object's state, thus violating Tell, Don't Ask principle. Consider moving that decisions logic to dependency.

// for this code you should setup mocks of person and address
if (person.Address != null) {
  Address address = person.Address;
  address.City = city;
}

vs

person.RelocateTo(city);

If you completely sure, that all logic in it's place, but your mock still requires some big setup, then consider moving mock creation to separate method. This also will allow to reuse that method in several tests.

Mock<Foo> fooMock = new Mock<Foo>();
fooMock.Setup(foo => foo.X).Returns("x");
fooMock.Setup(foo => foo.Y).Returns("y");
fooMock.Setup(foo => foo.Z).Returns("z");
Bar bar = new Bar(fooMock.Object);

vs

Foo foo = CreateFoo("x", "y", "z");
Bar bar = new Bar(foo);

If your sut requires lot of dependencies

If some of your dependencies always used together, than consider to introduce one object, which will hold them. Also check do you really need whole object to be passed. Maybe you just need one field from that object.

public void Foo(TimeProvider timeProvider)
{
   DateTime time = timeProvider.GetCurrentTime();
   ...
}

vs

public void Foo(DateTime currentTime)
{
   ...
}

OwnerDisplayName: lazyberezovsky


问:
How often should I be compiling?
For the longest time I've just done small app development.  Building and debugging took a matter of seconds (or should I say - second?).  I got fairly used to just debugging to test literally everything (and it's nice to see my stuff working - like a programming high almost).  The problem is that as of late I've been working on a much larger project.  The single solution contains 4 (and probably more soon) projects each very large.  As it expands, compile times naturally increase making debugging a real pain.  I'm stuck in my "compile every update" mode and it has wasted quite a bit of my time.  Every visible update I want to see it.

So...

How can I get out of this irrational compile/debug habit and how often should I actually be compiling and debugging my application?

EDIT:

I'm utilizing Visual Studio.  My compile times I realize are minuscule to what most of you are used to I realize, but it is still wasting my time :)

答:
First, you should use a very good ide with tools to help you to "pre-verify" your code logic. Something like eclipse or delphi or nusphere, depending of your language.

Second, you have to split your work on job codes. After a job is done, you compile only the files that were updated and them link to the rest.

Title: How often should I be compiling?


答:
Compile well and often. I typically do it after each block of new functionality has been completed. It's not unusual for this to happen tens of times per day.

However, your IDE should really only recompile those files that need it. You don't say what language you're using but if you update header files any source files that include it will need to be recompiled. A complete recompile each time could be a symptom of poorly organised code.

Title: How often should I be compiling?

Body:
For the longest time I've just done small app development.  Building and debugging took a matter of seconds (or should I say - second?).  I got fairly used to just debugging to test literally everything (and it's nice to see my stuff working - like a programming high almost).  The problem is that as of late I've been working on a much larger project.  The single solution contains 4 (and probably more soon) projects each very large.  As it expands, compile times naturally increase making debugging a real pain.  I'm stuck in my "compile every update" mode and it has wasted quite a bit of my time.  Every visible update I want to see it.

So...

How can I get out of this irrational compile/debug habit and how often should I actually be compiling and debugging my application?

EDIT:

I'm utilizing Visual Studio.  My compile times I realize are minuscule to what most of you are used to I realize, but it is still wasting my time :)


答:
If you're using a strongly-typed compiled language, you really should be compiling very often, since it provides a first-pass sanity check that you didn't write any invalid code.  The longer you take between creating the error and detecting it, the less fresh it will be in your mind.  If your project takes a long time to build, run an incremental compile instead.  (If you can't do that, use an IDE that supports it.)

And if your incremental compiles take too long, what are you coding in?  On Delphi I can full-build our (enormous, ~4M lines) client app in about 2 minutes on a hard drive and a VM, or ~15 seconds on an SSD and no VM.  Incremental compiles are even faster.  If productivity is important, it could be a matter of "the right tool for the right job."  (Which is not to say that you should abandon your entire existing codebase and rewrite the whole thing in Delphi just because it compiles faster.  That would be silly.  But you ought to keep in mind that not everything builds equally slowly.)

As for running to test and debug, you should do that fairly often too.  Not necessarily as often as you test-build, but every time you complete a feature or sub-feature you should give it a quick test or two right away, even if it's going to be later tested in other ways or by other people.  Remember, the longer you go between writing the code and detecting the error, the harder it'll be for you to fix.

Title: How often should I be compiling?


答: Unit testing is the answer. Good framework will allow you to execute only the tests that you're interested in at the moment. And unit tests are small by definition so will compile and run fast.</p>

Title: How often should I be compiling?


答:
This certainly hampers concurrency prospects, but there are cases when a single-threaded program running on a single core could still benefit from multiple threads : every time the thread waits for something (e.g. blocking IO).

Let's say this program executes a set of similar tasks where each involves C compute time and W wait time, then to keep the single core fully utilized you need W/C threads.

Here's the general formula, given those definitions:

Ncpu = number of CPUs

Ucpu = target CPU utilization; 0 <= Ucpu <= 1

W/C = ratio of wait time to compute time

The optimal number of threads to keep CPUs at the dezired utilisation is :

Nthreads = Ncpu * Ucpu * (W/C)

This means that multiple threads do not improve performance (only) when there are more runnable threads than available CPUs.


答:
You can use the "iOS Developer Program" (individual) to deploy your app to any single device; you're not required to submit all apps created to the App Store, you're only given the option to do so if you like.

Either way, in order to remain functioning on any given device, you'll need to continue to pay the annual fee for membership in the program.

Title: Developing an iOS app for a single device - licensing issue

Body:
I'm developing an iOS app for a museum as a freelancer. It's a very simple video player, to be installed on a single iPad that will be part of a permanent exhibition, basically acting as a kiosk. It turns out the iPad is the ideal device for that if you're looking for a small and affordable touchscreen.

The problem is: as far as I can tell, none of the Apple Developer Program options available will allow me to distribute an app like that. The relevant options are (from the link above):

iOS Developer Program ($99/year)
Select this program if you would like to distribute apps on the App Store as an individual, sole proprietor, company, organization, government entity or educational institution.

iOS Developer Enterprise Program ($299/year)
Select this program if you would like to develop proprietary apps for internal distribution within your company, organization, government entity or educational institution.

The regular program requires distribution through the App Store. The Enterprise version is for internal distribution within my own organization. Neither is the case here! It seems like I'm doomed to violate Apple's terms of service (and I can think of at least two ways of doing that: jailbreaking, or changing the iPad's date so it won't know the provisioning profile expired).

Is that really so, or did I get the descriptions wrong? Has anyone here been in a similar situation?


问:
When using Hibernate can we forget about Database Design?
We started (just me and my friend) working on a website. As a part design phase we have finished the drawing a Site Map, decided on the content in each of the web page and the navigation.

As we want to use the Spring MVC and Hibernate we want to start on Classes design (domain classes) first so that the database part is taken care by Hibernate (Except for some tables for static data). Does our approach correct? Is my understanding correct that when we use Hibernate the 80% of the database design can be forgotten?

答:
Your understanding is correct. Your domain model will be the key driver for database schema.

But managing the schema is best done outside of hibernate, though hibernate can create tables for you based on configuration. This way, though you have to manage database schema separately, you will have full control to manage the primary keys, constraint, foreign keys etc. Also, you need not worry about data being wiped every time you re-deploy the application.


答:
Are you working on Dotnet? If yes then following can be of use to you.

In various Projects added, there will be some/many references, make sure you make all the references to have the property Copy Local as FALSE

If you are developing ASP.NET stuff, make all the Aspx pages' code behind files as Code files to avoid Build and even Saving them can do the job + the application need not restarted over and over again. (But make sure, before sending deployment, i.e. before final you make them CodeBehind again, as Precompiled code works the best at any time)

Go to a specific project and Build that only (right-click->Build Project) rather than building or Rebuilding the complete solution. This will save a lot of time.

Hope this Helps!

Title: How often should I be compiling?


答:
No, your database is still important

NHibernate is an object-relational mapping (ORM) solution for the projects: it provides a framework for mapping an object-oriented domain model to a traditional relational database. Thus it is important to keep your database in a good shape.

Otherwise, you may face with performance issues once you project starts to grow.

In addition, it is always pays back if you keep your database design as normalized and as good as possible.

References to support my point:

NHibernate – Lessons Learned

Identifying NHibernate-Related Bottlenecks through Performance Monitoring

NHibernate Best Practices with ASP.NET

Title: When using Hibernate can we forget about Database Design?

Body:
We started (just me and my friend) working on a website. As a part design phase we have finished the drawing a Site Map, decided on the content in each of the web page and the navigation.

As we want to use the Spring MVC and Hibernate we want to start on Classes design (domain classes) first so that the database part is taken care by Hibernate (Except for some tables for static data). Does our approach correct? Is my understanding correct that when we use Hibernate the 80% of the database design can be forgotten?


答:
How can I get out of this irrational compile/debug habit

Practice. What has helped me is by solidifying my program design skills. Needing to 'make sure it works' is a sign that you're lacking confidence in what you've done. You get confidence via practice of course, but also by using things you know will work. Taking known patterns (not necessarily design patterns, but they count) and adapting them to the situation at hand. Since you've done them many times before, you know them well enough to do them right and be confident that you've done them right.

how often should I actually be compiling

Personally, I don't recommend compiling until you're ready to run your tests. There's too many coding environments that have sucky compilation either due to the language you're using (I'm looking at you C++), the platform you're working with, or the size/complexity of the codebase. It's good to be able to work without that step and focus on the partial compilation/error checking that most modern IDEs provide while you're working.

But it's only a recommendation. Do what is most productive for you.

and debugging my application

When your tests fail, or a bug has been reported that has eluded your tests (and you can't spot the bug without entering the debugger). This should be very uncommon when developing new code, and is a bad sign if needed when adding on to existing code.

Again, I tend to avoid the debugger these days for similar reasons that I avoid the compiler. Plus, once much of the code is known patterns spotting bugs becomes speedier since you're familiar where things can go wrong.

This too is merely a recommendation. It's nice to be able to spot bugs by eyeballing code, but the end goal is to produce quality software. If the debugger gets you that goal faster and more reliably, go right ahead and debug frequently.

Title: How often should I be compiling?


问:
Is my mediator layer a sensible way to manage this scenario using the Single Responsibility Principle?
I'm not sure how to start to explain my question, but here goes.

We have just finished an MVC application that hits 2 WCF services. But there has been a bit of a disagreement between those who worked on the project and some who haven't over the design used. What we have is two WCF services, one on each site (site specific data) and another at head office (data shared/common between all sites). Normally we would have two apps, one for site and another for head office. In this case I decided from a UX point of view that it would be better to have it look like one app from the users point of view so they would not need know two urls. Basically, the user does not know if they are hitting site or head office.

Now comes the design decision that has caused the disagreements.
The MVC App has controllers that need to hit either a site wcf service or a head office WCF service. So to prevent the need of the controllers needing to be aware of the two WCF communications layers and converting the WCF results into a model the controllers could use, I created a layer in between the controllers and WCF Proxies. Which accepts a request from a controller, then calls the appropriate site or central WCF proxy call, then if needed, convert the WCF result into a model that the controller can use.

This layer, I called a Mediator, but after much discussion, I am of the opinion that it is not the correct description for it. Anyway, the reason for this layer is when tring to keep to the SOILD object oriented principles, in particular the Single Responsibility Principal. The controllers responsibility is to handle client requests and return a view/result. It should not need to know or maintain a WCF proxy and convert its result. (It could go directly to a database instead of a WCF call but the controller shouldn't be responsible or even aware of that because it is responsible for the view) The same goes for the WCF proxy, it should not know what is consuming its result and that the WCF data contract should be converted into a model specific for each controller. The mediator layer in between is what decides which WCF service and method to call and then either via a extension method or a specific handler converts the result to a model the controller can use. (sometimes it may take several wcf calls to create the model).

```<code>Controller1 -> Mediator -> HeadOfficeWCFProxy
Controller2 -> Mediator -> SiteWCFProxy
</code>```

So the controller asks for data (not knowing where it comes from)

The mediator converts and passes the request to the appropriate WCF Proxy(s)

The WCF Proxy(s) make the calls across the wire and return the results.

The mediator then converts the result(s) into a model (if needed) via an extension method and returns it to the controller.

The controller renders the view using said model.

Now what I described here was just on the MVC side. I have a similar setup on the WCF service side but the mediators benefit is clearer.

On the head office WCF service

```<code>WCFListener -> Mediator -> DataLayer (LinqToSQL)
                        -> SiteSyncHandler (sends change to all sites asyncronously)
                        -> ThirdPartyContentManagementHandler (via web service)
</code>```

Now the devs that have worked on the project, like the separation of concerns alot as it is very clear where everything belongs and keeps code to a minimum in each layer. But the down side in the MVC app is for a lot of the calls the mediator just makes a single WCF call and doesn't even need to convert the result (most of the time the data contract is fine for use as a model) resulting in a fair amount of one liner method boiler plate code. The mediator doesn't really add much in that scenario except to keep things consistent across controllers. Some devs that haven't worked on the project, insist that there is no need at all for the Mediator layer and that it could be all handled by the controllers themselves. Which means maintaining the appropriate WCF Proxy in each controller. This in my mind violates the Single Responsibility principle. To which they argue that SOLID is more like a set of guidelines, and not to be blindly followed. Which while I kinda agree with that statement its also not to be blindly ignored.

I have conceded that the term mediator is not really appropriate (perhaps director or relay), but I still think the basic design is valid, and would use it again. The same can be said for those who have worked on the project. I would like to know what other people think. Is there a better solution or have I "over complicated it". (I still don't agree that is is complicated, its a very simple concept and easy to maintain)

答:
What you are suggesting is a service that seems desirable to abstract away from the controllers. It should also improve the ability to test the controllers by removing the concrete calls to the service (the D part of SOLID).

Maybe instead of "Mediator" call it a "Service Bus" as it is more likely to draw recognition and is catchier.


答:
In short, there are 3 things that I did to enhance the productivity when I'm in your situation:

Good logging instead of debugging

Unit test

Daily build

I strongly recommend logging against debugging using IDE. By a good log file, you will have a much quicker access to "what has happened" and the flow of the error, without re-compiling. Moreover, logging will also help you in troubleshooting the application when it is used by the clients, while debugging doesn't.

Many people here seems to recommend Unit test, but be aware that it will take time to learn and apply. Bad unit tests won't help you. You may want to try start small, and adding them for the most important and error-prone feature of your application first.

A daily build and some integration tests for important business work flow is another thing that saves my life so many times. Setting up an automatically build-and-deploy isn't hard, but it will help you and your co-workers to make sure that no one breaks anything by accident before the acceptance test.

I also recommend you taking a look at the Joel Test. It's very helpful for those who seeks to improve :)

UPDATE: More about logging. Just put a println statement here and there in your code may work, but you will want a full-fledge logging library if you are serious about troubleshooting in future. Every programming languages/frameworks now has a solid framework for logging, so you can count on that.

Title: How often should I be compiling?


答:
I generally have things setup to compile every time I save a file. Of course for that to work you need a build tool that will only recompile the files that need to be compiled. I generally use GNU Make for this. Actually I have my editor setup to compile the file and spot syntax errors with Emacs flymake mode so it probably does a compile every few seconds.

The trick here is that you are not rebuilding your entire project each time you compile you are only building the one component that has changed.

I will build everything from scratch once every few hours, generally if I am switching to a new branch or the like.

Title: How often should I be compiling?


问:
Lock-free IPC in Linux for multi-core processors
I'm trying to find a way to write an application with lock-free IPC on Linux, in C, with multi-core processors.

Let's assume I have process 1 and process 2 that write to a FIFO or shared memory. Then process 3 and process 4 will read from that shared memory or FIFO.

Is this possible with a lock-free algorithm?

Your guidance is highly appreciated.

答: Yes it's possible. We use one of the algorithms of the lock-free queue in our project. But these algorithms are really not obvious. If you want to understand them in depth you should be ready to spent couple months for it.</p>


答:
I hope I understood the situation, but for sure, I try to summarize it.

You have a separated "master" (shared tools, common data and functions), and (multiple?) "satellite" (site specific) services. Your application connects to one satellite (depending on the login, or the client logs into the site?) and also uses the services of the master. It is a natural decision that the users should not be aware of the fact that they use both within the same application - the question is how to handle this scenario programmatically. Of course, I don't know enough about the actual situation to answer this question, so I just throw in my view that you may find useful.

Your single application "hosts" several components: units with their data, business logic and user interface. Together they build up the whole app: the menu or a dashboard activate them, and perhaps multiple components can appear on a single screen, perhaps from different WCF services. Some of them may "be around" in the app for other components to use them.

The question here is: how you view the role of the application? It may either be

heavyweight, "I MANAGE" type: it hides the heterogeneous nature of the system, showing a single entry point to any service and dispatch the requests to the appropriate servers (therefore I would call this Dispatcher, but I don't know if this is a reserved word in the world of patterns)

lightweight, "I SERVE" type: knowing that there are different servers and their possibly  independent services (growing, changing), it does not try to mimic a single "virtual cover" layer above all, but contain multiple server connections, from which the components select their own.

Without knowing too much about your task (and absolutely zero knowledge on WCF), the second approach seems more comfortable. I think you are right in that components should not own their connection, because many of them share the same (head or site) - but they could refer to it. Your Mediator (that now appears to be all-in-all) should only resolve these references for the components, and also do housekeeping (state, communication, error management, etc.). With this approach, you would

keep the central role of the Mediator (a location for logging, throttling, caching, etc., no "quick and dirty" direct solutions in components), but

forget about managing the global service layer all the time when new sites appear, or any service is modified (although if you need app level management for the connectors, you should inject that into them - but this time your implementation adapts to their interface).

My 2 cents.

If this sounds good, the transition is not too complex. You already have the multiple connection management layer, you only have to open it and let the components access it directly. The dark side is that you have to move the central management part down, from the global cover layer into local cover layers above each connection.

I don't say this because I think you should change anything, I know far too little to have such opinion [EDIT: I don't even know whether this approach is viable in WCF, I have spent only 3 weeks with C# in my life, and I have found it quite quick and handy], but I think you should consider both options objectively by the required implementation and maintenance cost, both in short and long term.

Title: Is my mediator layer a sensible way to manage this scenario using the Single Responsibility Principle?

Body:
I'm not sure how to start to explain my question, but here goes.

We have just finished an MVC application that hits 2 WCF services. But there has been a bit of a disagreement between those who worked on the project and some who haven't over the design used. What we have is two WCF services, one on each site (site specific data) and another at head office (data shared/common between all sites). Normally we would have two apps, one for site and another for head office. In this case I decided from a UX point of view that it would be better to have it look like one app from the users point of view so they would not need know two urls. Basically, the user does not know if they are hitting site or head office.

Now comes the design decision that has caused the disagreements.
The MVC App has controllers that need to hit either a site wcf service or a head office WCF service. So to prevent the need of the controllers needing to be aware of the two WCF communications layers and converting the WCF results into a model the controllers could use, I created a layer in between the controllers and WCF Proxies. Which accepts a request from a controller, then calls the appropriate site or central WCF proxy call, then if needed, convert the WCF result into a model that the controller can use.

This layer, I called a Mediator, but after much discussion, I am of the opinion that it is not the correct description for it. Anyway, the reason for this layer is when tring to keep to the SOILD object oriented principles, in particular the Single Responsibility Principal. The controllers responsibility is to handle client requests and return a view/result. It should not need to know or maintain a WCF proxy and convert its result. (It could go directly to a database instead of a WCF call but the controller shouldn't be responsible or even aware of that because it is responsible for the view) The same goes for the WCF proxy, it should not know what is consuming its result and that the WCF data contract should be converted into a model specific for each controller. The mediator layer in between is what decides which WCF service and method to call and then either via a extension method or a specific handler converts the result to a model the controller can use. (sometimes it may take several wcf calls to create the model).

```<code>Controller1 -> Mediator -> HeadOfficeWCFProxy
Controller2 -> Mediator -> SiteWCFProxy
</code>```

So the controller asks for data (not knowing where it comes from)

The mediator converts and passes the request to the appropriate WCF Proxy(s)

The WCF Proxy(s) make the calls across the wire and return the results.

The mediator then converts the result(s) into a model (if needed) via an extension method and returns it to the controller.

The controller renders the view using said model.

Now what I described here was just on the MVC side. I have a similar setup on the WCF service side but the mediators benefit is clearer.

On the head office WCF service

```<code>WCFListener -> Mediator -> DataLayer (LinqToSQL)
                        -> SiteSyncHandler (sends change to all sites asyncronously)
                        -> ThirdPartyContentManagementHandler (via web service)
</code>```

Now the devs that have worked on the project, like the separation of concerns alot as it is very clear where everything belongs and keeps code to a minimum in each layer. But the down side in the MVC app is for a lot of the calls the mediator just makes a single WCF call and doesn't even need to convert the result (most of the time the data contract is fine for use as a model) resulting in a fair amount of one liner method boiler plate code. The mediator doesn't really add much in that scenario except to keep things consistent across controllers. Some devs that haven't worked on the project, insist that there is no need at all for the Mediator layer and that it could be all handled by the controllers themselves. Which means maintaining the appropriate WCF Proxy in each controller. This in my mind violates the Single Responsibility principle. To which they argue that SOLID is more like a set of guidelines, and not to be blindly followed. Which while I kinda agree with that statement its also not to be blindly ignored.

I have conceded that the term mediator is not really appropriate (perhaps director or relay), but I still think the basic design is valid, and would use it again. The same can be said for those who have worked on the project. I would like to know what other people think. Is there a better solution or have I "over complicated it". (I still don't agree that is is complicated, its a very simple concept and easy to maintain)


问:
Considerations for developing a large scale system that needs to be both traditional web accessible and mobile accessible
I am trying to begin planning of a system that would be both client management, and document management, with tools built in to do analysis on all of the transactions, etc.

I'm wondering what are the considerations I need to be mindful of at the beginning stages so that when I need to scale up I haven't shot myself in the foot in the beginning.

I also need to make sure that it is mobile accessible and not just traditional web accessible.

I've never done a large scale system like this and I have ample time to plan so any suggestions are much appreciated.

Edit

I also need to make sure that the handling of data would be secure because it would be sensitive client data.

答:
There are several frameworks that may provide this flexibility, and one of them is ASP.NET MVC latest version. This framework creates a mobile ready MVC 3.0 project using the Razor's view engine and jQuery mobile. Both mobile and desktop versions can be tested using mobile emulators or browsers.

More information for reference:

Mobile Ready HTML5 MVC.NET

ASP.NET MVC 4 - Default template changes and Adaptive Rendering using Viewport and CSS Media Queries

Mobile Support in ASP.NET


答:
Sounds well thought out. One thing web developers often don't get is, that servers (or the WCF service in your case) and clients (web application, mobile application or whatever) are two separate things, and should NOT be mixed up. You find plenty of so called MVC implementations that think it's a good idea to place controller and model at the server, and have the view on the client. They feel all not really satisfying.

When it comes to web development, somehow good developers stop to think. Somehow they don't spend any thoughts at a clean and reliable architecture. So, you did it well. Full stop. Leave the context, name it module "A" and module "B", whatever, and suddenly it doesn't look arguable anymore.

A clean way would be to have a full MVC stack at client side. Of course your Controller doesn't want to know how exactly your data is stored. Thats the model job, after all. If the model works with a database or a web-service doesn't matter, right? Your idea with the mediator in place is a good one, for every reason you mentioned.


问:
easiest way for push notifications
I wanted to implement real time push notification to one of the apps written in RoR. I don't have any experience with nodejs, nowjs, express or socketio.

What would be the easiest way to implement the realtime push notification system?

答: Take a look at Bridge made by the creators of nowjs. It helps you push messages down to your clients very easily, whether you're building a Rails app or a Node.js app or even python apps. It supports a lot of languages and platforms. It's a very robust system that can handle billions of messages a day.</p>

Title: easiest way for push notifications


答:
You can leave it for the moment, but don't, really DON'T forget about it. It is important to keep your database in a good shape, as mentioned by others. Hibernate will create you schema, it might be okay. But have a look at it before you finish work, chances are you will find serious flaws.

Personally I'm with @Emmad Kareem. Database design has to be done up front. You can forget about 80%, your right. But make sure you don't forget about 100%.


答:
You can start coding without design (either database design or application design) if you are experienced and if your application is small.
On the other hand there aren't applications in which too much time was spent in ; so by doing design you can be pretty sure that your applications is going to be better.</p>


答:
You need to think of at least three distinct systems in the beginning.

Backend/API

Web interface

Mobile Application

And, later on think of an additional system

A. You need to build the Backend/Server/API such that it is only concerned with data. Read about REST based APIs to start with. This API should most preferably receive and return data in JSON. The benefit of building the system like this is that view(s) are very clearly separated from data.

B. You can work on 2 & 3 in parallel. You can use javascript mvc framework for Web. Also, read a bit about the MVVM design pattern.

Title: Considerations for developing a large scale system that needs to be both traditional web accessible and mobile accessible

Body:
I am trying to begin planning of a system that would be both client management, and document management, with tools built in to do analysis on all of the transactions, etc.

I'm wondering what are the considerations I need to be mindful of at the beginning stages so that when I need to scale up I haven't shot myself in the foot in the beginning.

I also need to make sure that it is mobile accessible and not just traditional web accessible.

I've never done a large scale system like this and I have ample time to plan so any suggestions are much appreciated.

Edit

I also need to make sure that the handling of data would be secure because it would be sensitive client data.


问:
Should I use switch statements or long if...else chains?
Often when I hear about the switch statement, its put off as a way to replace long if...else chains. But it seems that when I use the switch statement I'm writing more code that I would be just writing if...else. You also have other issues like keeping all variables for all calls in the same scope.

Here's some code that represents the flow I normally write (thanks to diam)

```<code>String comment;   // The generated insult.
int which = (int)(Math.random() * 3);  //  Result is 0, 1, or 2.

if (which == 0) {
    comment = "You look so much better than usual.";
} else if (which == 1) {
    comment = "Your work is up to its usual standards.";
} else if (which == 2) {
    comment = "You're quite competent for so little experience.";
} else {
    comment = "Oops -- something is wrong with this code.";
}
</code>```

Then they want me to replace that with this:

```<code>String comment;   // The generated insult.
int which = (int)(Math.random() * 3);  //  Result is 0, 1, or 2.

switch (which) {
    case 0:
             comment = "You look so much better than usual.";
    break;
    case 1:
             comment = "Your work is up to its usual standards.";
    break;
    case 2:
             comment = "You're quite competent for so little experience.";
    break;
    default:
             comment = "Oops -- something is wrong with this code.";
}
</code>```

Seems like a lot more code in a much more awkward syntax. But is there really an advantage to using the switch statement?

答:
The problem with the if...else if... chain is that when I come along to read it, I have to look at every single if condition to understand what the program is doing. For example, you might have something like this:

```<code>if (a == 1) {
    // stuff
} else if (a == 2) {
    // stuff
} else if (a == 3) {
    // stuff
} else if (b == 1) {
    // stuff
} else if (b == 2) {
    // stuff
}
</code>```

(obviously, for a small number of statements like this, it's not so bad)

I'd have no way of knowing that you changed condition variable half-way through without reading every single statement. However, because a switch limits you to a single condition variable only, I can see at a glance what's happening.

At the end of the day, though, I'd prefer neither switch or a chain of if...else if. Often a better solution is some kind of jump table or dictionary for cases like in the original question, or polymorphism (if your language supports that). It's not always possible, of course, but I'd look for a solution that avoids switch as a first step...

Body:
The problem with the if...else if... chain is that when I come along to read it, I have to look at every single if condition to understand what the program is doing. For example, you might have something like this:

if (a == 1) {
    // stuff
} else if (a == 2) {
    // stuff
} else if (a == 3) {
    // stuff
} else if (b == 1) {
    // stuff
} else if (b == 2) {
    // stuff
}

(obviously, for a small number of statements like this, it's not so bad)

I'd have no way of knowing that you changed condition variable half-way through without reading every single statement. However, because a switch limits you to a single condition variable only, I can see at a glance what's happening.

At the end of the day, though, I'd prefer neither switch or a chain of if...else if. Often a better solution is some kind of jump table or dictionary for cases like in the original question, or polymorphism (if your language supports that). It's not always possible, of course, but I'd look for a solution that avoids switch as a first step...


问:
CQRS + Event Sourcing: (is it correct that) Commands are generally communicated point-to-point, while Domain Events are communicated through pub/sub?
I'm basically trying to wrap my head around the concept of CQRS and related concepts.

Although CQRS doesn't necessarily incorporate Messaging and Event Sourcing it seems to be a good combination (as can be seen with a lot of examples / blogposts combining these concepts )

Given a use-case for a state change for something (say to update a Question on SO), would you consider the following flow to be correct (as in best practice) ?

The system issues an aggregate UpdateQuestionCommand which might be separated into a couple of smaller commands: UpdateQuestion which is targeted at the Question Aggregate Root, and UpdateUserAction(to count points, etc) targeted at the User Aggregate Root. These are send asynchronously using point-to-point messaging.

The aggregate roots do their thing and if all goes well fire events QuestionUpdated and UserActionUpdated respectively, which contain state that is outsourced to an Event Store.. to be persisted yadayada, just to be complete, not really the point here.

These events are also put on a pub/sub queue for broadcasting. Any subscriber (among which likely one or multiple Projectors which create the Read Views) are free to subscribe to these events.

The general question: Is it indeed best practice, that Commands are communicated Point-to-Point (i.e: The receiver is known) whereas events are broadcasted (I.e: the receiver(s) are unknown) ?

Assuming the above, what would be the advantage/ disadvantage of allowing Commands to be broadcasted through pub/sub instead of point-to-point?

For example: When broadcasting Commands while using Saga's could be a problem, since the mediation role a Saga needs to play in case of failure of one of the aggregate roots is hindered, because the saga doesn't know which aggregate roots participate to begin with.

On the other hand, I see advantages (flexibility) when broadcasting commands would be allowed.

答:
Disclaimler: I'm only taking my first steps in the CQRS world, but I can offer my current understanding of the matter and we'll see if others confirm. All I write below has an underlying "as I see it" theme, and is not authoritative.

The 80% case

To answer your question, commands are indeed a point-to-point affair. When a command enters a controller (MVC webapp), that controller then asks a command dispatcher to find one and only one apropriate command handler, and delegates the work to that handler.

Why not publish?

It's a question of responsibility. If something sends a command, it entails expectation that it will be fulfilled. If you simply publish and hope that something somewhere picks it up and acts on it, there is no guarantee that this will be the case. By extrapolation, you also don't know if multiple handlers don't decide to act on a command, possibly resulting in the same change being applied more than once.

Events, on the other hand, are informative in nature, and it's reasonable to expect zero, two, or more components to be interested in a particular event. We don't really care in the scope of making the requested change.

Example

This could be compared to real life. If you have three children, walk into a room and simply shout "Clean the bathroom," you have no guarantee that someone will, and perhaphs if it won't be done twice (if you have obedient children that is ;-) You should fare better if you assign a specific child to do what you want done.

When that child finishes its job however, it's convenient if it shouts out "bathroom has been cleaned," so that everyone who wants to brush their teeth knows they can now do so.


问:
Project Management - Asana / activeCollab / basecamp / alternative / none
I don't know whether this should be on programmers - I've been looking at the above three apps over the past few weeks just for myself and I'm in two minds. All three look good, are easy to use, and I came to this conclusion;

Asana is the easiest to use

ActiveCollab is the feature rich and easiest flow

BaseCamp is the best UX / design

But I didn't really find my workflow was any more quicker / efficient, in fact it was a bit slower and organized.

Is there a realistic place for them in workflow - should programmers use them for themselves, or only when a project manager can take control of it?

答:
yes you should use some kind of project managment tool, even as a sole developer. but your primary goals are different, as a team your goal is to keep everyone up-to-date. as a sole developer you are by definition always up-to-date, your goal is to free your mind. freeing it form stuff that needs to be done, but not now.

you can reach this goal by simple writing task's down, in basecamp, excel, an a sheet of paper, .. it doesn't matter just free your brain.

for my projects i am using Trello which is a fantastic tool for my use-case, primary because it doesn't impose a specific workflow on me but it gives me the power to create my very own which fit's my needs.

here is a great blog posts from uservoice which show's how trello can be used in software development.


答:
Lacking a real title, I will be "in charge" of this team.

Don't make the mistake of letting your desire / ambition to be "in charge" get in the way.  If your company hires developers with more experience than you, the new hires may be a lot more suited to the team leader role than you are.

Your real value to the team and the company is your intimate knowledge of the products as currently implemented.

Title: Advice for solo programmer whose team will expand in the near future

Body:
For 4 years now, I've been the solo developer for a small company. We have a handful of well establish products in a niche industry. We will be hiring 1-2 developers soon, and that will likely change the way things operate around here.

While I won't have a "real" title, I will be "in charge" of this team. What I want to do is establish a very organized and productive programming department for my company. I got this solo job right out of college, so while I've become proficient as a programmer in this industry, I lack a lot of team programming experience. I feel that starting out on the right foot will be key.

Right now it's just me, a few computers, and an SVN server. I'm looking for any general guidance on building a team from the ground up.


问:
What is a good design strategy for retaining history of user activities and files like Visual Studio projects?
OK so I'm not so sure that "project" is the right term, but for my purposes, I define "project" as similar to what Visual Studio uses, or Microsoft word - files that the user can open and work on and then save, and when the user runs the application again the program is aware of the files that were worked on last time the application was open.

So I ask, what is a good design strategy for retaining history of user activities and files like Visual Studio projects?

答: You want persistence (the ability of user data to survive across different invocations of the same applications). There are many ways to implement it, and your product description is so general that it is hard to predict which will be best for you. Some possible directions to look at are databases, serialization, memory dumps, and many variations of home-grown persistence approaches (rarely useful unless your requirements are really unusual). Please search for any of those things in your favorite information retrieval tool and come back for more information exchange.


答:
```<code>The mediator doesn't really add much in that scenario
except to keep things consistent across controllers.
</code>```

Well, actually it does.

Keeping things consistent is, in my opinion, in and of itself a huge advantage well worth the trouble.

The added benefits I see is that having the Mediators:

allows you to add other sites

provides a covenient point for adding load balancing

allows you to change the communication method/framework

... (a whole bunch more)

And all without changing a single line of code outside of the mediators!

Basically it means your app is better modularized, and I have not yet come across a situations where that wasn't beneficial, even if the things that it insulates your app code from never change. It just makes all the other stuff less complicated simply because setting up the provider is no longer a concern.

So stick to your SRP guns. Convenience is hardly ever a good advisor when it comes to building maintable systems.

An interesting presentation on the simples versus complex and how we mistake ease for simplicity: http://www.infoq.com/presentations/Simple-Made-Easy It was a "ah yes, finally someone who puts what I have been thinking/feeling about this subject into words" experience.

Body:
The mediator doesn't really add much in that scenario
except to keep things consistent across controllers.

Well, actually it does.

Keeping things consistent is, in my opinion, in and of itself a huge advantage well worth the trouble.

The added benefits I see is that having the Mediators:

allows you to add other sites

provides a covenient point for adding load balancing

allows you to change the communication method/framework

... (a whole bunch more)

And all without changing a single line of code outside of the mediators!

Basically it means your app is better modularized, and I have not yet come across a situations where that wasn't beneficial, even if the things that it insulates your app code from never change. It just makes all the other stuff less complicated simply because setting up the provider is no longer a concern.

So stick to your SRP guns. Convenience is hardly ever a good advisor when it comes to building maintable systems.

An interesting presentation on the simples versus complex and how we mistake ease for simplicity: http://www.infoq.com/presentations/Simple-Made-Easy It was a "ah yes, finally someone who puts what I have been thinking/feeling about this subject into words" experience.


问:
why control + alt + delete couldn't be intercepted by any application
The secure attention key is designed to make login spoofing impossible, as the kernel will suspend any program, including those masquerading as the computer's login process, before starting a trustable login operation.

Why cannot other programs simulate control+alt+del?

What is the reason behind this?

答:
Why it cannot be intercepted:

Because it would be a huge security risk. Imagine an application which launches at logon. It shows a false logon screen to the user and invites the user to enter a password. To avoid this scenario, you often have (in business environments or on Windows Server) to press Ctrl+Alt+Delete before logging in; this ensures that you're not entering your password in a false logon screen.

Because Ctrl+Alt+Delete is known for being the last resort where a full-screen application hangs and you cannot switch to another one (Alt+Tab) or to the start menu (Win). If Ctrl+Alt+Delete is intercepted too, the only way to exit such application would be to power down/unplug/force reboot the PC.

Why it cannot be simulated:

Because you don't need it. You can already do whatever you want with the user session (given enough privileges), including the logoff.

Probably because it's difficult to implement. Since those keys cannot be intercepted, it might be that for the same reason, a piece of software (aside drivers) cannot emulate those keys.


问:
What are some good End-User Programming solutions you have seen?
End-User Programming is where regular end users, i.e. non-programmers, are able to customize a program, or create a new one, with minimal training or instruction.

App Inventor for Android is one recent example, but perhaps the most popular example of end-user programming is the spreadsheet.

What examples of end-user programming have you seen used, or believe to be useful? What's the philosophy of the system? What challenges remain?

答:
There are a lot of, what many would call, "domain specific" languages:

Mathematics:

Matlab & Simulink

Maple

Control Systems:

Ladder Logic

Function Block Diagram

Sequential Function Chart

I might even include the LEGO Mindstorms programming software here

Statistics:

SPSS

Databases:

SQL (the syntax is declarative enough that most non-programmers can write queries)

SQL Server Integration Services (I'm thinking about the flow-chart like editor here)


问:
JavaScript application design patterns
I need to write a PhoneGap application with JavaScript and I'm thinking of the code design patterns. I've read some books of JavaScript design patterns but can't really see the advantages/disadvantages on them and I think I don't understand the implementation and usage right.

I would like to have some opinions of which might suit my needs best. I'd like the code to be readable and maintainable.

The application itself is quite small and simple. It has a player management (add/remove), a game management (add/remove players from a team, start/stop/reset a stopwatch).

In last app I created I had over 30 named functions in a global scope which I think is a big no no. So, now I want to make things right, and was thinking of either using an object literal or a module pattern... something like this perhaps:

```<code>var MYAPP = {
    init: function() {
        $(document).ready(function() {
            MYAPP.bind();
        });
    },

    bind: function() {
        // Bind jQuery click and page events
    },

    player: {
        add:            function(name) { ... },
        remove:         function(name) { ... }
    },

    team: {
        addPlayer:      function(name) { ... },
        removePlayer:   function(name) { ... }
    },

    game: {
        create:         function() { ... },
        startTime:      function() { ... },
        stopTime:       function() { ... },
        resetTime:      function() { ... }
    }
};

document.addEventListener('deviceready', MYAPP.init, false);
</code>```

... or perhaps this?

```<code>var MYAPP = {
    init: function() {
        $(document).ready(function() {
            MYAPP.bind();
        });
    },

    bind: function() {
        // Bind jQuery click and page events
    }
}

var PLAYER = (function () {

    // Some private variables
    var privateVar, privateMethod;

    return {
        add: function (name) { ... },
        remove: function (name) { ... }
    };

}());

document.addEventListener('deviceready', MYAPP.init, false);
</code>```

答:
In last app I created I had over 30 named functions in a global scope which I think is a big no no.

100% correct.

[I] was thinking of either using an object literal or a module pattern.

Sure. Those would be viable patterns.

My thoughts closely align with @Aadaam 's with two caveats:

Here is my favorite JavaScript design patterns link.

I prefer the revealing prototype pattern. My second favorite is the revealing module pattern, which differs slightly from the standard module pattern in that you can declare public/private scope.

Title: JavaScript application design patterns


问:
Design Patterns (java) -- Strategy with fields. Ever acceptable?
Both here on stack overflow and on Java Effective it is suggested that strategy design patterns should be stateless. In fact in the book it is also suggested to make each strategy object a singleton.

The problem I have is that some strategies I envision for my program need states/fields. Either because they are path-dependent in their behavior or because I want them heterogeneous (a statistical distribution of similar strategies, if you prefer).

This forces me to break both Java Effective suggestions: I instantiate a new strategy for each user class AND each of these strategies contain its own fields.

Is that very bad? Should it be done differently?

It was suggested to me to keep the fields that make the strategy heterogeneous in the class that uses it and then pass it as an argument. I find that very anti-oo. Those fields don't belong to the user class. In fact, if that class uses another strategy it might not need those fields at all. That seems to run against the reason I am using the strategy pattern in the first place.

Mostly I am just very confused

I make a simple example here. Imagine you have a class Gambler, which represents somebody making bets on horses. Now this class will require a strategy predictStrategy that will work something like this:

```<code>interface predictStrategy{
    public Horse predictWinningHorse(HorseRace r);
}
</code>```

Now, I can have many implementations where the strategy is to choose at random, or pick the white horse or whatever. That's easy.

Imagine though that I implement a strategy that looks at past predictions and somewhat "learns" from its past mistakes. Clearly each strategy will have to have its own memory on which to learn. I might have to add one more method to the interface (or make an extension)

```<code>interface predictStrategy{
    public Horse predictWinningHorse(HorseRace r);

    public void addObservation(HorseRace r, Horse oldPrediction, Horse actualWinner);
}
</code>```

So that the Gambler class calls "strategy.addObservation(...)" at the end of each race to improve its predictive power.

Can this be really be done with a stateless strategy object? It seems impossible to me.

答:
I would argue that each instance should remain stateless once it is constructed, i.e., it should not maintain extra state across invocations that changes based on the parameters. A classic example is a tax calculator.

```<code>interface TaxCalculator {
    /**
     * Calculates the tax for the given purchase price and shipping charges.
     * All values are in pennies to avoid rounding.
     *
     * @param subtotal total price of all items ordered
     * @param shipping cost of shipping the order
     * @return calculated tax
     */
    int calculate(int subtotal, int shipping);
}

class NoTax implements TaxCalculator {
    public int calculate(int subtotal, int shipping) {
        return 0;
    }
}

class FixedPercentOfSubtotal implements TaxCalculator {
    private final int ratePercent;

    public FixedPercentOfSubtotal(int ratePercent) {
        this.ratePercent = ratePercent;
    }

    public int calculate(int subtotal, int shipping) {
        return subtotal * ratePercent / 100;
    }
}
</code>```

While FixedPercentOfSubtotal has a member (state), it's provided at construction time and never changes. You could store one instance per state, making them quasi-singletons.

Update

Neither the Wikipedia article nor this Strategy Pattern page make any stipulation that implementations should not maintain state across calls. It's less common because strategies are designed to be interchangeable and pluggable at runtime, but I wouldn't rule it out.

However, that you needed to add a new method to enable that one strategy implementation is a red flag. Other implementations may not need it. Will you define it in the interface anyway? It may make more sense to have the historical-tracking strategy implement RaceListener and add it to the race track instance. This would allow it to be shared among multiple users as a singleton.

OwnerDisplayName: CarrKnight

Body:
I would argue that each instance should remain stateless once it is constructed, i.e., it should not maintain extra state across invocations that changes based on the parameters. A classic example is a tax calculator.

interface TaxCalculator {
    /**
     * Calculates the tax for the given purchase price and shipping charges.
     * All values are in pennies to avoid rounding.
     *
     * @param subtotal total price of all items ordered
     * @param shipping cost of shipping the order
     * @return calculated tax
     */
    int calculate(int subtotal, int shipping);
}

class NoTax implements TaxCalculator {
    public int calculate(int subtotal, int shipping) {
        return 0;
    }
}

class FixedPercentOfSubtotal implements TaxCalculator {
    private final int ratePercent;

    public FixedPercentOfSubtotal(int ratePercent) {
        this.ratePercent = ratePercent;
    }

    public int calculate(int subtotal, int shipping) {
        return subtotal * ratePercent / 100;
    }
}

While FixedPercentOfSubtotal has a member (state), it's provided at construction time and never changes. You could store one instance per state, making them quasi-singletons.

Update

Neither the Wikipedia article nor this Strategy Pattern page make any stipulation that implementations should not maintain state across calls. It's less common because strategies are designed to be interchangeable and pluggable at runtime, but I wouldn't rule it out.

However, that you needed to add a new method to enable that one strategy implementation is a red flag. Other implementations may not need it. Will you define it in the interface anyway? It may make more sense to have the historical-tracking strategy implement RaceListener and add it to the race track instance. This would allow it to be shared among multiple users as a singleton.

OwnerDisplayName: David Harkness