Represent a Class which holds translation Strings [closed]

Posted on

Problem

I have a class which represents some translations of a keyword.

public abstract class Name {

    private String name;
    private String name_de;
    private String name_it;
    private String name_fr;
    private String name_hu;
    private String name_cs;

    public Name(String name_key, String name_de, String name_it, String name_fr, String name_hu, String name_cs) {
        super();
        this.name = name_key;
        this.name_de = name_de;
        this.name_it = name_it;
        this.name_fr = name_fr;
        this.name_hu = name_hu;
        this.name_cs = name_cs;
    }

Each translation has to be an own field because of saving purpose. The problem here is that I cant make sure that for instance the german translation is really the second parameter.

I was thinking about to create an own Object for each translation, but seems a litte bit of overhead. Are there any other options to represent a translation class?

Solution

A fluent builder can make your code more readable and safe:

new Name.Builder(key)
  .deutch("..")
  .italian("..")
  .build();

However nothing will prevent someone to pass wrong value.

You haven’t given much context about how you intend to use this class, which is always important. In my experience (echoed in comments), there’s not much use case for needing all translations of a string at one time. The use case is more typically that you need to render the UI in a particular language, so you need a bunch of German strings but none of the other languages. Also, you want to be able to easily add support for additional languages, ideally without any code changes. That’s what resource bundles are for, it seems like you are trying to reinvent the wheel here. If you think that resource bundles don’t solve your problem, you should give more context.

In addition to @gervais.b’s great answer, you can for instance use some kind of Map to store translations for different languages. Of course instead of using strings for keys like "de", "it", "fr" it will be safer to use enum for indication of different languages.

However nothing will prevent someone to pass wrong value.

It is possible to implement some mechanism in build() method to check if all enum values are covered and are correct. Here is some reference how to iterate over enum

You can also simplify the builder a little bit:

new Name.Builder(key)
  .translatedAs(Languages.DEUTCH, "..")
  .translatedAs(Languages.ITALIAN, "..")
  .build();

Leave a Reply

Your email address will not be published. Required fields are marked *