Obtaining an enumeration from the backend and utilizing it as a string in JavaScript

Today, I found myself in a spirited debate with a fellow developer who specializes in Java back-end while I handle the front-end with JavaScript Angular. The REST service he provides sends me an object containing an enum, which I receive as a string and need to display in an Angular grid.

The enums themselves are quite self-explanatory.

Here are some examples of what I receive:

Person = {gender: "MAN", position: "IS_EMPLOYED"}

In the view, I need to show it as follows: man is employed

My solution was simple yet effective:

Person.gender.toLowerCase() + ' ' + Person.position.toLowerCase().replace('_', ' ')

However, my counterpart found this method appalling and insisted that I create a mapper using if-else or switch statements like so:

If(Person.gender==="MAN") return "man"
Else if....

It's worth noting that the label name always matches the enum name, albeit in lowercase with spaces instead of underscores.

He expressed his strong disapproval of my approach, going as far as to call it bad coding, terrible, even sinful...

So the question remains: Is this practice considered good or bad (black-or-white), or can it be defended in certain scenarios?

Typed on my mobile device, hence the code examples not being enclosed in proper tags.

Answer №1

Here are a couple of perspectives on this matter:

Emphasizing Mapping: The importance of having a comprehensive mapping function is underscored here. Ensuring that errors are handled properly, such as not simply accepting "banana" as a valid response for position, can be crucial in backend development scenarios where adherence to a strict schema is key.

Consideration of Scale: While your current approach may technically work, its appropriateness depends on the size of data entries or user base/application scope. While it may not align perfectly with best practices, if functionality is ultimately what matters most, it could suffice. Always aim for adherence to best practices while keeping the bigger picture in mind.

Factor in Efficiency: Efficiency plays a role in comparing these approaches. The potential speed difference might be minimal, but in web development, prioritizing quick results can be imperative. Opt for the faster option if both methods yield similar outcomes.

Answer №2

If you want a more efficient solution, consider creating a client-enum map where you send back the actual value. For example:

var personTypes: {
    "1": "Is Employed",
    ..
}

Then, just send 1 as the enum and use the lookup object like this:

console.log("Person status: " + personTypes[Person.position]);

This approach also simplifies displaying a list of types - you can easily select a new one and send the enum back:

<select ng-model="personTypeEnum" ng-options="enum as type for (enum, type) in personTypes"></select>

Answer №3

Ensure to log the object in your console for inspection. For instance, if the object represents a person and you are converting it to JSON format, the gender (enum) would appear as:

{"success":true,"person":[{"class":"person","id":26,"comment":null,"gender":{"enumType":"com.project.Person$Gender","name":"MEN"},

Therefore, you can access the gender of the person by printing `person.gender.name`, which will return MEN.

Answer №4

Implementing the method described in the query may pose challenges when attempting to globalize the application. My suggestion would be to utilize a centralized utility function for mapping enum values to their corresponding display values. This way, if there is a need to internationalize the frontend in the future, you can easily retrieve the correct display values based on the selected language.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery form validation with delay in error prompts

I am experiencing a strange issue with my HTML form validation function. It seems to be showing the alert div twice, and I can't figure out why this is happening. Adjusting the delay time seems to affect which field triggers the problem. Can anyone sp ...

Can you explain the meaning of the code provided below?

I'm having trouble understanding the functionality of this code snippet: .bind(this); (I copied it from the Zurb Foundation dropdown plugin) .on('mouseleave.fndtn.dropdown', '[data-dropdown], [data-dropdown-content]', function ( ...

Navigating File Paths in Node.js

My directory structure is as follows: Main > models > file1.ejs | |> routes > file2.ejs In my code, I'm trying to require file1 from file2 like this: const variable = require("../models/file1.ejs). But what if I don't want to ...

Adding a mute/unmute button to your web browser's audio player: A quick guide

My code is functioning perfectly, but I am facing an issue with the lack of mute/unmute buttons. Can someone please help me figure out how to add them? <audio src="MUSIC URL" autoplay loop> <p>Your browser does not support the audio elem ...

Missing RequestVerificationToken value when hiding HTML element using jQuery

I am encountering an issue with my ASP.NET MVC 4 form that involves checkboxes being used to show and hide certain HTML elements. When I initially visit the form page, the RequestVerificationToken value is correctly created as a hidden field. Some HTML ele ...

Updating dates using moment.js

Is there a way to adjust a date by adding 5 days and setting the hour, minute, and second to 0:0:0? For instance, taking a current date like 2016-03-13 21:21:21 and adjusting it to 2016-03-18 00:00:00. When attempting to achieve this using moment().add(5 ...

Encountering continuous loops during the resolution of sinon, hindering the ability to conduct proper unit testing in node

In an attempt to implement unit testing in Nodejs using sinon, I have recently installed the following libraries: 1 npm i mocha [2] npm i chai [3] npm i sinon Below is the code that I am working with: unitTest-app.js var sinon = require('sinon&a ...

Ways to retrieve API data utilizing the $http service

My current project involves using the Riot Games API, but this example utilizes the REST Countries API. You can find more information at The technology stack I am using is MEAN.IO and below you will see a snippet of my code: test.html <html ng-app="l ...

Float: A threshold reached when adding 1 no longer has any effect

In the realm of programming, float serves as an estimation of a numeric value. For example, 12345678901234567890 === 12345678901234567891 evaluates to true However, 1234567890 === 1234567891 yields false Where does the equation num === num+1 reach a br ...

Accessing dynamically created AJAX controls in ASP.NET during postback operations

I am dynamically creating 2 dropdown boxes and a CheckBoxList control using AJAX callbacks to a web service (.asmx file). The server-side service generates the Dropdowns and CheckBoxList, returning the rendered html as a string which is then inserted into ...

uncertainty when implementing ng-if / ng-show / ng-hide

I am facing an issue with exporting content to PDF from my HTML. When a user clicks on the export button, the PDF is downloaded, but there are certain divs whose content I do not want to be exported or shown in the PDF. However, I still want them to be vis ...

Global axios configuration containing an undefined bearer token

After creating a Vue app using Axios that was installed via Vue UI dependency installation, I encountered an issue with the post headers returning an undefined token Bearer undefined. To resolve this, I made changes to my main.js file. Initially, I had add ...

Universal observer for data

I am looking for a way to implement a global listener in my AngularJs app that automatically calls a factory when a specific value changes. The value I want to monitor is $scope.loading For example, whenever I update $scope.loading = true; in the control ...

The route path consists of data that will be retrieved before entering the route

I am facing an issue with my router configuration. I have a dynamic Route that requires the last part of its path to be set after fetching data from a store call in beforeRouteEnter. beforeRouteEnter (to, from, next) { if(to.params.categoryId) { next(vm ...

Utilizing Ajax technology to load script in Tapestry 5

I have two components, a "DirectoryViewer" and a "MediaViewer", that I created. The Directory Viewer displays a list of file names and contains a MediaViewer component to show the selected file. This setup is functioning properly. Within the DirectoryView ...

What is the benefit of validating both the post request and the database schema on the backend?

Question: Is it necessary to use express-validator for data validation when mongoose schema can handle it? As a front end developer, I normally perform form validation before submission. Recently, I have been exploring express. Initially, I utilized a li ...

Setting the $dirty flag to true when a value is entered in the text box, but not the other way around

When I enter a value in the text box, myForm.$dirty gets set to true. However, the flag does not revert back to false when I delete all values from the text box. Why is this happening and how can I fix it? <input name="input" ng-model="myModel.text"& ...

Understanding the sequence of Node.js code execution

Today was my first day of programming in Node, and for the most part, everything has been going smoothly. However, I encountered something strange that I can't quite wrap my head around - perhaps it's related to Node's asynchronous nature. ...

Exploring Node.js and Express routing: Strategies for managing client-side promises

I've been working on a routing issue with MongoDB where I'm having trouble retrieving data on the client side from the promise received via $resource. There's a button on the HTML page that triggers the following function on ng-click: $scop ...

Sending back an array within the onOpen function

I am currently in the process of developing a chat application. At this stage, users are able to send messages to each other and I have successfully stored these messages in my database. Now, my objective is to display the stored messages from the database ...