1

i'm doing a project in NodeJS about finantial control that uses a model for accounts (Class Accounts) which have some "private" attributes (_id, _name, _parent, _balance and _isDeleted) and some methods (getters and setters plus others).

All created accounts (objects) are converted into a JSON and stored into a file (custom database), except their methods (only the attributes are passed to the JSON).

When I load the database file, I get the JSON containing all accounts and their attributes, and need to show them into a view page, using EJS engine.

But after converting into JSON and loading them they do not have their methods to get their private attributes anymore, and I couldn't think any way to get those info, except by using directly the attribute reference (like _id, _name, ...).

How can I get those attributes according to OO design patterns, avoiding to make external references to private attributes of a class?

Thanks!

roschach
  • 8,390
  • 14
  • 74
  • 124
Ighour
  • 21
  • 2
  • 1
    Make those types handle their own JSON serialization and deserialization. – Ry- May 28 '17 at 01:21
  • 1
    JSON is a notation, it can't store functions or object methods. Use JSON to store data, not to serialise complex objects. – RobG May 28 '17 at 01:23

1 Answers1

2

Before you even begin: I do not recommend node.js for financial projects.

The JavaScript Number type is an implementation of the IEEE 754 floating-point format, and this numeric representation is inadequate for manipulating financial information.

Please refer to the following article as well: Why not use Double or Float to represent currency?

Some workarounds include creating typed arrays with Int32 and then storing cents rather than dollars into them, but this still is not good enough for many reasons (you would be at some moment reading those cents, implicitly casting them to floats to manipulate them).

I recommend you to use a language that supports fixed-point numbers (e.g: C# decimal or Java's BigDecimal) unless you want to sign up for a big financial and legal liability.

There are npm modules that implement BigDecimal but I would test them very carefully prior to using them. Also they require significant more work and computational resources.

arboreal84
  • 2,086
  • 18
  • 21