Repetition is good
I've written this kind of code in the past (in pseudo-vue):
const FIELDS = [
{ name: 'name', label: 'Name', type: 'text', placeholder: 'Write your name...' },
{ name: 'surname', label: 'Surname', type: 'text', placeholder: 'Write your surname...' },
{ name: 'age', label: 'Age', type: 'number', placeholder: 'Enter your age...' },
...
]
<fieldset>
<div v-for="field in FIELDS">
<label :for="field.name"></label>
<input :type="field.type" v-model="form[field.name]" :placeholder="field.placeholder" />
</div>
</fieldset>
But now I'm convinced that (in most of the cases) this is better:
<fieldset>
<label for="name">Name</label>
<input type="text" v-model="form.name" placeholder="Write your name..." />
<label for="surname">Surname</label>
<input type="text" v-model="form.surname" placeholder="Write your surname..." />
<label for="name">Name</label>
<input type="text" v-model="form.name" placeholder="Enter your age..." />
...
</fieldset>
I think most of the developers gets into the first code when follows the mantra of "avoid repetition". The second example has a lot more repetition (specially if the form is very long). But even so, still think second it's better.
Here I'll try to convince you the same (if you're not already).
When to use #
Before continuing there are two scenarios where I think the first form is better:
- When rendering a "list" of items coming from an API. Basically there's no other way to do it that using a loop.
- When you need to "manipulate" the fields (in some complex ways) based on and dynamic conditions. With "complex ways" I mean things that can't be done with simple "ifs". For example, generating the fields on the fly based on certain data. For other simpler cases, like showing/hidding fields based on the user (for example) still simple html with some conditionals is probably a better approach.
How to measure #
To decide if a code is better than another (trying to avoid personal preferences) I'll compare both examples against two question: Which one is easier for a developer to understand in the future Which one adapts better to changes.