Skip to content
Advertisement

Instead of using primitive methods, should I be using a data structure?

This is my current code for a tax calculator based on age. I think that it would be easier to update in the future if I used data structures when calculating the brackets. Could someone help me make sense of this?

JavaScript

So the code that I’m assuming that I need to change is:

JavaScript

Also, I’m trying to learn so could you explain by putting #comments into the code :) Thank you!

Advertisement

Answer

1. Rewrite the code structure

First of all, I think most programmers do like to put function blocks all together and leave the main logic as clean/short as possible to improve readability. Therefore the ‘code structure’ like this could be hard to maintain or update in the future.

JavaScript

So this kind of structure is really weird, plus you have lots of variables (date_of_birth, age) declared between functions. Would be hard to do the update/maintenance. If I were you, I’d firstly revise the code like this way

JavaScript

2. Introduce data structure? or class?

Honestly I don’t quite understand what do you mean by “using data structure”, so I guess make a “class” is the one you wish. Then you have to consider some points:

  • what should be the attributes for this class? dob, salary, anything else?
  • what will you expand in the future? name? gender? contact_info? handicapped or not?

Whatever, we just create a class with dob and salary for now.

JavaScript

So once you create a variable in the class Person, you can access the age, salary, tax via .age, .salary, .tax. Please notice that I did not put the function get_salary() into the class since it’s a function for “asking user’s salary” and has nothing to do with the attribute.

The main logic can be rewritten to:

JavaScript

3. Future expansion

Let’s say if I want to add name as an attribute now. All I have to do is to modify the Person class. Should be easier for you to update in the future.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement