Mailing List Archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [tlug] Language localization in Javacript



> I.e. you set a reference variable to point to one language or the other.
> Then you use that reference variable to get at your strings.

If you must do this... well, if you must do this, don't. Use a localization
library instead, as Stephen and others have suggested. Your code only
communicates with a server to get JSON data now and again? Great! Have it hand
the server a language code and get back a hash between string IDs and
localized strings.

But if you really must do it this way, there's a teachable programming moment
here. Don't use indirect variable references. Let the data structure do the work:

strings = {
	english: { hi: "Hello world", bye: "Goodbye" },
	japanese: { hi: "こんにちは世界", bye: "さよなら" },
	french: { hi: "Bonjour tout le monde", bye: "Au revoir" },
}

var language = "english";

document.writeln( strings[language]["hi"] );


See the switch statement? You don't need it or anything like it. Ugly and
unmaintainable switch statements should be a big fat red flag that you're
already doing something wrong. If you need to add another case to the switch
statement when you add another set of data, you're repeating yourself in your
code, which is breaking the first cardinal rule of programming and should be
another big fat red flag that you're doing something wrong. You're only using
the switch statements or the ternary operator to choose the appropriate
portion of a data structure, so the right thing to do is to structure your
data to make it easy - use a hash instead.

Indirect variable references are a third big fat red flag that you're doing
something wrong. For why, see the series starting at
http://perl.plover.com/varvarname.html which is Perl-focused but the same
principles apply.

And for why localization is really really unpleasant and I would ask for
danger money, see http://interglacial.com/tpj/13/

Simon


Home | Main Index | Thread Index

Home Page Mailing List Linux and Japan TLUG Members Links