问:
How can I write HTML, CSS, and JavaScript to make back-end developers work easier?
When I get a design from a designer, I get it as a PSD (Photoshop) file. I always expect proper layer and folder names, basically a clean and managed PSD. From this desigbn I develop HTML, CSS and JavaScript and deliver it to the back-end developers. To make it easy for them to understand, I

write semantic code,

keep JavaScript and CSS in external files,

add useful comments in HTML, CSS and JS files,

use CSS sprites (though developers don't like it),

use HTML5 boiler plate,

use jQuery for JavaScript,

try to use new HTML5 tags and CSS3 whenever possible and

sent a Zip file containing the HTML, CSS, JS and images.

I expect that if small changes will need to be made to the layout, the developers can handle that.

I would like to hear from back-end developers and other CSS ninjas what more one could do in terms of organization of files and mark-up to make the integration with back-end systems easier (i.e. back-end technologies, PHP, .NET, Ruby etc.) Different client uses different systems.

答:
The obvious things I can think of that would make a back-end guy's life easier is simplicity in behavior. When designing elements of a webpage that have various behaviors (roll-overs, menus, etc), all of this behavior should be standardized in a common manner so that the developer doesn't continually have to revert to some chart to determine which function he needs to call to have a page behave.

Grids should not require a cell by cell manipulation of data or functionality. Block elements of pages should be easily definable as common elements so they can be easily segmented in the code behind. This will help the developer with reusing code and/or facilitating communication between various facets of the page.

Areas of the page should not cross specific design boundaries. Items from one element should not intrude on items from another element.

There comes a point, however, where you simply can't avoid making the developers jump through burning hoops. Some interface elements are just going to be tricky to build by their very nature.


问:
Are there general rules or best practices for building a new framework?
I need to start the design and development of a new framework to interact with an open source ECM. This inludes a customized data model to help web site developers interacting with this ECM, so they don't need to care about the details of nodes manipulation and other low level details. That's just a bunch of classes and methods to develop.

I have some doubts about how to handle the organization and managment of that project: Are there some general rules to follow, tips, best practices or something to keep in mind for developing this kind of project?

I'm sure there are some difference between the development of a framework or library and an application.

答:
First here are my 2 rules to avoid framework waste syndrome:

The absence of an existing one, covering 80% of my needs and extendable to match the last 20%

The near certainty that I will use it again, in another application

After you passed those, check this out:

http://www.slideshare.net/brada/framework-design-guidelines-presentation

http://www.informit.com/podcasts/episode.aspx?e=5a161893-c1ce-4449-8b67-31baa54ce316

http://www.marlabsblogs.com/?tag=microsoft-framework-design-guidelines

ContentLicense: CC BY-SA 3.0


答:
1) Stick to good conventions right from the start, make sure you've documented a very specific convention, the best frameworks are the ones that are internally consistent.

2) Make sure that everything is highly documented, from good code comments all the way through to explaining what the most important functions require and produce, even if it seems super simple to you you might have someone use it on the 14th straight hour and they just need that one thing right then.

3) Set out a project brief for yourself, with what you want the framework to achieve, realistic targets and overall priorities.

4) If it's going to be available for people to use, make sure you've got some form of support process/bug tracking in place. There's going to be bugs, it happens to all of us, but if you can manage them from the off it'll make your life easier.

All in all, similar approach to building any application, but developers are even fussier than users, and the best frameworks are the ones that we can pick up, make sense of, and we don't have to fight.

Title: Are there general rules or best practices for building a new framework?

Body:
I need to start the design and development of a new framework to interact with an open source ECM. This inludes a customized data model to help web site developers interacting with this ECM, so they don't need to care about the details of nodes manipulation and other low level details. That's just a bunch of classes and methods to develop.

I have some doubts about how to handle the organization and managment of that project: Are there some general rules to follow, tips, best practices or something to keep in mind for developing this kind of project?

I'm sure there are some difference between the development of a framework or library and an application.


答:
Note that sometimes, you have to do a choice between making it easy to modify a solution for a back-end developer and making something optimized.

CSS sprites you quoted is a good example. I don't understand how someone can create website when scalability and performance matter and have links to 100 images, 5 CSS and 15 JavaScript files from every page. On the other hand, CSS sprites are not easy to maintain, and slight changes in the design may require lots of work.

For example if you have three state icons, one below another, and you must add a fourth state, do you add the fourth icon to the bottom of the image, separately from three others? Or you add it after the third icon, moving everything else to the bottom to have some empty space for it?

The same comes with combining and minifying CSS and JavaScript files. You must do it for a website of some scale, but it would require extra effort.

It's exactly the same thing for CDN. You have to use it for large websites, but changes would be more difficult to make. For example if you changed a CSS file, you have to force the browsers to download the new one, by modifying the URI to the file to cdn.example.com/g.css?r=2, then cdn.example.com/g.css?r=3, etc.

Also, "easier" is relative. See, for example, the guidelines to write CSS code: personally, I prefer one style per line, with no whitespace:

```<code>#TopMenu a{text-decoration:none;color:#fff;padding:5px 10px;float:left;}
</code>```

while most people would hate this syntax, and prefer the one I hate and find difficult to read (no, I'm not crazy):

```<code>#TopMenu a
{
    text-decoration: none;
    color: #fff;
    padding: 5px 10px;
    float: left;
}
</code>```

In the same way, using jQuery doesn't mean you'll make it easier for back-end developer to modify your files, because some developers are more experienced with Prototype or other frameworks.

In all cases, a detailed documentation is helpful, if the developer wants to read it (most of them don't). You can also make the life of a developer easier by asking precisely to the specific developer how he prefers the things to be done, and by working side by side at the beginning, while building a framework (for example designing the workflow to use to minify and combine the files).

Title: How can I write HTML, CSS, and JavaScript to make back-end developers work easier?

Body:
When I get a design from a designer, I get it as a PSD (Photoshop) file. I always expect proper layer and folder names, basically a clean and managed PSD. From this desigbn I develop HTML, CSS and JavaScript and deliver it to the back-end developers. To make it easy for them to understand, I

write semantic code,

keep JavaScript and CSS in external files,

add useful comments in HTML, CSS and JS files,

use CSS sprites (though developers don't like it),

use HTML5 boiler plate,

use jQuery for JavaScript,

try to use new HTML5 tags and CSS3 whenever possible and

sent a Zip file containing the HTML, CSS, JS and images.

I expect that if small changes will need to be made to the layout, the developers can handle that.

I would like to hear from back-end developers and other CSS ninjas what more one could do in terms of organization of files and mark-up to make the integration with back-end systems easier (i.e. back-end technologies, PHP, .NET, Ruby etc.) Different client uses different systems.

Body:
Note that sometimes, you have to do a choice between making it easy to modify a solution for a back-end developer and making something optimized.

CSS sprites you quoted is a good example. I don't understand how someone can create website when scalability and performance matter and have links to 100 images, 5 CSS and 15 JavaScript files from every page. On the other hand, CSS sprites are not easy to maintain, and slight changes in the design may require lots of work.

For example if you have three state icons, one below another, and you must add a fourth state, do you add the fourth icon to the bottom of the image, separately from three others? Or you add it after the third icon, moving everything else to the bottom to have some empty space for it?

The same comes with combining and minifying CSS and JavaScript files. You must do it for a website of some scale, but it would require extra effort.

It's exactly the same thing for CDN. You have to use it for large websites, but changes would be more difficult to make. For example if you changed a CSS file, you have to force the browsers to download the new one, by modifying the URI to the file to cdn.example.com/g.css?r=2, then cdn.example.com/g.css?r=3, etc.

Also, "easier" is relative. See, for example, the guidelines to write CSS code: personally, I prefer one style per line, with no whitespace:

#TopMenu a{text-decoration:none;color:#fff;padding:5px 10px;float:left;}

while most people would hate this syntax, and prefer the one I hate and find difficult to read (no, I'm not crazy):

#TopMenu a
{
    text-decoration: none;
    color: #fff;
    padding: 5px 10px;
    float: left;
}

In the same way, using jQuery doesn't mean you'll make it easier for back-end developer to modify your files, because some developers are more experienced with Prototype or other frameworks.

In all cases, a detailed documentation is helpful, if the developer wants to read it (most of them don't). You can also make the life of a developer easier by asking precisely to the specific developer how he prefers the things to be done, and by working side by side at the beginning, while building a framework (for example designing the workflow to use to minify and combine the files).


问:
Studies on how noise affects productivity of programmers
Does anyone have any links to studies that show how noise affects the productivity of programmers? Specifically I would like to see how/if productivity rises when noise levels decrease.

As pointed in comments, the nature of the programming workflow is such that you go in and out of focus all the time -- so it's likely to be affected by noise differently than other lines of work.

The reason I think that this is programmer specific is that I am also interested in mathematics. In a noisy place, if I start thinking about maths, the noise goes away and I find myself lost in a world of pictures. In fact my favourite place to do maths was always The Copper Kettle cafe, a busy tourist place.

For programming it's completely different. While programming I'm usually thinking verbally, and any talking whatsoever destroys my train of thought. I'm literally incapable of programming anywhere where there is audible conversation.

I've talked to other programmers who don't even notice noise that disables me, and they say that they think mainly in pictures. Which is why I'm wondering whether there are any actual academic studies into whether programming is particularly noise-affected compared to say maths or lawyering.

答:
The typical response to noisy conditions is to listen to music with headphones.

However, one of the really interesting studies quoted in Peopleware is the experiment done at Cornell -- they gave two groups a complicated task involving a long string of calculations.  One group listened to music while performing the task, and one group had silence.

What they didn't tell either group is that the complicated string of calculations always returned the original number.

It turned out that not everyone figured this out, but of the people who did, a large majority came from the group that did not listen to music.

The theory apparently being is that listening to music is somehow engaging the part of the brain involved in creative thought, keeping it "busy" enough not to be able to look at the big picture of the task being performed.

Something to keep in mind the next time you plug in.

Look in the index under "Cornell" to find the reference.


答:
1) Features should only be added to a Framework when they are extracted from working code. In other words, before adding your cool new idea to your cool new framework, make sure that it actually adds value to and reduces repetition in a working, real world application.

2) Documentation, documentation, documentation.

3) Documentation, documentation, documentation.


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

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

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

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

答:
If the items are presented via an ItemsControl, ListBox, etc. then you can define an ItemTemplate and in that template, have a Button which binds appropriately.  When Silverlight/WPF sees the object type, it'll "inflate" to what the ItemTemplate defines.

A good resource.


答: Painful experience and a lot of wasted effort lead to this advice:  extract or refactor a framework from working software.  Build that software keeping in mind that you think you will want to extract a framework in the future, but don't build the framework first. </p>


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

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

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

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

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

Here's the code:

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

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

            histogram[result - min]++;
        }

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

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

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

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

        return result;
    }

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

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

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

        result += min;
        return result;
    }

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

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

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

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

... and here's the results:

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

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

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

答:
"Is it random (enough)" turns out to be an incredibly subtle question. The short answer is that a traditional unit test just won't cut it - you'll need to generate a bunch of random values and submit them to various statistical tests that give you a high confidence that they are random enough for your needs.

There will be a pattern - we're using psuedo-random number generators after all. But at some point things will be "good enough" for your application (where good enough varies a LOT between say games at one end, where relatively simple generators suffice, all the way up to cryptography where you really need sequences to be infeasible to determine by a determined and well equipped attacker).

The Wikipedia article http://en.wikipedia.org/wiki/Randomness_tests and its follow up links have more information.

ContentLicense: CC BY-SA 4.0


答:
I have two answers for you.

=== FIRST ANSWER ===

As soon as I saw the title of your question, I came to jump in and propose the solution. My solution was the same as what several others have proposed: to mock out your random number generator. After all, I have built several different programs that required this trick in order to write good unit tests, and I have begun making mockable access to random numbers a standard practice in all my coding.

But then I read your question. And for the particular issue that you describe, that is not the answer. Your problem was not that you needed to make predictable a process that used random numbers (so it would be testable). Rather, your problem was to verify that your algorithm mapped uniformly random output from your RNG to uniform-within-the-constraints output from your algorithm -- that if the underlying RNG was uniform it would result in evenly distributed inspection times (subject to the problem constraints).

That's a really hard (but fairly well-defined) problem. Which means it's an INTERESTING problem. Iimmediately began to think of some really great ideas for how to solve this. Back when I was a hotshot programmer I might have started doing something with these ideas. But I'm not a hotshot programmer anymore... I like to that I am more experienced and more skilled now.

So instead of diving in to the hard problem, I thought to myself: what is the value of this? And the answer was disappointing. Your bug got solved already, and you'll be diligent about this issue in the future. External circumstances cannot trigger the problem, only changes to your algorithm. The ONLY reason for tackling this interesting problem was in order to satisfy the practices of TDD (Test Driven Design). If there is one thing that I've learned it is that blindly adhering to any practice when it isn't valuable causes problems. My suggestion is this: Just don't write a test for this, and move on.

=== SECOND ANSWER ===

Wow... what a cool problem!

What you need to do here is to write a test that verifies that your algorithm for selecting inspection dates and times will produce output that is uniformly distributed (within the problem constraints) if the RNG it uses produces uniformly distributed numbers. Here are several approaches, sorted by level of difficulty.

You can apply brute force. Just run the algorithm a WHOLE bunch of times, with a real RNG as input. Inspect the output results to see if they are uniformly distributed. Your test will need to fail if the distribution varies from perfectly uniform by more than a certain threshhold, and to ensure you catch problems the threshhold can't be set TOO low. That means that you will need a HUGE number of runs in order to be sure that the probability of a false positive (a test failure by random chance) is very small (well < 1% for a medium-sized code base; even less for a big code base).

Consider your algorithm as a function that takes the concatenation of all RNG output as an input, then produces inspection times as an output. If you know that this function is piecewise continuous, then there is a way to test your property. Replace the RNG with a mockable RNG and run the algorithm numerous times, producing uniformly distributed RNG output. So if your code required 2 RNG calls, each in the range [0..1], you might have the test run the algorithm 100 times, returning the values [(0.0,0.0), (0.0,0.1), (0.0,0.2), ... (0.0,0.9), (0.1,0.0), (0.1,0.1), ... (0.9,0.9)]. Then you could check whether the output of the 100 runs was (approximately) uniformly distributed within the allowed range.

If you REALLY need to verify the algorithm in a reliable fashion and you can't make assumptions about the algorithm OR run a large number of times, then you can still attack the problem, but you might need some constraints on how you program the algorithm. Check out PyPy and their Object Space approach as an example. You could create an Object Space which, instead of actually executing the algorithm, instead just calculated the shape of the output distribution (assuming that the RNG input is uniform). Of course, this requires that you build such a tool and that your algorithm be built in PyPy or some other tool where it is easy to make drastic modifications to the compiler and use it to analyze the code.

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

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

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

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

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

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

Here's the code:

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

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

            histogram[result - min]++;
        }

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

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

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

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

        return result;
    }

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

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

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

        result += min;
        return result;
    }

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

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

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

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

... and here's the results:

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

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

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


问:
Entity-Component-System architecture: interaction between systems
I am studying the Entity-Component-System architecture philosophy. As I have read about it, a typical entity system has:

1) Entities - which are merely ID tags which have a number of components

2) Components - which contain data on various aspects of an enity that the component is responsible for

3) Systems - which update relevant components of every entity. Say, a rendering system updates the rendering component, or simply saying, draws a picture that is stored in the data of that component. A positional and movement system handles position and movement of each entity who has a corresponding component.

These statements follow from this article which in my opition tries to be the most clear and pure in it's statements -

But the author did not explain how the interaction between systems should be realized. For example, the rendering system must know the data from the positional component of an entity in order to draw it in a correct position. And so on.

So the question is - how should I implement the interaction between the various systems?

答:
Quick answer to the question that you haven't asked yet: the entity ID tag is like the key to a database row in a table, you query the system(s) using that key and pluck out the info you need.

Yes it is theoretically slower than storing pointers away.  No, it is not as slow as you would think because systems can look up that key O(1).

Another quick answer to a question you haven't asked yet: yes, these component systems that everyone loves lately require some infrastructure work to get them working smoothly - they don't exist just as a realignment of where data is stored =)  TANSTAAFL


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

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

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

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

答:
The only real defining feature of the master branch is that it's the default for some operations.  Also, branch names only have meaning within a specific repository.  My master might point to your development, for example.  Also, a master branch is not even required, so if there's any confusion about which branch it should be, my advice is usually to leave it out altogether.

However, in my opinion, the best way to think of it is as the default for pushing to.  Most any online tutorials your developers read are going to assume that.  So, it makes a lot of sense to have master be whatever branch is most often pushed to.  Some people think of it as the pristine copy that is untouchable to developers except after the strictest of scrutiny, but using it that way removes a lot of the helpful defaults git provides.  If you want that kind of pristine branch, I would put it in a completely separate repository that only some people can write to.

Edit:

This question is still getting attention after several years. In that time, the "master should be the pristine tested copy" theory has come to dominate, especially when using GitHub. So while git is still a very flexible version control system, and my original answer still has some merit if your needs are somewhat atypical, in general you should today be going with the model people expect, which is to develop in feature branches and pull request into master, merging only when it has been tested and reviewed.


问:
Advantages of Scrum for the developers themselves?
Scrum being a project management methodology, how would you 'sell' it to the developers in a team that is reasonably happy with its current situation?

It seems easy to me to explain to our Product Manager how Scrum will allow him to get regular releases, to amend requirements, and get the team to focus on the high-priority stories first.  I found it easy to explain what TDD or Continuous Integration bring in a developer's day-to-day life.

But how can developers be convinced to embrace Scrum?  How would Scrum make their life easier?

答:
A couple of things:

Building on Xavier's point about
requirements changing right from the
start - a less political atmosphere
develops when everyone accepts from the start that
some things will not be as the client
expects. Quick
delivery and review will mean that
the cost of mis-communications is
low, and instead of playing the blame
game, the developers can just change
things so that they do work as the
client expects.

Story points! What developer doesn't
like getting points for doing
stuff!!?! Seriously, it's better than
getting badges in SC2 or Stack
Overflow.

ContentLicense: CC BY-SA 2.5


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

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

So let's say we have a projects directory:

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

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

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

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

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

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

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

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

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

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

答:
You know, in SVN most popular folders sheme for "things" is trunk, branches, tags.

Now, how to choose what kind of "things" to use for above scheme?

My preferred way to arrange SVN structure can be called "versioning-driven". Not that it's particularly "my" way, just one suggested by more experienced colleagues. Anyway it's one that has been proven to work best for me.

Versioning-driven means things are defined by whether you find it convenient to have dediccated versions sequence for this kind things, like version 1.0, 2.0, 3.1 etc. anything you want to be "within" that version sequence, makes single SVN "thing". Anything you would find convenient to release under different "version streams" gowes to different SVN "things".

- This product release is composed from component1 version 1.23,
  component2 version 4.56 and component3 version 7.98. where can I get code for component1 used in this release?

  - Code for component1 v1.23 is in SVN folder component1/tags/1.23

- There was patch 666 we did for component2 version 4.3.1 two
  years ago. Where I can get its code? I am particularly interested in releases 1.0 and 2.0

  - That's easy. You can find patch code
  in SVN folder component2/branches/4.3.1.666 and releases in component2/tags/4.3.1.666.1.0, component2/tags/4.3.1.666.2.0

You see, above has basically nothing to do neither with project nor with source file type.

If I need say particular "mix" C#, SQL, Matlab to be released/versioned as a whole (component1 ver 1.0, 2.0, ...), these would go inside one "thing" - having same trunk, tags, branches.

If I need some bunch of C# files to be released/versioned separately of another bunch of C# files (component2 version 4.56 and component3 version 7.98), these would go to separate "things", each having dedicated sub-folders trunk, tags, branches.

As for the projects, SVN folders for these are, again, versioning-driven. If I can think of versions 1.0, 2.0, etc of the project, to me it means the need for own SVN "thing" - own folder "project-name" with trunk, tags, branches sub-folders inside.

Title: Organizing projects in SVN


答: I would suggest the book Framework Design Guidelines.  It's a couple years old, but the principles remain true.  It has a ton of patterns and explains the reasoning behind decisions you'll make when building a framework.</p>


问:
What does the term "fast follower" mean?
In the last few days, I've heard the term "fast follower" mentioned several times. It's used in the context of an unresolved bug/issue that (supposedly) will be quickly fixed and implemented.

Is this some new corporate jargon? I'm aware of a fast follower strategy, or second mover strategy (as described in this wikipedia article), but that doesn't apply in the context.

答:
I think this has more to do with the business "fast follower" that might be releasing similar software with bugs of the original developer fixed hence taking advantage of an idea and original's problems.

Though I have not heard this used in such a context.


答:
The best of all worlds is when the designer isn't tossing a zip file over a wall and is actually working in the project as one of the developers. Requires a bit of handholding to setup, but it is really awesome when there isn't any translation between design and dev and everyone can take part in the same iterations. If you've got a good frictionless agile process going it isn't too hard to make happen.

I'd settle in most cases for the designers working in a version controlled manner and using that as the distribution mechanism. I really don't want to deal with a big fat zip file every time there is a small change.


问:
What is the best way to handle product versioning and branching of long term projects?
In a general sense, for long term projects that may have multiple releases during the products life cycle and require support of previous products, what is the best way to handle product versions and branching of the code base?

In a more specific sense, assume that proper distributed version control is in place (i.e. git) and that the teams are small to large in size and that developer may be working on multiple projects at once. The major issue that is being faced is that there is a contractual obligation to support old versions as they existed at the time which means that new development can not patch old code (Microsoft Office products could be an example of this, you only get patches for the feature year you own).

As a result the current product versioning is a touch convoluted as each main product has multiple dependencies, each with their own versions which may change between annual releases. Likewise, while each product has its own repository, most of the work is not done on the main source trunk but rather on a branch for that years product release with a new branch being made when the product is released so that it may be supported. This in turn means that getting a product's code base isn't a simple matter as one might think when using version control.

答:
How much (and what kind of) structure you need depends a lot on what you want to be able to do.  Figure out what you can't live without, what you want to have, and what you don't care about.

A good example set of decisions might be:

Things we can't live without:

be able to reconstruct any past release at any time

be able to maintain multiple supported major versions of the product at any time

Things we would like to have:

be able to perform ongoing major-feature development (for the next major release) without worrying about branch merges

be able to perform maintenance updates to past releases

Things we can live without:

automated backporting of changes from current work to past releases

never interrupt major feature development even for a few days or a week at at time

If the above were your goals, you could then adopt a process like this:

Do all development work on the trunk of your VCS ("master" in git)

When you are close to a major release, halt major feature development, and focus on system stability for a week or so

When the trunk seems stable, create a branch for this major release

Major feature development can now proceed on the trunk, while only bug fixes and release preparation are allowed on the branch

However, all bug fixes to be made to the branch must first be tested on the trunk; this ensures that they will also be present in all future releases

Create a (VCS) tag on the branch when you are ready to release;  this tag can be used to recreate the release at any time, even after further work on the same branch

Further maintenance releases to this major release (minor releases) can now be prepared on the branch; each will be tagged before release

In the mean time, major feature development geared toward the next major release can continue on the trunk

When you get close to that release, repeat the above steps, creating a new releases branch for that release.  This allows you to have multiple major releases, each on their own branch, in supported status at the same time, with the ability to release separate minor releases against each.

This process won't answer all of your questions -- in particular, you will need a process in place to decide what fixes can be made to a release branch, and to ensure that bugs are not fixed on a release branch first (such fixes should always be tested on the trunk where possible).  But it will give you a framework in which to make such decisions.


答:
A simple histogram approach is a good first step, but is not sufficient to prove randomness. For a uniform PRNG you would also (at the very least) generate a 2-dimensional scatter plot (where x is the previous value and y is the new value). This plot should also be uniform. This is complicated in your situation because there are intentional non-linearities in the system.

My approach would be:

validate (or take as a given) that the source PRNG is sufficiently random (using standard statistical measures)

verify that an unconstrained PRNG-to-datetime conversion is sufficiently random over the output space (this verifies a lack of bias in the conversion). Your simple first-order uniformity test should be sufficient here.

verify that the constrained cases are sufficiently uniform (a simple first-order uniformity test over the valid bins).

Each of these tests is statistical and requires a large number of sample points to avoid false positives and false negatives with a high degree of confidence.

As to the nature of the conversion/constraint algorithm:

Given: method to generate pseudo-random value p where 0 <= p <= M

Need: output y in (possibly discontinuous) range 0 <= y <= N <= M

Algorithm:

calculate r = floor(M / N), that is, the number of complete output ranges that fit within the input range.

calculate the max acceptable value for p: p_max = r * N

generate values for p until a value less than or equal to p_max is found

calculate y = p / r

if y is acceptable, return it, otherwise repeat with step 3

The key is to discard unacceptable values rather than folding non-uniformly.

in pseudo-code:

```<code># assume prng generates non-negative values
def randomInRange(min, max, prng):
    range = max - min
    factor = prng.max / range

    do:
        value = prng()
    while value > range * factor
    return (value / factor) + min

def constrainedRandom(constraint, prng):
    do:
        value = randomInRange(constraint.min, constraint.max, prng)
    while not constraint.is_acceptable(value)
</code>```

Body:
A simple histogram approach is a good first step, but is not sufficient to prove randomness. For a uniform PRNG you would also (at the very least) generate a 2-dimensional scatter plot (where x is the previous value and y is the new value). This plot should also be uniform. This is complicated in your situation because there are intentional non-linearities in the system.

My approach would be:

validate (or take as a given) that the source PRNG is sufficiently random (using standard statistical measures)

verify that an unconstrained PRNG-to-datetime conversion is sufficiently random over the output space (this verifies a lack of bias in the conversion). Your simple first-order uniformity test should be sufficient here.

verify that the constrained cases are sufficiently uniform (a simple first-order uniformity test over the valid bins).

Each of these tests is statistical and requires a large number of sample points to avoid false positives and false negatives with a high degree of confidence.

As to the nature of the conversion/constraint algorithm:

Given: method to generate pseudo-random value p where 0 <= p <= M

Need: output y in (possibly discontinuous) range 0 <= y <= N <= M

Algorithm:

calculate r = floor(M / N), that is, the number of complete output ranges that fit within the input range.

calculate the max acceptable value for p: p_max = r * N

generate values for p until a value less than or equal to p_max is found

calculate y = p / r

if y is acceptable, return it, otherwise repeat with step 3

The key is to discard unacceptable values rather than folding non-uniformly.

in pseudo-code:

# assume prng generates non-negative values
def randomInRange(min, max, prng):
    range = max - min
    factor = prng.max / range

    do:
        value = prng()
    while value > range * factor
    return (value / factor) + min

def constrainedRandom(constraint, prng):
    do:
        value = randomInRange(constraint.min, constraint.max, prng)
    while not constraint.is_acceptable(value)


问:
What false ideas are there that puts people off using threads?
Implementing threading in a program is hard, yes, however why is it that some people will not implement them even when there is an obvious need for it.

An example: Program has to load a dataset from a database, the thing to do would be to make the connection and get the data from the database in a worker thread and then load it into the GUI, leaving the GUI thread responsive for the user.

But no, I've talked to people whom seem to think that threads are evil and bad and whatnot and one should avoid them at all costs.  I've even heard that some class instructor advised against to use of threads and therefore did not want cover their use. WHAT???

With the hardware going into multi-core, I think that we need to understand threads better and not be afraid to use them. I find it a fascinating subject personally.

So what are things you've heard about threading that are false?

答:
An example: Program has to load a dataset from a database, the thing to do would be to make the connection and get the data from the database in a worker thread and then load it into the GUI, leaving the GUI thread responsive for the user.

I don't see that this situation represents a necessity to use threading for at least 4 reasons:

The data retrieval should be very fast.

In many Line of Business applications, the user has nothing to do with the application in the 1 second or two he/she is waiting for the result. Also, the user will have to wait until the data comes back any way to complete the desired task. The query on the other hand could be coded intelligently such that it retrieves only a page-full of information at a time and other optimization techniques could help the response time.

In web based interfaces, links may be made active regarding of the threading model.

Threading adds complexity as you admit, some developers down the line may not be able to add features or debug complex code.

My opinion is: Use threading when you must because software maintainability and reliability is more valuable to an organization than code elegance.


问:
How-to convince company to start documenting for legacy software
It has been less than a year since I joined my current company. Their majority of sales have come from a single product that has been alive since the last 10 years. However, there is minimal (if at all) documentation.

Not only do the developers in the company struggle with the lack of documentation but also there is a high amount of turnover, causing everyone to lose their time. This is because experienced developers have left the company and there is less and less resources to communicate/brain storm with.

Without getting into too much detail, I have suggested to the previous manager that there needs to be some sort of documentation (at least an Architecture document) that outlines the product. I also suggested using JavaDoc and other automatic documentation tools. These suggestions were responded to by slight smiles and statements of the sort "We do not have enough time", "We need short-term improvements right now" and even "The code itself should be the documentation" from the programmers themselves.

I have already wasted enough time trying to find out if what I needed per requirement/bug had existed in this big (really) code base. I am looking for any suggestions that you might give regarding the need of documentation. Or, rather, if this is a lost case for this legacy system or organization.

答:
I don't think you really need your boss's permission to do some documentation.  The most obvious place to start your documentation is the code.

You don't have to launch an all-out documentation-only attack.  Just focus on incorporating documentation as part of your daily work.  When you work on a method without JavaDoc comments, add them.  When you add something convoluted but necessary, add a few comments to explain.  And of course make sure that any new code or features you add are fully documented.

Doing this to the code you're already working on won't add more than a couple of minutes to any given task, and will gradually improve the overall quality of the code.


问:
Roadblock-confused about structure of program
I'm new to programming, and I'm working in C. I know that this is structured programming but if I use blocks, say for local variables:

```<code>{
 int i;
 for(i=0; i<25; i++){
   printf("testing...\n");
   }
}
</code>```

Doesnt this make it kind of object oriented-like? Is this still structured?

答:
Using such code blocks does not really have anything to do with OOP. With that code you are just printing the statement 25 times. </p>

<p>Try looking at concrete differences between say C and Java in terms of design and application.  </p>

Body:
Using such code blocks does not really have anything to do with OOP. With that code you are just printing the statement 25 times.

Try looking at concrete differences between say C and Java in terms of design and application.


答:
One of the persistent myths about Object Oriented programming is that you need to use a special language to program in an object oriented fashion.

The truth is that you can write OO code in any language, and you can write non-OO code even in languages like C++ or Ruby that are very focused on OO.

In your example, though, the answer is no: your code is strictly procedural code.

That doesn't mean you can't write OO code in C, just that you haven't this time.

Consider http://en.wikipedia.org/wiki/Object-oriented_analysis_and_design for some of the background theory, and consider that the original C++ compilers were just a front-end to a C compiler.

Title: Roadblock-confused about structure of program

Body:
I'm new to programming, and I'm working in C. I know that this is structured programming but if I use blocks, say for local variables:

```<code>{
 int i;
 for(i=0; i<25; i++){
   printf("testing...\n");
   }
}
</code>```

Doesnt this make it kind of object oriented-like? Is this still structured?


答:
Sometimes a quick and temporary fix is applied to restrict an application to deal with a serious bug.  It's a temporary patch, and not a fix.  When the fix is a priority, it is often fast tracked and released immediately after the temporary solution.  This could typically be called a fast follower.

Sadly, I think this is more a case of the Pointy Haired Boss and his marketers using jargon to make something sound more interesting that it probably should be.

Note: Any comment that appears immediately after my post will not be considered a "fast follower"  :-P

Title: What does the term "fast follower" mean?

Body:
In the last few days, I've heard the term "fast follower" mentioned several times. It's used in the context of an unresolved bug/issue that (supposedly) will be quickly fixed and implemented.

Is this some new corporate jargon? I'm aware of a fast follower strategy, or second mover strategy (as described in this wikipedia article), but that doesn't apply in the context.


答:
A lot of these answers are going to cover the broad swaths of ideas, but here's my personal ones:

Leave room in the form design for error messages.

Don't put labels in the input boxes!

Put your CSS and JavaScript in a separate file, unless you know what you're doing and feel properly bad about it.

Keep design elements the same between pages. It's infuriating when a design component (like a "recently viewed" box) has different markup on every page.

Don't do what's easy for you, do what's right. <button> tags suck. backround-image for things that really should be  tags suck.

Make sure that if you're creating a page component, it can scale. I know most good front-end developers do this, but I've had plenty of instances where someone used a single image in what should have been a top/bottom cap situation. Programmers don't like opening up Photoshop.

Proofread your templates. Programmers (good ones) are dedicated, detail oriented people. If they start seeing issues in your design (maybe the footer navigation has spelling errors or inconsistent spelling) it's going to make them ask questions and slow down their work.

Finally, and maybe most importantly:

Learn the basic conventions of the language that is being developed in the back-end. Being able to look at a PHP template and understand the basic syntax behind a foreach or an if statement and how to format an echo statement or move a <?php ?> tag around will greatly increase your value as a front-end developer - I love when a front-end developer needs to make a simple change and can do it in the template instead of handing me a new zip of all of their files.

As an addendum, learn to use version control software. You don't need to be an expert, but if I can look at a diff instead of having to try and figure out what changed between two zip files it makes my job a hundred times easier.

Those are just a few - I'm sure there are many more, but if you accomplish all of these you're sure to earn the respect and appreciation of whoever is turning your templates into a web site.

Body:
A lot of these answers are going to cover the broad swaths of ideas, but here's my personal ones:

Leave room in the form design for error messages.

Don't put labels in the input boxes!

Put your CSS and JavaScript in a separate file, unless you know what you're doing and feel properly bad about it.

Keep design elements the same between pages. It's infuriating when a design component (like a "recently viewed" box) has different markup on every page.

Don't do what's easy for you, do what's right. <button> tags suck. backround-image for things that really should be <img> tags suck.

Make sure that if you're creating a page component, it can scale. I know most good front-end developers do this, but I've had plenty of instances where someone used a single image in what should have been a top/bottom cap situation. Programmers don't like opening up Photoshop.

Proofread your templates. Programmers (good ones) are dedicated, detail oriented people. If they start seeing issues in your design (maybe the footer navigation has spelling errors or inconsistent spelling) it's going to make them ask questions and slow down their work.

Finally, and maybe most importantly:

Learn the basic conventions of the language that is being developed in the back-end. Being able to look at a PHP template and understand the basic syntax behind a foreach or an if statement and how to format an echo statement or move a <?php ?> tag around will greatly increase your value as a front-end developer - I love when a front-end developer needs to make a simple change and can do it in the template instead of handing me a new zip of all of their files.

As an addendum, learn to use version control software. You don't need to be an expert, but if I can look at a diff instead of having to try and figure out what changed between two zip files it makes my job a hundred times easier.

Those are just a few - I'm sure there are many more, but if you accomplish all of these you're sure to earn the respect and appreciation of whoever is turning your templates into a web site.


问:
How to start team programming
I work in a small (7 developer) development team and we all work on our own projects.  Some of the barriers to team work are the languages and platforms we work on (.NET vs mainframe RPG programming) but other barriers are just that we're all so busy we haven't taken the time to take a step back and organize teams.  Me and two other .NET developers are taking initiative to starting a small team but we're all a little stuck on what to do.  We're starting with sharing knowledge on the products we work on so we can back each other up but we eventually want to tackle projects as a team instead of individually.  What advice would you give a group of guys like us trying to start up team work?</p>

答:
I can think of a few things to start with. This might not be an ideal list since this is something I see established teams wrestle with sometimes.

Firstly, if you don't have it, I'd get some necessary infrastructure in place. Things like source control, maybe a build server, and documentation couldn't hurt.

Secondly I'd try either code reviews to get people up to speed or some pair programming. Also, asking someone to come over and take a look at a problem could be a good start. They might not know your project or even the language, but it helps to have a sounding board and pretty soon they'll start picking things up.

Title: How to start team programming


答:
I disagree with a lot of what has been said and I feel that more has been left unmentioned so I'll start from scratch.

Agile Methodologies

Adopt agile methodologies during your framework development so that you can adapt to change, react quickly to roadblocks, and ensure a functional, quality final product.  Agile methodologies are those that, according to the "Agile Manifesto", prioritize:

Individuals and interactions over processes and tools

  Working software over comprehensive documentation

  Customer collaboration over contract negotiation

  Responding to change over following a plan

That's right.  I said functionality is more important than documentation.  Note that the "Agile Manifesto" mentions that the right-hand priorities are still important, just less so than those on the left.

Communication

Whoever is making the framework needs to know:

How it will be used: the target application

What problem it is intended to solve: the target problem

Who will be using it: the target audience

For example, if a company were intending to develop a final application with ASP .NET it would be foolish to tell its programmers "make this framework" without telling them the above. If the programmers didn't know the target application they might not make it web-oriented. If they didn't know the problem, they might make a framework for a different purpose. If they didn't know the audience they might program the framework in C++.  Any of these circumstances would render the resulting framework useless.

Style

Needless to say, establish a programming style/format and stick with it.

The E's

Modularity: Reuse code programmatically, not literally.

Efficiency: Your code is intended for reuse.  Any detriments to speed get multiplied.

Maintainability: You want to be able to edit the framework to update several programs, without having to modify said programs.

Usability: Can applications actually use your framework without jumping through hoops?

Practicality: Don't reinvent the wheel if you don't have to do so.  Your framework can depend on other frameworks.

Redundancy: Catch exceptions/errors. Everywhere. Handle them.  Everywhere.  Never trust any code but that in the local scope to handle errors, even if you know that it does.


答:
What you've illustrated is minimizing variable scope, which is a good thing to be doing.

You could call that a form of encapsulation, which is one of the tenets of object-oriented programming, because you're using a mechanism of the language to restrict visibility of data to only the code which needs to see it.  Calling that object-oriented programming would be quite a stretch, though.


问:
What do you consider to be the prime cause of software defects (and how to minimize them)
I define defect as :

"something within the application design or code which prevents it functioning as per requirements."

I'm looking for ideas about the causes of defects, eg the human factor, lack of testing, lack of prototyping, and possible ideas to mitigate these.

答:
At one level, management. But it's not just the PHB. It's the management of the code itself, which may or may not be a reflection of the corporate management.

The participants in the entire "lifecycle" need to be fully invested in quality and making a product that just doesn't die. Software itself has the promise of never breaking, given the proper abstraction reliability. It is only a question of whether the software constructors are interested in having that perfect operation.


问:
Are C and/or C++ viable/practical options for web development?
I am proficient in C, and I am learning C++ right now. I always played with websites (HTML/CSS), and I was wondering if it would be viable/practical to create some simple web apps using C and/or C++.

For C it would be via CGI scripts, as explained in this tutorial for example -> http://www.cs.tut.fi/~jkorpela/forms/cgic.html

For C++ it could be via a web toolkit like Wt -> http://www.webtoolkit.eu/wt

Notice that I know it's possible (as explained in this previous question -> Can C++ be used as a server-side web development language? ).

What I am asking is if it's viable/practical (i.e., not a nightmare). I am not keen on picking up another language yet as I just started with C++, but if it would make web dev incredibly easier I will consider it (or I'll postpone my web dev projects until I am ready to pick up a new language).

Also, in case you think it's viable/practical, recommendations on the route to follow would be highly appreciated (i.e., forget C and go with C++, what framework to use and so on).

答:
For webpages, yes your HTML and CSS are good (now even better with HTML5 and CSS3).
For web apps probably Flash and HTML5.

What I'm saying is that these are the easiest and fastest ways due to available resources compared to C and C++ unless you are a hardcore C++ enthusiast or if you're trying to accomplish something big!


答:
I'm sure there are some difference between the development of a framework or library and an application.

Development processes are essentially the same.  The differences may come down to marketing and deployment issues, although I find that the biggest differences are usually in terms of project scope and definition.  Remember that an Application may include or use a framework or a library, a framework may be a collection of libraries.

I have some doubts about how to handle the organization and managment of that project: Are there some general rules to follow, tips, best practices or something to keep in mind for developing this kind of project?

Project organization and management are again the same for any development project. Again it comes down to scope.  When it comes to writing a framework however, it pays to have a very clear vision about what it is you are trying to achieve, and to place strict design rules on the public interface to the framework to ensure consistency in terms of the API's presentation. If you allow every developer to do their own thing, you'll end up with a complicated mess, and a very inelegant API design.

I'll second Ryan Hayes' recommendation to read Framework Design Guidelines even though the book itself is aimed at developing .NET based frameworks, because the general advice is applicable regardless of the specific implementation technologies that you might choose to use.

From experience, I would advise sticking to the classic YAGNI principle by implementing the most simplistic public interfaces first, and then expanding to offer greater control and depth later on, but be careful to use useful names to show why methods or classes are being expanded.  I've never been a fan of adding "Ex" or other similar suffixes to method names, or adding numbers to expanded Interface definitions. Differentiate on functionality, and your interface/method names should become clearer, and hopefully less obfuscated and confusing.


答:
Lack of checking for things that "can't happen" or are unlikely to happen is a big one.  Sometimes the perfect is the enemy of the good.  If it's not worth a well-thought out exception hierarchy, some quick and dirty handling is always better than nothing.  I'm a huge fan of failing fast, of asserts and of leaving asserts that have negligible impact on performance on in release builds.  Even in quick and dirty one-off scripts where I control all input data, I put some quick/dirty error handling in, usually just with a function that is equivalent to assert but stays on all the time.  My rule of thumb is that, if it's not likely to occur or you think it can't happen, it doesn't need to fail gracefully with a user-friendly error message, but it should at least fail fast with an error message that gives a programmer some hints about what went wrong.

Edit:  One related useful tactic is to use asserts as a major debugging tool and leave them in there after the debugging session is over.  From that point on, your codebase will have some builtin sanity checks that make it very hard for related bugs to ever happen again.  This is especially useful for code that is hard to unittest.

Title: What do you consider to be the prime cause of software defects (and how to minimize them)

Body:
I define defect as :

"something within the application design or code which prevents it functioning as per requirements."

I'm looking for ideas about the causes of defects, eg the human factor, lack of testing, lack of prototyping, and possible ideas to mitigate these.


问:
Computed Values and Simple Reads - A nagging pain for my Domain Driven Designs!
The problem I continually face is how to deal with computed values driven by domain logic while still working efficiently against the data store.

Example:

I'm returning a list of Products from my repository via a service. This list is limited by pagination info from request DTO sent by the client. In addition, the DTO specifies a sort parameter (a client-friendly enum).

In a simple scenario, everything works great: the service sends paging and sorting expressions to the repo and the repo issues an efficient query to the DB.

That all breaks down, however, when I need to sort on values generated in memory from my domain model. For instance the Product class has an IsExpired() method that returns a bool based on business logic. Now I can't sort and page at the repo level --it would all have be done in memory (inefficient) and my service would have to know the intricacies of when to issue these params to the repo and when to perform sorting/paging itself.

The only pattern that seems to make sense to me is to store the state of the entity in the db (make IsExpired() a readonly field and update it via the domain logic before saving). If I separate this logic into a separate "read model/dto" and "reporting" repository, I'm making my model more anemic than I'd like to.

BTW, every example I've seen out there for computations like this really seems to lean on in-memory processing and glossing over the fact that it is far less efficient in the long run. Maybe I'm prematurely optimizing, but that just doesn't sit right with me.

I'd love to hear how others have dealt with this as I'm sure it's common on nearly project involving DDD.

答:
I don't think that having two different domain models of the same data model makes your domain anaemic. An anaemic domain model is one where the business logic that changes often is hidden away from the domain in a service layer (or, worse, in the UI layer).

Separation of command and query domain models is espoused often and has a nice acronym that you can google in CQRS (Command Query Responsibility Segregation).

Employing the Domain Model Pattern, Udi Dahan

While I was "successful" in the past in creating a single persistent object model that handled both commands and queries, it was often very difficult to scale it, as each part of the system tugged the model in a different direction.

It turns out that developers often take on more strenuous requirements than the business actually needs. The decision to use the domain model entities for showing information to the user is just such an example.

[...]

For those old enough to remember, the best practices around using COM+ guided us to create separate components for read-only and for read-write logic. Here we are, a decade later, with new technologies like the Entity Framework, yet those same principles continue to hold.

CQRS with Akka actors and functional domain models, Debasish Ghosh

Greg Young has delivered some great sessions on DDD and CQRS. In 2008 he said "A single model cannot be appropriate for reporting, searching and transactional behavior". We have at least two models - one that processes commands and feeds changes to another model which serves user queries and reports. The transactional behavior of the application gets executed through the rich domain model of aggregates and repositories, while the queries are directly served from a de-normalized data model.

CQRS, Martin Fowler

The change that CQRS introduces is to split that conceptual model into separate models for update and display, which it refers to as Command and Query respectively following the vocabulary of CommandQuerySeparation. The rationale is that for many problems, particularly in more complicated domains, having the same conceptual model for commands and queries leads to a more complex model that does neither well.

In short, your idea of having the command model handle the expiration and pass it to the database is absolutely fine. Read through the first article above and you'll see similar but more complex scenarios.


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

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

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

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

How should I handle the situation?

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

答:
When I was a newer developer on a very small team, I did a lot of this kind of improvement in my free time.  I enjoyed it; I would log on and try out interesting new techniques while sitting in the living room with my wife at night.  As I got to be a more senior developer and then manager of a bigger team, my free time disappeared.  We were working extra hours just to get the features and critical fixes done.  It became really hard to justify spending anyone's time on that regular housekeeping work, even though we all knew how important it was.

Your bosses don't need an explanation of how important it is, to keep maintenance costs down, reduce the cost of future growth, keep a talented development team engaged, etc.  If they do, you have big problems.  What they might need, however, is a plan.  Because right now I'm guessing that they have all sorts of plans, schedules, roadmaps, promises, and pressure on the "add functionality" side, which are competing against mere wishful thinking and open-ended requests from the developer team.

One thing you could try is making a documented plan.  See if you can tie it to releases, or to exit criteria for new functionality.  A request to "spend some time redoing the reference counting" might be tough for your boss to approve, but scheduling a 5-day block of time 4 weeks from now might be easier.  Basically, however you see that new features are planned and scheduled, try to mimic that, or inject a "under-the-hood" portion into it.

Start small by asking for 5% time allocated to that type of stuff, and then gradually build up your own technology roadmap priorities, and keep plugging away at justifying the business case, ROI, risk levels, etc. on each of them.  Pretty soon you'll even get a taste of your bosses' challenges, as you'll quickly find many more great ideas than you have time to do.

Good luck!


答:
I guess I would question what the business logic is that determines whether isExpired is true or not.  Can this logic be performed by a query as the data model stands?  If so, can you make your repository intelligent enough to use the "isExpired" logic when you ask it for Products in a certain way? If not, perhaps you do need to reexamine your data model. </p>

<p>DDD doesn't mean that your repositories need to be stupid--it just means your domain needs to know how to talk to your repositories. </p>

Title: Computed Values and Simple Reads - A nagging pain for my Domain Driven Designs!

Body:
The problem I continually face is how to deal with computed values driven by domain logic while still working efficiently against the data store.

Example:

I'm returning a list of Products from my repository via a service. This list is limited by pagination info from request DTO sent by the client. In addition, the DTO specifies a sort parameter (a client-friendly enum).

In a simple scenario, everything works great: the service sends paging and sorting expressions to the repo and the repo issues an efficient query to the DB.

That all breaks down, however, when I need to sort on values generated in memory from my domain model. For instance the Product class has an IsExpired() method that returns a bool based on business logic. Now I can't sort and page at the repo level --it would all have be done in memory (inefficient) and my service would have to know the intricacies of when to issue these params to the repo and when to perform sorting/paging itself.

The only pattern that seems to make sense to me is to store the state of the entity in the db (make IsExpired() a readonly field and update it via the domain logic before saving). If I separate this logic into a separate "read model/dto" and "reporting" repository, I'm making my model more anemic than I'd like to.

BTW, every example I've seen out there for computations like this really seems to lean on in-memory processing and glossing over the fact that it is far less efficient in the long run. Maybe I'm prematurely optimizing, but that just doesn't sit right with me.

I'd love to hear how others have dealt with this as I'm sure it's common on nearly project involving DDD.

Body:
I guess I would question what the business logic is that determines whether isExpired is true or not.  Can this logic be performed by a query as the data model stands?  If so, can you make your repository intelligent enough to use the "isExpired" logic when you ask it for Products in a certain way? If not, perhaps you do need to reexamine your data model.

DDD doesn't mean that your repositories need to be stupid--it just means your domain needs to know how to talk to your repositories.


答:
Any time you face challenges, you can start a discussions with your colleagues to come up with a solution. You can share your ideas and they will come up with theirs for the problem at hand. This will help foster collaborative learning environment that fostered teamwork and team learning.

Good luck!

Title: How to start team programming

Body: I work in a small (7 developer) development team and we all work on our own projects.  Some of the barriers to team work are the languages and platforms we work on (.NET vs mainframe RPG programming) but other barriers are just that we're all so busy we haven't taken the time to take a step back and organize teams.  Me and two other .NET developers are taking initiative to starting a small team but we're all a little stuck on what to do.  We're starting with sharing knowledge on the products we work on so we can back each other up but we eventually want to tackle projects as a team instead of individually.  What advice would you give a group of guys like us trying to start up team work?</p>


问:
Is developing games the best way to learn programming?
I heard recently an instructor mentinon that developing games was the best way to learn programming. Besides the fact that everything had to be created in code, he said you really get to fully experience and implement OOP into your programs. In other words everything you make in a game is a literal object both technically and in concept. Is it safe to make this assumption? Or are there always exceptions when learning programming?

note it was geared towards .net / xna / c# development.

答:
I think this is an excellent article giving an insight on game development.

It talks about some basic areas to focus on

Passion for game development.

Learning attitude.

It is important to enjoy playing games.

Importance of your programming skills.


答:
Not really no. There isn't a best type of project to learn programming on. The best type of project is one that's relevant to your interests.

For example, I tried to learn programming a couple different ways, including learning to program games. It just never seemed to stick.

Then when I needed to learn how to program for what I was doing in my research? Right now I'm comfortable enough to say I know 2 languages, and am working on a third. Why? Because it was relevant to my interests. I had a reason to stick with it, a reason to learn, and more problems to try than just "Exercise 8" in the book.

This, incidentally, doesn't mean programming epidemic models is the best way to learn programming. But it was the best way for me. Find yours. It might be games, but it may very well not.

Title: Is developing games the best way to learn programming?

Body:
I heard recently an instructor mentinon that developing games was the best way to learn programming. Besides the fact that everything had to be created in code, he said you really get to fully experience and implement OOP into your programs. In other words everything you make in a game is a literal object both technically and in concept. Is it safe to make this assumption? Or are there always exceptions when learning programming?

note it was geared towards .net / xna / c# development.