Which would be more advantageous: using a single setter method or multiple setter methods for objects that have a set number of fields?

As I ponder over designing a class with a member variable of type object containing a fixed number of fields, the question arises: should I opt for a single setter function or multiple setters to modify these fields?

To illustrate this dilemma clearly, I have created a simple organizational management structure class in two different ways:

  1. Multiple Setter Functions

    class Management {
        constructor() {
            this.numberOfManagers = 100;
            this.salaryDetails = {
                regionalManagerSalary: 80000,
                stateManagerSalary: 110000,
                executiveManagerSalary: 200000
            };
        }
    
        setRegionalManagerSalary(salary) {
            this.salaryDetails.regionalManagerSalary = salary;
        }
    
        setStateManagerSalary(salary) {
            this.salaryDetails.stateManagerSalary = salary;
        }  
    
        setExecutiveManagerSalary(salary) {
            this.salaryDetails.executiveManagerSalary = salary;
        }
    }
    
    const management = new Management();
    management.setRegionalManagerSalary(100000);
    management.setStateManagerSalary(120000);
    management.setExecutiveManagerSalary(210000);
    
  2. One Setter Function

    class Management {
        constructor() {
            this.numberOfManagers = 100;
            this.salaryDetails = {
                regionalManagerSalary: 80000,
                stateManagerSalary: 110000,
                executiveManagerSalary: 200000
            };
        }
    
        setManagerSalary(typeOfManagerSalary, salary) {
            this.salaryDetails[typeOfManagerSalary] = salary;
        }
    }
    
    const management = new Management();
    management.setManagerSalary('regionalManagerSalary', 100000);
    management.setManagerSalary('stateManagerSalary', 120000);
    management.setManagerSalary('executiveManagerSalary', 210000);
    

So, which implementation do you think would be more effective: the first one with multiple setters or the second one with a single setter function?

Answer №1

When it comes to choosing between readability and writability, I always lean towards the option that offers higher readability without sacrificing too much writability. The second approach may be more generic, but the clarity of the first approach is undeniable.

In my opinion, the first approach is preferable because it explicitly states that there are only 3 fields in salaryDetails. With the second approach, there is uncertainty about the number of fields in salaryDetails as additional fields could be added through external calls like

management.setManagerSalary('someNewSalary', 100000);
.

Unless you have multiple Management objects with unique fields under salaryDetails, I believe the first approach is the way to go.

Answer №2

If I were to offer a suggestion, I would propose implementing a method called setSalaryDetails. This method would accept a salary object as a parameter, allowing you to set it directly. Here's an example:

setSalaryDetails(salaryDetails) { this.salaryDetails = salaryDetails; }

When you call this method, you can easily create the salary object with the desired fields already set before passing it as an argument.

Answer №3

It is recommended to avoid using setters altogether. Instead, initialize all necessary properties in the constructor by passing arguments.

The code provided appears to be procedural rather than object-oriented. To make it truly OOP, the data should be kept within the class.

To start improving the code, consider structuring it like this:

class Management {
    constructor(numManagers, regionalSalary, stateSalary, executiveSalary) {
        this.numberOfManagers = numManagers;
        this.salaryDetails = {
            regionalManagerSalary: regionalSalary,
            stateManagerSalary: stateSalary,
            executiveManagerSalary: executiveSalary
        };
    }
}

const management = new Management(100, 100000, 120000, 210000);

This approach is more concise, cleaner, and less prone to errors.

Based on the constructor signature, it seems like there may be an issue with mixing too many responsibilities in a single class.

A more organized design involves utilizing separate classes for different manager types:

/* abstract */ class Manager {
    constructor(salary) {
        this.salary = salary;
    }
}

class RegionalManager extends Manager { }
class StateManager extends Manager { }
class ExecutiveManager extends Manager { }

class Management {
    constructor(numManagers, regionalMgr, stateMgr, executiveMgr) {
        this.numberOfManagers = numManagers;
        this.managers = {
            regionalManager: regionalMgr,
            stateManager: stateMgr,
            executiveManager: executiveMgr
        };
    }
}

const management = new Management(
    100,
    new RegionalManager(100000),
    new StateManager(120000),
    new ExecutiveManager(210000)
);

By organizing the code in this manner, common logic for all manager types can be implemented in the Manager class, while specific behaviors for each type can be encapsulated in their respective classes. The Management class can then handle these managers based on quantity, without getting bogged down with their individual characteristics. This results in code that is easier to comprehend, maintain, and extend.

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

The function is not explicitly declared within the instance, yet it is being cited during the rendering process in a .vue

import PageNav from '@/components/PageNav.vue'; import PageFooter from '@/components/PageFooter.vue'; export default { name: 'Groups', components: { PageNav, PageFooter, }, data() { return { groups: ...

Tips for creating an automatic interval timer reset feature

I searched for similar questions but couldn't find any that helped me. With the assistance of some kind individuals from Stack Overflow, I was able to implement an interval timer sequence on my website. This trailer automatically displays work example ...

Difficulty retrieving information using AngularJS service post selection of item

Currently, I am working on a project involving an AngularJS application. While using the service testPanelService, I encountered a problem where selecting an item from a list correctly logs the details of the selected item. However, when attempting to fetc ...

What is the best way to rotate a mesh by 90 degrees in ThreeJS?

Currently, I'm working on rotating a mesh by 90 degrees within Three JS. Below is an image illustrating the current position: My goal is to have the selected mesh rotated parallel to the larger mesh. I attempted to rotate the matrix using the follow ...

Issue: Module 'curl' is not located at Function.Module._resolveFilename (module.js:489:15)

After installing node.js using the Windows installer, I noticed that the folder structure created was C:\Program Files\nodejs\node_modules\npm\node_modules. It seems like all the module folders are in the last node_modules director ...

The usage of arrow functions in ReactJS programming

I'm working on a React component that has the following structure: import React, { PropTypes, Component } from 'react'; import { Accordion, Panel, PanelGroup, Table } from 'react-bootstrap'; const FormCell = ({ data }) => ( ...

Is the IE7 Modal Dialog Misaligned?

Update After some investigation, I discovered the root cause of the problem. In my code, I was referencing the height of the overlay, which resulted in different values in IE7 compared to other browsers. To resolve this issue, I adjusted the code to refe ...

Issue with jQuery UI: Accordion not functioning properly

I have created a nested sortable accordion, but there seems to be an issue. Within the 'accordion2' id, the heights of each item are too small and a vertical scroll bar appears. The content of the item labeled '1' is being cut off, show ...

Creating a multi-step form in Rails without using the Wizard gem allows for more

My Rails 3.2.14 app gathers call data and the new/edit action form is quite lengthy on a single page. I am interested in implementing a multistep form using JS/client side processing to navigate between steps. While considering the Wicked Gem for multi-ste ...

I am not sure how to properly execute this asynchronously

I have compiled a comprehensive list of everything related to this command I've been developing, and here is the error it keeps throwing at me. I tried testing if the image search feature was working properly, but instead, here's what I got: Synt ...

Start from scratch when establishing the baseline for "defaults."

Struggling to reimagine the _.defaults function from underscore.js, I keep encountering this pesky error: Error message: should copy source properties to undefined properties in the destination object‣ AssertionError: expected { a: 'existing' ...

Automating the selection of a drop down based on a condition in Angular 2: A step-by-step guide

I'm facing an issue with a drop-down menu where no default value is selected. On my homepage, I need to automatically select an option based on query parameters. I've attempted various methods but none have been successful. Below is the code snip ...

Skrollr's transformation effect makes the text tremble

Using skrollr.js, I am implementing transition effects on an inner div nested inside another div. The inner div is positioned relatively. Here are my codes: HTML Structure <div class="outer"> <div class="inner-div" style="transition:transform ...

Working with floating point numbers in Node.js with a zero decimal place

NodeJS interprets float values with a zero after the decimal point as integers, but this behavior occurs at the language level. For example: 5.0 is considered as 5 by NodeJS. In my work with APIs, it's crucial for me to be able to send float values w ...

Using JavaScript to load the contents of a JSON file

I attempted to display data from a JSON file on an HTML page using jQuery / Javascript. However, each time I load the page, it remains blank. Below is the code snippet: index.html <!DOCTYPE html> <html> <head> <meta conten ...

The CSS is not displaying correctly on Safari and Chrome browsers in Mac OS

I'm having trouble with CSS not loading properly on Apple devices for a website I made. Despite maintaining all media query statements and style sheets separately, the display is not correct in MAC OS safari and chrome. However, everything looks fine ...

NativeScript encountered an error while trying to locate the module 'ui/sidedrawer' for the specified element 'Sidedrawer'

Currently, I am in the process of developing a simple side-drawer menu for my NativeScript application by following this helpful tutorial. I have successfully implemented it on a single page using the given code below. starting_point.xml: <Page xmlns ...

What sets a module apart from a script?

As I delve into the depths of TypeScript documentation to grasp the concept of modules, particularly ES6 modules, I stumbled upon some interesting insights. typescript-modules - this documentation talks about typescript modules and highlights an important ...

What is the process for eliminating transparency from the overlay feature while utilizing Dojox/Standby?

Currently, I'm using a spinner image to indicate loading while retrieving data from the backend. However, the spinner widget creates a translucent overlay over the control. Is there a way to disable this translucency so that only the spinner is visibl ...

Upon the initial data retrieval, everything seems to be working fine. However, when the user transitions to chatting with another user, the state value does not reset and instead shows a combination

Exploring the world of react.js and node.js, I am currently working on developing a chatting application with the integration of socket.io. The issue I'm facing is that when a user clicks on another user to chat, the previous chat messages are display ...