Friday, February 4, 2011

Don't repeat yourself vs Internationalisation

A while back I was reading the W3C article on 'Re-using Strings in Scripted Content', which contains some useful advice on internationalisation, but which strikes me as at odds iwth the DRY (Don't Repeat Yourself) principle of eliminating repetitive code.

To take their example, we might have some code like this...

print "The printer is ";
if (printer.working) {
    print "on.\n";
} else {
    print "off.\n";
}

print "The stapler is ";
if (stapler.working) {
    print "on.\n";
} else {
    print "off.\n";
}

My instinct would be to eliminate the repetition roughly as follows...

report-state(printer, "printer");
report-state(stapler, "stapler");

function report-state(name, object) {
    print "The "+name+" is ";
    if (object.working) {
        print "on\n";
    } else {
        print "off\n";
    }
}

...but doing so would cause a difficulty in the code if we needed to localise it to Spanish because the word for 'on' is apparently different in those two cases.

So, I guess my question is, how have other developers approached balancing the DRY principle with internationalisation of their code?

Part of me wants to argue that internationalisation is one of those extreme programming “you arent gonna need it” situations. On the flip side however, refactoring with the DRY principle in mind is supposed to balance this by making it easy to implement functionality as it’s required, not harder as it does here.

  • I would suggest using a CMS rather than hardcoding in your textual values to cover localisation.

    From badbod99
  • I'd try to keep complete sentences in the language resource. As you said you might need different words in different contexts. But a bigger problem is that the order of sentences might be different in different languages. So building up strings from words can cause problems.

    Just store

    The printer is on
    The printer is off
    The stapler is on
    The stapler is off
    

    in the language resource for every language. The repetition here is less of a maintenance headache than trying to figure out where all the single words are going to pop up in your application.

    From Mendelt
  • I agree with Mendelt Siebenga when he says you should keep entire sentences or phrases in your language resource files. Differences in grammar will always prevent you from doing single word replacement across languages. This will still lead to less repetitive code than your first example because you only need to check the object type and its state, then print the appropriate message from the language resource.

  • I suppose it depends on the level of language quality that you are aiming to achieve.

    By trying to minimise repetition of code that deals with these real language strings, you are just exposing yourself to a whole other layer of logic in the syntaxes and structures of different languages. There would be a massive amount of work involved in producing code which still retains the original structure of the language whilst minimising repetition.

    You'd have to decide which was a more suitable approach to a particular problem; Code that repeats itself, or code that tries to be a Jack of all Trades and accomodates for countless rules of language (no doubt a maintenance nightmare).

    Of course, you can strike a middle-ground and minimise your code repitition but give up satisfactory grammatical eloquence. Take the example of Ultima Online - when it was localised, a string that previously read "A pile of 329 gold coins" became something like "A pile of gold coins: 329". Not great, but a fairly reasonable solution that lends itself easily to localisation.

  • We try not to create message strings by program manipulation because the loc. team can't see them.

    The loc. team actually prefer separate but nearly duplicate messages. However they will accept parameterized messages.

    E.g., "The %(appliance)% is %(on_or_off)%."

    The parameters can break down but at least it's more obvious to the loc team when it will work and when it won't.

    From maccullt
  • 100% agree with Mendelt.

    It is not only a maintenance problem, but can also be a linguistic one. In all Latin languages the gender, number, and case of the subject affect other elements. Example for Romanian

      The printer is on: Imprimanta este pornită // feminine
      The printer is off: Imprimanta este oprită
      The stapler is on: Perforatorul este pornit // masculine
      The stapler is off: Perforatorul este oprit
    

    Also see http://www.mihai-nita.net/article.php?artID=20060430a

    From

Dependency Injection/Inversion of Control

I am about to dip my toe into DI/IoC for the first time with part of an app we have in production. I've spent the last month or so researching DI/IoC and will most likely use the Castle Windsor Container although NInject may be an option.

Any of you folks out there got any advice & guidance on best practices, typical pinch/pain points, gotchas, anti-patterns.

  • A lot of DI tools make it really easy to use singletons which really are an antipattern - so the first pitfall to avoid is [excessive] use of singletons.

    ColinD : Er, if DI is a bright center to the universe, the Singleton anti-pattern is the planet it's farthest from. A DI singleton isn't even remotely the same thing. All singleton means in DI is that it will inject references to a single cached instance wherever that instance is needed.
  • I'd highly recommend implementing an auto-registration strategy up front for two reasons:

    1. It will prevent your configuration files from getting overly complicated
    2. It will enforce a structure onto the naming conventions (and locations) of items in your system
    From Wolfbyte
  • I only have a tiny bit of experience with Spring, but a lot of work done with Guice. Of course those are Java tools, and this seems to be a very .NET oriented crowd so far. But the same concepts apply. I believe NINject is in the spirit of Guice.

    If it's an existing code base, you're really going to be refactoring your code. In our case it was like untying a knot. You undo one dependency which frees up another one and you can refactor. You can just keep iterating until you've loosened up everything.

    About singletons: You will have singletons. They are useful. The reason they are not as terrible with DI is that the classes which depend on them are not statically dependent on them. This keeps unit testing easy. Which (I think) is really the goal here.

  • I've recently been using the unity container and although I don't think it's quite as mature as Castle Windsor it seems to me to be very robust, have all the key features and as a bonus be more cohesively documented.

    The selling point for me is that since it's from the patterns and practices team at Microsoft it was an easier sell in the corporate environment.

    You're going to have fun retrofitting it into an existing solution though, i'd suggest you check out the DI podcasts on the alt.net podcast for some background on this as a possibility.

    From Campbell
  • I've been using Castle Windsor with Binsor for a year or so now, and it's a joy to use! I highly recommend giving it a try.

  • +1 For castle windsor, however I would recommend using trunk as the 'official' release is quite old and there are many (some breaking) changes in trunk that will eventually get released.

  • I'd encourage you to be careful to not have references to your IoC/DI container anywhere except at the level where you register your dependencies and instantiate your Shell/Controller/Presenter/whatever and then let the dependencies flow from there. I've been tempted at times to call out to the static methods and get dependencies right there, but then, while attempting to remove dependencies and limit coupling, I'm now tightly coupled to my container!

    I've also seen the practice of actually wrapping the IoC/DI container with your own facade so that you can swap out containers easily if you feel the need as is described here.

    Jimmy : But when you get attached to your facade, you have to wrap that in another facade!
  • Thought I'd share a post from Jimmy Bogard on IoC container guidelines. He's got some good hints in there.

activerecord as model, is this a good idea?

Recently thanks to rails' popularity, many people start using activerecord as model. however, before I heard of rails (my peer group was not a fan of open source stuff, we were taught in a .NET school...) and while I was doing my final year project, i found this definition for a model

The model represents enterprise data and the business rules that govern access to and updates of this data. Often the model serves as a software approximation to a real-world process, so simple real-world modeling techniques apply when defining the model.

it doesn't say the model should represent one table as what activerecord does. And normally within a transaction, one may have to query a few unrelated tables and then manipulate data from different tables... so if activerecord is used as model, then either one would have to cram all the logic code into the controller (which is kinda popular in some php frameworks) that makes it difficult to test or hack the activerecord model so that it performs database operation on not only the table it maps to, but also other related tables as well...

so, what is so great about abusing (IMHO) activerecord as the model in a MVC architectural pattern?

  • Martin Fowler described this pattern in Patterns of Enterprise Application Architecture together with two other patterns or architectures. These patterns are good for different situations and different amounts of complexity.

    If you want to so only simple stuff you can use Transaction Script. This is an architecture you saw in lot's of old ASP and PHP pages where a single script contained the business logic, data-access logic and presentation logic. This falls apart fast when things get more complicated.

    The next thing you can do is add some separation between presentation and model. This is activerecord. The model is still tied to the database but you've a bit more flexibility because you can reuse your model/dataccess between views/pages/whatever. It's not as flexible as it could be but depending on your data-access solution it can be flexible enough. Frameworks like CSLA in .Net have a lot of aspects from this patterm (I think Entity Framework looks a bit too much like this too). It can still handle a lot of complexity without becoming unmaintainable.

    The next step is separating your data-access layer and your model. This usually requires a good OR mapper or a lot of work. So not everyone wants to go this way. Lot's of methodologies like domain driven design perscribe this approach.

    So it's all a matter of context. What do you need and what is the best solution. I even still use transaction-script sometimes for simple single use code.

    From Mendelt
  • The great thing about using the Rails ActiveRecord as a model in MVC is that it gives you an automatic ORM (Object Relational Mapper) and easy way to create associations between models. As you have pointed out, MVC can sometimes be lacking.

    Therefore, for some complex transaction involving many models, I'd suggest to use a Presenter in between your controller and your models (Rails Presenter Pattern). The Presenter would aggregate your models and transactional logic and would remain easily testable. You definitely want to strive to keep all of your business logic in your models or presenters, and out of your controllers (Skinny Controller, Fat Model).

    From ottobar

Stuts2 Tiles Tomcat suspected of changing UTF-8 to ?????

I'm having some internationalisation woes:

My UTF-8 string fields are being rendered in the browser as ???? after being returned from the database.

After retrieval from the database using Hibernate, the String fields are presented correctly on inspection using the eclipse debugger.

However Struts2/Tiles is rendering these strings as ???? in the HTML sent to the browser.

The charset directive is present in the HTML header:

Perhaps I need to add something to my struts2 or tiles configurations?

  • Try setting the lang attribute on the <html/> element.

    HTML example:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html lang="ja"> 
    

    XHTML example:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja"> 
    
  • You could try something like this.

    It's taken from sun's page on Character Sets and Encodings. I think this has to be the very first line in your jsp.

    <%@ page contentType="text/html; charset=UTF-8" %>
    
    From ScArcher2
  • Thanks guys.

    Sadly doing this hasn't helped.

    From Ash Kim
  • OMG - it turns out that the cause was a total WTF?

    all our tile responses were being served by a homegrown servlet that was ignoring the

    <%@ page contentType="text/html; charset=UTF-8" %>

    directive (and who know what else).

    TilesDispatchExtensionServlet : bloody architecture astronauts, i shake my fist at ye.

    From Ash Kim
  • You need to use a filter. See:

    http://wiki.apache.org/tomcat/Tomcat/UTF-8

Create drop down list options from enum in a DataGridView

I currently have a class and I'm trying to create an easy GUI to create a collection of this class. Most of the attributes of this class are strings. However, one of the attributes I want the user to be able to set is an Enum. Therefore, I would like the user interface, to have a dropdownlist for this enum, to restrict the user from entering a value that is not valid. Currently, I am taking the initial list of objects, adding them to a DataTable and setting the DataSource of my DataGridView to the table. Works nicely, even creates a checkbox column for the one Boolean property. But, I don't know how to make the column for the enum into a dropdownlist. I am using C# and .NET 2.0.

Also, I have tried assigning the DataSource of the DataGridView to the list of my objects, but when I do this, it doesn't help with the enum and I'm unable to create new rows in the DataGridView, but I am definitely not bound to using a DataTable as my DataSource, it was simply the option I have semi-working.

  • I do not know if that would work with a DataGridView column but it works with ComboBoxes:

    comboBox1.DataSource = Enum.GetValues(typeof(MyEnum));
    

    and:

    MyEnum value = (MyEnum)comboBox1.SelectedValue;
    

    UPDATE: It works with DataGridView columns too, just remember to set the value type.

    DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn();
    col.Name = "My Enum Column";
    col.DataSource = Enum.GetValues(typeof(MyEnum));
    col.ValueType = typeof(MyEnum);
    dataGridView1.Columns.Add(col);
    
  • Or, if you need to do some filtering of the enumerator values, you can loop through Enum.GetValues(typeof(EnumeratorName)) and add the ones you want using:

    dataGridViewComboBoxColumn.Items.Add(EnumeratorValue)
    

    As an aside, rather than using a DataTable, you can set the DataSource of the DataGridView to a BindingSource object, with the DataSource of the BindingSource object set to a BindingList<Your Class>, which you populate by passing an IList into the constructor.

    Actually, I'd be interested to know from anyone if this is preferable to using a DataTable in situations where you don't already have one (i.e. it is returned from a database call).

  • MyEnum value = (MyEnum)comboBox1.SelectedValue;

    Not working It Gives Error of Specified Cast is Not Valid.

    Any Other Solutuions ???

    From Sameep

How do you perform a CROSS JOIN with LINQ to SQL?

How do you perform a CROSS JOIN with LINQ to SQL?

  • A cross-join is simply the Cartesian product of two sets. There's no explicit join operator for it.

    var combo = from p in people
                from c in cars
                select new
                {
                    p.Name,
                    c.Make,
                    c.Model,
                    c.Colour
                };
    
  • Based on Steve's answer, the simplest expression would be this:

    var combo = from Person in people
                from Car    in cars
                select new {Person, Car};
    

How to test randomness (case in point - Shuffling)

First off, this question is ripped out from this question. I did it because I think this part is bigger than a sub-part of a longer question. If it offends, please pardon me.

Assume that you have a algorithm that generates randomness. Now how do you test it? Or to be more direct - Assume you have an algorithm that shuffles a deck of cards, how do you test that it's a perfectly random algorithm?

To add some theory to the problem - A deck of cards can be shuffled in 52! (52 factorial) different ways. Take a deck of cards, shuffle it by hand and write down the order of all cards. What is the probability that you would have gotten exactly that shuffle? Answer: 1 / 52!.

What is the chance that you, after shuffling, will get A, K, Q, J ... of each suit in a sequence? Answer 1 / 52!

So, just shuffling once and looking at the result will give you absolutely no information about your shuffling algorithms randomness. Twice and you have more information, Three even more...

How would you black box test a shuffling algorithm for randomness?

  • Shuffle alot, and then record the outcomes (if im reading this correctly). I remember seeing comparisons of "random number generators". They just test it over and over, then graph the results.

    If it is truly random the graph will be mostly even.

    From Deinumite
  • Have a look at this Coding Horror article, and the comments on it.

    From Ash
  • The only way to test for randomness is to write a program that attempts to build a predictive model for the data being tested, and then use that model to try to predict future data, and then showing that the uncertainty, or entropy, of its predictions tend towards maximum (i.e. the uniform distribution) over time. Of course, you'll always be uncertain whether or not your model has captured all of the necessary context; given a model, it'll always be possible to build a second model that generates non-random data that looks random to the first. But as long as you accept that the orbit of Pluto has an insignificant influence on the results of the shuffling algorithm, then you should be able to satisfy yourself that its results are acceptably random.

    Of course, if you do this, you might as well use your model generatively, to actually create the data you want. And if you do that, then you're back at square one.

    Ed Guiness : What are you sorry about?
    From MegaHAL
  • Statistics. The de facto standard for testing RNGs is the Diehard suite. Alternatively, the Ent program provides tests that are simpler to interpret but less comprehensive.

    As for shuffling algorithms, use a well-known algorithm such as Fisher-Yates (a.k.a "Knuth Shuffle"). The shuffle will be uniformly random so long as the underlying RNG is uniformly random. If you are using Java, this algorithm is available in the standard library (see Collections.shuffle).

    It probably doesn't matter for most applications, but be aware that most RNGs do not provide sufficient degrees of freedom to produce every possible permutation of a 52-card deck (explained here).

    From Dan Dyer
  • I'm not fully following your question. You say

    Assume that you have a algorithm that generates randomness. Now how do you test it?

    What do you mean? If you're assuming you can generate randomness, there's no need to test it.

    Once you have a good random number generator, creating a random permutation is easy (e.g. Call your cards 1-52. Generate 52 random numbers assigning each one to a card in order, and then sort according to your 52 randoms) . You're not going to destroy the randomness of your good RNG by generating your permutation.

    The difficult question is whether you can trust your RNG. Here's a sample link to people discussing that issue in a specific context.

    Tnilsson : Heh. A clarification then. "Assume that you have a algorithm that you believe generates randomness."
    Baltimark : OK. I wasn't trying to be snarky. I don't really know if you're asking "how to test randomness" which can be asked without referring to card shuffling, or if you're asking "how to test if my shuffling alogrithm has screwed up my good RNG."
    From Baltimark
  • First, it is impossible to know for sure if a certain finite output is "truly random" since, as you point out, any output is possible.

    What can be done, is to take a sequence of outputs and check various measurements of this sequence against what is more likely. You can derive a sort of confidence score that the generating algorithm is doing a good job.

    For example, you could check the output of 10 different shuffles. Assign a number 0-51 to each card, and take the average of the card in position 6 across the shuffles. The convergent average is 25.5, so you would be surprised to see a value of 1 here. You could use the central limit theorem to get an estimate of how likely each average is for a given position.

    But we shouldn't stop here! Because this algorithm could be fooled by a system that only alternates between two shuffles that are designed to give the exact average of 25.5 at each position. How can we do better?

    We expect a uniform distribution (equal likelihood for any given card) at each position, across different shuffles. So among the 10 shuffles, we could try to verify that the choices 'look uniform.' This is basically just a reduced version of the original problem. You could check that the standard deviation looks reasonable, that the min is reasonable, and the max value as well. You could also check that other values, such as the closest two cards (by our assigned numbers), also make sense.

    But we also can't just add various measurements like this ad infinitum, since, given enough statistics, any particular shuffle will appear highly unlikely for some reason (e.g. this is one of very few shuffles in which cards X,Y,Z appear in order). So the big question is: which is the right set of measurements to take? Here I have to admit that I don't know the best answer. However, if you have a certain application in mind, you can choose a good set of properties/measurements to test, and work with those -- this seems to be the way cryptographers handle things.

    From Tyler
  • There's a lot of theory on testing randomness. For a very simple test on a card shuffling algorithm you could do a lot of shuffles and then run a chi squared test that the probability of each card turning up in any position was uniform. But that doesn't test that consecutive cards aren't correlated so you would also want to do tests on that.

    Volume 2 of Knuth's Art of Computer Programming gives a number of tests that you could use in sections 3.3.2 (Empirical tests) and 3.3.4 (The Spectral Test) and the theory behind them.

    From Ian G
  • Testing 52! possibilities is of course impossible. Instead, try your shuffle on smaller numbers of cards, like 3, 5, and 10. Then you can test billions of shuffles and use a histogram and the chi-square statistical test to prove that each permutation is coming up an "even" number of times.

  • No code so far, therefore I copy-paste a testing part from my answer to the original question.

      // ...
      int main() {
        typedef std::map<std::pair<size_t, Deck::value_type>, size_t> Map;
        Map freqs;    
        Deck d;
        const size_t ntests = 100000;
    
        // compute frequencies of events: card at position
        for (size_t i = 0; i < ntests; ++i) {
          d.shuffle();
          size_t pos = 0;
          for(Deck::const_iterator j = d.begin(); j != d.end(); ++j, ++pos) 
            ++freqs[std::make_pair(pos, *j)]; 
        }
    
        // if Deck.shuffle() is correct then all frequencies must be similar
        for (Map::const_iterator j = freqs.begin(); j != freqs.end(); ++j)
          std::cout << "pos=" << j->first.first << " card=" << j->first.second 
                    << " freq=" << j->second << std::endl;    
      }
    

    This code does not test randomness of underlying pseudorandom number generator. Testing PRNG randomness is a whole branch of science.

  • Copying my answer from the original topic :

    YXJuLnphcnQ, that's the way I did it too. It's the most obvious.

    But the fact is, that if you write an algorithm, that just shuffles all the cards in the collection one position to the right every time you call sort() it would pass the test, even though the output is not random.

    What does everybody else think ? Maybe I'm wrong.

    Dan Dyer : Most of these simple tests for randomness can be gamed in some way. They don't prove anything either way, but they are useful for detecting sequences that probably aren't random (they're not so good for showing that a sequence *is* random).
    J.F. Sebastian : http://beta.stackoverflow.com/questions/56215/interesting-interview-questions#56501
  • Here's one simple check that you can perform. It uses generated random numbers to estimate Pi. It's not proof of randomness, but poor RNGs typically don't do well on it (they will return something like 2.5 or 3.8 rather ~3.14).

    Ideally this would be just one of many tests that you would run to check randomness.

    Something else that you can check is the standard deviation of the output. The expected standard deviation for a uniformly distributed population of values in the range 0..n approaches n/sqrt(12).

    /**
     * This is a rudimentary check to ensure that the output of a given RNG
     * is approximately uniformly distributed.  If the RNG output is not
     * uniformly distributed, this method will return a poor estimate for the
     * value of pi.
     * @param rng The RNG to test.
     * @param iterations The number of random points to generate for use in the
     * calculation.  This value needs to be sufficiently large in order to
     * produce a reasonably accurate result (assuming the RNG is uniform).
     * Less than 10,000 is not particularly useful.  100,000 should be sufficient.
     * @return An approximation of pi generated using the provided RNG.
     */
    public static double calculateMonteCarloValueForPi(Random rng,
                                                       int iterations)
    {
        // Assumes a quadrant of a circle of radius 1, bounded by a box with
        // sides of length 1.  The area of the square is therefore 1 square unit
        // and the area of the quadrant is (pi * r^2) / 4.
        int totalInsideQuadrant = 0;
        // Generate the specified number of random points and count how many fall
        // within the quadrant and how many do not.  We expect the number of points
        // in the quadrant (expressed as a fraction of the total number of points)
        // to be pi/4.  Therefore pi = 4 * ratio.
        for (int i = 0; i < iterations; i++)
        {
            double x = rng.nextDouble();
            double y = rng.nextDouble();
            if (isInQuadrant(x, y))
            {
                ++totalInsideQuadrant;
            }
        }
        // From these figures we can deduce an approximate value for Pi.
        return 4 * ((double) totalInsideQuadrant / iterations);
    }
    
    /**
     * Uses Pythagoras' theorem to determine whether the specified coordinates
     * fall within the area of the quadrant of a circle of radius 1 that is
     * centered on the origin.
     * @param x The x-coordinate of the point (must be between 0 and 1).
     * @param y The y-coordinate of the point (must be between 0 and 1).
     * @return True if the point is within the quadrant, false otherwise.
     */
    private static boolean isInQuadrant(double x, double y)
    {
        double distance = Math.sqrt((x * x) + (y * y));
        return distance <= 1;
    }
    
    Tnilsson : Me likes. Not the solution to the exact shuffle problem, but a good starting point. Have an upvote :)
    J.F. Sebastian : There is no need for `Math.sqrt()` in `isInQuadrant()`.
    Dan Dyer : YXJuLnphcnQ, good point.
    JoeBloggs : How is this, aside from all the extra processing, different from just counting higher/lower than 50% of the range of a random number?
    From Dan Dyer
  • Pondering it myself, what I would do is something like:

    Setup (Pseudo code)

    // A card has a Number 0-51 and a position 0-51
    int[][] StatMatrix = new int[52][52]; // Assume all are set to 0 as starting values
    ShuffleCards();
    ForEach (card in Cards) {
       StatMatrix[Card.Position][Card.Number]++;
    }
    

    This gives us a matrix 52x52 indicating how many times a card has ended up at a certain position. Repeat this a large number of times (I would start with 1000, but people better at statistics than me may give a better number).

    Analyze the matrix

    If we have perfect randomness and perform the shuffle an infinite number of times then for each card and for each position the number of times the card ended up in that position is the same as for any other card. Saying the same thing in a different way:

    statMatrix[position][card] / numberOfShuffle = 1/52.
    

    So I would calculate how far from that number we are.

    From Tnilsson
  • Most of the answers here seem to me to miss the point. People dork the implementation of the Fisher-Yates-Durstenfeld-Knuth shuffle algorithm all the time, even given a perfect RNG—I've done it myself. My question is simply this: Is there someplace I can find an existing Diehard-like battery of statistical tests specifically for shuffle output?

    The suggested frequency tests are a good start, but clearly much more could be done here. Indeed, many of the tests in Diehard look like they could be adapted to test permutations rather than uniform distributions by adapting the statistics appropriately. I've Googled for something like this with no success; have I missed something?

    "Beware of bugs in the above code; I have only proved it correct, not tried it." —Donald Knuth

    From PO8