← Back
drafts

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:

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.