Example of extracting data from DOM poorly
Often times in front end GUI programming we need to translate data in an HTML form into a Javascript object. This gives an example of how not to do it.
Here’s an example of overly complex code for extracting data from DOM using Javascript:
function SETparseUserData() {
let $Inputs = document.querySelector('.POPpopoutCard-content').querySelectorAll('.FORMinput');
let UserData = {
guid: document.querySelector('.SETuserInfo').dataset.guid, username: $Inputs[0].value, email: $Inputs[1].value, description: $Inputs[2].value,
};
if(UserData.guid == null) {
UserData.new_password = $Inputs[3].value;
UserData.confirm_new_password = $Inputs[4].value;
}
else {
UserData.password = $Inputs[5].value;
UserData.new_password = $Inputs[3].value;
UserData.confirm_new_password = $Inputs[4].value;
}
return UserData;
}
What makes the above code unnecessarily complex and brittle?
It stores data in the DOM. This is bad practice.
It doesn’t do a good job of separating concerns since it makes use of CSS classes which are used for other purposes - POPpopoutCard-content and FORMinput. If we change the names of these classes while doing maintenance on the rest of the system then it will break this code.
It relies on the order of fields as to what is mapped into the output Javascript object. This makes the code brittle and prone to breakage if we change the order of the fields.
It changes it logic based on whether the dataset GUID is set. It’s not good practice to store data in the DOM. Also it doesn’t make sense to break the design principle of separating concerns and have a function that is used to extract data from both the “create user” and “update user” logic.
The following code is a much more straightforward was to write the same logic:
function USERaddUserFormData(){
let Result = {}
Result.username = document.querySelector(".USERname").value;
Result.password = document.querySelector(".USERpassword").value;
Result.description = document.querySelector(".USERdescription").value;
Result.email = document.querySelector(".USERemail").value;
return Result;
}
What makes this code better:
It’s much more readable:
The code doesn’t mix concerns - the CSS classes USERname, USERpassword etc. are only used for a single purpose - to make it easy to extract the data. This makes the code more robust.
It’s easy to change the order of fields. This is more robust.
The code is boringly simple and readable which is how code should be.