Domanda

Does 'open-closed principle' also includes files and data of the app? According to https://softwareengineering.stackexchange.com/a/296955/248528, it says files and data are't included, but it doesn't mentions if they should be included.

Suppose I have 2 ways to define the locale string of my app:

Method 1 : all locale strings in a single file:

locale.json

{
    'title':{
        'en':'Welcome',
        'es':'bienvenida'
    },
    'hello_message':{
        'en':'Welcome to use the app',
        'es':'Bienvenido a usar la aplicación'
    }
}

pseudo code to load locale : load locale.json directly

how to add a new locale: edit locale.json, add a new key at each string

Method 2 : one json for each locale

locale_en.json

{
    'title':'Welcome',
    'hello_message':'Welcome to use the app'
}
locale_es.json

{
    'title':'bienvenida',
    'hello_message':'Bienvenido a usar la aplicación',
}

pseudo code to load locale : search and load all locale_xx.json files in specific app data folder

how to add a new locale : add a new locale_xx.json file in specific app data folder

My question is, suppose I may need to add a new locale in the future, and the code to handle keeps unchanged, is Method 2 preferred because it follows 'open-closed principle?

È stato utile?

Soluzione

This is about more than the open closed principle. This is about predicting change. Predicting change is hard.

Method 1 (a single file) makes it easy to add new features. It makes it hard to add new languages.

Method 2 (a file for every language) makes it easy to add new languages but hard to add new features.

I call this the interleaving problem. Your config file is laid out linearly so it has one dimension. But you're subject to change from two dimensions.

You can either lay your config out in two dimensions, use editing tools that present it in two dimensions, just deal with the interleaving when it happens, or try to force the future to behave the way you expect. After decades at this I can tell you the future does as it likes.

A sneaky trick that I've used is to abuse the file system by making an entire folder into your config. Fill it with files named title.en and title.es. Then you can sort it either way.

I've seen people solve this with spread sheets or databases but I prefer to use a lightweight solution if I can.

The open closed principle centers on the idea of organizing so that change can happen without having to edit what already works. Believe it or not the sneaky trick follows that fairly well.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
scroll top